brilliantsole 0.0.12 → 0.0.13

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.
@@ -2,5 +2,5 @@
2
2
  * @copyright Zack Qattan 2024
3
3
  * @license MIT
4
4
  */
5
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BS={})}(this,(function(e){"use strict";function t(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function s(e,t,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,s):n?n.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const i=!1,n="undefined"!=typeof window&&void 0!==window?.document,r="undefined"!=typeof process&&null!=process?.versions?.node,a=n&&navigator.userAgent||"";let o=!1;n?o=Boolean(navigator.bluetooth):r&&(o=!0);const c=n&&/Bluefy/i.test(a),h=n&&/WebBLE/i.test(a),l=n&&/Android/i.test(a),g=n&&/Safari/i.test(a)&&!/Chrome/i.test(a),f=n&&/iPad|iPhone|iPod/i.test(a),u=n&&/Macintosh/i.test(a),d=!n&&!r&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var m,p,v,w,y=Object.freeze({__proto__:null,isAndroid:l,get isBluetoothSupported(){return o},isIOS:f,isInBluefy:c,isInBrowser:n,isInDev:i,isInLensStudio:d,isInNode:r,isInProduction:!0,isInWebBLE:h,isMac:u,isSafari:g});if(d){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(w={}).log=e,w.warn=e.bind(w,"WARNING"),w.error=e.bind(w,"ERROR")}else w=console;if(!w.assert){const e=(e,...t)=>{e||w.warn(...t)};w.assert=e}if(!w.table){const e=(...e)=>{w.log(...e)};w.table=e}function b(){}const S=w.log.bind(w),E=w.warn.bind(w),C=w.error.bind(w),M=w.table.bind(w),D=w.assert.bind(w);class k{constructor(e){if(v.set(this,{log:i,warn:i,assert:!0,error:!0,table:!0}),t(m,m,"f",p)[e])throw new Error(`"${e}" console already exists`);t(m,m,"f",p)[e]=this}setLevelFlags(e){Object.assign(t(this,v,"f"),e)}static setLevelFlagsForType(e,s){if(!t(this,m,"f",p)[e])throw new Error(`no console found with type "${e}"`);t(this,m,"f",p)[e].setLevelFlags(s)}static setAllLevelFlags(e){for(const s in t(this,m,"f",p))t(this,m,"f",p)[s].setLevelFlags(e)}static create(e,s){return t(this,m,"f",p)[e]||new m(e)}get log(){return t(this,v,"f").log?S:b}get warn(){return t(this,v,"f").warn?E:b}get error(){return t(this,v,"f").error?C:b}get assert(){return t(this,v,"f").assert?D:b}get table(){return t(this,v,"f").table?M:b}assertWithError(e,t){if(!Boolean(e))throw new Error(t)}assertTypeWithError(e,t){this.assertWithError(typeof e==t,`value ${e} of type "${typeof e}" not of type "${t}"`)}assertEnumWithError(e,t){this.assertWithError(t.includes(e),`invalid enum "${e}"`)}}function T(e,t){return k.create(e,t)}m=k,v=new WeakMap,p={value:{}};const W=T("EventDispatcher",{log:!1});class _{constructor(e,t){this.target=e,this.validEventTypes=t,this.listeners={},this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.waitForEvent=this.waitForEvent.bind(this)}isValidEventType(e){return this.validEventTypes.includes(e)}updateEventListeners(e){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((t=>(t.shouldRemove&&W.log(`removing "${e}" eventListener`,t),!t.shouldRemove))))}addEventListener(e,t,s={once:!1}){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]||(this.listeners[e]=[],W.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==s.once))?W.log("already added listener"):(W.log(`adding "${e}" listener`,t,s),this.listeners[e].push({listener:t,once:s.once}),W.log(`currently have ${this.listeners[e].length} "${e}" listeners`))}removeEventListener(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(W.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((s=>{s.listener===t&&(W.log(`flagging "${e}" listener`,t),s.shouldRemove=!0)})),this.updateEventListeners(e))}dispatchEvent(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(this.listeners[e].forEach((s=>{s.shouldRemove||(W.log(`dispatching "${e}" listener`,s),s.listener({type:e,target:this.target,message:t}),s.once&&(W.log(`flagging "${e}" listener`,s),s.shouldRemove=!0))})),this.updateEventListeners(e))}waitForEvent(e){return new Promise((t=>{this.addEventListener(e,(e=>{t(e)}),{once:!0})}))}}var I,F,U;const L=T("Timer",{log:!1});class R{get callback(){return t(this,I,"f")}set callback(e){L.assertTypeWithError(e,"function"),L.log({newCallback:e}),s(this,I,e,"f"),this.isRunning&&this.restart()}get interval(){return t(this,F,"f")}set interval(e){L.assertTypeWithError(e,"number"),L.assertWithError(e>0,"interval must be above 0"),L.log({newInterval:e}),s(this,F,e,"f"),this.isRunning&&this.restart()}constructor(e,t){I.set(this,void 0),F.set(this,void 0),U.set(this,void 0),this.interval=t,this.callback=e}get isRunning(){return null!=t(this,U,"f")}start(){this.isRunning?L.log("interval already running"):(L.log("starting interval"),s(this,U,setInterval(t(this,I,"f"),t(this,F,"f")),"f"))}stop(){this.isRunning?(L.log("stopping interval"),clearInterval(t(this,U,"f")),s(this,U,void 0,"f")):L.log("interval already not running")}restart(){this.stop(),this.start()}}function x(e){for(let t=0;t<8;++t)e=(1&e?0:3988292384)^e>>>1;return 4278190080^e}I=new WeakMap,F=new WeakMap,U=new WeakMap,T("checksum",{log:!0});const A=new Uint32Array(256);for(let e=0;e<256;++e)A[e]=x(e);function O(e){let t=new Uint8Array(e),s=0;for(let e=0;e<t.byteLength;++e){const i=255&s,n=t[e];s=(A[i^n]^s>>>8)>>>0}return s}var $,B;$="undefined"==typeof TextEncoder?class{encode(e){const t=Array.from(e).map((e=>e.charCodeAt(0)));return Uint8Array.from(t)}}:TextEncoder,B="undefined"==typeof TextDecoder?class{decode(e){return Array.from(new Uint8Array(e)).map((e=>String.fromCharCode(e))).join("")}}:TextDecoder;const N=new $,P=new B,V=T("ArrayBufferUtils",{log:!1});function z(...e){const t=(e=(e=(e=e.filter((e=>null!=e||null!=e))).map((e=>{if("number"==typeof e){const t=e;return Uint8Array.from([Math.floor(t)])}if("boolean"==typeof e){const t=e;return Uint8Array.from([t?1:0])}if("string"==typeof e){return j(e)}if(e instanceof Array){return z(...e)}if(e instanceof ArrayBuffer)return e;if("buffer"in e&&e.buffer instanceof ArrayBuffer){return e.buffer}if(e instanceof DataView){return e.buffer}if("object"==typeof e){return function(e){return j(JSON.stringify(e))}(e)}return e}))).filter((e=>e&&"byteLength"in e))).reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(t);let i=0;return e.forEach((e=>{s.set(new Uint8Array(e),i),i+=e.byteLength})),s.buffer}function j(e){const t=N.encode(e);return z(t.byteLength,t)}function q(e,t,s){let i;return null!=s&&(i=e.byteOffset+t+s),V.log({dataView:e,begin:t,end:i,length:s}),new DataView(e.buffer.slice(e.byteOffset+t,i))}async function G(e){let t;if(e instanceof Array)t=Uint8Array.from(e);else if(e instanceof DataView)t=e.buffer;else if("string"==typeof e||e instanceof URL){const s=await fetch(e);t=await s.arrayBuffer()}else if(e instanceof File)t=await e.arrayBuffer();else{if(!(e instanceof ArrayBuffer))throw{error:"invalid file type",file:e};t=e}return t}function H(e,{include:t,exclude:s}={}){const i=e=>{const i=t=>"string"==typeof t?e===t:t.test(e);return t?t.some(i):!s||!s.some(i)};for(const[t,s]of(e=>{const t=new Set;do{for(const s of Reflect.ownKeys(e))t.add([e,s])}while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t})(e.constructor.prototype)){if("constructor"===s||!i(s))continue;const n=Reflect.getOwnPropertyDescriptor(t,s);n&&"function"==typeof n.value&&(e[s]=e[s].bind(e))}return e}var J,Q,K,Z,X,Y,ee,te,se,ie,ne,re,ae,oe,ce,he,le,ge,fe,ue,de,me,pe,ve,we,ye,be,Se,Ee,Ce,Me,De,ke,Te,We,_e,Ie,Fe;const Ue=T("FileTransferManager",{log:!0}),Le=["maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Re=["tflite"],xe=["idle","sending","receiving"],Ae=["startSend","startReceive","cancel"],Oe=[...Le,"fileTransferProgress","fileTransferComplete","fileReceived"];class $e{constructor(){J.add(this),se.set(this,Q.MaxLength),ae.set(this,void 0),le.set(this,0),de.set(this,0),ye.set(this,"idle"),Me.set(this,[]),ke.set(this,void 0),Te.set(this,0),Fe.set(this,!1),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}static get MaxLength(){return t(this,Q,"f",te)}get maxLength(){return t(this,se,"f")}get type(){return t(this,ae,"f")}get length(){return t(this,le,"f")}get checksum(){return t(this,de,"f")}get status(){return t(this,ye,"f")}parseMessage(e,s){switch(Ue.log({messageType:e}),e){case"maxFileLength":t(this,J,"m",ie).call(this,s);break;case"getFileType":case"setFileType":t(this,J,"m",oe).call(this,s);break;case"getFileLength":case"setFileLength":t(this,J,"m",ge).call(this,s);break;case"getFileChecksum":case"setFileChecksum":t(this,J,"m",me).call(this,s);break;case"fileTransferStatus":t(this,J,"m",be).call(this,s);break;case"getFileBlock":t(this,J,"m",De).call(this,s);break;case"fileBytesTransferred":t(this,J,"m",Ie).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}async send(e,s){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e);const i=await G(s),n=[];n.push(t(this,J,"m",he).call(this,e,!1));const r=i.byteLength;n.push(t(this,J,"m",ue).call(this,r,!1));const a=O(i);n.push(t(this,J,"m",ve).call(this,a,!1)),n.push(t(this,J,"m",we).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(n),await t(this,J,"m",We).call(this,i)}async receive(e){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e),await t(this,J,"m",he).call(this,e),await t(this,J,"m",we).call(this,"startReceive")}async cancel(){t(this,J,"m",Ce).call(this),await t(this,J,"m",we).call(this,"cancel")}get isServerSide(){return t(this,Fe,"f")}set isServerSide(e){t(this,Fe,"f")!=e?(Ue.log({newIsServerSide:e}),s(this,Fe,e,"f")):Ue.log("redundant isServerSide assignment")}}Q=$e,se=new WeakMap,ae=new WeakMap,le=new WeakMap,de=new WeakMap,ye=new WeakMap,Me=new WeakMap,ke=new WeakMap,Te=new WeakMap,Fe=new WeakMap,J=new WeakSet,K=function(){return this.eventDispatcher.dispatchEvent},Z=function(e){Ue.assertEnumWithError(e,Re)},X=function(e){Ue.assertWithError(e in Re,`invalid typeEnum ${e}`)},Y=function(e){Ue.assertWithError(e in xe,`invalid statusEnum ${e}`)},ee=function(e){Ue.assertEnumWithError(e,Ae)},ie=function(e){Ue.log("parseFileMaxLength",e);const s=e.getUint32(0,!0);Ue.log(`maxLength: ${s/1024}kB`),t(this,J,"m",ne).call(this,s)},ne=function(e){Ue.log({maxLength:e}),s(this,se,e,"f"),t(this,J,"a",K).call(this,"maxFileLength",{maxFileLength:e})},re=function(e){Ue.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},oe=function(e){Ue.log("parseFileType",e);const s=e.getUint8(0);t(this,J,"m",X).call(this,s);const i=Re[s];t(this,J,"m",ce).call(this,i)},ce=function(e){Ue.log({fileTransferType:e}),s(this,ae,e,"f"),t(this,J,"a",K).call(this,"getFileType",{fileType:e})},he=async function(e,s){if(t(this,J,"m",Z).call(this,e),this.type==e)return void Ue.log(`redundant type assignment ${e}`);const i=this.waitForEvent("getFileType"),n=Re.indexOf(e);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],s),await i},ge=function(e){Ue.log("parseFileLength",e);const s=e.getUint32(0,!0);t(this,J,"m",fe).call(this,s)},fe=function(e){Ue.log(`length: ${e/1024}kB`),s(this,le,e,"f"),t(this,J,"a",K).call(this,"getFileLength",{fileLength:e})},ue=async function(e,s){if(Ue.assertTypeWithError(e,"number"),t(this,J,"m",re).call(this,e),this.length==e)return void Ue.log(`redundant length assignment ${e}`);const i=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,e,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],s),await i},me=function(e){Ue.log("checksum",e);const s=e.getUint32(0,!0);t(this,J,"m",pe).call(this,s)},pe=function(e){Ue.log({checksum:e}),s(this,de,e,"f"),t(this,J,"a",K).call(this,"getFileChecksum",{fileChecksum:e})},ve=async function(e,t){if(Ue.assertTypeWithError(e,"number"),this.checksum==e)return void Ue.log(`redundant checksum assignment ${e}`);const s=this.waitForEvent("getFileChecksum"),i=new DataView(new ArrayBuffer(4));i.setUint32(0,e,!0),this.sendMessage([{type:"setFileChecksum",data:i.buffer}],t),await s},we=async function(e,s){t(this,J,"m",ee).call(this,e);const i=this.waitForEvent("fileTransferStatus"),n=Ae.indexOf(e);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],s),await i},be=function(e){Ue.log("parseFileStatus",e);const s=e.getUint8(0);t(this,J,"m",Y).call(this,s);const i=xe[s];t(this,J,"m",Se).call(this,i)},Se=function(e){Ue.log({status:e}),s(this,ye,e,"f"),t(this,J,"a",K).call(this,"fileTransferStatus",{fileTransferStatus:e}),t(this,Me,"f").length=0},Ee=function(){Ue.assertWithError("idle"==t(this,ye,"f"),"status is not idle")},Ce=function(){Ue.assertWithError("idle"!=t(this,ye,"f"),"status is idle")},De=async function(e){Ue.log("parseFileBlock",e),t(this,Me,"f").push(e.buffer);const s=t(this,Me,"f").reduce(((e,t)=>e+t.byteLength),0),i=s/t(this,le,"f");if(Ue.log(`received ${s} of ${t(this,le,"f")} bytes (${100*i}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:i}),s!=t(this,le,"f")){const e=new DataView(new ArrayBuffer(4));if(e.setUint32(0,s,!0),this.isServerSide)return;return void await this.sendMessage([{type:"fileBytesTransferred",data:e.buffer}])}Ue.log("file transfer complete");let n,r=(new Date).toLocaleString();if("tflite"===this.type)r+=".tflite";n="undefined"!=typeof File?new File(t(this,Me,"f"),r):new Blob(t(this,Me,"f"));const a=O(await n.arrayBuffer());Ue.log({checksum:a}),a==t(this,de,"f")?(Ue.log("received file",n),t(this,J,"a",K).call(this,"getFileBlock",{fileTransferBlock:e}),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"receiving"}),t(this,J,"a",K).call(this,"fileReceived",{file:n})):Ue.error(`wrong checksum - expected ${t(this,de,"f")}, got ${a}`)},We=async function(e){return s(this,ke,e,"f"),s(this,Te,0,"f"),t(this,J,"m",_e).call(this)},_e=async function(){if("sending"!=this.status)return;if(!t(this,ke,"f"))return void Ue.error("no buffer defined");const e=t(this,ke,"f");let i=t(this,Te,"f");const n=e.slice(i,i+(this.mtu-3-3));Ue.log("slicedBuffer",n);const r=1-(e.byteLength-i)/e.byteLength;Ue.log(`sending bytes ${i}-${i+n.byteLength} of ${e.byteLength} bytes (${100*r}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:r}),0==n.byteLength?(Ue.log("finished sending buffer"),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),s(this,Te,i+n.byteLength,"f"))},Ie=async function(e){Ue.log("parseBytesTransferred",e);const s=e.getUint32(0,!0);if(Ue.log({bytesTransferred:s}),"sending"==this.status)return this.isServerSide||t(this,Te,"f")==s?void t(this,J,"m",_e).call(this):(Ue.error(`bytesTransferred are not equal - got ${s}, expected ${t(this,Te,"f")}`),void this.cancel());Ue.error("not currently sending file")},te={value:0};const Be=T("MathUtils",{log:!0});const Ne=65536;function Pe(e,t){const s=Date.now();var i;let n=(i=s)-i%Ne+e.getUint16(t,!0);return Math.abs(s-n)>6e4&&(Be.log("correcting timestamp delta"),n+=Ne*Math.sign(s-n)),n}var Ve;const ze={min:1/0,max:-1/0,span:0};class je{constructor(){Ve.set(this,Object.assign({},ze))}reset(){Object.assign(t(this,Ve,"f"),ze)}update(e){t(this,Ve,"f").min=Math.min(e,t(this,Ve,"f").min),t(this,Ve,"f").max=Math.max(e,t(this,Ve,"f").max),t(this,Ve,"f").span=t(this,Ve,"f").max-t(this,Ve,"f").min}getNormalization(e,s){let i=function(e,t,s,i){return null==i&&(i=s-t),(e-t)/i}(e,t(this,Ve,"f").min,t(this,Ve,"f").max,t(this,Ve,"f").span);return s&&(i*=t(this,Ve,"f").span),i||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var qe,Ge,He,Je;Ve=new WeakMap;class Qe{constructor(){qe.set(this,{x:new je,y:new je})}reset(){t(this,qe,"f").x.reset(),t(this,qe,"f").y.reset()}update(e){t(this,qe,"f").x.update(e.x),t(this,qe,"f").y.update(e.y)}getNormalization(e){return{x:t(this,qe,"f").x.getNormalization(e.x,!1),y:t(this,qe,"f").y.getNormalization(e.y,!1)}}updateAndGetNormalization(e){return this.update(e),this.getNormalization(e)}}qe=new WeakMap;const Ke=T("PressureDataManager",{log:!0}),Ze=["pressure"],Xe=Ze;class Ye{constructor(){Ge.set(this,[]),He.set(this,void 0),Je.set(this,new Qe)}get positions(){return t(this,Ge,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const t=[];for(let s=0,i=0;i<e.byteLength;s++,i+=2)t.push({x:e.getUint8(i)/256,y:e.getUint8(i+1)/256});var i,n;Ke.log({positions:t}),s(this,Ge,t,"f"),s(this,He,(i=this.numberOfSensors,n=()=>new je,new Array(i).fill(1).map(((e,t)=>{if("function"==typeof n)return n(t);{const e=n;return Object.assign({},e)}}))),"f"),this.resetRange()}resetRange(){t(this,He,"f").forEach((e=>e.reset())),t(this,Je,"f").reset()}parseData(e,s){const i={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,r=0;r<e.byteLength;n++,r+=2){const a=e.getUint16(r,!0),o=a*s,c=t(this,He,"f")[n].updateAndGetNormalization(o,!0),h=this.positions[n];i.sensors[n]={rawValue:a,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},i.scaledSum+=o,i.normalizedSum+=c/this.numberOfSensors}return i.scaledSum>0&&i.normalizedSum>.001&&(i.center={x:0,y:0},i.sensors.forEach((e=>{e.weightedValue=e.scaledValue/i.scaledSum,i.center.x+=e.position.x*e.weightedValue,i.center.y+=e.position.y*e.weightedValue})),i.normalizedCenter=t(this,Je,"f").updateAndGetNormalization(i.center)),Ke.log({pressure:i}),i}}Ge=new WeakMap,He=new WeakMap,Je=new WeakMap;const et=T("MotionSensorDataManager",{log:!0}),tt=["still","walking","running","bicycle","vehicle","tilting"],st=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class it{parseVector3(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));const r={x:s,y:i,z:n};return et.log({vector:r}),r}parseQuaternion(e,t){let[s,i,n,r]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0),e.getInt16(6,!0)].map((e=>e*t));const a={x:s,y:i,z:n,w:r};return et.log({quaternion:a}),a}parseEuler(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));i*=-1,s*=-1,s+=360;const r={heading:s,pitch:i,roll:n};return et.log({euler:r}),r}parseStepCounter(e){et.log("parseStepCounter",e);const t=e.getUint32(0,!0);return et.log({stepCount:t}),t}parseActivity(e){et.log("parseActivity",e);const t={},s=e.getUint8(0);return et.log("activityBitfield",s.toString(2)),tt.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),et.log("activity",t),t}parseDeviceOrientation(e){et.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=st[t];return et.assertWithError(s,"undefined deviceOrientation"),et.log({deviceOrientation:s}),s}}var nt,rt;const at=["barometer"],ot=at,ct=T("BarometerSensorDataManager",{log:!0});class ht{constructor(){nt.add(this)}parseData(e,s){const i=e.getUint32(0,!0)*s,n=t(this,nt,"m",rt).call(this,i);return ct.log({pressure:i,altitude:n}),{pressure:i}}}nt=new WeakSet,rt=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const lt=T("ParseUtils",{log:!0});function gt(e,t=0){const s=e.getUint8(t++);return{string:P.decode(e.buffer.slice(e.byteOffset+t,e.byteOffset+t+s)),byteOffset:t+=s}}function ft(e,t,s,i,n=!1){let r=0;for(;r<e.byteLength;){const a=e.getUint8(r++);lt.assertWithError(a in t,`invalid messageTypeEnum ${a}`);const o=t[a];let c;n?(c=e.getUint16(r,!0),r+=2):c=e.getUint8(r++),lt.log({messageTypeEnum:a,messageType:o,messageLength:c,dataView:e,byteOffset:r});const h=q(e,r,c);lt.log({_dataView:h}),s(o,h,i),r+=c}}var ut;const dt=T("SensorDataManager",{log:!0}),mt=[...Ze,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation",...at],pt=[...Xe,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation",...ot],vt=["getPressurePositions","getSensorScalars","sensorData"],wt=[...vt,...mt];class yt{constructor(){this.pressureSensorDataManager=new Ye,this.motionSensorDataManager=new it,this.barometerSensorDataManager=new ht,ut.set(this,new Map)}static AssertValidSensorType(e){dt.assertEnumWithError(e,mt)}static AssertValidSensorTypeEnum(e){dt.assertTypeWithError(e,"number"),dt.assertWithError(e in mt,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(dt.log({messageType:e}),e){case"getSensorScalars":this.parseScalars(t);break;case"getPressurePositions":this.pressureSensorDataManager.parsePositions(t);break;case"sensorData":this.parseData(t);break;default:throw Error(`uncaught messageType ${e}`)}}parseScalars(e){for(let s=0;s<e.byteLength;s+=5){const i=e.getUint8(s),n=mt[i];if(!n){dt.warn(`unknown sensorType index ${i}`);continue}const r=e.getFloat32(s+1,!0);dt.log({sensorType:n,sensorScalar:r}),t(this,ut,"f").set(n,r)}}parseData(e){dt.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=Pe(e,t);t+=2;ft(new DataView(e.buffer,t),mt,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(e,s,{timestamp:i}){const n=t(this,ut,"f").get(e)||1;let r=null;switch(e){case"pressure":r=this.pressureSensorDataManager.parseData(s,n);break;case"acceleration":case"gravity":case"linearAcceleration":case"gyroscope":case"magnetometer":r=this.motionSensorDataManager.parseVector3(s,n);break;case"gameRotation":case"rotation":r=this.motionSensorDataManager.parseQuaternion(s,n);break;case"orientation":r=this.motionSensorDataManager.parseEuler(s,n);break;case"stepCounter":r=this.motionSensorDataManager.parseStepCounter(s);break;case"stepDetector":r={};break;case"activity":r=this.motionSensorDataManager.parseActivity(s);break;case"deviceOrientation":r=this.motionSensorDataManager.parseDeviceOrientation(s);break;case"barometer":r=this.barometerSensorDataManager.parseData(s,n);break;default:dt.error(`uncaught sensorType "${e}"`)}dt.assertWithError(null!=r,`no sensorData defined for sensorType "${e}"`),dt.log({sensorType:e,sensorData:r}),this.dispatchEvent(e,{sensorType:e,[e]:r,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:e,[e]:r,timestamp:i})}}var bt,St,Et,Ct,Mt,Dt,kt,Tt,Wt,_t,It,Ft,Ut;ut=new WeakMap;const Lt=T("SensorConfigurationManager",{log:!0}),Rt=["getSensorConfiguration","setSensorConfiguration"],xt=Rt;class At{constructor(){bt.add(this),Ct.set(this,void 0),Dt.set(this,void 0),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return t(this,Dt,"f")}async setConfiguration(e,s){if(s&&(e=Object.assign({...this.zeroSensorConfiguration},e)),Lt.log({newSensorConfiguration:e}),t(this,bt,"m",Tt).call(this,e))return void Lt.log("redundant sensor configuration");const i=t(this,bt,"m",Ft).call(this,e);Lt.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return t(this,St,"f",Ut)}get zeroSensorConfiguration(){const e={};return mt.forEach((t=>{e[t]=0})),e}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(e,s){switch(Lt.log({messageType:e}),e){case"getSensorConfiguration":case"setSensorConfiguration":const i=t(this,bt,"m",Wt).call(this,s);t(this,bt,"m",kt).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}}var Ot,$t,Bt,Nt,Pt,Vt,zt,jt,qt,Gt,Ht,Jt,Qt,Kt,Zt,Xt,Yt,es,ts,ss,is,ns,rs,as,os,cs,hs,ls,gs,fs;St=At,Ct=new WeakMap,Dt=new WeakMap,bt=new WeakSet,Et=function(){return this.eventDispatcher.dispatchEvent},Mt=function(e){Lt.assertWithError(t(this,Ct,"f"),"must get initial sensorConfiguration");const s=t(this,Ct,"f")?.includes(e);return Lt.assert(s,`unavailable sensor type "${e}"`),s},kt=function(e){s(this,Dt,e,"f"),Lt.log({updatedConfiguration:t(this,Dt,"f")}),t(this,bt,"a",Et).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},Tt=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},Wt=function(e){const t={};for(let s=0;s<e.byteLength;s+=3){const i=e.getUint8(s),n=mt[i];if(!n){Lt.warn(`unknown sensorType index ${i}`);continue}const r=e.getUint16(s+1,!0);Lt.log({sensorType:n,sensorRate:r}),t[n]=r}return Lt.log({parsedSensorConfiguration:t}),s(this,Ct,Object.keys(t),"f"),t},_t=function(e){Lt.assertTypeWithError(e,"number"),Lt.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),Lt.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),Lt.assertWithError(e%5==0,"sensorRate must be multiple of 5")},It=function(e){t(St,St,"m",_t).call(St,e)},Ft=function(e){let s=Object.keys(e);s=s.filter((e=>t(this,bt,"m",Mt).call(this,e)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{yt.AssertValidSensorType(s);const r=mt.indexOf(s);i.setUint8(3*n,r);const a=e[s];t(this,bt,"m",It).call(this,a),i.setUint16(3*n+1,a,!0)})),Lt.log({sensorConfigurationData:i}),i},Ut={value:{}},mt.forEach((e=>{t(St,St,"f",Ut)[e]=0}));const us=T("TfliteManager",{log:!0}),ds=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],ms=ds,ps=["classification","regression"],vs=["pressure","linearAcceleration","gyroscope","magnetometer"];class ws{constructor(){Ot.add(this),Pt.set(this,void 0),jt.set(this,void 0),Ht.set(this,void 0),Kt.set(this,[]),Yt.set(this,void 0),is.set(this,void 0),as.set(this,void 0),hs.set(this,void 0),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get name(){return t(this,Pt,"f")}async setName(e,t){if(us.assertTypeWithError(e,"string"),this.name==e)return void us.log(`redundant name assignment ${e}`);const s=this.waitForEvent("getTfliteName"),i=N.encode(e);this.sendMessage([{type:"setTfliteName",data:i.buffer}],t),await s}get task(){return t(this,jt,"f")}async setTask(e,s){if(t(this,Ot,"m",$t).call(this,e),this.task==e)return void us.log(`redundant task assignment ${e}`);const i=this.waitForEvent("getTfliteTask"),n=ps.indexOf(e);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],s),await i}get sampleRate(){return t(this,Ht,"f")}async setSampleRate(e,s){if(us.assertTypeWithError(e,"number"),e-=e%5,us.assertWithError(e>=5,`sampleRate must be multiple of 5 greater than 0 (got ${e})`),t(this,Ht,"f")==e)return void us.log(`redundant sampleRate assignment ${e}`);const i=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],s),await i}static AssertValidSensorType(e){yt.AssertValidSensorType(e),us.assertWithError(vs.includes(e),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return t(this,Kt,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{ws.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>mt.indexOf(e))).sort();us.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return t(this,Yt,"f")}get captureDelay(){return t(this,is,"f")}async setCaptureDelay(e,s){if(us.assertTypeWithError(e,"number"),t(this,is,"f")==e)return void us.log(`redundant captureDelay assignment ${e}`);const i=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],s),await i}get threshold(){return t(this,as,"f")}async setThreshold(e,s){if(us.assertTypeWithError(e,"number"),us.assertWithError(e>=0,`threshold must be positive (got ${e})`),t(this,as,"f")==e)return void us.log(`redundant threshold assignment ${e}`);const i=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,e,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],s),await i}get inferencingEnabled(){return t(this,hs,"f")}async setInferencingEnabled(e,s=!0){if(us.assertTypeWithError(e,"boolean"),!e&&!this.isReady)return;if(t(this,Ot,"m",ss).call(this),t(this,hs,"f")==e)return void us.log(`redundant inferencingEnabled assignment ${e}`);const i=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(e)]).buffer}],s),await i}async toggleInferencingEnabled(){return this.setInferencingEnabled(!this.inferencingEnabled)}async enableInferencing(){this.inferencingEnabled||this.setInferencingEnabled(!0)}async disableInferencing(){this.inferencingEnabled&&this.setInferencingEnabled(!1)}parseMessage(e,s){switch(us.log({messageType:e}),e){case"getTfliteName":case"setTfliteName":t(this,Ot,"m",Vt).call(this,s);break;case"getTfliteTask":case"setTfliteTask":t(this,Ot,"m",qt).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":t(this,Ot,"m",Jt).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":t(this,Ot,"m",Zt).call(this,s);break;case"tfliteIsReady":t(this,Ot,"m",es).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":t(this,Ot,"m",ns).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":t(this,Ot,"m",os).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":t(this,Ot,"m",ls).call(this,s);break;case"tfliteInference":t(this,Ot,"m",fs).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}}var ys,bs,Ss,Es,Cs;Pt=new WeakMap,jt=new WeakMap,Ht=new WeakMap,Kt=new WeakMap,Yt=new WeakMap,is=new WeakMap,as=new WeakMap,hs=new WeakMap,Ot=new WeakSet,$t=function(e){us.assertEnumWithError(e,ps)},Bt=function(e){us.assertWithError(e in ps,`invalid taskEnum ${e}`)},Nt=function(){return this.eventDispatcher.dispatchEvent},Vt=function(e){us.log("parseName",e);const s=P.decode(e.buffer);t(this,Ot,"m",zt).call(this,s)},zt=function(e){us.log({name:e}),s(this,Pt,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteName",{tfliteName:e})},qt=function(e){us.log("parseTask",e);const s=e.getUint8(0);t(this,Ot,"m",Bt).call(this,s);const i=ps[s];t(this,Ot,"m",Gt).call(this,i)},Gt=function(e){us.log({task:e}),s(this,jt,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteTask",{tfliteTask:e})},Jt=function(e){us.log("parseSampleRate",e);const s=e.getUint16(0,!0);t(this,Ot,"m",Qt).call(this,s)},Qt=function(e){us.log({sampleRate:e}),s(this,Ht,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteSampleRate",{tfliteSampleRate:e})},Zt=function(e){us.log("parseSensorTypes",e);const s=[];for(let t=0;t<e.byteLength;t++){const i=e.getUint8(t),n=mt[i];n?s.push(n):us.error(`invalid sensorTypeEnum ${i}`)}t(this,Ot,"m",Xt).call(this,s)},Xt=function(e){us.log({sensorTypes:e}),s(this,Kt,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:e})},es=function(e){us.log("parseIsReady",e);const s=Boolean(e.getUint8(0));t(this,Ot,"m",ts).call(this,s)},ts=function(e){us.log({isReady:e}),s(this,Yt,e,"f"),t(this,Ot,"a",Nt).call(this,"tfliteIsReady",{tfliteIsReady:e})},ss=function(){us.assertWithError(this.isReady,"tflite is not ready")},ns=function(e){us.log("parseCaptureDelay",e);const s=e.getUint16(0,!0);t(this,Ot,"m",rs).call(this,s)},rs=function(e){us.log({captureDelay:e}),s(this,is,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:e})},os=function(e){us.log("parseThreshold",e);const s=e.getFloat32(0,!0);t(this,Ot,"m",cs).call(this,s)},cs=function(e){us.log({threshold:e}),s(this,as,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteThreshold",{tfliteThreshold:e})},ls=function(e){us.log("parseInferencingEnabled",e);const s=Boolean(e.getUint8(0));t(this,Ot,"m",gs).call(this,s)},gs=function(e){us.log({inferencingEnabled:e}),s(this,hs,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:e})},fs=function(e){us.log("parseInference",e);const s=Pe(e,0);us.log({timestamp:s});const i=[];for(let t=0,s=2;s<e.byteLength;t++,s+=4){const t=e.getFloat32(s,!0);i.push(t)}us.log("values",i);const n={timestamp:s,values:i};if("classification"==this.task){let e=0,t=0;i.forEach(((s,i)=>{s>e&&(e=s,t=i)})),us.log({maxIndex:t,maxValue:e}),n.maxIndex=t,n.maxValue=e}t(this,Ot,"a",Nt).call(this,"tfliteInference",{tfliteInference:n})};const Ms=T("DeviceInformationManager",{log:!0}),Ds=["manufacturerName","modelNumber","softwareRevision","hardwareRevision","firmwareRevision","pnpId","serialNumber"],ks=[...Ds,"deviceInformation"];class Ts{constructor(){ys.add(this),Ss.set(this,{})}get information(){return t(this,Ss,"f")}clear(){s(this,Ss,{},"f")}parseMessage(e,s){switch(Ms.log({messageType:e}),e){case"manufacturerName":const i=P.decode(s.buffer);Ms.log({manufacturerName:i}),t(this,ys,"m",Cs).call(this,{manufacturerName:i});break;case"modelNumber":const n=P.decode(s.buffer);Ms.log({modelNumber:n}),t(this,ys,"m",Cs).call(this,{modelNumber:n});break;case"softwareRevision":const r=P.decode(s.buffer);Ms.log({softwareRevision:r}),t(this,ys,"m",Cs).call(this,{softwareRevision:r});break;case"hardwareRevision":const a=P.decode(s.buffer);Ms.log({hardwareRevision:a}),t(this,ys,"m",Cs).call(this,{hardwareRevision:a});break;case"firmwareRevision":const o=P.decode(s.buffer);Ms.log({firmwareRevision:o}),t(this,ys,"m",Cs).call(this,{firmwareRevision:o});break;case"pnpId":const c={source:1===s.getUint8(0)?"Bluetooth":"USB",productId:s.getUint16(3,!0),productVersion:s.getUint16(5,!0),vendorId:0};"Bluetooth"==c.source&&(c.vendorId=s.getUint16(1,!0)),Ms.log({pnpId:c}),t(this,ys,"m",Cs).call(this,{pnpId:c});break;case"serialNumber":const h=P.decode(s.buffer);Ms.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${e}`)}}}var Ws,_s,Is,Fs,Us,Ls,Rs,xs,As,Os,$s,Bs,Ns,Ps,Vs,zs,js,qs;Ss=new WeakMap,ys=new WeakSet,bs=function(){return this.eventDispatcher.dispatchEvent},Es=function(){return Ds.every((e=>e in t(this,Ss,"f")))},Cs=function(e){Ms.log({partialDeviceInformation:e});Object.keys(e).forEach((s=>{t(this,ys,"a",bs).call(this,s,{[s]:e[s]})})),Object.assign(t(this,Ss,"f"),e),Ms.log({deviceInformation:t(this,Ss,"f")}),t(this,ys,"a",Es)&&(Ms.log("completed deviceInformation"),t(this,ys,"a",bs).call(this,"deviceInformation",{deviceInformation:this.information}))};const Gs=T("InformationManager",{log:!0}),Hs=["leftInsole","rightInsole"],Js=["left","right"],Qs=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],Ks=Qs;class Zs{constructor(){Ws.add(this),Is.set(this,!1),Us.set(this,void 0),Rs.set(this,void 0),As.set(this,""),Os.set(this,void 0),Ps.set(this,0),zs.set(this,!1),H(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return t(this,Is,"f")}get batteryCurrent(){return t(this,Us,"f")}async getBatteryCurrent(){Gs.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return t(this,Rs,"f")}get name(){return t(this,As,"f")}updateName(e){Gs.assertTypeWithError(e,"string"),s(this,As,e,"f"),Gs.log({updatedName:t(this,As,"f")}),t(this,Ws,"a",_s).call(this,"getName",{name:t(this,As,"f")})}async setName(e){Gs.assertTypeWithError(e,"string"),Gs.assertWithError(e.length>=2,`name must be greater than 2 characters long ("${e}" is ${e.length} characters long)`),Gs.assertWithError(e.length<30,`name must be less than 30 characters long ("${e}" is ${e.length} characters long)`);const t=N.encode(e);Gs.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return t(this,Os,"f")}get typeEnum(){return Hs.indexOf(this.type)}updateType(e){t(this,Ws,"m",$s).call(this,e),e!=this.type?(s(this,Os,e,"f"),Gs.log({updatedType:t(this,Os,"f")}),t(this,Ws,"a",_s).call(this,"getType",{type:t(this,Os,"f")})):Gs.log("redundant type assignment")}async setType(e){t(this,Ws,"m",$s).call(this,e);const s=Hs.indexOf(e);t(this,Ws,"m",Ns).call(this,s)}get isInsole(){switch(this.type){case"leftInsole":case"rightInsole":return!0;default:return!1}}get insoleSide(){switch(this.type){case"leftInsole":return"left";case"rightInsole":return"right"}}get mtu(){return t(this,Ps,"f")}get isCurrentTimeSet(){return t(this,zs,"f")}parseMessage(e,s){switch(Gs.log({messageType:e}),e){case"isCharging":const i=Boolean(s.getUint8(0));Gs.log({isCharging:i}),t(this,Ws,"m",Fs).call(this,i);break;case"getBatteryCurrent":const n=s.getFloat32(0,!0);Gs.log({batteryCurrent:n}),t(this,Ws,"m",Ls).call(this,n);break;case"getId":const r=P.decode(s.buffer);Gs.log({id:r}),t(this,Ws,"m",xs).call(this,r);break;case"getName":case"setName":const a=P.decode(s.buffer);Gs.log({name:a}),this.updateName(a);break;case"getType":case"setType":const o=s.getUint8(0),c=Hs[o];Gs.log({typeEnum:o,type:c}),this.updateType(c);break;case"getMtu":const h=s.getUint16(0,!0);Gs.log({mtu:h}),t(this,Ws,"m",Vs).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(s.getBigUint64(0,!0));t(this,Ws,"m",js).call(this,l);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){s(this,zs,!1,"f")}}Is=new WeakMap,Us=new WeakMap,Rs=new WeakMap,As=new WeakMap,Os=new WeakMap,Ps=new WeakMap,zs=new WeakMap,Ws=new WeakSet,_s=function(){return this.eventDispatcher.dispatchEvent},Fs=function(e){Gs.assertTypeWithError(e,"boolean"),s(this,Is,e,"f"),Gs.log({isCharging:t(this,Is,"f")}),t(this,Ws,"a",_s).call(this,"isCharging",{isCharging:t(this,Is,"f")})},Ls=function(e){Gs.assertTypeWithError(e,"number"),s(this,Us,e,"f"),Gs.log({batteryCurrent:t(this,Us,"f")}),t(this,Ws,"a",_s).call(this,"getBatteryCurrent",{batteryCurrent:t(this,Us,"f")})},xs=function(e){Gs.assertTypeWithError(e,"string"),s(this,Rs,e,"f"),Gs.log({id:t(this,Rs,"f")}),t(this,Ws,"a",_s).call(this,"getId",{id:t(this,Rs,"f")})},$s=function(e){Gs.assertEnumWithError(e,Hs)},Bs=function(e){Gs.assertTypeWithError(e,"number"),Gs.assertWithError(e in Hs,`invalid typeEnum ${e}`)},Ns=async function(e){t(this,Ws,"m",Bs).call(this,e);const s=Uint8Array.from([e]);Gs.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},Vs=function(e){Gs.assertTypeWithError(e,"number"),t(this,Ps,"f")!=e?(s(this,Ps,e,"f"),t(this,Ws,"a",_s).call(this,"getMtu",{mtu:t(this,Ps,"f")})):Gs.log("redundant mtu assignment",e)},js=function(e){Gs.log({currentTime:e}),s(this,zs,0!=e||Math.abs(Date.now()-e)<Ne,"f"),t(this,zs,"f")||t(this,Ws,"m",qs).call(this)},qs=async function(){Gs.log("setting current time...");const e=new DataView(new ArrayBuffer(8));e.setBigUint64(0,BigInt(Date.now()),!0);const t=this.waitForEvent("getCurrentTime");this.sendMessage([{type:"setCurrentTime",data:e.buffer}]),await t};const Xs=["none","strongClick100","strongClick60","strongClick30","sharpClick100","sharpClick60","sharpClick30","softBump100","softBump60","softBump30","doubleClick100","doubleClick60","tripleClick100","softFuzz60","strongBuzz100","alert750ms","alert1000ms","strongClick1_100","strongClick2_80","strongClick3_60","strongClick4_30","mediumClick100","mediumClick80","mediumClick60","sharpTick100","sharpTick80","sharpTick60","shortDoubleClickStrong100","shortDoubleClickStrong80","shortDoubleClickStrong60","shortDoubleClickStrong30","shortDoubleClickMedium100","shortDoubleClickMedium80","shortDoubleClickMedium60","shortDoubleSharpTick100","shortDoubleSharpTick80","shortDoubleSharpTick60","longDoubleSharpClickStrong100","longDoubleSharpClickStrong80","longDoubleSharpClickStrong60","longDoubleSharpClickStrong30","longDoubleSharpClickMedium100","longDoubleSharpClickMedium80","longDoubleSharpClickMedium60","longDoubleSharpTick100","longDoubleSharpTick80","longDoubleSharpTick60","buzz100","buzz80","buzz60","buzz40","buzz20","pulsingStrong100","pulsingStrong60","pulsingMedium100","pulsingMedium60","pulsingSharp100","pulsingSharp60","transitionClick100","transitionClick80","transitionClick60","transitionClick40","transitionClick20","transitionClick10","transitionHum100","transitionHum80","transitionHum60","transitionHum40","transitionHum20","transitionHum10","transitionRampDownLongSmooth2_100","transitionRampDownLongSmooth1_100","transitionRampDownMediumSmooth1_100","transitionRampDownMediumSmooth2_100","transitionRampDownShortSmooth1_100","transitionRampDownShortSmooth2_100","transitionRampDownLongSharp1_100","transitionRampDownLongSharp2_100","transitionRampDownMediumSharp1_100","transitionRampDownMediumSharp2_100","transitionRampDownShortSharp1_100","transitionRampDownShortSharp2_100","transitionRampUpLongSmooth1_100","transitionRampUpLongSmooth2_100","transitionRampUpMediumSmooth1_100","transitionRampUpMediumSmooth2_100","transitionRampUpShortSmooth1_100","transitionRampUpShortSmooth2_100","transitionRampUpLongSharp1_100","transitionRampUpLongSharp2_100","transitionRampUpMediumSharp1_100","transitionRampUpMediumSharp2_100","transitionRampUpShortSharp1_100","transitionRampUpShortSharp2_100","transitionRampDownLongSmooth1_50","transitionRampDownLongSmooth2_50","transitionRampDownMediumSmooth1_50","transitionRampDownMediumSmooth2_50","transitionRampDownShortSmooth1_50","transitionRampDownShortSmooth2_50","transitionRampDownLongSharp1_50","transitionRampDownLongSharp2_50","transitionRampDownMediumSharp1_50","transitionRampDownMediumSharp2_50","transitionRampDownShortSharp1_50","transitionRampDownShortSharp2_50","transitionRampUpLongSmooth1_50","transitionRampUpLongSmooth2_50","transitionRampUpMediumSmooth1_50","transitionRampUpMediumSmooth2_50","transitionRampUpShortSmooth1_50","transitionRampUpShortSmooth2_50","transitionRampUpLongSharp1_50","transitionRampUpLongSharp2_50","transitionRampUpMediumSharp1_50","transitionRampUpMediumSharp2_50","transitionRampUpShortSharp1_50","transitionRampUpShortSharp2_50","longBuzz100","smoothHum50","smoothHum40","smoothHum30","smoothHum20","smoothHum10"];var Ys,ei,ti,si,ii,ni,ri,ai,oi,ci,hi,li,gi,fi,ui,di;const mi=T("VibrationManager"),pi=["front","rear"],vi=["waveformEffect","waveform"],wi=2550,yi=1270;class bi{constructor(){Ys.add(this),H(this)}async triggerVibration(e,s=!0){let i;e.forEach((e=>{const{type:s}=e;let n,{locations:r}=e;switch(r=r||pi.slice(),s){case"waveformEffect":{const{segments:s,loopCount:i}=e;n=t(this,Ys,"m",gi).call(this,r,s,i)}break;case"waveform":{const{segments:s}=e;n=t(this,Ys,"m",fi).call(this,r,s)}break;default:throw Error(`invalid vibration type "${s}"`)}mi.log({type:s,arrayBuffer:n}),i=z(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}}var Si,Ei,Ci,Mi,Di,ki,Ti,Wi,_i,Ii,Fi,Ui,Li,Ri;Ys=new WeakSet,ei=function(e){mi.assertTypeWithError(e,"string"),mi.assertWithError(pi.includes(e),`invalid location "${e}"`)},ti=function(e){t(this,Ys,"m",ii).call(this,e),e.forEach((e=>{t(this,Ys,"m",ei).call(this,e)}))},si=function(e){t(this,Ys,"m",ti).call(this,e);let s=0;return e.forEach((e=>{const t=pi.indexOf(e);s|=1<<t})),mi.log({locationsBitmask:s}),mi.assertWithError(s>0,"locationsBitmask must not be zero"),s},ii=function(e){mi.assertWithError(Array.isArray(e),"passed non-array"),mi.assertWithError(e.length>0,"passed empty array")},ni=function(e){mi.assertWithError(Xs.includes(e),`invalid waveformEffect "${e}"`)},ri=function(e){if(null!=e.effect){const s=e.effect;t(this,Ys,"m",ni).call(this,s)}else{if(null==e.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:t}=e;mi.assertWithError(t>=0,`delay must be 0ms or greater (got ${t})`),mi.assertWithError(t<=yi,`delay must be 1270ms or less (got ${t})`)}}if(null!=e.loopCount){const{loopCount:s}=e;t(this,Ys,"m",ai).call(this,s)}},ai=function(e){mi.assertTypeWithError(e,"number"),mi.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),mi.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},oi=function(e){t(this,Ys,"m",ii).call(this,e),mi.assertWithError(e.length<=8,`must have 8 waveformEffectSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ys,"m",ri).call(this,e)}))},ci=function(e){mi.assertTypeWithError(e,"number"),mi.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),mi.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},hi=function(e){mi.assertTypeWithError(e.amplitude,"number"),mi.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),mi.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),mi.assertTypeWithError(e.duration,"number"),mi.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),mi.assertWithError(e.duration<=wi,`duration must be 2550ms or less (got ${e.duration}ms)`)},li=function(e){t(this,Ys,"m",ii).call(this,e),mi.assertWithError(e.length<=20,`must have 20 waveformSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ys,"m",hi).call(this,e)}))},gi=function(e,s,i=0){t(this,Ys,"m",oi).call(this,s),t(this,Ys,"m",ci).call(this,i);let n=[],r=0;const a=s.some((e=>{const{loopCount:t}=e;return null!=t&&t>0}))||0!=i;for(let e=0;e<s.length||a&&e<8;e++){const t=s[e]||{effect:"none"};if(null!=t.effect){const e=t.effect;n[r++]=Xs.indexOf(e)}else{if(null==t.delay)throw Error("invalid waveformEffectSegment");{const{delay:e}=t;n[r++]=128|Math.floor(e/10)}}}const o=0!=i;for(let e=0;e<s.length||o&&e<8;e++){const t=s[e]?.loopCount||0;0!=e&&4!=e||(n[r]=0);const i=e%4*2;n[r]|=t<<i,3!=e&&7!=e||r++}0!=i&&(n[r++]=i);const c=new DataView(Uint8Array.from(n).buffer);return mi.log({dataArray:n,dataView:c}),t(this,Ys,"m",di).call(this,e,"waveformEffect",c)},fi=function(e,s){t(this,Ys,"m",li).call(this,s);const i=new DataView(new ArrayBuffer(2*s.length));return s.forEach(((e,t)=>{i.setUint8(2*t,Math.floor(127*e.amplitude)),i.setUint8(2*t+1,Math.floor(e.duration/10))})),mi.log({dataView:i}),t(this,Ys,"m",di).call(this,e,"waveform",i)},ui=function(e){mi.assertTypeWithError(e,"string"),mi.assertWithError(vi.includes(e),`invalid vibrationType "${e}"`)},di=function(e,s,i){mi.assertWithError(i?.byteLength>0,"no data received");const n=t(this,Ys,"m",si).call(this,e);t(this,Ys,"m",ui).call(this,s);const r=vi.indexOf(s);mi.log({locationsBitmask:n,vibrationTypeIndex:r,dataView:i});const a=z(n,r,i.byteLength,i);return mi.log({data:a}),a};const xi=T("BaseConnectionManager",{log:!0}),Ai=["notConnected","connecting","connected","disconnecting"],Oi=[...Ai,"connectionStatus","isConnected"],$i=[...Qs,...Rt,...vt,"triggerVibration",...ds,...Le],Bi=["batteryLevel"],Ni=["rx","tx"],Pi=[...Bi,...Ds,...Ni,...$i,"smp"];class Vi{get baseConstructor(){return this.constructor}static get isSupported(){return!1}get isSupported(){return this.baseConstructor.isSupported}get type(){return this.baseConstructor.type}constructor(){Si.add(this),Di.set(this,"notConnected"),Fi.set(this,[]),Li.set(this,new R(t(this,Si,"m",Ri).bind(this),5e3)),t(this,Si,"m",Mi).call(this)}get status(){return t(this,Di,"f")}set status(e){xi.assertEnumWithError(e,Ai),t(this,Di,"f")!=e?(xi.log(`new connection status "${e}"`),s(this,Di,e,"f"),this.onStatusUpdated(this.status),this.isConnected?t(this,Li,"f").start():t(this,Li,"f").stop(),"notConnected"==t(this,Di,"f")&&(this.mtu=void 0)):xi.log(`tried to assign same connection status "${e}"`)}get isConnected(){return"connected"==this.status}async connect(){t(this,Si,"m",ki).call(this),t(this,Si,"m",Ti).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){t(this,Si,"m",ki).call(this),t(this,Si,"m",Ti).call(this),xi.assert(this.canReconnect,"unable to reconnect")}async disconnect(){t(this,Si,"m",Wi).call(this),t(this,Si,"m",_i).call(this),this.status="disconnecting",xi.log("disconnecting from device...")}async sendSmpMessage(e){t(this,Si,"m",Ii).call(this),xi.log("sending smp message",e)}async sendTxMessages(e,s=!0){if(t(this,Si,"m",Ii).call(this),e&&t(this,Fi,"f").push(...e),!s)return;xi.log("sendTxMessages",t(this,Fi,"f").slice());const i=t(this,Fi,"f").map((e=>{t(Ei,Ei,"m",Ci).call(Ei,e.type);const s=$i.indexOf(e.type),i=new DataView(new ArrayBuffer(2));return i.setUint16(0,e.data?.byteLength||0,!0),z(s,i,e.data)}));if(this.mtu)for(;i.length>0;){let e=0,t=0;i.some((s=>{if(e+s.byteLength>this.mtu-3)return!0;t++,e+=s.byteLength}));const s=i.splice(0,t);xi.log({arrayBufferCount:t,arrayBuffersToSend:s});const n=z(...s);xi.log("sending arrayBuffer",n),await this.sendTxData(n)}else{const e=z(...i);xi.log("sending arrayBuffer",e),await this.sendTxData(e)}t(this,Fi,"f").length=0}async sendTxData(e){xi.log("sendTxData",e)}parseRxMessage(e){ft(e,$i,t(this,Si,"m",Ui).bind(this),null,!0)}}Ei=Vi,Di=new WeakMap,Fi=new WeakMap,Li=new WeakMap,Si=new WeakSet,Ci=function(e){xi.assertEnumWithError(e,$i)},Mi=function(){xi.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},ki=function(){xi.assertWithError(!this.isConnected,"device is already connected")},Ti=function(){xi.assertWithError("connecting"!=this.status,"device is already connecting")},Wi=function(){xi.assertWithError(this.isConnected,"device is not connected")},_i=function(){xi.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},Ii=function(){t(this,Si,"m",Wi).call(this),t(this,Si,"m",_i).call(this)},Ui=function(e,t){xi.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},Ri=function(){this.isConnected||(xi.log("timer detected disconnection"),this.status="notConnected")};const zi=T("EventUtils",{log:!1});function ji(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;zi.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function qi(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;zi.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const Gi=T("bluetoothUUIDs",{log:!1});if(n)var Hi=window.BluetoothUUID;function Ji(e){return Gi.assertTypeWithError(e,"string"),Gi.assertWithError(4==e.length,"value must be 4 characters long"),`ea6da725-${e}-4f9b-893d-c3913e33b39f`}function Qi(e){return Hi?.getCharacteristic?.(e)}function Ki(e){return Hi?.getService?.(e)}const Zi=Object.freeze({services:{deviceInformation:{uuid:Ki("device_information"),characteristics:{manufacturerName:{uuid:Qi("manufacturer_name_string")},modelNumber:{uuid:Qi("model_number_string")},hardwareRevision:{uuid:Qi("hardware_revision_string")},firmwareRevision:{uuid:Qi("firmware_revision_string")},softwareRevision:{uuid:Qi("software_revision_string")},pnpId:{uuid:Qi("pnp_id")},serialNumber:{uuid:Qi("serial_number_string")}}},battery:{uuid:Ki("battery_service"),characteristics:{batteryLevel:{uuid:Qi("battery_level")}}},main:{uuid:Ji("0000"),characteristics:{rx:{uuid:Ji("1000")},tx:{uuid:Ji("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),Xi=[Zi.services.main.uuid],Yi=[Zi.services.deviceInformation.uuid,Zi.services.battery.uuid,Zi.services.smp.uuid];function en(e){e=e.toString().toLowerCase();return Object.keys(Zi.services).find((t=>{let s=Zi.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const tn=[],sn=[];function nn(e){var t;return e=e.toString().toLowerCase(),Object.values(Zi.services).some((s=>{const i=Object.keys(s.characteristics);return t=i.find((t=>{let i=s.characteristics[t].uuid.toString();return 4==e.length&&(i=i.slice(4,8)),e.includes("-")||(i=i.replaceAll("-","")),e==i}))})),t}function rn(e){const t={broadcast:!1,read:!0,writeWithoutResponse:!1,write:!1,notify:!1,indicate:!1,authenticatedSignedWrites:!1,reliableWrite:!1,writableAuxiliaries:!1};switch(e){case"rx":case"tx":case"smp":t.read=!1}switch(e){case"batteryLevel":case"rx":case"smp":t.notify=!0}if("smp"===e)t.writeWithoutResponse=!0;if("tx"===e)t.write=!0;return t}Object.values(Zi.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];Xi.includes(e.uuid)&&(tn.push(i.uuid),t.push(s)),sn.push(i.uuid)}))}),[]);const an=T("BluetoothConnectionManager",{log:!0});class on extends Vi{constructor(){super(...arguments),this.isInRange=!0}onCharacteristicValueChanged(e,t){"rx"==e?this.parseRxMessage(t):this.onMessageReceived?.(e,t)}async writeCharacteristic(e,t){an.log("writeCharacteristic",...arguments)}async sendSmpMessage(e){super.sendSmpMessage(e),await this.writeCharacteristic("smp",e)}async sendTxData(e){super.sendTxData(e),await this.writeCharacteristic("tx",e)}}var cn,hn,ln,gn,fn,un,dn,mn,pn,vn,wn;const yn=T("WebBluetoothConnectionManager",{log:!0});var bn;n&&(bn=window.navigator.bluetooth);class Sn extends on{constructor(){super(...arguments),cn.add(this),hn.set(this,{characteristicvaluechanged:t(this,cn,"m",pn).bind(this)}),ln.set(this,{gattserverdisconnected:t(this,cn,"m",wn).bind(this)}),gn.set(this,void 0),fn.set(this,new Map),un.set(this,new Map)}get bluetoothId(){return this.device.id}static get isSupported(){return Boolean(bn)}static get type(){return"webBluetooth"}get device(){return t(this,gn,"f")}set device(e){t(this,gn,"f")!=e?(t(this,gn,"f")&&qi(t(this,gn,"f"),t(this,ln,"f")),e&&ji(e,t(this,ln,"f")),s(this,gn,e,"f")):yn.log("tried to assign the same BluetoothDevice")}get server(){return t(this,gn,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const e=await bn.requestDevice({filters:[{services:Xi}],optionalServices:n?Yi:[]});yn.log("got BluetoothDevice"),this.device=e,yn.log("connecting to device...");const s=await this.server.connect();yn.log(`connected to device? ${s.connected}`),await t(this,cn,"m",dn).call(this),yn.log("fully connected"),this.status="connected"}catch(e){yn.error(e),this.status="notConnected",this.server?.disconnect(),t(this,cn,"m",mn).call(this)}}async disconnect(){await t(this,cn,"m",mn).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(e,s){super.writeCharacteristic(e,s);const i=t(this,un,"f").get(e);yn.assertWithError(i,`${e} characteristic not found`),yn.log("writing characteristic",i,s);const n=i.properties||rn(e);n.writeWithoutResponse?(yn.log("writing without response"),await i.writeValueWithoutResponse(s)):(yn.log("writing with response"),await i.writeValueWithResponse(s)),yn.log("wrote characteristic"),n.read&&!n.notify&&(yn.log("reading value after write..."),await i.readValue(),(c||h)&&t(this,cn,"m",vn).call(this,i))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect(),yn.log("attempting to reconnect..."),this.status="connecting";try{await this.server.connect()}catch(e){yn.error(e),this.isInRange=!1}this.isConnected?(yn.log("successfully reconnected!"),await t(this,cn,"m",dn).call(this),this.status="connected"):(yn.log("unable to reconnect"),this.status="notConnected")}}hn=new WeakMap,ln=new WeakMap,gn=new WeakMap,fn=new WeakMap,un=new WeakMap,cn=new WeakSet,dn=async function(){t(this,cn,"m",mn).call(this),yn.log("getting services...");const e=await this.server.getPrimaryServices();yn.log("got services",e.length),await this.server.getPrimaryService("8d53dc1d-1db7-4cd3-868b-8a527460aa84"),yn.log("getting characteristics...");for(const s in e){const i=e[s];yn.log({service:i});const n=en(i.uuid);yn.assertWithError(n,`no name found for service uuid "${i.uuid}"`),yn.log(`got "${n}" service`),i.name=n,t(this,fn,"f").set(n,i),yn.log(`getting characteristics for "${n}" service`);const r=await i.getCharacteristics();yn.log(`got characteristics for "${n}" service`);for(const e in r){const s=r[e];yn.log({characteristic:s});const i=nn(s.uuid);yn.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),yn.log(`got "${i}" characteristic in "${n}" service`),s.name=i,t(this,un,"f").set(i,s),ji(s,t(this,hn,"f"));const a=s.properties||rn(i);a.notify&&(yn.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),a.read&&(yn.log(`reading "${i}" characteristic...`),await s.readValue(),(c||h)&&t(this,cn,"m",vn).call(this,s))}}},mn=async function(){this.device&&qi(this.device,t(this,ln,"f"));const e=Array.from(t(this,un,"f").keys()).map((e=>{const s=t(this,un,"f").get(e);qi(s,t(this,hn,"f"));if((s.properties||rn(e)).notify)return yn.log(`stopping notifications for "${e}" characteristic`),s.stopNotifications()}));return Promise.allSettled(e)},pn=function(e){yn.log("oncharacteristicvaluechanged");const s=e.target;t(this,cn,"m",vn).call(this,s)},vn=function(e){yn.log("onCharacteristicValue");const t=e.name;yn.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),yn.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;yn.assertWithError(s,`no data found for "${t}" characteristic`),yn.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){yn.error(e)}},wn=function(){yn.log("gattserverdisconnected"),this.status="notConnected"};const En=4294967296,Cn=9007199254740992;const Mn={encode:function(e){let t,s=new ArrayBuffer(256),i=new DataView(s),n=0;function r(e){let r=s.byteLength;const a=n+e;for(;r<a;)r<<=1;if(r!==s.byteLength){const e=i;s=new ArrayBuffer(r),i=new DataView(s);const t=n+3>>2;for(let s=0;s<t;++s)i.setUint32(s<<2,e.getUint32(s<<2))}return t=e,i}function a(){n+=t}function o(e){a(r(1).setUint8(n,e))}function c(e){const t=r(e.length);for(let s=0;s<e.length;++s)t.setUint8(n+s,e[s]);a()}function h(e,t){t<24?o(e<<5|t):t<256?(o(e<<5|24),o(t)):t<65536?(o(e<<5|25),function(e){a(r(2).setUint16(n,e))}(t)):t<4294967296?(o(e<<5|26),function(e){a(r(4).setUint32(n,e))}(t)):(o(e<<5|27),function(e){const t=e%En,s=(e-t)/En,i=r(8);i.setUint32(n,s),i.setUint32(n+4,t),a()}(t))}if(function e(t){let s;const i=[];let l;if(!1===t)return o(244);if(!0===t)return o(245);if(null===t)return o(246);if(void 0===t)return o(247);switch(typeof t){case"number":if(Math.floor(t)===t){if(t>=0&&t<=Cn)return h(0,t);if(-Cn<=t&&t<0)return h(1,-(t+1))}return o(251),function(e){a(r(8).setFloat64(n,e))}(t);case"string":for(s=0;s<t.length;++s){let e=t.charCodeAt(s);e<128?i.push(e):e<2048?(i.push(192|e>>6),i.push(128|63&e)):e<55296?(i.push(224|e>>12),i.push(128|e>>6&63),i.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++s),e+=65536,i.push(240|e>>18),i.push(128|e>>12&63),i.push(128|e>>6&63),i.push(128|63&e))}return h(3,i.length),c(i);default:if(Array.isArray(t))for(l=t.length,h(4,l),s=0;s<l;++s)e(t[s]);else if(t instanceof Uint8Array)h(2,t.length),c(t);else{const i=Object.keys(t);for(l=i.length,h(5,l),s=0;s<l;++s){const n=i[s];e(n),e(t[n])}}}}(e),"slice"in s)return s.slice(0,n);const l=new ArrayBuffer(n),g=new DataView(l);for(let e=0;e<n;++e)g.setUint8(e,i.getUint8(e));return l},decode:function(e,t,s){const i=new DataView(e);let n=0;function r(e,t){return n+=e,t}function a(t){return r(t,new Uint8Array(e,n,t))}function o(){return r(1,i.getUint8(n))}function c(){return r(2,i.getUint16(n))}function h(){return r(4,i.getUint32(n))}function l(){return 255===i.getUint8(n)&&(n+=1,!0)}function g(e){if(e<24)return e;if(24===e)return o();if(25===e)return c();if(26===e)return h();if(27===e)return h()*En+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function f(e){const t=o();if(255===t)return-1;const s=g(31&t);if(s<0||t>>5!==e)throw new Error("Invalid indefinite length element");return s}function u(e,t){for(let s=0;s<t;++s){let s=o();128&s&&(s<224?(s=(31&s)<<6|63&o(),t-=1):s<240?(s=(15&s)<<12|(63&o())<<6|63&o(),t-=2):(s=(15&s)<<18|(63&o())<<12|(63&o())<<6|63&o(),t-=3)),s<65536?e.push(s):(s-=65536,e.push(55296|s>>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof s&&(s=function(){});const d=function e(){const h=o(),d=h>>5,m=31&h;let p,v;if(7===d)switch(m){case 25:return function(){const e=new ArrayBuffer(4),t=new DataView(e),s=c(),i=32768&s;let n=31744&s;const r=1023&s;if(31744===n)n=261120;else if(0!==n)n+=114688;else if(0!==r)return(i?-1:1)*r*5.960464477539063e-8;return t.setUint32(0,i<<16|n<<13|r<<13),t.getFloat32(0)}();case 26:return r(4,i.getFloat32(n));case 27:return r(8,i.getFloat64(n))}if(v=g(m),v<0&&(d<2||d>6))throw new Error("Invalid length");const w=[];let y;const b={};switch(d){case 0:return v;case 1:return-1-v;case 2:if(v<0){const e=[];let t=0;for(;(v=f(d))>=0;)t+=v,e.push(a(v));const s=new Uint8Array(t);let i=0;for(p=0;p<e.length;++p)s.set(e[p],i),i+=e[p].length;return s}return a(v);case 3:if(v<0)for(;(v=f(d))>=0;)u(w,v);else u(w,v);return String.fromCharCode.apply(null,w);case 4:if(v<0)for(y=[];!l();)y.push(e());else for(y=new Array(v),p=0;p<v;++p)y[p]=e();return y;case 5:for(p=0;p<v||v<0&&!l();++p){b[e()]=e()}return b;case 6:return t(e(),v);case 7:switch(v){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return s(v)}}}();if(n!==e.byteLength)throw new Error("Remaining bytes");return d}},Dn=T("mcumgr",{log:!0}),kn=0,Tn=1,Wn=2,_n=3,In=0,Fn=1,Un=8,Ln=0,Rn=2,xn=3,An=5,On=0,$n=1,Bn=5,Nn=0;class Pn{constructor(){this._mtu=256,this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}onMessage(e){return this._messageCallback=e,this}onImageUploadNext(e){return this._imageUploadNextCallback=e,this}onImageUploadProgress(e){return this._imageUploadProgressCallback=e,this}onImageUploadFinished(e){return this._imageUploadFinishedCallback=e,this}onFileUploadNext(e){return this._fileUploadNextCallback=e,this}onFileUploadProgress(e){return this._fileUploadProgressCallback=e,this}onFileUploadFinished(e){return this._fileUploadFinishedCallback=e,this}onFileDownloadNext(e){return this._fileDownloadNextCallback=e,this}onFileDownloadProgress(e){return this._fileDownloadProgressCallback=e,this}onFileDownloadFinished(e){return this._fileDownloadFinishedCallback=e,this}_getMessage(e,t,s,i){let n=[];void 0!==i&&(n=[...new Uint8Array(Mn.encode(i))]);const r=255&n.length,a=[e,0,n.length>>8,r,t>>8,255&t,this._seq,s,...n];return this._seq=(this._seq+1)%256,a}_notification(e){Dn.log("mcumgr - message received");const t=new Uint8Array(e);this._buffer=new Uint8Array([...this._buffer,...t]);const s=256*this._buffer[2]+this._buffer[3];this._buffer.length<s+8||(this._processMessage(this._buffer.slice(0,s+8)),this._buffer=this._buffer.slice(s+8))}_processMessage(e){const[t,,s,i,n,r,,a]=e,o=Mn.decode(e.slice(8).buffer),c=256*s+i,h=256*n+r;return Dn.log("mcumgr - Process Message - Group: "+h+", Id: "+a+", Off: "+o.off),h===Fn&&a===$n&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===_n&&h===Un&&a===Nn&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===Tn&&h===Un&&a===Nn?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Dn.log("downloaded "+this._downloadFileOffset+" bytes of "+this._downloadFileLength),this._downloadFileLength>0&&this._fileDownloadProgressCallback({percentage:Math.floor(this._downloadFileOffset/this._downloadFileLength*100)}),this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}),void this._downloadFileNext()):void(this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}))}cmdReset(){return this._getMessage(Wn,In,An)}smpEcho(e){return this._getMessage(Wn,In,Ln,{d:e})}cmdImageState(){return this._getMessage(kn,Fn,On)}cmdImageErase(){return this._getMessage(Wn,Fn,Bn,{})}cmdImageTest(e){return this._getMessage(Wn,Fn,On,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(Wn,Fn,On,{hash:e,confirm:!0})}_hash(e){return crypto.subtle.digest("SHA-256",e)}async _uploadNext(){if(!this._uploadImage)return;if(this._uploadOffset>=this._uploadImage.byteLength)return this._uploadIsInProgress=!1,void this._imageUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadOffset};0===this._uploadOffset&&(e.len=this._uploadImage.byteLength,e.sha=new Uint8Array(await this._hash(this._uploadImage))),this._imageUploadProgressCallback({percentage:Math.floor(this._uploadOffset/this._uploadImage.byteLength*100)});const t=this._mtu-Mn.encode(e).byteLength-8-3-5;e.data=new Uint8Array(this._uploadImage.slice(this._uploadOffset,this._uploadOffset+t)),this._uploadOffset+=t;const s=this._getMessage(Wn,Fn,$n,e);Dn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._imageUploadNextCallback({packet:s})}async reset(){this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}async cmdUpload(e,t=0){this._uploadIsInProgress?Dn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadOffset=0,this._uploadImage=e,this._uploadSlot=t,this._uploadNext())}async cmdUploadFile(e,t){this._uploadIsInProgress?Dn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Dn.log("uploadFileNext - offset: "+this._uploadFileOffset+", length: "+this._uploadFile.byteLength),this._uploadFileOffset>=this._uploadFile.byteLength)return this._uploadIsInProgress=!1,void this._fileUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadFileOffset};0===this._uploadFileOffset&&(e.len=this._uploadFile.byteLength),e.name=this._uploadFilename,this._fileUploadProgressCallback({percentage:Math.floor(this._uploadFileOffset/this._uploadFile.byteLength*100)});const t=this._mtu-Mn.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(Wn,Un,Nn,e);Dn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Dn.error("Download is already in progress."):(this._downloadIsInProgress=!0,this._downloadFileOffset=0,this._downloadFileLength=0,this._downloadRemoteFilename=e,this._downloadLocalFilename=t,this._downloadFileNext())}async _downloadFileNext(){if(this._downloadFileLength>0&&this._downloadFileOffset>=this._downloadFileLength)return this._downloadIsInProgress=!1,void this._fileDownloadFinishedCallback();const e={off:this._downloadFileOffset};0===this._downloadFileOffset&&(e.name=this._downloadRemoteFilename);const t=this._getMessage(kn,Un,Nn,e);Dn.log("mcumgr - _downloadNext: Message Length: "+t.length),this._fileDownloadNextCallback({packet:t})}async imageInfo(e){const t={},s=new Uint8Array(e);if(s.length<32)throw new Error("Invalid image (too short file)");if(61!==s[0]||184!==s[1]||243!==s[2]||150!==s[3])throw new Error("Invalid image (wrong magic bytes)");if(0!==s[4]||0!==s[5]||0!==s[6]||0!==s[7])throw new Error("Invalid image (wrong load address)");const i=s[8]+256*s[9];if(0!==s[10]||0!==s[11])throw new Error("Invalid image (wrong protected TLV area size)");const n=s[12]+256*s[13]+65536*s[14]+s[15]*2**24;if(t.imageSize=n,s.length<n+i)throw new Error("Invalid image (wrong image size)");if(0!==s[16]||0!==s[17]||0!==s[18]||0!==s[19])throw new Error("Invalid image (wrong flags)");const r=`${s[20]}.${s[21]}.${s[22]+256*s[23]}`;return t.version=r,t.hash=[...new Uint8Array(await this._hash(e.slice(0,n+32)))].map((e=>e.toString(16).padStart(2,"0"))).join(""),t}}var Vn,zn,jn,qn,Gn,Hn,Jn,Qn,Kn,Zn,Xn,Yn,er,tr,sr,ir,nr,rr,ar,or,cr;const hr=T("FirmwareManager",{log:!0}),lr=["smp"],gr=[...lr,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],fr=["idle","uploading","uploaded","pending","testing","erasing"];class ur{constructor(){Vn.add(this),jn.set(this,"idle"),Gn.set(this,void 0),Qn.set(this,void 0),Kn.set(this,new Pn),t(this,Vn,"m",Zn).call(this),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(e,s){if(hr.log({messageType:e}),"smp"!==e)throw Error(`uncaught messageType ${e}`);t(this,Kn,"f")._notification(Array.from(new Uint8Array(s.buffer))),t(this,Vn,"a",zn).call(this,"smp",{dataView:s})}async uploadFirmware(e){hr.log("uploadFirmware",e);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await G(e),n=await t(this,Kn,"f").imageInfo(i);hr.log({imageInfo:n}),t(this,Kn,"f").cmdUpload(i,1),t(this,Vn,"m",qn).call(this,"uploading"),await s}get status(){return t(this,jn,"f")}get images(){return t(this,Gn,"f")}async getImages(){const e=this.waitForEvent("firmwareImages");hr.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageState()).buffer),await e}async testImage(e=1){if(t(this,Vn,"m",Jn).call(this,e),t(this,Vn,"m",Hn).call(this),!t(this,Gn,"f")[e])return void hr.log(`image ${e} not found`);if(1==t(this,Gn,"f")[e].pending)return void hr.log(`image ${e} is already pending`);if(t(this,Gn,"f")[e].empty)return void hr.log(`image ${e} is empty`);const s=this.waitForEvent("smp");hr.log("testing firmware image..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageTest(t(this,Gn,"f")[e].hash)).buffer),await s}async eraseImage(){t(this,Vn,"m",Hn).call(this);const e=this.waitForEvent("smp");hr.log("erasing image..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageErase()).buffer),t(this,Vn,"m",qn).call(this,"erasing"),await e,await this.getImages()}async confirmImage(e=0){if(t(this,Vn,"m",Jn).call(this,e),t(this,Vn,"m",Hn).call(this),!0===t(this,Gn,"f")[e].confirmed)return void hr.log(`image ${e} is already confirmed`);const s=this.waitForEvent("smp");hr.log("confirming image..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageConfirm(t(this,Gn,"f")[e].hash)).buffer),await s}async echo(e){hr.assertTypeWithError(e,"string");const s=this.waitForEvent("smp");hr.log("sending echo..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").smpEcho(e)).buffer),await s}async reset(){const e=this.waitForEvent("smp");hr.log("resetting..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdReset()).buffer),await e}get mtu(){return t(this,Qn,"f")}set mtu(e){s(this,Qn,e,"f"),t(this,Kn,"f")._mtu=e}}var dr,mr,pr,vr,wr,yr,br,Sr,Er,Cr,Mr,Dr,kr,Tr,Wr,_r,Ir,Fr;jn=new WeakMap,Gn=new WeakMap,Qn=new WeakMap,Kn=new WeakMap,Vn=new WeakSet,zn=function(){return this.eventDispatcher.dispatchEvent},qn=function(e){hr.assertEnumWithError(e,fr),t(this,jn,"f")!=e?(s(this,jn,e,"f"),hr.log({firmwareStatus:t(this,jn,"f")}),t(this,Vn,"a",zn).call(this,"firmwareStatus",{firmwareStatus:t(this,jn,"f")})):hr.log(`redundant firmwareStatus assignment "${e}"`)},Hn=function(){hr.assertWithError(t(this,Gn,"f"),"didn't get imageState")},Jn=function(e){hr.assertTypeWithError(e,"number"),hr.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},Zn=function(){t(this,Kn,"f").onMessage(t(this,Vn,"m",Xn).bind(this)),t(this,Kn,"f").onFileDownloadNext(t(this,Vn,"m",Yn)),t(this,Kn,"f").onFileDownloadProgress(t(this,Vn,"m",er).bind(this)),t(this,Kn,"f").onFileDownloadFinished(t(this,Vn,"m",tr).bind(this)),t(this,Kn,"f").onFileUploadNext(t(this,Vn,"m",sr).bind(this)),t(this,Kn,"f").onFileUploadProgress(t(this,Vn,"m",ir).bind(this)),t(this,Kn,"f").onFileUploadFinished(t(this,Vn,"m",nr).bind(this)),t(this,Kn,"f").onImageUploadNext(t(this,Vn,"m",rr).bind(this)),t(this,Kn,"f").onImageUploadProgress(t(this,Vn,"m",ar).bind(this)),t(this,Kn,"f").onImageUploadFinished(t(this,Vn,"m",or).bind(this))},Xn=function({op:e,group:s,id:i,data:n,length:r}){switch(hr.log("onMcuMessage",...arguments),s){case In:switch(i){case Ln:hr.log(`echo "${n.r}"`);break;case Rn:hr.table(n.tasks);break;case xn:hr.log(n)}break;case Fn:if(i===On)t(this,Vn,"m",cr).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},Yn=function(){hr.log("onMcuFileDownloadNext",...arguments)},er=function(){hr.log("onMcuFileDownloadProgress",...arguments)},tr=function(){hr.log("onMcuFileDownloadFinished",...arguments)},sr=function(){hr.log("onMcuFileUploadNext")},ir=function(){hr.log("onMcuFileUploadProgress")},nr=function(){hr.log("onMcuFileUploadFinished")},rr=function({packet:e}){hr.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},ar=function({percentage:e}){const s=e/100;hr.log("onMcuImageUploadProgress",...arguments),t(this,Vn,"a",zn).call(this,"firmwareUploadProgress",{progress:s})},or=async function(){hr.log("onMcuImageUploadFinished",...arguments),await this.getImages(),t(this,Vn,"a",zn).call(this,"firmwareUploadProgress",{progress:100}),t(this,Vn,"a",zn).call(this,"firmwareUploadComplete",{})},cr=function({images:e}){if(!e)return void hr.log("no images found");s(this,Gn,e,"f"),hr.log("images",t(this,Gn,"f"));let i="idle";2==t(this,Gn,"f").length&&(t(this,Gn,"f")[1].bootable?t(this,Gn,"f")[0].confirmed?t(this,Gn,"f")[1].pending?(hr.log("reset to upload to the new firmware image"),i="pending"):(hr.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(hr.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):hr.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==t(this,Gn,"f").length&&(t(this,Gn,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),hr.log("Select a firmware upload image to upload to slot 1.")),t(this,Vn,"m",qn).call(this,i),t(this,Vn,"a",zn).call(this,"firmwareImages",{firmwareImages:t(this,Gn,"f")})};const Ur=T("DeviceManager",{log:!0}),Lr=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class Rr{constructor(){if(dr.add(this),mr.set(this,{getType:t(this,dr,"m",pr).bind(this),isConnected:t(this,dr,"m",_r).bind(this)}),vr.set(this,[]),wr.set(this,!1),yr.set(this,{devices:[]}),br.set(this,void 0),Er.set(this,"BS.Device"),kr.set(this,[]),Tr.set(this,new _(this,Lr)),Rr.shared&&this!=Rr.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(e){ji(e,t(this,mr,"f"))}OnDeviceConnectionStatusUpdated(e,s){if("notConnected"==s&&!e.canReconnect&&t(this,kr,"f").includes(e)){const s=t(this,kr,"f").indexOf(e);this.AvailableDevices.splice(s,1),t(this,dr,"m",Ir).call(this)}}get ConnectedDevices(){return t(this,vr,"f")}get UseLocalStorage(){return t(this,wr,"f")}set UseLocalStorage(e){t(this,dr,"m",Sr).call(this),Ur.assertTypeWithError(e,"boolean"),s(this,wr,e,"f"),t(this,wr,"f")&&!t(this,br,"f")&&t(this,dr,"m",Mr).call(this)}get CanUseLocalStorage(){return n&&window.localStorage}get AvailableDevices(){return t(this,kr,"f")}get CanGetDevices(){return n&&navigator.bluetooth?.getDevices}async GetDevices(){if(!n)return void Ur.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void Ur.warn("bluetooth is not available in this browser");if(c)return void Ur.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void Ur.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void Ur.log("CanGetDevices is false");t(this,br,"f")||t(this,dr,"m",Mr).call(this);const e=t(this,br,"f");if(!e.devices||0==e.devices.length)return void Ur.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return Ur.log({bluetoothDevices:s}),s.forEach((s=>{if(!s.gatt)return;let i=e.devices.find((e=>s.id==e.bluetoothId));if(!i)return;let n=this.ConnectedDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));const r=this.AvailableDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));if(r)return void(n&&n?.bluetoothId==r.bluetoothId&&n!=r&&(this.AvailableDevices[t(this,kr,"f").indexOf(r)]=n));if(n)return void this.AvailableDevices.push(n);const a=new Ma,o=new Sn;o.device=s,s.name&&a._informationManager.updateName(s.name),a._informationManager.updateType(i.type),a.connectionManager=o,this.AvailableDevices.push(a)})),t(this,dr,"m",Ir).call(this),this.AvailableDevices}get AddEventListener(){return t(this,Tr,"f").addEventListener}get RemoveEventListener(){return t(this,Tr,"f").removeEventListener}}mr=new WeakMap,vr=new WeakMap,wr=new WeakMap,yr=new WeakMap,br=new WeakMap,Er=new WeakMap,kr=new WeakMap,Tr=new WeakMap,dr=new WeakSet,pr=function(e){t(this,wr,"f")&&t(this,dr,"m",Dr).call(this,e.target)},Sr=function(){Ur.assertWithError(n,"localStorage is only available in the browser"),Ur.assertWithError(window.localStorage,"localStorage not found")},Cr=function(){t(this,dr,"m",Sr).call(this),localStorage.setItem(t(this,Er,"f"),JSON.stringify(t(this,br,"f")))},Mr=async function(){t(this,dr,"m",Sr).call(this);let e=localStorage.getItem(t(this,Er,"f"));if("string"!=typeof e)return Ur.log("no info found in localStorage"),s(this,br,Object.assign({},t(this,yr,"f")),"f"),void t(this,dr,"m",Cr).call(this);try{const t=JSON.parse(e);Ur.log({configuration:t}),s(this,br,t,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){Ur.error(e)}},Dr=function(e){if("webBluetooth"!=e.connectionType)return void Ur.log("localStorage is only for webBluetooth devices");t(this,dr,"m",Sr).call(this);const s=t(this,br,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1!=s&&(t(this,br,"f").devices[s].type=e.type,t(this,dr,"m",Cr).call(this))},Wr=function(){return t(this,Tr,"f").dispatchEvent},_r=function(e){const{target:s}=e;if(s.isConnected)if(t(this,vr,"f").includes(s))Ur.log("device already included");else{if(Ur.log("adding device",s),t(this,vr,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const e={type:s.type,bluetoothId:s.bluetoothId},i=t(this,br,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1==i?t(this,br,"f").devices.push(e):t(this,br,"f").devices[i]=e,t(this,dr,"m",Cr).call(this)}t(this,dr,"a",Wr).call(this,"deviceConnected",{device:s}),t(this,dr,"a",Wr).call(this,"deviceIsConnected",{device:s}),t(this,dr,"m",Fr).call(this)}else t(this,vr,"f").includes(s)?(Ur.log("removing device",s),t(this,vr,"f").splice(t(this,vr,"f").indexOf(s),1),t(this,dr,"a",Wr).call(this,"deviceDisconnected",{device:s}),t(this,dr,"a",Wr).call(this,"deviceIsConnected",{device:s}),t(this,dr,"m",Fr).call(this)):Ur.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),s.isConnected&&!this.AvailableDevices.includes(s)){const e=this.AvailableDevices.find((e=>e.bluetoothId==s.bluetoothId));Ur.log({existingAvailableDevice:e}),e?this.AvailableDevices[this.AvailableDevices.indexOf(e)]=s:this.AvailableDevices.push(s),t(this,dr,"m",Ir).call(this)}},Ir=function(){Ur.log({AvailableDevices:this.AvailableDevices}),t(this,dr,"a",Wr).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},Fr=function(){Ur.log({ConnectedDevices:this.ConnectedDevices}),t(this,dr,"a",Wr).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},Rr.shared=new Rr;var xr,Ar,Or,$r,Br,Nr,Pr,Vr,zr,jr,qr,Gr,Hr,Jr,Qr,Kr,Zr,Xr,Yr,ea,ta,sa,ia,na,ra,aa,oa,ca,ha,la,ga,fa,ua,da=Rr.shared;const ma=T("Device",{log:!0}),pa=["connectionMessage",...Oi,...Ni,...Bi,...Ks,...ks,...xt,...wt,...Oe,...ms,...gr],va=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getPressurePositions","maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus","getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"];class wa{get bluetoothId(){return t(this,Nr,"f")?.bluetoothId}constructor(){xr.add(this),$r.set(this,new _(this,pa)),Nr.set(this,void 0),this.sendTxMessages=t(this,xr,"m",Pr).bind(this),Vr.set(this,!1),Jr.set(this,Ar.ReconnectOnDisconnection),Qr.set(this,void 0),this.latestConnectionMessage=new Map,ta.set(this,new Ts),sa.set(this,0),this._informationManager=new Zs,na.set(this,new At),aa.set(this,Ar.ClearSensorConfigurationOnLeave),oa.set(this,new yt),ca.set(this,new bi),ha.set(this,new $e),la.set(this,new ws),ga.set(this,new ur),this.sendSmpMessage=t(this,xr,"m",fa).bind(this),ua.set(this,!1),t(this,ta,"f").eventDispatcher=t(this,$r,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=t(this,$r,"f"),t(this,na,"f").sendMessage=this.sendTxMessages,t(this,na,"f").eventDispatcher=t(this,$r,"f"),t(this,oa,"f").eventDispatcher=t(this,$r,"f"),t(this,ca,"f").sendMessage=this.sendTxMessages,t(this,la,"f").sendMessage=this.sendTxMessages,t(this,la,"f").eventDispatcher=t(this,$r,"f"),t(this,ha,"f").sendMessage=this.sendTxMessages,t(this,ha,"f").eventDispatcher=t(this,$r,"f"),t(this,ga,"f").sendMessage=this.sendSmpMessage,t(this,ga,"f").eventDispatcher=t(this,$r,"f"),this.addEventListener("getMtu",(()=>{t(this,ga,"f").mtu=this.mtu,t(this,ha,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),da.onDevice(this),n&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),r&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return t(this,$r,"f").addEventListener}get removeEventListener(){return t(this,$r,"f").removeEventListener}get waitForEvent(){return t(this,$r,"f").waitForEvent}get connectionManager(){return t(this,Nr,"f")}set connectionManager(e){this.connectionManager!=e?(this.connectionManager&&(this.connectionManager.onStatusUpdated=void 0,this.connectionManager.onMessageReceived=void 0),e&&(e.onStatusUpdated=t(this,xr,"m",Kr).bind(this),e.onMessageReceived=t(this,xr,"m",ea).bind(this)),s(this,Nr,e,"f"),ma.log("assigned new connectionManager",t(this,Nr,"f"))):ma.log("same connectionManager is already assigned")}async connect(){return this.connectionManager||(this.connectionManager=t(Ar,Ar,"m",Or).call(Ar)),t(this,xr,"m",Yr).call(this),this.connectionManager.connect()}get isConnected(){return t(this,Vr,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return t(this,xr,"m",Gr).call(this),t(this,xr,"m",Yr).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Ar;return await e.connect(),e}static get ReconnectOnDisconnection(){return t(this,Ar,"f",Hr)}static set ReconnectOnDisconnection(e){ma.assertTypeWithError(e,"boolean"),s(this,Ar,e,"f",Hr)}get reconnectOnDisconnection(){return t(this,Jr,"f")}set reconnectOnDisconnection(e){ma.assertTypeWithError(e,"boolean"),s(this,Jr,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return t(this,xr,"m",zr).call(this),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.addEventListener("isConnected",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this.connectionManager.disconnect()}toggleConnection(){this.isConnected?this.disconnect():this.canReconnect?this.reconnect():this.connect()}get connectionStatus(){switch(t(this,Nr,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return t(this,Nr,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return t(this,ta,"f").information}get batteryLevel(){return t(this,sa,"f")}get id(){return this._informationManager.id}get isCharging(){return this._informationManager.isCharging}get batteryCurrent(){return this._informationManager.batteryCurrent}get getBatteryCurrent(){return this._informationManager.getBatteryCurrent}get name(){return this._informationManager.name}get setName(){return this._informationManager.setName}get type(){return this._informationManager.type}get setType(){return this._informationManager.setType}get isInsole(){return this._informationManager.isInsole}get insoleSide(){return this._informationManager.insoleSide}get mtu(){return this._informationManager.mtu}get sensorTypes(){return Object.keys(this.sensorConfiguration)}get continuousSensorTypes(){return pt.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return t(this,na,"f").configuration}async setSensorConfiguration(e,s){await t(this,na,"f").setConfiguration(e,s)}async clearSensorConfiguration(){return t(this,na,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return t(this,Ar,"f",ra)}static set ClearSensorConfigurationOnLeave(e){ma.assertTypeWithError(e,"boolean"),s(this,Ar,e,"f",ra)}get clearSensorConfigurationOnLeave(){return t(this,aa,"f")}set clearSensorConfigurationOnLeave(e){ma.assertTypeWithError(e,"boolean"),s(this,aa,e,"f")}get numberOfPressureSensors(){return t(this,oa,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){t(this,oa,"f").pressureSensorDataManager.resetRange()}async triggerVibration(e,s){t(this,ca,"f").triggerVibration(e,s)}get maxFileLength(){return t(this,ha,"f").maxLength}async sendFile(e,s){const i=this.waitForEvent("fileTransferComplete");t(this,ha,"f").send(e,s),await i}async receiveFile(e){const s=this.waitForEvent("fileTransferComplete");t(this,ha,"f").receive(e),await s}get fileTransferStatus(){return t(this,ha,"f").status}cancelFileTransfer(){t(this,ha,"f").cancel()}get tfliteName(){return t(this,la,"f").name}get setTfliteName(){return t(this,la,"f").setName}get tfliteTask(){return t(this,la,"f").task}get setTfliteTask(){return t(this,la,"f").setTask}get tfliteSampleRate(){return t(this,la,"f").sampleRate}get setTfliteSampleRate(){return t(this,la,"f").setSampleRate}get tfliteSensorTypes(){return t(this,la,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>vs.includes(e)))}get setTfliteSensorTypes(){return t(this,la,"f").setSensorTypes}get tfliteIsReady(){return t(this,la,"f").isReady}get tfliteInferencingEnabled(){return t(this,la,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return t(this,la,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return t(this,la,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return t(this,la,"f").captureDelay}get setTfliteCaptureDelay(){return t(this,la,"f").setCaptureDelay}get tfliteThreshold(){return t(this,la,"f").threshold}get setTfliteThreshold(){return t(this,la,"f").setThreshold}get uploadFirmware(){return t(this,ga,"f").uploadFirmware}async reset(){return await t(this,ga,"f").reset(),t(this,Nr,"f").disconnect()}get firmwareStatus(){return t(this,ga,"f").status}get getFirmwareImages(){return t(this,ga,"f").getImages}get firmwareImages(){return t(this,ga,"f").images}get eraseFirmwareImage(){return t(this,ga,"f").eraseImage}get confirmFirmwareImage(){return t(this,ga,"f").confirmImage}get testFirmwareImage(){return t(this,ga,"f").testImage}get isServerSide(){return t(this,ua,"f")}set isServerSide(e){t(this,ua,"f")!=e?(ma.log({newIsServerSide:e}),s(this,ua,e,"f"),t(this,ha,"f").isServerSide=this.isServerSide):ma.log("redundant isServerSide assignment")}}Ar=wa,$r=new WeakMap,Nr=new WeakMap,Vr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,ta=new WeakMap,sa=new WeakMap,na=new WeakMap,aa=new WeakMap,oa=new WeakMap,ca=new WeakMap,ha=new WeakMap,la=new WeakMap,ga=new WeakMap,ua=new WeakMap,xr=new WeakSet,Or=function(){return new Sn},Br=function(){return t(this,$r,"f").dispatchEvent},Pr=async function(e,s){await(t(this,Nr,"f")?.sendTxMessages(e,s))},zr=function(){ma.assertWithError(this.isConnected,"notConnected")},jr=function(){return va.every((e=>this.latestConnectionMessage.has(e)))},qr=function(){const e=va.map((e=>({type:e})));t(this,xr,"m",Pr).call(this,e)},Gr=function(){ma.assertWithError(this.canReconnect,"cannot reconnect to device")},Kr=function(e){ma.log({connectionStatus:e}),"notConnected"==e?this.canReconnect&&this.reconnectOnDisconnection&&(ma.log("starting reconnect interval..."),s(this,Qr,setInterval((()=>{ma.log("attempting reconnect..."),this.reconnect()}),1e3),"f")):null!=t(this,Qr,"f")&&(ma.log("clearing reconnect interval"),clearInterval(t(this,Qr,"f")),s(this,Qr,void 0,"f")),t(this,xr,"m",Xr).call(this),"connected"!=e||t(this,Vr,"f")||t(this,xr,"m",qr).call(this),da.OnDeviceConnectionStatusUpdated(this,e)},Zr=function(e=!1){t(this,xr,"a",Br).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),t(this,xr,"a",Br).call(this,this.connectionStatus,{}),e&&t(this,xr,"a",Br).call(this,"isConnected",{isConnected:this.isConnected})},Xr=function(){switch(s(this,Vr,Boolean(this.connectionManager?.isConnected)&&t(this,xr,"a",jr)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":t(this,Vr,"f")&&t(this,xr,"m",Zr).call(this,!0);break;case"notConnected":t(this,xr,"m",Zr).call(this,!0);break;default:t(this,xr,"m",Zr).call(this,!1)}},Yr=function(){this.latestConnectionMessage.clear(),this._informationManager.clear(),t(this,ta,"f").clear()},ea=function(e,s){if(ma.log({messageType:e,dataView:s}),"batteryLevel"===e){const e=s.getUint8(0);ma.log("received battery level",{batteryLevel:e}),t(this,xr,"m",ia).call(this,e)}else if(Le.includes(e))t(this,ha,"f").parseMessage(e,s);else if(ds.includes(e))t(this,la,"f").parseMessage(e,s);else if(vt.includes(e))t(this,oa,"f").parseMessage(e,s);else if(lr.includes(e))t(this,ga,"f").parseMessage(e,s);else if(Ds.includes(e))t(this,ta,"f").parseMessage(e,s);else if(Qs.includes(e))this._informationManager.parseMessage(e,s);else{if(!Rt.includes(e))throw Error(`uncaught messageType ${e}`);t(this,na,"f").parseMessage(e,s)}this.latestConnectionMessage.set(e,s),t(this,xr,"a",Br).call(this,"connectionMessage",{messageType:e,dataView:s}),!this.isConnected&&t(this,xr,"a",jr)&&t(this,xr,"m",Xr).call(this)},ia=function(e){ma.assertTypeWithError(e,"number"),t(this,sa,"f")!=e?(s(this,sa,e,"f"),ma.log({updatedBatteryLevel:t(this,sa,"f")}),t(this,xr,"a",Br).call(this,"batteryLevel",{batteryLevel:t(this,sa,"f")})):ma.log(`duplicate batteryLevel assignment ${e}`)},fa=function(e){return t(this,Nr,"f").sendSmpMessage(e)},Hr={value:!1},ra={value:!0};var ya,ba,Sa,Ea,Ca,Ma=wa;const Da=T("DevicePairPressureSensorDataManager",{log:!0});class ka{constructor(){ya.add(this),ba.set(this,{}),Sa.set(this,new Qe)}resetPressureRange(){t(this,Sa,"f").reset()}onDevicePressureData(e){const{pressure:s}=e.message,i=e.target.insoleSide;if(Da.log({pressure:s,insoleSide:i}),t(this,ba,"f")[i]=s,t(this,ya,"a",Ea))return t(this,ya,"m",Ca).call(this);Da.log("doesn't have all pressure data yet...")}}var Ta;ba=new WeakMap,Sa=new WeakMap,ya=new WeakSet,Ea=function(){return Js.every((e=>e in t(this,ba,"f")))},Ca=function(){const e={rawSum:0,normalizedSum:0};return Js.forEach((s=>{e.rawSum+=t(this,ba,"f")[s].scaledSum,e.normalizedSum+=t(this,ba,"f")[s].normalizedSum})),e.normalizedSum>.001&&(e.center={x:0,y:0},Js.forEach((s=>{const i=t(this,ba,"f")[s],n=i.normalizedSum/e.normalizedSum;n>0&&(null!=i.normalizedCenter?.y&&(e.center.y+=i.normalizedCenter.y*n),"right"==s&&(e.center.x=n))})),e.normalizedCenter=t(this,Sa,"f").updateAndGetNormalization(e.center)),Da.log({devicePairPressure:e}),e};const Wa=T("DevicePairSensorDataManager",{log:!0}),_a=["pressure","sensorData"];class Ia{constructor(){Ta.set(this,{}),this.pressureSensorDataManager=new ka}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(e){const{timestamp:s,sensorType:i}=e.message;let n;if(Wa.log({sensorType:i,timestamp:s,event:e}),t(this,Ta,"f")[i]||(t(this,Ta,"f")[i]={}),t(this,Ta,"f")[i][e.target.insoleSide]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(e);else Wa.log(`uncaught sensorType "${i}"`);if(n){const e=Object.assign({},t(this,Ta,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:e,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:e,[i]:n})}else Wa.log("no value received")}}var Fa,Ua,La,Ra,xa,Aa,Oa,$a,Ba,Na,Pa,Va,za,ja,qa,Ga;Ta=new WeakMap;const Ha=T("DevicePair",{log:!0});function Ja(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const Qa=["isConnected",..._a,...pa.map((e=>Ja(e)))];class Ka{constructor(){Fa.add(this),La.set(this,new _(this,Qa)),xa.set(this,void 0),Aa.set(this,void 0),Na.set(this,{isConnected:t(this,Fa,"m",Va).bind(this),sensorData:t(this,Fa,"m",qa).bind(this),getType:t(this,Fa,"m",za).bind(this)}),ja.set(this,new Ia),t(this,ja,"f").eventDispatcher=t(this,La,"f")}get sides(){return Js}get addEventListener(){return t(this,La,"f").addEventListener}get removeEventListener(){return t(this,La,"f").removeEventListener}get waitForEvent(){return t(this,La,"f").waitForEvent}get left(){return t(this,xa,"f")}get right(){return t(this,Aa,"f")}get isConnected(){return Js.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return Js.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignInsole(e){if(!e.isInsole)return void Ha.warn("device is not an insole");const i=e.insoleSide,n=this[i];if(e!=n){switch(n&&t(this,Fa,"m",$a).call(this,n),t(this,Fa,"m",Oa).call(this,e),i){case"left":s(this,xa,e,"f");break;case"right":s(this,Aa,e,"f")}return Ha.log(`assigned ${i} insole`,e),this.resetPressureRange(),t(this,Fa,"a",Ra).call(this,"isConnected",{isConnected:this.isConnected}),t(this,Fa,"a",Ra).call(this,"deviceIsConnected",{device:e,isConnected:e.isConnected,side:i}),n}Ha.log("device already assigned")}setSensorConfiguration(e){Js.forEach((t=>{this[t]?.isConnected&&this[t]?.setSensorConfiguration(e)}))}resetPressureRange(){t(this,ja,"f").resetPressureRange()}async triggerVibration(e,t){const s=Js.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get shared(){return t(this,Ua,"f",Ga)}}Ua=Ka,La=new WeakMap,xa=new WeakMap,Aa=new WeakMap,Na=new WeakMap,ja=new WeakMap,Fa=new WeakSet,Ra=function(){return t(this,La,"f").dispatchEvent},Oa=function(e){ji(e,t(this,Na,"f")),pa.forEach((s=>{e.addEventListener(s,t(this,Fa,"m",Pa).bind(this))}))},$a=function(e){qi(e,t(this,Na,"f")),pa.forEach((s=>{e.removeEventListener(s,t(this,Fa,"m",Pa).bind(this))}))},Ba=function(e){const s=Js.some((s=>this[s]==e&&(Ha.log(`removing ${s} insole`,e),qi(e,t(this,Na,"f")),delete this[s],!0)));return s&&t(this,Fa,"a",Ra).call(this,"isConnected",{isConnected:this.isConnected}),s},Pa=function(e){const{type:s,target:i,message:n}=e;t(this,Fa,"a",Ra).call(this,Ja(s),{...n,device:i,side:i.insoleSide})},Va=function(e){t(this,Fa,"a",Ra).call(this,"isConnected",{isConnected:this.isConnected})},za=function(e){const{target:s}=e;if(this[s.insoleSide]==s)return;t(this,Fa,"m",Ba).call(this,s)&&this.assignInsole(s)},qa=function(e){this.isConnected&&t(this,ja,"f").onDeviceSensorData(e)},Ga={value:new Ua},da.AddEventListener("deviceConnected",(e=>{const{device:s}=e.message;s.isInsole&&t(Ua,Ua,"f",Ga).assignInsole(s)}));const Za=T("ServerUtils",{log:!1}),Xa=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage"];function Ya(e,...t){Za.log("createMessage",...t);const s=t.map((t=>{"string"==typeof t&&(t={type:t}),null!=t.data?Array.isArray(t.data)||(t.data=[t.data]):t.data=[];const s=z(...t.data),i=s.byteLength;Za.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),r=new DataView(new ArrayBuffer(2));return r.setUint16(0,i,!0),z(n,r,s)}));return Za.log("messageBuffers",...s),z(...s)}function eo(...e){return Za.log("createServerMessage",...e),Ya(Xa,...e)}function to(...e){return Za.log("createClientDeviceMessage",...e),Ya(Pi,...e)}var so,io,no,ro,ao;eo("isScanningAvailable"),eo("isScanning"),eo("startScan"),eo("stopScan"),eo("discoveredDevices");const oo=T("ClientConnectionManager",{log:!0}),co=[...Ds,"batteryLevel"];class ho extends Vi{constructor(){super(...arguments),so.add(this),io.set(this,void 0),no.set(this,!1)}static get isSupported(){return n}static get type(){return"client"}get bluetoothId(){return t(this,io,"f")}set bluetoothId(e){oo.assertTypeWithError(e,"string"),t(this,io,"f")!=e?s(this,io,e,"f"):oo.log("redundant bluetoothId assignment")}get isConnected(){return t(this,no,"f")}set isConnected(e){oo.assertTypeWithError(e,"boolean"),t(this,no,"f")!=e?(s(this,no,e,"f"),this.status=t(this,no,"f")?"connected":"notConnected",this.isConnected&&t(this,so,"m",ro).call(this)):oo.log("redundant newIsConnected assignment",e)}async connect(){await super.connect(),this.sendClientConnectMessage()}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),oo.log("attempting to reconnect..."),this.connect()}async sendSmpMessage(e){super.sendSmpMessage(e),this.sendClientMessage({type:"smp",data:e})}async sendTxData(e){super.sendTxData(e),this.sendClientMessage({type:"tx",data:e})}onClientMessage(e){oo.log({dataView:e}),ft(e,pa,t(this,so,"m",ao).bind(this),null,!0)}}var lo,go,fo,uo,mo,po,vo,wo,yo,bo,So,Eo,Co,Mo,Do,ko,To,Wo;io=new WeakMap,no=new WeakMap,so=new WeakSet,ro=function(){this.sendClientMessage(...co)},ao=function(e,t){let s=0;switch(oo.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));oo.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const _o=T("BaseClient",{log:!0}),Io=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class Fo{constructor(){lo.add(this),go.set(this,{}),fo.set(this,new _(this,Io)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,uo.set(this,"notConnected"),po.set(this,!1),bo.set(this,!1),ko.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return t(this,go,"f")}get addEventListener(){return t(this,fo,"f").addEventListener}get dispatchEvent(){return t(this,fo,"f").dispatchEvent}get removeEventListener(){return t(this,fo,"f").removeEventListener}get waitForEvent(){return t(this,fo,"f").waitForEvent}assertConnection(){_o.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){_o.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){_o.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){_o.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return t(this,uo,"f")}set _connectionStatus(e){switch(_o.assertTypeWithError(e,"string"),_o.log({newConnectionStatus:e}),s(this,uo,e,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),e){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected?this.sendServerMessage("isScanningAvailable","discoveredDevices","connectedDevices"):(s(this,lo,!1,"a",wo),s(this,lo,!1,"a",Eo))}}get connectionStatus(){return this._connectionStatus}parseMessage(e){_o.log("parseMessage",{dataView:e}),ft(e,Xa,t(this,lo,"m",mo).bind(this),null,!0)}get isScanningAvailable(){return t(this,lo,"a",vo)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return t(this,lo,"a",So)}startScan(){t(this,lo,"m",Do).call(this),this.sendServerMessage("startScan")}stopScan(){t(this,lo,"m",Mo).call(this),this.sendServerMessage("stopScan")}toggleScan(){t(this,lo,"m",yo).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return t(this,ko,"f")}onDiscoveredDevice(e){_o.log({discoveredDevice:e}),t(this,ko,"f")[e.bluetoothId]=e,this.dispatchEvent("discoveredDevice",{discoveredDevice:e})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e){return this.requestConnectionToDevice(e)}requestConnectionToDevice(e){this.assertConnection(),_o.assertTypeWithError(e,"string");const s=t(this,lo,"m",Wo).call(this,e);return s.connect(),s}sendConnectToDeviceMessage(e){this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const t=new Ma,s=new ho;return s.bluetoothId=e,s.sendClientMessage=this.sendDeviceMessage.bind(this,e),s.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,e),s.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,e),t.connectionManager=s,t}onConnectedBluetoothDeviceIds(e){_o.log({bluetoothIds:e}),e.forEach((e=>{t(this,lo,"m",Wo).call(this,e).connectionManager.isConnected=!0}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),_o.assertTypeWithError(e,"string");const t=this.devices[e];return _o.assertWithError(t,`no device found with id ${e}`),t.disconnect(),t}sendDisconnectFromDeviceMessage(e){this.sendServerMessage({type:"disconnectFromDevice",data:e})}sendDeviceMessage(e,...t){this.sendServerMessage({type:"deviceMessage",data:[e,to(...t)]})}}go=new WeakMap,fo=new WeakMap,uo=new WeakMap,po=new WeakMap,bo=new WeakMap,ko=new WeakMap,lo=new WeakSet,mo=function(e,i){let n=0;switch(_o.log({messageType:e},i),e){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));_o.log({isScanningAvailable:e}),s(this,lo,e,"a",wo)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));_o.log({isScanning:e}),s(this,lo,e,"a",Eo)}break;case"discoveredDevice":{const{string:e}=gt(i,n);_o.log({discoveredDeviceString:e});const t=JSON.parse(e);_o.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:e}=gt(i,n);t(this,lo,"m",To).call(this,e)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=gt(i,n);_o.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e);_o.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:e,byteOffset:s}=gt(i,n);n=s;const r=t(this,go,"f")[e];_o.assertWithError(r,`no device found for id ${e}`);const a=r.connectionManager,o=q(i,n);a.onClientMessage(o)}break;default:_o.error(`uncaught messageType "${e}"`)}},vo=function(){return t(this,po,"f")},wo=function(e){_o.assertTypeWithError(e,"boolean"),s(this,po,e,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&t(this,lo,"m",Co).call(this)},yo=function(){this.assertConnection(),_o.assertWithError(this.isScanningAvailable,"scanning is not available")},So=function(){return t(this,bo,"f")},Eo=function(e){_o.assertTypeWithError(e,"boolean"),s(this,bo,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},Co=function(){this.sendServerMessage("isScanning")},Mo=function(){_o.assertWithError(this.isScanning,"is not scanning")},Do=function(){_o.assertWithError(!this.isScanning,"is already scanning")},To=function(e){_o.log({expiredBluetoothDeviceId:e});const s=t(this,ko,"f")[e];s?(_o.log({expiredDiscoveredDevice:s}),delete t(this,ko,"f")[e],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):_o.warn(`no discoveredDevice found with id "${e}"`)},Wo=function(e){let s=t(this,go,"f")[e];return s||(s=this.createDevice(e),t(this,go,"f")[e]=s),s},Fo._reconnectOnDisconnection=!0;const Uo=T("WebSocketUtils",{log:!1}),Lo=["ping","pong","serverMessage"];function Ro(...e){return Uo.log("createWebSocketMessage",...e),Ya(Lo,...e)}var xo,Ao,Oo,$o,Bo,No,Po,Vo,zo,jo,qo,Go,Ho;Ro("ping"),Ro("pong");const Jo=T("WebSocketClient",{log:!0});Ao=new WeakMap,$o=new WeakMap,qo=new WeakMap,xo=new WeakSet,Oo=function(...e){this.sendMessage(Ro(...e))},Bo=function(e){Jo.log("webSocket.open",e),t(this,qo,"f").start(),this._connectionStatus="connected"},No=async function(e){Jo.log("webSocket.message",e),t(this,qo,"f").restart();const s=await e.data.arrayBuffer(),i=new DataView(s);t(this,xo,"m",zo).call(this,i)},Po=function(e){Jo.log("webSocket.close",e),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),t(this,qo,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},Vo=function(e){Jo.error("webSocket.error",e.message)},zo=function(e){ft(e,Lo,t(this,xo,"m",jo).bind(this),null,!0)},jo=function(e,s){switch(e){case"ping":t(this,xo,"m",Ho).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:Jo.error(`uncaught messageType "${e}"`)}},Go=function(){t(this,xo,"m",Oo).call(this,"ping")},Ho=function(){t(this,xo,"m",Oo).call(this,"pong")},e.ContinuousSensorTypes=pt,e.DefaultNumberOfPressureSensors=8,e.Device=Ma,e.DeviceManager=da,e.DevicePair=Ka,e.DeviceTypes=Hs,e.Environment=y,e.FileTransferDirections=["sending","receiving"],e.FileTypes=Re,e.InsoleSides=Js,e.MaxNameLength=30,e.MaxNumberOfVibrationWaveformEffectSegments=8,e.MaxNumberOfVibrationWaveformSegments=20,e.MaxSensorRate=65535,e.MaxVibrationWaveformEffectSegmentDelay=yi,e.MaxVibrationWaveformEffectSegmentLoopCount=3,e.MaxVibrationWaveformEffectSequenceLoopCount=6,e.MaxVibrationWaveformSegmentDuration=wi,e.MinNameLength=2,e.SensorRateStep=5,e.SensorTypes=mt,e.TfliteSensorTypes=vs,e.TfliteTasks=ps,e.VibrationLocations=pi,e.VibrationTypes=vi,e.VibrationWaveformEffects=Xs,e.WebSocketClient=class extends Fo{constructor(){super(...arguments),xo.add(this),Ao.set(this,void 0),$o.set(this,{open:t(this,xo,"m",Bo).bind(this),message:t(this,xo,"m",No).bind(this),close:t(this,xo,"m",Po).bind(this),error:t(this,xo,"m",Vo).bind(this)}),qo.set(this,new R(t(this,xo,"m",Go).bind(this),3e7))}get webSocket(){return t(this,Ao,"f")}set webSocket(e){t(this,Ao,"f")!=e?(Jo.log("assigning webSocket",e),t(this,Ao,"f")&&qi(t(this,Ao,"f"),t(this,$o,"f")),ji(e,t(this,$o,"f")),s(this,Ao,e,"f"),Jo.log("assigned webSocket")):Jo.log("redundant webSocket assignment")}get readyState(){return this.webSocket?.readyState}get isConnected(){return this.readyState==WebSocket.OPEN}get isDisconnected(){return this.readyState==WebSocket.CLOSED}connect(e=`wss://${location.host}`){this.webSocket&&this.assertDisconnection(),this._connectionStatus="connecting",this.webSocket=new WebSocket(e)}disconnect(){this.assertConnection(),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.webSocket.addEventListener("close",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this._connectionStatus="disconnecting",this.webSocket.close()}reconnect(){this.assertDisconnection(),this.webSocket=new WebSocket(this.webSocket.url)}toggleConnection(e){this.isConnected?this.disconnect():e&&this.webSocket?.url==e?this.reconnect():this.connect(e)}sendMessage(e){this.assertConnection(),t(this,Ao,"f").send(e)}sendServerMessage(...e){this.sendMessage(Ro({type:"serverMessage",data:eo(...e)}))}},e.setAllConsoleLevelFlags=function(e){k.setAllLevelFlags(e)},e.setConsoleLevelFlagsForType=function(e,t){k.setLevelFlagsForType(e,t)}}));
5
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).BS={})}(this,(function(e){"use strict";function t(e,t,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(e):i?i.value:t.get(e)}function s(e,t,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(e,s):n?n.value=s:t.set(e,s),s}"function"==typeof SuppressedError&&SuppressedError;const i=!1,n="undefined"!=typeof window&&void 0!==window?.document,r="undefined"!=typeof process&&null!=process?.versions?.node,a=n&&navigator.userAgent||"";let o=!1;n?o=Boolean(navigator.bluetooth):r&&(o=!0);const c=n&&/Bluefy/i.test(a),h=n&&/WebBLE/i.test(a),l=n&&/Android/i.test(a),g=n&&/Safari/i.test(a)&&!/Chrome/i.test(a),f=n&&/iPad|iPhone|iPod/i.test(a),u=n&&/Macintosh/i.test(a),d=!n&&!r&&"undefined"!=typeof global&&"undefined"!=typeof Studio;var m,p,v,w,y=Object.freeze({__proto__:null,isAndroid:l,get isBluetoothSupported(){return o},isIOS:f,isInBluefy:c,isInBrowser:n,isInDev:i,isInLensStudio:d,isInNode:r,isInProduction:!0,isInWebBLE:h,isMac:u,isSafari:g});if(d){const e=function(...e){Studio.log(e.map((e=>new String(e))).join(","))};(w={}).log=e,w.warn=e.bind(w,"WARNING"),w.error=e.bind(w,"ERROR")}else w=console;if(!w.assert){const e=(e,...t)=>{e||w.warn(...t)};w.assert=e}if(!w.table){const e=(...e)=>{w.log(...e)};w.table=e}function b(){}const S=w.log.bind(w),E=w.warn.bind(w),C=w.error.bind(w),M=w.table.bind(w),D=w.assert.bind(w);class k{constructor(e){if(v.set(this,{log:i,warn:i,assert:!0,error:!0,table:!0}),t(m,m,"f",p)[e])throw new Error(`"${e}" console already exists`);t(m,m,"f",p)[e]=this}setLevelFlags(e){Object.assign(t(this,v,"f"),e)}static setLevelFlagsForType(e,s){if(!t(this,m,"f",p)[e])throw new Error(`no console found with type "${e}"`);t(this,m,"f",p)[e].setLevelFlags(s)}static setAllLevelFlags(e){for(const s in t(this,m,"f",p))t(this,m,"f",p)[s].setLevelFlags(e)}static create(e,s){return t(this,m,"f",p)[e]||new m(e)}get log(){return t(this,v,"f").log?S:b}get warn(){return t(this,v,"f").warn?E:b}get error(){return t(this,v,"f").error?C:b}get assert(){return t(this,v,"f").assert?D:b}get table(){return t(this,v,"f").table?M:b}assertWithError(e,t){if(!Boolean(e))throw new Error(t)}assertTypeWithError(e,t){this.assertWithError(typeof e==t,`value ${e} of type "${typeof e}" not of type "${t}"`)}assertEnumWithError(e,t){this.assertWithError(t.includes(e),`invalid enum "${e}"`)}}function T(e,t){return k.create(e,t)}m=k,v=new WeakMap,p={value:{}};const W=T("EventDispatcher",{log:!1});class _{constructor(e,t){this.target=e,this.validEventTypes=t,this.listeners={},this.addEventListener=this.addEventListener.bind(this),this.removeEventListener=this.removeEventListener.bind(this),this.removeEventListeners=this.removeEventListeners.bind(this),this.removeAllEventListeners=this.removeAllEventListeners.bind(this),this.dispatchEvent=this.dispatchEvent.bind(this),this.waitForEvent=this.waitForEvent.bind(this)}isValidEventType(e){return this.validEventTypes.includes(e)}updateEventListeners(e){this.listeners[e]&&(this.listeners[e]=this.listeners[e].filter((t=>(t.shouldRemove&&W.log(`removing "${e}" eventListener`,t),!t.shouldRemove))))}addEventListener(e,t,s={once:!1}){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]||(this.listeners[e]=[],W.log(`creating "${e}" listeners array`,this.listeners[e]));this.listeners[e].find((e=>e.listener==t&&e.once==s.once))?W.log("already added listener"):(W.log(`adding "${e}" listener`,t,s),this.listeners[e].push({listener:t,once:s.once}),W.log(`currently have ${this.listeners[e].length} "${e}" listeners`))}removeEventListener(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(W.log(`removing "${e}" listener...`,t),this.listeners[e].forEach((s=>{s.listener===t&&(W.log(`flagging "${e}" listener`,t),s.shouldRemove=!0)})),this.updateEventListeners(e))}removeEventListeners(e){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(W.log(`removing "${e}" listeners...`),this.listeners[e]=[])}removeAllEventListeners(){W.log("removing listeners..."),this.listeners={}}dispatchEvent(e,t){if(!this.isValidEventType(e))throw new Error(`Invalid event type: ${e}`);this.listeners[e]&&(this.listeners[e].forEach((s=>{s.shouldRemove||(W.log(`dispatching "${e}" listener`,s),s.listener({type:e,target:this.target,message:t}),s.once&&(W.log(`flagging "${e}" listener`,s),s.shouldRemove=!0))})),this.updateEventListeners(e))}waitForEvent(e){return new Promise((t=>{this.addEventListener(e,(e=>{t(e)}),{once:!0})}))}}var I,L,F;const U=T("Timer",{log:!1});class R{get callback(){return t(this,I,"f")}set callback(e){U.assertTypeWithError(e,"function"),U.log({newCallback:e}),s(this,I,e,"f"),this.isRunning&&this.restart()}get interval(){return t(this,L,"f")}set interval(e){U.assertTypeWithError(e,"number"),U.assertWithError(e>0,"interval must be above 0"),U.log({newInterval:e}),s(this,L,e,"f"),this.isRunning&&this.restart()}constructor(e,t){I.set(this,void 0),L.set(this,void 0),F.set(this,void 0),this.interval=t,this.callback=e}get isRunning(){return null!=t(this,F,"f")}start(){this.isRunning?U.log("interval already running"):(U.log("starting interval"),s(this,F,setInterval(t(this,I,"f"),t(this,L,"f")),"f"))}stop(){this.isRunning?(U.log("stopping interval"),clearInterval(t(this,F,"f")),s(this,F,void 0,"f")):U.log("interval already not running")}restart(){this.stop(),this.start()}}function x(e){for(let t=0;t<8;++t)e=(1&e?0:3988292384)^e>>>1;return 4278190080^e}I=new WeakMap,L=new WeakMap,F=new WeakMap,T("checksum",{log:!0});const A=new Uint32Array(256);for(let e=0;e<256;++e)A[e]=x(e);function O(e){let t=new Uint8Array(e),s=0;for(let e=0;e<t.byteLength;++e){const i=255&s,n=t[e];s=(A[i^n]^s>>>8)>>>0}return s}var $,B;$="undefined"==typeof TextEncoder?class{encode(e){const t=Array.from(e).map((e=>e.charCodeAt(0)));return Uint8Array.from(t)}}:TextEncoder,B="undefined"==typeof TextDecoder?class{decode(e){return Array.from(new Uint8Array(e)).map((e=>String.fromCharCode(e))).join("")}}:TextDecoder;const N=new $,P=new B,V=T("ArrayBufferUtils",{log:!1});function z(...e){const t=(e=(e=(e=e.filter((e=>null!=e||null!=e))).map((e=>{if("number"==typeof e){const t=e;return Uint8Array.from([Math.floor(t)])}if("boolean"==typeof e){const t=e;return Uint8Array.from([t?1:0])}if("string"==typeof e){return j(e)}if(e instanceof Array){return z(...e)}if(e instanceof ArrayBuffer)return e;if("buffer"in e&&e.buffer instanceof ArrayBuffer){return e.buffer}if(e instanceof DataView){return e.buffer}if("object"==typeof e){return function(e){return j(JSON.stringify(e))}(e)}return e}))).filter((e=>e&&"byteLength"in e))).reduce(((e,t)=>e+t.byteLength),0),s=new Uint8Array(t);let i=0;return e.forEach((e=>{s.set(new Uint8Array(e),i),i+=e.byteLength})),s.buffer}function j(e){const t=N.encode(e);return z(t.byteLength,t)}function q(e,t,s){let i;return null!=s&&(i=e.byteOffset+t+s),V.log({dataView:e,begin:t,end:i,length:s}),new DataView(e.buffer.slice(e.byteOffset+t,i))}async function G(e){let t;if(e instanceof Array)t=Uint8Array.from(e);else if(e instanceof DataView)t=e.buffer;else if("string"==typeof e||e instanceof URL){const s=await fetch(e);t=await s.arrayBuffer()}else if(e instanceof File)t=await e.arrayBuffer();else{if(!(e instanceof ArrayBuffer))throw{error:"invalid file type",file:e};t=e}return t}function H(e,{include:t,exclude:s}={}){const i=e=>{const i=t=>"string"==typeof t?e===t:t.test(e);return t?t.some(i):!s||!s.some(i)};for(const[t,s]of(e=>{const t=new Set;do{for(const s of Reflect.ownKeys(e))t.add([e,s])}while((e=Reflect.getPrototypeOf(e))&&e!==Object.prototype);return t})(e.constructor.prototype)){if("constructor"===s||!i(s))continue;const n=Reflect.getOwnPropertyDescriptor(t,s);n&&"function"==typeof n.value&&(e[s]=e[s].bind(e))}return e}var J,Q,K,Z,X,Y,ee,te,se,ie,ne,re,ae,oe,ce,he,le,ge,fe,ue,de,me,pe,ve,we,ye,be,Se,Ee,Ce,Me,De,ke,Te,We,_e,Ie,Le;const Fe=T("FileTransferManager",{log:!0}),Ue=["maxFileLength","getFileType","setFileType","getFileLength","setFileLength","getFileChecksum","setFileChecksum","setFileTransferCommand","fileTransferStatus","getFileBlock","setFileBlock","fileBytesTransferred"],Re=["tflite"],xe=["idle","sending","receiving"],Ae=["startSend","startReceive","cancel"],Oe=[...Ue,"fileTransferProgress","fileTransferComplete","fileReceived"];class $e{constructor(){J.add(this),se.set(this,Q.MaxLength),ae.set(this,void 0),le.set(this,0),de.set(this,0),ye.set(this,"idle"),Me.set(this,[]),ke.set(this,void 0),Te.set(this,0),Le.set(this,!1),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}static get MaxLength(){return t(this,Q,"f",te)}get maxLength(){return t(this,se,"f")}get type(){return t(this,ae,"f")}get length(){return t(this,le,"f")}get checksum(){return t(this,de,"f")}get status(){return t(this,ye,"f")}parseMessage(e,s){switch(Fe.log({messageType:e}),e){case"maxFileLength":t(this,J,"m",ie).call(this,s);break;case"getFileType":case"setFileType":t(this,J,"m",oe).call(this,s);break;case"getFileLength":case"setFileLength":t(this,J,"m",ge).call(this,s);break;case"getFileChecksum":case"setFileChecksum":t(this,J,"m",me).call(this,s);break;case"fileTransferStatus":t(this,J,"m",be).call(this,s);break;case"getFileBlock":t(this,J,"m",De).call(this,s);break;case"fileBytesTransferred":t(this,J,"m",Ie).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}async send(e,s){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e);const i=await G(s),n=[];n.push(t(this,J,"m",he).call(this,e,!1));const r=i.byteLength;n.push(t(this,J,"m",ue).call(this,r,!1));const a=O(i);n.push(t(this,J,"m",ve).call(this,a,!1)),n.push(t(this,J,"m",we).call(this,"startSend",!1)),this.sendMessage(),await Promise.all(n),await t(this,J,"m",We).call(this,i)}async receive(e){t(this,J,"m",Ee).call(this),t(this,J,"m",Z).call(this,e),await t(this,J,"m",he).call(this,e),await t(this,J,"m",we).call(this,"startReceive")}async cancel(){t(this,J,"m",Ce).call(this),await t(this,J,"m",we).call(this,"cancel")}get isServerSide(){return t(this,Le,"f")}set isServerSide(e){t(this,Le,"f")!=e?(Fe.log({newIsServerSide:e}),s(this,Le,e,"f")):Fe.log("redundant isServerSide assignment")}}Q=$e,se=new WeakMap,ae=new WeakMap,le=new WeakMap,de=new WeakMap,ye=new WeakMap,Me=new WeakMap,ke=new WeakMap,Te=new WeakMap,Le=new WeakMap,J=new WeakSet,K=function(){return this.eventDispatcher.dispatchEvent},Z=function(e){Fe.assertEnumWithError(e,Re)},X=function(e){Fe.assertWithError(e in Re,`invalid typeEnum ${e}`)},Y=function(e){Fe.assertWithError(e in xe,`invalid statusEnum ${e}`)},ee=function(e){Fe.assertEnumWithError(e,Ae)},ie=function(e){Fe.log("parseFileMaxLength",e);const s=e.getUint32(0,!0);Fe.log(`maxLength: ${s/1024}kB`),t(this,J,"m",ne).call(this,s)},ne=function(e){Fe.log({maxLength:e}),s(this,se,e,"f"),t(this,J,"a",K).call(this,"maxFileLength",{maxFileLength:e})},re=function(e){Fe.assertWithError(e<=this.maxLength,`file length ${e}kB too large - must be ${this.maxLength}kB or less`)},oe=function(e){Fe.log("parseFileType",e);const s=e.getUint8(0);t(this,J,"m",X).call(this,s);const i=Re[s];t(this,J,"m",ce).call(this,i)},ce=function(e){Fe.log({fileTransferType:e}),s(this,ae,e,"f"),t(this,J,"a",K).call(this,"getFileType",{fileType:e})},he=async function(e,s){if(t(this,J,"m",Z).call(this,e),this.type==e)return void Fe.log(`redundant type assignment ${e}`);const i=this.waitForEvent("getFileType"),n=Re.indexOf(e);this.sendMessage([{type:"setFileType",data:Uint8Array.from([n]).buffer}],s),await i},ge=function(e){Fe.log("parseFileLength",e);const s=e.getUint32(0,!0);t(this,J,"m",fe).call(this,s)},fe=function(e){Fe.log(`length: ${e/1024}kB`),s(this,le,e,"f"),t(this,J,"a",K).call(this,"getFileLength",{fileLength:e})},ue=async function(e,s){if(Fe.assertTypeWithError(e,"number"),t(this,J,"m",re).call(this,e),this.length==e)return void Fe.log(`redundant length assignment ${e}`);const i=this.waitForEvent("getFileLength"),n=new DataView(new ArrayBuffer(4));n.setUint32(0,e,!0),this.sendMessage([{type:"setFileLength",data:n.buffer}],s),await i},me=function(e){Fe.log("checksum",e);const s=e.getUint32(0,!0);t(this,J,"m",pe).call(this,s)},pe=function(e){Fe.log({checksum:e}),s(this,de,e,"f"),t(this,J,"a",K).call(this,"getFileChecksum",{fileChecksum:e})},ve=async function(e,t){if(Fe.assertTypeWithError(e,"number"),this.checksum==e)return void Fe.log(`redundant checksum assignment ${e}`);const s=this.waitForEvent("getFileChecksum"),i=new DataView(new ArrayBuffer(4));i.setUint32(0,e,!0),this.sendMessage([{type:"setFileChecksum",data:i.buffer}],t),await s},we=async function(e,s){t(this,J,"m",ee).call(this,e);const i=this.waitForEvent("fileTransferStatus"),n=Ae.indexOf(e);this.sendMessage([{type:"setFileTransferCommand",data:Uint8Array.from([n]).buffer}],s),await i},be=function(e){Fe.log("parseFileStatus",e);const s=e.getUint8(0);t(this,J,"m",Y).call(this,s);const i=xe[s];t(this,J,"m",Se).call(this,i)},Se=function(e){Fe.log({status:e}),s(this,ye,e,"f"),t(this,J,"a",K).call(this,"fileTransferStatus",{fileTransferStatus:e}),t(this,Me,"f").length=0},Ee=function(){Fe.assertWithError("idle"==t(this,ye,"f"),"status is not idle")},Ce=function(){Fe.assertWithError("idle"!=t(this,ye,"f"),"status is idle")},De=async function(e){Fe.log("parseFileBlock",e),t(this,Me,"f").push(e.buffer);const s=t(this,Me,"f").reduce(((e,t)=>e+t.byteLength),0),i=s/t(this,le,"f");if(Fe.log(`received ${s} of ${t(this,le,"f")} bytes (${100*i}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:i}),s!=t(this,le,"f")){const e=new DataView(new ArrayBuffer(4));if(e.setUint32(0,s,!0),this.isServerSide)return;return void await this.sendMessage([{type:"fileBytesTransferred",data:e.buffer}])}Fe.log("file transfer complete");let n,r=(new Date).toLocaleString();if("tflite"===this.type)r+=".tflite";n="undefined"!=typeof File?new File(t(this,Me,"f"),r):new Blob(t(this,Me,"f"));const a=O(await n.arrayBuffer());Fe.log({checksum:a}),a==t(this,de,"f")?(Fe.log("received file",n),t(this,J,"a",K).call(this,"getFileBlock",{fileTransferBlock:e}),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"receiving"}),t(this,J,"a",K).call(this,"fileReceived",{file:n})):Fe.error(`wrong checksum - expected ${t(this,de,"f")}, got ${a}`)},We=async function(e){return s(this,ke,e,"f"),s(this,Te,0,"f"),t(this,J,"m",_e).call(this)},_e=async function(){if("sending"!=this.status)return;if(!t(this,ke,"f"))return void Fe.error("no buffer defined");const e=t(this,ke,"f");let i=t(this,Te,"f");const n=e.slice(i,i+(this.mtu-3-3));Fe.log("slicedBuffer",n);const r=1-(e.byteLength-i)/e.byteLength;Fe.log(`sending bytes ${i}-${i+n.byteLength} of ${e.byteLength} bytes (${100*r}%)`),t(this,J,"a",K).call(this,"fileTransferProgress",{progress:r}),0==n.byteLength?(Fe.log("finished sending buffer"),t(this,J,"a",K).call(this,"fileTransferComplete",{direction:"sending"})):(await this.sendMessage([{type:"setFileBlock",data:n}]),s(this,Te,i+n.byteLength,"f"))},Ie=async function(e){Fe.log("parseBytesTransferred",e);const s=e.getUint32(0,!0);if(Fe.log({bytesTransferred:s}),"sending"==this.status)return this.isServerSide||t(this,Te,"f")==s?void t(this,J,"m",_e).call(this):(Fe.error(`bytesTransferred are not equal - got ${s}, expected ${t(this,Te,"f")}`),void this.cancel());Fe.error("not currently sending file")},te={value:0};const Be=T("MathUtils",{log:!0});const Ne=65536;function Pe(e,t){const s=Date.now();var i;let n=(i=s)-i%Ne+e.getUint16(t,!0);return Math.abs(s-n)>6e4&&(Be.log("correcting timestamp delta"),n+=Ne*Math.sign(s-n)),n}var Ve;const ze={min:1/0,max:-1/0,span:0};class je{constructor(){Ve.set(this,Object.assign({},ze))}reset(){Object.assign(t(this,Ve,"f"),ze)}update(e){t(this,Ve,"f").min=Math.min(e,t(this,Ve,"f").min),t(this,Ve,"f").max=Math.max(e,t(this,Ve,"f").max),t(this,Ve,"f").span=t(this,Ve,"f").max-t(this,Ve,"f").min}getNormalization(e,s){let i=function(e,t,s,i){return null==i&&(i=s-t),(e-t)/i}(e,t(this,Ve,"f").min,t(this,Ve,"f").max,t(this,Ve,"f").span);return s&&(i*=t(this,Ve,"f").span),i||0}updateAndGetNormalization(e,t){return this.update(e),this.getNormalization(e,t)}}var qe,Ge,He,Je;Ve=new WeakMap;class Qe{constructor(){qe.set(this,{x:new je,y:new je})}reset(){t(this,qe,"f").x.reset(),t(this,qe,"f").y.reset()}update(e){t(this,qe,"f").x.update(e.x),t(this,qe,"f").y.update(e.y)}getNormalization(e){return{x:t(this,qe,"f").x.getNormalization(e.x,!1),y:t(this,qe,"f").y.getNormalization(e.y,!1)}}updateAndGetNormalization(e){return this.update(e),this.getNormalization(e)}}qe=new WeakMap;const Ke=T("PressureDataManager",{log:!0}),Ze=["pressure"],Xe=Ze;class Ye{constructor(){Ge.set(this,[]),He.set(this,void 0),Je.set(this,new Qe)}get positions(){return t(this,Ge,"f")}get numberOfSensors(){return this.positions.length}parsePositions(e){const t=[];for(let s=0,i=0;i<e.byteLength;s++,i+=2)t.push({x:e.getUint8(i)/256,y:e.getUint8(i+1)/256});var i,n;Ke.log({positions:t}),s(this,Ge,t,"f"),s(this,He,(i=this.numberOfSensors,n=()=>new je,new Array(i).fill(1).map(((e,t)=>{if("function"==typeof n)return n(t);{const e=n;return Object.assign({},e)}}))),"f"),this.resetRange()}resetRange(){t(this,He,"f").forEach((e=>e.reset())),t(this,Je,"f").reset()}parseData(e,s){const i={sensors:[],scaledSum:0,normalizedSum:0};for(let n=0,r=0;r<e.byteLength;n++,r+=2){const a=e.getUint16(r,!0),o=a*s,c=t(this,He,"f")[n].updateAndGetNormalization(o,!0),h=this.positions[n];i.sensors[n]={rawValue:a,scaledValue:o,normalizedValue:c,position:h,weightedValue:0},i.scaledSum+=o,i.normalizedSum+=c/this.numberOfSensors}return i.scaledSum>0&&i.normalizedSum>.001&&(i.center={x:0,y:0},i.sensors.forEach((e=>{e.weightedValue=e.scaledValue/i.scaledSum,i.center.x+=e.position.x*e.weightedValue,i.center.y+=e.position.y*e.weightedValue})),i.normalizedCenter=t(this,Je,"f").updateAndGetNormalization(i.center)),Ke.log({pressure:i}),i}}Ge=new WeakMap,He=new WeakMap,Je=new WeakMap;const et=T("MotionSensorDataManager",{log:!0}),tt=["still","walking","running","bicycle","vehicle","tilting"],st=["portraitUpright","landscapeLeft","portraitUpsideDown","landscapeRight","unknown"];class it{parseVector3(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));const r={x:s,y:i,z:n};return et.log({vector:r}),r}parseQuaternion(e,t){let[s,i,n,r]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0),e.getInt16(6,!0)].map((e=>e*t));const a={x:s,y:i,z:n,w:r};return et.log({quaternion:a}),a}parseEuler(e,t){let[s,i,n]=[e.getInt16(0,!0),e.getInt16(2,!0),e.getInt16(4,!0)].map((e=>e*t));i*=-1,s*=-1,s+=360;const r={heading:s,pitch:i,roll:n};return et.log({euler:r}),r}parseStepCounter(e){et.log("parseStepCounter",e);const t=e.getUint32(0,!0);return et.log({stepCount:t}),t}parseActivity(e){et.log("parseActivity",e);const t={},s=e.getUint8(0);return et.log("activityBitfield",s.toString(2)),tt.forEach(((e,i)=>{t[e]=Boolean(s&1<<i)})),et.log("activity",t),t}parseDeviceOrientation(e){et.log("parseDeviceOrientation",e);const t=e.getUint8(0),s=st[t];return et.assertWithError(s,"undefined deviceOrientation"),et.log({deviceOrientation:s}),s}}var nt,rt;const at=["barometer"],ot=at,ct=T("BarometerSensorDataManager",{log:!0});class ht{constructor(){nt.add(this)}parseData(e,s){const i=e.getUint32(0,!0)*s,n=t(this,nt,"m",rt).call(this,i);return ct.log({pressure:i,altitude:n}),{pressure:i}}}nt=new WeakSet,rt=function(e){const t=.0065;return 288.15/t*(1-Math.pow(e/101325,.19026643566373183))};const lt=T("ParseUtils",{log:!0});function gt(e,t=0){const s=e.getUint8(t++);return{string:P.decode(e.buffer.slice(e.byteOffset+t,e.byteOffset+t+s)),byteOffset:t+=s}}function ft(e,t,s,i,n=!1){let r=0;for(;r<e.byteLength;){const a=e.getUint8(r++);lt.assertWithError(a in t,`invalid messageTypeEnum ${a}`);const o=t[a];let c;n?(c=e.getUint16(r,!0),r+=2):c=e.getUint8(r++),lt.log({messageTypeEnum:a,messageType:o,messageLength:c,dataView:e,byteOffset:r});const h=q(e,r,c);lt.log({_dataView:h}),s(o,h,i),r+=c}}var ut;const dt=T("SensorDataManager",{log:!0}),mt=[...Ze,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation","orientation","activity","stepCounter","stepDetector","deviceOrientation",...at],pt=[...Xe,"acceleration","gravity","linearAcceleration","gyroscope","magnetometer","gameRotation","rotation",...ot],vt=["getPressurePositions","getSensorScalars","sensorData"],wt=[...vt,...mt];class yt{constructor(){this.pressureSensorDataManager=new Ye,this.motionSensorDataManager=new it,this.barometerSensorDataManager=new ht,ut.set(this,new Map)}static AssertValidSensorType(e){dt.assertEnumWithError(e,mt)}static AssertValidSensorTypeEnum(e){dt.assertTypeWithError(e,"number"),dt.assertWithError(e in mt,`invalid sensorTypeEnum ${e}`)}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}parseMessage(e,t){switch(dt.log({messageType:e}),e){case"getSensorScalars":this.parseScalars(t);break;case"getPressurePositions":this.pressureSensorDataManager.parsePositions(t);break;case"sensorData":this.parseData(t);break;default:throw Error(`uncaught messageType ${e}`)}}parseScalars(e){for(let s=0;s<e.byteLength;s+=5){const i=e.getUint8(s),n=mt[i];if(!n){dt.warn(`unknown sensorType index ${i}`);continue}const r=e.getFloat32(s+1,!0);dt.log({sensorType:n,sensorScalar:r}),t(this,ut,"f").set(n,r)}}parseData(e){dt.log("sensorData",Array.from(new Uint8Array(e.buffer)));let t=0;const s=Pe(e,t);t+=2;ft(new DataView(e.buffer,t),mt,this.parseDataCallback.bind(this),{timestamp:s})}parseDataCallback(e,s,{timestamp:i}){const n=t(this,ut,"f").get(e)||1;let r=null;switch(e){case"pressure":r=this.pressureSensorDataManager.parseData(s,n);break;case"acceleration":case"gravity":case"linearAcceleration":case"gyroscope":case"magnetometer":r=this.motionSensorDataManager.parseVector3(s,n);break;case"gameRotation":case"rotation":r=this.motionSensorDataManager.parseQuaternion(s,n);break;case"orientation":r=this.motionSensorDataManager.parseEuler(s,n);break;case"stepCounter":r=this.motionSensorDataManager.parseStepCounter(s);break;case"stepDetector":r={};break;case"activity":r=this.motionSensorDataManager.parseActivity(s);break;case"deviceOrientation":r=this.motionSensorDataManager.parseDeviceOrientation(s);break;case"barometer":r=this.barometerSensorDataManager.parseData(s,n);break;default:dt.error(`uncaught sensorType "${e}"`)}dt.assertWithError(null!=r,`no sensorData defined for sensorType "${e}"`),dt.log({sensorType:e,sensorData:r}),this.dispatchEvent(e,{sensorType:e,[e]:r,timestamp:i}),this.dispatchEvent("sensorData",{sensorType:e,[e]:r,timestamp:i})}}var bt,St,Et,Ct,Mt,Dt,kt,Tt,Wt,_t,It,Lt,Ft;ut=new WeakMap;const Ut=T("SensorConfigurationManager",{log:!0}),Rt=["getSensorConfiguration","setSensorConfiguration"],xt=Rt;class At{constructor(){bt.add(this),Ct.set(this,void 0),Dt.set(this,void 0),H(this)}get addEventListener(){return this.eventDispatcher.addEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get configuration(){return t(this,Dt,"f")}async setConfiguration(e,s){if(s&&(e=Object.assign({...this.zeroSensorConfiguration},e)),Ut.log({newSensorConfiguration:e}),t(this,bt,"m",Tt).call(this,e))return void Ut.log("redundant sensor configuration");const i=t(this,bt,"m",Lt).call(this,e);Ut.log({setSensorConfigurationData:i});const n=this.waitForEvent("getSensorConfiguration");this.sendMessage([{type:"setSensorConfiguration",data:i.buffer}]),await n}static get ZeroSensorConfiguration(){return t(this,St,"f",Ft)}get zeroSensorConfiguration(){const e={};return mt.forEach((t=>{e[t]=0})),e}async clearSensorConfiguration(){return this.setConfiguration(this.zeroSensorConfiguration)}parseMessage(e,s){switch(Ut.log({messageType:e}),e){case"getSensorConfiguration":case"setSensorConfiguration":const i=t(this,bt,"m",Wt).call(this,s);t(this,bt,"m",kt).call(this,i);break;default:throw Error(`uncaught messageType ${e}`)}}}var Ot,$t,Bt,Nt,Pt,Vt,zt,jt,qt,Gt,Ht,Jt,Qt,Kt,Zt,Xt,Yt,es,ts,ss,is,ns,rs,as,os,cs,hs,ls,gs,fs;St=At,Ct=new WeakMap,Dt=new WeakMap,bt=new WeakSet,Et=function(){return this.eventDispatcher.dispatchEvent},Mt=function(e){Ut.assertWithError(t(this,Ct,"f"),"must get initial sensorConfiguration");const s=t(this,Ct,"f")?.includes(e);return Ut.assert(s,`unavailable sensor type "${e}"`),s},kt=function(e){s(this,Dt,e,"f"),Ut.log({updatedConfiguration:t(this,Dt,"f")}),t(this,bt,"a",Et).call(this,"getSensorConfiguration",{sensorConfiguration:this.configuration})},Tt=function(e){return Object.keys(e).every((t=>this.configuration[t]==e[t]))},Wt=function(e){const t={};for(let s=0;s<e.byteLength;s+=3){const i=e.getUint8(s),n=mt[i];if(!n){Ut.warn(`unknown sensorType index ${i}`);continue}const r=e.getUint16(s+1,!0);Ut.log({sensorType:n,sensorRate:r}),t[n]=r}return Ut.log({parsedSensorConfiguration:t}),s(this,Ct,Object.keys(t),"f"),t},_t=function(e){Ut.assertTypeWithError(e,"number"),Ut.assertWithError(e>=0,`sensorRate must be 0 or greater (got ${e})`),Ut.assertWithError(e<65535,`sensorRate must be 0 or greater (got ${e})`),Ut.assertWithError(e%5==0,"sensorRate must be multiple of 5")},It=function(e){t(St,St,"m",_t).call(St,e)},Lt=function(e){let s=Object.keys(e);s=s.filter((e=>t(this,bt,"m",Mt).call(this,e)));const i=new DataView(new ArrayBuffer(3*s.length));return s.forEach(((s,n)=>{yt.AssertValidSensorType(s);const r=mt.indexOf(s);i.setUint8(3*n,r);const a=e[s];t(this,bt,"m",It).call(this,a),i.setUint16(3*n+1,a,!0)})),Ut.log({sensorConfigurationData:i}),i},Ft={value:{}},mt.forEach((e=>{t(St,St,"f",Ft)[e]=0}));const us=T("TfliteManager",{log:!0}),ds=["getTfliteName","setTfliteName","getTfliteTask","setTfliteTask","getTfliteSampleRate","setTfliteSampleRate","getTfliteSensorTypes","setTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","setTfliteCaptureDelay","getTfliteThreshold","setTfliteThreshold","getTfliteInferencingEnabled","setTfliteInferencingEnabled","tfliteInference"],ms=ds,ps=["classification","regression"],vs=["pressure","linearAcceleration","gyroscope","magnetometer"];class ws{constructor(){Ot.add(this),Pt.set(this,void 0),jt.set(this,void 0),Ht.set(this,void 0),Kt.set(this,[]),Yt.set(this,void 0),is.set(this,void 0),as.set(this,void 0),hs.set(this,void 0),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}get name(){return t(this,Pt,"f")}async setName(e,t){if(us.assertTypeWithError(e,"string"),this.name==e)return void us.log(`redundant name assignment ${e}`);const s=this.waitForEvent("getTfliteName"),i=N.encode(e);this.sendMessage([{type:"setTfliteName",data:i.buffer}],t),await s}get task(){return t(this,jt,"f")}async setTask(e,s){if(t(this,Ot,"m",$t).call(this,e),this.task==e)return void us.log(`redundant task assignment ${e}`);const i=this.waitForEvent("getTfliteTask"),n=ps.indexOf(e);this.sendMessage([{type:"setTfliteTask",data:Uint8Array.from([n]).buffer}],s),await i}get sampleRate(){return t(this,Ht,"f")}async setSampleRate(e,s){if(us.assertTypeWithError(e,"number"),e-=e%5,us.assertWithError(e>=5,`sampleRate must be multiple of 5 greater than 0 (got ${e})`),t(this,Ht,"f")==e)return void us.log(`redundant sampleRate assignment ${e}`);const i=this.waitForEvent("getTfliteSampleRate"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteSampleRate",data:n.buffer}],s),await i}static AssertValidSensorType(e){yt.AssertValidSensorType(e),us.assertWithError(vs.includes(e),`invalid tflite sensorType "${e}"`)}get sensorTypes(){return t(this,Kt,"f").slice()}async setSensorTypes(e,t){e.forEach((e=>{ws.AssertValidSensorType(e)}));const s=this.waitForEvent("getTfliteSensorTypes");var i;const n=(e=(i=e).filter(((e,t)=>i.indexOf(e)==t))).map((e=>mt.indexOf(e))).sort();us.log(e,n),this.sendMessage([{type:"setTfliteSensorTypes",data:Uint8Array.from(n).buffer}],t),await s}get isReady(){return t(this,Yt,"f")}get captureDelay(){return t(this,is,"f")}async setCaptureDelay(e,s){if(us.assertTypeWithError(e,"number"),t(this,is,"f")==e)return void us.log(`redundant captureDelay assignment ${e}`);const i=this.waitForEvent("getTfliteCaptureDelay"),n=new DataView(new ArrayBuffer(2));n.setUint16(0,e,!0),this.sendMessage([{type:"setTfliteCaptureDelay",data:n.buffer}],s),await i}get threshold(){return t(this,as,"f")}async setThreshold(e,s){if(us.assertTypeWithError(e,"number"),us.assertWithError(e>=0,`threshold must be positive (got ${e})`),t(this,as,"f")==e)return void us.log(`redundant threshold assignment ${e}`);const i=this.waitForEvent("getTfliteThreshold"),n=new DataView(new ArrayBuffer(4));n.setFloat32(0,e,!0),this.sendMessage([{type:"setTfliteThreshold",data:n.buffer}],s),await i}get inferencingEnabled(){return t(this,hs,"f")}async setInferencingEnabled(e,s=!0){if(us.assertTypeWithError(e,"boolean"),!e&&!this.isReady)return;if(t(this,Ot,"m",ss).call(this),t(this,hs,"f")==e)return void us.log(`redundant inferencingEnabled assignment ${e}`);const i=this.waitForEvent("getTfliteInferencingEnabled");this.sendMessage([{type:"setTfliteInferencingEnabled",data:Uint8Array.from([Number(e)]).buffer}],s),await i}async toggleInferencingEnabled(){return this.setInferencingEnabled(!this.inferencingEnabled)}async enableInferencing(){this.inferencingEnabled||this.setInferencingEnabled(!0)}async disableInferencing(){this.inferencingEnabled&&this.setInferencingEnabled(!1)}parseMessage(e,s){switch(us.log({messageType:e}),e){case"getTfliteName":case"setTfliteName":t(this,Ot,"m",Vt).call(this,s);break;case"getTfliteTask":case"setTfliteTask":t(this,Ot,"m",qt).call(this,s);break;case"getTfliteSampleRate":case"setTfliteSampleRate":t(this,Ot,"m",Jt).call(this,s);break;case"getTfliteSensorTypes":case"setTfliteSensorTypes":t(this,Ot,"m",Zt).call(this,s);break;case"tfliteIsReady":t(this,Ot,"m",es).call(this,s);break;case"getTfliteCaptureDelay":case"setTfliteCaptureDelay":t(this,Ot,"m",ns).call(this,s);break;case"getTfliteThreshold":case"setTfliteThreshold":t(this,Ot,"m",os).call(this,s);break;case"getTfliteInferencingEnabled":case"setTfliteInferencingEnabled":t(this,Ot,"m",ls).call(this,s);break;case"tfliteInference":t(this,Ot,"m",fs).call(this,s);break;default:throw Error(`uncaught messageType ${e}`)}}}var ys,bs,Ss,Es,Cs;Pt=new WeakMap,jt=new WeakMap,Ht=new WeakMap,Kt=new WeakMap,Yt=new WeakMap,is=new WeakMap,as=new WeakMap,hs=new WeakMap,Ot=new WeakSet,$t=function(e){us.assertEnumWithError(e,ps)},Bt=function(e){us.assertWithError(e in ps,`invalid taskEnum ${e}`)},Nt=function(){return this.eventDispatcher.dispatchEvent},Vt=function(e){us.log("parseName",e);const s=P.decode(e.buffer);t(this,Ot,"m",zt).call(this,s)},zt=function(e){us.log({name:e}),s(this,Pt,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteName",{tfliteName:e})},qt=function(e){us.log("parseTask",e);const s=e.getUint8(0);t(this,Ot,"m",Bt).call(this,s);const i=ps[s];t(this,Ot,"m",Gt).call(this,i)},Gt=function(e){us.log({task:e}),s(this,jt,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteTask",{tfliteTask:e})},Jt=function(e){us.log("parseSampleRate",e);const s=e.getUint16(0,!0);t(this,Ot,"m",Qt).call(this,s)},Qt=function(e){us.log({sampleRate:e}),s(this,Ht,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteSampleRate",{tfliteSampleRate:e})},Zt=function(e){us.log("parseSensorTypes",e);const s=[];for(let t=0;t<e.byteLength;t++){const i=e.getUint8(t),n=mt[i];n?s.push(n):us.error(`invalid sensorTypeEnum ${i}`)}t(this,Ot,"m",Xt).call(this,s)},Xt=function(e){us.log({sensorTypes:e}),s(this,Kt,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteSensorTypes",{tfliteSensorTypes:e})},es=function(e){us.log("parseIsReady",e);const s=Boolean(e.getUint8(0));t(this,Ot,"m",ts).call(this,s)},ts=function(e){us.log({isReady:e}),s(this,Yt,e,"f"),t(this,Ot,"a",Nt).call(this,"tfliteIsReady",{tfliteIsReady:e})},ss=function(){us.assertWithError(this.isReady,"tflite is not ready")},ns=function(e){us.log("parseCaptureDelay",e);const s=e.getUint16(0,!0);t(this,Ot,"m",rs).call(this,s)},rs=function(e){us.log({captureDelay:e}),s(this,is,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteCaptureDelay",{tfliteCaptureDelay:e})},os=function(e){us.log("parseThreshold",e);const s=e.getFloat32(0,!0);t(this,Ot,"m",cs).call(this,s)},cs=function(e){us.log({threshold:e}),s(this,as,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteThreshold",{tfliteThreshold:e})},ls=function(e){us.log("parseInferencingEnabled",e);const s=Boolean(e.getUint8(0));t(this,Ot,"m",gs).call(this,s)},gs=function(e){us.log({inferencingEnabled:e}),s(this,hs,e,"f"),t(this,Ot,"a",Nt).call(this,"getTfliteInferencingEnabled",{tfliteInferencingEnabled:e})},fs=function(e){us.log("parseInference",e);const s=Pe(e,0);us.log({timestamp:s});const i=[];for(let t=0,s=2;s<e.byteLength;t++,s+=4){const t=e.getFloat32(s,!0);i.push(t)}us.log("values",i);const n={timestamp:s,values:i};if("classification"==this.task){let e=0,t=0;i.forEach(((s,i)=>{s>e&&(e=s,t=i)})),us.log({maxIndex:t,maxValue:e}),n.maxIndex=t,n.maxValue=e}t(this,Ot,"a",Nt).call(this,"tfliteInference",{tfliteInference:n})};const Ms=T("DeviceInformationManager",{log:!0}),Ds=["manufacturerName","modelNumber","softwareRevision","hardwareRevision","firmwareRevision","pnpId","serialNumber"],ks=[...Ds,"deviceInformation"];class Ts{constructor(){ys.add(this),Ss.set(this,{})}get information(){return t(this,Ss,"f")}clear(){s(this,Ss,{},"f")}parseMessage(e,s){switch(Ms.log({messageType:e}),e){case"manufacturerName":const i=P.decode(s.buffer);Ms.log({manufacturerName:i}),t(this,ys,"m",Cs).call(this,{manufacturerName:i});break;case"modelNumber":const n=P.decode(s.buffer);Ms.log({modelNumber:n}),t(this,ys,"m",Cs).call(this,{modelNumber:n});break;case"softwareRevision":const r=P.decode(s.buffer);Ms.log({softwareRevision:r}),t(this,ys,"m",Cs).call(this,{softwareRevision:r});break;case"hardwareRevision":const a=P.decode(s.buffer);Ms.log({hardwareRevision:a}),t(this,ys,"m",Cs).call(this,{hardwareRevision:a});break;case"firmwareRevision":const o=P.decode(s.buffer);Ms.log({firmwareRevision:o}),t(this,ys,"m",Cs).call(this,{firmwareRevision:o});break;case"pnpId":const c={source:1===s.getUint8(0)?"Bluetooth":"USB",productId:s.getUint16(3,!0),productVersion:s.getUint16(5,!0),vendorId:0};"Bluetooth"==c.source&&(c.vendorId=s.getUint16(1,!0)),Ms.log({pnpId:c}),t(this,ys,"m",Cs).call(this,{pnpId:c});break;case"serialNumber":const h=P.decode(s.buffer);Ms.log({serialNumber:h});break;default:throw Error(`uncaught messageType ${e}`)}}}var Ws,_s,Is,Ls,Fs,Us,Rs,xs,As,Os,$s,Bs,Ns,Ps,Vs,zs,js,qs;Ss=new WeakMap,ys=new WeakSet,bs=function(){return this.eventDispatcher.dispatchEvent},Es=function(){return Ds.every((e=>e in t(this,Ss,"f")))},Cs=function(e){Ms.log({partialDeviceInformation:e});Object.keys(e).forEach((s=>{t(this,ys,"a",bs).call(this,s,{[s]:e[s]})})),Object.assign(t(this,Ss,"f"),e),Ms.log({deviceInformation:t(this,Ss,"f")}),t(this,ys,"a",Es)&&(Ms.log("completed deviceInformation"),t(this,ys,"a",bs).call(this,"deviceInformation",{deviceInformation:this.information}))};const Gs=T("InformationManager",{log:!0}),Hs=["leftInsole","rightInsole"],Js=["left","right"],Qs=["isCharging","getBatteryCurrent","getMtu","getId","getName","setName","getType","setType","getCurrentTime","setCurrentTime"],Ks=Qs;class Zs{constructor(){Ws.add(this),Is.set(this,!1),Fs.set(this,void 0),Rs.set(this,void 0),As.set(this,""),Os.set(this,void 0),Ps.set(this,0),zs.set(this,!1),H(this)}get waitForEvent(){return this.eventDispatcher.waitForEvent}get isCharging(){return t(this,Is,"f")}get batteryCurrent(){return t(this,Fs,"f")}async getBatteryCurrent(){Gs.log("getting battery current...");const e=this.waitForEvent("getBatteryCurrent");this.sendMessage([{type:"getBatteryCurrent"}]),await e}get id(){return t(this,Rs,"f")}get name(){return t(this,As,"f")}updateName(e){Gs.assertTypeWithError(e,"string"),s(this,As,e,"f"),Gs.log({updatedName:t(this,As,"f")}),t(this,Ws,"a",_s).call(this,"getName",{name:t(this,As,"f")})}async setName(e){Gs.assertTypeWithError(e,"string"),Gs.assertWithError(e.length>=2,`name must be greater than 2 characters long ("${e}" is ${e.length} characters long)`),Gs.assertWithError(e.length<30,`name must be less than 30 characters long ("${e}" is ${e.length} characters long)`);const t=N.encode(e);Gs.log({setNameData:t});const s=this.waitForEvent("getName");this.sendMessage([{type:"setName",data:t.buffer}]),await s}get type(){return t(this,Os,"f")}get typeEnum(){return Hs.indexOf(this.type)}updateType(e){t(this,Ws,"m",$s).call(this,e),e!=this.type?(s(this,Os,e,"f"),Gs.log({updatedType:t(this,Os,"f")}),t(this,Ws,"a",_s).call(this,"getType",{type:t(this,Os,"f")})):Gs.log("redundant type assignment")}async setType(e){t(this,Ws,"m",$s).call(this,e);const s=Hs.indexOf(e);t(this,Ws,"m",Ns).call(this,s)}get isInsole(){switch(this.type){case"leftInsole":case"rightInsole":return!0;default:return!1}}get insoleSide(){switch(this.type){case"leftInsole":return"left";case"rightInsole":return"right"}}get mtu(){return t(this,Ps,"f")}get isCurrentTimeSet(){return t(this,zs,"f")}parseMessage(e,s){switch(Gs.log({messageType:e}),e){case"isCharging":const i=Boolean(s.getUint8(0));Gs.log({isCharging:i}),t(this,Ws,"m",Ls).call(this,i);break;case"getBatteryCurrent":const n=s.getFloat32(0,!0);Gs.log({batteryCurrent:n}),t(this,Ws,"m",Us).call(this,n);break;case"getId":const r=P.decode(s.buffer);Gs.log({id:r}),t(this,Ws,"m",xs).call(this,r);break;case"getName":case"setName":const a=P.decode(s.buffer);Gs.log({name:a}),this.updateName(a);break;case"getType":case"setType":const o=s.getUint8(0),c=Hs[o];Gs.log({typeEnum:o,type:c}),this.updateType(c);break;case"getMtu":const h=s.getUint16(0,!0);Gs.log({mtu:h}),t(this,Ws,"m",Vs).call(this,h);break;case"getCurrentTime":case"setCurrentTime":const l=Number(s.getBigUint64(0,!0));t(this,Ws,"m",js).call(this,l);break;default:throw Error(`uncaught messageType ${e}`)}}clear(){s(this,zs,!1,"f")}}Is=new WeakMap,Fs=new WeakMap,Rs=new WeakMap,As=new WeakMap,Os=new WeakMap,Ps=new WeakMap,zs=new WeakMap,Ws=new WeakSet,_s=function(){return this.eventDispatcher.dispatchEvent},Ls=function(e){Gs.assertTypeWithError(e,"boolean"),s(this,Is,e,"f"),Gs.log({isCharging:t(this,Is,"f")}),t(this,Ws,"a",_s).call(this,"isCharging",{isCharging:t(this,Is,"f")})},Us=function(e){Gs.assertTypeWithError(e,"number"),s(this,Fs,e,"f"),Gs.log({batteryCurrent:t(this,Fs,"f")}),t(this,Ws,"a",_s).call(this,"getBatteryCurrent",{batteryCurrent:t(this,Fs,"f")})},xs=function(e){Gs.assertTypeWithError(e,"string"),s(this,Rs,e,"f"),Gs.log({id:t(this,Rs,"f")}),t(this,Ws,"a",_s).call(this,"getId",{id:t(this,Rs,"f")})},$s=function(e){Gs.assertEnumWithError(e,Hs)},Bs=function(e){Gs.assertTypeWithError(e,"number"),Gs.assertWithError(e in Hs,`invalid typeEnum ${e}`)},Ns=async function(e){t(this,Ws,"m",Bs).call(this,e);const s=Uint8Array.from([e]);Gs.log({setTypeData:s});const i=this.waitForEvent("getType");this.sendMessage([{type:"setType",data:s.buffer}]),await i},Vs=function(e){Gs.assertTypeWithError(e,"number"),t(this,Ps,"f")!=e?(s(this,Ps,e,"f"),t(this,Ws,"a",_s).call(this,"getMtu",{mtu:t(this,Ps,"f")})):Gs.log("redundant mtu assignment",e)},js=function(e){Gs.log({currentTime:e}),s(this,zs,0!=e||Math.abs(Date.now()-e)<Ne,"f"),t(this,zs,"f")||t(this,Ws,"m",qs).call(this)},qs=async function(){Gs.log("setting current time...");const e=new DataView(new ArrayBuffer(8));e.setBigUint64(0,BigInt(Date.now()),!0);const t=this.waitForEvent("getCurrentTime");this.sendMessage([{type:"setCurrentTime",data:e.buffer}]),await t};const Xs=["none","strongClick100","strongClick60","strongClick30","sharpClick100","sharpClick60","sharpClick30","softBump100","softBump60","softBump30","doubleClick100","doubleClick60","tripleClick100","softFuzz60","strongBuzz100","alert750ms","alert1000ms","strongClick1_100","strongClick2_80","strongClick3_60","strongClick4_30","mediumClick100","mediumClick80","mediumClick60","sharpTick100","sharpTick80","sharpTick60","shortDoubleClickStrong100","shortDoubleClickStrong80","shortDoubleClickStrong60","shortDoubleClickStrong30","shortDoubleClickMedium100","shortDoubleClickMedium80","shortDoubleClickMedium60","shortDoubleSharpTick100","shortDoubleSharpTick80","shortDoubleSharpTick60","longDoubleSharpClickStrong100","longDoubleSharpClickStrong80","longDoubleSharpClickStrong60","longDoubleSharpClickStrong30","longDoubleSharpClickMedium100","longDoubleSharpClickMedium80","longDoubleSharpClickMedium60","longDoubleSharpTick100","longDoubleSharpTick80","longDoubleSharpTick60","buzz100","buzz80","buzz60","buzz40","buzz20","pulsingStrong100","pulsingStrong60","pulsingMedium100","pulsingMedium60","pulsingSharp100","pulsingSharp60","transitionClick100","transitionClick80","transitionClick60","transitionClick40","transitionClick20","transitionClick10","transitionHum100","transitionHum80","transitionHum60","transitionHum40","transitionHum20","transitionHum10","transitionRampDownLongSmooth2_100","transitionRampDownLongSmooth1_100","transitionRampDownMediumSmooth1_100","transitionRampDownMediumSmooth2_100","transitionRampDownShortSmooth1_100","transitionRampDownShortSmooth2_100","transitionRampDownLongSharp1_100","transitionRampDownLongSharp2_100","transitionRampDownMediumSharp1_100","transitionRampDownMediumSharp2_100","transitionRampDownShortSharp1_100","transitionRampDownShortSharp2_100","transitionRampUpLongSmooth1_100","transitionRampUpLongSmooth2_100","transitionRampUpMediumSmooth1_100","transitionRampUpMediumSmooth2_100","transitionRampUpShortSmooth1_100","transitionRampUpShortSmooth2_100","transitionRampUpLongSharp1_100","transitionRampUpLongSharp2_100","transitionRampUpMediumSharp1_100","transitionRampUpMediumSharp2_100","transitionRampUpShortSharp1_100","transitionRampUpShortSharp2_100","transitionRampDownLongSmooth1_50","transitionRampDownLongSmooth2_50","transitionRampDownMediumSmooth1_50","transitionRampDownMediumSmooth2_50","transitionRampDownShortSmooth1_50","transitionRampDownShortSmooth2_50","transitionRampDownLongSharp1_50","transitionRampDownLongSharp2_50","transitionRampDownMediumSharp1_50","transitionRampDownMediumSharp2_50","transitionRampDownShortSharp1_50","transitionRampDownShortSharp2_50","transitionRampUpLongSmooth1_50","transitionRampUpLongSmooth2_50","transitionRampUpMediumSmooth1_50","transitionRampUpMediumSmooth2_50","transitionRampUpShortSmooth1_50","transitionRampUpShortSmooth2_50","transitionRampUpLongSharp1_50","transitionRampUpLongSharp2_50","transitionRampUpMediumSharp1_50","transitionRampUpMediumSharp2_50","transitionRampUpShortSharp1_50","transitionRampUpShortSharp2_50","longBuzz100","smoothHum50","smoothHum40","smoothHum30","smoothHum20","smoothHum10"];var Ys,ei,ti,si,ii,ni,ri,ai,oi,ci,hi,li,gi,fi,ui,di;const mi=T("VibrationManager"),pi=["front","rear"],vi=["waveformEffect","waveform"],wi=2550,yi=1270;class bi{constructor(){Ys.add(this),H(this)}async triggerVibration(e,s=!0){let i;e.forEach((e=>{const{type:s}=e;let n,{locations:r}=e;switch(r=r||pi.slice(),s){case"waveformEffect":{const{segments:s,loopCount:i}=e;n=t(this,Ys,"m",gi).call(this,r,s,i)}break;case"waveform":{const{segments:s}=e;n=t(this,Ys,"m",fi).call(this,r,s)}break;default:throw Error(`invalid vibration type "${s}"`)}mi.log({type:s,arrayBuffer:n}),i=z(i,n)})),await this.sendMessage([{type:"triggerVibration",data:i}],s)}}var Si,Ei,Ci,Mi,Di,ki,Ti,Wi,_i,Ii,Li,Fi,Ui,Ri;Ys=new WeakSet,ei=function(e){mi.assertTypeWithError(e,"string"),mi.assertWithError(pi.includes(e),`invalid location "${e}"`)},ti=function(e){t(this,Ys,"m",ii).call(this,e),e.forEach((e=>{t(this,Ys,"m",ei).call(this,e)}))},si=function(e){t(this,Ys,"m",ti).call(this,e);let s=0;return e.forEach((e=>{const t=pi.indexOf(e);s|=1<<t})),mi.log({locationsBitmask:s}),mi.assertWithError(s>0,"locationsBitmask must not be zero"),s},ii=function(e){mi.assertWithError(Array.isArray(e),"passed non-array"),mi.assertWithError(e.length>0,"passed empty array")},ni=function(e){mi.assertWithError(Xs.includes(e),`invalid waveformEffect "${e}"`)},ri=function(e){if(null!=e.effect){const s=e.effect;t(this,Ys,"m",ni).call(this,s)}else{if(null==e.delay)throw Error("no effect or delay found in waveformEffectSegment");{const{delay:t}=e;mi.assertWithError(t>=0,`delay must be 0ms or greater (got ${t})`),mi.assertWithError(t<=yi,`delay must be 1270ms or less (got ${t})`)}}if(null!=e.loopCount){const{loopCount:s}=e;t(this,Ys,"m",ai).call(this,s)}},ai=function(e){mi.assertTypeWithError(e,"number"),mi.assertWithError(e>=0,`waveformEffectSegmentLoopCount must be 0 or greater (got ${e})`),mi.assertWithError(e<=3,`waveformEffectSegmentLoopCount must be 3 or fewer (got ${e})`)},oi=function(e){t(this,Ys,"m",ii).call(this,e),mi.assertWithError(e.length<=8,`must have 8 waveformEffectSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ys,"m",ri).call(this,e)}))},ci=function(e){mi.assertTypeWithError(e,"number"),mi.assertWithError(e>=0,`waveformEffectSequenceLoopCount must be 0 or greater (got ${e})`),mi.assertWithError(e<=6,`waveformEffectSequenceLoopCount must be 6 or fewer (got ${e})`)},hi=function(e){mi.assertTypeWithError(e.amplitude,"number"),mi.assertWithError(e.amplitude>=0,`amplitude must be 0 or greater (got ${e.amplitude})`),mi.assertWithError(e.amplitude<=1,`amplitude must be 1 or less (got ${e.amplitude})`),mi.assertTypeWithError(e.duration,"number"),mi.assertWithError(e.duration>0,`duration must be greater than 0ms (got ${e.duration}ms)`),mi.assertWithError(e.duration<=wi,`duration must be 2550ms or less (got ${e.duration}ms)`)},li=function(e){t(this,Ys,"m",ii).call(this,e),mi.assertWithError(e.length<=20,`must have 20 waveformSegments or fewer (got ${e.length})`),e.forEach((e=>{t(this,Ys,"m",hi).call(this,e)}))},gi=function(e,s,i=0){t(this,Ys,"m",oi).call(this,s),t(this,Ys,"m",ci).call(this,i);let n=[],r=0;const a=s.some((e=>{const{loopCount:t}=e;return null!=t&&t>0}))||0!=i;for(let e=0;e<s.length||a&&e<8;e++){const t=s[e]||{effect:"none"};if(null!=t.effect){const e=t.effect;n[r++]=Xs.indexOf(e)}else{if(null==t.delay)throw Error("invalid waveformEffectSegment");{const{delay:e}=t;n[r++]=128|Math.floor(e/10)}}}const o=0!=i;for(let e=0;e<s.length||o&&e<8;e++){const t=s[e]?.loopCount||0;0!=e&&4!=e||(n[r]=0);const i=e%4*2;n[r]|=t<<i,3!=e&&7!=e||r++}0!=i&&(n[r++]=i);const c=new DataView(Uint8Array.from(n).buffer);return mi.log({dataArray:n,dataView:c}),t(this,Ys,"m",di).call(this,e,"waveformEffect",c)},fi=function(e,s){t(this,Ys,"m",li).call(this,s);const i=new DataView(new ArrayBuffer(2*s.length));return s.forEach(((e,t)=>{i.setUint8(2*t,Math.floor(127*e.amplitude)),i.setUint8(2*t+1,Math.floor(e.duration/10))})),mi.log({dataView:i}),t(this,Ys,"m",di).call(this,e,"waveform",i)},ui=function(e){mi.assertTypeWithError(e,"string"),mi.assertWithError(vi.includes(e),`invalid vibrationType "${e}"`)},di=function(e,s,i){mi.assertWithError(i?.byteLength>0,"no data received");const n=t(this,Ys,"m",si).call(this,e);t(this,Ys,"m",ui).call(this,s);const r=vi.indexOf(s);mi.log({locationsBitmask:n,vibrationTypeIndex:r,dataView:i});const a=z(n,r,i.byteLength,i);return mi.log({data:a}),a};const xi=T("BaseConnectionManager",{log:!0}),Ai=["notConnected","connecting","connected","disconnecting"],Oi=[...Ai,"connectionStatus","isConnected"],$i=[...Qs,...Rt,...vt,"triggerVibration",...ds,...Ue],Bi=["batteryLevel"],Ni=["rx","tx"],Pi=[...Bi,...Ds,...Ni,...$i,"smp"];class Vi{get baseConstructor(){return this.constructor}static get isSupported(){return!1}get isSupported(){return this.baseConstructor.isSupported}get type(){return this.baseConstructor.type}constructor(){Si.add(this),Di.set(this,"notConnected"),Li.set(this,[]),Ui.set(this,new R(t(this,Si,"m",Ri).bind(this),5e3)),t(this,Si,"m",Mi).call(this)}get status(){return t(this,Di,"f")}set status(e){xi.assertEnumWithError(e,Ai),t(this,Di,"f")!=e?(xi.log(`new connection status "${e}"`),s(this,Di,e,"f"),this.onStatusUpdated(this.status),this.isConnected?t(this,Ui,"f").start():t(this,Ui,"f").stop(),"notConnected"==t(this,Di,"f")&&(this.mtu=void 0)):xi.log(`tried to assign same connection status "${e}"`)}get isConnected(){return"connected"==this.status}async connect(){t(this,Si,"m",ki).call(this),t(this,Si,"m",Ti).call(this),this.status="connecting"}get canReconnect(){return!1}async reconnect(){t(this,Si,"m",ki).call(this),t(this,Si,"m",Ti).call(this),xi.assert(this.canReconnect,"unable to reconnect")}async disconnect(){t(this,Si,"m",Wi).call(this),t(this,Si,"m",_i).call(this),this.status="disconnecting",xi.log("disconnecting from device...")}async sendSmpMessage(e){t(this,Si,"m",Ii).call(this),xi.log("sending smp message",e)}async sendTxMessages(e,s=!0){if(t(this,Si,"m",Ii).call(this),e&&t(this,Li,"f").push(...e),!s)return;xi.log("sendTxMessages",t(this,Li,"f").slice());const i=t(this,Li,"f").map((e=>{t(Ei,Ei,"m",Ci).call(Ei,e.type);const s=$i.indexOf(e.type),i=new DataView(new ArrayBuffer(2));return i.setUint16(0,e.data?.byteLength||0,!0),z(s,i,e.data)}));if(this.mtu)for(;i.length>0;){let e=0,t=0;i.some((s=>{if(e+s.byteLength>this.mtu-3)return!0;t++,e+=s.byteLength}));const s=i.splice(0,t);xi.log({arrayBufferCount:t,arrayBuffersToSend:s});const n=z(...s);xi.log("sending arrayBuffer",n),await this.sendTxData(n)}else{const e=z(...i);xi.log("sending arrayBuffer",e),await this.sendTxData(e)}t(this,Li,"f").length=0}async sendTxData(e){xi.log("sendTxData",e)}parseRxMessage(e){ft(e,$i,t(this,Si,"m",Fi).bind(this),null,!0)}}Ei=Vi,Di=new WeakMap,Li=new WeakMap,Ui=new WeakMap,Si=new WeakSet,Ci=function(e){xi.assertEnumWithError(e,$i)},Mi=function(){xi.assertWithError(this.isSupported,`${this.constructor.name} is not supported`)},ki=function(){xi.assertWithError(!this.isConnected,"device is already connected")},Ti=function(){xi.assertWithError("connecting"!=this.status,"device is already connecting")},Wi=function(){xi.assertWithError(this.isConnected,"device is not connected")},_i=function(){xi.assertWithError("disconnecting"!=this.status,"device is already disconnecting")},Ii=function(){t(this,Si,"m",Wi).call(this),t(this,Si,"m",_i).call(this)},Fi=function(e,t){xi.log({messageType:e,dataView:t}),this.onMessageReceived(e,t)},Ri=function(){this.isConnected||(xi.log("timer detected disconnection"),this.status="notConnected")};const zi=T("EventUtils",{log:!1});function ji(e,t){let s=e.addEventListener||e.addListener||e.on||e.AddEventListener;zi.assertWithError(s,"no add listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}function qi(e,t){let s=e.removeEventListener||e.removeListener||e.RemoveEventListener;zi.assertWithError(s,"no remove listener function found for target"),s=s.bind(e),Object.entries(t).forEach((([e,t])=>{s(e,t)}))}const Gi=T("bluetoothUUIDs",{log:!1});if(n)var Hi=window.BluetoothUUID;function Ji(e){return Gi.assertTypeWithError(e,"string"),Gi.assertWithError(4==e.length,"value must be 4 characters long"),`ea6da725-${e}-4f9b-893d-c3913e33b39f`}function Qi(e){return Hi?.getCharacteristic?.(e)}function Ki(e){return Hi?.getService?.(e)}const Zi=Object.freeze({services:{deviceInformation:{uuid:Ki("device_information"),characteristics:{manufacturerName:{uuid:Qi("manufacturer_name_string")},modelNumber:{uuid:Qi("model_number_string")},hardwareRevision:{uuid:Qi("hardware_revision_string")},firmwareRevision:{uuid:Qi("firmware_revision_string")},softwareRevision:{uuid:Qi("software_revision_string")},pnpId:{uuid:Qi("pnp_id")},serialNumber:{uuid:Qi("serial_number_string")}}},battery:{uuid:Ki("battery_service"),characteristics:{batteryLevel:{uuid:Qi("battery_level")}}},main:{uuid:Ji("0000"),characteristics:{rx:{uuid:Ji("1000")},tx:{uuid:Ji("1001")}}},smp:{uuid:"8d53dc1d-1db7-4cd3-868b-8a527460aa84",characteristics:{smp:{uuid:"da2e7828-fbce-4e01-ae9e-261174997c48"}}}}}),Xi=[Zi.services.main.uuid],Yi=[Zi.services.deviceInformation.uuid,Zi.services.battery.uuid,Zi.services.smp.uuid];function en(e){e=e.toString().toLowerCase();return Object.keys(Zi.services).find((t=>{let s=Zi.services[t].uuid.toString();return 4==e.length&&(s=s.slice(4,8)),e.includes("-")||(s=s.replaceAll("-","")),e==s}))}const tn=[],sn=[];function nn(e){var t;return e=e.toString().toLowerCase(),Object.values(Zi.services).some((s=>{const i=Object.keys(s.characteristics);return t=i.find((t=>{let i=s.characteristics[t].uuid.toString();return 4==e.length&&(i=i.slice(4,8)),e.includes("-")||(i=i.replaceAll("-","")),e==i}))})),t}function rn(e){const t={broadcast:!1,read:!0,writeWithoutResponse:!1,write:!1,notify:!1,indicate:!1,authenticatedSignedWrites:!1,reliableWrite:!1,writableAuxiliaries:!1};switch(e){case"rx":case"tx":case"smp":t.read=!1}switch(e){case"batteryLevel":case"rx":case"smp":t.notify=!0}if("smp"===e)t.writeWithoutResponse=!0;if("tx"===e)t.write=!0;return t}Object.values(Zi.services).forEach((e=>{if(!e.characteristics)return;const t=Object.keys(e.characteristics);t.forEach((s=>{const i=e.characteristics[s];Xi.includes(e.uuid)&&(tn.push(i.uuid),t.push(s)),sn.push(i.uuid)}))}),[]);const an=T("BluetoothConnectionManager",{log:!0});class on extends Vi{constructor(){super(...arguments),this.isInRange=!0}onCharacteristicValueChanged(e,t){"rx"==e?this.parseRxMessage(t):this.onMessageReceived?.(e,t)}async writeCharacteristic(e,t){an.log("writeCharacteristic",...arguments)}async sendSmpMessage(e){super.sendSmpMessage(e),await this.writeCharacteristic("smp",e)}async sendTxData(e){super.sendTxData(e),await this.writeCharacteristic("tx",e)}}var cn,hn,ln,gn,fn,un,dn,mn,pn,vn,wn;const yn=T("WebBluetoothConnectionManager",{log:!0});var bn;n&&(bn=window.navigator.bluetooth);class Sn extends on{constructor(){super(...arguments),cn.add(this),hn.set(this,{characteristicvaluechanged:t(this,cn,"m",pn).bind(this)}),ln.set(this,{gattserverdisconnected:t(this,cn,"m",wn).bind(this)}),gn.set(this,void 0),fn.set(this,new Map),un.set(this,new Map)}get bluetoothId(){return this.device.id}static get isSupported(){return Boolean(bn)}static get type(){return"webBluetooth"}get device(){return t(this,gn,"f")}set device(e){t(this,gn,"f")!=e?(t(this,gn,"f")&&qi(t(this,gn,"f"),t(this,ln,"f")),e&&ji(e,t(this,ln,"f")),s(this,gn,e,"f")):yn.log("tried to assign the same BluetoothDevice")}get server(){return t(this,gn,"f")?.gatt}get isConnected(){return this.server?.connected||!1}async connect(){await super.connect();try{const e=await bn.requestDevice({filters:[{services:Xi}],optionalServices:n?Yi:[]});yn.log("got BluetoothDevice"),this.device=e,yn.log("connecting to device...");const s=await this.server.connect();yn.log(`connected to device? ${s.connected}`),await t(this,cn,"m",dn).call(this),yn.log("fully connected"),this.status="connected"}catch(e){yn.error(e),this.status="notConnected",this.server?.disconnect(),t(this,cn,"m",mn).call(this)}}async disconnect(){await t(this,cn,"m",mn).call(this),await super.disconnect(),this.server?.disconnect(),this.status="notConnected"}async writeCharacteristic(e,s){super.writeCharacteristic(e,s);const i=t(this,un,"f").get(e);yn.assertWithError(i,`${e} characteristic not found`),yn.log("writing characteristic",i,s);const n=i.properties||rn(e);n.writeWithoutResponse?(yn.log("writing without response"),await i.writeValueWithoutResponse(s)):(yn.log("writing with response"),await i.writeValueWithResponse(s)),yn.log("wrote characteristic"),n.read&&!n.notify&&(yn.log("reading value after write..."),await i.readValue(),(c||h)&&t(this,cn,"m",vn).call(this,i))}get canReconnect(){return Boolean(this.server&&!this.server.connected&&this.isInRange)}async reconnect(){await super.reconnect(),yn.log("attempting to reconnect..."),this.status="connecting";try{await this.server.connect()}catch(e){yn.error(e),this.isInRange=!1}this.isConnected?(yn.log("successfully reconnected!"),await t(this,cn,"m",dn).call(this),this.status="connected"):(yn.log("unable to reconnect"),this.status="notConnected")}}hn=new WeakMap,ln=new WeakMap,gn=new WeakMap,fn=new WeakMap,un=new WeakMap,cn=new WeakSet,dn=async function(){t(this,cn,"m",mn).call(this),yn.log("getting services...");const e=await this.server.getPrimaryServices();yn.log("got services",e.length),await this.server.getPrimaryService("8d53dc1d-1db7-4cd3-868b-8a527460aa84"),yn.log("getting characteristics...");for(const s in e){const i=e[s];yn.log({service:i});const n=en(i.uuid);yn.assertWithError(n,`no name found for service uuid "${i.uuid}"`),yn.log(`got "${n}" service`),i.name=n,t(this,fn,"f").set(n,i),yn.log(`getting characteristics for "${n}" service`);const r=await i.getCharacteristics();yn.log(`got characteristics for "${n}" service`);for(const e in r){const s=r[e];yn.log({characteristic:s});const i=nn(s.uuid);yn.assertWithError(Boolean(i),`no name found for characteristic uuid "${s.uuid}" in "${n}" service`),yn.log(`got "${i}" characteristic in "${n}" service`),s.name=i,t(this,un,"f").set(i,s),ji(s,t(this,hn,"f"));const a=s.properties||rn(i);a.notify&&(yn.log(`starting notifications for "${i}" characteristic`),await s.startNotifications()),a.read&&(yn.log(`reading "${i}" characteristic...`),await s.readValue(),(c||h)&&t(this,cn,"m",vn).call(this,s))}}},mn=async function(){this.device&&qi(this.device,t(this,ln,"f"));const e=Array.from(t(this,un,"f").keys()).map((e=>{const s=t(this,un,"f").get(e);qi(s,t(this,hn,"f"));if((s.properties||rn(e)).notify)return yn.log(`stopping notifications for "${e}" characteristic`),s.stopNotifications()}));return Promise.allSettled(e)},pn=function(e){yn.log("oncharacteristicvaluechanged");const s=e.target;t(this,cn,"m",vn).call(this,s)},vn=function(e){yn.log("onCharacteristicValue");const t=e.name;yn.assertWithError(Boolean(t),`no name found for characteristic with uuid "${e.uuid}"`),yn.log(`oncharacteristicvaluechanged for "${t}" characteristic`);const s=e.value;yn.assertWithError(s,`no data found for "${t}" characteristic`),yn.log(`data for "${t}" characteristic`,Array.from(new Uint8Array(s.buffer)));try{this.onCharacteristicValueChanged(t,s)}catch(e){yn.error(e)}},wn=function(){yn.log("gattserverdisconnected"),this.status="notConnected"};const En=4294967296,Cn=9007199254740992;const Mn={encode:function(e){let t,s=new ArrayBuffer(256),i=new DataView(s),n=0;function r(e){let r=s.byteLength;const a=n+e;for(;r<a;)r<<=1;if(r!==s.byteLength){const e=i;s=new ArrayBuffer(r),i=new DataView(s);const t=n+3>>2;for(let s=0;s<t;++s)i.setUint32(s<<2,e.getUint32(s<<2))}return t=e,i}function a(){n+=t}function o(e){a(r(1).setUint8(n,e))}function c(e){const t=r(e.length);for(let s=0;s<e.length;++s)t.setUint8(n+s,e[s]);a()}function h(e,t){t<24?o(e<<5|t):t<256?(o(e<<5|24),o(t)):t<65536?(o(e<<5|25),function(e){a(r(2).setUint16(n,e))}(t)):t<4294967296?(o(e<<5|26),function(e){a(r(4).setUint32(n,e))}(t)):(o(e<<5|27),function(e){const t=e%En,s=(e-t)/En,i=r(8);i.setUint32(n,s),i.setUint32(n+4,t),a()}(t))}if(function e(t){let s;const i=[];let l;if(!1===t)return o(244);if(!0===t)return o(245);if(null===t)return o(246);if(void 0===t)return o(247);switch(typeof t){case"number":if(Math.floor(t)===t){if(t>=0&&t<=Cn)return h(0,t);if(-Cn<=t&&t<0)return h(1,-(t+1))}return o(251),function(e){a(r(8).setFloat64(n,e))}(t);case"string":for(s=0;s<t.length;++s){let e=t.charCodeAt(s);e<128?i.push(e):e<2048?(i.push(192|e>>6),i.push(128|63&e)):e<55296?(i.push(224|e>>12),i.push(128|e>>6&63),i.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++s),e+=65536,i.push(240|e>>18),i.push(128|e>>12&63),i.push(128|e>>6&63),i.push(128|63&e))}return h(3,i.length),c(i);default:if(Array.isArray(t))for(l=t.length,h(4,l),s=0;s<l;++s)e(t[s]);else if(t instanceof Uint8Array)h(2,t.length),c(t);else{const i=Object.keys(t);for(l=i.length,h(5,l),s=0;s<l;++s){const n=i[s];e(n),e(t[n])}}}}(e),"slice"in s)return s.slice(0,n);const l=new ArrayBuffer(n),g=new DataView(l);for(let e=0;e<n;++e)g.setUint8(e,i.getUint8(e));return l},decode:function(e,t,s){const i=new DataView(e);let n=0;function r(e,t){return n+=e,t}function a(t){return r(t,new Uint8Array(e,n,t))}function o(){return r(1,i.getUint8(n))}function c(){return r(2,i.getUint16(n))}function h(){return r(4,i.getUint32(n))}function l(){return 255===i.getUint8(n)&&(n+=1,!0)}function g(e){if(e<24)return e;if(24===e)return o();if(25===e)return c();if(26===e)return h();if(27===e)return h()*En+h();if(31===e)return-1;throw new Error("Invalid length encoding")}function f(e){const t=o();if(255===t)return-1;const s=g(31&t);if(s<0||t>>5!==e)throw new Error("Invalid indefinite length element");return s}function u(e,t){for(let s=0;s<t;++s){let s=o();128&s&&(s<224?(s=(31&s)<<6|63&o(),t-=1):s<240?(s=(15&s)<<12|(63&o())<<6|63&o(),t-=2):(s=(15&s)<<18|(63&o())<<12|(63&o())<<6|63&o(),t-=3)),s<65536?e.push(s):(s-=65536,e.push(55296|s>>10),e.push(56320|1023&s))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof s&&(s=function(){});const d=function e(){const h=o(),d=h>>5,m=31&h;let p,v;if(7===d)switch(m){case 25:return function(){const e=new ArrayBuffer(4),t=new DataView(e),s=c(),i=32768&s;let n=31744&s;const r=1023&s;if(31744===n)n=261120;else if(0!==n)n+=114688;else if(0!==r)return(i?-1:1)*r*5.960464477539063e-8;return t.setUint32(0,i<<16|n<<13|r<<13),t.getFloat32(0)}();case 26:return r(4,i.getFloat32(n));case 27:return r(8,i.getFloat64(n))}if(v=g(m),v<0&&(d<2||d>6))throw new Error("Invalid length");const w=[];let y;const b={};switch(d){case 0:return v;case 1:return-1-v;case 2:if(v<0){const e=[];let t=0;for(;(v=f(d))>=0;)t+=v,e.push(a(v));const s=new Uint8Array(t);let i=0;for(p=0;p<e.length;++p)s.set(e[p],i),i+=e[p].length;return s}return a(v);case 3:if(v<0)for(;(v=f(d))>=0;)u(w,v);else u(w,v);return String.fromCharCode.apply(null,w);case 4:if(v<0)for(y=[];!l();)y.push(e());else for(y=new Array(v),p=0;p<v;++p)y[p]=e();return y;case 5:for(p=0;p<v||v<0&&!l();++p){b[e()]=e()}return b;case 6:return t(e(),v);case 7:switch(v){case 20:return!1;case 21:return!0;case 22:return null;case 23:return;default:return s(v)}}}();if(n!==e.byteLength)throw new Error("Remaining bytes");return d}},Dn=T("mcumgr",{log:!0}),kn=0,Tn=1,Wn=2,_n=3,In=0,Ln=1,Fn=8,Un=0,Rn=2,xn=3,An=5,On=0,$n=1,Bn=5,Nn=0;class Pn{constructor(){this._mtu=256,this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}onMessage(e){return this._messageCallback=e,this}onImageUploadNext(e){return this._imageUploadNextCallback=e,this}onImageUploadProgress(e){return this._imageUploadProgressCallback=e,this}onImageUploadFinished(e){return this._imageUploadFinishedCallback=e,this}onFileUploadNext(e){return this._fileUploadNextCallback=e,this}onFileUploadProgress(e){return this._fileUploadProgressCallback=e,this}onFileUploadFinished(e){return this._fileUploadFinishedCallback=e,this}onFileDownloadNext(e){return this._fileDownloadNextCallback=e,this}onFileDownloadProgress(e){return this._fileDownloadProgressCallback=e,this}onFileDownloadFinished(e){return this._fileDownloadFinishedCallback=e,this}_getMessage(e,t,s,i){let n=[];void 0!==i&&(n=[...new Uint8Array(Mn.encode(i))]);const r=255&n.length,a=[e,0,n.length>>8,r,t>>8,255&t,this._seq,s,...n];return this._seq=(this._seq+1)%256,a}_notification(e){Dn.log("mcumgr - message received");const t=new Uint8Array(e);this._buffer=new Uint8Array([...this._buffer,...t]);const s=256*this._buffer[2]+this._buffer[3];this._buffer.length<s+8||(this._processMessage(this._buffer.slice(0,s+8)),this._buffer=this._buffer.slice(s+8))}_processMessage(e){const[t,,s,i,n,r,,a]=e,o=Mn.decode(e.slice(8).buffer),c=256*s+i,h=256*n+r;return Dn.log("mcumgr - Process Message - Group: "+h+", Id: "+a+", Off: "+o.off),h===Ln&&a===$n&&o.off?(this._uploadOffset=o.off,void this._uploadNext()):t===_n&&h===Fn&&a===Nn&&o.off?(this._uploadFileOffset=o.off,void this._uploadFileNext()):t===Tn&&h===Fn&&a===Nn?(this._downloadFileOffset+=o.data.length,null!=o.len&&(this._downloadFileLength=o.len),Dn.log("downloaded "+this._downloadFileOffset+" bytes of "+this._downloadFileLength),this._downloadFileLength>0&&this._fileDownloadProgressCallback({percentage:Math.floor(this._downloadFileOffset/this._downloadFileLength*100)}),this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}),void this._downloadFileNext()):void(this._messageCallback&&this._messageCallback({op:t,group:h,id:a,data:o,length:c}))}cmdReset(){return this._getMessage(Wn,In,An)}smpEcho(e){return this._getMessage(Wn,In,Un,{d:e})}cmdImageState(){return this._getMessage(kn,Ln,On)}cmdImageErase(){return this._getMessage(Wn,Ln,Bn,{})}cmdImageTest(e){return this._getMessage(Wn,Ln,On,{hash:e,confirm:!1})}cmdImageConfirm(e){return this._getMessage(Wn,Ln,On,{hash:e,confirm:!0})}_hash(e){return crypto.subtle.digest("SHA-256",e)}async _uploadNext(){if(!this._uploadImage)return;if(this._uploadOffset>=this._uploadImage.byteLength)return this._uploadIsInProgress=!1,void this._imageUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadOffset};0===this._uploadOffset&&(e.len=this._uploadImage.byteLength,e.sha=new Uint8Array(await this._hash(this._uploadImage))),this._imageUploadProgressCallback({percentage:Math.floor(this._uploadOffset/this._uploadImage.byteLength*100)});const t=this._mtu-Mn.encode(e).byteLength-8-3-5;e.data=new Uint8Array(this._uploadImage.slice(this._uploadOffset,this._uploadOffset+t)),this._uploadOffset+=t;const s=this._getMessage(Wn,Ln,$n,e);Dn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._imageUploadNextCallback({packet:s})}async reset(){this._messageCallback=null,this._imageUploadProgressCallback=null,this._imageUploadNextCallback=null,this._fileUploadProgressCallback=null,this._fileUploadNextCallback=null,this._uploadIsInProgress=!1,this._downloadIsInProgress=!1,this._buffer=new Uint8Array,this._seq=0}async cmdUpload(e,t=0){this._uploadIsInProgress?Dn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadOffset=0,this._uploadImage=e,this._uploadSlot=t,this._uploadNext())}async cmdUploadFile(e,t){this._uploadIsInProgress?Dn.error("Upload is already in progress."):(this._uploadIsInProgress=!0,this._uploadFileOffset=0,this._uploadFile=e,this._uploadFilename=t,this._uploadFileNext())}async _uploadFileNext(){if(Dn.log("uploadFileNext - offset: "+this._uploadFileOffset+", length: "+this._uploadFile.byteLength),this._uploadFileOffset>=this._uploadFile.byteLength)return this._uploadIsInProgress=!1,void this._fileUploadFinishedCallback();const e={data:new Uint8Array,off:this._uploadFileOffset};0===this._uploadFileOffset&&(e.len=this._uploadFile.byteLength),e.name=this._uploadFilename,this._fileUploadProgressCallback({percentage:Math.floor(this._uploadFileOffset/this._uploadFile.byteLength*100)});const t=this._mtu-Mn.encode(e).byteLength-8;e.data=new Uint8Array(this._uploadFile.slice(this._uploadFileOffset,this._uploadFileOffset+t)),this._uploadFileOffset+=t;const s=this._getMessage(Wn,Fn,Nn,e);Dn.log("mcumgr - _uploadNext: Message Length: "+s.length),this._fileUploadNextCallback({packet:s})}async cmdDownloadFile(e,t){this._downloadIsInProgress?Dn.error("Download is already in progress."):(this._downloadIsInProgress=!0,this._downloadFileOffset=0,this._downloadFileLength=0,this._downloadRemoteFilename=e,this._downloadLocalFilename=t,this._downloadFileNext())}async _downloadFileNext(){if(this._downloadFileLength>0&&this._downloadFileOffset>=this._downloadFileLength)return this._downloadIsInProgress=!1,void this._fileDownloadFinishedCallback();const e={off:this._downloadFileOffset};0===this._downloadFileOffset&&(e.name=this._downloadRemoteFilename);const t=this._getMessage(kn,Fn,Nn,e);Dn.log("mcumgr - _downloadNext: Message Length: "+t.length),this._fileDownloadNextCallback({packet:t})}async imageInfo(e){const t={},s=new Uint8Array(e);if(s.length<32)throw new Error("Invalid image (too short file)");if(61!==s[0]||184!==s[1]||243!==s[2]||150!==s[3])throw new Error("Invalid image (wrong magic bytes)");if(0!==s[4]||0!==s[5]||0!==s[6]||0!==s[7])throw new Error("Invalid image (wrong load address)");const i=s[8]+256*s[9];if(0!==s[10]||0!==s[11])throw new Error("Invalid image (wrong protected TLV area size)");const n=s[12]+256*s[13]+65536*s[14]+s[15]*2**24;if(t.imageSize=n,s.length<n+i)throw new Error("Invalid image (wrong image size)");if(0!==s[16]||0!==s[17]||0!==s[18]||0!==s[19])throw new Error("Invalid image (wrong flags)");const r=`${s[20]}.${s[21]}.${s[22]+256*s[23]}`;return t.version=r,t.hash=[...new Uint8Array(await this._hash(e.slice(0,n+32)))].map((e=>e.toString(16).padStart(2,"0"))).join(""),t}}var Vn,zn,jn,qn,Gn,Hn,Jn,Qn,Kn,Zn,Xn,Yn,er,tr,sr,ir,nr,rr,ar,or,cr;const hr=T("FirmwareManager",{log:!0}),lr=["smp"],gr=[...lr,"firmwareImages","firmwareUploadProgress","firmwareStatus","firmwareUploadComplete"],fr=["idle","uploading","uploaded","pending","testing","erasing"];class ur{constructor(){Vn.add(this),jn.set(this,"idle"),Gn.set(this,void 0),Qn.set(this,void 0),Kn.set(this,new Pn),t(this,Vn,"m",Zn).call(this),H(this)}get addEventListenter(){return this.eventDispatcher.addEventListener}get removeEventListener(){return this.eventDispatcher.removeEventListener}get waitForEvent(){return this.eventDispatcher.waitForEvent}parseMessage(e,s){if(hr.log({messageType:e}),"smp"!==e)throw Error(`uncaught messageType ${e}`);t(this,Kn,"f")._notification(Array.from(new Uint8Array(s.buffer))),t(this,Vn,"a",zn).call(this,"smp",{dataView:s})}async uploadFirmware(e){hr.log("uploadFirmware",e);const s=this.waitForEvent("firmwareUploadComplete");await this.getImages();const i=await G(e),n=await t(this,Kn,"f").imageInfo(i);hr.log({imageInfo:n}),t(this,Kn,"f").cmdUpload(i,1),t(this,Vn,"m",qn).call(this,"uploading"),await s}get status(){return t(this,jn,"f")}get images(){return t(this,Gn,"f")}async getImages(){const e=this.waitForEvent("firmwareImages");hr.log("getting firmware image state..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageState()).buffer),await e}async testImage(e=1){if(t(this,Vn,"m",Jn).call(this,e),t(this,Vn,"m",Hn).call(this),!t(this,Gn,"f")[e])return void hr.log(`image ${e} not found`);if(1==t(this,Gn,"f")[e].pending)return void hr.log(`image ${e} is already pending`);if(t(this,Gn,"f")[e].empty)return void hr.log(`image ${e} is empty`);const s=this.waitForEvent("smp");hr.log("testing firmware image..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageTest(t(this,Gn,"f")[e].hash)).buffer),await s}async eraseImage(){t(this,Vn,"m",Hn).call(this);const e=this.waitForEvent("smp");hr.log("erasing image..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageErase()).buffer),t(this,Vn,"m",qn).call(this,"erasing"),await e,await this.getImages()}async confirmImage(e=0){if(t(this,Vn,"m",Jn).call(this,e),t(this,Vn,"m",Hn).call(this),!0===t(this,Gn,"f")[e].confirmed)return void hr.log(`image ${e} is already confirmed`);const s=this.waitForEvent("smp");hr.log("confirming image..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdImageConfirm(t(this,Gn,"f")[e].hash)).buffer),await s}async echo(e){hr.assertTypeWithError(e,"string");const s=this.waitForEvent("smp");hr.log("sending echo..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").smpEcho(e)).buffer),await s}async reset(){const e=this.waitForEvent("smp");hr.log("resetting..."),this.sendMessage(Uint8Array.from(t(this,Kn,"f").cmdReset()).buffer),await e}get mtu(){return t(this,Qn,"f")}set mtu(e){s(this,Qn,e,"f"),t(this,Kn,"f")._mtu=e}}var dr,mr,pr,vr,wr,yr,br,Sr,Er,Cr,Mr,Dr,kr,Tr,Wr,_r,Ir,Lr;jn=new WeakMap,Gn=new WeakMap,Qn=new WeakMap,Kn=new WeakMap,Vn=new WeakSet,zn=function(){return this.eventDispatcher.dispatchEvent},qn=function(e){hr.assertEnumWithError(e,fr),t(this,jn,"f")!=e?(s(this,jn,e,"f"),hr.log({firmwareStatus:t(this,jn,"f")}),t(this,Vn,"a",zn).call(this,"firmwareStatus",{firmwareStatus:t(this,jn,"f")})):hr.log(`redundant firmwareStatus assignment "${e}"`)},Hn=function(){hr.assertWithError(t(this,Gn,"f"),"didn't get imageState")},Jn=function(e){hr.assertTypeWithError(e,"number"),hr.assertWithError(0==e||1==e,"imageIndex must be 0 or 1")},Zn=function(){t(this,Kn,"f").onMessage(t(this,Vn,"m",Xn).bind(this)),t(this,Kn,"f").onFileDownloadNext(t(this,Vn,"m",Yn)),t(this,Kn,"f").onFileDownloadProgress(t(this,Vn,"m",er).bind(this)),t(this,Kn,"f").onFileDownloadFinished(t(this,Vn,"m",tr).bind(this)),t(this,Kn,"f").onFileUploadNext(t(this,Vn,"m",sr).bind(this)),t(this,Kn,"f").onFileUploadProgress(t(this,Vn,"m",ir).bind(this)),t(this,Kn,"f").onFileUploadFinished(t(this,Vn,"m",nr).bind(this)),t(this,Kn,"f").onImageUploadNext(t(this,Vn,"m",rr).bind(this)),t(this,Kn,"f").onImageUploadProgress(t(this,Vn,"m",ar).bind(this)),t(this,Kn,"f").onImageUploadFinished(t(this,Vn,"m",or).bind(this))},Xn=function({op:e,group:s,id:i,data:n,length:r}){switch(hr.log("onMcuMessage",...arguments),s){case In:switch(i){case Un:hr.log(`echo "${n.r}"`);break;case Rn:hr.table(n.tasks);break;case xn:hr.log(n)}break;case Ln:if(i===On)t(this,Vn,"m",cr).call(this,n);break;default:throw Error(`uncaught mcuMessage group ${s}`)}},Yn=function(){hr.log("onMcuFileDownloadNext",...arguments)},er=function(){hr.log("onMcuFileDownloadProgress",...arguments)},tr=function(){hr.log("onMcuFileDownloadFinished",...arguments)},sr=function(){hr.log("onMcuFileUploadNext")},ir=function(){hr.log("onMcuFileUploadProgress")},nr=function(){hr.log("onMcuFileUploadFinished")},rr=function({packet:e}){hr.log("onMcuImageUploadNext"),this.sendMessage(Uint8Array.from(e).buffer)},ar=function({percentage:e}){const s=e/100;hr.log("onMcuImageUploadProgress",...arguments),t(this,Vn,"a",zn).call(this,"firmwareUploadProgress",{progress:s})},or=async function(){hr.log("onMcuImageUploadFinished",...arguments),await this.getImages(),t(this,Vn,"a",zn).call(this,"firmwareUploadProgress",{progress:100}),t(this,Vn,"a",zn).call(this,"firmwareUploadComplete",{})},cr=function({images:e}){if(!e)return void hr.log("no images found");s(this,Gn,e,"f"),hr.log("images",t(this,Gn,"f"));let i="idle";2==t(this,Gn,"f").length&&(t(this,Gn,"f")[1].bootable?t(this,Gn,"f")[0].confirmed?t(this,Gn,"f")[1].pending?(hr.log("reset to upload to the new firmware image"),i="pending"):(hr.log("Slot 1 has a valid image. run testImage() to test it or upload a different image."),i="uploaded"):(hr.log('Slot 0 has a valid image. Click "Confirm Image" to confirm it or wait and the device will swap images back.'),i="testing"):hr.warn('Slot 1 has a invalid image. Click "Erase Image" to erase it or upload a different image')),1==t(this,Gn,"f").length&&(t(this,Gn,"f").push({slot:1,empty:!0,version:"Empty",pending:!1,confirmed:!1,bootable:!1,active:!1,permanent:!1}),hr.log("Select a firmware upload image to upload to slot 1.")),t(this,Vn,"m",qn).call(this,i),t(this,Vn,"a",zn).call(this,"firmwareImages",{firmwareImages:t(this,Gn,"f")})};const Fr=T("DeviceManager",{log:!0}),Ur=["deviceConnected","deviceDisconnected","deviceIsConnected","availableDevices","connectedDevices"];class Rr{constructor(){if(dr.add(this),mr.set(this,{getType:t(this,dr,"m",pr).bind(this),isConnected:t(this,dr,"m",_r).bind(this)}),vr.set(this,[]),wr.set(this,!1),yr.set(this,{devices:[]}),br.set(this,void 0),Er.set(this,"BS.Device"),kr.set(this,[]),Tr.set(this,new _(this,Ur)),Rr.shared&&this!=Rr.shared)throw Error("DeviceManager is a singleton - use DeviceManager.shared");this.CanUseLocalStorage&&(this.UseLocalStorage=!0)}onDevice(e){ji(e,t(this,mr,"f"))}OnDeviceConnectionStatusUpdated(e,s){if("notConnected"==s&&!e.canReconnect&&t(this,kr,"f").includes(e)){const s=t(this,kr,"f").indexOf(e);this.AvailableDevices.splice(s,1),t(this,dr,"m",Ir).call(this)}}get ConnectedDevices(){return t(this,vr,"f")}get UseLocalStorage(){return t(this,wr,"f")}set UseLocalStorage(e){t(this,dr,"m",Sr).call(this),Fr.assertTypeWithError(e,"boolean"),s(this,wr,e,"f"),t(this,wr,"f")&&!t(this,br,"f")&&t(this,dr,"m",Mr).call(this)}get CanUseLocalStorage(){return n&&window.localStorage}get AvailableDevices(){return t(this,kr,"f")}get CanGetDevices(){return n&&navigator.bluetooth?.getDevices}async GetDevices(){if(!n)return void Fr.warn("GetDevices is only available in the browser");if(!navigator.bluetooth)return void Fr.warn("bluetooth is not available in this browser");if(c)return void Fr.warn("bluefy lists too many devices...");if(!navigator.bluetooth.getDevices)return void Fr.warn("bluetooth.getDevices() is not available in this browser");if(!this.CanGetDevices)return void Fr.log("CanGetDevices is false");t(this,br,"f")||t(this,dr,"m",Mr).call(this);const e=t(this,br,"f");if(!e.devices||0==e.devices.length)return void Fr.log("no devices found in configuration");const s=await navigator.bluetooth.getDevices();return Fr.log({bluetoothDevices:s}),s.forEach((s=>{if(!s.gatt)return;let i=e.devices.find((e=>s.id==e.bluetoothId));if(!i)return;let n=this.ConnectedDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));const r=this.AvailableDevices.filter((e=>"webBluetooth"==e.connectionType)).find((e=>e.bluetoothId==s.id));if(r)return void(n&&n?.bluetoothId==r.bluetoothId&&n!=r&&(this.AvailableDevices[t(this,kr,"f").indexOf(r)]=n));if(n)return void this.AvailableDevices.push(n);const a=new Ma,o=new Sn;o.device=s,s.name&&a._informationManager.updateName(s.name),a._informationManager.updateType(i.type),a.connectionManager=o,this.AvailableDevices.push(a)})),t(this,dr,"m",Ir).call(this),this.AvailableDevices}get AddEventListener(){return t(this,Tr,"f").addEventListener}get RemoveEventListener(){return t(this,Tr,"f").removeEventListener}get RemoveEventListeners(){return t(this,Tr,"f").removeEventListeners}get RemoveAllEventListeners(){return t(this,Tr,"f").removeAllEventListeners}}mr=new WeakMap,vr=new WeakMap,wr=new WeakMap,yr=new WeakMap,br=new WeakMap,Er=new WeakMap,kr=new WeakMap,Tr=new WeakMap,dr=new WeakSet,pr=function(e){t(this,wr,"f")&&t(this,dr,"m",Dr).call(this,e.target)},Sr=function(){Fr.assertWithError(n,"localStorage is only available in the browser"),Fr.assertWithError(window.localStorage,"localStorage not found")},Cr=function(){t(this,dr,"m",Sr).call(this),localStorage.setItem(t(this,Er,"f"),JSON.stringify(t(this,br,"f")))},Mr=async function(){t(this,dr,"m",Sr).call(this);let e=localStorage.getItem(t(this,Er,"f"));if("string"!=typeof e)return Fr.log("no info found in localStorage"),s(this,br,Object.assign({},t(this,yr,"f")),"f"),void t(this,dr,"m",Cr).call(this);try{const t=JSON.parse(e);Fr.log({configuration:t}),s(this,br,t,"f"),this.CanGetDevices&&await this.GetDevices()}catch(e){Fr.error(e)}},Dr=function(e){if("webBluetooth"!=e.connectionType)return void Fr.log("localStorage is only for webBluetooth devices");t(this,dr,"m",Sr).call(this);const s=t(this,br,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1!=s&&(t(this,br,"f").devices[s].type=e.type,t(this,dr,"m",Cr).call(this))},Wr=function(){return t(this,Tr,"f").dispatchEvent},_r=function(e){const{target:s}=e;if(s.isConnected)if(t(this,vr,"f").includes(s))Fr.log("device already included");else{if(Fr.log("adding device",s),t(this,vr,"f").push(s),this.UseLocalStorage&&"webBluetooth"==s.connectionType){const e={type:s.type,bluetoothId:s.bluetoothId},i=t(this,br,"f").devices.findIndex((t=>t.bluetoothId==e.bluetoothId));-1==i?t(this,br,"f").devices.push(e):t(this,br,"f").devices[i]=e,t(this,dr,"m",Cr).call(this)}t(this,dr,"a",Wr).call(this,"deviceConnected",{device:s}),t(this,dr,"a",Wr).call(this,"deviceIsConnected",{device:s}),t(this,dr,"m",Lr).call(this)}else t(this,vr,"f").includes(s)?(Fr.log("removing device",s),t(this,vr,"f").splice(t(this,vr,"f").indexOf(s),1),t(this,dr,"a",Wr).call(this,"deviceDisconnected",{device:s}),t(this,dr,"a",Wr).call(this,"deviceIsConnected",{device:s}),t(this,dr,"m",Lr).call(this)):Fr.log("device already not included");if(this.CanGetDevices&&this.GetDevices(),s.isConnected&&!this.AvailableDevices.includes(s)){const e=this.AvailableDevices.find((e=>e.bluetoothId==s.bluetoothId));Fr.log({existingAvailableDevice:e}),e?this.AvailableDevices[this.AvailableDevices.indexOf(e)]=s:this.AvailableDevices.push(s),t(this,dr,"m",Ir).call(this)}},Ir=function(){Fr.log({AvailableDevices:this.AvailableDevices}),t(this,dr,"a",Wr).call(this,"availableDevices",{availableDevices:this.AvailableDevices})},Lr=function(){Fr.log({ConnectedDevices:this.ConnectedDevices}),t(this,dr,"a",Wr).call(this,"connectedDevices",{connectedDevices:this.ConnectedDevices})},Rr.shared=new Rr;var xr,Ar,Or,$r,Br,Nr,Pr,Vr,zr,jr,qr,Gr,Hr,Jr,Qr,Kr,Zr,Xr,Yr,ea,ta,sa,ia,na,ra,aa,oa,ca,ha,la,ga,fa,ua,da=Rr.shared;const ma=T("Device",{log:!0}),pa=["connectionMessage",...Oi,...Ni,...Bi,...Ks,...ks,...xt,...wt,...Oe,...ms,...gr],va=["isCharging","getBatteryCurrent","getId","getMtu","getName","getType","getCurrentTime","getSensorConfiguration","getSensorScalars","getPressurePositions","maxFileLength","getFileLength","getFileChecksum","getFileType","fileTransferStatus","getTfliteName","getTfliteTask","getTfliteSampleRate","getTfliteSensorTypes","tfliteIsReady","getTfliteCaptureDelay","getTfliteThreshold","getTfliteInferencingEnabled"];class wa{get bluetoothId(){return t(this,Nr,"f")?.bluetoothId}constructor(){xr.add(this),$r.set(this,new _(this,pa)),Nr.set(this,void 0),this.sendTxMessages=t(this,xr,"m",Pr).bind(this),Vr.set(this,!1),Jr.set(this,Ar.ReconnectOnDisconnection),Qr.set(this,void 0),this.latestConnectionMessage=new Map,ta.set(this,new Ts),sa.set(this,0),this._informationManager=new Zs,na.set(this,new At),aa.set(this,Ar.ClearSensorConfigurationOnLeave),oa.set(this,new yt),ca.set(this,new bi),ha.set(this,new $e),la.set(this,new ws),ga.set(this,new ur),this.sendSmpMessage=t(this,xr,"m",fa).bind(this),ua.set(this,!1),t(this,ta,"f").eventDispatcher=t(this,$r,"f"),this._informationManager.sendMessage=this.sendTxMessages,this._informationManager.eventDispatcher=t(this,$r,"f"),t(this,na,"f").sendMessage=this.sendTxMessages,t(this,na,"f").eventDispatcher=t(this,$r,"f"),t(this,oa,"f").eventDispatcher=t(this,$r,"f"),t(this,ca,"f").sendMessage=this.sendTxMessages,t(this,la,"f").sendMessage=this.sendTxMessages,t(this,la,"f").eventDispatcher=t(this,$r,"f"),t(this,ha,"f").sendMessage=this.sendTxMessages,t(this,ha,"f").eventDispatcher=t(this,$r,"f"),t(this,ga,"f").sendMessage=this.sendSmpMessage,t(this,ga,"f").eventDispatcher=t(this,$r,"f"),this.addEventListener("getMtu",(()=>{t(this,ga,"f").mtu=this.mtu,t(this,ha,"f").mtu=this.mtu,this.connectionManager.mtu=this.mtu})),da.onDevice(this),n&&window.addEventListener("beforeunload",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()})),r&&process.on("exit",(()=>{this.isConnected&&this.clearSensorConfigurationOnLeave&&this.clearSensorConfiguration()}))}get addEventListener(){return t(this,$r,"f").addEventListener}get removeEventListener(){return t(this,$r,"f").removeEventListener}get waitForEvent(){return t(this,$r,"f").waitForEvent}get removeEventListeners(){return t(this,$r,"f").removeEventListeners}get removeAllEventListeners(){return t(this,$r,"f").removeAllEventListeners}get connectionManager(){return t(this,Nr,"f")}set connectionManager(e){this.connectionManager!=e?(this.connectionManager&&(this.connectionManager.onStatusUpdated=void 0,this.connectionManager.onMessageReceived=void 0),e&&(e.onStatusUpdated=t(this,xr,"m",Kr).bind(this),e.onMessageReceived=t(this,xr,"m",ea).bind(this)),s(this,Nr,e,"f"),ma.log("assigned new connectionManager",t(this,Nr,"f"))):ma.log("same connectionManager is already assigned")}async connect(){return this.connectionManager||(this.connectionManager=t(Ar,Ar,"m",Or).call(Ar)),t(this,xr,"m",Yr).call(this),this.connectionManager.connect()}get isConnected(){return t(this,Vr,"f")}get canReconnect(){return this.connectionManager?.canReconnect}async reconnect(){return t(this,xr,"m",Gr).call(this),t(this,xr,"m",Yr).call(this),this.connectionManager?.reconnect()}static async Connect(){const e=new Ar;return await e.connect(),e}static get ReconnectOnDisconnection(){return t(this,Ar,"f",Hr)}static set ReconnectOnDisconnection(e){ma.assertTypeWithError(e,"boolean"),s(this,Ar,e,"f",Hr)}get reconnectOnDisconnection(){return t(this,Jr,"f")}set reconnectOnDisconnection(e){ma.assertTypeWithError(e,"boolean"),s(this,Jr,e,"f")}get connectionType(){return this.connectionManager?.type}async disconnect(){return t(this,xr,"m",zr).call(this),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.addEventListener("isConnected",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this.connectionManager.disconnect()}toggleConnection(){this.isConnected?this.disconnect():this.canReconnect?this.reconnect():this.connect()}get connectionStatus(){switch(t(this,Nr,"f")?.status){case"connected":return this.isConnected?"connected":"connecting";case"notConnected":case"connecting":case"disconnecting":return t(this,Nr,"f").status;default:return"notConnected"}}get isConnectionBusy(){return"connecting"==this.connectionStatus||"disconnecting"==this.connectionStatus}get deviceInformation(){return t(this,ta,"f").information}get batteryLevel(){return t(this,sa,"f")}get id(){return this._informationManager.id}get isCharging(){return this._informationManager.isCharging}get batteryCurrent(){return this._informationManager.batteryCurrent}get getBatteryCurrent(){return this._informationManager.getBatteryCurrent}get name(){return this._informationManager.name}get setName(){return this._informationManager.setName}get type(){return this._informationManager.type}get setType(){return this._informationManager.setType}get isInsole(){return this._informationManager.isInsole}get insoleSide(){return this._informationManager.insoleSide}get mtu(){return this._informationManager.mtu}get sensorTypes(){return Object.keys(this.sensorConfiguration)}get continuousSensorTypes(){return pt.filter((e=>this.sensorTypes.includes(e)))}get sensorConfiguration(){return t(this,na,"f").configuration}async setSensorConfiguration(e,s){await t(this,na,"f").setConfiguration(e,s)}async clearSensorConfiguration(){return t(this,na,"f").clearSensorConfiguration()}static get ClearSensorConfigurationOnLeave(){return t(this,Ar,"f",ra)}static set ClearSensorConfigurationOnLeave(e){ma.assertTypeWithError(e,"boolean"),s(this,Ar,e,"f",ra)}get clearSensorConfigurationOnLeave(){return t(this,aa,"f")}set clearSensorConfigurationOnLeave(e){ma.assertTypeWithError(e,"boolean"),s(this,aa,e,"f")}get numberOfPressureSensors(){return t(this,oa,"f").pressureSensorDataManager.numberOfSensors}resetPressureRange(){t(this,oa,"f").pressureSensorDataManager.resetRange()}async triggerVibration(e,s){t(this,ca,"f").triggerVibration(e,s)}get maxFileLength(){return t(this,ha,"f").maxLength}async sendFile(e,s){const i=this.waitForEvent("fileTransferComplete");t(this,ha,"f").send(e,s),await i}async receiveFile(e){const s=this.waitForEvent("fileTransferComplete");t(this,ha,"f").receive(e),await s}get fileTransferStatus(){return t(this,ha,"f").status}cancelFileTransfer(){t(this,ha,"f").cancel()}get tfliteName(){return t(this,la,"f").name}get setTfliteName(){return t(this,la,"f").setName}get tfliteTask(){return t(this,la,"f").task}get setTfliteTask(){return t(this,la,"f").setTask}get tfliteSampleRate(){return t(this,la,"f").sampleRate}get setTfliteSampleRate(){return t(this,la,"f").setSampleRate}get tfliteSensorTypes(){return t(this,la,"f").sensorTypes}get allowedTfliteSensorTypes(){return this.sensorTypes.filter((e=>vs.includes(e)))}get setTfliteSensorTypes(){return t(this,la,"f").setSensorTypes}get tfliteIsReady(){return t(this,la,"f").isReady}get tfliteInferencingEnabled(){return t(this,la,"f").inferencingEnabled}get setTfliteInferencingEnabled(){return t(this,la,"f").setInferencingEnabled}async enableTfliteInferencing(){return this.setTfliteInferencingEnabled(!0)}async disableTfliteInferencing(){return this.setTfliteInferencingEnabled(!1)}get toggleTfliteInferencing(){return t(this,la,"f").toggleInferencingEnabled}get tfliteCaptureDelay(){return t(this,la,"f").captureDelay}get setTfliteCaptureDelay(){return t(this,la,"f").setCaptureDelay}get tfliteThreshold(){return t(this,la,"f").threshold}get setTfliteThreshold(){return t(this,la,"f").setThreshold}get uploadFirmware(){return t(this,ga,"f").uploadFirmware}async reset(){return await t(this,ga,"f").reset(),t(this,Nr,"f").disconnect()}get firmwareStatus(){return t(this,ga,"f").status}get getFirmwareImages(){return t(this,ga,"f").getImages}get firmwareImages(){return t(this,ga,"f").images}get eraseFirmwareImage(){return t(this,ga,"f").eraseImage}get confirmFirmwareImage(){return t(this,ga,"f").confirmImage}get testFirmwareImage(){return t(this,ga,"f").testImage}get isServerSide(){return t(this,ua,"f")}set isServerSide(e){t(this,ua,"f")!=e?(ma.log({newIsServerSide:e}),s(this,ua,e,"f"),t(this,ha,"f").isServerSide=this.isServerSide):ma.log("redundant isServerSide assignment")}}Ar=wa,$r=new WeakMap,Nr=new WeakMap,Vr=new WeakMap,Jr=new WeakMap,Qr=new WeakMap,ta=new WeakMap,sa=new WeakMap,na=new WeakMap,aa=new WeakMap,oa=new WeakMap,ca=new WeakMap,ha=new WeakMap,la=new WeakMap,ga=new WeakMap,ua=new WeakMap,xr=new WeakSet,Or=function(){return new Sn},Br=function(){return t(this,$r,"f").dispatchEvent},Pr=async function(e,s){await(t(this,Nr,"f")?.sendTxMessages(e,s))},zr=function(){ma.assertWithError(this.isConnected,"notConnected")},jr=function(){return va.every((e=>this.latestConnectionMessage.has(e)))},qr=function(){const e=va.map((e=>({type:e})));t(this,xr,"m",Pr).call(this,e)},Gr=function(){ma.assertWithError(this.canReconnect,"cannot reconnect to device")},Kr=function(e){ma.log({connectionStatus:e}),"notConnected"==e?this.canReconnect&&this.reconnectOnDisconnection&&(ma.log("starting reconnect interval..."),s(this,Qr,setInterval((()=>{ma.log("attempting reconnect..."),this.reconnect()}),1e3),"f")):null!=t(this,Qr,"f")&&(ma.log("clearing reconnect interval"),clearInterval(t(this,Qr,"f")),s(this,Qr,void 0,"f")),t(this,xr,"m",Xr).call(this),"connected"!=e||t(this,Vr,"f")||t(this,xr,"m",qr).call(this),da.OnDeviceConnectionStatusUpdated(this,e)},Zr=function(e=!1){t(this,xr,"a",Br).call(this,"connectionStatus",{connectionStatus:this.connectionStatus}),t(this,xr,"a",Br).call(this,this.connectionStatus,{}),e&&t(this,xr,"a",Br).call(this,"isConnected",{isConnected:this.isConnected})},Xr=function(){switch(s(this,Vr,Boolean(this.connectionManager?.isConnected)&&t(this,xr,"a",jr)&&this._informationManager.isCurrentTimeSet,"f"),this.connectionStatus){case"connected":t(this,Vr,"f")&&t(this,xr,"m",Zr).call(this,!0);break;case"notConnected":t(this,xr,"m",Zr).call(this,!0);break;default:t(this,xr,"m",Zr).call(this,!1)}},Yr=function(){this.latestConnectionMessage.clear(),this._informationManager.clear(),t(this,ta,"f").clear()},ea=function(e,s){if(ma.log({messageType:e,dataView:s}),"batteryLevel"===e){const e=s.getUint8(0);ma.log("received battery level",{batteryLevel:e}),t(this,xr,"m",ia).call(this,e)}else if(Ue.includes(e))t(this,ha,"f").parseMessage(e,s);else if(ds.includes(e))t(this,la,"f").parseMessage(e,s);else if(vt.includes(e))t(this,oa,"f").parseMessage(e,s);else if(lr.includes(e))t(this,ga,"f").parseMessage(e,s);else if(Ds.includes(e))t(this,ta,"f").parseMessage(e,s);else if(Qs.includes(e))this._informationManager.parseMessage(e,s);else{if(!Rt.includes(e))throw Error(`uncaught messageType ${e}`);t(this,na,"f").parseMessage(e,s)}this.latestConnectionMessage.set(e,s),t(this,xr,"a",Br).call(this,"connectionMessage",{messageType:e,dataView:s}),!this.isConnected&&t(this,xr,"a",jr)&&t(this,xr,"m",Xr).call(this)},ia=function(e){ma.assertTypeWithError(e,"number"),t(this,sa,"f")!=e?(s(this,sa,e,"f"),ma.log({updatedBatteryLevel:t(this,sa,"f")}),t(this,xr,"a",Br).call(this,"batteryLevel",{batteryLevel:t(this,sa,"f")})):ma.log(`duplicate batteryLevel assignment ${e}`)},fa=function(e){return t(this,Nr,"f").sendSmpMessage(e)},Hr={value:!1},ra={value:!0};var ya,ba,Sa,Ea,Ca,Ma=wa;const Da=T("DevicePairPressureSensorDataManager",{log:!0});class ka{constructor(){ya.add(this),ba.set(this,{}),Sa.set(this,new Qe)}resetPressureRange(){t(this,Sa,"f").reset()}onDevicePressureData(e){const{pressure:s}=e.message,i=e.target.insoleSide;if(Da.log({pressure:s,insoleSide:i}),t(this,ba,"f")[i]=s,t(this,ya,"a",Ea))return t(this,ya,"m",Ca).call(this);Da.log("doesn't have all pressure data yet...")}}var Ta;ba=new WeakMap,Sa=new WeakMap,ya=new WeakSet,Ea=function(){return Js.every((e=>e in t(this,ba,"f")))},Ca=function(){const e={rawSum:0,normalizedSum:0};return Js.forEach((s=>{e.rawSum+=t(this,ba,"f")[s].scaledSum,e.normalizedSum+=t(this,ba,"f")[s].normalizedSum})),e.normalizedSum>.001&&(e.center={x:0,y:0},Js.forEach((s=>{const i=t(this,ba,"f")[s],n=i.normalizedSum/e.normalizedSum;n>0&&(null!=i.normalizedCenter?.y&&(e.center.y+=i.normalizedCenter.y*n),"right"==s&&(e.center.x=n))})),e.normalizedCenter=t(this,Sa,"f").updateAndGetNormalization(e.center)),Da.log({devicePairPressure:e}),e};const Wa=T("DevicePairSensorDataManager",{log:!0}),_a=["pressure","sensorData"];class Ia{constructor(){Ta.set(this,{}),this.pressureSensorDataManager=new ka}get dispatchEvent(){return this.eventDispatcher.dispatchEvent}resetPressureRange(){this.pressureSensorDataManager.resetPressureRange()}onDeviceSensorData(e){const{timestamp:s,sensorType:i}=e.message;let n;if(Wa.log({sensorType:i,timestamp:s,event:e}),t(this,Ta,"f")[i]||(t(this,Ta,"f")[i]={}),t(this,Ta,"f")[i][e.target.insoleSide]=s,"pressure"===i)n=this.pressureSensorDataManager.onDevicePressureData(e);else Wa.log(`uncaught sensorType "${i}"`);if(n){const e=Object.assign({},t(this,Ta,"f")[i]);this.dispatchEvent(i,{sensorType:i,timestamps:e,[i]:n}),this.dispatchEvent("sensorData",{sensorType:i,timestamps:e,[i]:n})}else Wa.log("no value received")}}var La,Fa,Ua,Ra,xa,Aa,Oa,$a,Ba,Na,Pa,Va,za,ja,qa,Ga;Ta=new WeakMap;const Ha=T("DevicePair",{log:!0});function Ja(e){return`device${t=e,t[0].toUpperCase()+t.slice(1)}`;var t}const Qa=["isConnected",..._a,...pa.map((e=>Ja(e)))];class Ka{constructor(){La.add(this),Ua.set(this,new _(this,Qa)),xa.set(this,void 0),Aa.set(this,void 0),Na.set(this,{isConnected:t(this,La,"m",Va).bind(this),sensorData:t(this,La,"m",qa).bind(this),getType:t(this,La,"m",za).bind(this)}),ja.set(this,new Ia),t(this,ja,"f").eventDispatcher=t(this,Ua,"f")}get sides(){return Js}get addEventListener(){return t(this,Ua,"f").addEventListener}get removeEventListener(){return t(this,Ua,"f").removeEventListener}get waitForEvent(){return t(this,Ua,"f").waitForEvent}get removeEventListeners(){return t(this,Ua,"f").removeEventListeners}get removeAllEventListeners(){return t(this,Ua,"f").removeAllEventListeners}get left(){return t(this,xa,"f")}get right(){return t(this,Aa,"f")}get isConnected(){return Js.every((e=>this[e]?.isConnected))}get isPartiallyConnected(){return Js.some((e=>this[e]?.isConnected))}get isHalfConnected(){return this.isPartiallyConnected&&!this.isConnected}assignInsole(e){if(!e.isInsole)return void Ha.warn("device is not an insole");const i=e.insoleSide,n=this[i];if(e!=n){switch(n&&t(this,La,"m",$a).call(this,n),t(this,La,"m",Oa).call(this,e),i){case"left":s(this,xa,e,"f");break;case"right":s(this,Aa,e,"f")}return Ha.log(`assigned ${i} insole`,e),this.resetPressureRange(),t(this,La,"a",Ra).call(this,"isConnected",{isConnected:this.isConnected}),t(this,La,"a",Ra).call(this,"deviceIsConnected",{device:e,isConnected:e.isConnected,side:i}),n}Ha.log("device already assigned")}setSensorConfiguration(e){Js.forEach((t=>{this[t]?.isConnected&&this[t]?.setSensorConfiguration(e)}))}resetPressureRange(){t(this,ja,"f").resetPressureRange()}async triggerVibration(e,t){const s=Js.map((s=>this[s]?.triggerVibration(e,t))).filter(Boolean);return Promise.allSettled(s)}static get shared(){return t(this,Fa,"f",Ga)}}Fa=Ka,Ua=new WeakMap,xa=new WeakMap,Aa=new WeakMap,Na=new WeakMap,ja=new WeakMap,La=new WeakSet,Ra=function(){return t(this,Ua,"f").dispatchEvent},Oa=function(e){ji(e,t(this,Na,"f")),pa.forEach((s=>{e.addEventListener(s,t(this,La,"m",Pa).bind(this))}))},$a=function(e){qi(e,t(this,Na,"f")),pa.forEach((s=>{e.removeEventListener(s,t(this,La,"m",Pa).bind(this))}))},Ba=function(e){const s=Js.some((s=>this[s]==e&&(Ha.log(`removing ${s} insole`,e),qi(e,t(this,Na,"f")),delete this[s],!0)));return s&&t(this,La,"a",Ra).call(this,"isConnected",{isConnected:this.isConnected}),s},Pa=function(e){const{type:s,target:i,message:n}=e;t(this,La,"a",Ra).call(this,Ja(s),{...n,device:i,side:i.insoleSide})},Va=function(e){t(this,La,"a",Ra).call(this,"isConnected",{isConnected:this.isConnected})},za=function(e){const{target:s}=e;if(this[s.insoleSide]==s)return;t(this,La,"m",Ba).call(this,s)&&this.assignInsole(s)},qa=function(e){this.isConnected&&t(this,ja,"f").onDeviceSensorData(e)},Ga={value:new Fa},da.AddEventListener("deviceConnected",(e=>{const{device:s}=e.message;s.isInsole&&t(Fa,Fa,"f",Ga).assignInsole(s)}));const Za=T("ServerUtils",{log:!1}),Xa=["isScanningAvailable","isScanning","startScan","stopScan","discoveredDevice","discoveredDevices","expiredDiscoveredDevice","connectToDevice","disconnectFromDevice","connectedDevices","deviceMessage"];function Ya(e,...t){Za.log("createMessage",...t);const s=t.map((t=>{"string"==typeof t&&(t={type:t}),null!=t.data?Array.isArray(t.data)||(t.data=[t.data]):t.data=[];const s=z(...t.data),i=s.byteLength;Za.assertEnumWithError(t.type,e);const n=e.indexOf(t.type),r=new DataView(new ArrayBuffer(2));return r.setUint16(0,i,!0),z(n,r,s)}));return Za.log("messageBuffers",...s),z(...s)}function eo(...e){return Za.log("createServerMessage",...e),Ya(Xa,...e)}function to(...e){return Za.log("createClientDeviceMessage",...e),Ya(Pi,...e)}var so,io,no,ro,ao;eo("isScanningAvailable"),eo("isScanning"),eo("startScan"),eo("stopScan"),eo("discoveredDevices");const oo=T("ClientConnectionManager",{log:!0}),co=[...Ds,"batteryLevel"];class ho extends Vi{constructor(){super(...arguments),so.add(this),io.set(this,void 0),no.set(this,!1)}static get isSupported(){return n}static get type(){return"client"}get bluetoothId(){return t(this,io,"f")}set bluetoothId(e){oo.assertTypeWithError(e,"string"),t(this,io,"f")!=e?s(this,io,e,"f"):oo.log("redundant bluetoothId assignment")}get isConnected(){return t(this,no,"f")}set isConnected(e){oo.assertTypeWithError(e,"boolean"),t(this,no,"f")!=e?(s(this,no,e,"f"),this.status=t(this,no,"f")?"connected":"notConnected",this.isConnected&&t(this,so,"m",ro).call(this)):oo.log("redundant newIsConnected assignment",e)}async connect(){await super.connect(),this.sendClientConnectMessage()}async disconnect(){await super.disconnect(),this.sendClientDisconnectMessage()}get canReconnect(){return!0}async reconnect(){await super.reconnect(),oo.log("attempting to reconnect..."),this.connect()}async sendSmpMessage(e){super.sendSmpMessage(e),this.sendClientMessage({type:"smp",data:e})}async sendTxData(e){super.sendTxData(e),this.sendClientMessage({type:"tx",data:e})}onClientMessage(e){oo.log({dataView:e}),ft(e,pa,t(this,so,"m",ao).bind(this),null,!0)}}var lo,go,fo,uo,mo,po,vo,wo,yo,bo,So,Eo,Co,Mo,Do,ko,To,Wo;io=new WeakMap,no=new WeakMap,so=new WeakSet,ro=function(){this.sendClientMessage(...co)},ao=function(e,t){let s=0;switch(oo.log({messageType:e},t),e){case"isConnected":const i=Boolean(t.getUint8(s++));oo.log({isConnected:i}),this.isConnected=i;break;case"rx":this.parseRxMessage(t);break;default:this.onMessageReceived(e,t)}};const _o=T("BaseClient",{log:!0}),Io=["notConnected","connecting","connected","disconnecting","connectionStatus","isConnected","isScanningAvailable","isScanning","discoveredDevice","expiredDiscoveredDevice"];class Lo{constructor(){lo.add(this),go.set(this,{}),fo.set(this,new _(this,Io)),this._reconnectOnDisconnection=this.baseConstructor.ReconnectOnDisconnection,uo.set(this,"notConnected"),po.set(this,!1),bo.set(this,!1),ko.set(this,{})}get baseConstructor(){return this.constructor}get devices(){return t(this,go,"f")}get addEventListener(){return t(this,fo,"f").addEventListener}get dispatchEvent(){return t(this,fo,"f").dispatchEvent}get removeEventListener(){return t(this,fo,"f").removeEventListener}get waitForEvent(){return t(this,fo,"f").waitForEvent}assertConnection(){_o.assertWithError(this.isConnected,"notConnected")}assertDisconnection(){_o.assertWithError(this.isDisconnected,"not disconnected")}static get ReconnectOnDisconnection(){return this._reconnectOnDisconnection}static set ReconnectOnDisconnection(e){_o.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get reconnectOnDisconnection(){return this._reconnectOnDisconnection}set reconnectOnDisconnection(e){_o.assertTypeWithError(e,"boolean"),this._reconnectOnDisconnection=e}get _connectionStatus(){return t(this,uo,"f")}set _connectionStatus(e){switch(_o.assertTypeWithError(e,"string"),_o.log({newConnectionStatus:e}),s(this,uo,e,"f"),this.dispatchEvent("connectionStatus",{connectionStatus:this.connectionStatus}),this.dispatchEvent(this.connectionStatus,{}),e){case"connected":case"notConnected":this.dispatchEvent("isConnected",{isConnected:this.isConnected}),this.isConnected?this.sendServerMessage("isScanningAvailable","discoveredDevices","connectedDevices"):(s(this,lo,!1,"a",wo),s(this,lo,!1,"a",Eo))}}get connectionStatus(){return this._connectionStatus}parseMessage(e){_o.log("parseMessage",{dataView:e}),ft(e,Xa,t(this,lo,"m",mo).bind(this),null,!0)}get isScanningAvailable(){return t(this,lo,"a",vo)}requestIsScanningAvailable(){this.sendServerMessage("isScanningAvailable")}get isScanning(){return t(this,lo,"a",So)}startScan(){t(this,lo,"m",Do).call(this),this.sendServerMessage("startScan")}stopScan(){t(this,lo,"m",Mo).call(this),this.sendServerMessage("stopScan")}toggleScan(){t(this,lo,"m",yo).call(this),this.isScanning?this.stopScan():this.startScan()}get discoveredDevices(){return t(this,ko,"f")}onDiscoveredDevice(e){_o.log({discoveredDevice:e}),t(this,ko,"f")[e.bluetoothId]=e,this.dispatchEvent("discoveredDevice",{discoveredDevice:e})}requestDiscoveredDevices(){this.sendServerMessage({type:"discoveredDevices"})}connectToDevice(e){return this.requestConnectionToDevice(e)}requestConnectionToDevice(e){this.assertConnection(),_o.assertTypeWithError(e,"string");const s=t(this,lo,"m",Wo).call(this,e);return s.connect(),s}sendConnectToDeviceMessage(e){this.sendServerMessage({type:"connectToDevice",data:e})}createDevice(e){const t=new Ma,s=new ho;return s.bluetoothId=e,s.sendClientMessage=this.sendDeviceMessage.bind(this,e),s.sendClientConnectMessage=this.sendConnectToDeviceMessage.bind(this,e),s.sendClientDisconnectMessage=this.sendDisconnectFromDeviceMessage.bind(this,e),t.connectionManager=s,t}onConnectedBluetoothDeviceIds(e){_o.log({bluetoothIds:e}),e.forEach((e=>{t(this,lo,"m",Wo).call(this,e).connectionManager.isConnected=!0}))}disconnectFromDevice(e){this.requestDisconnectionFromDevice(e)}requestDisconnectionFromDevice(e){this.assertConnection(),_o.assertTypeWithError(e,"string");const t=this.devices[e];return _o.assertWithError(t,`no device found with id ${e}`),t.disconnect(),t}sendDisconnectFromDeviceMessage(e){this.sendServerMessage({type:"disconnectFromDevice",data:e})}sendDeviceMessage(e,...t){this.sendServerMessage({type:"deviceMessage",data:[e,to(...t)]})}}go=new WeakMap,fo=new WeakMap,uo=new WeakMap,po=new WeakMap,bo=new WeakMap,ko=new WeakMap,lo=new WeakSet,mo=function(e,i){let n=0;switch(_o.log({messageType:e},i),e){case"isScanningAvailable":{const e=Boolean(i.getUint8(n++));_o.log({isScanningAvailable:e}),s(this,lo,e,"a",wo)}break;case"isScanning":{const e=Boolean(i.getUint8(n++));_o.log({isScanning:e}),s(this,lo,e,"a",Eo)}break;case"discoveredDevice":{const{string:e}=gt(i,n);_o.log({discoveredDeviceString:e});const t=JSON.parse(e);_o.log({discoveredDevice:t}),this.onDiscoveredDevice(t)}break;case"expiredDiscoveredDevice":{const{string:e}=gt(i,n);t(this,lo,"m",To).call(this,e)}break;case"connectedDevices":{if(0==i.byteLength)break;const{string:e}=gt(i,n);_o.log({connectedBluetoothDeviceIdStrings:e});const t=JSON.parse(e);_o.log({connectedBluetoothDeviceIds:t}),this.onConnectedBluetoothDeviceIds(t)}break;case"deviceMessage":{const{string:e,byteOffset:s}=gt(i,n);n=s;const r=t(this,go,"f")[e];_o.assertWithError(r,`no device found for id ${e}`);const a=r.connectionManager,o=q(i,n);a.onClientMessage(o)}break;default:_o.error(`uncaught messageType "${e}"`)}},vo=function(){return t(this,po,"f")},wo=function(e){_o.assertTypeWithError(e,"boolean"),s(this,po,e,"f"),this.dispatchEvent("isScanningAvailable",{isScanningAvailable:this.isScanningAvailable}),this.isScanningAvailable&&t(this,lo,"m",Co).call(this)},yo=function(){this.assertConnection(),_o.assertWithError(this.isScanningAvailable,"scanning is not available")},So=function(){return t(this,bo,"f")},Eo=function(e){_o.assertTypeWithError(e,"boolean"),s(this,bo,e,"f"),this.dispatchEvent("isScanning",{isScanning:this.isScanning})},Co=function(){this.sendServerMessage("isScanning")},Mo=function(){_o.assertWithError(this.isScanning,"is not scanning")},Do=function(){_o.assertWithError(!this.isScanning,"is already scanning")},To=function(e){_o.log({expiredBluetoothDeviceId:e});const s=t(this,ko,"f")[e];s?(_o.log({expiredDiscoveredDevice:s}),delete t(this,ko,"f")[e],this.dispatchEvent("expiredDiscoveredDevice",{discoveredDevice:s})):_o.warn(`no discoveredDevice found with id "${e}"`)},Wo=function(e){let s=t(this,go,"f")[e];return s||(s=this.createDevice(e),t(this,go,"f")[e]=s),s},Lo._reconnectOnDisconnection=!0;const Fo=T("WebSocketUtils",{log:!1}),Uo=["ping","pong","serverMessage"];function Ro(...e){return Fo.log("createWebSocketMessage",...e),Ya(Uo,...e)}var xo,Ao,Oo,$o,Bo,No,Po,Vo,zo,jo,qo,Go,Ho;Ro("ping"),Ro("pong");const Jo=T("WebSocketClient",{log:!0});Ao=new WeakMap,$o=new WeakMap,qo=new WeakMap,xo=new WeakSet,Oo=function(...e){this.sendMessage(Ro(...e))},Bo=function(e){Jo.log("webSocket.open",e),t(this,qo,"f").start(),this._connectionStatus="connected"},No=async function(e){Jo.log("webSocket.message",e),t(this,qo,"f").restart();const s=await e.data.arrayBuffer(),i=new DataView(s);t(this,xo,"m",zo).call(this,i)},Po=function(e){Jo.log("webSocket.close",e),this._connectionStatus="notConnected",Object.entries(this.devices).forEach((([e,t])=>{t.connectionManager.isConnected=!1})),t(this,qo,"f").stop(),this.reconnectOnDisconnection&&setTimeout((()=>{this.reconnect()}),3e3)},Vo=function(e){Jo.error("webSocket.error",e.message)},zo=function(e){ft(e,Uo,t(this,xo,"m",jo).bind(this),null,!0)},jo=function(e,s){switch(e){case"ping":t(this,xo,"m",Ho).call(this);break;case"pong":break;case"serverMessage":this.parseMessage(s);break;default:Jo.error(`uncaught messageType "${e}"`)}},Go=function(){t(this,xo,"m",Oo).call(this,"ping")},Ho=function(){t(this,xo,"m",Oo).call(this,"pong")},e.ContinuousSensorTypes=pt,e.DefaultNumberOfPressureSensors=8,e.Device=Ma,e.DeviceManager=da,e.DevicePair=Ka,e.DeviceTypes=Hs,e.Environment=y,e.FileTransferDirections=["sending","receiving"],e.FileTypes=Re,e.InsoleSides=Js,e.MaxNameLength=30,e.MaxNumberOfVibrationWaveformEffectSegments=8,e.MaxNumberOfVibrationWaveformSegments=20,e.MaxSensorRate=65535,e.MaxVibrationWaveformEffectSegmentDelay=yi,e.MaxVibrationWaveformEffectSegmentLoopCount=3,e.MaxVibrationWaveformEffectSequenceLoopCount=6,e.MaxVibrationWaveformSegmentDuration=wi,e.MinNameLength=2,e.SensorRateStep=5,e.SensorTypes=mt,e.TfliteSensorTypes=vs,e.TfliteTasks=ps,e.VibrationLocations=pi,e.VibrationTypes=vi,e.VibrationWaveformEffects=Xs,e.WebSocketClient=class extends Lo{constructor(){super(...arguments),xo.add(this),Ao.set(this,void 0),$o.set(this,{open:t(this,xo,"m",Bo).bind(this),message:t(this,xo,"m",No).bind(this),close:t(this,xo,"m",Po).bind(this),error:t(this,xo,"m",Vo).bind(this)}),qo.set(this,new R(t(this,xo,"m",Go).bind(this),3e7))}get webSocket(){return t(this,Ao,"f")}set webSocket(e){t(this,Ao,"f")!=e?(Jo.log("assigning webSocket",e),t(this,Ao,"f")&&qi(t(this,Ao,"f"),t(this,$o,"f")),ji(e,t(this,$o,"f")),s(this,Ao,e,"f"),Jo.log("assigned webSocket")):Jo.log("redundant webSocket assignment")}get readyState(){return this.webSocket?.readyState}get isConnected(){return this.readyState==WebSocket.OPEN}get isDisconnected(){return this.readyState==WebSocket.CLOSED}connect(e=`wss://${location.host}`){this.webSocket&&this.assertDisconnection(),this._connectionStatus="connecting",this.webSocket=new WebSocket(e)}disconnect(){this.assertConnection(),this.reconnectOnDisconnection&&(this.reconnectOnDisconnection=!1,this.webSocket.addEventListener("close",(()=>{this.reconnectOnDisconnection=!0}),{once:!0})),this._connectionStatus="disconnecting",this.webSocket.close()}reconnect(){this.assertDisconnection(),this.webSocket=new WebSocket(this.webSocket.url)}toggleConnection(e){this.isConnected?this.disconnect():e&&this.webSocket?.url==e?this.reconnect():this.connect(e)}sendMessage(e){this.assertConnection(),t(this,Ao,"f").send(e)}sendServerMessage(...e){this.sendMessage(Ro({type:"serverMessage",data:eo(...e)}))}},e.setAllConsoleLevelFlags=function(e){k.setAllLevelFlags(e)},e.setConsoleLevelFlagsForType=function(e,t){k.setLevelFlagsForType(e,t)}}));
6
6
  //# sourceMappingURL=brilliantsole.min.js.map