esp32tool 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -93,6 +93,22 @@ export declare class ESPLoader extends EventTarget {
93
93
  checksum(data: number[], state?: number): number;
94
94
  setBaudrate(baud: number): Promise<void>;
95
95
  reconfigurePort(baud: number): Promise<void>;
96
+ /**
97
+ * @name connectWithResetStrategies
98
+ * Try different reset strategies to enter bootloader mode
99
+ * Similar to esptool.py's connect() method with multiple reset strategies
100
+ */
101
+ connectWithResetStrategies(): Promise<void>;
102
+ /**
103
+ * @name hardResetUSBJTAGSerial
104
+ * USB-JTAG/Serial reset sequence for ESP32-C3, ESP32-S3, ESP32-C6, etc.
105
+ */
106
+ hardResetUSBJTAGSerial(): Promise<void>;
107
+ /**
108
+ * @name hardResetClassic
109
+ * Classic reset sequence for USB-to-Serial bridge chips (CH340, CP2102, etc.)
110
+ */
111
+ hardResetClassic(): Promise<void>;
96
112
  /**
97
113
  * @name sync
98
114
  * Put into ROM bootload mode & attempt to synchronize with the
@@ -86,7 +86,6 @@ export class ESPLoader extends EventTarget {
86
86
  };
87
87
  }
88
88
  async initialize() {
89
- await this.hardReset(true);
90
89
  if (!this._parent) {
91
90
  this.__inputBuffer = [];
92
91
  this.__totalBytesRead = 0;
@@ -107,12 +106,8 @@ export class ESPLoader extends EventTarget {
107
106
  // Don't await this promise so it doesn't block rest of method.
108
107
  this.readLoop();
109
108
  }
110
- // Drain input buffer first for CP210x compatibility on Windows
111
- // This helps clear any stale data before sync
112
- await this.drainInputBuffer(200);
113
- // Clear buffer again after starting read loop
114
- await this.flushSerialBuffers();
115
- await this.sync();
109
+ // Try to connect with different reset strategies
110
+ await this.connectWithResetStrategies();
116
111
  // Detect chip type
117
112
  await this.detectChip();
118
113
  // Read the OTP data for this chip and store into this.efuses array
@@ -304,35 +299,12 @@ export class ESPLoader extends EventTarget {
304
299
  if (bootloader) {
305
300
  // enter flash mode
306
301
  if (this.port.getInfo().usbProductId === USB_JTAG_SERIAL_PID) {
307
- // esp32c3 esp32s3 etc. build-in USB serial.
308
- // when connect to computer direct via usb, using following signals
309
- // to enter flash mode automatically.
310
- await this.setDTR(false);
311
- await this.setRTS(false);
312
- await this.sleep(100);
313
- await this.setDTR(true);
314
- await this.setRTS(false);
315
- await this.sleep(100);
316
- await this.setRTS(true);
317
- await this.setDTR(false);
318
- await this.setRTS(true);
319
- await this.sleep(100);
320
- await this.setDTR(false);
321
- await this.setRTS(false);
322
- this.logger.log("USB MCU reset.");
302
+ await this.hardResetUSBJTAGSerial();
303
+ this.logger.log("USB-JTAG/Serial reset.");
323
304
  }
324
305
  else {
325
- // otherwise, esp chip should be connected to computer via usb-serial
326
- // bridge chip like ch340,CP2102 etc.
327
- // use normal way to enter flash mode.
328
- await this.setDTR(false);
329
- await this.setRTS(true);
330
- await this.sleep(100);
331
- await this.setDTR(true);
332
- await this.setRTS(false);
333
- await this.sleep(50);
334
- await this.setDTR(false);
335
- this.logger.log("DTR/RTS USB serial chip reset.");
306
+ await this.hardResetClassic();
307
+ this.logger.log("Classic reset.");
336
308
  }
337
309
  }
338
310
  else {
@@ -676,6 +648,108 @@ export class ESPLoader extends EventTarget {
676
648
  throw new Error(`Unable to change the baud rate to ${baud}: ${e}`);
677
649
  }
678
650
  }
651
+ /**
652
+ * @name connectWithResetStrategies
653
+ * Try different reset strategies to enter bootloader mode
654
+ * Similar to esptool.py's connect() method with multiple reset strategies
655
+ */
656
+ async connectWithResetStrategies() {
657
+ var _a, _b;
658
+ const portInfo = this.port.getInfo();
659
+ const isUSBJTAGSerial = portInfo.usbProductId === USB_JTAG_SERIAL_PID;
660
+ const isEspressifUSB = portInfo.usbVendorId === 0x303a;
661
+ this.logger.log(`Detected USB: VID=0x${((_a = portInfo.usbVendorId) === null || _a === void 0 ? void 0 : _a.toString(16)) || "unknown"}, PID=0x${((_b = portInfo.usbProductId) === null || _b === void 0 ? void 0 : _b.toString(16)) || "unknown"}`);
662
+ // Define reset strategies to try in order
663
+ const resetStrategies = [];
664
+ // Strategy 1: USB-JTAG/Serial reset (for ESP32-C3, C6, S3, etc.)
665
+ // Try this first if we detect Espressif USB VID or the specific PID
666
+ if (isUSBJTAGSerial || isEspressifUSB) {
667
+ resetStrategies.push({
668
+ name: "USB-JTAG/Serial",
669
+ fn: async () => await this.hardResetUSBJTAGSerial(),
670
+ });
671
+ }
672
+ // Strategy 2: Classic reset (for USB-to-Serial bridges)
673
+ resetStrategies.push({
674
+ name: "Classic",
675
+ fn: async () => await this.hardResetClassic(),
676
+ });
677
+ // Strategy 3: If USB-JTAG/Serial was not tried yet, try it as fallback
678
+ if (!isUSBJTAGSerial && !isEspressifUSB) {
679
+ resetStrategies.push({
680
+ name: "USB-JTAG/Serial (fallback)",
681
+ fn: async () => await this.hardResetUSBJTAGSerial(),
682
+ });
683
+ }
684
+ let lastError = null;
685
+ // Try each reset strategy
686
+ for (const strategy of resetStrategies) {
687
+ try {
688
+ this.logger.log(`Trying ${strategy.name} reset...`);
689
+ // Check if port is still open, if not, skip this strategy
690
+ if (!this.connected || !this.port.writable) {
691
+ this.logger.log(`Port disconnected, skipping ${strategy.name} reset`);
692
+ continue;
693
+ }
694
+ await strategy.fn();
695
+ // Try to sync after reset
696
+ await this.sync();
697
+ // If we get here, sync succeeded
698
+ this.logger.log(`Connected successfully with ${strategy.name} reset.`);
699
+ return;
700
+ }
701
+ catch (error) {
702
+ lastError = error;
703
+ this.logger.log(`${strategy.name} reset failed: ${error.message}`);
704
+ // If port got disconnected, we can't try more strategies
705
+ if (!this.connected || !this.port.writable) {
706
+ this.logger.log(`Port disconnected during reset attempt`);
707
+ break;
708
+ }
709
+ // Clear buffers before trying next strategy
710
+ this._inputBuffer.length = 0;
711
+ await this.drainInputBuffer(200);
712
+ await this.flushSerialBuffers();
713
+ }
714
+ }
715
+ // All strategies failed
716
+ throw new Error(`Couldn't sync to ESP. Try resetting manually. Last error: ${lastError === null || lastError === void 0 ? void 0 : lastError.message}`);
717
+ }
718
+ /**
719
+ * @name hardResetUSBJTAGSerial
720
+ * USB-JTAG/Serial reset sequence for ESP32-C3, ESP32-S3, ESP32-C6, etc.
721
+ */
722
+ async hardResetUSBJTAGSerial() {
723
+ await this.setRTS(false);
724
+ await this.setDTR(false); // Idle
725
+ await this.sleep(100);
726
+ await this.setDTR(true); // Set IO0
727
+ await this.setRTS(false);
728
+ await this.sleep(100);
729
+ await this.setRTS(true); // Reset. Calls inverted to go through (1,1) instead of (0,0)
730
+ await this.setDTR(false);
731
+ await this.setRTS(true); // RTS set as Windows only propagates DTR on RTS setting
732
+ await this.sleep(100);
733
+ await this.setDTR(false);
734
+ await this.setRTS(false); // Chip out of reset
735
+ // Wait for chip to boot into bootloader
736
+ await this.sleep(200);
737
+ }
738
+ /**
739
+ * @name hardResetClassic
740
+ * Classic reset sequence for USB-to-Serial bridge chips (CH340, CP2102, etc.)
741
+ */
742
+ async hardResetClassic() {
743
+ await this.setDTR(false); // IO0=HIGH
744
+ await this.setRTS(true); // EN=LOW, chip in reset
745
+ await this.sleep(100);
746
+ await this.setDTR(true); // IO0=LOW
747
+ await this.setRTS(false); // EN=HIGH, chip out of reset
748
+ await this.sleep(50);
749
+ await this.setDTR(false); // IO0=HIGH, done
750
+ // Wait for chip to boot into bootloader
751
+ await this.sleep(200);
752
+ }
679
753
  /**
680
754
  * @name sync
681
755
  * Put into ROM bootload mode & attempt to synchronize with the
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)),n={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"},r=115200,o=1343410176,h=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),l=33382,c=50,d=12882,u=12883,f=12994,g=12995,_=12997,p=12998,b=207969,m=12914,w=12916,y=12917,I=12928,S=12849,E={5:{name:"ESP32-C3",family:g},9:{name:"ESP32-S3",family:u},12:{name:"ESP32-C2",family:f},13:{name:"ESP32-C6",family:p},16:{name:"ESP32-H2",family:m},18:{name:"ESP32-P4",family:I},20:{name:"ESP32-C61",family:b},23:{name:"ESP32-C5",family:_},25:{name:"ESP32-H21",family:y},28:{name:"ESP32-H4",family:w},32:{name:"ESP32-S31",family:S}},B={4293968129:{name:"ESP8266",family:l},15736195:{name:"ESP32",family:c},1990:{name:"ESP32-S2",family:d}},k=3e3,O=15e4,x=100,z=(t,e)=>{const i=Math.floor(t*(e/486));return i<k?k:i},v=t=>{switch(t){case c:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case d:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case u:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case l:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case f:case g:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case _:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case p:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case b:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case m:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case w:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case y:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case I:return{regBase:1342754816,baseFuse:o,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case S:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class A extends Error{constructor(t){super(t),this.name="SlipReadError"}}const D=async(t,i)=>{let s;return t==w||t==y||t==S?null:(t==c?s=await import("./esp32-CijhsJH1.js"):t==d?s=await import("./esp32s2-IiDBtXxo.js"):t==u?s=await import("./esp32s3-6yv5yxum.js"):t==l?s=await import("./esp8266-CUwxJpGa.js"):t==f?s=await import("./esp32c2-C17SM4gO.js"):t==g?s=await import("./esp32c3-DxRGijbg.js"):t==_?s=await import("./esp32c5-3mDOIGa4.js"):t==p?s=await import("./esp32c6-h6U0SQTm.js"):t==b?s=await import("./esp32c61-BKtexhPZ.js"):t==m?s=await import("./esp32h2-RtuWSEmP.js"):t==I&&(s=null!=i&&i>=300?await import("./esp32p4r3-CpHBYEwI.js"):await import("./esp32p4-5nkIjxqJ.js")),{...s,text:e(atob(s.text)),data:e(atob(s.data))})};function L(t){let e=t.length;for(;--e>=0;)t[e]=0}const C=256,R=286,P=30,F=15,U=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]),j=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]),N=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),T=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),M=new Array(576);L(M);const $=new Array(60);L($);const H=new Array(512);L(H);const G=new Array(256);L(G);const Z=new Array(29);L(Z);const J=new Array(P);function V(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 K,W,X;function Y(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}L(J);const q=t=>t<256?H[t]:H[256+(t>>>7)],Q=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},tt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,Q(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},et=(t,e,i)=>{tt(t,i[2*e],i[2*e+1])},it=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},st=(t,e,i)=>{const s=new Array(16);let a,n,r=0;for(a=1;a<=F;a++)r=r+i[a-1]<<1,s[a]=r;for(n=0;n<=e;n++){let e=t[2*n+1];0!==e&&(t[2*n]=it(s[e]++,e))}},at=t=>{let e;for(e=0;e<R;e++)t.dyn_ltree[2*e]=0;for(e=0;e<P;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},nt=t=>{t.bi_valid>8?Q(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},rt=(t,e,i,s)=>{const a=2*e,n=2*i;return t[a]<t[n]||t[a]===t[n]&&s[e]<=s[i]},ot=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&rt(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!rt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},ht=(t,e,i)=>{let s,a,n,r,o=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+o++],s+=(255&t.pending_buf[t.sym_buf+o++])<<8,a=t.pending_buf[t.sym_buf+o++],0===s?et(t,a,e):(n=G[a],et(t,n+C+1,e),r=U[n],0!==r&&(a-=Z[n],tt(t,a,r)),s--,n=q(s),et(t,n,i),r=j[n],0!==r&&(s-=J[n],tt(t,s,r)))}while(o<t.sym_next);et(t,256,e)},lt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=e.stat_desc.has_stree,n=e.stat_desc.elems;let r,o,h,l=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<n;r++)0!==i[2*r]?(t.heap[++t.heap_len]=l=r,t.depth[r]=0):i[2*r+1]=0;for(;t.heap_len<2;)h=t.heap[++t.heap_len]=l<2?++l:0,i[2*h]=1,t.depth[h]=0,t.opt_len--,a&&(t.static_len-=s[2*h+1]);for(e.max_code=l,r=t.heap_len>>1;r>=1;r--)ot(t,i,r);h=n;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ot(t,i,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,i[2*h]=i[2*r]+i[2*o],t.depth[h]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,i[2*r+1]=i[2*o+1]=h,t.heap[1]=h++,ot(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,n=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,h=e.stat_desc.max_length;let l,c,d,u,f,g,_=0;for(u=0;u<=F;u++)t.bl_count[u]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)c=t.heap[l],u=i[2*i[2*c+1]+1]+1,u>h&&(u=h,_++),i[2*c+1]=u,c>s||(t.bl_count[u]++,f=0,c>=o&&(f=r[c-o]),g=i[2*c],t.opt_len+=g*(u+f),n&&(t.static_len+=g*(a[2*c+1]+f)));if(0!==_){do{for(u=h-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[h]--,_-=2}while(_>0);for(u=h;0!==u;u--)for(c=t.bl_count[u];0!==c;)d=t.heap[--l],d>s||(i[2*d+1]!==u&&(t.opt_len+=(u-i[2*d+1])*i[2*d],i[2*d+1]=u),c--)}})(t,e),st(i,l,t.bl_count)},ct=(t,e,i)=>{let s,a,n=-1,r=e[1],o=0,h=7,l=4;for(0===r&&(h=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=r,r=e[2*(s+1)+1],++o<h&&a===r||(o<l?t.bl_tree[2*a]+=o:0!==a?(a!==n&&t.bl_tree[2*a]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,n=a,0===r?(h=138,l=3):a===r?(h=6,l=3):(h=7,l=4))},dt=(t,e,i)=>{let s,a,n=-1,r=e[1],o=0,h=7,l=4;for(0===r&&(h=138,l=3),s=0;s<=i;s++)if(a=r,r=e[2*(s+1)+1],!(++o<h&&a===r)){if(o<l)do{et(t,a,t.bl_tree)}while(0!==--o);else 0!==a?(a!==n&&(et(t,a,t.bl_tree),o--),et(t,16,t.bl_tree),tt(t,o-3,2)):o<=10?(et(t,17,t.bl_tree),tt(t,o-3,3)):(et(t,18,t.bl_tree),tt(t,o-11,7));o=0,n=a,0===r?(h=138,l=3):a===r?(h=6,l=3):(h=7,l=4)}};let ut=!1;const ft=(t,e,i,s)=>{tt(t,0+(s?1:0),3),nt(t),Q(t,i),Q(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var gt=(t,e,i,s)=>{let a,n,r=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<C;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),lt(t,t.l_desc),lt(t,t.d_desc),r=(t=>{let e;for(ct(t,t.dyn_ltree,t.l_desc.max_code),ct(t,t.dyn_dtree,t.d_desc.max_code),lt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*T[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,n=t.static_len+3+7>>>3,n<=a&&(a=n)):a=n=i+5,i+4<=a&&-1!==e?ft(t,e,i,s):4===t.strategy||n===a?(tt(t,2+(s?1:0),3),ht(t,M,$)):(tt(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(tt(t,e-257,5),tt(t,i-1,5),tt(t,s-4,4),a=0;a<s;a++)tt(t,t.bl_tree[2*T[a]+1],3);dt(t,t.dyn_ltree,e-1),dt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,r+1),ht(t,t.dyn_ltree,t.dyn_dtree)),at(t),s&&nt(t)},_t={_tr_init:t=>{ut||((()=>{let t,e,i,s,a;const n=new Array(16);for(i=0,s=0;s<28;s++)for(Z[s]=i,t=0;t<1<<U[s];t++)G[i++]=s;for(G[i-1]=s,a=0,s=0;s<16;s++)for(J[s]=a,t=0;t<1<<j[s];t++)H[a++]=s;for(a>>=7;s<P;s++)for(J[s]=a<<7,t=0;t<1<<j[s]-7;t++)H[256+a++]=s;for(e=0;e<=F;e++)n[e]=0;for(t=0;t<=143;)M[2*t+1]=8,t++,n[8]++;for(;t<=255;)M[2*t+1]=9,t++,n[9]++;for(;t<=279;)M[2*t+1]=7,t++,n[7]++;for(;t<=287;)M[2*t+1]=8,t++,n[8]++;for(st(M,287,n),t=0;t<P;t++)$[2*t+1]=5,$[2*t]=it(t,5);K=new V(M,U,257,R,F),W=new V($,j,0,P,F),X=new V(new Array(0),N,0,19,7)})(),ut=!0),t.l_desc=new Y(t.dyn_ltree,K),t.d_desc=new Y(t.dyn_dtree,W),t.bl_desc=new Y(t.bl_tree,X),t.bi_buf=0,t.bi_valid=0,at(t)},_tr_stored_block:ft,_tr_flush_block:gt,_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*(G[i]+C+1)]++,t.dyn_dtree[2*q(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{tt(t,2,3),et(t,256,M),(t=>{16===t.bi_valid?(Q(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var pt=(t,e,i,s)=>{let a=65535&t,n=t>>>16&65535,r=0;for(;0!==i;){r=i>2e3?2e3:i,i-=r;do{a=a+e[s++]|0,n=n+a|0}while(--r);a%=65521,n%=65521}return a|n<<16};const bt=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 mt=(t,e,i,s)=>{const a=bt,n=s+i;t^=-1;for(let i=s;i<n;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},wt={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},yt={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:It,_tr_stored_block:St,_tr_flush_block:Et,_tr_tally:Bt,_tr_align:kt}=_t,{Z_NO_FLUSH:Ot,Z_PARTIAL_FLUSH:xt,Z_FULL_FLUSH:zt,Z_FINISH:vt,Z_BLOCK:At,Z_OK:Dt,Z_STREAM_END:Lt,Z_STREAM_ERROR:Ct,Z_DATA_ERROR:Rt,Z_BUF_ERROR:Pt,Z_DEFAULT_COMPRESSION:Ft,Z_FILTERED:Ut,Z_HUFFMAN_ONLY:jt,Z_RLE:Nt,Z_FIXED:Tt,Z_DEFAULT_STRATEGY:Mt,Z_UNKNOWN:$t,Z_DEFLATED:Ht}=yt,Gt=258,Zt=262,Jt=42,Vt=113,Kt=666,Wt=(t,e)=>(t.msg=wt[e],e),Xt=t=>2*t-(t>4?9:0),Yt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},qt=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 Qt=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const te=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},ee=(t,e)=>{Et(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,te(t.strm)},ie=(t,e)=>{t.pending_buf[t.pending++]=e},se=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ae=(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=pt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=mt(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ne=(t,e)=>{let i,s,a=t.max_chain_length,n=t.strstart,r=t.prev_length,o=t.nice_match;const h=t.strstart>t.w_size-Zt?t.strstart-(t.w_size-Zt):0,l=t.window,c=t.w_mask,d=t.prev,u=t.strstart+Gt;let f=l[n+r-1],g=l[n+r];t.prev_length>=t.good_match&&(a>>=2),o>t.lookahead&&(o=t.lookahead);do{if(i=e,l[i+r]===g&&l[i+r-1]===f&&l[i]===l[n]&&l[++i]===l[n+1]){n+=2,i++;do{}while(l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&n<u);if(s=Gt-(u-n),n=u-Gt,s>r){if(t.match_start=e,r=s,s>=o)break;f=l[n+r-1],g=l[n+r]}}}while((e=d[e&c])>h&&0!==--a);return r<=t.lookahead?r:t.lookahead},re=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Zt)&&(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),qt(t),s+=e),0===t.strm.avail_in)break;if(i=ae(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=Qt(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=Qt(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<Zt&&0!==t.strm.avail_in)},oe=(t,e)=>{let i,s,a,n=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=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<n&&(0===i&&e!==vt||e===Ot||i!==s+t.strm.avail_in))break;r=e===vt&&i===s+t.strm.avail_in?1:0,St(t,0,0,r),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,te(t.strm),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&&(ae(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===r);return o-=t.strm.avail_in,o&&(o>=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<=o&&(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-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),r?4:e!==Ot&&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&&(ae(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,n=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=n||(s||e===vt)&&e!==Ot&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,r=e===vt&&0===t.strm.avail_in&&i===s?1:0,St(t,t.block_start,i,r),t.block_start+=i,te(t.strm)),r?3:1)},he=(t,e)=>{let i,s;for(;;){if(t.lookahead<Zt){if(re(t),t.lookahead<Zt&&e===Ot)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Zt&&(t.match_length=ne(t,i)),t.match_length>=3)if(s=Bt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+1]);else s=Bt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2},le=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Zt){if(re(t),t.lookahead<Zt&&e===Ot)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Zt&&(t.match_length=ne(t,i),t.match_length<=5&&(t.strategy===Ut||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=Bt(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=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,s&&(ee(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Bt(t,0,t.window[t.strstart-1]),s&&ee(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=Bt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2};function ce(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 de=[new ce(0,0,0,0,oe),new ce(4,4,8,4,he),new ce(4,5,16,8,he),new ce(4,6,32,32,he),new ce(4,4,16,16,le),new ce(8,16,32,32,le),new ce(8,16,128,128,le),new ce(8,32,128,256,le),new ce(32,128,258,1024,le),new ce(32,258,258,4096,le)];function ue(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Ht,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Yt(this.dyn_ltree),Yt(this.dyn_dtree),Yt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Yt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Yt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const fe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Jt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==Vt&&e.status!==Kt?1:0},ge=t=>{if(fe(t))return Wt(t,Ct);t.total_in=t.total_out=0,t.data_type=$t;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?Jt:Vt,t.adler=2===e.wrap?0:1,e.last_flush=-2,It(e),Dt},_e=t=>{const e=ge(t);var i;return e===Dt&&((i=t.state).window_size=2*i.w_size,Yt(i.head),i.max_lazy_match=de[i.level].max_lazy,i.good_match=de[i.level].good_length,i.nice_match=de[i.level].nice_length,i.max_chain_length=de[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},pe=(t,e,i,s,a,n)=>{if(!t)return Ct;let r=1;if(e===Ft&&(e=6),s<0?(r=0,s=-s):s>15&&(r=2,s-=16),a<1||a>9||i!==Ht||s<8||s>15||e<0||e>9||n<0||n>Tt||8===s&&1!==r)return Wt(t,Ct);8===s&&(s=9);const o=new ue;return t.state=o,o.strm=t,o.status=Jt,o.wrap=r,o.gzhead=null,o.w_bits=s,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=a+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<a+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=n,o.method=i,_e(t)};var be={deflateInit:(t,e)=>pe(t,e,Ht,15,8,Mt),deflateInit2:pe,deflateReset:_e,deflateResetKeep:ge,deflateSetHeader:(t,e)=>fe(t)||2!==t.state.wrap?Ct:(t.state.gzhead=e,Dt),deflate:(t,e)=>{if(fe(t)||e>At||e<0)return t?Wt(t,Ct):Ct;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===Kt&&e!==vt)return Wt(t,0===t.avail_out?Pt:Ct);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(te(t),0===t.avail_out)return i.last_flush=-1,Dt}else if(0===t.avail_in&&Xt(e)<=Xt(s)&&e!==vt)return Wt(t,Pt);if(i.status===Kt&&0!==t.avail_in)return Wt(t,Pt);if(i.status===Jt&&0===i.wrap&&(i.status=Vt),i.status===Jt){let e=Ht+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=jt||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,se(i,e),0!==i.strstart&&(se(i,t.adler>>>16),se(i,65535&t.adler)),t.adler=1,i.status=Vt,te(t),0!==i.pending)return i.last_flush=-1,Dt}if(57===i.status)if(t.adler=0,ie(i,31),ie(i,139),ie(i,8),i.gzhead)ie(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),ie(i,255&i.gzhead.time),ie(i,i.gzhead.time>>8&255),ie(i,i.gzhead.time>>16&255),ie(i,i.gzhead.time>>24&255),ie(i,9===i.level?2:i.strategy>=jt||i.level<2?4:0),ie(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(ie(i,255&i.gzhead.extra.length),ie(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=mt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,9===i.level?2:i.strategy>=jt||i.level<2?4:0),ie(i,3),i.status=Vt,te(t),0!==i.pending)return i.last_flush=-1,Dt;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=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,te(t),0!==i.pending)return i.last_flush=-1,Dt;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=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=mt(t.adler,i.pending_buf,i.pending-s,s)),te(t),0!==i.pending)return i.last_flush=-1,Dt;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=mt(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=mt(t.adler,i.pending_buf,i.pending-s,s)),te(t),0!==i.pending)return i.last_flush=-1,Dt;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=mt(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&&(te(t),0!==i.pending))return i.last_flush=-1,Dt;ie(i,255&t.adler),ie(i,t.adler>>8&255),t.adler=0}if(i.status=Vt,te(t),0!==i.pending)return i.last_flush=-1,Dt}if(0!==t.avail_in||0!==i.lookahead||e!==Ot&&i.status!==Kt){let s=0===i.level?oe(i,e):i.strategy===jt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(re(t),0===t.lookahead)){if(e===Ot)return 1;break}if(t.match_length=0,i=Bt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===Nt?((t,e)=>{let i,s,a,n;const r=t.window;for(;;){if(t.lookahead<=Gt){if(re(t),t.lookahead<=Gt&&e===Ot)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=r[a],s===r[++a]&&s===r[++a]&&s===r[++a])){n=t.strstart+Gt;do{}while(s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&a<n);t.match_length=Gt-(n-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Bt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Bt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):de[i.level].func(i,e);if(3!==s&&4!==s||(i.status=Kt),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),Dt;if(2===s&&(e===xt?kt(i):e!==At&&(St(i,0,0,!1),e===zt&&(Yt(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),te(t),0===t.avail_out))return i.last_flush=-1,Dt}return e!==vt?Dt:i.wrap<=0?Lt:(2===i.wrap?(ie(i,255&t.adler),ie(i,t.adler>>8&255),ie(i,t.adler>>16&255),ie(i,t.adler>>24&255),ie(i,255&t.total_in),ie(i,t.total_in>>8&255),ie(i,t.total_in>>16&255),ie(i,t.total_in>>24&255)):(se(i,t.adler>>>16),se(i,65535&t.adler)),te(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Dt:Lt)},deflateEnd:t=>{if(fe(t))return Ct;const e=t.state.status;return t.state=null,e===Vt?Wt(t,Rt):Dt},deflateSetDictionary:(t,e)=>{let i=e.length;if(fe(t))return Ct;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Jt||s.lookahead)return Ct;if(1===a&&(t.adler=pt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(Yt(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 n=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,re(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=Qt(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,re(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=r,t.input=o,t.avail_in=n,s.wrap=a,Dt},deflateInfo:"pako deflate (from Nodeca project)"};const me=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var we=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)me(i,e)&&(t[e]=i[e])}}return t},ye=t=>{let e=0;for(let i=0,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 Ie=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Ie=!1}const Se=new Uint8Array(256);for(let t=0;t<256;t++)Se[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Se[254]=Se[254]=1;var Ee=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,n,r=t.length,o=0;for(a=0;a<r;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<r&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(o),n=0,a=0;n<o;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<r&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),i<128?e[n++]=i:i<2048?(e[n++]=192|i>>>6,e[n++]=128|63&i):i<65536?(e[n++]=224|i>>>12,e[n++]=128|i>>>6&63,e[n++]=128|63&i):(e[n++]=240|i>>>18,e[n++]=128|i>>>12&63,e[n++]=128|i>>>6&63,e[n++]=128|63&i);return e};var Be=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 ke=Object.prototype.toString,{Z_NO_FLUSH:Oe,Z_SYNC_FLUSH:xe,Z_FULL_FLUSH:ze,Z_FINISH:ve,Z_OK:Ae,Z_STREAM_END:De,Z_DEFAULT_COMPRESSION:Le,Z_DEFAULT_STRATEGY:Ce,Z_DEFLATED:Re}=yt;function Pe(t){this.options=we({level:Le,method:Re,chunkSize:16384,windowBits:15,memLevel:8,strategy:Ce},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 Be,this.strm.avail_out=0;let i=be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==Ae)throw new Error(wt[i]);if(e.header&&be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Ee(e.dictionary):"[object ArrayBuffer]"===ke.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=be.deflateSetDictionary(this.strm,t),i!==Ae)throw new Error(wt[i]);this._dict_set=!0}}Pe.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,n;if(this.ended)return!1;for(n=e===~~e?e:!0===e?ve:Oe,"string"==typeof t?i.input=Ee(t):"[object ArrayBuffer]"===ke.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),(n===xe||n===ze)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=be.deflate(i,n),a===De)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=be.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===Ae;if(0!==i.avail_out){if(n>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},Pe.prototype.onData=function(t){this.chunks.push(t)},Pe.prototype.onEnd=function(t){t===Ae&&(this.result=ye(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Fe={deflate:function(t,e){const i=new Pe(e);if(i.push(t,!0),i.err)throw i.msg||wt[i.err];return i.result}};const{deflate:Ue}=Fe;var je=Ue;const Ne={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}},Te=(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:(n(t[s],e[i]),i++);function n(t,e){if(!(t in Ne))throw"Unhandled character '"+t+"' in pack format";const i=Ne[t].bytes,n=new DataView(new ArrayBuffer(i));Ne[t].p.bind(n)(0,e,a);for(let t=0;t<i;t++)s.push(n.getUint8(t))}return s},Me=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:n(e);function n(t){if(!(t in Ne))throw"Unhandled character '"+t+"' in unpack format";const n=Ne[t].bytes,r=new DataView(new ArrayBuffer(n));for(let t=0;t<n;t++)r.setUint8(t,255&e[i+t]);const o=Ne[t].u.bind(r);s.push(o(0,a)),i+=n}return s};class $e 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=r,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.state_DTR=!1}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}detectUSBSerialChip(t,e){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6},4098:{name:"ESP32 Native USB",maxBaudrate:2e6},16386:{name:"ESP32 Native USB",maxBaudrate:2e6},4096:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(await this.hardReset(!0),!this._parent){this.__inputBuffer=[],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)}this.readLoop()}await this.drainInputBuffer(200),await this.flushSerialBuffers(),await this.sync(),await this.detectChip();const t=v(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=E[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===I&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._inputBuffer.length=0,await a(x);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=B[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.chipFamily===I&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==I)return 0;const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:Me("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?Me("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?Me("<I",t.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{this.logger.error("Read loop got disconnected")}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this.dispatchEvent(new Event("disconnect")),this.logger.debug("Finished read loop")}sleep(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async hardReset(t=!1){t?4097===this.port.getInfo().usbProductId?(await this.setDTR(!1),await this.setRTS(!1),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(100),await this.setRTS(!0),await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!1),await this.setRTS(!1),this.logger.log("USB MCU reset.")):(await this.setDTR(!1),await this.setRTS(!0),await this.sleep(100),await this.setDTR(!0),await this.setRTS(!1),await this.sleep(50),await this.setDTR(!1),this.logger.log("DTR/RTS USB serial chip reset.")):(await this.setRTS(!0),await this.sleep(100),await this.setRTS(!1),this.logger.log("Hard reset.")),await new Promise(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 n;if(this.chipFamily==l){if(0!=a)n=[a>>16&255,a>>8&255,255&a];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");n=[172,208,116]}else n=[24,254,52];t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==c)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!=d&&this.chipFamily!=u&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=_&&this.chipFamily!=p&&this.chipFamily!=b&&this.chipFamily!=m&&this.chipFamily!=w&&this.chipFamily!=y&&this.chipFamily!=I&&this.chipFamily!=S)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=Te("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[n,r]=await this.getResponse(t,a);if(null===r)throw new Error("Didn't get enough status bytes");let o=r,h=0;if(this.IS_STUB||this.chipFamily==l?h=2:[c,d,u,f,g,_,p,b,m,w,y,I,S].includes(this.chipFamily)||20===t?h=4:[2,4].includes(o.length)&&(h=o.length),o.length<h)throw new Error("Didn't get enough status bytes");const E=o.slice(-h,o.length);if(o=o.slice(0,-h),this.debug&&(this.logger.debug("status",E),this.logger.debug("value",n),this.logger.debug("data",o)),1==E[0])throw 5==E[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+s(t))):new Error("Command failure error code "+s(E[1]));return[n,o]}async sendCommand(e,i,s=0){const a=t([...Te("<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,n=!1,r=[];for(;;){const o=Date.now();for(r=[];Date.now()-o<t;){if(this._inputBuffer.length>0){r.push(this._inputBuffer.shift());break}await a(1)}if(0==r.length){throw new A("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+r.length+" bytes: "+i(r));for(const t of r)if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+i(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new A("Invalid head of packet ("+s(t)+")");e=[]}else if(n)if(n=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+i(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new A("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(219)}else if(219==t)n=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),e;e.push(t)}}throw new A("Invalid state")}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,n,,r]=Me("<BBHI",i.slice(0,8));if(1!=a)continue;const o=i.slice(8);if(null==t||n==t)return[r,o];if(0!=o[0]&&5==o[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 setBaudrate(t){if(this.chipFamily==l)throw new Error("Changing baud rate is not supported on the ESP8266");try{const e=Te("<II",t,this.IS_STUB?r:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(x),this._parent?this._parent._currentBaudRate=t:this._currentBaudRate=t;const e=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;e&&t>e&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${e})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;try{await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}async sync(){for(let t=0;t<5;t++){this._inputBuffer.length=0;if(await this._sync())return await a(x),!0;await a(x)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,h);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,x);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch{}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],n=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(n)}`)}const n=t.byteLength;let r,o=0,h=k;a?(r=je(new Uint8Array(t),{level:9}).buffer,o=r.byteLength,this.logger.log(`Writing data with filesize: ${n}. Compressed Size: ${o}`),h=await this.flashDeflBegin(n,o,i)):(this.logger.log(`Writing data with filesize: ${n}`),r=t,await this.flashBegin(n,i));let l=[],c=0,d=0,u=0;const f=Date.now(),g=this.getFlashWriteSize(),_=a?o:n;for(;_-u>0;)this.debug&&this.logger.log(`Writing at ${s(i+c*g,8)} `),_-u>=g?l=Array.from(new Uint8Array(r,u,g)):(l=Array.from(new Uint8Array(r,u,_-u)),a||(l=l.concat(new Array(g-l.length).fill(255)))),a?await this.flashDeflBlock(l,c,h):await this.flashBlock(l,c),c+=1,d+=a?Math.round(l.length*n/o):l.length,u+=g,e(Math.min(d,n),n);this.logger.log("Took "+(Date.now()-f)+"ms to write "+_+" 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,Te("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Te("<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 n=this.getFlashWriteSize();!this.IS_STUB&&[c,d,u,f,g,_,p,b,m,w,y,I,S].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const r=Math.floor((t+n-1)/n);a=this.chipFamily==l?this.getEraseSize(e,t):t;const o=this.IS_STUB?k:z(3e4,t),h=Date.now();let E=Te("<IIII",a,r,n,e);return this.chipFamily!=c&&this.chipFamily!=d&&this.chipFamily!=u&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=_&&this.chipFamily!=p&&this.chipFamily!=b&&this.chipFamily!=m&&this.chipFamily!=w&&this.chipFamily!=y&&this.chipFamily!=I&&this.chipFamily!=S||(E=E.concat(Te("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+r+", block size "+s(n,4)+", offset "+s(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,E,0,o),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-h)+"ms to erase "+r+" bytes"),r}async flashDeflBegin(t=0,e=0,i=0){const s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),n=Math.floor((t+s-1)/s);let r=0,o=0;this.IS_STUB?(r=t,o=z(3e4,r)):(r=n*s,o=k);const h=Te("<IIII",r,a,s,i);return await this.checkCommand(16,h,0,o),o}async flashFinish(){const t=Te("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Te("<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 n=Te("<IIII",t,e,i,s);a>0&&(n=n.concat(Te("<IIII",v(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,n)}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()),n=a.regBase,r=n,o=n+a.usrOffs,h=n+a.usr2Offs,l=n+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,u=await this.readRegister(o),f=await this.readRegister(h);let g=1<<31;if(i>0&&(g|=268435456),d>0&&(g|=134217728),await this.setDataLengths(a,d,i),await this.writeRegister(o,g),await this.writeRegister(h,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=Me("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(r,c),await this.waitDone(r,c);const _=await this.readRegister(l);return await this.writeRegister(o,u),await this.writeRegister(h,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=n[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,Te("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,Te("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?k:500,i=Te("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){const e=await D(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`],n=s.length,r=Math.floor((n+i-1)/i);await this.memBegin(n,r,i,a);for(const t of Array(r).keys()){const e=t*i;let a=e+i;a>n&&(a=n),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 n=new He(this.port,this.logger,this);return t||await n.detectFlashSize(),n}async writeToStream(t){if(!this.port.writable)return void this.logger.debug("Port writable stream not available, skipping write");const e=this.port.writable.getWriter();await e.write(new Uint8Array(t));try{e.releaseLock()}catch(t){this.logger.error(`Ignoring release lock error: ${t}`)}}async disconnect(){this._parent?await this._parent.disconnect():this.port.writable?(await this.port.writable.getWriter().close(),await new Promise(t=>{this._reader||t(void 0),this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()}),this.connected=!1):this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)return void await this._parent.reconnect();if(this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this._reader){try{await this._reader.cancel()}catch(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:r}),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})`);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");const n=await this.runStub(!0);if(this.logger.debug("Stub loaded"),this._currentBaudRate!==r&&(await n.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,n),this.logger.debug("Reconnection successful")}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(x),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 n=new Uint8Array(0),r=e,o=i;for(;o>0;){const e=Math.min(65536,o);let h=!1,l=0;const c=5;for(;!h&&l<=c;){let i=new Uint8Array(0);try{this.logger.debug(`Reading chunk at 0x${r.toString(16)}, size: 0x${e.toString(16)}`);const s=Te("<IIII",r,e,4096,1024),[a]=await this.checkCommand(210,s);if(0!=a)throw new Error("Failed to read memory: "+a);for(;i.length<e;){let s;try{s=await this.readPacket(100)}catch(s){if(s instanceof A){if(this.logger.debug(`SLIP read error at ${i.length} bytes: ${s.message}`),i.length>0)try{const e=Te("<I",i.length),s=t(e);await this.writeToStream(s)}catch(t){this.logger.debug(`ACK send error: ${t}`)}if(await this.drainInputBuffer(300),i.length>=e)break}throw s}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 n=Te("<I",i.length),r=t(n);await this.writeToStream(r)}}const o=new Uint8Array(n.length+i.length);o.set(n),o.set(i,n.length),n=o,h=!0}catch(t){if(l++,!(t instanceof A))throw t;if(!(l<=c))throw new Error(`Failed to read chunk at 0x${r.toString(16)} after ${c} retries: ${t}`);this.logger.log(`⚠️ ${t.message} at 0x${r.toString(16)}. Draining buffer and retrying (attempt ${l}/${c})...`);try{await this.drainInputBuffer(300),await this.flushSerialBuffers(),await a(x)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}}s&&s(new Uint8Array(e),n.length,i),r+=e,o-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${i.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${n.length} bytes from flash`),n}}class He extends $e{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const n=await D(this.chipFamily,this.chipRevision);if(null===n)return[0,[]];const r=a,o=a+t;this.logger.debug(`Load range: ${s(r,8)}-${s(o,8)}`),this.logger.debug(`Stub data: ${s(n.data_start,8)}, len: ${n.data.length}, text: ${s(n.text_start,8)}, len: ${n.text.length}`);for(const[t,e]of[[n.data_start,n.data_start+n.data.length],[n.text_start,n.text_start+n.text.length]])if(r<e&&o>t)throw new Error("Software loader is resident at "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(r,8)+"-"+s(o,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,O)}}const Ge=4096,Ze=[4096,2048,1024,512],Je=4096,Ve=[4096,2048,1024,512],Ke=8192,We=[8192,4096],Xe=256,Ye=256,qe=8192;function Qe(t){if(t.length<4096)return!1;let e=0;const i=256,s=Math.min(32,Math.floor(t.length/i));for(let a=0;a<s;a++){const s=a*i;if(s+i>t.length)break;const n=t.slice(s,s+i),r=n[0]|n[1]<<8;for(let t=0;t<n.length-10;t++)if(1===n[t]&&47===n[t+1]){let i=0;for(let e=t+1;e<Math.min(t+20,n.length);e++)if(n[e]>=32&&n[e]<127)i++;else if(0===n[e])break;if(i>=4){e+=5;break}}if(32768&r){const t=32767&r;t>0&&t<4096&&(e+=2)}}return e>=10}function ti(t,e,i){const s=We;for(const a of s)for(let s=0;s<2;s++){const n=s*a,r=n+8;if(r+8>t.length)continue;if("littlefs"===String.fromCharCode(t[r],t[r+1],t[r+2],t[r+3],t[r+4],t[r+5],t[r+6],t[r+7])){const s=n+16,r=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(0!==r&&r>>>0!=4294967295){const s=n+24;if(s+4<=t.length){const n=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(n>0&&n<1e5){const t=n*a;if(t>0&&e+t<=i)return{start:e,end:e+t,size:t,page:256,block:a}}}return ei(e,i,a)}}}if(Qe(t))return ei(e,i,qe);if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)){let s=!0;if(t.length>=16){let e=!0;for(let i=4;i<16;i++)if(255!==t[i]){e=!1;break}e&&(s=!1)}if(s)return ei(e,i,qe)}}const a=[0,4096];for(const s of a){if(t.length<s+512)continue;if(43605===(t[s+510]|t[s+511]<<8)){const a=t[s+11]|t[s+12]<<8;if(![512,1024,2048,4096].includes(a))continue;let n=t[s+19]|t[s+20]<<8;if(0===n&&(n=t[s+32]|t[s+33]<<8|t[s+34]<<16|t[s+35]<<24),a>0&&n>0&&n<1e8){const t=n*a,r=e+s;if(t>0&&r+t<=i)return{start:r,end:r+t,size:t,page:a,block:a}}}}return null}function ei(t,e,i){const s=e/1048576;if(s>=16){if(1048576===t)return{start:1048576,end:16752640,size:15704064,page:256,block:i};if(2097152===t)return{start:2097152,end:16752640,size:14655488,page:256,block:i}}if(s>=8){if(1048576===t)return{start:1048576,end:8364032,size:7315456,page:256,block:i};if(2097152===t)return{start:2097152,end:8364032,size:6266880,page:256,block:i}}if(s>=4){if(1048576===t)return{start:1048576,end:4169728,size:3121152,page:256,block:i};if(2097152===t)return{start:2097152,end:4169728,size:2072576,page:256,block:i};if(3145728===t)return{start:3145728,end:4169728,size:1024e3,page:256,block:i}}if(s>=2){if(1048576===t)return{start:1048576,end:2072576,size:1024e3,page:256,block:i};if(1572864===t)return{start:1572864,end:2072576,size:499712,page:256,block:i};if(1835008===t)return{start:1835008,end:2076672,size:241664,page:256,block:i};if(1966080===t)return{start:1966080,end:2076672,size:110592,page:256,block:i};if(2031616===t)return{start:2031616,end:2076672,size:45056,page:256,block:i}}if(s>=1){if(503808===t)return{start:503808,end:1028096,size:524288,page:256,block:i};if(765952===t)return{start:765952,end:1028096,size:262144,page:256,block:i};if(831488===t)return{start:831488,end:1028096,size:196608,page:256,block:i};if(864256===t)return{start:864256,end:1028096,size:163840,page:256,block:i};if(880640===t)return{start:880640,end:1028096,size:147456,page:256,block:i};if(897024===t)return{start:897024,end:1028096,size:131072,page:256,block:i};if(962560===t)return{start:962560,end:1028096,size:65536,page:256,block:i}}if(s>=.5){if(372736===t)return{start:372736,end:503808,size:131072,page:256,block:i};if(438272===t)return{start:438272,end:503808,size:65536,page:256,block:i};if(471040===t)return{start:471040,end:503808,size:32768,page:256,block:i}}return{start:t,end:e,size:e-t,page:256,block:i}}function ii(t){return t>=16?[{start:1048576,end:16752640,size:15704064,page:256,block:8192},{start:2097152,end:16752640,size:14655488,page:256,block:8192}]:t>=8?[{start:1048576,end:8364032,size:7315456,page:256,block:8192},{start:2097152,end:8364032,size:6266880,page:256,block:8192}]:t>=4?[{start:2097152,end:4169728,size:2072576,page:256,block:8192},{start:1048576,end:4169728,size:3121152,page:256,block:8192},{start:3145728,end:4169728,size:1024e3,page:256,block:8192}]:t>=2?[{start:1048576,end:2072576,size:1024e3,page:256,block:8192},{start:1572864,end:2072576,size:499712,page:256,block:8192},{start:1835008,end:2076672,size:241664,page:256,block:8192},{start:1966080,end:2076672,size:110592,page:256,block:8192},{start:2031616,end:2076672,size:45056,page:256,block:8192}]:t>=1?[{start:897024,end:1028096,size:131072,page:256,block:8192},{start:503808,end:1028096,size:524288,page:256,block:8192},{start:765952,end:1028096,size:262144,page:256,block:8192},{start:831488,end:1028096,size:196608,page:256,block:8192},{start:864256,end:1028096,size:163840,page:256,block:8192},{start:880640,end:1028096,size:147456,page:256,block:8192},{start:962560,end:1028096,size:65536,page:256,block:8192}]:t>=.5?[{start:372736,end:503808,size:131072,page:256,block:8192},{start:438272,end:503808,size:65536,page:256,block:8192},{start:471040,end:503808,size:32768,page:256,block:8192}]:[]}var si;function ai(t){return 1!==t.type?si.UNKNOWN:129===t.subtype?si.FATFS:si.UNKNOWN}function ni(t,e){if(t.length<512)return si.UNKNOWN;const i=(null==e?void 0:e.toUpperCase().includes("ESP8266"))?We:Ze;for(const e of i)for(let i=0;i<2;i++){const s=i*e;if(s+20>t.length)continue;const a=s+8;if(a+8<=t.length){if("littlefs"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3],t[a+4],t[a+5],t[a+6],t[a+7])){const e=s+16,i=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;if(0!==i&&i>>>0!=4294967295)return si.LITTLEFS}}}const s=[0,4096];for(const e of s){if(t.length<e+512)continue;if(43605===(t[e+510]|t[e+511]<<8)){const i=t.length>=e+62?String.fromCharCode(t[e+54],t[e+55],t[e+56],t[e+57],t[e+58]):"",s=t.length>=e+90?String.fromCharCode(t[e+82],t[e+83],t[e+84],t[e+85],t[e+86]):"";if(i.startsWith("FAT")||s.startsWith("FAT"))return si.FATFS}}if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24))return si.SPIFFS}return Qe(t)?si.SPIFFS:si.UNKNOWN}function ri(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case si.FATFS:return 4096;case si.LITTLEFS:default:return i?Ke:4096}}function oi(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case si.FATFS:return Ve;case si.LITTLEFS:return i?We:Ze;default:return i?We:[4096,2048,1024,512]}}!function(t){t.UNKNOWN="unknown",t.LITTLEFS="littlefs",t.FATFS="fatfs",t.SPIFFS="spiffs"}(si||(si={}));const hi={0:"app",1:"data"},li={0:"factory",16:"ota_0",17:"ota_1",18:"ota_2",19:"ota_3",20:"ota_4",21:"ota_5",22:"ota_6",23:"ota_7",24:"ota_8",25:"ota_9",26:"ota_10",27:"ota_11",28:"ota_12",29:"ota_13",30:"ota_14",31:"ota_15",32:"test"},ci={0:"ota",1:"phy",2:"nvs",3:"coredump",4:"nvs_keys",5:"efuse",128:"esphttpd",129:"fat",130:"spiffs",131:"littlefs"};function di(t){if(t.length<32)return null;if(20650!==(65535&(t[0]|t[1]<<8)))return null;const e=t[2],i=t[3],s=t[4]|t[5]<<8|t[6]<<16|t[7]<<24,a=t[8]|t[9]<<8|t[10]<<16|t[11]<<24;let n="";for(let e=12;e<28&&0!==t[e];e++)n+=String.fromCharCode(t[e]);const r=t[28]|t[29]<<8|t[30]<<16|t[31]<<24,o=hi[e]||`unknown(0x${e.toString(16)})`;let h="";return h=0===e?li[i]||`unknown(0x${i.toString(16)})`:1===e?ci[i]||`unknown(0x${i.toString(16)})`:`0x${i.toString(16)}`,{name:n,type:e,subtype:i,offset:s,size:a,flags:r,typeName:o,subtypeName:h}}function ui(t){const e=[];for(let i=0;i<t.length;i+=32){const s=di(t.slice(i,i+32));if(null===s)break;e.push(s)}return e}function fi(){return 32768}function gi(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}class _i{constructor(t){var e,i,s,a,n,r,o,h,l,c,d,u;if(t.blockSize%t.pageSize!==0)throw new Error("block size should be a multiple of page size");this.pageSize=t.pageSize,this.blockSize=t.blockSize,this.objIdLen=null!==(e=t.objIdLen)&&void 0!==e?e:2,this.spanIxLen=null!==(i=t.spanIxLen)&&void 0!==i?i:2,this.packed=null===(s=t.packed)||void 0===s||s,this.aligned=null===(a=t.aligned)||void 0===a||a,this.objNameLen=null!==(n=t.objNameLen)&&void 0!==n?n:32,this.metaLen=null!==(r=t.metaLen)&&void 0!==r?r:4,this.pageIxLen=null!==(o=t.pageIxLen)&&void 0!==o?o:2,this.blockIxLen=null!==(h=t.blockIxLen)&&void 0!==h?h:2,this.endianness=null!==(l=t.endianness)&&void 0!==l?l:"little",this.useMagic=null===(c=t.useMagic)||void 0===c||c,this.useMagicLen=null===(d=t.useMagicLen)||void 0===d||d,this.alignedObjIxTables=null!==(u=t.alignedObjIxTables)&&void 0!==u&&u,this.PAGES_PER_BLOCK=Math.floor(this.blockSize/this.pageSize),this.OBJ_LU_PAGES_PER_BLOCK=Math.ceil(this.blockSize/this.pageSize*this.objIdLen/this.pageSize),this.OBJ_USABLE_PAGES_PER_BLOCK=this.PAGES_PER_BLOCK-this.OBJ_LU_PAGES_PER_BLOCK,this.OBJ_LU_PAGES_OBJ_IDS_LIM=Math.floor(this.pageSize/this.objIdLen),this.OBJ_DATA_PAGE_HEADER_LEN=this.objIdLen+this.spanIxLen+1;const f=4-(this.OBJ_DATA_PAGE_HEADER_LEN%4==0?4:this.OBJ_DATA_PAGE_HEADER_LEN%4);this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED=this.OBJ_DATA_PAGE_HEADER_LEN+f,this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD=f,this.OBJ_DATA_PAGE_CONTENT_LEN=this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN=this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED+4+1+this.objNameLen+this.metaLen,this.alignedObjIxTables?(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN+2-1&-2,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED-this.OBJ_INDEX_PAGES_HEADER_LEN):(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=0),this.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM=Math.floor((this.pageSize-this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED)/this.blockIxLen),this.OBJ_INDEX_PAGES_OBJ_IDS_LIM=Math.floor((this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED)/this.blockIxLen)}}class pi extends Error{constructor(t="SPIFFS is full"){super(t),this.name="SpiffsFullError"}}class bi{constructor(t,e){this.buildConfig=e,this.bix=t}pack(t,...e){const i=new ArrayBuffer(this.calcSize(t)),s=new DataView(i);let a=0;for(let i=0;i<t.length;i++){const n=t[i],r=e[i];switch(n){case"B":s.setUint8(a,r),a+=1;break;case"H":"little"===this.buildConfig.endianness?s.setUint16(a,r,!0):s.setUint16(a,r,!1),a+=2;break;case"I":"little"===this.buildConfig.endianness?s.setUint32(a,r,!0):s.setUint32(a,r,!1),a+=4}}return new Uint8Array(i)}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let n=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(n)),n+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(n,!0):s.getUint16(n,!1)),n+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(n,!0):s.getUint32(n,!1)),n+=4}return a}calcSize(t){let e=0;for(const i of t)switch(i){case"B":e+=1;break;case"H":e+=2;break;case"I":e+=4}return e}}class mi extends bi{constructor(t,e){super(0,e),this.objId=t}getObjId(){return this.objId}}class wi extends bi{constructor(t,e){super(t,e),this.objIdsLimit=this.buildConfig.OBJ_LU_PAGES_OBJ_IDS_LIM,this.objIds=[]}calcMagic(t){let e=538182953^this.buildConfig.pageSize;this.buildConfig.useMagicLen&&(e^=t-this.bix);return e&(1<<8*this.buildConfig.objIdLen)-1}registerPage(t){if(this.objIdsLimit<=0)throw new pi;const e=t instanceof yi?"index":"data";this.objIds.push([t.getObjId(),e]),this.objIdsLimit--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);let e=0;for(const[i,s]of this.objIds){let a=i;"index"===s&&(a^=1<<8*this.buildConfig.objIdLen-1);const n=this.pack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",a);t.set(n,e),e+=n.length}return t}magicfy(t){const e=this.objIdsLimit,i=(1<<8*this.buildConfig.objIdLen)-1;if(e>=2)for(let s=0;s<e;s++){if(s===e-2){this.objIds.push([this.calcMagic(t),"data"]);break}this.objIds.push([i,"data"]),this.objIdsLimit--}}}class yi extends mi{constructor(t,e,i,s,a){super(t,a),this.spanIx=e,this.name=s,this.size=i,0===this.spanIx?this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM:this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_LIM,this.pages=[]}registerPage(t){if(this.pagesLim<=0)throw new pi;this.pages.push(t.offset),this.pagesLim--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=this.objId^1<<8*this.buildConfig.objIdLen-1,i=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B";let s=0;const a=this.pack(i,e,this.spanIx,248);if(t.set(a,s),s+=a.length,s+=this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD,0===this.spanIx){const e=this.pack("IB",this.size,1);t.set(e,s),s+=e.length;const i=(new TextEncoder).encode(this.name),a=Math.min(i.length,this.buildConfig.objNameLen);t.set(i.slice(0,a),s);for(let e=a;e<this.buildConfig.objNameLen;e++)t[s+e]=0;s+=this.buildConfig.objNameLen+this.buildConfig.metaLen+this.buildConfig.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD}for(const e of this.pages){const i=Math.floor(e/this.buildConfig.pageSize),a=this.pack(1===this.buildConfig.pageIxLen?"B":2===this.buildConfig.pageIxLen?"H":"I",i);t.set(a,s),s+=a.length}return t}}class Ii extends mi{constructor(t,e,i,s,a){super(e,a),this.offset=t,this.spanIx=i,this.contents=s}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.pack(e,this.objId,this.spanIx,252);return t.set(i,0),t.set(this.contents,i.length),t}}class Si{constructor(t,e){this.buildConfig=e,this.offset=t*this.buildConfig.blockSize,this.remainingPages=this.buildConfig.OBJ_USABLE_PAGES_PER_BLOCK,this.pages=[],this.bix=t,this.luPages=[];for(let t=0;t<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;t++){const t=new wi(this.bix,this.buildConfig);this.luPages.push(t)}this.pages.push(...this.luPages),this.luPageIter=this.luPages[Symbol.iterator](),this.luPage=this.luPageIter.next().value||null,this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}reset(){this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}registerPage(t){if(t instanceof Ii){if(!this.curObjIdxPage)throw new Error("No current object index page");this.curObjIdxPage.registerPage(t)}try{if(!this.luPage)throw new pi;this.luPage.registerPage(t)}catch(e){if(!(e instanceof pi))throw e;{const e=this.luPageIter.next();if(e.done)throw new Error("Invalid attempt to add page to a block when there is no more space in lookup");this.luPage=e.value,this.luPage.registerPage(t)}}this.pages.push(t)}beginObj(t,e,i,s=0,a=0){if(this.remainingPages<=0)throw new pi;this.reset(),this.curObjId=t,this.curObjIndexSpanIx=s,this.curObjDataSpanIx=a;const n=new yi(t,this.curObjIndexSpanIx,e,i,this.buildConfig);this.registerPage(n),this.curObjIdxPage=n,this.remainingPages--,this.curObjIndexSpanIx++}updateObj(t){if(this.remainingPages<=0)throw new pi;const e=new Ii(this.offset+this.pages.length*this.buildConfig.pageSize,this.curObjId,this.curObjDataSpanIx,t,this.buildConfig);this.registerPage(e),this.curObjDataSpanIx++,this.remainingPages--}endObj(){this.reset()}isFull(){return this.remainingPages<=0}toBinary(t){const e=new Uint8Array(this.buildConfig.blockSize);e.fill(255);let i=0;if(this.buildConfig.useMagic)for(let s=0;s<this.pages.length;s++){const a=this.pages[s];s===this.buildConfig.OBJ_LU_PAGES_PER_BLOCK-1&&a instanceof wi&&a.magicfy(t);const n=a.toBinary();e.set(n,i),i+=n.length}else for(const t of this.pages){const s=t.toBinary();e.set(s,i),i+=s.length}return e}get currentObjIndexSpanIx(){return this.curObjIndexSpanIx}get currentObjDataSpanIx(){return this.curObjDataSpanIx}get currentObjId(){return this.curObjId}get currentObjIdxPage(){return this.curObjIdxPage}set currentObjId(t){this.curObjId=t}set currentObjIdxPage(t){this.curObjIdxPage=t}set currentObjDataSpanIx(t){this.curObjDataSpanIx=t}set currentObjIndexSpanIx(t){this.curObjIndexSpanIx=t}}class Ei{constructor(t,e){if(t%e.blockSize!==0)throw new Error("image size should be a multiple of block size");this.imgSize=t,this.buildConfig=e,this.blocks=[],this.blocksLim=Math.floor(this.imgSize/this.buildConfig.blockSize),this.remainingBlocks=this.blocksLim,this.curObjId=1}createBlock(){if(this.isFull())throw new pi("the image size has been exceeded");const t=new Si(this.blocks.length,this.buildConfig);return this.blocks.push(t),this.remainingBlocks--,t}isFull(){return this.remainingBlocks<=0}createFile(t,e){if(t.length>this.buildConfig.objNameLen)throw new Error(`object name '${t}' too long`);const i=t;let s=0;try{this.blocks[this.blocks.length-1].beginObj(this.curObjId,e.length,i)}catch{this.createBlock().beginObj(this.curObjId,e.length,i)}for(;s<e.length;){const t=Math.min(this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN,e.length-s),a=e.slice(s,s+t);try{const t=this.blocks[this.blocks.length-1];try{t.updateObj(a)}catch(s){if(s instanceof pi){if(t.isFull())throw s;t.beginObj(this.curObjId,e.length,i,t.currentObjIndexSpanIx,t.currentObjDataSpanIx);continue}throw s}}catch(t){if(t instanceof pi){const t=this.blocks[this.blocks.length-1],e=this.createBlock();e.currentObjId=t.currentObjId,e.currentObjIdxPage=t.currentObjIdxPage,e.currentObjDataSpanIx=t.currentObjDataSpanIx,e.currentObjIndexSpanIx=t.currentObjIndexSpanIx;continue}throw t}s+=t}this.blocks[this.blocks.length-1].endObj(),this.curObjId++}toBinary(){const t=[];for(const e of this.blocks)t.push(e.toBinary(this.blocksLim));let e=this.blocks.length,i=this.remainingBlocks;if(this.buildConfig.useMagic)for(;i>0;){const s=new Si(e,this.buildConfig);t.push(s.toBinary(this.blocksLim)),i--,e++}else{const e=this.imgSize-t.length*this.buildConfig.blockSize;if(e>0){const i=new Uint8Array(e);i.fill(255),t.push(i)}}const s=t.reduce((t,e)=>t+e.length,0),a=new Uint8Array(s);let n=0;for(const e of t)a.set(e,n),n+=e.length;return a}listFiles(){throw new Error("listFiles requires fromBinary to be called first")}readFile(){throw new Error("readFile requires fromBinary to be called first")}deleteFile(){throw new Error("deleteFile not yet implemented - requires filesystem recreation")}}class Bi{constructor(t,e){this.imageData=t,this.buildConfig=e,this.filesMap=new Map}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let n=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(n)),n+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(n,!0):s.getUint16(n,!1)),n+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(n,!0):s.getUint32(n,!1)),n+=4}return a}parse(){const t=Math.floor(this.imageData.length/this.buildConfig.blockSize);for(let e=0;e<t;e++){const t=e*this.buildConfig.blockSize,i=this.imageData.slice(t,t+this.buildConfig.blockSize);this.parseBlock(i)}}parseBlock(t){for(let e=0;e<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);for(let t=0;t<s.length&&!(t+this.buildConfig.objIdLen>s.length);t+=this.buildConfig.objIdLen){const e=s.slice(t,t+this.buildConfig.objIdLen),[i]=this.unpack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",e);if(i===(1<<8*this.buildConfig.objIdLen)-1)continue;const a=!!(i&1<<8*this.buildConfig.objIdLen-1),n=i&~(1<<8*this.buildConfig.objIdLen-1);a&&!this.filesMap.has(n)&&this.filesMap.set(n,{name:null,size:0,dataPages:[]})}}for(let e=this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e<this.buildConfig.PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);this.parsePage(s)}}parsePage(t){const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.buildConfig.objIdLen+this.buildConfig.spanIxLen+1;if(t.length<i)return;const[s,a,n]=this.unpack(e,t);if(s===(1<<8*this.buildConfig.objIdLen)-1)return;const r=!!(s&1<<8*this.buildConfig.objIdLen-1),o=s&~(1<<8*this.buildConfig.objIdLen-1);if(r&&248===n)this.filesMap.has(o)||this.filesMap.set(o,{name:null,size:0,dataPages:[]}),0===a&&this.parseIndexPage(t,i,o);else if(!r&&252===n&&this.filesMap.has(o)){const e=i,s=t.slice(e,e+this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN);this.filesMap.get(o).dataPages.push([a,s])}}parseIndexPage(t,e,i){let s=e+this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD;if(s+5<=t.length){const[e]=this.unpack("IB",t,s);s+=5;const a=s+this.buildConfig.objNameLen;if(a<=t.length){const n=t.slice(s,a),r=n.indexOf(0),o=-1!==r?n.slice(0,r):n,h=(new TextDecoder).decode(o),l=this.filesMap.get(i);l.name=h,l.size=e}}}listFiles(){const t=[];for(const[,e]of this.filesMap){if(null===e.name)continue;e.dataPages.sort((t,e)=>t[0]-e[0]);const i=[];let s=0;for(const[,t]of e.dataPages){const a=e.size-s;if(a<=0)break;const n=Math.min(t.length,a);i.push(t.slice(0,n)),s+=n}const a=new Uint8Array(s);let n=0;for(const t of i)a.set(t,n),n+=t.length;t.push({name:e.name,size:e.size,data:a})}return t}readFile(t){const e=this.listFiles().find(e=>e.name===t||e.name==="/"+t);return e?e.data:null}}const ki={pageSize:256,blockSize:4096,objNameLen:32,metaLen:4,useMagic:!0,useMagicLen:!0,alignedObjIxTables:!1},Oi=async t=>{const e=await navigator.serial.requestPort();return await e.open({baudRate:r}),t.log("Connected successfully."),new $e(e,t)};export{c as CHIP_FAMILY_ESP32,f as CHIP_FAMILY_ESP32C2,g as CHIP_FAMILY_ESP32C3,_ as CHIP_FAMILY_ESP32C5,p as CHIP_FAMILY_ESP32C6,b as CHIP_FAMILY_ESP32C61,m as CHIP_FAMILY_ESP32H2,y as CHIP_FAMILY_ESP32H21,w as CHIP_FAMILY_ESP32H4,I as CHIP_FAMILY_ESP32P4,d as CHIP_FAMILY_ESP32S2,u as CHIP_FAMILY_ESP32S3,S as CHIP_FAMILY_ESP32S31,l as CHIP_FAMILY_ESP8266,ki as DEFAULT_SPIFFS_CONFIG,Ke as ESP8266_LITTLEFS_BLOCK_SIZE,We as ESP8266_LITTLEFS_BLOCK_SIZE_CANDIDATES,Xe as ESP8266_LITTLEFS_PAGE_SIZE,qe as ESP8266_SPIFFS_BLOCK_SIZE,Ye as ESP8266_SPIFFS_PAGE_SIZE,$e as ESPLoader,Ve as FATFS_BLOCK_SIZE_CANDIDATES,Je as FATFS_DEFAULT_BLOCK_SIZE,si as FilesystemType,Ze as LITTLEFS_BLOCK_SIZE_CANDIDATES,Ge as LITTLEFS_DEFAULT_BLOCK_SIZE,_i as SpiffsBuildConfig,Ei as SpiffsFS,Bi as SpiffsReader,Oi as connect,ni as detectFilesystemFromImage,ai as detectFilesystemType,gi as formatSize,oi as getBlockSizeCandidates,ri as getDefaultBlockSize,ii as getESP8266FilesystemLayout,fi as getPartitionTableOffset,ui as parsePartitionTable,ti as scanESP8266Filesystem};
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)),n={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"},r=115200,o=1343410176,h=e(" UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU"),l=33382,c=50,d=12882,u=12883,f=12994,g=12995,_=12997,p=12998,b=207969,m=12914,w=12916,y=12917,S=12928,I=12849,E={5:{name:"ESP32-C3",family:g},9:{name:"ESP32-S3",family:u},12:{name:"ESP32-C2",family:f},13:{name:"ESP32-C6",family:p},16:{name:"ESP32-H2",family:m},18:{name:"ESP32-P4",family:S},20:{name:"ESP32-C61",family:b},23:{name:"ESP32-C5",family:_},25:{name:"ESP32-H21",family:y},28:{name:"ESP32-H4",family:w},32:{name:"ESP32-S31",family:I}},B={4293968129:{name:"ESP8266",family:l},15736195:{name:"ESP32",family:c},1990:{name:"ESP32-S2",family:d}},k=3e3,O=15e4,x=100,z=(t,e)=>{const i=Math.floor(t*(e/486));return i<k?k:i},v=t=>{switch(t){case c:return{regBase:1072963584,baseFuse:1073061888,macFuse:1073061888,usrOffs:28,usr1Offs:32,usr2Offs:36,mosiDlenOffs:40,misoDlenOffs:44,w0Offs:128,uartDateReg:1610612856,flashOffs:4096};case d:return{regBase:1061167104,baseFuse:1061265408,macFuse:1061265476,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612856,flashOffs:4096};case u:return{regBase:1610620928,usrOffs:24,baseFuse:1610641408,macFuse:1610641476,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612864,flashOffs:0};case l:return{regBase:1610613248,usrOffs:28,baseFuse:1072693328,macFuse:1072693328,usr1Offs:32,usr2Offs:36,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:64,uartDateReg:1610612856,flashOffs:0};case f:case g:return{regBase:1610620928,baseFuse:1610647552,macFuse:1610647620,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case _:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:8192};case p:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case b:return{regBase:1610625024,baseFuse:1611352064,macFuse:1611352132,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case m:return{regBase:1610625024,baseFuse:1611335680,macFuse:1611335748,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case w:return{regBase:1611239424,baseFuse:1611339776,macFuse:1611339844,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610686588,flashOffs:8192};case y:return{regBase:1610625024,baseFuse:1611350016,macFuse:1611350084,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1610612860,flashOffs:0};case S:return{regBase:1342754816,baseFuse:o,macFuse:1343410244,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:1343004812,flashOffs:8192};case I:return{regBase:542113792,baseFuse:544296960,macFuse:544297028,usrOffs:24,usr1Offs:28,usr2Offs:32,mosiDlenOffs:36,misoDlenOffs:40,w0Offs:88,uartDateReg:540582028,flashOffs:8192};default:return{regBase:-1,baseFuse:-1,macFuse:-1,usrOffs:-1,usr1Offs:-1,usr2Offs:-1,mosiDlenOffs:-1,misoDlenOffs:-1,w0Offs:-1,uartDateReg:-1,flashOffs:-1}}};class A extends Error{constructor(t){super(t),this.name="SlipReadError"}}const D=async(t,i)=>{let s;return t==w||t==y||t==I?null:(t==c?s=await import("./esp32-CijhsJH1.js"):t==d?s=await import("./esp32s2-IiDBtXxo.js"):t==u?s=await import("./esp32s3-6yv5yxum.js"):t==l?s=await import("./esp8266-CUwxJpGa.js"):t==f?s=await import("./esp32c2-C17SM4gO.js"):t==g?s=await import("./esp32c3-DxRGijbg.js"):t==_?s=await import("./esp32c5-3mDOIGa4.js"):t==p?s=await import("./esp32c6-h6U0SQTm.js"):t==b?s=await import("./esp32c61-BKtexhPZ.js"):t==m?s=await import("./esp32h2-RtuWSEmP.js"):t==S&&(s=null!=i&&i>=300?await import("./esp32p4r3-CpHBYEwI.js"):await import("./esp32p4-5nkIjxqJ.js")),{...s,text:e(atob(s.text)),data:e(atob(s.data))})};function C(t){let e=t.length;for(;--e>=0;)t[e]=0}const L=256,R=286,P=30,U=15,F=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]),T=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]),j=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),N=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),$=new Array(576);C($);const M=new Array(60);C(M);const H=new Array(512);C(H);const G=new Array(256);C(G);const J=new Array(29);C(J);const Z=new Array(P);function V(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 K,W,X;function Y(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}C(Z);const q=t=>t<256?H[t]:H[256+(t>>>7)],Q=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},tt=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,Q(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},et=(t,e,i)=>{tt(t,i[2*e],i[2*e+1])},it=(t,e)=>{let i=0;do{i|=1&t,t>>>=1,i<<=1}while(--e>0);return i>>>1},st=(t,e,i)=>{const s=new Array(16);let a,n,r=0;for(a=1;a<=U;a++)r=r+i[a-1]<<1,s[a]=r;for(n=0;n<=e;n++){let e=t[2*n+1];0!==e&&(t[2*n]=it(s[e]++,e))}},at=t=>{let e;for(e=0;e<R;e++)t.dyn_ltree[2*e]=0;for(e=0;e<P;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},nt=t=>{t.bi_valid>8?Q(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},rt=(t,e,i,s)=>{const a=2*e,n=2*i;return t[a]<t[n]||t[a]===t[n]&&s[e]<=s[i]},ot=(t,e,i)=>{const s=t.heap[i];let a=i<<1;for(;a<=t.heap_len&&(a<t.heap_len&&rt(e,t.heap[a+1],t.heap[a],t.depth)&&a++,!rt(e,s,t.heap[a],t.depth));)t.heap[i]=t.heap[a],i=a,a<<=1;t.heap[i]=s},ht=(t,e,i)=>{let s,a,n,r,o=0;if(0!==t.sym_next)do{s=255&t.pending_buf[t.sym_buf+o++],s+=(255&t.pending_buf[t.sym_buf+o++])<<8,a=t.pending_buf[t.sym_buf+o++],0===s?et(t,a,e):(n=G[a],et(t,n+L+1,e),r=F[n],0!==r&&(a-=J[n],tt(t,a,r)),s--,n=q(s),et(t,n,i),r=T[n],0!==r&&(s-=Z[n],tt(t,s,r)))}while(o<t.sym_next);et(t,256,e)},lt=(t,e)=>{const i=e.dyn_tree,s=e.stat_desc.static_tree,a=e.stat_desc.has_stree,n=e.stat_desc.elems;let r,o,h,l=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<n;r++)0!==i[2*r]?(t.heap[++t.heap_len]=l=r,t.depth[r]=0):i[2*r+1]=0;for(;t.heap_len<2;)h=t.heap[++t.heap_len]=l<2?++l:0,i[2*h]=1,t.depth[h]=0,t.opt_len--,a&&(t.static_len-=s[2*h+1]);for(e.max_code=l,r=t.heap_len>>1;r>=1;r--)ot(t,i,r);h=n;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],ot(t,i,1),o=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=o,i[2*h]=i[2*r]+i[2*o],t.depth[h]=(t.depth[r]>=t.depth[o]?t.depth[r]:t.depth[o])+1,i[2*r+1]=i[2*o+1]=h,t.heap[1]=h++,ot(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,n=e.stat_desc.has_stree,r=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,h=e.stat_desc.max_length;let l,c,d,u,f,g,_=0;for(u=0;u<=U;u++)t.bl_count[u]=0;for(i[2*t.heap[t.heap_max]+1]=0,l=t.heap_max+1;l<573;l++)c=t.heap[l],u=i[2*i[2*c+1]+1]+1,u>h&&(u=h,_++),i[2*c+1]=u,c>s||(t.bl_count[u]++,f=0,c>=o&&(f=r[c-o]),g=i[2*c],t.opt_len+=g*(u+f),n&&(t.static_len+=g*(a[2*c+1]+f)));if(0!==_){do{for(u=h-1;0===t.bl_count[u];)u--;t.bl_count[u]--,t.bl_count[u+1]+=2,t.bl_count[h]--,_-=2}while(_>0);for(u=h;0!==u;u--)for(c=t.bl_count[u];0!==c;)d=t.heap[--l],d>s||(i[2*d+1]!==u&&(t.opt_len+=(u-i[2*d+1])*i[2*d],i[2*d+1]=u),c--)}})(t,e),st(i,l,t.bl_count)},ct=(t,e,i)=>{let s,a,n=-1,r=e[1],o=0,h=7,l=4;for(0===r&&(h=138,l=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)a=r,r=e[2*(s+1)+1],++o<h&&a===r||(o<l?t.bl_tree[2*a]+=o:0!==a?(a!==n&&t.bl_tree[2*a]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,n=a,0===r?(h=138,l=3):a===r?(h=6,l=3):(h=7,l=4))},dt=(t,e,i)=>{let s,a,n=-1,r=e[1],o=0,h=7,l=4;for(0===r&&(h=138,l=3),s=0;s<=i;s++)if(a=r,r=e[2*(s+1)+1],!(++o<h&&a===r)){if(o<l)do{et(t,a,t.bl_tree)}while(0!==--o);else 0!==a?(a!==n&&(et(t,a,t.bl_tree),o--),et(t,16,t.bl_tree),tt(t,o-3,2)):o<=10?(et(t,17,t.bl_tree),tt(t,o-3,3)):(et(t,18,t.bl_tree),tt(t,o-11,7));o=0,n=a,0===r?(h=138,l=3):a===r?(h=6,l=3):(h=7,l=4)}};let ut=!1;const ft=(t,e,i,s)=>{tt(t,0+(s?1:0),3),nt(t),Q(t,i),Q(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var gt=(t,e,i,s)=>{let a,n,r=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<L;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0})(t)),lt(t,t.l_desc),lt(t,t.d_desc),r=(t=>{let e;for(ct(t,t.dyn_ltree,t.l_desc.max_code),ct(t,t.dyn_dtree,t.d_desc.max_code),lt(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*N[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e})(t),a=t.opt_len+3+7>>>3,n=t.static_len+3+7>>>3,n<=a&&(a=n)):a=n=i+5,i+4<=a&&-1!==e?ft(t,e,i,s):4===t.strategy||n===a?(tt(t,2+(s?1:0),3),ht(t,$,M)):(tt(t,4+(s?1:0),3),((t,e,i,s)=>{let a;for(tt(t,e-257,5),tt(t,i-1,5),tt(t,s-4,4),a=0;a<s;a++)tt(t,t.bl_tree[2*N[a]+1],3);dt(t,t.dyn_ltree,e-1),dt(t,t.dyn_dtree,i-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,r+1),ht(t,t.dyn_ltree,t.dyn_dtree)),at(t),s&&nt(t)},_t={_tr_init:t=>{ut||((()=>{let t,e,i,s,a;const n=new Array(16);for(i=0,s=0;s<28;s++)for(J[s]=i,t=0;t<1<<F[s];t++)G[i++]=s;for(G[i-1]=s,a=0,s=0;s<16;s++)for(Z[s]=a,t=0;t<1<<T[s];t++)H[a++]=s;for(a>>=7;s<P;s++)for(Z[s]=a<<7,t=0;t<1<<T[s]-7;t++)H[256+a++]=s;for(e=0;e<=U;e++)n[e]=0;for(t=0;t<=143;)$[2*t+1]=8,t++,n[8]++;for(;t<=255;)$[2*t+1]=9,t++,n[9]++;for(;t<=279;)$[2*t+1]=7,t++,n[7]++;for(;t<=287;)$[2*t+1]=8,t++,n[8]++;for(st($,287,n),t=0;t<P;t++)M[2*t+1]=5,M[2*t]=it(t,5);K=new V($,F,257,R,U),W=new V(M,T,0,P,U),X=new V(new Array(0),j,0,19,7)})(),ut=!0),t.l_desc=new Y(t.dyn_ltree,K),t.d_desc=new Y(t.dyn_dtree,W),t.bl_desc=new Y(t.bl_tree,X),t.bi_buf=0,t.bi_valid=0,at(t)},_tr_stored_block:ft,_tr_flush_block:gt,_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*(G[i]+L+1)]++,t.dyn_dtree[2*q(e)]++),t.sym_next===t.sym_end),_tr_align:t=>{tt(t,2,3),et(t,256,$),(t=>{16===t.bi_valid?(Q(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)})(t)}};var pt=(t,e,i,s)=>{let a=65535&t,n=t>>>16&65535,r=0;for(;0!==i;){r=i>2e3?2e3:i,i-=r;do{a=a+e[s++]|0,n=n+a|0}while(--r);a%=65521,n%=65521}return a|n<<16};const bt=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 mt=(t,e,i,s)=>{const a=bt,n=s+i;t^=-1;for(let i=s;i<n;i++)t=t>>>8^a[255&(t^e[i])];return-1^t},wt={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},yt={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:St,_tr_stored_block:It,_tr_flush_block:Et,_tr_tally:Bt,_tr_align:kt}=_t,{Z_NO_FLUSH:Ot,Z_PARTIAL_FLUSH:xt,Z_FULL_FLUSH:zt,Z_FINISH:vt,Z_BLOCK:At,Z_OK:Dt,Z_STREAM_END:Ct,Z_STREAM_ERROR:Lt,Z_DATA_ERROR:Rt,Z_BUF_ERROR:Pt,Z_DEFAULT_COMPRESSION:Ut,Z_FILTERED:Ft,Z_HUFFMAN_ONLY:Tt,Z_RLE:jt,Z_FIXED:Nt,Z_DEFAULT_STRATEGY:$t,Z_UNKNOWN:Mt,Z_DEFLATED:Ht}=yt,Gt=258,Jt=262,Zt=42,Vt=113,Kt=666,Wt=(t,e)=>(t.msg=wt[e],e),Xt=t=>2*t-(t>4?9:0),Yt=t=>{let e=t.length;for(;--e>=0;)t[e]=0},qt=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 Qt=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const te=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))},ee=(t,e)=>{Et(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,te(t.strm)},ie=(t,e)=>{t.pending_buf[t.pending++]=e},se=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ae=(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=pt(t.adler,e,a,i):2===t.state.wrap&&(t.adler=mt(t.adler,e,a,i)),t.next_in+=a,t.total_in+=a,a)},ne=(t,e)=>{let i,s,a=t.max_chain_length,n=t.strstart,r=t.prev_length,o=t.nice_match;const h=t.strstart>t.w_size-Jt?t.strstart-(t.w_size-Jt):0,l=t.window,c=t.w_mask,d=t.prev,u=t.strstart+Gt;let f=l[n+r-1],g=l[n+r];t.prev_length>=t.good_match&&(a>>=2),o>t.lookahead&&(o=t.lookahead);do{if(i=e,l[i+r]===g&&l[i+r-1]===f&&l[i]===l[n]&&l[++i]===l[n+1]){n+=2,i++;do{}while(l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&l[++n]===l[++i]&&n<u);if(s=Gt-(u-n),n=u-Gt,s>r){if(t.match_start=e,r=s,s>=o)break;f=l[n+r-1],g=l[n+r]}}}while((e=d[e&c])>h&&0!==--a);return r<=t.lookahead?r:t.lookahead},re=t=>{const e=t.w_size;let i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Jt)&&(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),qt(t),s+=e),0===t.strm.avail_in)break;if(i=ae(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=Qt(t,t.ins_h,t.window[a+1]);t.insert&&(t.ins_h=Qt(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<Jt&&0!==t.strm.avail_in)},oe=(t,e)=>{let i,s,a,n=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,r=0,o=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<n&&(0===i&&e!==vt||e===Ot||i!==s+t.strm.avail_in))break;r=e===vt&&i===s+t.strm.avail_in?1:0,It(t,0,0,r),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,te(t.strm),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&&(ae(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===r);return o-=t.strm.avail_in,o&&(o>=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<=o&&(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-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),r?4:e!==Ot&&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&&(ae(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,n=a>t.w_size?t.w_size:a,s=t.strstart-t.block_start,(s>=n||(s||e===vt)&&e!==Ot&&0===t.strm.avail_in&&s<=a)&&(i=s>a?a:s,r=e===vt&&0===t.strm.avail_in&&i===s?1:0,It(t,t.block_start,i,r),t.block_start+=i,te(t.strm)),r?3:1)},he=(t,e)=>{let i,s;for(;;){if(t.lookahead<Jt){if(re(t),t.lookahead<Jt&&e===Ot)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-Jt&&(t.match_length=ne(t,i)),t.match_length>=3)if(s=Bt(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!==--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+1]);else s=Bt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2},le=(t,e)=>{let i,s,a;for(;;){if(t.lookahead<Jt){if(re(t),t.lookahead<Jt&&e===Ot)return 1;if(0===t.lookahead)break}if(i=0,t.lookahead>=3&&(t.ins_h=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-Jt&&(t.match_length=ne(t,i),t.match_length<=5&&(t.strategy===Ft||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=Bt(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=Qt(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!==--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,s&&(ee(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if(s=Bt(t,0,t.window[t.strstart-1]),s&&ee(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=Bt(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2};function ce(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 de=[new ce(0,0,0,0,oe),new ce(4,4,8,4,he),new ce(4,5,16,8,he),new ce(4,6,32,32,he),new ce(4,4,16,16,le),new ce(8,16,32,32,le),new ce(8,16,128,128,le),new ce(8,32,128,256,le),new ce(32,128,258,1024,le),new ce(32,258,258,4096,le)];function ue(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Ht,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),Yt(this.dyn_ltree),Yt(this.dyn_dtree),Yt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),Yt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),Yt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const fe=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==Zt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==Vt&&e.status!==Kt?1:0},ge=t=>{if(fe(t))return Wt(t,Lt);t.total_in=t.total_out=0,t.data_type=Mt;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?Zt:Vt,t.adler=2===e.wrap?0:1,e.last_flush=-2,St(e),Dt},_e=t=>{const e=ge(t);var i;return e===Dt&&((i=t.state).window_size=2*i.w_size,Yt(i.head),i.max_lazy_match=de[i.level].max_lazy,i.good_match=de[i.level].good_length,i.nice_match=de[i.level].nice_length,i.max_chain_length=de[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),e},pe=(t,e,i,s,a,n)=>{if(!t)return Lt;let r=1;if(e===Ut&&(e=6),s<0?(r=0,s=-s):s>15&&(r=2,s-=16),a<1||a>9||i!==Ht||s<8||s>15||e<0||e>9||n<0||n>Nt||8===s&&1!==r)return Wt(t,Lt);8===s&&(s=9);const o=new ue;return t.state=o,o.strm=t,o.status=Zt,o.wrap=r,o.gzhead=null,o.w_bits=s,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=a+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+3-1)/3),o.window=new Uint8Array(2*o.w_size),o.head=new Uint16Array(o.hash_size),o.prev=new Uint16Array(o.w_size),o.lit_bufsize=1<<a+6,o.pending_buf_size=4*o.lit_bufsize,o.pending_buf=new Uint8Array(o.pending_buf_size),o.sym_buf=o.lit_bufsize,o.sym_end=3*(o.lit_bufsize-1),o.level=e,o.strategy=n,o.method=i,_e(t)};var be={deflateInit:(t,e)=>pe(t,e,Ht,15,8,$t),deflateInit2:pe,deflateReset:_e,deflateResetKeep:ge,deflateSetHeader:(t,e)=>fe(t)||2!==t.state.wrap?Lt:(t.state.gzhead=e,Dt),deflate:(t,e)=>{if(fe(t)||e>At||e<0)return t?Wt(t,Lt):Lt;const i=t.state;if(!t.output||0!==t.avail_in&&!t.input||i.status===Kt&&e!==vt)return Wt(t,0===t.avail_out?Pt:Lt);const s=i.last_flush;if(i.last_flush=e,0!==i.pending){if(te(t),0===t.avail_out)return i.last_flush=-1,Dt}else if(0===t.avail_in&&Xt(e)<=Xt(s)&&e!==vt)return Wt(t,Pt);if(i.status===Kt&&0!==t.avail_in)return Wt(t,Pt);if(i.status===Zt&&0===i.wrap&&(i.status=Vt),i.status===Zt){let e=Ht+(i.w_bits-8<<4)<<8,s=-1;if(s=i.strategy>=Tt||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,se(i,e),0!==i.strstart&&(se(i,t.adler>>>16),se(i,65535&t.adler)),t.adler=1,i.status=Vt,te(t),0!==i.pending)return i.last_flush=-1,Dt}if(57===i.status)if(t.adler=0,ie(i,31),ie(i,139),ie(i,8),i.gzhead)ie(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),ie(i,255&i.gzhead.time),ie(i,i.gzhead.time>>8&255),ie(i,i.gzhead.time>>16&255),ie(i,i.gzhead.time>>24&255),ie(i,9===i.level?2:i.strategy>=Tt||i.level<2?4:0),ie(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(ie(i,255&i.gzhead.extra.length),ie(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=mt(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,0),ie(i,9===i.level?2:i.strategy>=Tt||i.level<2?4:0),ie(i,3),i.status=Vt,te(t),0!==i.pending)return i.last_flush=-1,Dt;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=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex+=a,te(t),0!==i.pending)return i.last_flush=-1,Dt;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=mt(t.adler,i.pending_buf,i.pending-e,e)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let e,s=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>s&&(t.adler=mt(t.adler,i.pending_buf,i.pending-s,s)),te(t),0!==i.pending)return i.last_flush=-1,Dt;s=0}e=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=mt(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=mt(t.adler,i.pending_buf,i.pending-s,s)),te(t),0!==i.pending)return i.last_flush=-1,Dt;s=0}e=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,ie(i,e)}while(0!==e);i.gzhead.hcrc&&i.pending>s&&(t.adler=mt(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&&(te(t),0!==i.pending))return i.last_flush=-1,Dt;ie(i,255&t.adler),ie(i,t.adler>>8&255),t.adler=0}if(i.status=Vt,te(t),0!==i.pending)return i.last_flush=-1,Dt}if(0!==t.avail_in||0!==i.lookahead||e!==Ot&&i.status!==Kt){let s=0===i.level?oe(i,e):i.strategy===Tt?((t,e)=>{let i;for(;;){if(0===t.lookahead&&(re(t),0===t.lookahead)){if(e===Ot)return 1;break}if(t.match_length=0,i=Bt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):i.strategy===jt?((t,e)=>{let i,s,a,n;const r=t.window;for(;;){if(t.lookahead<=Gt){if(re(t),t.lookahead<=Gt&&e===Ot)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(a=t.strstart-1,s=r[a],s===r[++a]&&s===r[++a]&&s===r[++a])){n=t.strstart+Gt;do{}while(s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&s===r[++a]&&a<n);t.match_length=Gt-(n-a),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(i=Bt(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=Bt(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(ee(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,e===vt?(ee(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(ee(t,!1),0===t.strm.avail_out)?1:2})(i,e):de[i.level].func(i,e);if(3!==s&&4!==s||(i.status=Kt),1===s||3===s)return 0===t.avail_out&&(i.last_flush=-1),Dt;if(2===s&&(e===xt?kt(i):e!==At&&(It(i,0,0,!1),e===zt&&(Yt(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),te(t),0===t.avail_out))return i.last_flush=-1,Dt}return e!==vt?Dt:i.wrap<=0?Ct:(2===i.wrap?(ie(i,255&t.adler),ie(i,t.adler>>8&255),ie(i,t.adler>>16&255),ie(i,t.adler>>24&255),ie(i,255&t.total_in),ie(i,t.total_in>>8&255),ie(i,t.total_in>>16&255),ie(i,t.total_in>>24&255)):(se(i,t.adler>>>16),se(i,65535&t.adler)),te(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Dt:Ct)},deflateEnd:t=>{if(fe(t))return Lt;const e=t.state.status;return t.state=null,e===Vt?Wt(t,Rt):Dt},deflateSetDictionary:(t,e)=>{let i=e.length;if(fe(t))return Lt;const s=t.state,a=s.wrap;if(2===a||1===a&&s.status!==Zt||s.lookahead)return Lt;if(1===a&&(t.adler=pt(t.adler,e,i,0)),s.wrap=0,i>=s.w_size){0===a&&(Yt(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 n=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,re(s);s.lookahead>=3;){let t=s.strstart,e=s.lookahead-2;do{s.ins_h=Qt(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,re(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=r,t.input=o,t.avail_in=n,s.wrap=a,Dt},deflateInfo:"pako deflate (from Nodeca project)"};const me=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var we=function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const e in i)me(i,e)&&(t[e]=i[e])}}return t},ye=t=>{let e=0;for(let i=0,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 Se=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){Se=!1}const Ie=new Uint8Array(256);for(let t=0;t<256;t++)Ie[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;Ie[254]=Ie[254]=1;var Ee=t=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(t);let e,i,s,a,n,r=t.length,o=0;for(a=0;a<r;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<r&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(o),n=0,a=0;n<o;a++)i=t.charCodeAt(a),55296==(64512&i)&&a+1<r&&(s=t.charCodeAt(a+1),56320==(64512&s)&&(i=65536+(i-55296<<10)+(s-56320),a++)),i<128?e[n++]=i:i<2048?(e[n++]=192|i>>>6,e[n++]=128|63&i):i<65536?(e[n++]=224|i>>>12,e[n++]=128|i>>>6&63,e[n++]=128|63&i):(e[n++]=240|i>>>18,e[n++]=128|i>>>12&63,e[n++]=128|i>>>6&63,e[n++]=128|63&i);return e};var Be=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 ke=Object.prototype.toString,{Z_NO_FLUSH:Oe,Z_SYNC_FLUSH:xe,Z_FULL_FLUSH:ze,Z_FINISH:ve,Z_OK:Ae,Z_STREAM_END:De,Z_DEFAULT_COMPRESSION:Ce,Z_DEFAULT_STRATEGY:Le,Z_DEFLATED:Re}=yt;function Pe(t){this.options=we({level:Ce,method:Re,chunkSize:16384,windowBits:15,memLevel:8,strategy:Le},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 Be,this.strm.avail_out=0;let i=be.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==Ae)throw new Error(wt[i]);if(e.header&&be.deflateSetHeader(this.strm,e.header),e.dictionary){let t;if(t="string"==typeof e.dictionary?Ee(e.dictionary):"[object ArrayBuffer]"===ke.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,i=be.deflateSetDictionary(this.strm,t),i!==Ae)throw new Error(wt[i]);this._dict_set=!0}}Pe.prototype.push=function(t,e){const i=this.strm,s=this.options.chunkSize;let a,n;if(this.ended)return!1;for(n=e===~~e?e:!0===e?ve:Oe,"string"==typeof t?i.input=Ee(t):"[object ArrayBuffer]"===ke.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),(n===xe||n===ze)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(a=be.deflate(i,n),a===De)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),a=be.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===Ae;if(0!==i.avail_out){if(n>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},Pe.prototype.onData=function(t){this.chunks.push(t)},Pe.prototype.onEnd=function(t){t===Ae&&(this.result=ye(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var Ue={deflate:function(t,e){const i=new Pe(e);if(i.push(t,!0),i.err)throw i.msg||wt[i.err];return i.result}};const{deflate:Fe}=Ue;var Te=Fe;const je={b:{u:DataView.prototype.getInt8,p:DataView.prototype.setInt8,bytes:1},B:{u:DataView.prototype.getUint8,p:DataView.prototype.setUint8,bytes:1},h:{u:DataView.prototype.getInt16,p:DataView.prototype.setInt16,bytes:2},H:{u:DataView.prototype.getUint16,p:DataView.prototype.setUint16,bytes:2},i:{u:DataView.prototype.getInt32,p:DataView.prototype.setInt32,bytes:4},I:{u:DataView.prototype.getUint32,p:DataView.prototype.setUint32,bytes:4}},Ne=(t,...e)=>{let i=0;if(t.replace(/[<>]/,"").length!=e.length)throw"Pack format to Argument count mismatch";const s=[];let a=!0;for(let s=0;s<t.length;s++)"<"==t[s]?a=!0:">"==t[s]?a=!1:(n(t[s],e[i]),i++);function n(t,e){if(!(t in je))throw"Unhandled character '"+t+"' in pack format";const i=je[t].bytes,n=new DataView(new ArrayBuffer(i));je[t].p.bind(n)(0,e,a);for(let t=0;t<i;t++)s.push(n.getUint8(t))}return s},$e=(t,e)=>{let i=0;const s=[];let a=!0;for(const e of t)"<"==e?a=!0:">"==e?a=!1:n(e);function n(t){if(!(t in je))throw"Unhandled character '"+t+"' in unpack format";const n=je[t].bytes,r=new DataView(new ArrayBuffer(n));for(let t=0;t<n;t++)r.setUint8(t,255&e[i+t]);const o=je[t].u.bind(r);s.push(o(0,a)),i+=n}return s};class Me 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=r,this._isESP32S2NativeUSB=!1,this._initializationSucceeded=!1,this.state_DTR=!1}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}get _totalBytesRead(){return this._parent?this._parent._totalBytesRead:this.__totalBytesRead||0}set _totalBytesRead(t){this._parent?this._parent._totalBytesRead=t:this.__totalBytesRead=t}detectUSBSerialChip(t,e){const i={6790:{29986:{name:"CH340",maxBaudrate:460800},29987:{name:"CH340",maxBaudrate:460800},30084:{name:"CH340",maxBaudrate:460800},21795:{name:"CH341",maxBaudrate:2e6},21971:{name:"CH343",maxBaudrate:6e6},21972:{name:"CH9102",maxBaudrate:6e6},21976:{name:"CH9101",maxBaudrate:3e6}},4292:{6e4:{name:"CP2102(n)",maxBaudrate:3e6},60016:{name:"CP2105",maxBaudrate:2e6},60017:{name:"CP2108",maxBaudrate:2e6}},1027:{24577:{name:"FT232R",maxBaudrate:3e6},24592:{name:"FT2232",maxBaudrate:3e6},24593:{name:"FT4232",maxBaudrate:3e6},24596:{name:"FT232H",maxBaudrate:12e6},24597:{name:"FT230X",maxBaudrate:3e6}},12346:{2:{name:"ESP32-S2 Native USB",maxBaudrate:2e6},4097:{name:"ESP32 Native USB",maxBaudrate:2e6},4098:{name:"ESP32 Native USB",maxBaudrate:2e6},16386:{name:"ESP32 Native USB",maxBaudrate:2e6},4096:{name:"ESP32 Native USB",maxBaudrate:2e6}}}[t];return i&&i[e]?i[e]:{name:`Unknown (VID: 0x${t.toString(16)}, PID: 0x${e.toString(16)})`}}async initialize(){if(!this._parent){this.__inputBuffer=[],this.__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)}this.readLoop()}await this.connectWithResetStrategies(),await this.detectChip();const t=v(this.getChipFamily()),e=t.macFuse;for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`),this.logger.debug(`Bootloader flash offset: 0x${t.flashOffs.toString(16)}`),this._initializationSucceeded=!0}async detectChip(){try{const t=(await this.getSecurityInfo()).chipId,e=E[t];if(e)return this.chipName=e.name,this.chipFamily=e.family,this.chipFamily===S&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),void this.logger.debug(`Detected chip via IMAGE_CHIP_ID: ${t} (${this.chipName})`);this.logger.debug(`Unknown IMAGE_CHIP_ID: ${t}, falling back to magic value detection`)}catch(t){this.logger.debug(`GET_SECURITY_INFO failed, using magic value detection: ${t}`),await this.drainInputBuffer(200),this._inputBuffer.length=0,await a(x);try{await this.sync()}catch(t){this.logger.debug(`Re-sync after GET_SECURITY_INFO failure: ${t}`)}}const t=await this.readRegister(1073745920),e=B[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.chipFamily===S&&(this.chipRevision=await this.getChipRevision(),this.logger.debug(`ESP32-P4 revision: ${this.chipRevision}`),this.chipRevision>=300?this.chipVariant="rev300":this.chipVariant="rev0",this.logger.debug(`ESP32-P4 variant: ${this.chipVariant}`)),this.logger.debug(`Detected chip via magic value: ${s(t>>>0,8)} (${this.chipName})`)}async getChipRevision(){if(this.chipFamily!==S)return 0;const t=await this.readRegister(1343410252);return 100*((t>>23&1)<<2|t>>4&3)+(15&t)}async getSecurityInfo(){const[,t]=await this.checkCommand(20,[],0);if(0===t.length)throw new Error("GET_SECURITY_INFO not supported or returned empty response");if(t.length<12)throw new Error(`Invalid security info response length: ${t.length} (expected at least 12 bytes)`);return{flags:$e("<I",t.slice(0,4))[0],flashCryptCnt:t[4],keyPurposes:Array.from(t.slice(5,12)),chipId:t.length>=16?$e("<I",t.slice(12,16))[0]:0,apiVersion:t.length>=20?$e("<I",t.slice(16,20))[0]:0}}async readLoop(){this.debug&&this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{let t=!0;for(;t;){const{value:e,done:i}=await this._reader.read();if(i){this._reader.releaseLock(),t=!1;break}if(!e||0===e.length)continue;const s=Array.from(e);Array.prototype.push.apply(this._inputBuffer,s),this._totalBytesRead+=e.length}}catch{this.logger.error("Read loop got disconnected")}this.connected=!1,this._isESP32S2NativeUSB&&!this._initializationSucceeded&&(this.logger.log("ESP32-S2 Native USB detected - requesting port reselection"),this.dispatchEvent(new CustomEvent("esp32s2-usb-reconnect",{detail:{message:"ESP32-S2 Native USB requires port reselection"}}))),this.dispatchEvent(new Event("disconnect")),this.logger.debug("Finished read loop")}sleep(t=100){return new Promise(e=>setTimeout(e,t))}async setRTS(t){await this.port.setSignals({requestToSend:t}),await this.setDTR(this.state_DTR)}async setDTR(t){this.state_DTR=t,await this.port.setSignals({dataTerminalReady:t})}async 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 n;if(this.chipFamily==l){if(0!=a)n=[a>>16&255,a>>8&255,255&a];else if(i>>16&255){if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");n=[172,208,116]}else n=[24,254,52];t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=i>>8&255,t[4]=255&i,t[5]=e>>24&255}else if(this.chipFamily==c)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!=d&&this.chipFamily!=u&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=_&&this.chipFamily!=p&&this.chipFamily!=b&&this.chipFamily!=m&&this.chipFamily!=w&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=I)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=Ne("<I",t);await this.sendCommand(10,e);const[i]=await this.getResponse(10);return i}async checkCommand(t,e,i=0,a=3e3){a=Math.min(a,3e5),await this.sendCommand(t,e,i);const[n,r]=await this.getResponse(t,a);if(null===r)throw new Error("Didn't get enough status bytes");let o=r,h=0;if(this.IS_STUB||this.chipFamily==l?h=2:[c,d,u,f,g,_,p,b,m,w,y,S,I].includes(this.chipFamily)||20===t?h=4:[2,4].includes(o.length)&&(h=o.length),o.length<h)throw new Error("Didn't get enough status bytes");const E=o.slice(-h,o.length);if(o=o.slice(0,-h),this.debug&&(this.logger.debug("status",E),this.logger.debug("value",n),this.logger.debug("data",o)),1==E[0])throw 5==E[1]?(await this.drainInputBuffer(200),new Error("Invalid (unsupported) command "+s(t))):new Error("Command failure error code "+s(E[1]));return[n,o]}async sendCommand(e,i,s=0){const a=t([...Ne("<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,n=!1,r=[];for(;;){const o=Date.now();for(r=[];Date.now()-o<t;){if(this._inputBuffer.length>0){r.push(this._inputBuffer.shift());break}await a(1)}if(0==r.length){throw new A("Timed out waiting for packet "+(null===e?"header":"content"))}this.debug&&this.logger.debug("Read "+r.length+" bytes: "+i(r));for(const t of r)if(null===e){if(192!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+i(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new A("Invalid head of packet ("+s(t)+")");e=[]}else if(n)if(n=!1,220==t)e.push(192);else{if(221!=t)throw this.debug&&(this.logger.debug("Read invalid data: "+i(r)),this.logger.debug("Remaining data in serial buffer: "+i(this._inputBuffer))),new A("Invalid SLIP escape (0xdb, "+s(t)+")");e.push(219)}else if(219==t)n=!0;else{if(192==t)return this.debug&&this.logger.debug("Received full packet: "+i(e)),e;e.push(t)}}throw new A("Invalid state")}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,n,,r]=$e("<BBHI",i.slice(0,8));if(1!=a)continue;const o=i.slice(8);if(null==t||n==t)return[r,o];if(0!=o[0]&&5==o[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 setBaudrate(t){if(this.chipFamily==l)throw new Error("Changing baud rate is not supported on the ESP8266");try{const e=Ne("<II",t,this.IS_STUB?r:0);await this.checkCommand(15,e)}catch(e){throw this.logger.error(`Baudrate change error: ${e}`),new Error(`Unable to change the baud rate to ${t}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(t):await this.reconfigurePort(t),await a(x),this._parent?this._parent._currentBaudRate=t:this._currentBaudRate=t;const e=this._parent?this._parent._maxUSBSerialBaudrate:this._maxUSBSerialBaudrate;e&&t>e&&(this.logger.log(`⚠️ WARNING: Baudrate ${t} exceeds USB-Serial chip limit (${e})!`),this.logger.log("⚠️ This may cause data corruption or connection failures!")),this.logger.log(`Changed baud rate to ${t}`)}async reconfigurePort(t){var e;try{await(null===(e=this._reader)||void 0===e?void 0:e.cancel()),await this.port.close(),await this.port.open({baudRate:t}),await this.flushSerialBuffers(),this.readLoop()}catch(e){throw this.logger.error(`Reconfigure port error: ${e}`),new Error(`Unable to change the baud rate to ${t}: ${e}`)}}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 n=[];(s||a)&&n.push({name:"USB-JTAG/Serial",fn:async()=>await this.hardResetUSBJTAGSerial()}),n.push({name:"Classic",fn:async()=>await this.hardResetClassic()}),s||a||n.push({name:"USB-JTAG/Serial (fallback)",fn:async()=>await this.hardResetUSBJTAGSerial()});let r=null;for(const t of n)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(r=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==r?void 0:r.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(x),!0;await a(x)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(8,h);for(let t=0;t<8;t++)try{const[,t]=await this.getResponse(8,x);if(t.length>1&&0==t[0]&&0==t[1])return!0}catch{}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],n=e[3];this.logger.log(`Image header, Magic=${s(i)}, FlashMode=${s(a)}, FlashSizeFreq=${s(n)}`)}const n=t.byteLength;let r,o=0,h=k;a?(r=Te(new Uint8Array(t),{level:9}).buffer,o=r.byteLength,this.logger.log(`Writing data with filesize: ${n}. Compressed Size: ${o}`),h=await this.flashDeflBegin(n,o,i)):(this.logger.log(`Writing data with filesize: ${n}`),r=t,await this.flashBegin(n,i));let l=[],c=0,d=0,u=0;const f=Date.now(),g=this.getFlashWriteSize(),_=a?o:n;for(;_-u>0;)this.debug&&this.logger.log(`Writing at ${s(i+c*g,8)} `),_-u>=g?l=Array.from(new Uint8Array(r,u,g)):(l=Array.from(new Uint8Array(r,u,_-u)),a||(l=l.concat(new Array(g-l.length).fill(255)))),a?await this.flashDeflBlock(l,c,h):await this.flashBlock(l,c),c+=1,d+=a?Math.round(l.length*n/o):l.length,u+=g,e(Math.min(d,n),n);this.logger.log("Took "+(Date.now()-f)+"ms to write "+_+" 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,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashDeflBlock(t,e,i=3e3){await this.checkCommand(17,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t),i)}async flashBegin(t=0,e=0,i=!1){let a;await this.flushSerialBuffers();const n=this.getFlashWriteSize();!this.IS_STUB&&[c,d,u,f,g,_,p,b,m,w,y,S,I].includes(this.chipFamily)&&await this.checkCommand(13,new Array(8).fill(0));const r=Math.floor((t+n-1)/n);a=this.chipFamily==l?this.getEraseSize(e,t):t;const o=this.IS_STUB?k:z(3e4,t),h=Date.now();let E=Ne("<IIII",a,r,n,e);return this.chipFamily!=c&&this.chipFamily!=d&&this.chipFamily!=u&&this.chipFamily!=f&&this.chipFamily!=g&&this.chipFamily!=_&&this.chipFamily!=p&&this.chipFamily!=b&&this.chipFamily!=m&&this.chipFamily!=w&&this.chipFamily!=y&&this.chipFamily!=S&&this.chipFamily!=I||(E=E.concat(Ne("<I",i?1:0))),this.logger.log("Erase size "+a+", blocks "+r+", block size "+s(n,4)+", offset "+s(e,4)+", encrypted "+(i?"yes":"no")),await this.checkCommand(2,E,0,o),0==t||this.IS_STUB||this.logger.log("Took "+(Date.now()-h)+"ms to erase "+r+" bytes"),r}async flashDeflBegin(t=0,e=0,i=0){const s=this.getFlashWriteSize(),a=Math.floor((e+s-1)/s),n=Math.floor((t+s-1)/s);let r=0,o=0;this.IS_STUB?(r=t,o=z(3e4,r)):(r=n*s,o=k);const h=Ne("<IIII",r,a,s,i);return await this.checkCommand(16,h,0,o),o}async flashFinish(){const t=Ne("<I",1);await this.checkCommand(4,t)}async flashDeflFinish(){const t=Ne("<I",1);await this.checkCommand(18,t)}getBootloaderOffset(){return 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 n=Ne("<IIII",t,e,i,s);a>0&&(n=n.concat(Ne("<IIII",v(this.getChipFamily()).uartDateReg,0,0,a))),await this.checkCommand(9,n)}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()),n=a.regBase,r=n,o=n+a.usrOffs,h=n+a.usr2Offs,l=n+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,u=await this.readRegister(o),f=await this.readRegister(h);let g=1<<31;if(i>0&&(g|=268435456),d>0&&(g|=134217728),await this.setDataLengths(a,d,i),await this.writeRegister(o,g),await this.writeRegister(h,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=$e("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(r,c),await this.waitDone(r,c);const _=await this.readRegister(l);return await this.writeRegister(o,u),await this.writeRegister(h,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=n[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,Ne("<IIII",t,e,i,s))}async memBlock(t,e){return await this.checkCommand(7,Ne("<IIII",t.length,e,0,0).concat(t),this.checksum(t))}async memFinish(t=0){const e=this.IS_STUB?k:500,i=Ne("<II",0==t?1:0,t);return await this.checkCommand(6,i,0,e)}async runStub(t=!1){const e=await D(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`],n=s.length,r=Math.floor((n+i-1)/i);await this.memBegin(n,r,i,a);for(const t of Array(r).keys()){const e=t*i;let a=e+i;a>n&&(a=n),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 n=new He(this.port,this.logger,this);return t||await n.detectFlashSize(),n}async writeToStream(t){if(!this.port.writable)return void this.logger.debug("Port writable stream not available, skipping write");const e=this.port.writable.getWriter();await e.write(new Uint8Array(t));try{e.releaseLock()}catch(t){this.logger.error(`Ignoring release lock error: ${t}`)}}async disconnect(){this._parent?await this._parent.disconnect():this.port.writable?(await this.port.writable.getWriter().close(),await new Promise(t=>{this._reader||t(void 0),this.addEventListener("disconnect",t,{once:!0}),this._reader.cancel()}),this.connected=!1):this.logger.debug("Port already closed, skipping disconnect")}async reconnect(){if(this._parent)return void await this._parent.reconnect();if(this.logger.log("Reconnecting serial port..."),this.connected=!1,this.__inputBuffer=[],this._reader){try{await this._reader.cancel()}catch(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:r}),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})`);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");const n=await this.runStub(!0);if(this.logger.debug("Stub loaded"),this._currentBaudRate!==r&&(await n.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,n),this.logger.debug("Reconnection successful")}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(x),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 n=new Uint8Array(0),r=e,o=i;for(;o>0;){const e=Math.min(65536,o);let h=!1,l=0;const c=5;for(;!h&&l<=c;){let i=new Uint8Array(0);try{this.logger.debug(`Reading chunk at 0x${r.toString(16)}, size: 0x${e.toString(16)}`);const s=Ne("<IIII",r,e,4096,1024),[a]=await this.checkCommand(210,s);if(0!=a)throw new Error("Failed to read memory: "+a);for(;i.length<e;){let s;try{s=await this.readPacket(100)}catch(s){if(s instanceof A){if(this.logger.debug(`SLIP read error at ${i.length} bytes: ${s.message}`),i.length>0)try{const e=Ne("<I",i.length),s=t(e);await this.writeToStream(s)}catch(t){this.logger.debug(`ACK send error: ${t}`)}if(await this.drainInputBuffer(300),i.length>=e)break}throw s}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 n=Ne("<I",i.length),r=t(n);await this.writeToStream(r)}}const o=new Uint8Array(n.length+i.length);o.set(n),o.set(i,n.length),n=o,h=!0}catch(t){if(l++,!(t instanceof A))throw t;if(!(l<=c))throw new Error(`Failed to read chunk at 0x${r.toString(16)} after ${c} retries: ${t}`);this.logger.log(`⚠️ ${t.message} at 0x${r.toString(16)}. Draining buffer and retrying (attempt ${l}/${c})...`);try{await this.drainInputBuffer(300),await this.flushSerialBuffers(),await a(x)}catch(t){this.logger.debug(`Buffer drain error: ${t}`)}}}s&&s(new Uint8Array(e),n.length,i),r+=e,o-=e,this.logger.debug(`Total progress: 0x${n.length.toString(16)} from 0x${i.toString(16)} bytes`)}return this.logger.debug(`Successfully read ${n.length} bytes from flash`),n}}class He extends Me{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(t,e,i,a){const n=await D(this.chipFamily,this.chipRevision);if(null===n)return[0,[]];const r=a,o=a+t;this.logger.debug(`Load range: ${s(r,8)}-${s(o,8)}`),this.logger.debug(`Stub data: ${s(n.data_start,8)}, len: ${n.data.length}, text: ${s(n.text_start,8)}, len: ${n.text.length}`);for(const[t,e]of[[n.data_start,n.data_start+n.data.length],[n.text_start,n.text_start+n.text.length]])if(r<e&&o>t)throw new Error("Software loader is resident at "+s(t,8)+"-"+s(e,8)+". Can't load binary at overlapping address range "+s(r,8)+"-"+s(o,8)+". Try changing the binary loading address.");return[0,[]]}async eraseFlash(){await this.checkCommand(208,[],0,O)}}const Ge=4096,Je=[4096,2048,1024,512],Ze=4096,Ve=[4096,2048,1024,512],Ke=8192,We=[8192,4096],Xe=256,Ye=256,qe=8192;function Qe(t){if(t.length<4096)return!1;let e=0;const i=256,s=Math.min(32,Math.floor(t.length/i));for(let a=0;a<s;a++){const s=a*i;if(s+i>t.length)break;const n=t.slice(s,s+i),r=n[0]|n[1]<<8;for(let t=0;t<n.length-10;t++)if(1===n[t]&&47===n[t+1]){let i=0;for(let e=t+1;e<Math.min(t+20,n.length);e++)if(n[e]>=32&&n[e]<127)i++;else if(0===n[e])break;if(i>=4){e+=5;break}}if(32768&r){const t=32767&r;t>0&&t<4096&&(e+=2)}}return e>=10}function ti(t,e,i){const s=We;for(const a of s)for(let s=0;s<2;s++){const n=s*a,r=n+8;if(r+8>t.length)continue;if("littlefs"===String.fromCharCode(t[r],t[r+1],t[r+2],t[r+3],t[r+4],t[r+5],t[r+6],t[r+7])){const s=n+16,r=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(0!==r&&r>>>0!=4294967295){const s=n+24;if(s+4<=t.length){const n=t[s]|t[s+1]<<8|t[s+2]<<16|t[s+3]<<24;if(n>0&&n<1e5){const t=n*a;if(t>0&&e+t<=i)return{start:e,end:e+t,size:t,page:256,block:a}}}return ei(e,i,a)}}}if(Qe(t))return ei(e,i,qe);if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24)){let s=!0;if(t.length>=16){let e=!0;for(let i=4;i<16;i++)if(255!==t[i]){e=!1;break}e&&(s=!1)}if(s)return ei(e,i,qe)}}const a=[0,4096];for(const s of a){if(t.length<s+512)continue;if(43605===(t[s+510]|t[s+511]<<8)){const a=t[s+11]|t[s+12]<<8;if(![512,1024,2048,4096].includes(a))continue;let n=t[s+19]|t[s+20]<<8;if(0===n&&(n=t[s+32]|t[s+33]<<8|t[s+34]<<16|t[s+35]<<24),a>0&&n>0&&n<1e8){const t=n*a,r=e+s;if(t>0&&r+t<=i)return{start:r,end:r+t,size:t,page:a,block:a}}}}return null}function ei(t,e,i){const s=e/1048576;if(s>=16){if(1048576===t)return{start:1048576,end:16752640,size:15704064,page:256,block:i};if(2097152===t)return{start:2097152,end:16752640,size:14655488,page:256,block:i}}if(s>=8){if(1048576===t)return{start:1048576,end:8364032,size:7315456,page:256,block:i};if(2097152===t)return{start:2097152,end:8364032,size:6266880,page:256,block:i}}if(s>=4){if(1048576===t)return{start:1048576,end:4169728,size:3121152,page:256,block:i};if(2097152===t)return{start:2097152,end:4169728,size:2072576,page:256,block:i};if(3145728===t)return{start:3145728,end:4169728,size:1024e3,page:256,block:i}}if(s>=2){if(1048576===t)return{start:1048576,end:2072576,size:1024e3,page:256,block:i};if(1572864===t)return{start:1572864,end:2072576,size:499712,page:256,block:i};if(1835008===t)return{start:1835008,end:2076672,size:241664,page:256,block:i};if(1966080===t)return{start:1966080,end:2076672,size:110592,page:256,block:i};if(2031616===t)return{start:2031616,end:2076672,size:45056,page:256,block:i}}if(s>=1){if(503808===t)return{start:503808,end:1028096,size:524288,page:256,block:i};if(765952===t)return{start:765952,end:1028096,size:262144,page:256,block:i};if(831488===t)return{start:831488,end:1028096,size:196608,page:256,block:i};if(864256===t)return{start:864256,end:1028096,size:163840,page:256,block:i};if(880640===t)return{start:880640,end:1028096,size:147456,page:256,block:i};if(897024===t)return{start:897024,end:1028096,size:131072,page:256,block:i};if(962560===t)return{start:962560,end:1028096,size:65536,page:256,block:i}}if(s>=.5){if(372736===t)return{start:372736,end:503808,size:131072,page:256,block:i};if(438272===t)return{start:438272,end:503808,size:65536,page:256,block:i};if(471040===t)return{start:471040,end:503808,size:32768,page:256,block:i}}return{start:t,end:e,size:e-t,page:256,block:i}}function ii(t){return t>=16?[{start:1048576,end:16752640,size:15704064,page:256,block:8192},{start:2097152,end:16752640,size:14655488,page:256,block:8192}]:t>=8?[{start:1048576,end:8364032,size:7315456,page:256,block:8192},{start:2097152,end:8364032,size:6266880,page:256,block:8192}]:t>=4?[{start:2097152,end:4169728,size:2072576,page:256,block:8192},{start:1048576,end:4169728,size:3121152,page:256,block:8192},{start:3145728,end:4169728,size:1024e3,page:256,block:8192}]:t>=2?[{start:1048576,end:2072576,size:1024e3,page:256,block:8192},{start:1572864,end:2072576,size:499712,page:256,block:8192},{start:1835008,end:2076672,size:241664,page:256,block:8192},{start:1966080,end:2076672,size:110592,page:256,block:8192},{start:2031616,end:2076672,size:45056,page:256,block:8192}]:t>=1?[{start:897024,end:1028096,size:131072,page:256,block:8192},{start:503808,end:1028096,size:524288,page:256,block:8192},{start:765952,end:1028096,size:262144,page:256,block:8192},{start:831488,end:1028096,size:196608,page:256,block:8192},{start:864256,end:1028096,size:163840,page:256,block:8192},{start:880640,end:1028096,size:147456,page:256,block:8192},{start:962560,end:1028096,size:65536,page:256,block:8192}]:t>=.5?[{start:372736,end:503808,size:131072,page:256,block:8192},{start:438272,end:503808,size:65536,page:256,block:8192},{start:471040,end:503808,size:32768,page:256,block:8192}]:[]}var si;function ai(t){return 1!==t.type?si.UNKNOWN:129===t.subtype?si.FATFS:si.UNKNOWN}function ni(t,e){if(t.length<512)return si.UNKNOWN;const i=(null==e?void 0:e.toUpperCase().includes("ESP8266"))?We:Je;for(const e of i)for(let i=0;i<2;i++){const s=i*e;if(s+20>t.length)continue;const a=s+8;if(a+8<=t.length){if("littlefs"===String.fromCharCode(t[a],t[a+1],t[a+2],t[a+3],t[a+4],t[a+5],t[a+6],t[a+7])){const e=s+16,i=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;if(0!==i&&i>>>0!=4294967295)return si.LITTLEFS}}}const s=[0,4096];for(const e of s){if(t.length<e+512)continue;if(43605===(t[e+510]|t[e+511]<<8)){const i=t.length>=e+62?String.fromCharCode(t[e+54],t[e+55],t[e+56],t[e+57],t[e+58]):"",s=t.length>=e+90?String.fromCharCode(t[e+82],t[e+83],t[e+84],t[e+85],t[e+86]):"";if(i.startsWith("FAT")||s.startsWith("FAT"))return si.FATFS}}if(t.length>=4){if(538182953===(t[0]|t[1]<<8|t[2]<<16|t[3]<<24))return si.SPIFFS}return Qe(t)?si.SPIFFS:si.UNKNOWN}function ri(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case si.FATFS:return 4096;case si.LITTLEFS:default:return i?Ke:4096}}function oi(t,e){const i=null==e?void 0:e.toUpperCase().includes("ESP8266");switch(t){case si.FATFS:return Ve;case si.LITTLEFS:return i?We:Je;default:return i?We:[4096,2048,1024,512]}}!function(t){t.UNKNOWN="unknown",t.LITTLEFS="littlefs",t.FATFS="fatfs",t.SPIFFS="spiffs"}(si||(si={}));const hi={0:"app",1:"data"},li={0:"factory",16:"ota_0",17:"ota_1",18:"ota_2",19:"ota_3",20:"ota_4",21:"ota_5",22:"ota_6",23:"ota_7",24:"ota_8",25:"ota_9",26:"ota_10",27:"ota_11",28:"ota_12",29:"ota_13",30:"ota_14",31:"ota_15",32:"test"},ci={0:"ota",1:"phy",2:"nvs",3:"coredump",4:"nvs_keys",5:"efuse",128:"esphttpd",129:"fat",130:"spiffs",131:"littlefs"};function di(t){if(t.length<32)return null;if(20650!==(65535&(t[0]|t[1]<<8)))return null;const e=t[2],i=t[3],s=t[4]|t[5]<<8|t[6]<<16|t[7]<<24,a=t[8]|t[9]<<8|t[10]<<16|t[11]<<24;let n="";for(let e=12;e<28&&0!==t[e];e++)n+=String.fromCharCode(t[e]);const r=t[28]|t[29]<<8|t[30]<<16|t[31]<<24,o=hi[e]||`unknown(0x${e.toString(16)})`;let h="";return h=0===e?li[i]||`unknown(0x${i.toString(16)})`:1===e?ci[i]||`unknown(0x${i.toString(16)})`:`0x${i.toString(16)}`,{name:n,type:e,subtype:i,offset:s,size:a,flags:r,typeName:o,subtypeName:h}}function ui(t){const e=[];for(let i=0;i<t.length;i+=32){const s=di(t.slice(i,i+32));if(null===s)break;e.push(s)}return e}function fi(){return 32768}function gi(t){return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(2)} KB`:`${(t/1048576).toFixed(2)} MB`}class _i{constructor(t){var e,i,s,a,n,r,o,h,l,c,d,u;if(t.blockSize%t.pageSize!==0)throw new Error("block size should be a multiple of page size");this.pageSize=t.pageSize,this.blockSize=t.blockSize,this.objIdLen=null!==(e=t.objIdLen)&&void 0!==e?e:2,this.spanIxLen=null!==(i=t.spanIxLen)&&void 0!==i?i:2,this.packed=null===(s=t.packed)||void 0===s||s,this.aligned=null===(a=t.aligned)||void 0===a||a,this.objNameLen=null!==(n=t.objNameLen)&&void 0!==n?n:32,this.metaLen=null!==(r=t.metaLen)&&void 0!==r?r:4,this.pageIxLen=null!==(o=t.pageIxLen)&&void 0!==o?o:2,this.blockIxLen=null!==(h=t.blockIxLen)&&void 0!==h?h:2,this.endianness=null!==(l=t.endianness)&&void 0!==l?l:"little",this.useMagic=null===(c=t.useMagic)||void 0===c||c,this.useMagicLen=null===(d=t.useMagicLen)||void 0===d||d,this.alignedObjIxTables=null!==(u=t.alignedObjIxTables)&&void 0!==u&&u,this.PAGES_PER_BLOCK=Math.floor(this.blockSize/this.pageSize),this.OBJ_LU_PAGES_PER_BLOCK=Math.ceil(this.blockSize/this.pageSize*this.objIdLen/this.pageSize),this.OBJ_USABLE_PAGES_PER_BLOCK=this.PAGES_PER_BLOCK-this.OBJ_LU_PAGES_PER_BLOCK,this.OBJ_LU_PAGES_OBJ_IDS_LIM=Math.floor(this.pageSize/this.objIdLen),this.OBJ_DATA_PAGE_HEADER_LEN=this.objIdLen+this.spanIxLen+1;const f=4-(this.OBJ_DATA_PAGE_HEADER_LEN%4==0?4:this.OBJ_DATA_PAGE_HEADER_LEN%4);this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED=this.OBJ_DATA_PAGE_HEADER_LEN+f,this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD=f,this.OBJ_DATA_PAGE_CONTENT_LEN=this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN=this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED+4+1+this.objNameLen+this.metaLen,this.alignedObjIxTables?(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN+2-1&-2,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED-this.OBJ_INDEX_PAGES_HEADER_LEN):(this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED=this.OBJ_INDEX_PAGES_HEADER_LEN,this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD=0),this.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM=Math.floor((this.pageSize-this.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED)/this.blockIxLen),this.OBJ_INDEX_PAGES_OBJ_IDS_LIM=Math.floor((this.pageSize-this.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED)/this.blockIxLen)}}class pi extends Error{constructor(t="SPIFFS is full"){super(t),this.name="SpiffsFullError"}}class bi{constructor(t,e){this.buildConfig=e,this.bix=t}pack(t,...e){const i=new ArrayBuffer(this.calcSize(t)),s=new DataView(i);let a=0;for(let i=0;i<t.length;i++){const n=t[i],r=e[i];switch(n){case"B":s.setUint8(a,r),a+=1;break;case"H":"little"===this.buildConfig.endianness?s.setUint16(a,r,!0):s.setUint16(a,r,!1),a+=2;break;case"I":"little"===this.buildConfig.endianness?s.setUint32(a,r,!0):s.setUint32(a,r,!1),a+=4}}return new Uint8Array(i)}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let n=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(n)),n+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(n,!0):s.getUint16(n,!1)),n+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(n,!0):s.getUint32(n,!1)),n+=4}return a}calcSize(t){let e=0;for(const i of t)switch(i){case"B":e+=1;break;case"H":e+=2;break;case"I":e+=4}return e}}class mi extends bi{constructor(t,e){super(0,e),this.objId=t}getObjId(){return this.objId}}class wi extends bi{constructor(t,e){super(t,e),this.objIdsLimit=this.buildConfig.OBJ_LU_PAGES_OBJ_IDS_LIM,this.objIds=[]}calcMagic(t){let e=538182953^this.buildConfig.pageSize;this.buildConfig.useMagicLen&&(e^=t-this.bix);return e&(1<<8*this.buildConfig.objIdLen)-1}registerPage(t){if(this.objIdsLimit<=0)throw new pi;const e=t instanceof yi?"index":"data";this.objIds.push([t.getObjId(),e]),this.objIdsLimit--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);let e=0;for(const[i,s]of this.objIds){let a=i;"index"===s&&(a^=1<<8*this.buildConfig.objIdLen-1);const n=this.pack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",a);t.set(n,e),e+=n.length}return t}magicfy(t){const e=this.objIdsLimit,i=(1<<8*this.buildConfig.objIdLen)-1;if(e>=2)for(let s=0;s<e;s++){if(s===e-2){this.objIds.push([this.calcMagic(t),"data"]);break}this.objIds.push([i,"data"]),this.objIdsLimit--}}}class yi extends mi{constructor(t,e,i,s,a){super(t,a),this.spanIx=e,this.name=s,this.size=i,0===this.spanIx?this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_HEAD_LIM:this.pagesLim=this.buildConfig.OBJ_INDEX_PAGES_OBJ_IDS_LIM,this.pages=[]}registerPage(t){if(this.pagesLim<=0)throw new pi;this.pages.push(t.offset),this.pagesLim--}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=this.objId^1<<8*this.buildConfig.objIdLen-1,i=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B";let s=0;const a=this.pack(i,e,this.spanIx,248);if(t.set(a,s),s+=a.length,s+=this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD,0===this.spanIx){const e=this.pack("IB",this.size,1);t.set(e,s),s+=e.length;const i=(new TextEncoder).encode(this.name),a=Math.min(i.length,this.buildConfig.objNameLen);t.set(i.slice(0,a),s);for(let e=a;e<this.buildConfig.objNameLen;e++)t[s+e]=0;s+=this.buildConfig.objNameLen+this.buildConfig.metaLen+this.buildConfig.OBJ_INDEX_PAGES_HEADER_LEN_ALIGNED_PAD}for(const e of this.pages){const i=Math.floor(e/this.buildConfig.pageSize),a=this.pack(1===this.buildConfig.pageIxLen?"B":2===this.buildConfig.pageIxLen?"H":"I",i);t.set(a,s),s+=a.length}return t}}class Si extends mi{constructor(t,e,i,s,a){super(e,a),this.offset=t,this.spanIx=i,this.contents=s}toBinary(){const t=new Uint8Array(this.buildConfig.pageSize);t.fill(255);const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.pack(e,this.objId,this.spanIx,252);return t.set(i,0),t.set(this.contents,i.length),t}}class Ii{constructor(t,e){this.buildConfig=e,this.offset=t*this.buildConfig.blockSize,this.remainingPages=this.buildConfig.OBJ_USABLE_PAGES_PER_BLOCK,this.pages=[],this.bix=t,this.luPages=[];for(let t=0;t<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;t++){const t=new wi(this.bix,this.buildConfig);this.luPages.push(t)}this.pages.push(...this.luPages),this.luPageIter=this.luPages[Symbol.iterator](),this.luPage=this.luPageIter.next().value||null,this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}reset(){this.curObjIndexSpanIx=0,this.curObjDataSpanIx=0,this.curObjId=0,this.curObjIdxPage=null}registerPage(t){if(t instanceof Si){if(!this.curObjIdxPage)throw new Error("No current object index page");this.curObjIdxPage.registerPage(t)}try{if(!this.luPage)throw new pi;this.luPage.registerPage(t)}catch(e){if(!(e instanceof pi))throw e;{const e=this.luPageIter.next();if(e.done)throw new Error("Invalid attempt to add page to a block when there is no more space in lookup");this.luPage=e.value,this.luPage.registerPage(t)}}this.pages.push(t)}beginObj(t,e,i,s=0,a=0){if(this.remainingPages<=0)throw new pi;this.reset(),this.curObjId=t,this.curObjIndexSpanIx=s,this.curObjDataSpanIx=a;const n=new yi(t,this.curObjIndexSpanIx,e,i,this.buildConfig);this.registerPage(n),this.curObjIdxPage=n,this.remainingPages--,this.curObjIndexSpanIx++}updateObj(t){if(this.remainingPages<=0)throw new pi;const e=new Si(this.offset+this.pages.length*this.buildConfig.pageSize,this.curObjId,this.curObjDataSpanIx,t,this.buildConfig);this.registerPage(e),this.curObjDataSpanIx++,this.remainingPages--}endObj(){this.reset()}isFull(){return this.remainingPages<=0}toBinary(t){const e=new Uint8Array(this.buildConfig.blockSize);e.fill(255);let i=0;if(this.buildConfig.useMagic)for(let s=0;s<this.pages.length;s++){const a=this.pages[s];s===this.buildConfig.OBJ_LU_PAGES_PER_BLOCK-1&&a instanceof wi&&a.magicfy(t);const n=a.toBinary();e.set(n,i),i+=n.length}else for(const t of this.pages){const s=t.toBinary();e.set(s,i),i+=s.length}return e}get currentObjIndexSpanIx(){return this.curObjIndexSpanIx}get currentObjDataSpanIx(){return this.curObjDataSpanIx}get currentObjId(){return this.curObjId}get currentObjIdxPage(){return this.curObjIdxPage}set currentObjId(t){this.curObjId=t}set currentObjIdxPage(t){this.curObjIdxPage=t}set currentObjDataSpanIx(t){this.curObjDataSpanIx=t}set currentObjIndexSpanIx(t){this.curObjIndexSpanIx=t}}class Ei{constructor(t,e){if(t%e.blockSize!==0)throw new Error("image size should be a multiple of block size");this.imgSize=t,this.buildConfig=e,this.blocks=[],this.blocksLim=Math.floor(this.imgSize/this.buildConfig.blockSize),this.remainingBlocks=this.blocksLim,this.curObjId=1}createBlock(){if(this.isFull())throw new pi("the image size has been exceeded");const t=new Ii(this.blocks.length,this.buildConfig);return this.blocks.push(t),this.remainingBlocks--,t}isFull(){return this.remainingBlocks<=0}createFile(t,e){if(t.length>this.buildConfig.objNameLen)throw new Error(`object name '${t}' too long`);const i=t;let s=0;try{this.blocks[this.blocks.length-1].beginObj(this.curObjId,e.length,i)}catch{this.createBlock().beginObj(this.curObjId,e.length,i)}for(;s<e.length;){const t=Math.min(this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN,e.length-s),a=e.slice(s,s+t);try{const t=this.blocks[this.blocks.length-1];try{t.updateObj(a)}catch(s){if(s instanceof pi){if(t.isFull())throw s;t.beginObj(this.curObjId,e.length,i,t.currentObjIndexSpanIx,t.currentObjDataSpanIx);continue}throw s}}catch(t){if(t instanceof pi){const t=this.blocks[this.blocks.length-1],e=this.createBlock();e.currentObjId=t.currentObjId,e.currentObjIdxPage=t.currentObjIdxPage,e.currentObjDataSpanIx=t.currentObjDataSpanIx,e.currentObjIndexSpanIx=t.currentObjIndexSpanIx;continue}throw t}s+=t}this.blocks[this.blocks.length-1].endObj(),this.curObjId++}toBinary(){const t=[];for(const e of this.blocks)t.push(e.toBinary(this.blocksLim));let e=this.blocks.length,i=this.remainingBlocks;if(this.buildConfig.useMagic)for(;i>0;){const s=new Ii(e,this.buildConfig);t.push(s.toBinary(this.blocksLim)),i--,e++}else{const e=this.imgSize-t.length*this.buildConfig.blockSize;if(e>0){const i=new Uint8Array(e);i.fill(255),t.push(i)}}const s=t.reduce((t,e)=>t+e.length,0),a=new Uint8Array(s);let n=0;for(const e of t)a.set(e,n),n+=e.length;return a}listFiles(){throw new Error("listFiles requires fromBinary to be called first")}readFile(){throw new Error("readFile requires fromBinary to be called first")}deleteFile(){throw new Error("deleteFile not yet implemented - requires filesystem recreation")}}class Bi{constructor(t,e){this.imageData=t,this.buildConfig=e,this.filesMap=new Map}unpack(t,e,i=0){const s=new DataView(e.buffer,e.byteOffset+i),a=[];let n=0;for(const e of t)switch(e){case"B":a.push(s.getUint8(n)),n+=1;break;case"H":a.push("little"===this.buildConfig.endianness?s.getUint16(n,!0):s.getUint16(n,!1)),n+=2;break;case"I":a.push("little"===this.buildConfig.endianness?s.getUint32(n,!0):s.getUint32(n,!1)),n+=4}return a}parse(){const t=Math.floor(this.imageData.length/this.buildConfig.blockSize);for(let e=0;e<t;e++){const t=e*this.buildConfig.blockSize,i=this.imageData.slice(t,t+this.buildConfig.blockSize);this.parseBlock(i)}}parseBlock(t){for(let e=0;e<this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);for(let t=0;t<s.length&&!(t+this.buildConfig.objIdLen>s.length);t+=this.buildConfig.objIdLen){const e=s.slice(t,t+this.buildConfig.objIdLen),[i]=this.unpack(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I",e);if(i===(1<<8*this.buildConfig.objIdLen)-1)continue;const a=!!(i&1<<8*this.buildConfig.objIdLen-1),n=i&~(1<<8*this.buildConfig.objIdLen-1);a&&!this.filesMap.has(n)&&this.filesMap.set(n,{name:null,size:0,dataPages:[]})}}for(let e=this.buildConfig.OBJ_LU_PAGES_PER_BLOCK;e<this.buildConfig.PAGES_PER_BLOCK;e++){const i=e*this.buildConfig.pageSize,s=t.slice(i,i+this.buildConfig.pageSize);this.parsePage(s)}}parsePage(t){const e=(1===this.buildConfig.objIdLen?"B":2===this.buildConfig.objIdLen?"H":"I")+(1===this.buildConfig.spanIxLen?"B":2===this.buildConfig.spanIxLen?"H":"I")+"B",i=this.buildConfig.objIdLen+this.buildConfig.spanIxLen+1;if(t.length<i)return;const[s,a,n]=this.unpack(e,t);if(s===(1<<8*this.buildConfig.objIdLen)-1)return;const r=!!(s&1<<8*this.buildConfig.objIdLen-1),o=s&~(1<<8*this.buildConfig.objIdLen-1);if(r&&248===n)this.filesMap.has(o)||this.filesMap.set(o,{name:null,size:0,dataPages:[]}),0===a&&this.parseIndexPage(t,i,o);else if(!r&&252===n&&this.filesMap.has(o)){const e=i,s=t.slice(e,e+this.buildConfig.OBJ_DATA_PAGE_CONTENT_LEN);this.filesMap.get(o).dataPages.push([a,s])}}parseIndexPage(t,e,i){let s=e+this.buildConfig.OBJ_DATA_PAGE_HEADER_LEN_ALIGNED_PAD;if(s+5<=t.length){const[e]=this.unpack("IB",t,s);s+=5;const a=s+this.buildConfig.objNameLen;if(a<=t.length){const n=t.slice(s,a),r=n.indexOf(0),o=-1!==r?n.slice(0,r):n,h=(new TextDecoder).decode(o),l=this.filesMap.get(i);l.name=h,l.size=e}}}listFiles(){const t=[];for(const[,e]of this.filesMap){if(null===e.name)continue;e.dataPages.sort((t,e)=>t[0]-e[0]);const i=[];let s=0;for(const[,t]of e.dataPages){const a=e.size-s;if(a<=0)break;const n=Math.min(t.length,a);i.push(t.slice(0,n)),s+=n}const a=new Uint8Array(s);let n=0;for(const t of i)a.set(t,n),n+=t.length;t.push({name:e.name,size:e.size,data:a})}return t}readFile(t){const e=this.listFiles().find(e=>e.name===t||e.name==="/"+t);return e?e.data:null}}const ki={pageSize:256,blockSize:4096,objNameLen:32,metaLen:4,useMagic:!0,useMagicLen:!0,alignedObjIxTables:!1},Oi=async t=>{const e=await navigator.serial.requestPort();return await e.open({baudRate:r}),t.log("Connected successfully."),new Me(e,t)};export{c as CHIP_FAMILY_ESP32,f as CHIP_FAMILY_ESP32C2,g as CHIP_FAMILY_ESP32C3,_ as CHIP_FAMILY_ESP32C5,p as CHIP_FAMILY_ESP32C6,b as CHIP_FAMILY_ESP32C61,m as CHIP_FAMILY_ESP32H2,y as CHIP_FAMILY_ESP32H21,w as CHIP_FAMILY_ESP32H4,S as CHIP_FAMILY_ESP32P4,d as CHIP_FAMILY_ESP32S2,u as CHIP_FAMILY_ESP32S3,I as CHIP_FAMILY_ESP32S31,l as CHIP_FAMILY_ESP8266,ki as DEFAULT_SPIFFS_CONFIG,Ke as ESP8266_LITTLEFS_BLOCK_SIZE,We as ESP8266_LITTLEFS_BLOCK_SIZE_CANDIDATES,Xe as ESP8266_LITTLEFS_PAGE_SIZE,qe as ESP8266_SPIFFS_BLOCK_SIZE,Ye as ESP8266_SPIFFS_PAGE_SIZE,Me as ESPLoader,Ve as FATFS_BLOCK_SIZE_CANDIDATES,Ze as FATFS_DEFAULT_BLOCK_SIZE,si as FilesystemType,Je as LITTLEFS_BLOCK_SIZE_CANDIDATES,Ge as LITTLEFS_DEFAULT_BLOCK_SIZE,_i as SpiffsBuildConfig,Ei as SpiffsFS,Bi as SpiffsReader,Oi as connect,ni as detectFilesystemFromImage,ai as detectFilesystemType,gi as formatSize,oi as getBlockSizeCandidates,ri as getDefaultBlockSize,ii as getESP8266FilesystemLayout,fi as getPartitionTableOffset,ui as parsePartitionTable,ti as scanESP8266Filesystem};