import{f as e,A as t,_ as r,p as i,L as a,b as s,c as o,g as n,d as c,e as l}from"./c.1ff2516f.js";import{C as h,b as d,c as g,d as m,t as p,e as u,f,p as y,E as w,u as _,D as b,M as I,R as $,g as k,h as v,i as S,j as F,k as B,l as C,S as R,n as z,o as x,F as D,q as E,r as L,v as T,w as U,x as A,y as P,z as M,A as W,B as O,G as j,H as N,I as q,J as H,K as V,L as G,N as J,O as K,P as Q,Q as X,T as Y,U as Z,V as ee,W as te,X as re,Y as ie,Z as ae,_ as se,$ as oe,a0 as ne,a1 as ce,a2 as le}from"./c.8d16680b.js";import{f as he,s as de}from"./index-9fb59a6d.js";function ge(e,t,r){if(void 0!==t)return function(e,t,r){const i=e.constructor;if(!r){const e=`__${t}`;if(!(r=i.getPropertyDescriptor(t,e)))throw new Error("@ariaProperty must be used after a @property decorator")}const a=r;let s="";if(!a.set)throw new Error(`@ariaProperty requires a setter for ${t}`);const o={configurable:!0,enumerable:!0,set(e){if(""===s){const e=i.getPropertyOptions(t);s=e.attribute}this.hasAttribute(s)&&this.removeAttribute(s),a.set.call(this,e)}};return a.get&&(o.get=function(){return a.get.call(this)}),o}(e,t,r);throw new Error("@ariaProperty only supports TypeScript Decorators")}const me=new WeakMap,pe=e((e=>r=>{const i=me.get(r);if(void 0===e&&r instanceof t){if(void 0!==i||!me.has(r)){const e=r.committer.name;r.committer.element.removeAttribute(e)}}else e!==i&&r.setValue(e);me.set(r,e)}));class ue extends a{constructor(){super(...arguments),this.indeterminate=!1,this.progress=0,this.density=0,this.closed=!1}open(){this.closed=!1}close(){this.closed=!0}render(){const e={"mdc-circular-progress--closed":this.closed,"mdc-circular-progress--indeterminate":this.indeterminate},t=48+4*this.density,r={width:`${t}px`,height:`${t}px`};return s`
      <div
        class="mdc-circular-progress ${o(e)}"
        style="${n(r)}"
        role="progressbar"
        aria-label="${pe(this.ariaLabel)}"
        aria-valuemin="0"
        aria-valuemax="1"
        aria-valuenow="${pe(this.indeterminate?void 0:this.progress)}">
        ${this.renderDeterminateContainer()}
        ${this.renderIndeterminateContainer()}
      </div>`}renderDeterminateContainer(){const e=48+4*this.density,t=e/2,r=this.density>=-3?18+11*this.density/6:12.5+5*(this.density+3)/4,i=6.2831852*r,a=(1-this.progress)*i,o=this.density>=-3?4+this.density*(1/3):3+(this.density+3)*(1/6);return s`
      <div class="mdc-circular-progress__determinate-container">
        <svg class="mdc-circular-progress__determinate-circle-graphic"
             viewBox="0 0 ${e} ${e}">
          <circle class="mdc-circular-progress__determinate-track"
                  cx="${t}" cy="${t}" r="${r}"
                  stroke-width="${o}"></circle>
          <circle class="mdc-circular-progress__determinate-circle"
                  cx="${t}" cy="${t}" r="${r}"
                  stroke-dasharray="${6.2831852*r}"
                  stroke-dashoffset="${a}"
                  stroke-width="${o}"></circle>
        </svg>
      </div>`}renderIndeterminateContainer(){return s`
      <div class="mdc-circular-progress__indeterminate-container">
        <div class="mdc-circular-progress__spinner-layer">
          ${this.renderIndeterminateSpinnerLayer()}
        </div>
      </div>`}renderIndeterminateSpinnerLayer(){const e=48+4*this.density,t=e/2,r=this.density>=-3?18+11*this.density/6:12.5+5*(this.density+3)/4,i=6.2831852*r,a=.5*i,o=this.density>=-3?4+this.density*(1/3):3+(this.density+3)*(1/6);return s`
        <div class="mdc-circular-progress__circle-clipper mdc-circular-progress__circle-left">
          <svg class="mdc-circular-progress__indeterminate-circle-graphic"
               viewBox="0 0 ${e} ${e}">
            <circle cx="${t}" cy="${t}" r="${r}"
                    stroke-dasharray="${i}"
                    stroke-dashoffset="${a}"
                    stroke-width="${o}"></circle>
          </svg>
        </div>
        <div class="mdc-circular-progress__gap-patch">
          <svg class="mdc-circular-progress__indeterminate-circle-graphic"
               viewBox="0 0 ${e} ${e}">
            <circle cx="${t}" cy="${t}" r="${r}"
                    stroke-dasharray="${i}"
                    stroke-dashoffset="${a}"
                    stroke-width="${.8*o}"></circle>
          </svg>
        </div>
        <div class="mdc-circular-progress__circle-clipper mdc-circular-progress__circle-right">
          <svg class="mdc-circular-progress__indeterminate-circle-graphic"
               viewBox="0 0 ${e} ${e}">
            <circle cx="${t}" cy="${t}" r="${r}"
                    stroke-dasharray="${i}"
                    stroke-dashoffset="${a}"
                    stroke-width="${o}"></circle>
          </svg>
        </div>`}update(e){super.update(e),e.has("progress")&&(this.progress>1&&(this.progress=1),this.progress<0&&(this.progress=0))}}r([i({type:Boolean,reflect:!0})],ue.prototype,"indeterminate",void 0),r([i({type:Number,reflect:!0})],ue.prototype,"progress",void 0),r([i({type:Number,reflect:!0})],ue.prototype,"density",void 0),r([i({type:Boolean,reflect:!0})],ue.prototype,"closed",void 0),r([ge,i({type:String,attribute:"aria-label"})],ue.prototype,"ariaLabel",void 0);const fe=c`.mdc-circular-progress__determinate-circle,.mdc-circular-progress__indeterminate-circle-graphic{stroke:#6200ee;stroke:var(--mdc-theme-primary, #6200ee)}.mdc-circular-progress__determinate-track{stroke:transparent}@keyframes mdc-circular-progress-container-rotate{to{transform:rotate(360deg)}}@keyframes mdc-circular-progress-spinner-layer-rotate{12.5%{transform:rotate(135deg)}25%{transform:rotate(270deg)}37.5%{transform:rotate(405deg)}50%{transform:rotate(540deg)}62.5%{transform:rotate(675deg)}75%{transform:rotate(810deg)}87.5%{transform:rotate(945deg)}100%{transform:rotate(1080deg)}}@keyframes mdc-circular-progress-color-1-fade-in-out{from{opacity:.99}25%{opacity:.99}26%{opacity:0}89%{opacity:0}90%{opacity:.99}to{opacity:.99}}@keyframes mdc-circular-progress-color-2-fade-in-out{from{opacity:0}15%{opacity:0}25%{opacity:.99}50%{opacity:.99}51%{opacity:0}to{opacity:0}}@keyframes mdc-circular-progress-color-3-fade-in-out{from{opacity:0}40%{opacity:0}50%{opacity:.99}75%{opacity:.99}76%{opacity:0}to{opacity:0}}@keyframes mdc-circular-progress-color-4-fade-in-out{from{opacity:0}65%{opacity:0}75%{opacity:.99}90%{opacity:.99}to{opacity:0}}@keyframes mdc-circular-progress-left-spin{from{transform:rotate(265deg)}50%{transform:rotate(130deg)}to{transform:rotate(265deg)}}@keyframes mdc-circular-progress-right-spin{from{transform:rotate(-265deg)}50%{transform:rotate(-130deg)}to{transform:rotate(-265deg)}}.mdc-circular-progress{display:inline-flex;position:relative;direction:ltr;line-height:0;transition:opacity 250ms 0ms cubic-bezier(0.4, 0, 0.6, 1)}.mdc-circular-progress__determinate-container,.mdc-circular-progress__indeterminate-circle-graphic,.mdc-circular-progress__indeterminate-container,.mdc-circular-progress__spinner-layer{position:absolute;width:100%;height:100%}.mdc-circular-progress__determinate-container{transform:rotate(-90deg)}.mdc-circular-progress__indeterminate-container{font-size:0;letter-spacing:0;white-space:nowrap;opacity:0}.mdc-circular-progress__determinate-circle-graphic,.mdc-circular-progress__indeterminate-circle-graphic{fill:transparent}.mdc-circular-progress__determinate-circle{transition:stroke-dashoffset 500ms 0ms cubic-bezier(0, 0, 0.2, 1)}.mdc-circular-progress__gap-patch{position:absolute;top:0;left:47.5%;box-sizing:border-box;width:5%;height:100%;overflow:hidden}.mdc-circular-progress__gap-patch .mdc-circular-progress__indeterminate-circle-graphic{left:-900%;width:2000%;transform:rotate(180deg)}.mdc-circular-progress__circle-clipper{display:inline-flex;position:relative;width:50%;height:100%;overflow:hidden}.mdc-circular-progress__circle-clipper .mdc-circular-progress__indeterminate-circle-graphic{width:200%}.mdc-circular-progress__circle-right .mdc-circular-progress__indeterminate-circle-graphic{left:-100%}.mdc-circular-progress--indeterminate .mdc-circular-progress__determinate-container{opacity:0}.mdc-circular-progress--indeterminate .mdc-circular-progress__indeterminate-container{opacity:1}.mdc-circular-progress--indeterminate .mdc-circular-progress__indeterminate-container{animation:mdc-circular-progress-container-rotate 1568.2352941176ms linear infinite}.mdc-circular-progress--indeterminate .mdc-circular-progress__spinner-layer{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-1{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-1-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-2{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-2-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-3{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-3-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__color-4{animation:mdc-circular-progress-spinner-layer-rotate 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both,mdc-circular-progress-color-4-fade-in-out 5332ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__circle-left .mdc-circular-progress__indeterminate-circle-graphic{animation:mdc-circular-progress-left-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--indeterminate .mdc-circular-progress__circle-right .mdc-circular-progress__indeterminate-circle-graphic{animation:mdc-circular-progress-right-spin 1333ms cubic-bezier(0.4, 0, 0.2, 1) infinite both}.mdc-circular-progress--closed{opacity:0}:host{display:inline-flex}.mdc-circular-progress__determinate-track{stroke:transparent;stroke:var(--mdc-circular-progress-track-color, transparent)}`;let ye=class extends ue{};ye.styles=[fe],ye=r([l("mwc-circular-progress")],ye);const we=async e=>{let t;return e==h?t=await import("./c.4302b905.js"):e==d?t=await import("./c.987f3e2b.js"):e==g?t=await import("./c.78993cb6.js"):e==m&&(t=await import("./c.4cda624e.js")),{...t,text:p(atob(t.text)),data:p(atob(t.data))}};class _e extends EventTarget{constructor(e,t,r){super(),this.port=e,this.logger=t,this._parent=r,this.chipName=null,this._efuses=new Array(4).fill(0),this._flashsize=4194304,this.debug=!1,this.IS_STUB=!1,this.connected=!0,this.stopReadLoop=!1,this.flashSize=null}get _inputBuffer(){return this._parent?this._parent._inputBuffer:this.__inputBuffer}async initialize(){await this.hardReset(!0),this._parent||(this.__inputBuffer=[],this.readLoop()),await this.sync();let e,t=await this.readRegister(u),r=re[t];if(void 0===r)throw new Error(`Unknown Chip: Hex: ${f(t,8).toLowerCase()} Number: ${t}`);this.chipName=r.name,this.chipFamily=r.family,this.chipFamily==g?e=1072693328:(this.chipFamily==h||this.chipFamily==d)&&(e=1610719232);for(let t=0;t<4;t++)this._efuses[t]=await this.readRegister(e+4*t);this.logger.log(`Chip type ${this.chipName}`)}async readLoop(){this.logger.debug("Starting read loop"),this._reader=this.port.readable.getReader();try{for(;!this.stopReadLoop;){const{value:e,done:t}=await this._reader.read();if(t){this._reader.releaseLock();break}e&&0!==e.length&&this._inputBuffer.push(...Array.from(e))}}catch(e){console.error("Read loop got disconnected"),this.connected=!1,this.dispatchEvent(new Event("disconnect"))}this.logger.debug("Finished read loop")}async hardReset(e=!1){this.logger.log("Try hard reset."),await this.port.setSignals({dataTerminalReady:!1,requestToSend:!0}),await this.port.setSignals({dataTerminalReady:e,requestToSend:!1}),await new Promise((e=>setTimeout(e,1e3)))}macAddr(){let e,t=new Array(6).fill(0),r=this._efuses[0],i=this._efuses[1],a=this._efuses[2],s=this._efuses[3];if(this.chipFamily==g){if(0!=s)e=[s>>16&255,s>>8&255,255&s];else if(0==(i>>16&255))e=[24,254,52];else{if(1!=(i>>16&255))throw new Error("Couldnt determine OUI");e=[172,208,116]}t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=i>>8&255,t[4]=255&i,t[5]=r>>24&255}else if(this.chipFamily==h)t[0]=a>>8&255,t[1]=255&a,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i;else{if(this.chipFamily!=d)throw new Error("Unknown chip family");t[0]=a>>8&255,t[1]=255&a,t[2]=i>>24&255,t[3]=i>>16&255,t[4]=i>>8&255,t[5]=255&i}return t}async readRegister(e){this.debug&&this.logger.debug("Reading Register",e);let t=y("I",e),r=(await this.checkCommand(w,t))[0];return _("I",r)[0]}async checkCommand(e,t,r=0,i=b){i=Math.min(i,I),await this.sendCommand(e,t,r);let[a,s]=await this.getResponse(e,i);if(null===s)throw new Error("Didn't get enough status bytes");let o=0;if(this.IS_STUB||this.chipFamily==g?o=2:[h,d].includes(this.chipFamily)?o=4:[2,4].includes(s.length)&&(o=s.length),s.length<o)throw new Error("Didn't get enough status bytes");let n=s.slice(-o,s.length);if(s=s.slice(0,-o),this.debug&&(this.logger.debug("status",n),this.logger.debug("value",a),this.logger.debug("data",s)),1==n[0])throw n[1]==$?new Error("Invalid (unsupported) command "+f(e)):new Error("Command failure error code "+f(n[1]));return[a,s]}async sendCommand(e,t,r=0){this._inputBuffer.length=0;let i=[192,0];i.push(e),i=i.concat(y("H",t.length)),i=i.concat(k(y("I",r))),i=i.concat(k(t)),i.push(192),this.debug&&this.logger.debug("Writing "+i.length+" byte"+(1==i.length?"":"s")+":",i),await this.writeToStream(i)}async getResponse(e,t=b){let r=[],i=0,a=!1,s=Date.now();for(;Date.now()-s<t;){if(this._inputBuffer.length>0){let e=this._inputBuffer.shift();219==e?a=!0:a?(221==e?r.push(220):220==e?r.push(192):r=r.concat([219,e]),a=!1):r.push(e)}else await v(10);if(r.length>0&&192!=r[0]&&r.shift(),r.length>1&&1!=r[1]&&r.shift(),r.length>2&&r[2]!=e&&r.shift(),r.length>4&&(i=r[3]+(r[4]<<8)),r.length==i+10)break}if(r.length!=i+10)return this.logger.log("Timed out after "+t+" milliseconds"),[null,null];this.debug&&this.logger.debug("Reading "+r.length+" byte"+(1==r.length?"":"s")+":",r);let o=r.slice(5,9),n=r.slice(9,-1);return this.debug&&this.logger.debug("value:",o,"data:",n),[o,n]}async readBuffer(e=b){let t=[],r=!1,i=Date.now();for(;Date.now()-i<e;){if(this._inputBuffer.length>0){let e=this._inputBuffer.shift();219==e?r=!0:r?(221==e?t.push(220):220==e?t.push(192):t=t.concat([219,e]),r=!1):t.push(e)}else await v(10);if(t.length>0&&192!=t[0]&&t.shift(),t.length>1&&192==t[t.length-1])break}if(t.length<2)return this.logger.log("Timed out after "+e+" milliseconds"),null;this.debug&&this.logger.debug("Reading "+t.length+" byte"+(1==t.length?"":"s")+":",t);let a=t.slice(1,-1);return this.debug&&this.logger.debug("data:",a),a}checksum(e,t=S){for(let r of e)t^=r;return t}async setBaudrate(e){if(this.chipFamily==g)throw new Error("Changing baud rate is not supported on the ESP8266");this.logger.log("Attempting to change baud rate to "+e+"...");try{let t=y("<II",e,this.IS_STUB?F:0);await this.checkCommand(B,t)}catch(t){throw console.error(t),new Error(`Unable to change the baud rate to ${e}: No response from set baud rate command.`)}this._parent?await this._parent.reconfigurePort(e):await this.reconfigurePort(e)}async reconfigurePort(e){var t,r;try{this.stopReadLoop=!0,await(null===(t=this._reader)||void 0===t?void 0:t.cancel()),null===(r=this._reader)||void 0===r||r.releaseLock(),await this.port.close(),await this.port.open({baudRate:e}),this.stopReadLoop=!1,this.readLoop(),this.logger.log(`Changed baud rate to ${e}`)}catch(t){throw console.error(t),new Error(`Unable to change the baud rate to ${e}: ${t}`)}}async sync(){for(let e=0;e<5;e++){if(await this._sync())return await v(100),!0;await v(100)}throw new Error("Couldn't sync to ESP. Try resetting.")}async _sync(){await this.sendCommand(C,R);for(let e=0;e<8;e++){let[e,t]=await this.getResponse(C,z);if(null!==t&&(t.length>1&&0==t[0]&&0==t[1]))return!0}return!1}getFlashWriteSize(){return this.IS_STUB?x:D}async flashData(e,t,r=0,i=!1){this.updateImageFlashParams(r,e);let a,s=e.byteLength,o=0;i?(a=E(new Uint8Array(e),{level:9}).buffer,o=a.byteLength,this.logger.log(`Writing data with filesize: ${s}. Compressed Size: ${o}`),await this.flashDeflBegin(s,o,r)):(this.logger.log(`Writing data with filesize: ${s}`),a=e,await this.flashBegin(s,r));let n=[],c=0,l=0,h=0,d=Date.now(),g=this.getFlashWriteSize(),m=i?o:s;for(;m-h>0;)this.debug&&this.logger.log(`Writing at ${f(r+c*g,8)} `),m-h>=g?n=Array.from(new Uint8Array(a,h,g)):(n=Array.from(new Uint8Array(a,h,m-h)),i||(n=n.concat(new Array(g-n.length).fill(255)))),i?await this.flashDeflBlock(n,c,2e3):await this.flashBlock(n,c,2e3),c+=1,l+=i?Math.round(n.length*s/o):n.length,h+=g,t(l,m);this.logger.log("Took "+(Date.now()-d)+"ms to write "+m+" bytes"),this.IS_STUB&&(await this.flashBegin(0,0),i?await this.flashDeflFinish():await this.flashFinish())}async flashBlock(e,t,r=100){await this.checkCommand(L,y("<IIII",e.length,t,0,0).concat(e),this.checksum(e),r)}async flashDeflBlock(e,t,r=100){await this.checkCommand(T,y("<IIII",e.length,t,0,0).concat(e),this.checksum(e))}async flashBegin(e=0,t=0,r=!1){let i,a,s=this.getFlashWriteSize();[h,d].includes(this.chipFamily)&&await this.checkCommand(U,new Array(8).fill(0)),this.chipFamily==h&&(a=y("<IIIIII",0,this._flashsize,65536,4096,256,65535),await this.checkCommand(A,a));let o,n=Math.floor((e+s-1)/s);i=this.chipFamily==g?this.getEraseSize(t,e):e,o=this.IS_STUB?b:ie(ce,e);let c=Date.now();return a=y("<IIII",i,n,s,t),this.chipFamily==d&&(a=a.concat(y("<I",r?1:0))),this.logger.log("Erase size "+i+", blocks "+n+", block size "+s+", offset "+f(t,4)+", encrypted "+(r?"yes":"no")),await this.checkCommand(P,a,0,o),0==e||this.IS_STUB||this.logger.log("Took "+(Date.now()-c)+"ms to erase "+n+" bytes"),n}async flashDeflBegin(e=0,t=0,r=0,i=!1){let a,s=this.getFlashWriteSize(),o=Math.floor((t+s-1)/s),n=Math.floor((e+s-1)/s),c=0,l=0;return this.IS_STUB?(c=e,l=b):(c=n*s,l=ie(ce,c)),a=y("<IIII",c,o,s,r),await this.checkCommand(M,a,0,l),o}async flashFinish(){let e=y("<I",1);await this.checkCommand(W,e)}async flashDeflFinish(){let e=y("<I",1);await this.checkCommand(O,e)}getBootloaderOffset(){var e;return this.chipFamily==h||(null===(e=this._parent)||void 0===e?void 0:e.chipFamily)==h?j:N}updateImageFlashParams(e,t){if(t.byteLength<8)return t;var r=Array.from(new Uint8Array(t,0,4));let i=r[0],a=r[2],s=r[3];if(this.logger.debug(`Image header, Magic=${f(i)}, FlashMode=${f(a)}, FlashSizeFreq=${f(s)}`),e!=this.getBootloaderOffset())return t;if(i!=q)return this.logger.log("Warning: Image file at %s doesn't look like an image file, so not changing any flash settings.",f(e,4)),t;this.logger.log("Image being flashed is a bootloader");let o=oe.dio,n=ne["40m"],c=H(this.getChipFamily())[this.flashSize?this.flashSize:"4MB"],l=y("BB",o,c+n),h=new Uint8Array(t,2,2);return l[0]!=h[0]||l[1]!=h[1]?(h[0]=l[0],h[1]=l[1],this.logger.log(`Patching Flash parameters header bytes to ${f(l[0],2)} ${f(l[1],2)}`)):this.logger.log("Flash parameters header did not need patching."),t}async flashId(){return await this.runSpiFlashCommand(159,[],24)}getChipFamily(){return this._parent?this._parent.chipFamily:this.chipFamily}async writeRegister(e,t,r=4294967295,i=0,a=0){let s=y("<IIII",e,t,r,i);a>0&&s.concat(y("<IIII",V(this.getChipFamily()),0,0,a)),await this.checkCommand(G,s)}async setDataLengths(e,t,r){if(-1!=e.mosiDlenOffs){let i=e.regBase+e.mosiDlenOffs,a=e.regBase+e.misoDlenOffs;t>0&&await this.writeRegister(i,t-1),r>0&&await this.writeRegister(a,r-1)}else{let i=e.regBase+e.usr1Offs,a=(0==r?0:r-1)<<8|(0==t?0:t-1)<<17;await this.writeRegister(i,a)}}async waitDone(e,t){for(let r=0;r<10;r++){if(0==(await this.readRegister(e)&t))return}throw Error("SPI command did not complete in time")}async runSpiFlashCommand(e,t,r=0){let i=J(this.getChipFamily()),a=i.regBase,s=a+0,o=a+i.usrOffs,n=a+i.usr2Offs,c=a+i.w0Offs,l=1<<18;if(r>32)throw new Error("Reading more than 32 bits back from a SPI flash operation is unsupported");if(t.length>64)throw new Error("Writing more than 64 bytes of data with one SPI command is unsupported");let h=8*t.length,d=await this.readRegister(o),g=await this.readRegister(n),m=1<<31;if(r>0&&(m|=268435456),h>0&&(m|=134217728),await this.setDataLengths(i,h,r),await this.writeRegister(o,m),await this.writeRegister(n,7<<28|e),0==h)await this.writeRegister(c,0);else{t.concat(new Array(t.length%4).fill(0));let e=_("I".repeat(Math.floor(t.length/4)),t),r=c;this.logger.debug(`Words Length: ${e.length}`);for(const t of e)this.logger.debug(`Writing word ${f(t)} to register offset ${f(r)}`),await this.writeRegister(r,t),r+=4}await this.writeRegister(s,l),await this.waitDone(s,l);let p=await this.readRegister(c);return await this.writeRegister(o,d),await this.writeRegister(n,g),p}async detectFlashSize(){this.logger.log("Detecting Flash Size");let e=await this.flashId(),t=255&e,r=e>>16&255;this.logger.debug(`FlashId: ${f(e)}`),this.logger.log(`Flash Manufacturer: ${t.toString(16)}`),this.logger.log(`Flash Device: ${(e>>8&255).toString(16)}${r.toString(16)}`),this.flashSize=K[r],this.logger.log(`Auto-detected Flash size: ${this.flashSize}`)}getEraseSize(e,t){let r=ae,i=Math.floor((t+r-1)/r),a=16-Math.floor(e/r)%16;return i<a&&(a=i),i<2*a?Math.floor((i+1)/2*r):(i-a)*r}async memBegin(e,t,r,i){return await this.checkCommand(Q,y("<IIII",e,t,r,i))}async memBlock(e,t){return await this.checkCommand(X,y("<IIII",e.length,t,0,0).concat(e),this.checksum(e))}async memFinish(e=0){let t=this.IS_STUB?b:Y,r=y("<II",0==e?1:0,e);return await this.checkCommand(Z,r,0,t)}async runStub(){const e=await we(this.chipFamily);let t=se;this.logger.log("Uploading stub...");for(let r of["text","data"])if(Object.keys(e).includes(r)){let i=e[r+"_start"],a=e[r].length,s=Math.floor((a+t-1)/t);await this.memBegin(a,s,t,i);for(let i of Array(s).keys()){let s=i*t,o=s+t;o>a&&(o=a),await this.memBlock(e[r].slice(s,o),i)}}this.logger.log("Running stub..."),await this.memFinish(e.entry);const r=await this.readBuffer(100),i=String.fromCharCode(...r);if("OHAI"!=i)throw new Error("Failed to start stub. Unexpected response: "+i);this.logger.log("Stub is now running...");const a=new be(this.port,this.logger,this);return await a.detectFlashSize(),a}async writeToStream(e){const t=this.port.writable.getWriter();await t.write(new Uint8Array(e));try{t.releaseLock()}catch(e){console.error("Ignoring release lock error",e)}}async disconnect(){this._parent?await this._parent.disconnect():(this._reader&&await this._reader.cancel(),await this.port.writable.getWriter().close(),await this.port.close(),this.connected=!1)}}class be extends _e{constructor(){super(...arguments),this.IS_STUB=!0}async memBegin(e,t,r,i){let a=await we(this.chipFamily),s=i,o=i+e;console.log(s,o),console.log(a.data_start,a.data.length,a.text_start,a.text.length);for(let[e,t]of[[a.data_start,a.data_start+a.data.length],[a.text_start,a.text_start+a.text.length]])if(s<t&&o>e)throw new Error("Software loader is resident at "+f(e,8)+"-"+f(t,8)+". Can't load binary at overlapping address range "+f(s,8)+"-"+f(o,8)+". Try changing the binary loading address.")}async eraseFlash(){await this.checkCommand(ee,[],0,te)}}const Ie=async e=>{const t=await navigator.serial.requestPort();return e.log("Connecting..."),await t.open({baudRate:F}),e.log("Connected successfully."),new _e(t,e)},$e=e=>he("./wizard.html",{method:"post",body:new URLSearchParams(e)}),ke=e=>he(`./info?configuration=${e}`),ve=e=>he(`./delete?configuration=${e}`,{method:"post"}),Se=e=>de("compile",{configuration:e}),Fe=async(e,t,r,i)=>{const a=await ke(t);if(le[e.chipFamily]!==a.esp_platform)throw new Error(`Configuration does not match the platform of the connected device. Expected a ${a.esp_platform} device.`);let s;s="ESP32"===a.esp_platform?[{path:"./static/firmware/bootloader.bin",offset:4096},{path:"./static/firmware/partitions.bin",offset:32768},{path:"./static/firmware/ota.bin",offset:57344},{path:`./download.bin?configuration=${t}`,offset:65536}]:[{path:`./download.bin?configuration=${t}`,offset:0}];const o=s.map((async e=>{const t=new URL(e.path,location.href).toString(),r=await fetch(t);if(!r.ok)throw new Error(`Downlading firmware ${e.path} failed: ${r.status}`);return r.arrayBuffer()})),n=[];let c=0;for(const e of o){const t=await e;n.push(t),c+=t.byteLength}const l=await e.runStub();r&&await l.eraseFlash();let h=0,d=0;i(0);for(const e of s){const t=n.shift();await l.flashData(t,(e=>{const t=Math.floor((d+e)/c*100);t!==h&&(h=t,i(t))}),e.offset,!0),d+=t.byteLength}i(100)};export{Se as a,ge as b,Ie as c,$e as d,ve as e,Fe as f,ke as g,pe as i};
