@blueharford/scrypted-spatial-awareness 0.1.4 → 0.1.5
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.
- package/dist/main.nodejs.js +1 -1
- package/dist/main.nodejs.js.map +1 -1
- package/dist/plugin.zip +0 -0
- package/package.json +1 -1
- package/src/main.ts +96 -2
package/dist/main.nodejs.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
/*! For license information please see main.nodejs.js.LICENSE.txt */
|
|
2
|
-
(()=>{var e={128(e,t){"use strict";function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.validateTopic=r,t.validateTopics=function(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}},181(e){"use strict";e.exports=require("buffer")},277(e,t,r){"use strict";const{ArrayIsArray:n,ArrayPrototypeIncludes:i,ArrayPrototypeJoin:o,ArrayPrototypeMap:s,NumberIsInteger:a,NumberIsNaN:c,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:u,NumberParseInt:d,ObjectPrototypeHasOwnProperty:h,RegExpPrototypeExec:p,String:f,StringPrototypeToUpperCase:g,StringPrototypeTrim:m}=r(4134),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:y,ERR_INVALID_ARG_TYPE:_,ERR_INVALID_ARG_VALUE:v,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:w}}=r(6371),{normalizeEncoding:k}=r(7760),{isAsyncFunction:E,isArrayBufferView:I}=r(7760).types,T={};const O=/^[0-7]+$/;const C=b((e,t,r=u,n=l)=>{if("number"!=typeof e)throw new _(t,"number",e);if(!a(e))throw new S(t,"an integer",e);if(e<r||e>n)throw new S(t,`>= ${r} && <= ${n}`,e)}),A=b((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new _(t,"number",e);if(!a(e))throw new S(t,"an integer",e);if(e<r||e>n)throw new S(t,`>= ${r} && <= ${n}`,e)}),x=b((e,t,r=!1)=>{if("number"!=typeof e)throw new _(t,"number",e);if(!a(e))throw new S(t,"an integer",e);const n=r?1:0,i=4294967295;if(e<n||e>i)throw new S(t,`>= ${n} && <= ${i}`,e)});function P(e,t){if("string"!=typeof e)throw new _(t,"string",e)}const R=b((e,t,r)=>{if(!i(r,e)){const n=o(s(r,e=>"string"==typeof e?`'${e}'`:f(e)),", ");throw new v(t,e,"must be one of: "+n)}});function M(e,t){if("boolean"!=typeof e)throw new _(t,"boolean",e)}function B(e,t,r){return null!=e&&h(e,t)?e[t]:r}const N=b((e,t,r=null)=>{const i=B(r,"allowArray",!1),o=B(r,"allowFunction",!1);if(!B(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new _(t,"Object",e)}),j=b((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new _(t,"a dictionary",e)}),D=b((e,t,r=0)=>{if(!n(e))throw new _(t,"Array",e);if(e.length<r){throw new v(t,e,`must be longer than ${r}`)}});const L=b((e,t="buffer")=>{if(!I(e))throw new _(t,["Buffer","TypedArray","DataView"],e)});const U=b((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new _(t,"AbortSignal",e)}),F=b((e,t)=>{if("function"!=typeof e)throw new _(t,"Function",e)}),$=b((e,t)=>{if("function"!=typeof e||E(e))throw new _(t,"Function",e)}),V=b((e,t)=>{if(void 0!==e)throw new _(t,"undefined",e)});const W=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function H(e,t){if("undefined"==typeof e||!p(W,e))throw new v(t,e,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if("undefined"==typeof e&&(e=r),"string"==typeof e){if(null===p(O,e))throw new v(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return x(e,t),e},validateArray:D,validateStringArray:function(e,t){D(e,t);for(let r=0;r<e.length;r++)P(e[r],`${t}[${r}]`)},validateBooleanArray:function(e,t){D(e,t);for(let r=0;r<e.length;r++)M(e[r],`${t}[${r}]`)},validateAbortSignalArray:function(e,t){D(e,t);for(let r=0;r<e.length;r++){const n=e[r],i=`${t}[${r}]`;if(null==n)throw new _(i,"AbortSignal",n);U(n,i)}},validateBoolean:M,validateBuffer:L,validateDictionary:j,validateEncoding:function(e,t){const r=k(t),n=e.length;if("hex"===r&&n%2!=0)throw new v("encoding",t,`is invalid for data of length ${n}`)},validateFunction:F,validateInt32:A,validateInteger:C,validateNumber:function(e,t,r=void 0,n){if("number"!=typeof e)throw new _(t,"number",e);if(null!=r&&e<r||null!=n&&e>n||(null!=r||null!=n)&&c(e))throw new S(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:N,validateOneOf:R,validatePlainFunction:$,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===m(e).length||+e!==+e>>>0||e>65535||0===e&&!r)throw new y(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(P(e,t),void 0===T[e]){if(void 0!==T[g(e)])throw new w(e+" (signals must use all capital letters)");throw new w(e)}},validateString:P,validateUint32:x,validateUndefined:V,validateUnion:function(e,t,r){if(!i(r,e))throw new _(t,`('${o(r,"|")}')`,e)},validateAbortSignal:U,validateLinkHeaderValue:function(e){if("string"==typeof e)return H(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n<t;n++){const i=e[n];H(i,"hints"),r+=i,n!==t-1&&(r+=", ")}return r}throw new v("hints",e,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}}},321(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ADDRESS_BOUNDARY=void 0,t.groupPossibilities=a,t.padGroup=c,t.simpleRegularExpression=function(e){const t=[];e.forEach((e,r)=>{0===parseInt(e,16)&&t.push(r)});const r=t.map(t=>e.map((e,r)=>{if(r===t){const t=0===r||r===s.GROUPS-1?":":"";return a([c(e),t])}return c(e)}).join(":"));return r.push(e.map(c).join(":")),a(r)},t.possibleElisions=function(e,t,r){const n=t?"":":",i=r?"":":",o=[];t||r||o.push("::");t&&r&&o.push("");(r&&!t||!r&&t)&&o.push(":");o.push(`${n}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)o.push(`(0{1,4}:){${r}}:(0{1,4}:){${e-r-t-1}}0{1,4}`);return a(o)};const s=o(r(8914));function a(e){return`(${e.join("|")})`}function c(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}t.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]"},345(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(4134),{Buffer:a}=r(181),{inspect:c}=r(7760);e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return a.alloc(0);const t=a.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(e<r.length){const t=r.slice(0,e);return this.head.data=r.slice(e),t}return e===r.length?this.shift():t?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[i](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let t="",r=this.head,i=0;do{const o=r.data;if(!(e>o.length)){e===o.length?(t+=o,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(o,0,e),this.head=r,r.data=n(o,e));break}t+=o,e-=o.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(t,a,r-e),e-=a.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},397(e,t,r){"use strict";const n=r(181),i=r(4478),o=r(2635);let s,a,c,l=!1;t.A=(e,t)=>{if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";!function(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}(t);const u=function(e,t){const r="alis"===e.protocol?"wss":"ws";let n=`${r}://${e.hostname}${e.path}`;return e.port&&80!==e.port&&443!==e.port&&(n=`${r}://${e.hostname}:${e.port}${e.path}`),"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}(t,e);return s=t.my,s.connectSocket({url:u,protocols:r}),a=function(){const e=new i.Transform;return e._write=(e,t,r)=>{s.sendSocketMessage({data:e.buffer,success(){r()},fail(){r(new Error)}})},e._flush=e=>{s.closeSocket({success(){e()}})},e}(),c=new o.BufferedDuplex(t,a,s),l||(l=!0,s.onSocketOpen(()=>{c.socketReady()}),s.onSocketMessage(e=>{if("string"==typeof e.data){const t=n.Buffer.from(e.data,"base64");a.push(t)}else{const t=new FileReader;t.addEventListener("load",()=>{t.result instanceof ArrayBuffer?a.push(n.Buffer.from(t.result)):a.push(n.Buffer.from(t.result,"utf-8"))}),t.readAsArrayBuffer(e.data)}}),s.onSocketClose(()=>{c.end(),c.destroy()}),s.onSocketError(e=>{c.destroy(e)})),c}},441(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createTrackedObject=function(e,t,r){return{globalId:e,className:t.detection.className,label:t.detection.label,sightings:[t],journey:[],firstSeen:t.timestamp,lastSeen:t.timestamp,activeOnCameras:[t.cameraId],entryCamera:r?t.cameraId:void 0,entryCameraName:r?t.cameraName:void 0,hasExited:!1,totalDwellTime:0,state:"active",visualDescriptor:t.embedding,bestThumbnailId:t.detectionId}},t.addSighting=function(e,t){e.sightings.push(t),e.lastSeen=t.timestamp,e.activeOnCameras.includes(t.cameraId)||e.activeOnCameras.push(t.cameraId);t.embedding&&!e.visualDescriptor&&(e.visualDescriptor=t.embedding);t.detectionId&&t.confidence>.8&&(e.bestThumbnailId=t.detectionId);t.detection.label&&!e.label&&(e.label=t.detection.label)},t.addJourneySegment=function(e,t){e.journey.push(t),e.activeOnCameras=e.activeOnCameras.filter(e=>e!==t.fromCameraId),e.activeOnCameras.includes(t.toCameraId)||e.activeOnCameras.push(t.toCameraId)},t.calculateDwellTime=function(e){return 0===e.sightings.length?0:e.lastSeen-e.firstSeen},t.getLastCamera=function(e){return 0===e.sightings.length?void 0:e.sightings[e.sightings.length-1].cameraId},t.getLastSighting=function(e){return 0===e.sightings.length?void 0:e.sightings[e.sightings.length-1]},t.getJourneySummary=function(e){const t=[];e.entryCamera&&t.push(e.entryCameraName||e.entryCamera);for(const r of e.journey)t.includes(r.toCameraName||r.toCameraId)||t.push(r.toCameraName||r.toCameraId);e.exitCamera&&!t.includes(e.exitCameraName||e.exitCamera)&&t.push(e.exitCameraName||e.exitCamera);return t.join(" → ")}},465(e,t){"use strict";function r(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function n(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}Object.defineProperty(t,"__esModule",{value:!0}),t.spanAllZeroes=r,t.spanAll=function(e,t=0){return e.split("").map((e,n)=>`<span class="digit value-${e} position-${n+t}">${r(e)}</span>`).join("")},t.spanLeadingZeroes=function(e){return e.split(":").map(e=>n(e)).join(":")},t.simpleGroup=function(e,t=0){return e.split(":").map((e,r)=>/group-v4/.test(e)?e:`<span class="hover-group group-${r+t}">${n(e)}</span>`)}},495(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(1021),o=n(r(3497)),s=r(4723);t.default=(e,t)=>{e.log("_handleConnack");const{options:r}=e,n=5===r.protocolVersion?t.reasonCode:t.returnCode;if(clearTimeout(e.connackTimer),delete e.topicAliasSend,t.properties){if(t.properties.topicAliasMaximum){if(t.properties.topicAliasMaximum>65535)return void e.emit("error",new Error("topicAliasMaximum from broker is out of range"));t.properties.topicAliasMaximum>0&&(e.topicAliasSend=new o.default(t.properties.topicAliasMaximum))}t.properties.serverKeepAlive&&r.keepalive&&(r.keepalive=t.properties.serverKeepAlive),t.properties.maximumPacketSize&&(r.properties||(r.properties={}),r.properties.maximumPacketSize=t.properties.maximumPacketSize)}if(0===n)e.reconnecting=!1,e._onConnect(t);else if(n>0){const t=new s.ErrorWithReasonCode(`Connection refused: ${i.ReasonCodes[n]}`,n);e.emit("error",t),e.options.reconnectOnConnackError&&e._cleanUp(!0)}}},576(e){e.exports=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}},579(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(65535*Math.random()))}allocate(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e}getLastAllocated(){return 1===this.nextId?65535:this.nextId-1}register(e){return!0}deallocate(e){}clear(){}}},597(e,t,r){"use strict";const{kForOnEventAttribute:n,kListener:i}=r(2614),o=Symbol("kCode"),s=Symbol("kData"),a=Symbol("kError"),c=Symbol("kMessage"),l=Symbol("kReason"),u=Symbol("kTarget"),d=Symbol("kType"),h=Symbol("kWasClean");class p{constructor(e){this[u]=null,this[d]=e}get target(){return this[u]}get type(){return this[d]}}Object.defineProperty(p.prototype,"target",{enumerable:!0}),Object.defineProperty(p.prototype,"type",{enumerable:!0});class f extends p{constructor(e,t={}){super(e),this[o]=void 0===t.code?0:t.code,this[l]=void 0===t.reason?"":t.reason,this[h]=void 0!==t.wasClean&&t.wasClean}get code(){return this[o]}get reason(){return this[l]}get wasClean(){return this[h]}}Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});class g extends p{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[c]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[c]}}Object.defineProperty(g.prototype,"error",{enumerable:!0}),Object.defineProperty(g.prototype,"message",{enumerable:!0});class m extends p{constructor(e,t={}){super(e),this[s]=void 0===t.data?null:t.data}get data(){return this[s]}}Object.defineProperty(m.prototype,"data",{enumerable:!0});const b={addEventListener(e,t,r={}){for(const o of this.listeners(e))if(!r[n]&&o[i]===t&&!o[n])return;let o;if("message"===e)o=function(e,r){const n=new m("message",{data:r?e:e.toString()});n[u]=this,y(t,this,n)};else if("close"===e)o=function(e,r){const n=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[u]=this,y(t,this,n)};else if("error"===e)o=function(e){const r=new g("error",{error:e,message:e.message});r[u]=this,y(t,this,r)};else{if("open"!==e)return;o=function(){const e=new p("open");e[u]=this,y(t,this,e)}}o[n]=!!r[n],o[i]=t,r.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[i]===t&&!r[n]){this.removeListener(e,r);break}}};function y(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}e.exports={CloseEvent:f,ErrorEvent:g,Event:p,EventTarget:b,MessageEvent:m}},720(e,t,r){const n=r(9291);e.exports.NumberAllocator=n},736(e,t,r){e.exports=function(e){function t(e){let r,i,o,s=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),o=i-(r||i);n.diff=o,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";s++;const o=t.formatters[i];if("function"==typeof o){const t=e[s];r=o.call(n,t),e.splice(s,1),s--}return r}),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+("undefined"==typeof r?":":r)+e);return n.log=this.log,n}function i(e,t){let r=0,n=0,i=-1,o=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,o=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,o++,r=o}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},778(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(9278)),o=n(r(5753)),s=n(r(6968)),a=(0,o.default)("mqttjs:tcp");t.default=(e,t)=>{if(t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost",t.socksProxy)return(0,s.default)(t.hostname,t.port,t.socksProxy,{timeout:t.socksTimeout});const{port:r,path:n}=t,o=t.hostname;return a("port %d and host %s",r,o),i.default.createConnection({port:r,host:o,path:n})}},823(e,t,r){"use strict";const n=globalThis.AbortController||r(6584).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(6371),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(277),h=r(4134).Symbol("kWeak"),p=r(4134).Symbol("kResistStopPropagation"),{finished:f}=r(6238),g=r(7830),{addAbortSignalNoValidate:m}=r(4147),{isWritable:b,isNodeStream:y}=r(6115),{deprecate:_}=r(7760),{ArrayPrototypePush:v,Boolean:S,MathFloor:w,Number:k,NumberIsNaN:E,Promise:I,PromiseReject:T,PromiseResolve:O,PromisePrototypeThen:C,Symbol:A}=r(4134),x=A("kEmpty"),P=A("kEof");function R(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=w(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=w(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(7760).AbortSignalAny([null==t?void 0:t.signal].filter(S)),s=this,a=[],l={signal:o};let u,d,h=!1,p=0;function f(){h=!0,g()}function g(){p-=1,m()}function m(){d&&!h&&p<n&&a.length<i&&(d(),d=null)}!async function(){try{for await(let t of s){if(h)return;if(o.aborted)throw new c;try{if(t=e(t,l),t===x)continue;t=O(t)}catch(e){t=T(e)}p+=1,C(t,g,f),a.push(t),u&&(u(),u=null),!h&&(a.length>=i||p>=n)&&await new I(e=>{d=e})}a.push(P)}catch(e){const t=T(e);C(t,g,f),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===P)return;if(o.aborted)throw new c;e!==x&&(yield e),a.shift(),m()}await new I(e=>{u=e})}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function M(e,t=void 0){for await(const r of B.call(this,e,t))return!0;return!1}function B(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return R.call(this,async function(t,r){return await e(t,r)?t:x},t)}class N extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function j(e){if(e=k(e),E(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:_(function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c({cause:e.signal.reason});yield[t++,n]}}.call(this)},"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=j(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:B,flatMap:function(e,t){const r=R.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:R,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=j(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),y(e)&&!b(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&m(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return!await M.call(this,async(...t)=>!await e(...t),t)},forEach:async function(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);for await(const r of R.call(this,async function(t,r){return await e(t,r),x},t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await f(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[p]:!0};r.signal.addEventListener("abort",()=>a.abort(),e)}let g=!1;try{for await(const n of this){var m;if(g=!0,null!=r&&null!==(m=r.signal)&&void 0!==m&&m.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new N}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c(void 0,{cause:e.signal.reason});v(t,n)}return t},some:M,find:async function(e,t){for await(const r of B.call(this,e,t))return r}}},837(e,t){"use strict";function r(e){return e.toString(16).padStart(2,"0")}Object.defineProperty(t,"__esModule",{value:!0}),t.isInSubnet=function(e){if(this.subnetMask<e.subnetMask)return!1;if(this.mask(e.subnetMask)===e.mask())return!0;return!1},t.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}},t.numberToPaddedHex=r,t.stringToPaddedHex=function(e){return r(parseInt(e,10))},t.testBit=function(e,t){const{length:r}=e;if(t>r)return!1;const n=r-t;return"1"===e.substring(n,n+1)}},857(e){"use strict";e.exports=require("os")},914(e,t,r){"use strict";const{Duplex:n}=r(2203),{randomFillSync:i}=r(6982),o=r(2971),{EMPTY_BUFFER:s,kWebSocket:a,NOOP:c}=r(2614),{isBlob:l,isValidStatusCode:u}=r(5880),{mask:d,toBuffer:h}=r(3338),p=Symbol("kByteLength"),f=Buffer.alloc(4),g=8192;let m,b=g;class y{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[a]=void 0}static frame(e,t){let r,n,o=!1,s=2,a=!1;t.mask&&(r=t.maskBuffer||f,t.generateMask?t.generateMask(r):(b===g&&(void 0===m&&(m=Buffer.alloc(g)),i(m,0,g),b=0),r[0]=m[b++],r[1]=m[b++],r[2]=m[b++],r[3]=m[b++]),a=0===(r[0]|r[1]|r[2]|r[3]),s=6),"string"==typeof e?n=t.mask&&!a||void 0===t[p]?(e=Buffer.from(e)).length:t[p]:(n=e.length,o=t.mask&&t.readOnly&&!a);let c=n;n>=65536?(s+=8,c=127):n>125&&(s+=2,c=126);const l=Buffer.allocUnsafe(o?n+s:s);return l[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,126===c?l.writeUInt16BE(n,2):127===c&&(l[2]=l[3]=0,l.writeUIntBE(n,4,6)),t.mask?(l[1]|=128,l[s-4]=r[0],l[s-3]=r[1],l[s-2]=r[2],l[s-1]=r[3],a?[l,e]:o?(d(e,r,l,s,n),[l]):(d(e,r,e,0,n),[l,e])):[l,e]}close(e,t,r,n){let i;if(void 0===e)i=s;else{if("number"!=typeof e||!u(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+r),i.writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0)}const o={[p]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,o,n]):this.sendFrame(y.frame(i,o),n)}ping(e,t,r){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):l(e)?(n=e.size,i=!1):(n=(e=h(e)).length,i=h.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[p]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};l(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):0!==this._state?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(y.frame(e,o),r)}pong(e,t,r){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):l(e)?(n=e.size,i=!1):(n=(e=h(e)).length,i=h.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[p]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};l(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):0!==this._state?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(y.frame(e,o),r)}send(e,t,r){const n=this._extensions[o.extensionName];let i,s,a=t.binary?2:1,c=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):l(e)?(i=e.size,s=!1):(i=(e=h(e)).length,s=h.readOnly),this._firstFragment?(this._firstFragment=!1,c&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(c=i>=n._threshold),this._compress=c):(c=!1,a=0),t.fin&&(this._firstFragment=!0);const u={[p]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:s,rsv1:c};l(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,t,r,n){this._bufferedBytes+=r[p],this._state=2,e.arrayBuffer().then(e=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(_,this,e,n)}this._bufferedBytes-=r[p];const i=h(e);t?this.dispatch(i,t,r,n):(this._state=0,this.sendFrame(y.frame(i,r),n),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,n)})}dispatch(e,t,r,n){if(!t)return void this.sendFrame(y.frame(e,r),n);const i=this._extensions[o.extensionName];this._bufferedBytes+=r[p],this._state=1,i.compress(e,r.fin,(e,t)=>{if(this._socket.destroyed){return void _(this,new Error("The socket was closed while data was being compressed"),n)}this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(y.frame(t,r),n),this.dequeue()})}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function _(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){const n=e._queue[r],i=n[n.length-1];"function"==typeof i&&i(t)}}function v(e,t,r){_(e,t,r),e.onerror(t)}e.exports=y},1021(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasonCodes=void 0;const n=r(4723);t.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};t.default=(e,r)=>{const{messageId:i}=r,o=r.cmd;let s=null;const a=e.outgoing[i]?e.outgoing[i].cb:null;let c=null;if(a){switch(e.log("_handleAck :: packet type",o),o){case"pubcomp":case"puback":{const o=r.reasonCode;o&&o>0&&16!==o?(c=new n.ErrorWithReasonCode(`Publish error: ${t.ReasonCodes[o]}`,o),e._removeOutgoingAndStoreMessage(i,()=>{a(c,r)})):e._removeOutgoingAndStoreMessage(i,a);break}case"pubrec":{s={cmd:"pubrel",qos:2,messageId:i};const o=r.reasonCode;o&&o>0&&16!==o?(c=new n.ErrorWithReasonCode(`Publish error: ${t.ReasonCodes[o]}`,o),e._removeOutgoingAndStoreMessage(i,()=>{a(c,r)})):e._sendPacket(s);break}case"suback":{delete e.outgoing[i],e.messageIdProvider.deallocate(i);const n=r.granted;for(let r=0;r<n.length;r++){const o=n[r];if(128&o){c=new Error(`Subscribe error: ${t.ReasonCodes[o]}`),c.code=o;const r=e.messageIdToTopic[i];r&&r.forEach(t=>{delete e._resubscribeTopics[t]})}}delete e.messageIdToTopic[i],e._invokeStoreProcessingQueue(),a(c,r);break}case"unsuback":delete e.outgoing[i],e.messageIdProvider.deallocate(i),e._invokeStoreProcessingQueue(),a(null,r);break;default:e.emit("error",new Error("unrecognized packet type"))}e.disconnecting&&0===Object.keys(e.outgoing).length&&e.emit("outgoingEmpty")}else e.log("_handleAck :: Server sent an ack in error. Ignoring.")}},1060(e,t,r){"use strict";const n=r(4434),i=r(5692),o=r(8611),s=r(9278),a=r(4756),{randomBytes:c,createHash:l}=r(6982),{Duplex:u,Readable:d}=r(2203),{URL:h}=r(7016),p=r(2971),f=r(6286),g=r(914),{isBlob:m}=r(5880),{BINARY_TYPES:b,EMPTY_BUFFER:y,GUID:_,kForOnEventAttribute:v,kListener:S,kStatusCode:w,kWebSocket:k,NOOP:E}=r(2614),{EventTarget:{addEventListener:I,removeEventListener:T}}=r(597),{format:O,parse:C}=r(5926),{toBuffer:A}=r(3338),x=Symbol("kAborted"),P=[8,13],R=["CONNECTING","OPEN","CLOSING","CLOSED"],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class B extends n{constructor(e,t,r){super(),this._binaryType=b[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=B.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),N(this,e,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){b.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new f({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new g(e,this._extensions,r.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[k]=this,i[k]=this,e[k]=this,n.on("conclude",$),n.on("drain",V),n.on("error",W),n.on("message",z),n.on("ping",q),n.on("pong",G),i.onerror=Q,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Z),e.on("data",J),e.on("end",X),e.on("error",ee),this._readyState=B.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=B.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=B.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==B.CLOSED){if(this.readyState===B.CONNECTING){const e="WebSocket was closed before the connection was established";return void U(this,this._req,e)}this.readyState!==B.CLOSING?(this._readyState=B.CLOSING,this._sender.close(e,t,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Y(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==B.CONNECTING&&this.readyState!==B.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===B.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===B.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||y,t,r)):F(this,e,r)}pong(e,t,r){if(this.readyState===B.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===B.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||y,t,r)):F(this,e,r)}resume(){this.readyState!==B.CONNECTING&&this.readyState!==B.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===B.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==B.OPEN)return void F(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[p.extensionName]||(n.compress=!1),this._sender.send(e||y,n,r)}terminate(){if(this.readyState!==B.CLOSED){if(this.readyState===B.CONNECTING){const e="WebSocket was closed before the connection was established";return void U(this,this._req,e)}this._socket&&(this._readyState=B.CLOSING,this._socket.destroy())}}}function N(e,t,r,n){const s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:P[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=s.autoPong,!P.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${P.join(", ")})`);let a;if(t instanceof h)a=t;else try{a=new h(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===a.protocol?a.protocol="ws:":"https:"===a.protocol&&(a.protocol="wss:"),e._url=a.href;const u="wss:"===a.protocol,d="ws+unix:"===a.protocol;let f;if("ws:"===a.protocol||u||d?d&&!a.pathname?f="The URL's pathname is empty":a.hash&&(f="The URL contains a fragment identifier"):f='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',f){const t=new SyntaxError(f);if(0===e._redirects)throw t;return void j(e,t)}const g=u?443:80,m=c(16).toString("base64"),b=u?i.request:o.request,y=new Set;let v,S;if(s.createConnection=s.createConnection||(u?L:D),s.defaultPort=s.defaultPort||g,s.port=a.port||g,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new p(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=O({[p.extensionName]:v.offer()})),r.length){for(const e of r){if("string"!=typeof e||!M.test(e)||y.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),d){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?s.socketPath:a.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=d?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&a.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=e._req=b(s),e._redirects&&e.emit("redirect",e.url,S)}else S=e._req=b(s);s.timeout&&S.on("timeout",()=>{U(e,S,"Opening handshake has timed out")}),S.on("error",t=>{null===S||S[x]||(S=e._req=null,j(e,t))}),S.on("response",i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void U(e,S,"Maximum redirects exceeded");let i;S.abort();try{i=new h(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void j(e,r)}N(e,i,r,n)}else e.emit("unexpected-response",S,i)||U(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on("upgrade",(t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==B.CONNECTING)return;S=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void U(e,r,"Invalid Upgrade header");const o=l("sha1").update(m+_).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void U(e,r,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?y.size?y.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":y.size&&(c="Server sent no subprotocol"),c)return void U(e,r,c);a&&(e._protocol=a);const u=t.headers["sec-websocket-extensions"];if(void 0!==u){if(!v){return void U(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=C(u)}catch(t){return void U(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==p.extensionName){return void U(e,r,"Server indicated an extension that was not requested")}try{v.accept(t[p.extensionName])}catch(t){return void U(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[p.extensionName]=v}e.setSocket(r,n,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,e):S.end()}function j(e,t){e._readyState=B.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function D(e){return e.path=e.socketPath,s.connect(e)}function L(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=s.isIP(e.host)?"":e.host),a.connect(e)}function U(e,t,r){e._readyState=B.CLOSING;const n=new Error(r);Error.captureStackTrace(n,U),t.setHeader?(t[x]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(j,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function F(e,t,r){if(t){const r=m(t)?t.size:A(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${R[e.readyState]})`);process.nextTick(r,t)}}function $(e,t){const r=this[k];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[k]&&(r._socket.removeListener("data",J),process.nextTick(K,r._socket),1005===e?r.close():r.close(e,t))}function V(){const e=this[k];e.isPaused||e._socket.resume()}function W(e){const t=this[k];void 0!==t._socket[k]&&(t._socket.removeListener("data",J),process.nextTick(K,t._socket),t.close(e[w])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function H(){this[k].emitClose()}function z(e,t){this[k].emit("message",e,t)}function q(e){const t=this[k];t._autoPong&&t.pong(e,!this._isServer,E),t.emit("ping",e)}function G(e){this[k].emit("pong",e)}function K(e){e.resume()}function Q(e){const t=this[k];t.readyState!==B.CLOSED&&(t.readyState===B.OPEN&&(t._readyState=B.CLOSING,Y(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Y(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function Z(){const e=this[k];let t;this.removeListener("close",Z),this.removeListener("data",J),this.removeListener("end",X),e._readyState=B.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[k]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",H),e._receiver.on("finish",H))}function J(e){this[k]._receiver.write(e)||this.pause()}function X(){const e=this[k];e._readyState=B.CLOSING,e._receiver.end(),this.end()}function ee(){const e=this[k];this.removeListener("error",ee),this.on("error",E),e&&(e._readyState=B.CLOSING,this.destroy())}Object.defineProperty(B,"CONNECTING",{enumerable:!0,value:R.indexOf("CONNECTING")}),Object.defineProperty(B.prototype,"CONNECTING",{enumerable:!0,value:R.indexOf("CONNECTING")}),Object.defineProperty(B,"OPEN",{enumerable:!0,value:R.indexOf("OPEN")}),Object.defineProperty(B.prototype,"OPEN",{enumerable:!0,value:R.indexOf("OPEN")}),Object.defineProperty(B,"CLOSING",{enumerable:!0,value:R.indexOf("CLOSING")}),Object.defineProperty(B.prototype,"CLOSING",{enumerable:!0,value:R.indexOf("CLOSING")}),Object.defineProperty(B,"CLOSED",{enumerable:!0,value:R.indexOf("CLOSED")}),Object.defineProperty(B.prototype,"CLOSED",{enumerable:!0,value:R.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(B.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(B.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[v])return t[S];return null},set(t){for(const t of this.listeners(e))if(t[v]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[v]:!0})}})}),B.prototype.addEventListener=I,B.prototype.removeEventListener=T,e.exports=B},1278(e,t,r){t.parser=r(3079).parser,t.generate=r(2535),t.writeToStream=r(3132)},1554(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createEmptyTopology=function(){return{version:"1.0",cameras:[],connections:[],globalZones:[]}},t.findCamera=function(e,t){return e.cameras.find(e=>e.deviceId===t)},t.findConnectionsFrom=function(e,t){return e.connections.filter(e=>e.fromCameraId===t||e.bidirectional&&e.toCameraId===t)},t.findConnection=function(e,t,r){return e.connections.find(e=>e.fromCameraId===t&&e.toCameraId===r||e.bidirectional&&e.fromCameraId===r&&e.toCameraId===t)},t.getEntryPoints=function(e){return e.cameras.filter(e=>e.isEntryPoint)},t.getExitPoints=function(e){return e.cameras.filter(e=>e.isExitPoint)}},1676(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||i(t,e,r)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ReasonCodes=t.KeepaliveManager=t.UniqueMessageIdProvider=t.DefaultMessageIdProvider=t.Store=t.MqttClient=t.connectAsync=t.connect=t.Client=void 0;const l=c(r(9777));t.MqttClient=l.default;const u=c(r(579));t.DefaultMessageIdProvider=u.default;const d=c(r(2099));t.UniqueMessageIdProvider=d.default;const h=c(r(7969));t.Store=h.default;const p=s(r(2793));t.connect=p.default,Object.defineProperty(t,"connectAsync",{enumerable:!0,get:function(){return p.connectAsync}});const f=c(r(3175));t.KeepaliveManager=f.default,t.Client=l.default,a(r(9777),t),a(r(4723),t);var g=r(1021);Object.defineProperty(t,"ReasonCodes",{enumerable:!0,get:function(){return g.ReasonCodes}})},1722(e,t,r){"use strict";const n=r(4434),i=r(8611),{Duplex:o}=r(2203),{createHash:s}=r(6982),a=r(5926),c=r(2971),l=r(8237),u=r(1060),{GUID:d,kWebSocket:h}=r(2614),p=/^[+/0-9A-Za-z]{22}==$/;function f(e){e._state=2,e.emit("close")}function g(){this.destroy()}function m(e,t,r,n){r=r||i.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r\n`+Object.keys(n).map(e=>`${e}: ${n[e]}`).join("\r\n")+"\r\n\r\n"+r)}function b(e,t,r,n,i,o){if(e.listenerCount("wsClientError")){const n=new Error(i);Error.captureStackTrace(n,b),e.emit("wsClientError",n,r,t)}else m(r,n,i,o)}e.exports=class extends n{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{const r=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",()=>{e(new Error("The server is not running"))}),void process.nextTick(f,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(f,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{f(this)})}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",g);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void b(this,e,t,405,"Invalid HTTP method")}if(void 0===o||"websocket"!==o.toLowerCase()){return void b(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!p.test(i)){return void b(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(13!==s&&8!==s){return void b(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"})}if(!this.shouldHandle(e))return void m(t,400);const u=e.headers["sec-websocket-protocol"];let d=new Set;if(void 0!==u)try{d=l.parse(u)}catch(r){return void b(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const h=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&void 0!==h){const r=new c(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=a.parse(h);e[c.extensionName]&&(r.accept(e[c.extensionName]),f[c.extensionName]=r)}catch(r){return void b(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===s?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,(o,s,a,c)=>{if(!o)return m(t,s||401,a,c);this.completeUpgrade(f,i,d,e,t,r,n)});if(!this.options.verifyClient(o))return m(t,401)}this.completeUpgrade(f,i,d,e,t,r,n)}completeUpgrade(e,t,r,n,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[h])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return m(i,503);const u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(t+d).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[c.extensionName]){const t=e[c.extensionName].params,r=a.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${r}`),p._extensions=e}this.emit("headers",u,n),i.write(u.concat("\r\n").join("\r\n")),i.removeListener("error",g),p.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(f,this)})),l(p,n)}}},1725(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(181),i={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};function o(e){return"number"==typeof e&&isFinite(e)&&function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e}(e)}function s(e,t){if("number"!=typeof e)throw new Error(t?i.INVALID_OFFSET_NON_NUMBER:i.INVALID_LENGTH_NON_NUMBER);if(!o(e)||e<0)throw new Error(t?i.INVALID_OFFSET:i.INVALID_LENGTH)}t.ERRORS=i,t.checkEncoding=function(e){if(!n.Buffer.isEncoding(e))throw new Error(i.INVALID_ENCODING)},t.isFiniteInteger=o,t.checkLengthValue=function(e){s(e,!1)},t.checkOffsetValue=function(e){s(e,!0)},t.checkTargetOffset=function(e,t){if(e<0||e>t.length)throw new Error(i.INVALID_TARGET_OFFSET)},t.bigIntAndBufferInt64Check=function(e){if("undefined"==typeof BigInt)throw new Error("Platform does not support JS BigInt type.");if("undefined"==typeof n.Buffer.prototype[e])throw new Error(`Platform does not support Buffer.prototype.${e}.`)}},2017(e,t,r){try{var n=r(9023);if("function"!=typeof n.inherits)throw"";e.exports=n.inherits}catch(t){e.exports=r(6698)}},2018(e){"use strict";e.exports=require("tty")},2099(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(720);t.default=class{numberAllocator;lastId;constructor(){this.numberAllocator=new n.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(e){return this.numberAllocator.use(e)}deallocate(e){this.numberAllocator.free(e)}clear(){this.numberAllocator.clear()}}},2203(e){"use strict";e.exports=require("stream")},2250(e){"use strict";e.exports=require("dns")},2437(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AddressError=void 0;class r extends Error{constructor(e,t){super(e),this.name="AddressError",this.parseMessage=t}}t.AddressError=r},2535(e,t,r){const n=r(3132),{EventEmitter:i}=r(4434),{Buffer:o}=r(181);class s extends i{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let n,i=0;for(n=0;n<r.length&&void 0!==r[n];n++)"string"!=typeof r[n]?t[n]=r[n].length:t[n]=o.byteLength(r[n]),e+=t[n];const s=o.allocUnsafe(e);for(n=0;n<r.length&&void 0!==r[n];n++)"string"!=typeof r[n]?(r[n].copy(s,i),i+=t[n]):(s.write(r[n],i),i+=t[n]);return s}destroy(e){e&&this.emit("error",e)}}e.exports=function(e,t){const r=new s;return n(e,r,t),r.concat()}},2613(e){"use strict";e.exports=require("assert")},2614(e){"use strict";const t=["nodebuffer","arraybuffer","fragments"],r="undefined"!=typeof Blob;r&&t.push("blob"),e.exports={BINARY_TYPES:t,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:r,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},2635(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BufferedDuplex=void 0,t.writev=o;const n=r(4478),i=r(181);function o(e,t){const r=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?r[t]=i.Buffer.from(e[t].chunk,"utf8"):r[t]=e[t].chunk;this._write(i.Buffer.concat(r),"binary",t)}class s extends n.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(e,t,r){super({objectMode:!0}),this.proxy=t,this.socket=r,this.writeQueue=[],e.objectMode||(this._writev=o.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",e=>{!this.destroyed&&this.readable&&this.push(e)})}_read(e){this.proxy.read(e)}_write(e,t,r){this.isSocketOpen?this.writeToProxy(e,t,r):this.writeQueue.push({chunk:e,encoding:t,cb:r})}_final(e){this.writeQueue=[],this.proxy.end(e)}_destroy(e,t){this.writeQueue=[],this.proxy.destroy(),t(e)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(e,t,r){!1===this.proxy.write(e,t)?this.proxy.once("drain",r):r()}processWriteQueue(){for(;this.writeQueue.length>0;){const{chunk:e,encoding:t,cb:r}=this.writeQueue.shift();this.writeToProxy(e,t,r)}}}t.BufferedDuplex=s},2639(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=class{aliasToTopic;max;length;constructor(e){this.aliasToTopic={},this.max=e}put(e,t){return!(0===t||t>this.max)&&(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(e){return this.aliasToTopic[e]}clear(){this.aliasToTopic={}}}},2793(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.connectAsync=function(e,t,r=!0){return new Promise((n,i)=>{const o=u(e,t),s={connect:e=>{a(),n(o)},end:()=>{a(),n(o)},error:e=>{a(),o.end(),i(e)}};function a(){Object.keys(s).forEach(e=>{o.off(e,s[e])})}!1===r&&(s.close=()=>{s.error(new Error("Couldn't connect to server"))}),Object.keys(s).forEach(e=>{o.on(e,s[e])})})};const i=n(r(5753)),o=n(r(7016)),s=n(r(9777)),a=n(r(6887));"function"!=typeof process?.nextTick&&(process.nextTick=setImmediate);const c=(0,i.default)("mqttjs");let l=null;function u(e,t){if(c("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=""),t=t||{},e&&"string"==typeof e){const r=o.default.parse(e,!0),n={};if(null!=r.port&&(n.port=Number(r.port)),n.host=r.hostname,n.query=r.query,n.auth=r.auth,n.protocol=r.protocol,n.path=r.path,!(t={...n,...t}).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(t.unixSocket=t.unixSocket||t.protocol?.includes("+unix"),t.unixSocket?t.protocol=t.protocol.replace("+unix",""):t.protocol?.startsWith("ws")||t.protocol?.startsWith("wx")||delete t.path,function(e){let t;if(e.auth)if(t=e.auth.match(/^(.+):(.+)$/),t){const[,r,n]=t;e.username=r,e.password=n}else e.username=e.auth}(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),a.default||t.unixSocket?t.socksProxy=void 0:void 0===t.socksProxy&&"undefined"!=typeof process&&(t.socksProxy=process.env.MQTTJS_SOCKS_PROXY),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${t.protocol}"!`)}}if(l||(l={},a.default||t.forceNativeWebSocket?(l.ws=r(8203).browserStreamBuilder,l.wss=r(8203).browserStreamBuilder,l.wx=r(5670).A,l.wxs=r(5670).A,l.ali=r(397).A,l.alis=r(397).A):(l.ws=r(8203).streamBuilder,l.wss=r(8203).streamBuilder,l.mqtt=r(778).default,l.tcp=r(778).default,l.ssl=r(3936).default,l.tls=l.ssl,l.mqtts=r(3936).default)),!l[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((t,r)=>(!e||r%2!=0)&&"function"==typeof l[t])[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");t.protocol&&(t.defaultProtocol=t.protocol);const n=new s.default(function(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),c("calling streambuilder for",t.protocol),l[t.protocol](e,t)},t);return n.on("error",()=>{}),n}t.default=u},2839(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Address4=void 0;const s=o(r(837)),a=o(r(9576)),c=r(2437);class l{constructor(e){this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=s.isCorrect(a.BITS),this.isInSubnet=s.isInSubnet,this.address=e;const t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new c.AddressError("Invalid subnet mask.");e=e.replace(a.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new l(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(a.RE_ADDRESS))throw new c.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let n;for(n=0;n<8;n+=2){const e=t.slice(n,n+2);r.push(parseInt(e,16))}return new l(r.join("."))}static fromInteger(e){return l.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new l(t)}toHex(){return this.parsedAddress.map(e=>s.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){const e=[];let t;for(t=0;t<a.GROUPS;t+=2)e.push(`${s.stringToPaddedHex(this.parsedAddress[t])}${s.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>s.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(a.BITS-this.subnetMask)}`)}startAddress(){return l.fromBigInt(this._startAddress())}startAddressExclusive(){const e=BigInt("1");return l.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(a.BITS-this.subnetMask)}`)}endAddress(){return l.fromBigInt(this._endAddress())}endAddressExclusive(){const e=BigInt("1");return l.fromBigInt(this._endAddress()-e)}static fromBigInt(e){return l.fromHex(e.toString(16))}static fromByteArray(e){if(4!==e.length)throw new c.AddressError("IPv4 addresses require exactly 4 bytes");for(let t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)throw new c.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(4!==e.length)throw new c.AddressError("IPv4 addresses require exactly 4 bytes");const t=e.join(".");return new l(t)}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new l("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(a.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}}t.Address4=l},2846(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TrackingZone=void 0;const n=r(7562),i=r(6117);class o extends n.ScryptedDeviceBase{trackingState;plugin;config={type:"entry",cameras:[]};storageSettings=new i.StorageSettings(this,{zoneType:{title:"Zone Type",type:"string",choices:["entry","exit","dwell","restricted"],defaultValue:"entry",description:"Type of zone for alerting purposes"},cameras:{title:"Cameras",type:"device",multiple:!0,deviceFilter:`interfaces.includes('${n.ScryptedInterface.ObjectDetector}')`,description:"Cameras that make up this zone"},dwellThreshold:{title:"Dwell Time Threshold (seconds)",type:"number",defaultValue:60,description:"For dwell zones: alert if object stays longer than this"},trackClasses:{title:"Track Object Types",type:"string",multiple:!0,choices:["person","car","vehicle","animal","package"],description:"Object types to monitor in this zone (empty = all)"}});constructor(e,t,r){super(t),this.plugin=e,this.trackingState=r,this.loadConfig(),r.onStateChange(()=>this.evaluateZone()),this.evaluateZone()}loadConfig(){try{const e=this.storage.getItem("zoneConfig");e&&(this.config=JSON.parse(e))}catch(e){this.console.error("Failed to load zone config:",e)}}saveConfig(){try{this.storage.setItem("zoneConfig",JSON.stringify(this.config))}catch(e){this.console.error("Failed to save zone config:",e)}}configure(e){this.config={...this.config,...e},this.saveConfig(),this.evaluateZone()}evaluateZone(){const e=this.getCameraIds();if(0===e.length)return this.occupied=!1,void(this.motionDetected=!1);const t=this.storageSettings.values.trackClasses||[];let r=!1,n=!1;const i=Date.now();for(const o of e){const e=this.trackingState.getObjectsOnCamera(o);for(const s of e){if(t.length>0&&!t.includes(s.className))continue;r=!0;s.sightings.filter(e=>e.cameraId===o&&i-e.timestamp<5e3).some(e=>e.detection.movement?.moving)&&(n=!0)}}this.occupied=r,this.motionDetected=n}getCameraIds(){const e=this.storageSettings.values.cameras;return Array.isArray(e)?e:e?[e]:this.config.cameras||[]}getObjectsInZone(){const e=this.getCameraIds(),t=this.storageSettings.values.trackClasses||[],r=[],n=new Set;for(const i of e)for(const e of this.trackingState.getObjectsOnCamera(i))n.has(e.globalId)||(n.add(e.globalId),(0===t.length||t.includes(e.className))&&r.push(e));return r}async getSettings(){const e=await this.storageSettings.getSettings(),t=this.getObjectsInZone();return e.push({key:"currentStatus",title:"Current Status",type:"string",readonly:!0,value:this.occupied?`Occupied: ${t.length} object${1!==t.length?"s":""}`:"Empty",group:"Status"}),t.length>0&&e.push({key:"objectsList",title:"Objects in Zone",type:"string",readonly:!0,value:t.map(e=>`${e.className}${e.label?` (${e.label})`:""}`).join(", "),group:"Status"}),e}async putSetting(e,t){await this.storageSettings.putSetting(e,t),this.config.type=this.storageSettings.values.zoneType||"entry",this.config.cameras=this.getCameraIds(),this.config.dwellThreshold=1e3*(this.storageSettings.values.dwellThreshold||60),this.saveConfig(),this.evaluateZone()}}t.TrackingZone=o},2860(e){"use strict";e.exports={version:"5.14.1"}},2861(e,t,r){var n=r(181),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},2971(e,t,r){"use strict";const n=r(3106),i=r(3338),o=r(4759),{kStatusCode:s}=r(2614),a=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol("permessage-deflate"),u=Symbol("total-length"),d=Symbol("callback"),h=Symbol("buffers"),p=Symbol("error");let f;function g(e){this[h].push(e),this[u]+=e.length}function m(e){this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload?this[h].push(e):(this[p]=new RangeError("Max payload size exceeded"),this[p].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[p][s]=1009,this.removeListener("data",m),this.reset())}function b(e){this[l]._inflate=null,this[p]?this[d](this[p]):(e[s]=1007,this[d](e))}e.exports=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!f){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;f=new o(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find(e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r})}),e}decompress(e,t,r){f.add(n=>{this._decompress(e,t,(e,t)=>{n(),r(e,t)})})}compress(e,t,r){f.add(n=>{this._compress(e,t,(e,t)=>{n(),r(e,t)})})}_decompress(e,t,r){const o=this._isServer?"client":"server";if(!this._inflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[h]=[],this._inflate.on("error",b),this._inflate.on("data",m)}this._inflate[d]=r,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{const e=this._inflate[p];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=i.concat(this._inflate[h],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,n)})}_compress(e,t,r){const o=this._isServer?"server":"client";if(!this._deflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[h]=[],this._deflate.on("data",g)}this._deflate[d]=r,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[h],this._deflate[u]);t&&(e=new a(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,e)})}}},3079(e,t,r){const n=r(4829),{EventEmitter:i}=r(4434),o=r(576),s=r(5399),a=r(5753)("mqtt-packet:parser");class c extends i{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){a("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=n(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),a("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,a("parse: state complete. _stateCounter is now: %d",this._stateCounter),a("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return a("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0),t=e>>s.CMD_SHIFT;this.packet.cmd=s.types[t];const r=15&e,n=s.requiredHeaderFlags[t];return null!=n&&r!==n?this._emitError(new Error(s.requiredHeaderFlagsErrors[t])):(this.packet.retain=0!==(e&s.RETAIN_MASK),this.packet.qos=e>>s.QOS_SHIFT&s.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=0!==(e&s.DUP_MASK),a("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),a("_parseLength %d",e.value),!!e}_parsePayload(){a("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return a("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,r,n;a("_parseConnect");const i={},o=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(o.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(o.protocolVersion=this._list.readUInt8(this._pos),o.protocolVersion>=128&&(o.bridgeMode=!0,o.protocolVersion=o.protocolVersion-128),3!==o.protocolVersion&&4!==o.protocolVersion&&5!==o.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(1&this._list.readUInt8(this._pos))return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));i.username=this._list.readUInt8(this._pos)&s.USERNAME_MASK,i.password=this._list.readUInt8(this._pos)&s.PASSWORD_MASK,i.will=this._list.readUInt8(this._pos)&s.WILL_FLAG_MASK;const l=!!(this._list.readUInt8(this._pos)&s.WILL_RETAIN_MASK),u=(this._list.readUInt8(this._pos)&s.WILL_QOS_MASK)>>s.WILL_QOS_SHIFT;if(i.will)o.will={},o.will.retain=l,o.will.qos=u;else{if(l)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(u)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(o.clean=0!==(this._list.readUInt8(this._pos)&s.CLEAN_SESSION_MASK),this._pos++,o.keepalive=this._parseNum(),-1===o.keepalive)return this._emitError(new Error("Packet too short"));if(5===o.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(o.properties=e)}const d=this._parseString();if(null===d)return this._emitError(new Error("Packet too short"));if(o.clientId=d,a("_parseConnect: packet.clientId: %s",o.clientId),i.will){if(5===o.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(o.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(o.will.topic=e,a("_parseConnect: packet.will.topic: %s",o.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));o.will.payload=t,a("_parseConnect: packet.will.paylaod: %s",o.will.payload)}if(i.username){if(n=this._parseString(),null===n)return this._emitError(new Error("Cannot parse username"));o.username=n,a("_parseConnect: packet.username: %s",o.username)}if(i.password){if(r=this._parseBuffer(),null===r)return this._emitError(new Error("Cannot parse password"));o.password=r}return this.settings=o,a("_parseConnect: complete"),o}_parseConnack(){a("_parseConnack");const e=this.packet;if(this._list.length<1)return null;const t=this._list.readUInt8(this._pos++);if(t>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(e.sessionPresent=!!(t&s.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}a("_parseConnack: complete")}_parsePublish(){a("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),a("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){a("_parseSubscribe");const e=this.packet;let t,r,n,i,o,c,l;if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}if(e.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(r=this._parseByte(),5===this.settings.protocolVersion){if(192&r)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(252&r)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(n=r&s.SUBSCRIBE_OPTIONS_QOS_MASK,n>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(c=0!==(r>>s.SUBSCRIBE_OPTIONS_NL_SHIFT&s.SUBSCRIBE_OPTIONS_NL_MASK),o=0!==(r>>s.SUBSCRIBE_OPTIONS_RAP_SHIFT&s.SUBSCRIBE_OPTIONS_RAP_MASK),i=r>>s.SUBSCRIBE_OPTIONS_RH_SHIFT&s.SUBSCRIBE_OPTIONS_RH_MASK,i>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));l={topic:t,qos:n},5===this.settings.protocolVersion?(l.nl=c,l.rap=o,l.rh=i):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),a("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){a("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}if(e.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){const e=this._list.readUInt8(this._pos++);if(5===this.settings.protocolVersion){if(!s.MQTT5_SUBACK_CODES[e])return this._emitError(new Error("Invalid suback code"))}else if(e>2&&128!==e)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(e)}}}_parseUnsubscribe(){a("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}if(e.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));a("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){a("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((3===this.settings.protocolVersion||4===this.settings.protocolVersion)&&2!==e.length)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(e.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;){const e=this._list.readUInt8(this._pos++);if(!s.MQTT5_UNSUBACK_CODES[e])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(e)}}}_parseConfirmation(){a("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion){if(e.length>2){switch(e.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!s.MQTT5_PUBACK_PUBREC_CODES[e.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!s.MQTT5_PUBREL_PUBCOMP_CODES[e.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"))}a("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)}else e.reasonCode=0;if(e.length>3){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}}return!0}_parseDisconnect(){const e=this.packet;if(a("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?(e.reasonCode=this._parseByte(),s.MQTT5_DISCONNECT_CODES[e.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return a("_parseDisconnect result: true"),!0}_parseAuth(){a("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(e.reasonCode=this._parseByte(),!s.MQTT5_AUTH_CODES[e.reasonCode])return this._emitError(new Error("Invalid auth reason code"));const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),a("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(a("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),r=t+this._pos;if(-1===t||r>this._list.length||r>this.packet.length)return null;const n=this._list.toString("utf8",this._pos,r);return this._pos+=t,a("_parseString: result: %s",n),n}_parseStringPair(){return a("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const r=this._list.slice(this._pos,t);return this._pos+=e,a("_parseBuffer: result: %o",r),r}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,a("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,a("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){a("_parseVarByteNum");let t,r=0,n=1,i=0,o=!1;const c=this._pos?this._pos:0;for(;r<4&&c+r<this._list.length;){if(t=this._list.readUInt8(c+r++),i+=n*(t&s.VARBYTEINT_MASK),n*=128,0===(t&s.VARBYTEINT_FIN_MASK)){o=!0;break}if(this._list.length<=r)break}return!o&&4===r&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),c&&(this._pos+=r),o=!!o&&(e?{bytes:r,value:i}:i),a("_parseVarByteNum: result: %o",o),o}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),a("_parseByte: result: %o",e),e}_parseByType(e){switch(a("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){a("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,r={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=s.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"===t){r[t]||(r[t]=Object.create(null));const e=this._parseByType(s.propertiesTypes[t]);if(r[t][e.name])if(Array.isArray(r[t][e.name]))r[t][e.name].push(e.value);else{const n=r[t][e.name];r[t][e.name]=[n],r[t][e.name].push(e.value)}else r[t][e.name]=e.value;continue}r[t]?(Array.isArray(r[t])||(r[t]=[r[t]]),r[t].push(this._parseByType(s.propertiesTypes[t]))):r[t]=this._parseByType(s.propertiesTypes[t])}return r}_newPacket(){return a("_newPacket"),this.packet&&(this._list.consume(this.packet.length),a("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),a("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(e){a("_emitError",e),this.error=e,this.emit("error",e)}}e.exports=c},3095(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(4134),{isIterable:o,isNodeStream:s,isWebStream:a}=r(6115),{pipelineImpl:c}=r(7758),{finished:l}=r(6238);r(5506),e.exports={finished:l,pipeline:function(...e){return new i((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,(e,n)=>{e?r(e):t(n)},{signal:i,end:l})})}}},3106(e){"use strict";e.exports=require("zlib")},3132(e,t,r){const n=r(5399),{Buffer:i}=r(181),o=i.allocUnsafe(0),s=i.from([0]),a=r(6172),c=r(3225).nextTick,l=r(5753)("mqtt-packet:writeToStream"),u=a.cache,d=a.generateNumber,h=a.generateCache,p=a.genBufVariableByteInt,f=a.generate4ByteBuffer;let g=k,m=!0;function b(e,t,r){switch(l("generate called"),t.cork&&(t.cork(),c(y,t)),m&&(m=!1,h()),l("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return function(e,t){const r=e||{},o=r.protocolId||"MQTT";let s=r.protocolVersion||4;const a=r.will;let c=r.clean;const l=r.keepalive||0,u=r.clientId||"",d=r.username,h=r.password,p=r.properties;void 0===c&&(c=!0);let f,m,b=0;if(!o||"string"!=typeof o&&!i.isBuffer(o))return t.destroy(new Error("Invalid protocolId")),!1;b+=o.length+2;if(3!==s&&4!==s&&5!==s)return t.destroy(new Error("Invalid protocol version")),!1;b+=1;if(("string"==typeof u||i.isBuffer(u))&&(u||s>=4)&&(u||c))b+=i.byteLength(u)+2;else{if(s<4)return t.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(1*c==0)return t.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof l||l<0||l>65535||l%1!=0)return t.destroy(new Error("Invalid keepalive")),!1;b+=2;if(b+=1,5===s){if(f=T(t,p),!f)return!1;b+=f.length}if(a){if("object"!=typeof a)return t.destroy(new Error("Invalid will")),!1;if(!a.topic||"string"!=typeof a.topic)return t.destroy(new Error("Invalid will topic")),!1;if(b+=i.byteLength(a.topic)+2,b+=2,a.payload){if(!(a.payload.length>=0))return t.destroy(new Error("Invalid will payload")),!1;"string"==typeof a.payload?b+=i.byteLength(a.payload):b+=a.payload.length}if(m={},5===s){if(m=T(t,a.properties),!m)return!1;b+=m.length}}let y=!1;if(null!=d){if(!P(d))return t.destroy(new Error("Invalid username")),!1;y=!0,b+=i.byteLength(d)+2}if(null!=h){if(!y)return t.destroy(new Error("Username is required to use password")),!1;if(!P(h))return t.destroy(new Error("Invalid password")),!1;b+=x(h)+2}t.write(n.CONNECT_HEADER),v(t,b),I(t,o),r.bridgeMode&&(s+=128);t.write(131===s?n.VERSION131:132===s?n.VERSION132:4===s?n.VERSION4:5===s?n.VERSION5:n.VERSION3);let _=0;_|=null!=d?n.USERNAME_MASK:0,_|=null!=h?n.PASSWORD_MASK:0,_|=a&&a.retain?n.WILL_RETAIN_MASK:0,_|=a&&a.qos?a.qos<<n.WILL_QOS_SHIFT:0,_|=a?n.WILL_FLAG_MASK:0,_|=c?n.CLEAN_SESSION_MASK:0,t.write(i.from([_])),g(t,l),5===s&&f.write();I(t,u),a&&(5===s&&m.write(),S(t,a.topic),I(t,a.payload));null!=d&&I(t,d);null!=h&&I(t,h);return!0}(e,t);case"connack":return function(e,t,r){const o=r?r.protocolVersion:4,a=e||{},c=5===o?a.reasonCode:a.returnCode,l=a.properties;let u=2;if("number"!=typeof c)return t.destroy(new Error("Invalid return code")),!1;let d=null;if(5===o){if(d=T(t,l),!d)return!1;u+=d.length}t.write(n.CONNACK_HEADER),v(t,u),t.write(a.sessionPresent?n.SESSIONPRESENT_HEADER:s),t.write(i.from([c])),null!=d&&d.write();return!0}(e,t,r);case"publish":return function(e,t,r){l("publish: packet: %o",e);const s=r?r.protocolVersion:4,a=e||{},c=a.qos||0,u=a.retain?n.RETAIN_MASK:0,d=a.topic,h=a.payload||o,p=a.messageId,f=a.properties;let m=0;if("string"==typeof d)m+=i.byteLength(d)+2;else{if(!i.isBuffer(d))return t.destroy(new Error("Invalid topic")),!1;m+=d.length+2}i.isBuffer(h)?m+=h.length:m+=i.byteLength(h);if(c&&"number"!=typeof p)return t.destroy(new Error("Invalid messageId")),!1;c&&(m+=2);let b=null;if(5===s){if(b=T(t,f),!b)return!1;m+=b.length}t.write(n.PUBLISH_HEADER[c][a.dup?1:0][u?1:0]),v(t,m),g(t,x(d)),t.write(d),c>0&&g(t,p);null!=b&&b.write();return l("publish: payload: %o",h),t.write(h)}(e,t,r);case"puback":case"pubrec":case"pubrel":case"pubcomp":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.cmd||"puback",c=s.messageId,l=s.dup&&"pubrel"===a?n.DUP_MASK:0;let u=0;const d=s.reasonCode,h=s.properties;let p=5===o?3:2;"pubrel"===a&&(u=1);if("number"!=typeof c)return t.destroy(new Error("Invalid messageId")),!1;let f=null;if(5===o&&"object"==typeof h){if(f=O(t,h,r,p),!f)return!1;p+=f.length}t.write(n.ACKS[a][u][l][0]),3===p&&(p+=0!==d?1:-1);v(t,p),g(t,c),5===o&&2!==p&&t.write(i.from([d]));null!==f?f.write():4===p&&t.write(i.from([0]));return!0}(e,t,r);case"subscribe":return function(e,t,r){l("subscribe: packet: ");const o=r?r.protocolVersion:4,s=e||{},a=s.dup?n.DUP_MASK:0,c=s.messageId,u=s.subscriptions,d=s.properties;let h=0;if("number"!=typeof c)return t.destroy(new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===o){if(p=T(t,d),!p)return!1;h+=p.length}if("object"!=typeof u||!u.length)return t.destroy(new Error("Invalid subscriptions")),!1;for(let e=0;e<u.length;e+=1){const r=u[e].topic,n=u[e].qos;if("string"!=typeof r)return t.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof n)return t.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(5===o){if("boolean"!=typeof(u[e].nl||!1))return t.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(u[e].rap||!1))return t.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;const r=u[e].rh||0;if("number"!=typeof r||r>2)return t.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=i.byteLength(r)+2+1}l("subscribe: writing to stream: %o",n.SUBSCRIBE_HEADER),t.write(n.SUBSCRIBE_HEADER[1][a?1:0][0]),v(t,h),g(t,c),null!==p&&p.write();let f=!0;for(const e of u){const r=e.topic,s=e.qos,a=+e.nl,c=+e.rap,l=e.rh;let u;S(t,r),u=n.SUBSCRIBE_OPTIONS_QOS[s],5===o&&(u|=a?n.SUBSCRIBE_OPTIONS_NL:0,u|=c?n.SUBSCRIBE_OPTIONS_RAP:0,u|=l?n.SUBSCRIBE_OPTIONS_RH[l]:0),f=t.write(i.from([u]))}return f}(e,t,r);case"suback":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.messageId,c=s.granted,l=s.properties;let u=0;if("number"!=typeof a)return t.destroy(new Error("Invalid messageId")),!1;u+=2;if("object"!=typeof c||!c.length)return t.destroy(new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.destroy(new Error("Invalid qos vector")),!1;u+=1}let d=null;if(5===o){if(d=O(t,l,r,u),!d)return!1;u+=d.length}t.write(n.SUBACK_HEADER),v(t,u),g(t,a),null!==d&&d.write();return t.write(i.from(c))}(e,t,r);case"unsubscribe":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.messageId,c=s.dup?n.DUP_MASK:0,l=s.unsubscriptions,u=s.properties;let d=0;if("number"!=typeof a)return t.destroy(new Error("Invalid messageId")),!1;d+=2;if("object"!=typeof l||!l.length)return t.destroy(new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.destroy(new Error("Invalid unsubscriptions")),!1;d+=i.byteLength(l[e])+2}let h=null;if(5===o){if(h=T(t,u),!h)return!1;d+=h.length}t.write(n.UNSUBSCRIBE_HEADER[1][c?1:0][0]),v(t,d),g(t,a),null!==h&&h.write();let p=!0;for(let e=0;e<l.length;e++)p=S(t,l[e]);return p}(e,t,r);case"unsuback":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.messageId,c=s.dup?n.DUP_MASK:0,l=s.granted,u=s.properties,d=s.cmd,h=0;let p=2;if("number"!=typeof a)return t.destroy(new Error("Invalid messageId")),!1;if(5===o){if("object"!=typeof l||!l.length)return t.destroy(new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.destroy(new Error("Invalid qos vector")),!1;p+=1}}let f=null;if(5===o){if(f=O(t,u,r,p),!f)return!1;p+=f.length}t.write(n.ACKS[d][h][c][0]),v(t,p),g(t,a),null!==f&&f.write();5===o&&t.write(i.from(l));return!0}(e,t,r);case"pingreq":case"pingresp":return function(e,t){return t.write(n.EMPTY[e.cmd])}(e,t);case"disconnect":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.reasonCode,c=s.properties;let l=5===o?1:0,u=null;if(5===o){if(u=O(t,c,r,l),!u)return!1;l+=u.length}t.write(i.from([n.codes.disconnect<<4])),v(t,l),5===o&&t.write(i.from([a]));null!==u&&u.write();return!0}(e,t,r);case"auth":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.reasonCode,c=s.properties;let l=5===o?1:0;5!==o&&t.destroy(new Error("Invalid mqtt version for auth packet"));const u=O(t,c,r,l);if(!u)return!1;l+=u.length,t.write(i.from([n.codes.auth<<4])),v(t,l),t.write(i.from([a])),null!==u&&u.write();return!0}(e,t,r);default:return t.destroy(new Error("Unknown command")),!1}}function y(e){e.uncork()}Object.defineProperty(b,"cacheNumbers",{get:()=>g===k,set(e){e?(u&&0!==Object.keys(u).length||(m=!0),g=k):(m=!1,g=E)}});const _={};function v(e,t){if(t>n.VARBYTEINT_MAX)return e.destroy(new Error(`Invalid variable byte integer: ${t}`)),!1;let r=_[t];return r||(r=p(t),t<16384&&(_[t]=r)),l("writeVarByteInt: writing to stream: %o",r),e.write(r)}function S(e,t){const r=i.byteLength(t);return g(e,r),l("writeString: %s",t),e.write(t,"utf8")}function w(e,t,r){S(e,t),S(e,r)}function k(e,t){return l("writeNumberCached: number: %d",t),l("writeNumberCached: %o",u[t]),e.write(u[t])}function E(e,t){const r=d(t);return l("writeNumberGenerated: %o",r),e.write(r)}function I(e,t){"string"==typeof t?S(e,t):t?(g(e,t.length),e.write(t)):g(e,0)}function T(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){A(e,{},0)}};let r=0;function o(t,r){let o=0;switch(n.propertiesTypes[t]){case"byte":if("boolean"!=typeof r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=2;break;case"int8":if("number"!=typeof r||r<0||r>255)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=2;break;case"binary":if(r&&null===r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=1+i.byteLength(r)+2;break;case"int16":if("number"!=typeof r||r<0||r>65535)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=3;break;case"int32":if("number"!=typeof r||r<0||r>4294967295)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=5;break;case"var":if("number"!=typeof r||r<0||r>268435455)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=1+i.byteLength(p(r));break;case"string":if("string"!=typeof r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=3+i.byteLength(r.toString());break;case"pair":if("object"!=typeof r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=Object.getOwnPropertyNames(r).reduce((e,t)=>{const n=r[t];return Array.isArray(n)?e+=n.reduce((e,r)=>e+=3+i.byteLength(t.toString())+2+i.byteLength(r.toString()),0):e+=3+i.byteLength(t.toString())+2+i.byteLength(r[t].toString()),e},0);break;default:return e.destroy(new Error(`Invalid property ${t}: ${r}`)),!1}return o}if(t)for(const e in t){let n=0,i=0;const s=t[e];if(void 0!==s){if(Array.isArray(s))for(let t=0;t<s.length;t++){if(i=o(e,s[t]),!i)return!1;n+=i}else{if(i=o(e,s),!i)return!1;n=i}if(!n)return!1;r+=n}}return{length:i.byteLength(p(r))+r,write(){A(e,t,r)}}}function O(e,t,r,n){const i=["reasonString","userProperties"],o=r&&r.properties&&r.properties.maximumPacketSize?r.properties.maximumPacketSize:0;let s=T(e,t);if(o)for(;n+s.length>o;){const r=i.shift();if(!r||!t[r])return!1;delete t[r],s=T(e,t)}return s}function C(e,t,r){switch(n.propertiesTypes[t]){case"byte":e.write(i.from([n.properties[t]])),e.write(i.from([+r]));break;case"int8":e.write(i.from([n.properties[t]])),e.write(i.from([r]));break;case"binary":e.write(i.from([n.properties[t]])),I(e,r);break;case"int16":e.write(i.from([n.properties[t]])),g(e,r);break;case"int32":e.write(i.from([n.properties[t]])),function(e,t){const r=f(t);l("write4ByteNumber: %o",r),e.write(r)}(e,r);break;case"var":e.write(i.from([n.properties[t]])),v(e,r);break;case"string":e.write(i.from([n.properties[t]])),S(e,r);break;case"pair":Object.getOwnPropertyNames(r).forEach(o=>{const s=r[o];Array.isArray(s)?s.forEach(r=>{e.write(i.from([n.properties[t]])),w(e,o.toString(),r.toString())}):(e.write(i.from([n.properties[t]])),w(e,o.toString(),s.toString()))});break;default:return e.destroy(new Error(`Invalid property ${t} value: ${r}`)),!1}}function A(e,t,r){v(e,r);for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&null!=t[r]){const n=t[r];if(Array.isArray(n))for(let t=0;t<n.length;t++)C(e,r,n[t]);else C(e,r,n)}}function x(e){return e?e instanceof i?e.length:i.byteLength(e):0}function P(e){return"string"==typeof e||e instanceof i}e.exports=b},3141(e,t,r){"use strict";var n=r(2861).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,this.end=d,t=3;break;default:return this.write=h,void(this.end=p)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function u(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function p(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},o.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},o.prototype.text=function(e,t){var r=function(e,t,r){var n=t.length-1;if(n<r)return 0;var i=s(t[n]);if(i>=0)return i>0&&(e.lastNeed=i-1),i;if(--n<r||-2===i)return 0;if(i=s(t[n]),i>=0)return i>0&&(e.lastNeed=i-2),i;if(--n<r||-2===i)return 0;if(i=s(t[n]),i>=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},3175(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(7732));t.default=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(e,t){this.client=e,this.timer="object"==typeof t&&"set"in t&&"clear"in t?t:(0,i.default)(t),this.setKeepalive(e.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(e){if(e*=1e3,isNaN(e)||e<=0||e>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${e}`);this._keepalive=e,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${e}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;const e=Math.ceil(1.5*this._keepalive);this._keepaliveTimeoutTimestamp=Date.now()+e,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,2===this.counter?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}}},3225(e){"use strict";"undefined"==typeof process||!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?e.exports={nextTick:function(e,t,r,n){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var i,o,s=arguments.length;switch(s){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,t)});case 3:return process.nextTick(function(){e.call(null,t,r)});case 4:return process.nextTick(function(){e.call(null,t,r,n)});default:for(i=new Array(s-1),o=0;o<i.length;)i[o++]=arguments[o];return process.nextTick(function(){e.apply(null,i)})}}}:e.exports=process},3338(e,t,r){"use strict";const{EMPTY_BUFFER:n}=r(2614),i=Buffer[Symbol.species];function o(e,t,r,n,i){for(let o=0;o<i;o++)r[n+o]=e[o]^t[3&o]}function s(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(e.exports={concat:function(e,t){if(0===e.length)return n;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let o=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,o),o+=n.length}return o<t?new i(r.buffer,r.byteOffset,o):r},mask:o,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new i(t):ArrayBuffer.isView(t)?r=new i(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{const t=r(Object(function(){var e=new Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e}()));e.exports.mask=function(e,r,n,i,s){s<48?o(e,r,n,i,s):t.mask(e,r,n,i,s)},e.exports.unmask=function(e,r){e.length<32?s(e,r):t.unmask(e,r)}}catch(e){}},3339(e){"use strict";e.exports=require("module")},3370(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(4134);e.exports=l;const a=r(7576),c=r(8584);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t<e.length;t++){const r=e[t];l.prototype[r]||(l.prototype[r]=c.prototype[r])}}function l(e){if(!(this instanceof l))return new l(e);a.call(this,e),c.call(this,e),e?(this.allowHalfOpen=!1!==e.allowHalfOpen,!1===e.readable&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===e.writable&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}let u,d;function h(){return void 0===u&&(u={}),u}n(l.prototype,{writable:{__proto__:null,...i(c.prototype,"writable")},writableHighWaterMark:{__proto__:null,...i(c.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...i(c.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...i(c.prototype,"writableBuffer")},writableLength:{__proto__:null,...i(c.prototype,"writableLength")},writableFinished:{__proto__:null,...i(c.prototype,"writableFinished")},writableCorked:{__proto__:null,...i(c.prototype,"writableCorked")},writableEnded:{__proto__:null,...i(c.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...i(c.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set(e){this._readableState&&this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}}),l.fromWeb=function(e,t){return h().newStreamDuplexFromReadableWritablePair(e,t)},l.toWeb=function(e){return h().newReadableWritablePairFromDuplex(e)},l.from=function(e){return d||(d=r(6706)),d(e,"body")}},3497(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(4966),i=r(720);t.default=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(e){e>0&&(this.aliasToTopic=new n.LRUCache({max:e}),this.topicToAlias={},this.numberAllocator=new i.NumberAllocator(1,e),this.max=e,this.length=0)}put(e,t){if(0===t||t>this.max)return!1;const r=this.aliasToTopic.get(t);return r&&delete this.topicToAlias[r],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.size,!0}getTopicByAlias(e){return this.aliasToTopic.get(e)}getAliasByTopic(e){const t=this.topicToAlias[e];return"undefined"!=typeof t&&this.aliasToTopic.get(t),t}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){const e=this.numberAllocator.firstVacant();return e||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}}},3719(e,t,r){"use strict";r(1060);const{Duplex:n}=r(2203);function i(e){e.emit("close")}function o(){!this.destroyed&&this._writableState.finished&&this.destroy()}function s(e){this.removeListener("error",s),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}e.exports=function(e,t){let r=!0;const a=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,r){const n=!r&&a._readableState.objectMode?t.toString():t;a.push(n)||e.pause()}),e.once("error",function(e){a.destroyed||(r=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,n){if(e.readyState===e.CLOSED)return n(t),void process.nextTick(i,a);let o=!1;e.once("error",function(e){o=!0,n(e)}),e.once("close",function(){o||n(t),process.nextTick(i,a)}),r&&e.terminate()},a._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close())):e.once("open",function(){a._final(t)})},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",function(){a._write(t,r,n)})},a.on("end",o),a.on("error",s),a}},3763(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shuffleArray=t.SocksClientError=void 0;class r extends Error{constructor(e,t){super(e),this.options=t}}t.SocksClientError=r,t.shuffleArray=function(e){for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}}},3874(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EDITOR_HTML=void 0,t.EDITOR_HTML='<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>Spatial Awareness - Topology Editor</title>\n <style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif; background: #1a1a2e; color: #eee; min-height: 100vh; }\n .container { display: flex; height: 100vh; }\n .sidebar { width: 300px; background: #16213e; border-right: 1px solid #0f3460; display: flex; flex-direction: column; overflow: hidden; }\n .sidebar-header { padding: 20px; border-bottom: 1px solid #0f3460; }\n .sidebar-header h1 { font-size: 18px; font-weight: 600; margin-bottom: 5px; }\n .sidebar-header p { font-size: 12px; color: #888; }\n .sidebar-content { flex: 1; overflow-y: auto; padding: 15px; }\n .section { margin-bottom: 20px; }\n .section-title { font-size: 12px; font-weight: 600; text-transform: uppercase; color: #888; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; }\n .btn { background: #0f3460; color: #fff; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-size: 13px; transition: background 0.2s; }\n .btn:hover { background: #1a4a7a; }\n .btn-primary { background: #e94560; }\n .btn-primary:hover { background: #ff6b6b; }\n .btn-small { padding: 4px 8px; font-size: 11px; }\n .camera-item, .connection-item { background: #0f3460; border-radius: 6px; padding: 12px; margin-bottom: 8px; cursor: pointer; transition: background 0.2s; }\n .camera-item:hover, .connection-item:hover { background: #1a4a7a; }\n .camera-item.selected, .connection-item.selected { outline: 2px solid #e94560; }\n .camera-name { font-weight: 500; margin-bottom: 4px; }\n .camera-info { font-size: 11px; color: #888; }\n .editor { flex: 1; display: flex; flex-direction: column; overflow: hidden; }\n .toolbar { background: #16213e; border-bottom: 1px solid #0f3460; padding: 10px 20px; display: flex; gap: 10px; align-items: center; }\n .toolbar-group { display: flex; gap: 5px; padding-right: 15px; border-right: 1px solid #0f3460; margin-right: 5px; }\n .toolbar-group:last-child { border-right: none; }\n .canvas-container { flex: 1; position: relative; overflow: hidden; background: #0f0f1a; }\n #floor-plan-canvas { position: absolute; top: 0; left: 0; }\n .canvas-placeholder { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: #666; }\n .canvas-placeholder h2 { margin-bottom: 15px; }\n .properties-panel { width: 280px; background: #16213e; border-left: 1px solid #0f3460; overflow-y: auto; padding: 15px; }\n .properties-panel h3 { font-size: 14px; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #0f3460; }\n .form-group { margin-bottom: 15px; }\n .form-group label { display: block; font-size: 12px; color: #888; margin-bottom: 5px; }\n .form-group input, .form-group select { width: 100%; padding: 8px 10px; background: #0f3460; border: 1px solid #1a4a7a; border-radius: 4px; color: #fff; font-size: 13px; }\n .form-group input:focus, .form-group select:focus { outline: none; border-color: #e94560; }\n .checkbox-group { display: flex; align-items: center; gap: 8px; }\n .checkbox-group input[type="checkbox"] { width: auto; }\n .transit-time-inputs { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; }\n .transit-time-inputs input { text-align: center; }\n .transit-time-labels { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; font-size: 10px; color: #666; text-align: center; }\n .modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.7); z-index: 1000; align-items: center; justify-content: center; }\n .modal-overlay.active { display: flex; }\n .modal { background: #16213e; border-radius: 8px; padding: 25px; max-width: 500px; width: 90%; max-height: 80vh; overflow-y: auto; }\n .modal h2 { margin-bottom: 20px; }\n .modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }\n .upload-zone { border: 2px dashed #0f3460; border-radius: 8px; padding: 40px; text-align: center; cursor: pointer; transition: border-color 0.2s, background 0.2s; }\n .upload-zone:hover { border-color: #e94560; background: rgba(233, 69, 96, 0.1); }\n .upload-zone input { display: none; }\n .status-bar { background: #0f3460; padding: 8px 20px; font-size: 12px; color: #888; display: flex; justify-content: space-between; }\n .status-indicator { display: flex; align-items: center; gap: 6px; }\n .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #4caf50; }\n .status-dot.warning { background: #ff9800; }\n .status-dot.error { background: #f44336; }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="sidebar">\n <div class="sidebar-header">\n <h1>Spatial Awareness</h1>\n <p>Topology Editor</p>\n </div>\n <div class="sidebar-content">\n <div class="section">\n <div class="section-title">\n <span>Cameras</span>\n <button class="btn btn-small" onclick="openAddCameraModal()">+ Add</button>\n </div>\n <div id="camera-list">\n <div class="camera-item" style="color: #666; text-align: center; cursor: default;">No cameras configured</div>\n </div>\n </div>\n <div class="section">\n <div class="section-title">\n <span>Connections</span>\n <button class="btn btn-small" onclick="openAddConnectionModal()">+ Add</button>\n </div>\n <div id="connection-list">\n <div class="connection-item" style="color: #666; text-align: center; cursor: default;">No connections configured</div>\n </div>\n </div>\n </div>\n </div>\n <div class="editor">\n <div class="toolbar">\n <div class="toolbar-group">\n <button class="btn" onclick="uploadFloorPlan()">Upload Floor Plan</button>\n </div>\n <div class="toolbar-group">\n <button class="btn" onclick="setTool(\'select\')">Select</button>\n <button class="btn" onclick="setTool(\'camera\')">Place Camera</button>\n <button class="btn" onclick="setTool(\'connect\')">Connect</button>\n </div>\n <div class="toolbar-group">\n <button class="btn btn-primary" onclick="saveTopology()">Save</button>\n </div>\n </div>\n <div class="canvas-container">\n <canvas id="floor-plan-canvas"></canvas>\n <div class="canvas-placeholder" id="canvas-placeholder">\n <h2>Floor Plan Editor</h2>\n <p>Upload a floor plan image to get started</p>\n <br>\n <button class="btn btn-primary" onclick="uploadFloorPlan()">Upload Floor Plan</button>\n </div>\n </div>\n <div class="status-bar">\n <div class="status-indicator">\n <div class="status-dot" id="status-dot"></div>\n <span id="status-text">Ready</span>\n </div>\n <div>\n <span id="camera-count">0</span> cameras | <span id="connection-count">0</span> connections\n </div>\n </div>\n </div>\n <div class="properties-panel" id="properties-panel">\n <h3>Properties</h3>\n <p style="color: #666; font-size: 13px;">Select a camera or connection to edit its properties.</p>\n </div>\n </div>\n\n <div class="modal-overlay" id="add-camera-modal">\n <div class="modal">\n <h2>Add Camera</h2>\n <div class="form-group">\n <label>Camera Device</label>\n <select id="camera-device-select"><option value="">Loading cameras...</option></select>\n </div>\n <div class="form-group">\n <label>Display Name</label>\n <input type="text" id="camera-name-input" placeholder="e.g., Front Door Camera">\n </div>\n <div class="form-group">\n <label class="checkbox-group">\n <input type="checkbox" id="camera-entry-checkbox">\n Entry Point (objects can enter property here)\n </label>\n </div>\n <div class="form-group">\n <label class="checkbox-group">\n <input type="checkbox" id="camera-exit-checkbox">\n Exit Point (objects can exit property here)\n </label>\n </div>\n <div class="modal-actions">\n <button class="btn" onclick="closeModal(\'add-camera-modal\')">Cancel</button>\n <button class="btn btn-primary" onclick="addCamera()">Add Camera</button>\n </div>\n </div>\n </div>\n\n <div class="modal-overlay" id="add-connection-modal">\n <div class="modal">\n <h2>Add Connection</h2>\n <div class="form-group">\n <label>Connection Name</label>\n <input type="text" id="connection-name-input" placeholder="e.g., Driveway to Front Door">\n </div>\n <div class="form-group">\n <label>From Camera</label>\n <select id="connection-from-select"></select>\n </div>\n <div class="form-group">\n <label>To Camera</label>\n <select id="connection-to-select"></select>\n </div>\n <div class="form-group">\n <label>Transit Time (seconds)</label>\n <div class="transit-time-inputs">\n <input type="number" id="transit-min" placeholder="Min" value="3">\n <input type="number" id="transit-typical" placeholder="Typical" value="10">\n <input type="number" id="transit-max" placeholder="Max" value="30">\n </div>\n <div class="transit-time-labels">\n <span>Minimum</span>\n <span>Typical</span>\n <span>Maximum</span>\n </div>\n </div>\n <div class="form-group">\n <label class="checkbox-group">\n <input type="checkbox" id="connection-bidirectional" checked>\n Bidirectional (works both ways)\n </label>\n </div>\n <div class="modal-actions">\n <button class="btn" onclick="closeModal(\'add-connection-modal\')">Cancel</button>\n <button class="btn btn-primary" onclick="addConnection()">Add Connection</button>\n </div>\n </div>\n </div>\n\n <div class="modal-overlay" id="upload-modal">\n <div class="modal">\n <h2>Upload Floor Plan</h2>\n <div class="upload-zone" onclick="document.getElementById(\'floor-plan-input\').click()">\n <p>Click to select an image<br><small>PNG, JPG, or SVG</small></p>\n <input type="file" id="floor-plan-input" accept="image/*" onchange="handleFloorPlanUpload(event)">\n </div>\n <div class="modal-actions">\n <button class="btn" onclick="closeModal(\'upload-modal\')">Cancel</button>\n </div>\n </div>\n </div>\n\n <script>\n let topology = { version: \'1.0\', cameras: [], connections: [], globalZones: [], floorPlan: null };\n let selectedItem = null;\n let currentTool = \'select\';\n let floorPlanImage = null;\n let availableCameras = [];\n const canvas = document.getElementById(\'floor-plan-canvas\');\n const ctx = canvas.getContext(\'2d\');\n\n async function init() {\n await loadTopology();\n await loadAvailableCameras();\n resizeCanvas();\n render();\n updateUI();\n }\n\n async function loadTopology() {\n try {\n const response = await fetch(\'../api/topology\');\n if (response.ok) {\n topology = await response.json();\n if (topology.floorPlan?.imageData) {\n await loadFloorPlanImage(topology.floorPlan.imageData);\n }\n }\n } catch (e) { console.error(\'Failed to load topology:\', e); }\n }\n\n async function loadAvailableCameras() {\n availableCameras = topology.cameras.map(c => ({ id: c.deviceId, name: c.name }));\n updateCameraSelects();\n }\n\n async function saveTopology() {\n try {\n setStatus(\'Saving...\', \'warning\');\n const response = await fetch(\'../api/topology\', {\n method: \'PUT\',\n headers: { \'Content-Type\': \'application/json\' },\n body: JSON.stringify(topology)\n });\n if (response.ok) { setStatus(\'Saved successfully\', \'success\'); }\n else { setStatus(\'Failed to save\', \'error\'); }\n } catch (e) { console.error(\'Failed to save topology:\', e); setStatus(\'Failed to save\', \'error\'); }\n }\n\n function resizeCanvas() {\n const container = canvas.parentElement;\n canvas.width = container.clientWidth;\n canvas.height = container.clientHeight;\n }\n\n function render() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n if (floorPlanImage) {\n document.getElementById(\'canvas-placeholder\').style.display = \'none\';\n const scale = Math.min(canvas.width / floorPlanImage.width, canvas.height / floorPlanImage.height) * 0.9;\n const x = (canvas.width - floorPlanImage.width * scale) / 2;\n const y = (canvas.height - floorPlanImage.height * scale) / 2;\n ctx.drawImage(floorPlanImage, x, y, floorPlanImage.width * scale, floorPlanImage.height * scale);\n } else {\n document.getElementById(\'canvas-placeholder\').style.display = \'block\';\n }\n for (const conn of topology.connections) {\n const fromCam = topology.cameras.find(c => c.deviceId === conn.fromCameraId);\n const toCam = topology.cameras.find(c => c.deviceId === conn.toCameraId);\n if (fromCam?.floorPlanPosition && toCam?.floorPlanPosition) {\n drawConnection(fromCam.floorPlanPosition, toCam.floorPlanPosition, conn);\n }\n }\n for (const camera of topology.cameras) {\n if (camera.floorPlanPosition) { drawCamera(camera); }\n }\n }\n\n function drawCamera(camera) {\n const pos = camera.floorPlanPosition;\n const isSelected = selectedItem?.type === \'camera\' && selectedItem?.id === camera.deviceId;\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, 20, 0, Math.PI * 2);\n ctx.fillStyle = isSelected ? \'#e94560\' : \'#0f3460\';\n ctx.fill();\n ctx.strokeStyle = \'#fff\';\n ctx.lineWidth = 2;\n ctx.stroke();\n ctx.fillStyle = \'#fff\';\n ctx.font = \'12px sans-serif\';\n ctx.textAlign = \'center\';\n ctx.textBaseline = \'middle\';\n ctx.fillText(\'CAM\', pos.x, pos.y);\n ctx.fillText(camera.name, pos.x, pos.y + 35);\n }\n\n function drawConnection(from, to, conn) {\n const isSelected = selectedItem?.type === \'connection\' && selectedItem?.id === conn.id;\n ctx.beginPath();\n ctx.moveTo(from.x, from.y);\n ctx.lineTo(to.x, to.y);\n ctx.strokeStyle = isSelected ? \'#e94560\' : \'#4caf50\';\n ctx.lineWidth = isSelected ? 4 : 2;\n ctx.stroke();\n if (!conn.bidirectional) {\n const angle = Math.atan2(to.y - from.y, to.x - from.x);\n const midX = (from.x + to.x) / 2;\n const midY = (from.y + to.y) / 2;\n ctx.beginPath();\n ctx.moveTo(midX, midY);\n ctx.lineTo(midX - 10 * Math.cos(angle - 0.5), midY - 10 * Math.sin(angle - 0.5));\n ctx.lineTo(midX - 10 * Math.cos(angle + 0.5), midY - 10 * Math.sin(angle + 0.5));\n ctx.closePath();\n ctx.fillStyle = isSelected ? \'#e94560\' : \'#4caf50\';\n ctx.fill();\n }\n }\n\n function uploadFloorPlan() { document.getElementById(\'upload-modal\').classList.add(\'active\'); }\n\n async function handleFloorPlanUpload(event) {\n const file = event.target.files[0];\n if (!file) return;\n const reader = new FileReader();\n reader.onload = async (e) => {\n const imageData = e.target.result;\n await loadFloorPlanImage(imageData);\n topology.floorPlan = { imageData, width: floorPlanImage.width, height: floorPlanImage.height };\n closeModal(\'upload-modal\');\n render();\n };\n reader.readAsDataURL(file);\n }\n\n function loadFloorPlanImage(imageData) {\n return new Promise((resolve) => {\n floorPlanImage = new Image();\n floorPlanImage.onload = resolve;\n floorPlanImage.src = imageData;\n });\n }\n\n function openAddCameraModal() { document.getElementById(\'add-camera-modal\').classList.add(\'active\'); }\n\n function addCamera() {\n const deviceId = document.getElementById(\'camera-device-select\').value;\n const name = document.getElementById(\'camera-name-input\').value || \'New Camera\';\n const isEntry = document.getElementById(\'camera-entry-checkbox\').checked;\n const isExit = document.getElementById(\'camera-exit-checkbox\').checked;\n const camera = {\n deviceId: deviceId || \'camera-\' + Date.now(),\n nativeId: \'cam-\' + Date.now(),\n name,\n isEntryPoint: isEntry,\n isExitPoint: isExit,\n trackClasses: [\'person\', \'car\', \'animal\'],\n floorPlanPosition: { x: canvas.width / 2 + Math.random() * 100 - 50, y: canvas.height / 2 + Math.random() * 100 - 50 }\n };\n topology.cameras.push(camera);\n closeModal(\'add-camera-modal\');\n updateUI();\n render();\n }\n\n function openAddConnectionModal() {\n if (topology.cameras.length < 2) { alert(\'Add at least 2 cameras before creating connections\'); return; }\n updateCameraSelects();\n document.getElementById(\'add-connection-modal\').classList.add(\'active\');\n }\n\n function updateCameraSelects() {\n const options = topology.cameras.map(c => \'<option value="\' + c.deviceId + \'">\' + c.name + \'</option>\').join(\'\');\n document.getElementById(\'connection-from-select\').innerHTML = options;\n document.getElementById(\'connection-to-select\').innerHTML = options;\n }\n\n function addConnection() {\n const name = document.getElementById(\'connection-name-input\').value;\n const fromId = document.getElementById(\'connection-from-select\').value;\n const toId = document.getElementById(\'connection-to-select\').value;\n const minTransit = parseInt(document.getElementById(\'transit-min\').value) * 1000;\n const typicalTransit = parseInt(document.getElementById(\'transit-typical\').value) * 1000;\n const maxTransit = parseInt(document.getElementById(\'transit-max\').value) * 1000;\n const bidirectional = document.getElementById(\'connection-bidirectional\').checked;\n if (fromId === toId) { alert(\'Please select different cameras\'); return; }\n const connection = {\n id: \'conn-\' + Date.now(),\n fromCameraId: fromId,\n toCameraId: toId,\n name: name || fromId + \' to \' + toId,\n exitZone: [],\n entryZone: [],\n transitTime: { min: minTransit, typical: typicalTransit, max: maxTransit },\n bidirectional\n };\n topology.connections.push(connection);\n closeModal(\'add-connection-modal\');\n updateUI();\n render();\n }\n\n function updateUI() {\n const cameraList = document.getElementById(\'camera-list\');\n if (topology.cameras.length === 0) {\n cameraList.innerHTML = \'<div class="camera-item" style="color: #666; text-align: center; cursor: default;">No cameras configured</div>\';\n } else {\n cameraList.innerHTML = topology.cameras.map(c => \'<div class="camera-item \' + (selectedItem?.type === \'camera\' && selectedItem?.id === c.deviceId ? \'selected\' : \'\') + \'" onclick="selectCamera(\\\'\' + c.deviceId + \'\\\')"><div class="camera-name">CAM \' + c.name + \'</div><div class="camera-info">\' + (c.isEntryPoint ? \'Entry \' : \'\') + (c.isExitPoint ? \'Exit\' : \'\') + \'</div></div>\').join(\'\');\n }\n const connectionList = document.getElementById(\'connection-list\');\n if (topology.connections.length === 0) {\n connectionList.innerHTML = \'<div class="connection-item" style="color: #666; text-align: center; cursor: default;">No connections configured</div>\';\n } else {\n connectionList.innerHTML = topology.connections.map(c => \'<div class="connection-item \' + (selectedItem?.type === \'connection\' && selectedItem?.id === c.id ? \'selected\' : \'\') + \'" onclick="selectConnection(\\\'\' + c.id + \'\\\')"><div class="camera-name">\' + c.name + \'</div><div class="camera-info">\' + (c.transitTime.typical / 1000) + \'s typical \' + (c.bidirectional ? \'<->\' : \'->\') + \'</div></div>\').join(\'\');\n }\n document.getElementById(\'camera-count\').textContent = topology.cameras.length;\n document.getElementById(\'connection-count\').textContent = topology.connections.length;\n }\n\n function selectCamera(deviceId) {\n selectedItem = { type: \'camera\', id: deviceId };\n const camera = topology.cameras.find(c => c.deviceId === deviceId);\n showCameraProperties(camera);\n updateUI();\n render();\n }\n\n function selectConnection(connId) {\n selectedItem = { type: \'connection\', id: connId };\n const connection = topology.connections.find(c => c.id === connId);\n showConnectionProperties(connection);\n updateUI();\n render();\n }\n\n function showCameraProperties(camera) {\n const panel = document.getElementById(\'properties-panel\');\n panel.innerHTML = \'<h3>Camera Properties</h3><div class="form-group"><label>Name</label><input type="text" value="\' + camera.name + \'" onchange="updateCameraName(\\\'\' + camera.deviceId + \'\\\', this.value)"></div><div class="form-group"><label class="checkbox-group"><input type="checkbox" \' + (camera.isEntryPoint ? \'checked\' : \'\') + \' onchange="updateCameraEntry(\\\'\' + camera.deviceId + \'\\\', this.checked)">Entry Point</label></div><div class="form-group"><label class="checkbox-group"><input type="checkbox" \' + (camera.isExitPoint ? \'checked\' : \'\') + \' onchange="updateCameraExit(\\\'\' + camera.deviceId + \'\\\', this.checked)">Exit Point</label></div><div class="form-group"><button class="btn" style="width: 100%; background: #f44336;" onclick="deleteCamera(\\\'\' + camera.deviceId + \'\\\')">Delete Camera</button></div>\';\n }\n\n function showConnectionProperties(connection) {\n const panel = document.getElementById(\'properties-panel\');\n panel.innerHTML = \'<h3>Connection Properties</h3><div class="form-group"><label>Name</label><input type="text" value="\' + connection.name + \'" onchange="updateConnectionName(\\\'\' + connection.id + \'\\\', this.value)"></div><div class="form-group"><label>Transit Time (seconds)</label><div class="transit-time-inputs"><input type="number" value="\' + (connection.transitTime.min / 1000) + \'" onchange="updateTransitTime(\\\'\' + connection.id + \'\\\', \\\'min\\\', this.value)"><input type="number" value="\' + (connection.transitTime.typical / 1000) + \'" onchange="updateTransitTime(\\\'\' + connection.id + \'\\\', \\\'typical\\\', this.value)"><input type="number" value="\' + (connection.transitTime.max / 1000) + \'" onchange="updateTransitTime(\\\'\' + connection.id + \'\\\', \\\'max\\\', this.value)"></div><div class="transit-time-labels"><span>Min</span><span>Typical</span><span>Max</span></div></div><div class="form-group"><label class="checkbox-group"><input type="checkbox" \' + (connection.bidirectional ? \'checked\' : \'\') + \' onchange="updateConnectionBidi(\\\'\' + connection.id + \'\\\', this.checked)">Bidirectional</label></div><div class="form-group"><button class="btn" style="width: 100%; background: #f44336;" onclick="deleteConnection(\\\'\' + connection.id + \'\\\')">Delete Connection</button></div>\';\n }\n\n function updateCameraName(id, value) { const camera = topology.cameras.find(c => c.deviceId === id); if (camera) camera.name = value; updateUI(); }\n function updateCameraEntry(id, value) { const camera = topology.cameras.find(c => c.deviceId === id); if (camera) camera.isEntryPoint = value; }\n function updateCameraExit(id, value) { const camera = topology.cameras.find(c => c.deviceId === id); if (camera) camera.isExitPoint = value; }\n function updateConnectionName(id, value) { const conn = topology.connections.find(c => c.id === id); if (conn) conn.name = value; updateUI(); }\n function updateTransitTime(id, field, value) { const conn = topology.connections.find(c => c.id === id); if (conn) conn.transitTime[field] = parseInt(value) * 1000; }\n function updateConnectionBidi(id, value) { const conn = topology.connections.find(c => c.id === id); if (conn) conn.bidirectional = value; render(); }\n function deleteCamera(id) { if (!confirm(\'Delete this camera?\')) return; topology.cameras = topology.cameras.filter(c => c.deviceId !== id); topology.connections = topology.connections.filter(c => c.fromCameraId !== id && c.toCameraId !== id); selectedItem = null; document.getElementById(\'properties-panel\').innerHTML = \'<h3>Properties</h3><p style="color: #666;">Select a camera or connection.</p>\'; updateUI(); render(); }\n function deleteConnection(id) { if (!confirm(\'Delete this connection?\')) return; topology.connections = topology.connections.filter(c => c.id !== id); selectedItem = null; document.getElementById(\'properties-panel\').innerHTML = \'<h3>Properties</h3><p style="color: #666;">Select a camera or connection.</p>\'; updateUI(); render(); }\n function setTool(tool) { currentTool = tool; setStatus(\'Tool: \' + tool, \'success\'); }\n function closeModal(id) { document.getElementById(id).classList.remove(\'active\'); }\n function setStatus(text, type) { document.getElementById(\'status-text\').textContent = text; const dot = document.getElementById(\'status-dot\'); dot.className = \'status-dot\'; if (type === \'warning\') dot.classList.add(\'warning\'); if (type === \'error\') dot.classList.add(\'error\'); }\n\n canvas.addEventListener(\'mousedown\', (e) => {\n const rect = canvas.getBoundingClientRect();\n const x = e.clientX - rect.left;\n const y = e.clientY - rect.top;\n if (currentTool === \'select\') {\n for (const camera of topology.cameras) {\n if (camera.floorPlanPosition) {\n const dist = Math.hypot(x - camera.floorPlanPosition.x, y - camera.floorPlanPosition.y);\n if (dist < 25) { selectCamera(camera.deviceId); return; }\n }\n }\n }\n });\n\n let dragging = null;\n canvas.addEventListener(\'mousedown\', (e) => {\n if (currentTool !== \'select\') return;\n const rect = canvas.getBoundingClientRect();\n const x = e.clientX - rect.left;\n const y = e.clientY - rect.top;\n for (const camera of topology.cameras) {\n if (camera.floorPlanPosition) {\n const dist = Math.hypot(x - camera.floorPlanPosition.x, y - camera.floorPlanPosition.y);\n if (dist < 25) { dragging = camera; return; }\n }\n }\n });\n\n canvas.addEventListener(\'mousemove\', (e) => {\n if (!dragging) return;\n const rect = canvas.getBoundingClientRect();\n dragging.floorPlanPosition.x = e.clientX - rect.left;\n dragging.floorPlanPosition.y = e.clientY - rect.top;\n render();\n });\n\n canvas.addEventListener(\'mouseup\', () => { dragging = null; });\n window.addEventListener(\'resize\', () => { resizeCanvas(); render(); });\n init();\n <\/script>\n</body>\n</html>'},3885(e,t,r){"use strict";e.exports=r(9844)()},3891(e){function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=3891,e.exports=t},3936(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(4756),o=n(r(9278)),s=n(r(5753)),a=n(r(6968)),c=(0,s.default)("mqttjs:tls");t.default=(e,t)=>{t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===o.default.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,c("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const r=function(e){const{host:t,port:r,socksProxy:n,...o}=e;if(void 0!==n){const s=(0,a.default)(t,r,n,{timeout:e.socksTimeout});return(0,i.connect)({...o,socket:s})}return(0,i.connect)(e)}(t);function n(n){t.rejectUnauthorized&&e.emit("error",n),r.end()}return r.on("secureConnect",()=>{t.rejectUnauthorized&&!r.authorized?r.emit("error",new Error("TLS not authorized")):r.removeListener("error",n)}),r.on("error",n),r}},4134(e){"use strict";class t extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r<e.length;r++)t+=` ${e[r].stack}\n`;super(t),this.name="AggregateError",this.errors=e}}e.exports={AggregateError:t,ArrayIsArray:e=>Array.isArray(e),ArrayPrototypeIncludes:(e,t)=>e.includes(t),ArrayPrototypeIndexOf:(e,t)=>e.indexOf(t),ArrayPrototypeJoin:(e,t)=>e.join(t),ArrayPrototypeMap:(e,t)=>e.map(t),ArrayPrototypePop:(e,t)=>e.pop(t),ArrayPrototypePush:(e,t)=>e.push(t),ArrayPrototypeSlice:(e,t,r)=>e.slice(t,r),Error,FunctionPrototypeCall:(e,t,...r)=>e.call(t,...r),FunctionPrototypeSymbolHasInstance:(e,t)=>Function.prototype[Symbol.hasInstance].call(e,t),MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties:(e,t)=>Object.defineProperties(e,t),ObjectDefineProperty:(e,t,r)=>Object.defineProperty(e,t,r),ObjectGetOwnPropertyDescriptor:(e,t)=>Object.getOwnPropertyDescriptor(e,t),ObjectKeys:e=>Object.keys(e),ObjectSetPrototypeOf:(e,t)=>Object.setPrototypeOf(e,t),Promise,PromisePrototypeCatch:(e,t)=>e.catch(t),PromisePrototypeThen:(e,t,r)=>e.then(t,r),PromiseReject:e=>Promise.reject(e),PromiseResolve:e=>Promise.resolve(e),ReflectApply:Reflect.apply,RegExpPrototypeTest:(e,t)=>e.test(t),SafeSet:Set,String,StringPrototypeSlice:(e,t,r)=>e.slice(t,r),StringPrototypeToLowerCase:e=>e.toLowerCase(),StringPrototypeToUpperCase:e=>e.toUpperCase(),StringPrototypeTrim:e=>e.trim(),Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet:(e,t,r)=>e.set(t,r),Boolean,Uint8Array}},4147(e,t,r){"use strict";const{SymbolDispose:n}=r(4134),{AbortError:i,codes:o}=r(6371),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(6115),l=r(6238),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if(((e,t)=>{if("object"!=typeof e||!("aborted"in e))throw new u(t,"AbortSignal",e)})(t,"signal"),!s(r)&&!a(r))throw new u("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const o=s(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)o();else{d=d||r(7760).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},4152(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TypedEventEmitter=void 0;const i=n(r(4434)),o=r(4723);class s{}t.TypedEventEmitter=s,(0,o.applyMixin)(s,i.default)},4192(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ScryptedMimeTypes=t.ScryptedInterface=t.MediaPlayerState=t.SecuritySystemObstruction=t.SecuritySystemMode=t.AirQuality=t.AirPurifierMode=t.AirPurifierStatus=t.ChargeState=t.LockState=t.PanTiltZoomMovement=t.ThermostatMode=t.TemperatureUnit=t.FanMode=t.HumidityMode=t.ScryptedDeviceType=t.ScryptedInterfaceDescriptors=t.ScryptedInterfaceMethod=t.ScryptedInterfaceProperty=t.DeviceBase=t.TYPES_VERSION=void 0,t.TYPES_VERSION="0.5.51";var r,n,i,o,s,a,c,l,u,d,h,p,f,g,m,b,y,_;t.DeviceBase=class{},function(e){e.id="id",e.info="info",e.interfaces="interfaces",e.mixins="mixins",e.name="name",e.nativeId="nativeId",e.pluginId="pluginId",e.providedInterfaces="providedInterfaces",e.providedName="providedName",e.providedRoom="providedRoom",e.providedType="providedType",e.providerId="providerId",e.room="room",e.type="type",e.scryptedRuntimeArguments="scryptedRuntimeArguments",e.on="on",e.brightness="brightness",e.colorTemperature="colorTemperature",e.rgb="rgb",e.hsv="hsv",e.buttons="buttons",e.sensors="sensors",e.running="running",e.paused="paused",e.docked="docked",e.temperatureSetting="temperatureSetting",e.temperature="temperature",e.temperatureUnit="temperatureUnit",e.humidity="humidity",e.resolution="resolution",e.audioVolumes="audioVolumes",e.recordingActive="recordingActive",e.ptzCapabilities="ptzCapabilities",e.lockState="lockState",e.entryOpen="entryOpen",e.batteryLevel="batteryLevel",e.chargeState="chargeState",e.online="online",e.fromMimeType="fromMimeType",e.toMimeType="toMimeType",e.converters="converters",e.binaryState="binaryState",e.tampered="tampered",e.sleeping="sleeping",e.powerDetected="powerDetected",e.audioDetected="audioDetected",e.motionDetected="motionDetected",e.ambientLight="ambientLight",e.occupied="occupied",e.flooded="flooded",e.ultraviolet="ultraviolet",e.luminance="luminance",e.position="position",e.securitySystemState="securitySystemState",e.pm10Density="pm10Density",e.pm25Density="pm25Density",e.vocDensity="vocDensity",e.noxDensity="noxDensity",e.co2ppm="co2ppm",e.airQuality="airQuality",e.airPurifierState="airPurifierState",e.filterChangeIndication="filterChangeIndication",e.filterLifeLevel="filterLifeLevel",e.humiditySetting="humiditySetting",e.fan="fan",e.applicationInfo="applicationInfo",e.chatCompletionCapabilities="chatCompletionCapabilities",e.systemDevice="systemDevice"}(r||(t.ScryptedInterfaceProperty=r={})),function(e){e.listen="listen",e.probe="probe",e.setMixins="setMixins",e.setName="setName",e.setRoom="setRoom",e.setType="setType",e.getPluginJson="getPluginJson",e.turnOff="turnOff",e.turnOn="turnOn",e.setBrightness="setBrightness",e.getTemperatureMaxK="getTemperatureMaxK",e.getTemperatureMinK="getTemperatureMinK",e.setColorTemperature="setColorTemperature",e.setRgb="setRgb",e.setHsv="setHsv",e.pressButton="pressButton",e.sendNotification="sendNotification",e.start="start",e.stop="stop",e.pause="pause",e.resume="resume",e.dock="dock",e.setTemperature="setTemperature",e.setTemperatureUnit="setTemperatureUnit",e.getPictureOptions="getPictureOptions",e.takePicture="takePicture",e.getAudioStream="getAudioStream",e.setAudioVolumes="setAudioVolumes",e.startDisplay="startDisplay",e.stopDisplay="stopDisplay",e.getVideoStream="getVideoStream",e.getVideoStreamOptions="getVideoStreamOptions",e.getPrivacyMasks="getPrivacyMasks",e.setPrivacyMasks="setPrivacyMasks",e.getVideoTextOverlays="getVideoTextOverlays",e.setVideoTextOverlay="setVideoTextOverlay",e.getRecordingStream="getRecordingStream",e.getRecordingStreamCurrentTime="getRecordingStreamCurrentTime",e.getRecordingStreamOptions="getRecordingStreamOptions",e.getRecordingStreamThumbnail="getRecordingStreamThumbnail",e.deleteRecordingStream="deleteRecordingStream",e.setRecordingActive="setRecordingActive",e.ptzCommand="ptzCommand",e.getRecordedEvents="getRecordedEvents",e.getVideoClip="getVideoClip",e.getVideoClips="getVideoClips",e.getVideoClipThumbnail="getVideoClipThumbnail",e.removeVideoClips="removeVideoClips",e.setVideoStreamOptions="setVideoStreamOptions",e.startIntercom="startIntercom",e.stopIntercom="stopIntercom",e.lock="lock",e.unlock="unlock",e.addPassword="addPassword",e.getPasswords="getPasswords",e.removePassword="removePassword",e.activate="activate",e.deactivate="deactivate",e.isReversible="isReversible",e.closeEntry="closeEntry",e.openEntry="openEntry",e.getDevice="getDevice",e.releaseDevice="releaseDevice",e.adoptDevice="adoptDevice",e.discoverDevices="discoverDevices",e.createDevice="createDevice",e.getCreateDeviceSettings="getCreateDeviceSettings",e.reboot="reboot",e.getRefreshFrequency="getRefreshFrequency",e.refresh="refresh",e.getMediaStatus="getMediaStatus",e.load="load",e.seek="seek",e.skipNext="skipNext",e.skipPrevious="skipPrevious",e.convert="convert",e.convertMedia="convertMedia",e.getSettings="getSettings",e.putSetting="putSetting",e.armSecuritySystem="armSecuritySystem",e.disarmSecuritySystem="disarmSecuritySystem",e.setAirPurifierState="setAirPurifierState",e.getReadmeMarkdown="getReadmeMarkdown",e.getOauthUrl="getOauthUrl",e.onOauthCallback="onOauthCallback",e.canMixin="canMixin",e.getMixin="getMixin",e.releaseMixin="releaseMixin",e.onRequest="onRequest",e.onConnection="onConnection",e.onPush="onPush",e.run="run",e.eval="eval",e.loadScripts="loadScripts",e.saveScript="saveScript",e.forkInterface="forkInterface",e.getDetectionInput="getDetectionInput",e.getObjectTypes="getObjectTypes",e.detectObjects="detectObjects",e.generateObjectDetections="generateObjectDetections",e.getDetectionModel="getDetectionModel",e.setHumidity="setHumidity",e.setFan="setFan",e.startRTCSignalingSession="startRTCSignalingSession",e.createRTCSignalingSession="createRTCSignalingSession",e.getScryptedUserAccessControl="getScryptedUserAccessControl",e.generateVideoFrames="generateVideoFrames",e.connectStream="connectStream",e.getTTYSettings="getTTYSettings",e.getChatCompletion="getChatCompletion",e.streamChatCompletion="streamChatCompletion",e.getTextEmbedding="getTextEmbedding",e.getImageEmbedding="getImageEmbedding",e.callLLMTool="callLLMTool",e.getLLMTools="getLLMTools"}(n||(t.ScryptedInterfaceMethod=n={})),t.ScryptedInterfaceDescriptors={ScryptedDevice:{name:"ScryptedDevice",methods:["listen","probe","setMixins","setName","setRoom","setType"],properties:["id","info","interfaces","mixins","name","nativeId","pluginId","providedInterfaces","providedName","providedRoom","providedType","providerId","room","type"]},ScryptedPlugin:{name:"ScryptedPlugin",methods:["getPluginJson"],properties:[]},ScryptedPluginRuntime:{name:"ScryptedPluginRuntime",methods:[],properties:["scryptedRuntimeArguments"]},OnOff:{name:"OnOff",methods:["turnOff","turnOn"],properties:["on"]},Brightness:{name:"Brightness",methods:["setBrightness"],properties:["brightness"]},ColorSettingTemperature:{name:"ColorSettingTemperature",methods:["getTemperatureMaxK","getTemperatureMinK","setColorTemperature"],properties:["colorTemperature"]},ColorSettingRgb:{name:"ColorSettingRgb",methods:["setRgb"],properties:["rgb"]},ColorSettingHsv:{name:"ColorSettingHsv",methods:["setHsv"],properties:["hsv"]},Buttons:{name:"Buttons",methods:[],properties:["buttons"]},PressButtons:{name:"PressButtons",methods:["pressButton"],properties:[]},Sensors:{name:"Sensors",methods:[],properties:["sensors"]},Notifier:{name:"Notifier",methods:["sendNotification"],properties:[]},StartStop:{name:"StartStop",methods:["start","stop"],properties:["running"]},Pause:{name:"Pause",methods:["pause","resume"],properties:["paused"]},Dock:{name:"Dock",methods:["dock"],properties:["docked"]},TemperatureSetting:{name:"TemperatureSetting",methods:["setTemperature"],properties:["temperatureSetting"]},Thermometer:{name:"Thermometer",methods:["setTemperatureUnit"],properties:["temperature","temperatureUnit"]},HumiditySensor:{name:"HumiditySensor",methods:[],properties:["humidity"]},Camera:{name:"Camera",methods:["getPictureOptions","takePicture"],properties:[]},Resolution:{name:"Resolution",methods:[],properties:["resolution"]},Microphone:{name:"Microphone",methods:["getAudioStream"],properties:[]},AudioVolumeControl:{name:"AudioVolumeControl",methods:["setAudioVolumes"],properties:["audioVolumes"]},Display:{name:"Display",methods:["startDisplay","stopDisplay"],properties:[]},VideoCamera:{name:"VideoCamera",methods:["getVideoStream","getVideoStreamOptions"],properties:[]},VideoCameraMask:{name:"VideoCameraMask",methods:["getPrivacyMasks","setPrivacyMasks"],properties:[]},VideoTextOverlays:{name:"VideoTextOverlays",methods:["getVideoTextOverlays","setVideoTextOverlay"],properties:[]},VideoRecorder:{name:"VideoRecorder",methods:["getRecordingStream","getRecordingStreamCurrentTime","getRecordingStreamOptions","getRecordingStreamThumbnail"],properties:["recordingActive"]},VideoRecorderManagement:{name:"VideoRecorderManagement",methods:["deleteRecordingStream","setRecordingActive"],properties:[]},PanTiltZoom:{name:"PanTiltZoom",methods:["ptzCommand"],properties:["ptzCapabilities"]},EventRecorder:{name:"EventRecorder",methods:["getRecordedEvents"],properties:[]},VideoClips:{name:"VideoClips",methods:["getVideoClip","getVideoClips","getVideoClipThumbnail","removeVideoClips"],properties:[]},VideoCameraConfiguration:{name:"VideoCameraConfiguration",methods:["setVideoStreamOptions"],properties:[]},Intercom:{name:"Intercom",methods:["startIntercom","stopIntercom"],properties:[]},Lock:{name:"Lock",methods:["lock","unlock"],properties:["lockState"]},PasswordStore:{name:"PasswordStore",methods:["addPassword","getPasswords","removePassword"],properties:[]},Scene:{name:"Scene",methods:["activate","deactivate","isReversible"],properties:[]},Entry:{name:"Entry",methods:["closeEntry","openEntry"],properties:[]},EntrySensor:{name:"EntrySensor",methods:[],properties:["entryOpen"]},DeviceProvider:{name:"DeviceProvider",methods:["getDevice","releaseDevice"],properties:[]},DeviceDiscovery:{name:"DeviceDiscovery",methods:["adoptDevice","discoverDevices"],properties:[]},DeviceCreator:{name:"DeviceCreator",methods:["createDevice","getCreateDeviceSettings"],properties:[]},Battery:{name:"Battery",methods:[],properties:["batteryLevel"]},Charger:{name:"Charger",methods:[],properties:["chargeState"]},Reboot:{name:"Reboot",methods:["reboot"],properties:[]},Refresh:{name:"Refresh",methods:["getRefreshFrequency","refresh"],properties:[]},MediaPlayer:{name:"MediaPlayer",methods:["getMediaStatus","load","seek","skipNext","skipPrevious"],properties:[]},Online:{name:"Online",methods:[],properties:["online"]},BufferConverter:{name:"BufferConverter",methods:["convert"],properties:["fromMimeType","toMimeType"]},MediaConverter:{name:"MediaConverter",methods:["convertMedia"],properties:["converters"]},Settings:{name:"Settings",methods:["getSettings","putSetting"],properties:[]},BinarySensor:{name:"BinarySensor",methods:[],properties:["binaryState"]},TamperSensor:{name:"TamperSensor",methods:[],properties:["tampered"]},Sleep:{name:"Sleep",methods:[],properties:["sleeping"]},PowerSensor:{name:"PowerSensor",methods:[],properties:["powerDetected"]},AudioSensor:{name:"AudioSensor",methods:[],properties:["audioDetected"]},MotionSensor:{name:"MotionSensor",methods:[],properties:["motionDetected"]},AmbientLightSensor:{name:"AmbientLightSensor",methods:[],properties:["ambientLight"]},OccupancySensor:{name:"OccupancySensor",methods:[],properties:["occupied"]},FloodSensor:{name:"FloodSensor",methods:[],properties:["flooded"]},UltravioletSensor:{name:"UltravioletSensor",methods:[],properties:["ultraviolet"]},LuminanceSensor:{name:"LuminanceSensor",methods:[],properties:["luminance"]},PositionSensor:{name:"PositionSensor",methods:[],properties:["position"]},SecuritySystem:{name:"SecuritySystem",methods:["armSecuritySystem","disarmSecuritySystem"],properties:["securitySystemState"]},PM10Sensor:{name:"PM10Sensor",methods:[],properties:["pm10Density"]},PM25Sensor:{name:"PM25Sensor",methods:[],properties:["pm25Density"]},VOCSensor:{name:"VOCSensor",methods:[],properties:["vocDensity"]},NOXSensor:{name:"NOXSensor",methods:[],properties:["noxDensity"]},CO2Sensor:{name:"CO2Sensor",methods:[],properties:["co2ppm"]},AirQualitySensor:{name:"AirQualitySensor",methods:[],properties:["airQuality"]},AirPurifier:{name:"AirPurifier",methods:["setAirPurifierState"],properties:["airPurifierState"]},FilterMaintenance:{name:"FilterMaintenance",methods:[],properties:["filterChangeIndication","filterLifeLevel"]},Readme:{name:"Readme",methods:["getReadmeMarkdown"],properties:[]},OauthClient:{name:"OauthClient",methods:["getOauthUrl","onOauthCallback"],properties:[]},MixinProvider:{name:"MixinProvider",methods:["canMixin","getMixin","releaseMixin"],properties:[]},HttpRequestHandler:{name:"HttpRequestHandler",methods:["onRequest"],properties:[]},EngineIOHandler:{name:"EngineIOHandler",methods:["onConnection"],properties:[]},PushHandler:{name:"PushHandler",methods:["onPush"],properties:[]},Program:{name:"Program",methods:["run"],properties:[]},Scriptable:{name:"Scriptable",methods:["eval","loadScripts","saveScript"],properties:[]},ClusterForkInterface:{name:"ClusterForkInterface",methods:["forkInterface"],properties:[]},ObjectDetector:{name:"ObjectDetector",methods:["getDetectionInput","getObjectTypes"],properties:[]},ObjectDetection:{name:"ObjectDetection",methods:["detectObjects","generateObjectDetections","getDetectionModel"],properties:[]},ObjectDetectionPreview:{name:"ObjectDetectionPreview",methods:[],properties:[]},ObjectDetectionGenerator:{name:"ObjectDetectionGenerator",methods:[],properties:[]},HumiditySetting:{name:"HumiditySetting",methods:["setHumidity"],properties:["humiditySetting"]},Fan:{name:"Fan",methods:["setFan"],properties:["fan"]},RTCSignalingChannel:{name:"RTCSignalingChannel",methods:["startRTCSignalingSession"],properties:[]},RTCSignalingClient:{name:"RTCSignalingClient",methods:["createRTCSignalingSession"],properties:[]},LauncherApplication:{name:"LauncherApplication",methods:[],properties:["applicationInfo"]},ScryptedUser:{name:"ScryptedUser",methods:["getScryptedUserAccessControl"],properties:[]},VideoFrameGenerator:{name:"VideoFrameGenerator",methods:["generateVideoFrames"],properties:[]},StreamService:{name:"StreamService",methods:["connectStream"],properties:[]},TTY:{name:"TTY",methods:[],properties:[]},TTYSettings:{name:"TTYSettings",methods:["getTTYSettings"],properties:[]},ChatCompletion:{name:"ChatCompletion",methods:["getChatCompletion","streamChatCompletion"],properties:["chatCompletionCapabilities"]},TextEmbedding:{name:"TextEmbedding",methods:["getTextEmbedding"],properties:[]},ImageEmbedding:{name:"ImageEmbedding",methods:["getImageEmbedding"],properties:[]},LLMTools:{name:"LLMTools",methods:["callLLMTool","getLLMTools"],properties:[]},ScryptedSystemDevice:{name:"ScryptedSystemDevice",methods:[],properties:["systemDevice"]},ScryptedDeviceCreator:{name:"ScryptedDeviceCreator",methods:[],properties:[]},ScryptedSettings:{name:"ScryptedSettings",methods:[],properties:[]}},function(e){e.Builtin="Builtin",e.Internal="Internal",e.Camera="Camera",e.Fan="Fan",e.Light="Light",e.Switch="Switch",e.Outlet="Outlet",e.Sensor="Sensor",e.Scene="Scene",e.Program="Program",e.Automation="Automation",e.Vacuum="Vacuum",e.Notifier="Notifier",e.Thermostat="Thermostat",e.Lock="Lock",e.PasswordControl="PasswordControl",e.Display="Display",e.SmartDisplay="SmartDisplay",e.Speaker="Speaker",e.SmartSpeaker="SmartSpeaker",e.RemoteDesktop="RemoteDesktop",e.Event="Event",e.Entry="Entry",e.Garage="Garage",e.DeviceProvider="DeviceProvider",e.DataSource="DataSource",e.API="API",e.Buttons="Buttons",e.Doorbell="Doorbell",e.Irrigation="Irrigation",e.Valve="Valve",e.Person="Person",e.SecuritySystem="SecuritySystem",e.WindowCovering="WindowCovering",e.Siren="Siren",e.AirPurifier="AirPurifier",e.Internet="Internet",e.Network="Network",e.Bridge="Bridge",e.LLM="LLM",e.Unknown="Unknown"}(i||(t.ScryptedDeviceType=i={})),function(e){e.Humidify="Humidify",e.Dehumidify="Dehumidify",e.Auto="Auto",e.Off="Off"}(o||(t.HumidityMode=o={})),function(e){e.Auto="Auto",e.Manual="Manual"}(s||(t.FanMode=s={})),function(e){e.C="C",e.F="F"}(a||(t.TemperatureUnit=a={})),function(e){e.Off="Off",e.Cool="Cool",e.Heat="Heat",e.HeatCool="HeatCool",e.Auto="Auto",e.FanOnly="FanOnly",e.Purifier="Purifier",e.Eco="Eco",e.Dry="Dry",e.On="On"}(c||(t.ThermostatMode=c={})),function(e){e.Absolute="Absolute",e.Relative="Relative",e.Continuous="Continuous",e.Preset="Preset",e.Home="Home"}(l||(t.PanTiltZoomMovement=l={})),function(e){e.Locked="Locked",e.Unlocked="Unlocked",e.Jammed="Jammed"}(u||(t.LockState=u={})),function(e){e.Trickle="trickle",e.Charging="charging",e.NotCharging="not-charging"}(d||(t.ChargeState=d={})),function(e){e.Inactive="Inactive",e.Idle="Idle",e.Active="Active",e.ActiveNightMode="ActiveNightMode"}(h||(t.AirPurifierStatus=h={})),function(e){e.Manual="Manual",e.Automatic="Automatic"}(p||(t.AirPurifierMode=p={})),function(e){e.Unknown="Unknown",e.Excellent="Excellent",e.Good="Good",e.Fair="Fair",e.Inferior="Inferior",e.Poor="Poor"}(f||(t.AirQuality=f={})),function(e){e.Disarmed="Disarmed",e.HomeArmed="HomeArmed",e.AwayArmed="AwayArmed",e.NightArmed="NightArmed"}(g||(t.SecuritySystemMode=g={})),function(e){e.Sensor="Sensor",e.Occupied="Occupied",e.Time="Time",e.Error="Error"}(m||(t.SecuritySystemObstruction=m={})),function(e){e.Idle="Idle",e.Playing="Playing",e.Paused="Paused",e.Buffering="Buffering"}(b||(t.MediaPlayerState=b={})),function(e){e.ScryptedDevice="ScryptedDevice",e.ScryptedPlugin="ScryptedPlugin",e.ScryptedPluginRuntime="ScryptedPluginRuntime",e.OnOff="OnOff",e.Brightness="Brightness",e.ColorSettingTemperature="ColorSettingTemperature",e.ColorSettingRgb="ColorSettingRgb",e.ColorSettingHsv="ColorSettingHsv",e.Buttons="Buttons",e.PressButtons="PressButtons",e.Sensors="Sensors",e.Notifier="Notifier",e.StartStop="StartStop",e.Pause="Pause",e.Dock="Dock",e.TemperatureSetting="TemperatureSetting",e.Thermometer="Thermometer",e.HumiditySensor="HumiditySensor",e.Camera="Camera",e.Resolution="Resolution",e.Microphone="Microphone",e.AudioVolumeControl="AudioVolumeControl",e.Display="Display",e.VideoCamera="VideoCamera",e.VideoCameraMask="VideoCameraMask",e.VideoTextOverlays="VideoTextOverlays",e.VideoRecorder="VideoRecorder",e.VideoRecorderManagement="VideoRecorderManagement",e.PanTiltZoom="PanTiltZoom",e.EventRecorder="EventRecorder",e.VideoClips="VideoClips",e.VideoCameraConfiguration="VideoCameraConfiguration",e.Intercom="Intercom",e.Lock="Lock",e.PasswordStore="PasswordStore",e.Scene="Scene",e.Entry="Entry",e.EntrySensor="EntrySensor",e.DeviceProvider="DeviceProvider",e.DeviceDiscovery="DeviceDiscovery",e.DeviceCreator="DeviceCreator",e.Battery="Battery",e.Charger="Charger",e.Reboot="Reboot",e.Refresh="Refresh",e.MediaPlayer="MediaPlayer",e.Online="Online",e.BufferConverter="BufferConverter",e.MediaConverter="MediaConverter",e.Settings="Settings",e.BinarySensor="BinarySensor",e.TamperSensor="TamperSensor",e.Sleep="Sleep",e.PowerSensor="PowerSensor",e.AudioSensor="AudioSensor",e.MotionSensor="MotionSensor",e.AmbientLightSensor="AmbientLightSensor",e.OccupancySensor="OccupancySensor",e.FloodSensor="FloodSensor",e.UltravioletSensor="UltravioletSensor",e.LuminanceSensor="LuminanceSensor",e.PositionSensor="PositionSensor",e.SecuritySystem="SecuritySystem",e.PM10Sensor="PM10Sensor",e.PM25Sensor="PM25Sensor",e.VOCSensor="VOCSensor",e.NOXSensor="NOXSensor",e.CO2Sensor="CO2Sensor",e.AirQualitySensor="AirQualitySensor",e.AirPurifier="AirPurifier",e.FilterMaintenance="FilterMaintenance",e.Readme="Readme",e.OauthClient="OauthClient",e.MixinProvider="MixinProvider",e.HttpRequestHandler="HttpRequestHandler",e.EngineIOHandler="EngineIOHandler",e.PushHandler="PushHandler",e.Program="Program",e.Scriptable="Scriptable",e.ClusterForkInterface="ClusterForkInterface",e.ObjectDetector="ObjectDetector",e.ObjectDetection="ObjectDetection",e.ObjectDetectionPreview="ObjectDetectionPreview",e.ObjectDetectionGenerator="ObjectDetectionGenerator",e.HumiditySetting="HumiditySetting",e.Fan="Fan",e.RTCSignalingChannel="RTCSignalingChannel",e.RTCSignalingClient="RTCSignalingClient",e.LauncherApplication="LauncherApplication",e.ScryptedUser="ScryptedUser",e.VideoFrameGenerator="VideoFrameGenerator",e.StreamService="StreamService",e.TTY="TTY",e.TTYSettings="TTYSettings",e.ChatCompletion="ChatCompletion",e.TextEmbedding="TextEmbedding",e.ImageEmbedding="ImageEmbedding",e.LLMTools="LLMTools",e.ScryptedSystemDevice="ScryptedSystemDevice",e.ScryptedDeviceCreator="ScryptedDeviceCreator",e.ScryptedSettings="ScryptedSettings"}(y||(t.ScryptedInterface=y={})),function(e){e.Url="text/x-uri",e.InsecureLocalUrl="text/x-insecure-local-uri",e.LocalUrl="text/x-local-uri",e.ServerId="text/x-server-id",e.PushEndpoint="text/x-push-endpoint",e.SchemePrefix="x-scrypted/x-scrypted-scheme-",e.MediaStreamUrl="text/x-media-url",e.MediaObject="x-scrypted/x-scrypted-media-object",e.RequestMediaObject="x-scrypted/x-scrypted-request-media-object",e.RequestMediaStream="x-scrypted/x-scrypted-request-stream",e.MediaStreamFeedback="x-scrypted/x-media-stream-feedback",e.FFmpegInput="x-scrypted/x-ffmpeg-input",e.FFmpegTranscodeStream="x-scrypted/x-ffmpeg-transcode-stream",e.RTCSignalingChannel="x-scrypted/x-scrypted-rtc-signaling-channel",e.RTCSignalingSession="x-scrypted/x-scrypted-rtc-signaling-session",e.RTCConnectionManagement="x-scrypted/x-scrypted-rtc-connection-management",e.Image="x-scrypted/x-scrypted-image"}(_||(t.ScryptedMimeTypes=_={}))},4259(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(4134),{EventEmitter:o}=r(4434);function s(e){o.call(this,e)}function a(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(s.prototype,o.prototype),i(s,o),s.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(e){d(),0===o.listenerCount(this,"error")&&this.emit("error",e)}function d(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},4264(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=(e,t,r)=>{e.log("handling pubrel packet");const n="undefined"!=typeof r?r:e.noop,{messageId:i}=t,o={cmd:"pubcomp",messageId:i};e.incomingStore.get(t,(t,r)=>{t?e._sendPacket(o,n):(e.emit("message",r.topic,r.payload,r),e.handleMessage(r,t=>{if(t)return n(t);e.incomingStore.del(r,e.noop),e._sendPacket(o,n)}))})}},4386(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AlertManager=void 0;const i=n(r(7562)),o=r(4997),{systemManager:s}=i.default;t.AlertManager=class{rules=[];recentAlerts=[];cooldowns=new Map;console;storage;maxAlerts=100;constructor(e,t){this.console=e,this.storage=t,this.loadRules()}async checkAndAlert(e,t,r){const n=this.rules.find(t=>t.type===e&&t.enabled);if(!n)return null;if(n.objectClasses&&n.objectClasses.length>0&&!n.objectClasses.includes(t.className))return null;if(n.cameraIds&&n.cameraIds.length>0&&r.cameraId&&!n.cameraIds.includes(r.cameraId))return null;const i=`${n.id}:${t.globalId}`,s=this.cooldowns.get(i)||0;if(n.cooldown>0&&Date.now()-s<n.cooldown)return null;if(!this.evaluateConditions(n.conditions,t))return null;const a={...r,objectClass:t.className,objectLabel:t.label},c=(0,o.createAlert)(e,t.globalId,a,n.severity,n.id);return this.recentAlerts.unshift(c),this.recentAlerts.length>this.maxAlerts&&this.recentAlerts.pop(),this.cooldowns.set(i,Date.now()),await this.sendNotifications(c,n),this.console.log(`Alert generated: [${c.severity}] ${c.message}`),c}async sendNotifications(e,t){const r=t.notifiers.length>0?t.notifiers:this.getDefaultNotifiers();for(const t of r)try{const r=s.getDeviceById(t);if(!r){this.console.warn(`Notifier not found: ${t}`);continue}await r.sendNotification(this.getNotificationTitle(e),{body:e.message,data:{type:e.type,severity:e.severity,trackedObjectId:e.trackedObjectId,timestamp:e.timestamp}}),this.console.log(`Notification sent to ${t}`)}catch(e){this.console.error(`Failed to send notification to ${t}:`,e)}}getNotificationTitle(e){const t="critical"===e.severity?"🚨 ":"warning"===e.severity?"⚠️ ":"ℹ️ ";switch(e.type){case"property_entry":return`${t}Entry Detected`;case"property_exit":return`${t}Exit Detected`;case"unusual_path":return`${t}Unusual Path`;case"dwell_time":return`${t}Extended Presence`;case"restricted_zone":return`${t}Restricted Zone Alert`;case"lost_tracking":return`${t}Lost Tracking`;case"reappearance":return`${t}Object Reappeared`;default:return`${t}Spatial Awareness Alert`}}getDefaultNotifiers(){try{const e=this.storage.getItem("defaultNotifier");return e?[e]:[]}catch{return[]}}evaluateConditions(e,t){for(const r of e){const e=this.getFieldValue(r.field,t);switch(r.operator){case"equals":if(e!==r.value)return!1;break;case"not_equals":if(e===r.value)return!1;break;case"contains":if(!String(e).includes(String(r.value)))return!1;break;case"greater_than":if(Number(e)<=Number(r.value))return!1;break;case"less_than":if(Number(e)>=Number(r.value))return!1}}return!0}getFieldValue(e,t){const r=e.split(".");let n=t;for(const e of r){if(null==n)return;n=n[e]}return n}getRecentAlerts(e=50){return this.recentAlerts.slice(0,e)}acknowledgeAlert(e){const t=this.recentAlerts.find(t=>t.id===e);return!!t&&(t.acknowledged=!0,!0)}getAlertsForObject(e){return this.recentAlerts.filter(t=>t.trackedObjectId===e)}setRules(e){this.rules=e,this.saveRules()}getRules(){return this.rules}upsertRule(e){const t=this.rules.findIndex(t=>t.id===e.id);t>=0?this.rules[t]=e:this.rules.push(e),this.saveRules()}deleteRule(e){const t=this.rules.findIndex(t=>t.id===e);return t>=0&&(this.rules.splice(t,1),this.saveRules(),!0)}setRuleEnabled(e,t){const r=this.rules.find(t=>t.id===e);return!!r&&(r.enabled=t,this.saveRules(),!0)}loadRules(){try{const e=this.storage.getItem("alertRules");this.rules=e?JSON.parse(e):(0,o.createDefaultRules)()}catch(e){this.console.error("Failed to load alert rules:",e),this.rules=(0,o.createDefaultRules)()}}saveRules(){try{this.storage.setItem("alertRules",JSON.stringify(this.rules))}catch(e){this.console.error("Failed to save alert rules:",e)}}clearCooldowns(){this.cooldowns.clear()}clearHistory(){this.recentAlerts=[]}}},4422(e){e.exports=global.process},4434(e){"use strict";e.exports=require("events")},4478(e,t,r){"use strict";const n=r(2203);if(n&&"disable"===process.env.READABLE_STREAM){const t=n.promises;e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get:()=>t}),e.exports.Stream=n.Stream}else{const t=r(5506),n=r(3095),i=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=i,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get:()=>n}),e.exports.Stream=t.Stream}e.exports.default=e.exports},4723(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MQTTJS_VERSION=t.nextTick=t.ErrorWithSubackPacket=t.ErrorWithReasonCode=void 0,t.applyMixin=function(e,t,r=!1){const n=[t];for(;;){const e=n[0],t=Object.getPrototypeOf(e);if(!t?.prototype)break;n.unshift(t)}for(const t of n)for(const n of Object.getOwnPropertyNames(t.prototype))(r||"constructor"!==n)&&Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)??Object.create(null))};class n extends Error{code;constructor(e,t){super(e),this.code=t,Object.setPrototypeOf(this,n.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}t.ErrorWithReasonCode=n;class i extends Error{packet;constructor(e,t){super(e),this.packet=t,Object.setPrototypeOf(this,i.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}t.ErrorWithSubackPacket=i,t.nextTick="function"==typeof process?.nextTick?process.nextTick:e=>{setTimeout(e,0)},t.MQTTJS_VERSION=r(2860).version},4756(e){"use strict";e.exports=require("tls")},4759(e){"use strict";const t=Symbol("kDone"),r=Symbol("kRun");e.exports=class{constructor(e){this[t]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[t])}}}},4829(e,t,r){"use strict";const n=r(4478).Duplex,i=r(2017),o=r(7813);function s(e){if(!(this instanceof s))return new s(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",function(e){e.on("error",t)}),this.on("unpipe",function(e){e.removeListener("error",t)}),e=null}o._init.call(this,e),n.call(this)}i(s,n),Object.assign(s.prototype,o.prototype),s.prototype._new=function(e){return new s(e)},s.prototype._write=function(e,t,r){this._appendBuffer(e),"function"==typeof r&&r()},s.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},s.prototype.end=function(e){n.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},s.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},s.prototype._isBufferList=function(e){return e instanceof s||e instanceof o||s.isBufferList(e)},s.isBufferList=o.isBufferList,e.exports=s,e.exports.BufferListStream=s,e.exports.BufferList=o},4959(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=[0,16,128,131,135,144,145,151,153];t.default=(e,t,n)=>{e.log("handlePublish: packet %o",t),n="undefined"!=typeof n?n:e.noop;let i=t.topic.toString();const o=t.payload,{qos:s}=t,{messageId:a}=t,{options:c}=e;if(5===e.options.protocolVersion){let r;if(t.properties&&(r=t.properties.topicAlias),"undefined"!=typeof r)if(0===i.length){if(!(r>0&&r<=65535))return e.log("handlePublish :: topic alias out of range. alias: %d",r),void e.emit("error",new Error("Received Topic Alias is out of range"));{const t=e.topicAliasRecv.getTopicByAlias(r);if(!t)return e.log("handlePublish :: unregistered topic alias. alias: %d",r),void e.emit("error",new Error("Received unregistered Topic Alias"));i=t,e.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,r)}}else{if(!e.topicAliasRecv.put(i,r))return e.log("handlePublish :: topic alias out of range. alias: %d",r),void e.emit("error",new Error("Received Topic Alias is out of range"));e.log("handlePublish :: registered topic: %s - alias: %d",i,r)}}switch(e.log("handlePublish: qos %d",s),s){case 2:c.customHandleAcks(i,o,t,(i,o)=>("number"==typeof i&&(o=i,i=null),i?e.emit("error",i):-1===r.indexOf(o)?e.emit("error",new Error("Wrong reason code for pubrec")):void(o?e._sendPacket({cmd:"pubrec",messageId:a,reasonCode:o},n):e.incomingStore.put(t,()=>{e._sendPacket({cmd:"pubrec",messageId:a},n)}))));break;case 1:c.customHandleAcks(i,o,t,(s,c)=>("number"==typeof s&&(c=s,s=null),s?e.emit("error",s):-1===r.indexOf(c)?e.emit("error",new Error("Wrong reason code for puback")):(c||e.emit("message",i,o,t),void e.handleMessage(t,t=>{if(t)return n&&n(t);e._sendPacket({cmd:"puback",messageId:a,reasonCode:c},n)}))));break;case 0:e.emit("message",i,o,t),e.handleMessage(t,n);break;default:e.log("handlePublish: unknown QoS. Doing nothing.")}}},4966(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LRUCache=void 0;const r="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,n=new Set,i="object"==typeof process&&process?process:{},o=(e,t,r,n)=>{"function"==typeof i.emitWarning?i.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let s=globalThis.AbortController,a=globalThis.AbortSignal;if("undefined"==typeof s){a=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},s=class{constructor(){t()}signal=new a;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==i.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,o("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const c=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),l=e=>c(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?u:null:null;class u extends Array{constructor(e){super(e),this.fill(0)}}class d{heap;length;static#e=!1;static create(e){const t=l(e);if(!t)return[];d.#e=!0;const r=new d(e,t);return d.#e=!1,r}constructor(e,t){if(!d.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class h{#t;#r;#n;#i;#o;#s;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#c;#l;#u;#d;#h;#p;#f;#g;#m;#b;#y;#_;#v;#S;#w;#k;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#v,sizes:e.#y,keyMap:e.#l,keyList:e.#u,valList:e.#d,next:e.#h,prev:e.#p,get head(){return e.#f},get tail(){return e.#g},free:e.#m,isBackgroundFetch:t=>e.#E(t),backgroundFetch:(t,r,n,i)=>e.#I(t,r,n,i),moveToTail:t=>e.#T(t),indexes:t=>e.#O(t),rindexes:t=>e.#C(t),isStale:t=>e.#A(t)}}get max(){return this.#t}get maxSize(){return this.#r}get calculatedSize(){return this.#c}get size(){return this.#a}get fetchMethod(){return this.#o}get memoMethod(){return this.#s}get dispose(){return this.#n}get disposeAfter(){return this.#i}constructor(e){const{max:t=0,ttl:r,ttlResolution:i=1,ttlAutopurge:s,updateAgeOnGet:a,updateAgeOnHas:u,allowStale:p,dispose:f,disposeAfter:g,noDisposeOnSet:m,noUpdateTTL:b,maxSize:y=0,maxEntrySize:_=0,sizeCalculation:v,fetchMethod:S,memoMethod:w,noDeleteOnFetchRejection:k,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:I,allowStaleOnFetchAbort:T,ignoreFetchAbort:O}=e;if(0!==t&&!c(t))throw new TypeError("max option must be a nonnegative integer");const C=t?l(t):Array;if(!C)throw new Error("invalid max value: "+t);if(this.#t=t,this.#r=y,this.maxEntrySize=_||this.#r,this.sizeCalculation=v,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==w&&"function"!=typeof w)throw new TypeError("memoMethod must be a function if defined");if(this.#s=w,void 0!==S&&"function"!=typeof S)throw new TypeError("fetchMethod must be a function if specified");if(this.#o=S,this.#w=!!S,this.#l=new Map,this.#u=new Array(t).fill(void 0),this.#d=new Array(t).fill(void 0),this.#h=new C(t),this.#p=new C(t),this.#f=0,this.#g=0,this.#m=d.create(t),this.#a=0,this.#c=0,"function"==typeof f&&(this.#n=f),"function"==typeof g?(this.#i=g,this.#b=[]):(this.#i=void 0,this.#b=void 0),this.#S=!!this.#n,this.#k=!!this.#i,this.noDisposeOnSet=!!m,this.noUpdateTTL=!!b,this.noDeleteOnFetchRejection=!!k,this.allowStaleOnFetchRejection=!!I,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!O,0!==this.maxEntrySize){if(0!==this.#r&&!c(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!c(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#x()}if(this.allowStale=!!p,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!u,this.ttlResolution=c(i)||0===i?i:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!c(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(0===this.#t&&0===this.ttl&&0===this.#r)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){const e="LRU_CACHE_UNBOUNDED";if((e=>!n.has(e))(e)){n.add(e);o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,h)}}}getRemainingTTL(e){return this.#l.has(e)?1/0:0}#P(){const e=new u(this.#t),t=new u(this.#t);this.#v=e,this.#_=t,this.#R=(n,i,o=r.now())=>{if(t[n]=0!==i?o:0,e[n]=i,0!==i&&this.ttlAutopurge){const e=setTimeout(()=>{this.#A(n)&&this.#M(this.#u[n],"expire")},i+1);e.unref&&e.unref()}},this.#B=n=>{t[n]=0!==e[n]?r.now():0},this.#N=(r,o)=>{if(e[o]){const s=e[o],a=t[o];if(!s||!a)return;r.ttl=s,r.start=a,r.now=n||i();const c=r.now-a;r.remainingTTL=s-c}};let n=0;const i=()=>{const e=r.now();if(this.ttlResolution>0){n=e;const t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=r=>{const o=this.#l.get(r);if(void 0===o)return 0;const s=e[o],a=t[o];if(!s||!a)return 1/0;return s-((n||i())-a)},this.#A=r=>{const o=t[r],s=e[r];return!!s&&!!o&&(n||i())-o>s}}#B=()=>{};#N=()=>{};#R=()=>{};#A=()=>!1;#x(){const e=new u(this.#t);this.#c=0,this.#y=e,this.#j=t=>{this.#c-=e[t],e[t]=0},this.#D=(e,t,r,n)=>{if(this.#E(t))return 0;if(!c(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!c(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#L=(t,r,n)=>{if(e[t]=r,this.#r){const r=this.#r-e[t];for(;this.#c>r;)this.#U(!0)}this.#c+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#c)}}#j=e=>{};#L=(e,t,r)=>{};#D=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#g;this.#F(t)&&(!e&&this.#A(t)||(yield t),t!==this.#f);)t=this.#p[t]}*#C({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#f;this.#F(t)&&(!e&&this.#A(t)||(yield t),t!==this.#g);)t=this.#h[t]}#F(e){return void 0!==e&&this.#l.get(this.#u[e])===e}*entries(){for(const e of this.#O())void 0===this.#d[e]||void 0===this.#u[e]||this.#E(this.#d[e])||(yield[this.#u[e],this.#d[e]])}*rentries(){for(const e of this.#C())void 0===this.#d[e]||void 0===this.#u[e]||this.#E(this.#d[e])||(yield[this.#u[e],this.#d[e]])}*keys(){for(const e of this.#O()){const t=this.#u[e];void 0===t||this.#E(this.#d[e])||(yield t)}}*rkeys(){for(const e of this.#C()){const t=this.#u[e];void 0===t||this.#E(this.#d[e])||(yield t)}}*values(){for(const e of this.#O()){void 0===this.#d[e]||this.#E(this.#d[e])||(yield this.#d[e])}}*rvalues(){for(const e of this.#C()){void 0===this.#d[e]||this.#E(this.#d[e])||(yield this.#d[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#O()){const n=this.#d[r],i=this.#E(n)?n.__staleWhileFetching:n;if(void 0!==i&&e(i,this.#u[r],this))return this.get(this.#u[r],t)}}forEach(e,t=this){for(const r of this.#O()){const n=this.#d[r],i=this.#E(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#u[r],this)}}rforEach(e,t=this){for(const r of this.#C()){const n=this.#d[r],i=this.#E(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#u[r],this)}}purgeStale(){let e=!1;for(const t of this.#C({allowStale:!0}))this.#A(t)&&(this.#M(this.#u[t],"expire"),e=!0);return e}info(e){const t=this.#l.get(e);if(void 0===t)return;const n=this.#d[t],i=this.#E(n)?n.__staleWhileFetching:n;if(void 0===i)return;const o={value:i};if(this.#v&&this.#_){const e=this.#v[t],n=this.#_[t];if(e&&n){const t=e-(r.now()-n);o.ttl=t,o.start=Date.now()}}return this.#y&&(o.size=this.#y[t]),o}dump(){const e=[];for(const t of this.#O({allowStale:!0})){const n=this.#u[t],i=this.#d[t],o=this.#E(i)?i.__staleWhileFetching:i;if(void 0===o||void 0===n)continue;const s={value:o};if(this.#v&&this.#_){s.ttl=this.#v[t];const e=r.now()-this.#_[t];s.start=Math.floor(Date.now()-e)}this.#y&&(s.size=this.#y[t]),e.unshift([n,s])}return e}load(e){this.clear();for(const[t,n]of e){if(n.start){const e=Date.now()-n.start;n.start=r.now()-e}this.set(t,n.value,n)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const l=this.#D(e,t,r.size||0,s);if(this.maxEntrySize&&l>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#M(e,"set"),this;let u=0===this.#a?void 0:this.#l.get(e);if(void 0===u)u=0===this.#a?this.#g:0!==this.#m.length?this.#m.pop():this.#a===this.#t?this.#U(!1):this.#a,this.#u[u]=e,this.#d[u]=t,this.#l.set(e,u),this.#h[this.#g]=u,this.#p[u]=this.#g,this.#g=u,this.#a++,this.#L(u,l,a),a&&(a.set="add"),c=!1;else{this.#T(u);const r=this.#d[u];if(t!==r){if(this.#w&&this.#E(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||o||(this.#S&&this.#n?.(t,e,"set"),this.#k&&this.#b?.push([t,e,"set"]))}else o||(this.#S&&this.#n?.(r,e,"set"),this.#k&&this.#b?.push([r,e,"set"]));if(this.#j(u),this.#L(u,l,a),this.#d[u]=t,a){a.set="replace";const e=r&&this.#E(r)?r.__staleWhileFetching:r;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update")}if(0===n||this.#v||this.#P(),this.#v&&(c||this.#R(u,n,i),a&&this.#N(a,u)),!o&&this.#k&&this.#b){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}return this}pop(){try{for(;this.#a;){const e=this.#d[this.#f];if(this.#U(!0),this.#E(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#k&&this.#b){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}}}#U(e){const t=this.#f,r=this.#u[t],n=this.#d[t];return this.#w&&this.#E(n)?n.__abortController.abort(new Error("evicted")):(this.#S||this.#k)&&(this.#S&&this.#n?.(n,r,"evict"),this.#k&&this.#b?.push([n,r,"evict"])),this.#j(t),e&&(this.#u[t]=void 0,this.#d[t]=void 0,this.#m.push(t)),1===this.#a?(this.#f=this.#g=0,this.#m.length=0):this.#f=this.#h[t],this.#l.delete(r),this.#a--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,i=this.#l.get(e);if(void 0!==i){const e=this.#d[i];if(this.#E(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#A(i))return r&&this.#B(i),n&&(n.has="hit",this.#N(n,i)),!0;n&&(n.has="stale",this.#N(n,i))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#l.get(e);if(void 0===n||!r&&this.#A(n))return;const i=this.#d[n];return this.#E(i)?i.__staleWhileFetching:i}#I(e,t,r,n){const i=void 0===t?void 0:this.#d[t];if(this.#E(i))return i;const o=new s,{signal:a}=r;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});const c={signal:o.signal,options:r,context:n},l=(n,i=!1)=>{const{aborted:s}=o.signal,a=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(s&&!i?(r.status.fetchAborted=!0,r.status.fetchError=o.signal.reason,a&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),s&&!a&&!i)return u(o.signal.reason);const l=d;return this.#d[t]===d&&(void 0===n?l.__staleWhileFetching?this.#d[t]=l.__staleWhileFetching:this.#M(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,c.options))),n},u=n=>{const{aborted:i}=o.signal,s=i&&r.allowStaleOnFetchAbort,a=s||r.allowStaleOnFetchRejection,c=a||r.noDeleteOnFetchRejection,l=d;if(this.#d[t]===d){!c||void 0===l.__staleWhileFetching?this.#M(e,"fetch"):s||(this.#d[t]=l.__staleWhileFetching)}if(a)return r.status&&void 0!==l.__staleWhileFetching&&(r.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw n};r.status&&(r.status.fetchDispatched=!0);const d=new Promise((t,n)=>{const s=this.#o?.(e,i,c);s&&s instanceof Promise&&s.then(e=>t(void 0===e?void 0:e),n),o.signal.addEventListener("abort",()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})}).then(l,e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e))),h=Object.assign(d,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,h,{...c.options,status:void 0}),t=this.#l.get(e)):this.#d[t]=h,h}#E(e){if(!this.#w)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof s}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:g=!1,status:m,signal:b}=t;if(!this.#w)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:m});const y={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:s,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:m,signal:b};let _=this.#l.get(e);if(void 0===_){m&&(m.fetch="miss");const t=this.#I(e,_,y,f);return t.__returned=t}{const t=this.#d[_];if(this.#E(t)){const e=r&&void 0!==t.__staleWhileFetching;return m&&(m.fetch="inflight",e&&(m.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#A(_);if(!g&&!i)return m&&(m.fetch="hit"),this.#T(_),n&&this.#B(_),m&&this.#N(m,_),t;const o=this.#I(e,_,y,f),s=void 0!==o.__staleWhileFetching&&r;return m&&(m.fetch=i?"stale":"refresh",s&&i&&(m.returnedStale=!0)),s?o.__staleWhileFetching:o.__returned=o}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#s;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:i,...o}=t,s=this.get(e,o);if(!i&&void 0!==s)return s;const a=r(e,s,{options:o,context:n});return this.set(e,a,o),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=t,s=this.#l.get(e);if(void 0!==s){const t=this.#d[s],a=this.#E(t);return o&&this.#N(o,s),this.#A(s)?(o&&(o.get="stale"),a?(o&&r&&void 0!==t.__staleWhileFetching&&(o.returnedStale=!0),r?t.__staleWhileFetching:void 0):(i||this.#M(e,"expire"),o&&r&&(o.returnedStale=!0),r?t:void 0)):(o&&(o.get="hit"),a?t.__staleWhileFetching:(this.#T(s),n&&this.#B(s),t))}o&&(o.get="miss")}#$(e,t){this.#p[t]=e,this.#h[e]=t}#T(e){e!==this.#g&&(e===this.#f?this.#f=this.#h[e]:this.#$(this.#p[e],this.#h[e]),this.#$(this.#g,e),this.#g=e)}delete(e){return this.#M(e,"delete")}#M(e,t){let r=!1;if(0!==this.#a){const n=this.#l.get(e);if(void 0!==n)if(r=!0,1===this.#a)this.#V(t);else{this.#j(n);const r=this.#d[n];if(this.#E(r)?r.__abortController.abort(new Error("deleted")):(this.#S||this.#k)&&(this.#S&&this.#n?.(r,e,t),this.#k&&this.#b?.push([r,e,t])),this.#l.delete(e),this.#u[n]=void 0,this.#d[n]=void 0,n===this.#g)this.#g=this.#p[n];else if(n===this.#f)this.#f=this.#h[n];else{const e=this.#p[n];this.#h[e]=this.#h[n];const t=this.#h[n];this.#p[t]=this.#p[n]}this.#a--,this.#m.push(n)}}if(this.#k&&this.#b?.length){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}return r}clear(){return this.#V("delete")}#V(e){for(const t of this.#C({allowStale:!0})){const r=this.#d[t];if(this.#E(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#u[t];this.#S&&this.#n?.(r,n,e),this.#k&&this.#b?.push([r,n,e])}}if(this.#l.clear(),this.#d.fill(void 0),this.#u.fill(void 0),this.#v&&this.#_&&(this.#v.fill(0),this.#_.fill(0)),this.#y&&this.#y.fill(0),this.#f=0,this.#g=0,this.#m.length=0,this.#c=0,this.#a=0,this.#k&&this.#b){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}}}t.LRUCache=h},4988(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=new WeakMap,n=new WeakMap;function i(e){const t=r.get(e);return console.assert(null!=t,"'this' is expected an Event object, but got",e),t}function o(e){null==e.passiveListener?e.event.cancelable&&(e.canceled=!0,"function"==typeof e.event.preventDefault&&e.event.preventDefault()):"undefined"!=typeof console&&"function"==typeof console.error&&console.error("Unable to preventDefault inside passive event listener invocation.",e.passiveListener)}function s(e,t){r.set(this,{eventTarget:e,event:t,eventPhase:2,currentTarget:e,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:t.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});const n=Object.keys(t);for(let e=0;e<n.length;++e){const t=n[e];t in this||Object.defineProperty(this,t,a(t))}}function a(e){return{get(){return i(this).event[e]},set(t){i(this).event[e]=t},configurable:!0,enumerable:!0}}function c(e){return{value(){const t=i(this).event;return t[e].apply(t,arguments)},configurable:!0,enumerable:!0}}function l(e){if(null==e||e===Object.prototype)return s;let t=n.get(e);return null==t&&(t=function(e,t){const r=Object.keys(t);if(0===r.length)return e;function n(t,r){e.call(this,t,r)}n.prototype=Object.create(e.prototype,{constructor:{value:n,configurable:!0,writable:!0}});for(let i=0;i<r.length;++i){const o=r[i];if(!(o in e.prototype)){const e="function"==typeof Object.getOwnPropertyDescriptor(t,o).value;Object.defineProperty(n.prototype,o,e?c(o):a(o))}}return n}(l(Object.getPrototypeOf(e)),e),n.set(e,t)),t}function u(e){return i(e).immediateStopped}function d(e,t){i(e).passiveListener=t}s.prototype={get type(){return i(this).event.type},get target(){return i(this).eventTarget},get currentTarget(){return i(this).currentTarget},composedPath(){const e=i(this).currentTarget;return null==e?[]:[e]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return i(this).eventPhase},stopPropagation(){const e=i(this);e.stopped=!0,"function"==typeof e.event.stopPropagation&&e.event.stopPropagation()},stopImmediatePropagation(){const e=i(this);e.stopped=!0,e.immediateStopped=!0,"function"==typeof e.event.stopImmediatePropagation&&e.event.stopImmediatePropagation()},get bubbles(){return Boolean(i(this).event.bubbles)},get cancelable(){return Boolean(i(this).event.cancelable)},preventDefault(){o(i(this))},get defaultPrevented(){return i(this).canceled},get composed(){return Boolean(i(this).event.composed)},get timeStamp(){return i(this).timeStamp},get srcElement(){return i(this).eventTarget},get cancelBubble(){return i(this).stopped},set cancelBubble(e){if(!e)return;const t=i(this);t.stopped=!0,"boolean"==typeof t.event.cancelBubble&&(t.event.cancelBubble=!0)},get returnValue(){return!i(this).canceled},set returnValue(e){e||o(i(this))},initEvent(){}},Object.defineProperty(s.prototype,"constructor",{value:s,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.Event&&(Object.setPrototypeOf(s.prototype,window.Event.prototype),n.set(window.Event.prototype,s));const h=new WeakMap;function p(e){return null!==e&&"object"==typeof e}function f(e){const t=h.get(e);if(null==t)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return t}function g(e,t){Object.defineProperty(e,`on${t}`,function(e){return{get(){let t=f(this).get(e);for(;null!=t;){if(3===t.listenerType)return t.listener;t=t.next}return null},set(t){"function"==typeof t||p(t)||(t=null);const r=f(this);let n=null,i=r.get(e);for(;null!=i;)3===i.listenerType?null!==n?n.next=i.next:null!==i.next?r.set(e,i.next):r.delete(e):n=i,i=i.next;if(null!==t){const i={listener:t,listenerType:3,passive:!1,once:!1,next:null};null===n?r.set(e,i):n.next=i}},configurable:!0,enumerable:!0}}(t))}function m(e){function t(){b.call(this)}t.prototype=Object.create(b.prototype,{constructor:{value:t,configurable:!0,writable:!0}});for(let r=0;r<e.length;++r)g(t.prototype,e[r]);return t}function b(){if(!(this instanceof b)){if(1===arguments.length&&Array.isArray(arguments[0]))return m(arguments[0]);if(arguments.length>0){const e=new Array(arguments.length);for(let t=0;t<arguments.length;++t)e[t]=arguments[t];return m(e)}throw new TypeError("Cannot call a class as a function")}h.set(this,new Map)}b.prototype={addEventListener(e,t,r){if(null==t)return;if("function"!=typeof t&&!p(t))throw new TypeError("'listener' should be a function or an object.");const n=f(this),i=p(r),o=(i?Boolean(r.capture):Boolean(r))?1:2,s={listener:t,listenerType:o,passive:i&&Boolean(r.passive),once:i&&Boolean(r.once),next:null};let a=n.get(e);if(void 0===a)return void n.set(e,s);let c=null;for(;null!=a;){if(a.listener===t&&a.listenerType===o)return;c=a,a=a.next}c.next=s},removeEventListener(e,t,r){if(null==t)return;const n=f(this),i=(p(r)?Boolean(r.capture):Boolean(r))?1:2;let o=null,s=n.get(e);for(;null!=s;){if(s.listener===t&&s.listenerType===i)return void(null!==o?o.next=s.next:null!==s.next?n.set(e,s.next):n.delete(e));o=s,s=s.next}},dispatchEvent(e){if(null==e||"string"!=typeof e.type)throw new TypeError('"event.type" should be a string.');const t=f(this),r=e.type;let n=t.get(r);if(null==n)return!0;const o=function(e,t){return new(l(Object.getPrototypeOf(t)))(e,t)}(this,e);let s=null;for(;null!=n;){if(n.once?null!==s?s.next=n.next:null!==n.next?t.set(r,n.next):t.delete(r):s=n,d(o,n.passive?n.listener:null),"function"==typeof n.listener)try{n.listener.call(this,o)}catch(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e)}else 3!==n.listenerType&&"function"==typeof n.listener.handleEvent&&n.listener.handleEvent(o);if(u(o))break;n=n.next}return d(o,null),function(e,t){i(e).eventPhase=t}(o,0),function(e,t){i(e).currentTarget=t}(o,null),!o.defaultPrevented}},Object.defineProperty(b.prototype,"constructor",{value:b,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.EventTarget&&Object.setPrototypeOf(b.prototype,window.EventTarget.prototype),t.defineEventAttribute=g,t.EventTarget=b,t.default=b,e.exports=b,e.exports.EventTarget=e.exports.default=b,e.exports.defineEventAttribute=g},4997(e,t){"use strict";function r(e,t){const r=t.objectLabel?`${t.objectClass} (${t.objectLabel})`:t.objectClass||"Object";switch(e){case"property_entry":return`${r} entered property via ${t.cameraName||"unknown camera"}`;case"property_exit":return`${r} exited property via ${t.cameraName||"unknown camera"}`;case"unusual_path":return`${r} took unusual path: ${t.actualPath||"unknown"}`;case"dwell_time":return`${r} has been present for ${Math.round((t.dwellTime||0)/6e4)} minutes in ${t.zoneName||t.cameraName||"area"}`;case"restricted_zone":return`${r} entered restricted zone: ${t.zoneName}`;case"lost_tracking":return`Lost tracking of ${r} near ${t.cameraName||"unknown location"}`;case"reappearance":return`${r} reappeared on ${t.cameraName}`;case"zone_entry":return`${r} entered ${t.zoneName}`;case"zone_exit":return`${r} exited ${t.zoneName}`;default:return`Tracking event: ${e}`}}Object.defineProperty(t,"__esModule",{value:!0}),t.createDefaultRules=function(){return[{id:"property-entry",name:"Property Entry",enabled:!0,type:"property_entry",conditions:[],severity:"info",notifiers:[],cooldown:3e5},{id:"property-exit",name:"Property Exit",enabled:!0,type:"property_exit",conditions:[],severity:"info",notifiers:[],cooldown:3e5},{id:"unusual-path",name:"Unusual Path Detected",enabled:!0,type:"unusual_path",conditions:[],severity:"warning",notifiers:[],cooldown:6e5},{id:"dwell-time",name:"Extended Dwell Time",enabled:!0,type:"dwell_time",conditions:[{field:"totalDwellTime",operator:"greater_than",value:3e5}],severity:"warning",notifiers:[],cooldown:6e5},{id:"restricted-zone",name:"Restricted Zone Entry",enabled:!0,type:"restricted_zone",conditions:[],severity:"critical",notifiers:[],cooldown:0},{id:"lost-tracking",name:"Lost Object Tracking",enabled:!1,type:"lost_tracking",conditions:[],severity:"info",notifiers:[],cooldown:3e5}]},t.generateAlertMessage=r,t.createAlert=function(e,t,n,i="info",o){return{id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,type:e,severity:i,timestamp:Date.now(),trackedObjectId:t,message:r(e,n),details:n,acknowledged:!1,ruleId:o}}},5228(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(4723),i=r(1021);t.default=(e,t)=>{const{options:r}=e,o=r.protocolVersion,s=5===o?t.reasonCode:t.returnCode;if(5!==o){const t=new n.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${o}`,s);return void e.emit("error",t)}e.handleAuth(t,(t,r)=>{if(t)e.emit("error",t);else if(24===s)e.reconnecting=!1,e._sendPacket(r);else{const t=new n.ErrorWithReasonCode(`Connection refused: ${i.ReasonCodes[s]}`,s);e.emit("error",t)}})}},5291(e,t,r){"use strict";const{MathFloor:n,NumberIsInteger:i}=r(4134),{validateInteger:o}=r(277),{ERR_INVALID_ARG_VALUE:s}=r(6371).codes;let a=16384,c=16;function l(e){return e?c:a}e.exports={getHighWaterMark:function(e,t,r,o){const a=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,o,r);if(null!=a){if(!i(a)||a<0){throw new s(o?`options.${r}`:"options.highWaterMark",a)}return n(a)}return l(e.objectMode)},getDefaultHighWaterMark:l,setDefaultHighWaterMark:function(e,t){o(t,"value",0),e?c=t:a=t}}},5389(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TrackingState=void 0;const n=r(441);t.TrackingState=class{objects=new Map;objectsByCamera=new Map;changeCallbacks=[];storage;console;constructor(e,t){this.storage=e,this.console=t,this.loadPersistedState()}createObject(e,t,r){const i=(0,n.createTrackedObject)(e,t,r);return this.upsertObject(i),i}upsertObject(e){const t=this.objects.get(e.globalId);if(t)for(const r of t.activeOnCameras)this.objectsByCamera.get(r)?.delete(e.globalId);for(const t of e.activeOnCameras)this.objectsByCamera.has(t)||this.objectsByCamera.set(t,new Set),this.objectsByCamera.get(t).add(e.globalId);this.objects.set(e.globalId,e),this.notifyChange(),this.persistState()}addSighting(e,t){const r=this.objects.get(e);return!!r&&((0,n.addSighting)(r,t),this.objectsByCamera.has(t.cameraId)||this.objectsByCamera.set(t.cameraId,new Set),this.objectsByCamera.get(t.cameraId).add(e),this.notifyChange(),this.persistState(),!0)}addJourney(e,t){const r=this.objects.get(e);return!!r&&((0,n.addJourneySegment)(r,t),this.objectsByCamera.get(t.fromCameraId)?.delete(e),this.objectsByCamera.has(t.toCameraId)||this.objectsByCamera.set(t.toCameraId,new Set),this.objectsByCamera.get(t.toCameraId).add(e),this.notifyChange(),this.persistState(),!0)}getObject(e){return this.objects.get(e)}getActiveObjects(){return Array.from(this.objects.values()).filter(e=>"active"===e.state||"pending"===e.state)}getObjectsOnCamera(e){const t=this.objectsByCamera.get(e)||new Set;return Array.from(t).map(e=>this.objects.get(e)).filter(e=>!!e&&"active"===e.state)}getAllObjects(){return Array.from(this.objects.values())}getActiveCount(){return this.getActiveObjects().length}getJourney(e){return this.objects.get(e)?.journey}markExited(e,t,r){const n=this.objects.get(e);if(n){n.state="exited",n.hasExited=!0,n.exitCamera=t,n.exitCameraName=r,n.activeOnCameras=[];for(const[t,r]of this.objectsByCamera.entries())r.delete(e);this.notifyChange(),this.persistState()}}markLost(e){const t=this.objects.get(e);if(t){t.state="lost",t.activeOnCameras=[];for(const[t,r]of this.objectsByCamera.entries())r.delete(e);this.notifyChange(),this.persistState()}}markPending(e){const t=this.objects.get(e);t&&"active"===t.state&&(t.state="pending",this.notifyChange())}reactivate(e){const t=this.objects.get(e);t&&"pending"===t.state&&(t.state="active",this.notifyChange())}onStateChange(e){this.changeCallbacks.push(e)}offStateChange(e){const t=this.changeCallbacks.indexOf(e);-1!==t&&this.changeCallbacks.splice(t,1)}notifyChange(){const e=this.getAllObjects();for(const t of this.changeCallbacks)try{t(e)}catch(e){this.console.error("State change callback error:",e)}}persistState(){try{const e=Date.now(),t=Array.from(this.objects.values()).filter(t=>"active"===t.state||"pending"===t.state||e-t.lastSeen<36e5);this.storage.setItem("tracked-objects",JSON.stringify(t))}catch(e){this.console.error("Failed to persist tracking state:",e)}}loadPersistedState(){try{const e=this.storage.getItem("tracked-objects");if(e){const t=JSON.parse(e),r=Date.now();for(const e of t){"active"===e.state&&r-e.lastSeen>3e5&&(e.state="lost",e.activeOnCameras=[]),this.objects.set(e.globalId,e);for(const t of e.activeOnCameras)this.objectsByCamera.has(t)||this.objectsByCamera.set(t,new Set),this.objectsByCamera.get(t).add(e.globalId)}this.console.log(`Loaded ${t.length} persisted tracked objects`)}}catch(e){this.console.error("Failed to load persisted tracking state:",e)}}cleanup(e=864e5){const t=Date.now();let r=0;for(const[n,i]of this.objects.entries())t-i.lastSeen>e&&"active"!==i.state&&(this.objects.delete(n),r++);r>0&&(this.console.log(`Cleaned up ${r} old tracked objects`),this.persistState())}generateId(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}}},5399(e,t,r){const n=e.exports,{Buffer:i}=r(181);n.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},n.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},n.requiredHeaderFlagsErrors={};for(const e in n.requiredHeaderFlags){const t=n.requiredHeaderFlags[e];n.requiredHeaderFlagsErrors[e]="Invalid header flag bits, must be 0x"+t.toString(16)+" for "+n.types[e]+" packet"}n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=i.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=i.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=i.from([n.codes.connect<<n.CMD_SHIFT]),n.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function o(e){return[0,1,2].map(t=>[0,1].map(r=>[0,1].map(o=>{const s=i.alloc(1);return s.writeUInt8(n.codes[e]<<n.CMD_SHIFT|(r?n.DUP_MASK:0)|t<<n.QOS_SHIFT|o,0,!0),s})))}n.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},n.PUBLISH_HEADER=o("publish"),n.SUBSCRIBE_HEADER=o("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=o("unsubscribe"),n.ACKS={unsuback:o("unsuback"),puback:o("puback"),pubcomp:o("pubcomp"),pubrel:o("pubrel"),pubrec:o("pubrec")},n.SUBACK_HEADER=i.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=i.from([3]),n.VERSION4=i.from([4]),n.VERSION5=i.from([5]),n.VERSION131=i.from([131]),n.VERSION132=i.from([132]),n.QOS=[0,1,2].map(e=>i.from([e])),n.EMPTY={pingreq:i.from([n.codes.pingreq<<4,0]),pingresp:i.from([n.codes.pingresp<<4,0]),disconnect:i.from([n.codes.disconnect<<4,0])},n.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},n.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},n.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},n.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},n.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},n.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}},5438(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SOCKS5_NO_ACCEPTABLE_AUTH=t.SOCKS5_CUSTOM_AUTH_END=t.SOCKS5_CUSTOM_AUTH_START=t.SOCKS_INCOMING_PACKET_SIZES=t.SocksClientState=t.Socks5Response=t.Socks5HostType=t.Socks5Auth=t.Socks4Response=t.SocksCommand=t.ERRORS=t.DEFAULT_TIMEOUT=void 0;t.DEFAULT_TIMEOUT=3e4;t.ERRORS={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};var r,n,i;t.SOCKS_INCOMING_PACKET_SIZES={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:e=>e+7,Socks4Response:8},function(e){e[e.connect=1]="connect",e[e.bind=2]="bind",e[e.associate=3]="associate"}(r||(t.SocksCommand=r={})),function(e){e[e.Granted=90]="Granted",e[e.Failed=91]="Failed",e[e.Rejected=92]="Rejected",e[e.RejectedIdent=93]="RejectedIdent"}(n||(t.Socks4Response=n={})),function(e){e[e.NoAuth=0]="NoAuth",e[e.GSSApi=1]="GSSApi",e[e.UserPass=2]="UserPass"}(i||(t.Socks5Auth=i={}));t.SOCKS5_CUSTOM_AUTH_START=128;t.SOCKS5_CUSTOM_AUTH_END=254;var o,s,a;t.SOCKS5_NO_ACCEPTABLE_AUTH=255,function(e){e[e.Granted=0]="Granted",e[e.Failure=1]="Failure",e[e.NotAllowed=2]="NotAllowed",e[e.NetworkUnreachable=3]="NetworkUnreachable",e[e.HostUnreachable=4]="HostUnreachable",e[e.ConnectionRefused=5]="ConnectionRefused",e[e.TTLExpired=6]="TTLExpired",e[e.CommandNotSupported=7]="CommandNotSupported",e[e.AddressNotSupported=8]="AddressNotSupported"}(o||(t.Socks5Response=o={})),function(e){e[e.IPv4=1]="IPv4",e[e.Hostname=3]="Hostname",e[e.IPv6=4]="IPv6"}(s||(t.Socks5HostType=s={})),function(e){e[e.Created=0]="Created",e[e.Connecting=1]="Connecting",e[e.Connected=2]="Connected",e[e.SentInitialHandshake=3]="SentInitialHandshake",e[e.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",e[e.SentAuthentication=5]="SentAuthentication",e[e.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",e[e.SentFinalHandshake=7]="SentFinalHandshake",e[e.ReceivedFinalResponse=8]="ReceivedFinalResponse",e[e.BoundWaitingForConnection=9]="BoundWaitingForConnection",e[e.Established=10]="Established",e[e.Disconnected=11]="Disconnected",e[e.Error=99]="Error"}(a||(t.SocksClientState=a={}))},5471(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalTrackerSensor=void 0;const n=r(7562),i=r(441);class o extends n.ScryptedDeviceBase{trackingState;plugin;constructor(e,t,r){super(t),this.plugin=e,this.trackingState=r,r.onStateChange(()=>this.updateOccupancy()),this.updateOccupancy()}updateOccupancy(){const e=this.trackingState.getActiveCount();this.occupied=e>0}async getSettings(){const e=this.trackingState.getActiveObjects(),t=this.trackingState.getAllObjects(),r=[];if(r.push({key:"activeCount",title:"Currently Active",type:"string",readonly:!0,value:`${e.length} object${1!==e.length?"s":""}`,group:"Status"}),r.push({key:"totalTracked",title:"Total Tracked (24h)",type:"string",readonly:!0,value:`${t.length} object${1!==t.length?"s":""}`,group:"Status"}),e.length>0){r.push({key:"activeObjectsHeader",title:"Active Objects",type:"html",value:'<h4 style="margin: 0;">Currently Tracked</h4>',group:"Active Objects"});for(const t of e.slice(0,10)){const e=(0,i.calculateDwellTime)(t),n=Math.round(e/6e4);r.push({key:`active-${t.globalId}`,title:`${t.className}${t.label?` (${t.label})`:""}`,type:"string",readonly:!0,value:`Cameras: ${t.activeOnCameras.join(", ")} | Time: ${n}m`,group:"Active Objects"})}e.length>10&&r.push({key:"moreActive",title:"More",type:"string",readonly:!0,value:`...and ${e.length-10} more`,group:"Active Objects"})}const n=t.filter(e=>"exited"===e.state).sort((e,t)=>t.lastSeen-e.lastSeen).slice(0,5);if(n.length>0){r.push({key:"recentExitsHeader",title:"Recent Exits",type:"html",value:'<h4 style="margin: 0;">Recently Exited</h4>',group:"Recent Activity"});for(const e of n){const t=new Date(e.lastSeen).toLocaleTimeString(),n=(0,i.getJourneySummary)(e);r.push({key:`exit-${e.globalId}`,title:`${e.className} at ${t}`,type:"string",readonly:!0,value:n||"No journey recorded",group:"Recent Activity"})}}return r}async putSetting(e,t){}async getReadmeMarkdown(){const e=this.trackingState.getActiveObjects(),t=this.trackingState.getAllObjects(),r=e.filter(e=>"person"===e.className).length,n=e.filter(e=>["car","vehicle","truck"].includes(e.className)).length,i=e.filter(e=>"animal"===e.className).length;let o="";return r>0&&(o+=`- People: ${r}\n`),n>0&&(o+=`- Vehicles: ${n}\n`),i>0&&(o+=`- Animals: ${i}\n`),`\n# Global Object Tracker\n\nThis sensor tracks the presence of objects across all connected cameras in your property.\n\n## Current Status\n\n**Occupied**: ${this.occupied?"Yes":"No"}\n\n**Active Objects**: ${e.length}\n${o||"- None currently"}\n\n**Total Tracked (24h)**: ${t.length}\n\n## How It Works\n\nThe Global Tracker combines detection events from all configured cameras to maintain a unified view of objects on your property. When an object moves from one camera's view to another, the system correlates these sightings to track the object's journey.\n\n## States\n\n- **Active**: Object is currently visible on camera\n- **Pending**: Object left camera view, waiting for correlation\n- **Exited**: Object left the property\n- **Lost**: Object disappeared without exiting (timeout)\n\n## Integration\n\nThis sensor can be used in automations:\n- Trigger actions when property becomes occupied/unoccupied\n- Create presence-based automations\n- Monitor overall property activity\n`}}t.GlobalTrackerSensor=o},5506(e,t,r){"use strict";const{Buffer:n}=r(181),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(4134),{promisify:{custom:a}}=r(7760),{streamReturningOperators:c,promiseReturningOperators:l}=r(823),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(6371),d=r(7830),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:p}=r(5291),{pipeline:f}=r(7758),{destroyer:g}=r(5896),m=r(6238),b=r(3095),y=r(6115),_=e.exports=r(4259).Stream;_.isDestroyed=y.isDestroyed,_.isDisturbed=y.isDisturbed,_.isErrored=y.isErrored,_.isReadable=y.isReadable,_.isWritable=y.isWritable,_.Readable=r(7576);for(const S of o(c)){const w=c[S];function k(...e){if(new.target)throw u();return _.Readable.from(s(w,this,e))}i(k,"name",{__proto__:null,value:w.name}),i(k,"length",{__proto__:null,value:w.length}),i(_.Readable.prototype,S,{__proto__:null,value:k,enumerable:!1,configurable:!0,writable:!0})}for(const E of o(l)){const I=l[E];function T(...e){if(new.target)throw u();return s(I,this,e)}i(T,"name",{__proto__:null,value:I.name}),i(T,"length",{__proto__:null,value:I.length}),i(_.Readable.prototype,E,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}_.Writable=r(8584),_.Duplex=r(3370),_.Transform=r(7382),_.PassThrough=r(6524),_.pipeline=f;const{addAbortSignal:v}=r(4147);_.addAbortSignal=v,_.finished=m,_.destroy=g,_.compose=d,_.setDefaultHighWaterMark=h,_.getDefaultHighWaterMark=p,i(_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get:()=>b}),i(f,a,{__proto__:null,enumerable:!0,get:()=>b.pipeline}),i(m,a,{__proto__:null,enumerable:!0,get:()=>b.finished}),_.Stream=_,_._isUint8Array=function(e){return e instanceof Uint8Array},_._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},5670(e,t,r){"use strict";const n=r(181),i=r(4478),o=r(2635);let s,a,c;t.A=(e,t)=>{if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";!function(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}(t);const l=function(e,t){const r="wxs"===e.protocol?"wss":"ws";let n=`${r}://${e.hostname}${e.path}`;return e.port&&80!==e.port&&443!==e.port&&(n=`${r}://${e.hostname}:${e.port}${e.path}`),"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}(t,e);s=wx.connectSocket({url:l,protocols:[r]}),a=function(){const e=new i.Transform;return e._write=(e,t,r)=>{s.send({data:e.buffer,success(){r()},fail(e){r(new Error(e))}})},e._flush=e=>{s.close({success(){e()}})},e}(),c=new o.BufferedDuplex(t,a,s),c._destroy=(e,t)=>{s.close({success(){t&&t(e)}})};const u=c.destroy;return c.destroy=(e,t)=>(c.destroy=u,setTimeout(()=>{s.close({fail(){c._destroy(e,t)}})},0),c),s.onOpen(()=>{c.socketReady()}),s.onMessage(e=>{let{data:t}=e;t=t instanceof ArrayBuffer?n.Buffer.from(t):n.Buffer.from(t,"utf8"),a.push(t)}),s.onClose(()=>{c.emit("close"),c.end(),c.destroy()}),s.onError(e=>{const t=new Error(e.errMsg);c.destroy(t)}),c}},5692(e){"use strict";e.exports=require("https")},5753(e,t,r){"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?e.exports=r(7833):e.exports=r(6033)},5861(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(7631),t)},5880(e,t,r){"use strict";const{isUtf8:n}=r(181),{hasBlob:i}=r(2614);function o(e){const t=e.length;let r=0;for(;r<t;)if(128&e[r])if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}else r++;return!0}if(e.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:o,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},n)e.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const t=r(Object(function(){var e=new Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e}()));e.exports.isValidUTF8=function(e){return e.length<32?o(e):t(e)}}catch(e){}},5884(e){"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return-1!==n&&(-1===i||n<i)}},5896(e,t,r){"use strict";const n=r(4422),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(6371),{Symbol:a}=r(4134),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(6115),h=a("kDestroy"),p=a("kConstruct");function f(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;f(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(m,e,t):n.nextTick(b,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function m(e,t){y(e,t),b(e)}function b(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function y(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function _(e,t,r){const i=e._readableState,o=e._writableState;if(null!=o&&o.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=o&&o.autoDestroy?e.destroy(t):t&&(t.stack,o&&!o.errored&&(o.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(y,e,t):y(e,t))}function v(e){let t=!1;function r(r){if(t)return void _(e,null!=r?r:new o);t=!0;const i=e._readableState,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?_(e,r,!0):n.nextTick(S,e)}try{e._construct(e=>{n.nextTick(r,e)})}catch(e){n.nextTick(r,e)}}function S(e){e.emit(p)}function w(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function k(e){e.emit("close")}function E(e,t){e.emit("error",t),n.nextTick(k,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(p,t),e.listenerCount(p)>1||n.nextTick(v,e)},destroyer:function(e,t){e&&!l(e)&&(t||u(e)||(t=new s),d(e)?(e.socket=null,e.destroy(t)):w(e)?e.abort():w(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(E,e,t):n.nextTick(k,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,o=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(f(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),o.constructed?g(this,e,t):this.once(h,function(r){g(this,i(r,e),t)}),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:_}},5926(e,t,r){"use strict";const{tokenChars:n}=r(5880);function i(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}e.exports={format:function(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>[t].concat(Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){const t=Object.create(null);let r,o,s=Object.create(null),a=!1,c=!1,l=!1,u=-1,d=-1,h=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),void 0===r)if(-1===h&&1===n[d])-1===u&&(u=p);else if(0===p||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${p}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);const n=e.slice(u,h);44===d?(i(t,n,s),s=Object.create(null)):r=n,u=h=-1}}else-1===h&&-1!==u&&(h=p);else if(void 0===o)if(-1===h&&1===n[d])-1===u&&(u=p);else if(32===d||9===d)-1===h&&-1!==u&&(h=p);else if(59===d||44===d){if(-1===u)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p),i(s,e.slice(u,h),!0),44===d&&(i(t,r,s),s=Object.create(null),r=void 0),u=h=-1}else{if(61!==d||-1===u||-1!==h)throw new SyntaxError(`Unexpected character at index ${p}`);o=e.slice(u,p),u=h=-1}else if(c){if(1!==n[d])throw new SyntaxError(`Unexpected character at index ${p}`);-1===u?u=p:a||(a=!0),c=!1}else if(l)if(1===n[d])-1===u&&(u=p);else if(34===d&&-1!==u)l=!1,h=p;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${p}`);c=!0}else if(34===d&&61===e.charCodeAt(p-1))l=!0;else if(-1===h&&1===n[d])-1===u&&(u=p);else if(-1===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${p}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);let n=e.slice(u,h);a&&(n=n.replace(/\\/g,""),a=!1),i(s,o,n),44===d&&(i(t,r,s),s=Object.create(null),r=void 0),o=void 0,u=h=-1}}else-1===h&&(h=p);if(-1===u||l||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===h&&(h=p);const f=e.slice(u,h);return void 0===r?i(t,f,s):(void 0===o?i(s,f,!0):i(s,o,a?f.replace(/\\/g,""):f),i(t,r,s)),t}}},6033(e,t,r){const n=r(2018),i=r(9023);t.init=function(e){e.inspectOpts={};const r=Object.keys(t.inspectOpts);for(let n=0;n<r.length;n++)e.inspectOpts[r[n]]=t.inspectOpts[r[n]]},t.log=function(...e){return process.stderr.write(i.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(r){const{namespace:n,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),o=` ${i};1m${n} [0m`;r[0]=o+r[0].split("\n").join("\n"+o),r.push(i+"m+"+e.exports.humanize(this.diff)+"[0m")}else r[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+n+" "+r[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=r(7687);e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[r]=n,e},{}),e.exports=r(736)(t);const{formatters:o}=e.exports;o.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},o.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}},6115(e,t,r){"use strict";const{SymbolAsyncIterator:n,SymbolIterator:i,SymbolFor:o}=r(4134),s=o("nodejs.stream.destroyed"),a=o("nodejs.stream.errored"),c=o("nodejs.stream.readable"),l=o("nodejs.stream.writable"),u=o("nodejs.stream.disturbed"),d=o("nodejs.webstream.isClosedPromise"),h=o("nodejs.webstream.controllerErrorFunction");function p(e,t=!1){var r;return!(!e||"function"!=typeof e.pipe||"function"!=typeof e.on||t&&("function"!=typeof e.pause||"function"!=typeof e.resume)||e._writableState&&!1===(null===(r=e._readableState)||void 0===r?void 0:r.readable)||e._writableState&&!e._readableState)}function f(e){var t;return!(!e||"function"!=typeof e.write||"function"!=typeof e.on||e._readableState&&!1===(null===(t=e._writableState)||void 0===t?void 0:t.writable))}function g(e){return e&&(e._readableState||e._writableState||"function"==typeof e.write&&"function"==typeof e.on||"function"==typeof e.pipe&&"function"==typeof e.on)}function m(e){return!(!e||g(e)||"function"!=typeof e.pipeThrough||"function"!=typeof e.getReader||"function"!=typeof e.cancel)}function b(e){return!(!e||g(e)||"function"!=typeof e.getWriter||"function"!=typeof e.abort)}function y(e){return!(!e||g(e)||"object"!=typeof e.readable||"object"!=typeof e.writable)}function _(e){if(!g(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!!(e.destroyed||e[s]||null!=n&&n.destroyed)}function v(e){if(!f(e))return null;if(!0===e.writableEnded)return!0;const t=e._writableState;return(null==t||!t.errored)&&("boolean"!=typeof(null==t?void 0:t.ended)?null:t.ended)}function S(e,t){if(!p(e))return null;const r=e._readableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.endEmitted)?null:!!(r.endEmitted||!1===t&&!0===r.ended&&0===r.length))}function w(e){return e&&null!=e[c]?e[c]:"boolean"!=typeof(null==e?void 0:e.readable)?null:!_(e)&&(p(e)&&e.readable&&!S(e))}function k(e){return e&&null!=e[l]?e[l]:"boolean"!=typeof(null==e?void 0:e.writable)?null:!_(e)&&(f(e)&&e.writable&&!v(e))}function E(e){return"boolean"==typeof e._closed&&"boolean"==typeof e._defaultKeepAlive&&"boolean"==typeof e._removedConnection&&"boolean"==typeof e._removedContLen}function I(e){return"boolean"==typeof e._sent100&&E(e)}e.exports={isDestroyed:_,kIsDestroyed:s,isDisturbed:function(e){var t;return!(!e||!(null!==(t=e[u])&&void 0!==t?t:e.readableDidRead||e.readableAborted))},kIsDisturbed:u,isErrored:function(e){var t,r,n,i,o,s,c,l,u,d;return!(!e||!(null!==(t=null!==(r=null!==(n=null!==(i=null!==(o=null!==(s=e[a])&&void 0!==s?s:e.readableErrored)&&void 0!==o?o:e.writableErrored)&&void 0!==i?i:null===(c=e._readableState)||void 0===c?void 0:c.errorEmitted)&&void 0!==n?n:null===(l=e._writableState)||void 0===l?void 0:l.errorEmitted)&&void 0!==r?r:null===(u=e._readableState)||void 0===u?void 0:u.errored)&&void 0!==t?t:null===(d=e._writableState)||void 0===d?void 0:d.errored))},kIsErrored:a,isReadable:w,kIsReadable:c,kIsClosedPromise:d,kControllerErrorFunction:h,kIsWritable:l,isClosed:function(e){if(!g(e))return null;if("boolean"==typeof e.closed)return e.closed;const t=e._writableState,r=e._readableState;return"boolean"==typeof(null==t?void 0:t.closed)||"boolean"==typeof(null==r?void 0:r.closed)?(null==t?void 0:t.closed)||(null==r?void 0:r.closed):"boolean"==typeof e._closed&&E(e)?e._closed:null},isDuplexNodeStream:function(e){return!(!e||"function"!=typeof e.pipe||!e._readableState||"function"!=typeof e.on||"function"!=typeof e.write)},isFinished:function(e,t){return g(e)?!!_(e)||(!1===(null==t?void 0:t.readable)||!w(e))&&(!1===(null==t?void 0:t.writable)||!k(e)):null},isIterable:function(e,t){return null!=e&&(!0===t?"function"==typeof e[n]:!1===t?"function"==typeof e[i]:"function"==typeof e[n]||"function"==typeof e[i])},isReadableNodeStream:p,isReadableStream:m,isReadableEnded:function(e){if(!p(e))return null;if(!0===e.readableEnded)return!0;const t=e._readableState;return!(!t||t.errored)&&("boolean"!=typeof(null==t?void 0:t.ended)?null:t.ended)},isReadableFinished:S,isReadableErrored:function(e){var t,r;return g(e)?e.readableErrored?e.readableErrored:null!==(t=null===(r=e._readableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isNodeStream:g,isWebStream:function(e){return m(e)||b(e)||y(e)},isWritable:k,isWritableNodeStream:f,isWritableStream:b,isWritableEnded:v,isWritableFinished:function(e,t){if(!f(e))return null;if(!0===e.writableFinished)return!0;const r=e._writableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.finished)?null:!!(r.finished||!1===t&&!0===r.ended&&0===r.length))},isWritableErrored:function(e){var t,r;return g(e)?e.writableErrored?e.writableErrored:null!==(t=null===(r=e._writableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isServerRequest:function(e){var t;return"boolean"==typeof e._consuming&&"boolean"==typeof e._dumped&&void 0===(null===(t=e.req)||void 0===t?void 0:t.upgradeOrConnect)},isServerResponse:I,willEmitClose:function(e){if(!g(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!n&&I(e)||!!(n&&n.autoDestroy&&n.emitClose&&!1===n.closed)},isTransformStream:y}},6117(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.StorageSettings=void 0;const a=s(r(7562)),{systemManager:c}=a.default;t.StorageSettings=class{constructor(e,t){this.device=e,this.settings=t,this.values={},this.hasValue={};for(const e of Object.keys(t)){const r=t[e],n=()=>this.getItem(e);let i;i="clippath"!==r.type?n:()=>{try{return JSON.parse(n())}catch(e){}},Object.defineProperty(this.values,e,{get:i,set:t=>this.putSetting(e,t),enumerable:!0}),Object.defineProperty(this.hasValue,e,{get:()=>null!=this.device.storage.getItem(e),enumerable:!0})}}get keys(){const e={};for(const t of Object.keys(this.settings))e[t]=t;return e}async getSettings(){const e=await(this.options?.onGet?.()),t=[];for(const[r,n]of Object.entries(this.settings)){let i=Object.assign({},n);e?.[r]&&(i=Object.assign(i,e[r])),i.onGet&&(i=Object.assign(i,await i.onGet())),i.hide||await(this.options?.hide?.[r]?.())||(i.key=r,i.value=this.getItemInternal(r,i,!0),"function"==typeof i.deviceFilter&&(i.deviceFilter=i.deviceFilter.toString()),t.push(i),delete i.onPut,delete i.onGet,delete i.mapPut,delete i.mapGet)}return t}async putSetting(e,t){const r=this.settings[e];let n;return r&&(n=this.getItemInternal(e,r)),this.putSettingInternal(r,n,e,t)}putSettingInternal(e,t,r,n){e?.noStore||(e?.mapPut&&(n=e.mapPut(t,n)),null==n?this.device.storage.removeItem(r):"object"==typeof n?this.device.storage.setItem(r,JSON.stringify(n)):this.device.storage.setItem(r,n?.toString())),e?.onPut?.(t,n),e?.hide||this.device.onDeviceEvent(a.ScryptedInterface.Settings,void 0)}getItemInternal(e,t,r){if(!t)return this.device.storage.getItem(e);const n=function(e,t,r,n){if(null==e)return r();const i=t.multiple?"array":t.type;if("boolean"===i)return"true"===e||"false"!==e&&(r()||!1);if("number"===i){const t=parseFloat(e);return isNaN(t)?r()||0:t}if("integer"===i){const t=parseInt(e);return isNaN(t)?r()||0:t}if("array"===i){if(!e)return r()||[];try{return JSON.parse(e)}catch(e){return r()||[]}}if("device"===i)return n?e:c.getDeviceById(e)||c.getDeviceById(r());if(e&&t.json)try{return JSON.parse(e)}catch(e){return r()}return e||r()}(this.device.storage.getItem(e),t,()=>null!=t.persistedDefaultValue?(this.putSettingInternal(t,void 0,e,t.persistedDefaultValue),t.persistedDefaultValue):t.defaultValue,r);return t.mapGet?t.mapGet(n):n}getItem(e){return this.getItemInternal(e,this.settings[e])}}},6172(e,t,r){const{Buffer:n}=r(181),i={},o=n.isBuffer(n.from([1,2]).subarray(0,1));function s(e){const t=n.allocUnsafe(2);return t.writeUInt8(e>>8,0),t.writeUInt8(255&e,1),t}e.exports={cache:i,generateCache:function(){for(let e=0;e<65536;e++)i[e]=s(e)},generateNumber:s,genBufVariableByteInt:function(e){let t=0,r=0;const i=n.allocUnsafe(4);do{t=e%128|0,(e=e/128|0)>0&&(t|=128),i.writeUInt8(t,r++)}while(e>0&&r<4);return e>0&&(r=0),o?i.subarray(0,r):i.slice(0,r)},generate4ByteBuffer:function(e){const t=n.allocUnsafe(4);return t.writeUInt32BE(e,0),t}}},6238(e,t,r){"use strict";const n=r(4422),{AbortError:i,codes:o}=r(6371),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(7760),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:p}=r(277),{Promise:f,PromisePrototypeThen:g,SymbolDispose:m}=r(4134),{isClosed:b,isReadable:y,isReadableNodeStream:_,isReadableStream:v,isReadableFinished:S,isReadableErrored:w,isWritable:k,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:T,isWritableErrored:O,isNodeStream:C,willEmitClose:A,kIsClosedPromise:x}=r(6115);let P;const R=()=>{};function M(e,t,o){var p,f;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),v(e)||I(e))return function(e,t,o){let s=!1,a=R;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{P=P||r(7760).addAbortListener;const n=P(t.signal,a),i=o;o=l((...t)=>{n[m](),i.apply(e,t)})}const c=(...t)=>{s||n.nextTick(()=>o.apply(e,t))};return g(e[x].promise,c,c),R}(e,t,o);if(!C(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const M=null!==(p=t.readable)&&void 0!==p?p:_(e),B=null!==(f=t.writable)&&void 0!==f?f:E(e),N=e._writableState,j=e._readableState,D=()=>{e.writable||F()};let L=A(e)&&_(e)===M&&E(e)===B,U=T(e,!1);const F=()=>{U=!0,e.destroyed&&(L=!1),(!L||e.readable&&!M)&&(M&&!$||o.call(e))};let $=S(e,!1);const V=()=>{$=!0,e.destroyed&&(L=!1),(!L||e.writable&&!B)&&(B&&!U||o.call(e))},W=t=>{o.call(e,t)};let H=b(e);const z=()=>{H=!0;const t=O(e)||w(e);return t&&"boolean"!=typeof t?o.call(e,t):M&&!$&&_(e,!0)&&!S(e,!1)?o.call(e,new a):!B||U||T(e,!1)?void o.call(e):o.call(e,new a)},q=()=>{H=!0;const t=O(e)||w(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",F)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?B&&!N&&(e.on("end",D),e.on("close",D)):(e.on("complete",F),L||e.on("abort",z),e.req?G():e.on("request",G)),L||"boolean"!=typeof e.aborted||e.on("aborted",z),e.on("end",V),e.on("finish",F),!1!==t.error&&e.on("error",W),e.on("close",z),H?n.nextTick(z):null!=N&&N.errorEmitted||null!=j&&j.errorEmitted?L||n.nextTick(q):(M||L&&!y(e)||!U&&!1!==k(e))&&(B||L&&!k(e)||!$&&!1!==y(e))?j&&e.req&&e.aborted&&n.nextTick(q):n.nextTick(q);const K=()=>{o=R,e.removeListener("aborted",z),e.removeListener("complete",F),e.removeListener("abort",z),e.removeListener("request",G),e.req&&e.req.removeListener("finish",F),e.removeListener("end",D),e.removeListener("close",D),e.removeListener("finish",F),e.removeListener("end",V),e.removeListener("error",W),e.removeListener("close",z)};if(t.signal&&!H){const s=()=>{const r=o;K(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{P=P||r(7760).addAbortListener;const n=P(t.signal,s),i=o;o=l((...t)=>{n[m](),i.apply(e,t)})}}return K}e.exports=M,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(p(t.cleanup,"cleanup"),n=t.cleanup),new f((r,i)=>{const o=M(e,t,e=>{n&&o(),e?i(e):r()})})}},6286(e,t,r){"use strict";const{Writable:n}=r(2203),i=r(2971),{BINARY_TYPES:o,EMPTY_BUFFER:s,kStatusCode:a,kWebSocket:c}=r(2614),{concat:l,toArrayBuffer:u,unmask:d}=r(3338),{isValidStatusCode:h,isValidUTF8:p}=r(5880),f=Buffer[Symbol.species];e.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||o[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=!(64&~t[0]);if(r&&!this._extensions[i.extensionName]){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){return void e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){return void e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=s;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!==(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&d(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let n;n="nodebuffer"===this._binaryType?l(r,t):"arraybuffer"===this._binaryType?u(l(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)}))}else{const n=l(r,t);if(!this._skipUTF8Validation&&!p(n)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,s),this.end();else{const r=e.readUInt16BE(0);if(!h(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const n=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(n)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0}}createError(e,t,r,n,i){this._loop=!1,this._errored=!0;const o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[a]=n,o}}},6329(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Address6=void 0;const s=o(r(837)),a=o(r(9576)),c=o(r(8914)),l=o(r(465)),u=r(2839),d=r(321),h=r(2437),p=r(837);function f(e){if(!e)throw new Error("Assertion failed.")}function g(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function m(e){return parseInt(e,16).toString(16).padStart(4,"0")}function b(e){return 255&e}class y{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=s.isInSubnet,this.isCorrect=s.isCorrect(c.BITS),this.groups=void 0===t?c.GROUPS:t,this.address=e;const r=c.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>c.BITS)throw new h.AddressError("Invalid subnet mask.");e=e.replace(c.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new h.AddressError("Invalid subnet mask.");const n=c.RE_ZONE_STRING.exec(e);n&&(this.zone=n[0],e=e.replace(c.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new y(e),!0}catch(e){return!1}}static fromBigInt(e){const t=e.toString(16).padStart(32,"0"),r=[];let n;for(n=0;n<c.GROUPS;n++)r.push(t.slice(4*n,4*(n+1)));return new y(r.join(":"))}static fromURL(e){let t,r,n=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=c.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],n=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=c.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new y(t),port:n}}static fromAddress4(e){const t=new u.Address4(e),r=c.BITS-(a.BITS-t.subnetMask);return new y(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new h.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new y(t)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=c.BITS-this.subnetMask-Math.abs(e-c.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}((BigInt("2")**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(c.BITS-this.subnetMask)}`)}startAddress(){return y.fromBigInt(this._startAddress())}startAddressExclusive(){const e=BigInt("1");return y.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(c.BITS-this.subnetMask)}`)}endAddress(){return y.fromBigInt(this._endAddress())}endAddressExclusive(){const e=BigInt("1");return y.fromBigInt(this._endAddress()-e)}getScope(){let e=c.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(c.TYPES))if(this.isInSubnet(new y(e)))return c.TYPES[e];return"Global unicast"}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,c.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:`${r}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const n=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&n.push([e-r,e-1]),r=0)}r>1&&n.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const i=n.map(e=>e[1]-e[0]+1);if(n.length>0){const e=i.indexOf(Math.max(...i));t=function(e,t){const r=[],n=[];let i;for(i=0;i<e.length;i++)i<t[0]?r.push(e[i]):i>t[1]&&n.push(e[i]);return r.concat(["compact"]).concat(n)}(this.parsedAddress,n[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let o=t.join(":");return o=o.replace(/^compact$/,"::"),o=o.replace(/(^compact)|(compact$)/,":"),o=o.replace(/compact/,""),o}binaryZeroPad(){return this.bigInt().toString(2).padStart(c.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(a.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new u.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new h.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(a.RE_ADDRESS,this.address4.parsedAddress.map(g).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(c.RE_BAD_CHARACTERS);if(t)throw new h.AddressError(`Bad character${t.length>1?"s":""} detected in address: ${t.join("")}`,e.replace(c.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(c.RE_BAD_ADDRESS);if(r)throw new h.AddressError(`Address failed regex: ${r.join("")}`,e.replace(c.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let n=[];const i=e.split("::");if(2===i.length){let e=i[0].split(":"),t=i[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new h.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,n=n.concat(e);for(let e=0;e<r;e++)n.push("0");n=n.concat(t)}else{if(1!==i.length)throw new h.AddressError("Too many :: groups found");n=e.split(":"),this.elidedGroups=0}if(n=n.map(e=>parseInt(e,16).toString(16)),n.length!==this.groups)throw new h.AddressError("Incorrect number of groups found");return n}canonicalForm(){return this.parsedAddress.map(m).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(m).join("")}`)}to4(){const e=this.binaryZeroPad().split("");return u.Address4.fromHex(BigInt(`0b${e.slice(96,128).join("")}`).toString(16))}to4in6(){const e=this.to4(),t=new y(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt("0xffff")).toString(),r=u.Address4.fromHex(this.getBitsBase16(32,64)),n=this.getBits(96,128),i=u.Address4.fromHex((n^BigInt("0xffffffff")).toString(16)),o=this.getBitsBase2(64,80),s=(0,p.testBit)(o,15),a=(0,p.testBit)(o,14),c=(0,p.testBit)(o,8),l=(0,p.testBit)(o,9),d=BigInt(`0b${o.slice(2,6)+o.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:r.address,client4:i.address,flags:o,coneNat:s,microsoft:{reserved:a,universalLocal:l,groupIndividual:c,nonce:d},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=u.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new y(e)}toByteArray(){const e=this.bigInt().toString(16),t=`${"0".repeat(e.length%2)}${e}`,r=[];for(let e=0,n=t.length;e<n;e+=2)r.push(parseInt(t.substring(e,e+2),16));return r}toUnsignedByteArray(){return this.toByteArray().map(b)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(b))}static fromUnsignedByteArray(e){const t=BigInt("256");let r=BigInt("0"),n=BigInt("1");for(let i=e.length-1;i>=0;i--)r+=n*BigInt(e[i].toString(10)),n*=t;return y.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new y("2001::/32"))}is6to4(){return this.isInSubnet(new y("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);const r=t.call(this);return e.className?`<a href="${e.prefix}${r}" class="${e.className}">${r}</a>`:`<a href="${e.prefix}${r}">${r}</a>`}group(){if(0===this.elidedGroups)return l.simpleGroup(this.address).join(":");f("number"==typeof this.elidedGroups),f("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...l.simpleGroup(t)):e.push("");const n=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)n.push(`group-${e}`);return e.push(`<span class="${n.join(" ")}"></span>`),r.length?e.push(...l.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(f(this.address4 instanceof u.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new y(this.correctForm());if(0===r.elidedGroups)t.push((0,d.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===c.GROUPS)t.push((0,d.possibleElisions)(c.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,d.simpleRegularExpression)(e[0].split(":"))),f("number"==typeof r.elidedGroups),t.push((0,d.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,d.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",d.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",d.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}t.Address6=y},6371(e,t,r){"use strict";const{format:n,inspect:i}=r(9231),{AggregateError:o}=r(4134),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.ERR_INTERNAL_ASSERTION(t)}function h(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function p(e,t,r){r||(r=Error);class i extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return d(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return d(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(i.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function f(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}p("ERR_ASSERTION","%s",Error),p("ERR_INVALID_ARG_TYPE",(e,t,r)=>{d("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const o=[],s=[],a=[];for(const e of t)d("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?o.push(e.toLowerCase()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`one of type ${o.join(", ")}, or ${e}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.join(", ")}, or ${e}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`one of ${a.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var u;if(null!==(u=r.constructor)&&void 0!==u&&u.name)n+=`. Received an instance of ${r.constructor.name}`;else{n+=`. Received ${i(r,{depth:-1})}`}}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n},TypeError),p("ERR_INVALID_ARG_VALUE",(e,t,r="is invalid")=>{let n=i(t);n.length>128&&(n=n.slice(0,128)+"...");return`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`},TypeError),p("ERR_INVALID_RETURN_VALUE",(e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`},TypeError),p("ERR_MISSING_ARGS",(...e)=>{let t;d(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map(e=>`"${e}"`).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`},TypeError),p("ERR_OUT_OF_RANGE",(e,t,r)=>{let n;if(d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32)n=h(String(r));else if("bigint"==typeof r){n=String(r);const e=BigInt(2)**BigInt(32);(r>e||r<-e)&&(n=h(n)),n+="n"}else n=i(r);return`The value of "${e}" is out of range. It must be ${t}. Received ${n}`},RangeError),p("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),p("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),p("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),p("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),p("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),p("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),p("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),p("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),p("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),p("ERR_STREAM_WRITE_AFTER_END","write after end",Error),p("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:g,aggregateTwoErrors:f(function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t}),hideStackFrames:f,codes:u}},6524(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(4134);e.exports=o;const i=r(7382);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}n(o.prototype,i.prototype),n(o,i),o.prototype._transform=function(e,t,r){r(null,e)}},6532(e,t,r){"use strict";const n=r(4422),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(4134),{Buffer:a}=r(181),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(6371).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}const h=new e({objectMode:!0,highWaterMark:1,...r});let p=!1;return h._read=function(){p||(p=!0,async function(){for(;;){try{const{value:e,done:t}=d?await u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw p=!1,new l;if(h.push(t))continue;p=!1}}catch(e){h.destroy(e)}break}}())},h._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),()=>n.nextTick(t,e),r=>n.nextTick(t,r||e))},h}},6584(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(4988);class i extends n.EventTarget{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){const e=o.get(this);if("boolean"!=typeof e)throw new TypeError("Expected 'this' to be an 'AbortSignal' object, but got "+(null===this?"null":typeof this));return e}}n.defineEventAttribute(i.prototype,"abort");const o=new WeakMap;Object.defineProperties(i.prototype,{aborted:{enumerable:!0}}),"function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(i.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});class s{constructor(){a.set(this,function(){const e=Object.create(i.prototype);return n.EventTarget.call(e),o.set(e,!1),e}())}get signal(){return c(this)}abort(){var e;e=c(this),!1===o.get(e)&&(o.set(e,!0),e.dispatchEvent({type:"abort"}))}}const a=new WeakMap;function c(e){const t=a.get(e);if(null==t)throw new TypeError("Expected 'this' to be an 'AbortController' object, but got "+(null===e?"null":typeof e));return t}Object.defineProperties(s.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),"function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(s.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"}),t.AbortController=s,t.AbortSignal=i,t.default=s,e.exports=s,e.exports.AbortController=e.exports.default=s,e.exports.AbortSignal=i},6585(e){var t=1e3,r=60*t,n=60*r,i=24*n,o=7*i,s=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var o=Math.abs(e);if(o>=i)return a(e,o,i,"day");if(o>=n)return a(e,o,n,"hour");if(o>=r)return a(e,o,r,"minute");if(o>=t)return a(e,o,t,"second");return e+" ms"}(e):function(e){var o=Math.abs(e);if(o>=i)return Math.round(e/i)+"d";if(o>=n)return Math.round(e/n)+"h";if(o>=r)return Math.round(e/r)+"m";if(o>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},6698(e){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},6706(e,t,r){const n=r(4422),i=r(181),{isReadable:o,isWritable:s,isIterable:a,isNodeStream:c,isReadableNodeStream:l,isWritableNodeStream:u,isDuplexNodeStream:d,isReadableStream:h,isWritableStream:p}=r(6115),f=r(6238),{AbortError:g,codes:{ERR_INVALID_ARG_TYPE:m,ERR_INVALID_RETURN_VALUE:b}}=r(6371),{destroyer:y}=r(5896),_=r(3370),v=r(7576),S=r(8584),{createDeferredPromise:w}=r(7760),k=r(6532),E=globalThis.Blob||i.Blob,I="undefined"!=typeof E?function(e){return e instanceof E}:function(e){return!1},T=globalThis.AbortController||r(6584).AbortController,{FunctionPrototypeCall:O}=r(4134);class C extends _{constructor(e){super(e),!1===(null==e?void 0:e.readable)&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===(null==e?void 0:e.writable)&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}}function A(e){const t=e.readable&&"function"!=typeof e.readable.read?v.wrap(e.readable):e.readable,r=e.writable;let n,i,a,c,l,u=!!o(t),d=!!s(r);function h(e){const t=c;c=null,t?t(e):e&&l.destroy(e)}return l=new C({readableObjectMode:!(null==t||!t.readableObjectMode),writableObjectMode:!(null==r||!r.writableObjectMode),readable:u,writable:d}),d&&(f(r,e=>{d=!1,e&&y(t,e),h(e)}),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._final=function(e){r.end(),i=e},r.on("drain",function(){if(n){const e=n;n=null,e()}}),r.on("finish",function(){if(i){const e=i;i=null,e()}})),u&&(f(t,e=>{u=!1,e&&y(t,e),h(e)}),t.on("readable",function(){if(a){const e=a;a=null,e()}}),t.on("end",function(){l.push(null)}),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,y(r,e),y(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return A({readable:t});if(u(t))return A({writable:t});if(c(t))return A({writable:!1,readable:!1});if(h(t))return A({readable:v.fromWeb(t)});if(p(t))return A({writable:S.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=w();const i=new T,o=i.signal,s=e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=w()),yield i}}(),{signal:o});return{value:s,write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(a(e))return k(C,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=O(c,e,e=>{if(null!=e)throw new b("nully","body",e)},e=>{y(t,e)});return t=new C({objectMode:!0,readable:!1,write:i,final(e){o(async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}})},destroy:s})}throw new b("Iterable, AsyncIterable or AsyncFunction",r,e)}if(I(t))return e(t.arrayBuffer());if(a(t))return k(C,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&p(null==t?void 0:t.writable))return C.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable)){return A({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0})}const i=null==t?void 0:t.then;if("function"==typeof i){let e;return O(i,t,t=>{null!=t&&e.push(t),e.push(null)},t=>{y(e,t)}),e=new C({objectMode:!0,writable:!1,read(){}})}throw new m(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},6751(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectCorrelator=void 0;const n=r(1554),i=r(441);t.ObjectCorrelator=class{topology;config;constructor(e,t){this.topology=e,this.config=t}async findBestMatch(e,t){const r=[];for(const n of t){const t=await this.evaluateCandidate(n,e);t.confidence>=this.config.correlationThreshold&&r.push(t)}return 0===r.length?null:(r.sort((e,t)=>t.confidence-e.confidence),r[0])}async evaluateCandidate(e,t){const r={timing:this.evaluateTimingFactor(e,t),visual:await this.evaluateVisualFactor(e,t),spatial:this.evaluateSpatialFactor(e,t),class:this.evaluateClassFactor(e,t)};if(0===r.class)return{trackedObject:e,newSighting:t,confidence:0,factors:r};if(0===r.timing)return{trackedObject:e,newSighting:t,confidence:0,factors:r};return{trackedObject:e,newSighting:t,confidence:.3*r.timing+.35*r.visual+.25*r.spatial+.1*r.class,factors:r}}evaluateTimingFactor(e,t){const r=(0,i.getLastSighting)(e);if(!r)return 0;if(r.cameraId===t.cameraId)return 1;const o=(0,n.findConnection)(this.topology,r.cameraId,t.cameraId);if(!o)return.2;const s=t.timestamp-r.timestamp,{min:a,typical:c,max:l}=o.transitTime;if(s<.5*a||s>2*l)return 0;if(s<a||s>l)return s<a?s/a*.3:l/s*.3;const u=Math.abs(s-c),d=(l-a)/2;return 0===d?1:Math.max(.5,1-u/d*.5)}async evaluateVisualFactor(e,t){if(!this.config.useVisualMatching)return.5;if(!e.visualDescriptor||!t.embedding)return.5;try{return(this.cosineSimilarity(e.visualDescriptor,t.embedding)+1)/2}catch(e){return.5}}evaluateSpatialFactor(e,t){const r=(0,i.getLastSighting)(e);if(!r)return.5;if(r.cameraId===t.cameraId)return 1;const o=(0,n.findConnection)(this.topology,r.cameraId,t.cameraId);if(!o)return.3;let s=0;if(r.position&&o.exitZone.length>0){this.isPointNearZone(r.position,o.exitZone,.2)&&(s+=.5)}else s+=.25;if(t.position&&o.entryZone.length>0){this.isPointNearZone(t.position,o.entryZone,.2)&&(s+=.5)}else s+=.25;return s}evaluateClassFactor(e,t){if(e.className===t.detection.className)return 1;return({car:["vehicle","truck","suv"],vehicle:["car","truck","suv"],truck:["vehicle","car"],person:["human"],human:["person"]}[e.className]||[]).includes(t.detection.className)?.8:0}cosineSimilarity(e,t){try{const r=this.decodeEmbedding(e),n=this.decodeEmbedding(t);if(r.length!==n.length||0===r.length)return 0;let i=0,o=0,s=0;for(let e=0;e<r.length;e++)i+=r[e]*n[e],o+=r[e]*r[e],s+=n[e]*n[e];return o=Math.sqrt(o),s=Math.sqrt(s),0===o||0===s?0:i/(o*s)}catch(e){return 0}}decodeEmbedding(e){try{const t=Buffer.from(e,"base64"),r=[];for(let e=0;e<t.length;e+=4)r.push(t.readFloatLE(e));return r}catch(e){return[]}}isPointNearZone(e,t,r){if(t.length<3)return!1;const n=100*e.x,i=100*e.y;let o=!1;for(let e=0,r=t.length-1;e<t.length;r=e++){const s=t[e][0],a=t[e][1],c=t[r][0],l=t[r][1];a>i!=l>i&&n<(c-s)*(i-a)/(l-a)+s&&(o=!o)}if(o)return!0;for(const e of t){const t=Math.abs(n-e[0])/100,o=Math.abs(i-e[1])/100;if(t<r&&o<r)return!0}return!1}}},6887(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isReactNativeBrowser=t.isWebWorker=void 0;const r=()=>Boolean("object"==typeof self&&self?.constructor?.name?.includes("WorkerGlobalScope")&&"undefined"==typeof Deno),n=()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product,i=(()=>{if("undefined"!=typeof window){if("undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&process?.versions){return!Object.prototype.hasOwnProperty.call(process.versions,"electron")}return"undefined"!=typeof window.document}return!1})()||r()||n();t.isWebWorker=r(),t.isReactNativeBrowser=n(),t.default=i},6912(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(4959)),o=n(r(5228)),s=n(r(495)),a=n(r(1021)),c=n(r(4264));t.default=(e,t,r)=>{const{options:n}=e;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<t.length)return e.emit("error",new Error(`exceeding packets size ${t.cmd}`)),e.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),e;switch(e.log("_handlePacket :: emitting packetreceive"),e.emit("packetreceive",t),t.cmd){case"publish":(0,i.default)(e,t,r);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":e.reschedulePing(),(0,a.default)(e,t),r();break;case"pubrel":e.reschedulePing(),(0,c.default)(e,t,r);break;case"connack":(0,s.default)(e,t),r();break;case"auth":e.reschedulePing(),(0,o.default)(e,t),r();break;case"pingresp":e.log("_handlePacket :: received pingresp"),e.reschedulePing(!0),r();break;case"disconnect":e.emit("disconnect",t),r();break;default:e.log("_handlePacket :: unknown command"),r()}}},6968(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r,n){f("SOCKS connection to %s:%d via %s",e,t,r);const i=new g;return async function(e,t,r,n,i={}){const o=i.lookup??(0,h.promisify)(d.lookup),[s,a]=function(e){const t=new URL(e);if(t.pathname||t.hash||t.search)throw m(new Error("bad SOCKS URL"));const[r,n]=function(e){switch(e){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}(t.protocol);if(!r)throw m(new Error("bad SOCKS URL: invalid protocol"));const i=parseInt(t.port,10);if(Number.isNaN(i))throw m(new Error("bad SOCKS URL: invalid port"));const o={host:t.hostname,port:i,type:r};return[o,n]}(r);a||(f("resolving %s locally",e),e=(await o(e,{family:4===s.type?4:0})).address);f("establishing SOCKS%d connection to %s:%d via %s:%d",s.type,e,t,s.host,s.port);const c=new u.SocksClient({command:"connect",destination:{host:e,port:t},proxy:{...s},timeout:i.timeout});c.connect(),c.on("established",({socket:e})=>n._start(e)),c.on("error",e=>{f("SOCKS failed: %s",e),n.destroy(m(e))})}(e,t,r,i,n).catch(e=>{f("SOCKS failed: %s",e),i.destroy(e)}),i};const c=a(r(5753)),l=r(2203),u=r(5861),d=s(r(2250)),h=r(9023),p=a(r(2613)),f=(0,c.default)("mqttjs:socks");class g extends l.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1}),this.cork()}_start(e){f("proxy stream started"),(0,p.default)(!this._socket),this.destroyed?e.destroy(this.errored):(this._socket=e,this._flowing||e.pause(),e.on("data",this._onData),e.on("end",this._onEnd),e.on("error",this._onError),e.on("close",this._onClose),e.emit("connect"),this.uncork())}_write(e,t,r){(0,p.default)(this._socket),this._socket.write(e,r)}_read(e){this._flowing=!0,this._socket?.resume?.()}_destroy(e,t){this._socket?.destroy?.(e),t(e)}_onData=e=>{(0,p.default)(this._socket),this._flowing=this.push(e),this._flowing||this._socket.pause()};_onEnd=()=>{f("proxy stream received EOF"),this.push(null)};_onClose=()=>{f("proxy stream closed"),this.destroy()};_onError=e=>{f("proxy stream died with error %s",e),this.destroy(e)}}function m(e){try{return void 0===e.code&&(e.code="SOCKS"),e}catch{return e}}},6982(e){"use strict";e.exports=require("crypto")},7016(e){"use strict";e.exports=require("url")},7130(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipToBuffer=t.int32ToIpv4=t.ipv4ToInt32=t.validateSocksClientChainOptions=t.validateSocksClientOptions=void 0;const n=r(3763),i=r(5438),o=r(2203),s=r(9424),a=r(9278);function c(e,t){if(void 0!==e.custom_auth_method){if(e.custom_auth_method<i.SOCKS5_CUSTOM_AUTH_START||e.custom_auth_method>i.SOCKS5_CUSTOM_AUTH_END)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthRange,t);if(void 0===e.custom_auth_request_handler||"function"!=typeof e.custom_auth_request_handler)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,t);if(void 0===e.custom_auth_response_size)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,t);if(void 0===e.custom_auth_response_handler||"function"!=typeof e.custom_auth_response_handler)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,t)}}function l(e){return e&&"string"==typeof e.host&&Buffer.byteLength(e.host)<256&&"number"==typeof e.port&&e.port>=0&&e.port<=65535}function u(e){return e&&("string"==typeof e.host||"string"==typeof e.ipaddress)&&"number"==typeof e.port&&e.port>=0&&e.port<=65535&&(4===e.type||5===e.type)}function d(e){return"number"==typeof e&&e>0}t.validateSocksClientOptions=function(e,t=["connect","bind","associate"]){if(!i.SocksCommand[e.command])throw new n.SocksClientError(i.ERRORS.InvalidSocksCommand,e);if(-1===t.indexOf(e.command))throw new n.SocksClientError(i.ERRORS.InvalidSocksCommandForOperation,e);if(!l(e.destination))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsDestination,e);if(!u(e.proxy))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsProxy,e);if(c(e.proxy,e),e.timeout&&!d(e.timeout))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsTimeout,e);if(e.existing_socket&&!(e.existing_socket instanceof o.Duplex))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsExistingSocket,e)},t.validateSocksClientChainOptions=function(e){if("connect"!==e.command)throw new n.SocksClientError(i.ERRORS.InvalidSocksCommandChain,e);if(!l(e.destination))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsDestination,e);if(!(e.proxies&&Array.isArray(e.proxies)&&e.proxies.length>=2))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsProxiesLength,e);if(e.proxies.forEach(t=>{if(!u(t))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsProxy,e);c(t,e)}),e.timeout&&!d(e.timeout))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsTimeout,e)},t.ipv4ToInt32=function(e){return new s.Address4(e).toArray().reduce((e,t)=>(e<<8)+t,0)>>>0},t.int32ToIpv4=function(e){return[e>>>24&255,e>>>16&255,e>>>8&255,255&e].join(".")},t.ipToBuffer=function(e){if(a.isIPv4(e)){const t=new s.Address4(e);return Buffer.from(t.toArray())}if(a.isIPv6(e)){const t=new s.Address6(e);return Buffer.from(t.canonicalForm().split(":").map(e=>e.padStart(4,"0")).join(""),"hex")}throw new Error("Invalid IP address format")}},7136(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.TrackingEngine=void 0;const a=s(r(7562)),c=r(1554),l=r(441),u=r(6751),{systemManager:d}=a.default;t.TrackingEngine=class{topology;state;alertManager;config;console;correlator;listeners=new Map;pendingTimers=new Map;lostCheckInterval=null;constructor(e,t,r,n,i){this.topology=e,this.state=t,this.alertManager=r,this.config=n,this.console=i,this.correlator=new u.ObjectCorrelator(e,n)}async startTracking(){this.console.log("Starting tracking engine..."),await this.stopTracking();for(const e of this.topology.cameras)try{const t=d.getDeviceById(e.deviceId);if(!t){this.console.warn(`Camera not found: ${e.deviceId} (${e.name})`);continue}if(!t.interfaces?.includes(a.ScryptedInterface.ObjectDetector)){this.console.warn(`Camera ${e.name} does not support object detection`);continue}const r=t.listen(a.ScryptedInterface.ObjectDetector,(t,r,n)=>{this.handleDetection(e.deviceId,e.name,n)});this.listeners.set(e.deviceId,r),this.console.log(`Listening to camera: ${e.name}`)}catch(t){this.console.error(`Failed to subscribe to camera ${e.name}:`,t)}this.lostCheckInterval=setInterval(()=>{this.checkForLostObjects()},3e4),this.console.log(`Tracking engine started with ${this.listeners.size} cameras`)}async stopTracking(){for(const[e,t]of this.listeners.entries())try{t.removeListener()}catch(t){this.console.error(`Failed to remove listener for ${e}:`,t)}this.listeners.clear();for(const e of this.pendingTimers.values())clearTimeout(e);this.pendingTimers.clear(),this.lostCheckInterval&&(clearInterval(this.lostCheckInterval),this.lostCheckInterval=null),this.console.log("Tracking engine stopped")}async handleDetection(e,t,r){if(!r.detections||0===r.detections.length)return;const n=(0,c.findCamera)(this.topology,e);if(!n)return;const i=r.timestamp||Date.now();for(const o of r.detections){if(o.score<.5)continue;if(n.trackClasses.length>0&&!n.trackClasses.includes(o.className))continue;const s={detection:o,cameraId:e,cameraName:t,timestamp:i,confidence:o.score,embedding:o.embedding,detectionId:r.detectionId,position:o.boundingBox?{x:(o.boundingBox[0]+o.boundingBox[2]/2)/100,y:(o.boundingBox[1]+o.boundingBox[3]/2)/100}:void 0};await this.processSighting(s,n.isEntryPoint,n.isExitPoint)}}async processSighting(e,t,r){const n=await this.correlateDetection(e);if(n){const t=n.trackedObject,i=(0,l.getLastSighting)(t);i&&i.cameraId!==e.cameraId&&(this.state.addJourney(t.globalId,{fromCameraId:i.cameraId,fromCameraName:i.cameraName,toCameraId:e.cameraId,toCameraName:e.cameraName,exitTime:i.timestamp,entryTime:e.timestamp,transitDuration:e.timestamp-i.timestamp,correlationConfidence:n.confidence}),this.console.log(`Object ${t.globalId.slice(0,8)} transited: ${i.cameraName} → ${e.cameraName} (confidence: ${(100*n.confidence).toFixed(0)}%)`)),this.state.addSighting(t.globalId,e);const o=this.pendingTimers.get(t.globalId);o&&(clearTimeout(o),this.pendingTimers.delete(t.globalId)),this.state.reactivate(t.globalId),r&&this.isLeavingFrame(e)&&this.handlePotentialExit(t,e)}else{const r=this.state.generateId(),n=this.state.createObject(r,e,t);this.console.log(`New ${e.detection.className} detected on ${e.cameraName} (ID: ${r.slice(0,8)})`),t&&await this.alertManager.checkAndAlert("property_entry",n,{cameraId:e.cameraId,cameraName:e.cameraName,objectClass:e.detection.className,objectLabel:e.detection.label,detectionId:e.detectionId})}}async correlateDetection(e){const t=this.state.getActiveObjects();if(0===t.length)return null;for(const r of t){const t=(0,l.getLastSighting)(r);if(t&&t.cameraId===e.cameraId&&t.detection.id===e.detection.id)return{trackedObject:r,newSighting:e,confidence:1,factors:{timing:1,visual:1,spatial:1,class:1}}}return await this.correlator.findBestMatch(e,t)}isLeavingFrame(e){if(!e.position)return!1;const t=.1;return e.position.x<t||e.position.x>.9||e.position.y<t||e.position.y>.9}handlePotentialExit(e,t){this.state.markPending(e.globalId);const r=setTimeout(async()=>{const r=this.state.getObject(e.globalId);r&&"pending"===r.state&&(this.state.markExited(e.globalId,t.cameraId,t.cameraName),this.console.log(`Object ${e.globalId.slice(0,8)} exited via ${t.cameraName}`),await this.alertManager.checkAndAlert("property_exit",r,{cameraId:t.cameraId,cameraName:t.cameraName,objectClass:r.className,objectLabel:r.label})),this.pendingTimers.delete(e.globalId)},this.config.correlationWindow);this.pendingTimers.set(e.globalId,r)}checkForLostObjects(){const e=Date.now(),t=this.state.getActiveObjects();for(const r of t){const t=e-r.lastSeen;t>this.config.lostTimeout&&(this.state.markLost(r.globalId),this.console.log(`Object ${r.globalId.slice(0,8)} marked as lost (not seen for ${Math.round(t/1e3)}s)`),this.alertManager.checkAndAlert("lost_tracking",r,{objectClass:r.className,objectLabel:r.label}))}}updateTopology(e){this.topology=e,this.correlator=new u.ObjectCorrelator(e,this.config)}getTopology(){return this.topology}getTrackedObjects(){return this.state.getAllObjects()}getTrackedObject(e){return this.state.getObject(e)}}},7279(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MqttPublisher=void 0;const i=n(r(9372));t.MqttPublisher=class{client=null;config;console;connected=!1;reconnectTimer=null;constructor(e,t){this.config=e,this.console=t}async connect(){if(this.client)return;const e={clientId:`scrypted-spatial-awareness-${Date.now()}`,clean:!0,connectTimeout:1e4,reconnectPeriod:5e3};this.config.username&&(e.username=this.config.username,e.password=this.config.password);try{this.client=i.default.connect(this.config.broker,e),this.client.on("connect",()=>{this.connected=!0,this.console.log(`MQTT connected to ${this.config.broker}`),this.publishDiscovery()}),this.client.on("error",e=>{this.console.error("MQTT error:",e)}),this.client.on("close",()=>{this.connected=!1,this.console.log("MQTT connection closed")}),this.client.on("offline",()=>{this.connected=!1,this.console.log("MQTT offline")})}catch(e){this.console.error("Failed to connect to MQTT:",e)}}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.client.end(),this.client=null,this.connected=!1)}publishDiscovery(){if(!this.client||!this.connected)return;const e=this.config.baseTopic,t={name:"Property Occupancy",unique_id:"spatial_awareness_occupancy",state_topic:`${e}/occupancy/state`,device_class:"occupancy",payload_on:"ON",payload_off:"OFF",device:{identifiers:["spatial_awareness"],name:"Spatial Awareness",model:"Cross-Camera Tracker",manufacturer:"Scrypted"}};this.client.publish("homeassistant/binary_sensor/spatial_awareness_occupancy/config",JSON.stringify(t),{retain:!0});const r={name:"Active Tracked Objects",unique_id:"spatial_awareness_count",state_topic:`${e}/count/state`,icon:"mdi:account-multiple",device:{identifiers:["spatial_awareness"]}};this.client.publish("homeassistant/sensor/spatial_awareness_count/config",JSON.stringify(r),{retain:!0});const n={name:"People on Property",unique_id:"spatial_awareness_person_count",state_topic:`${e}/person_count/state`,icon:"mdi:account-group",device:{identifiers:["spatial_awareness"]}};this.client.publish("homeassistant/sensor/spatial_awareness_person_count/config",JSON.stringify(n),{retain:!0});const i={name:"Vehicles on Property",unique_id:"spatial_awareness_vehicle_count",state_topic:`${e}/vehicle_count/state`,icon:"mdi:car",device:{identifiers:["spatial_awareness"]}};this.client.publish("homeassistant/sensor/spatial_awareness_vehicle_count/config",JSON.stringify(i),{retain:!0}),this.console.log("MQTT discovery published")}publishState(e){if(!this.client||!this.connected)return;const t=this.config.baseTopic,r=e.filter(e=>"active"===e.state||"pending"===e.state),n=r.length>0;this.client.publish(`${t}/occupancy/state`,n?"ON":"OFF",{retain:!0}),this.client.publish(`${t}/count/state`,String(r.length),{retain:!0});const i=r.filter(e=>"person"===e.className).length;this.client.publish(`${t}/person_count/state`,String(i),{retain:!0});const o=r.filter(e=>["car","vehicle","truck"].includes(e.className)).length;this.client.publish(`${t}/vehicle_count/state`,String(o),{retain:!0});const s={timestamp:Date.now(),occupied:n,activeCount:r.length,personCount:i,vehicleCount:o,objects:r.map(e=>({id:e.globalId,class:e.className,label:e.label,cameras:e.activeOnCameras,firstSeen:e.firstSeen,lastSeen:e.lastSeen,state:e.state}))};this.client.publish(`${t}/state`,JSON.stringify(s),{retain:!0})}publishAlert(e){if(!this.client||!this.connected)return;const t=this.config.baseTopic,r={id:e.id,type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp,objectId:e.trackedObjectId,details:e.details};this.client.publish(`${t}/alerts`,JSON.stringify(r)),this.client.publish(`${t}/alerts/${e.type}`,JSON.stringify(r))}publishEntry(e,t){if(!this.client||!this.connected)return;const r=this.config.baseTopic,n={event:"entry",timestamp:Date.now(),object:{id:e.globalId,class:e.className,label:e.label},camera:t};this.client.publish(`${r}/events/entry`,JSON.stringify(n))}publishExit(e,t){if(!this.client||!this.connected)return;const r=this.config.baseTopic,n={event:"exit",timestamp:Date.now(),object:{id:e.globalId,class:e.className,label:e.label,dwellTime:e.lastSeen-e.firstSeen},camera:t};this.client.publish(`${r}/events/exit`,JSON.stringify(n))}publishTransition(e,t,r){if(!this.client||!this.connected)return;const n=this.config.baseTopic,i={event:"transition",timestamp:Date.now(),object:{id:e.globalId,class:e.className,label:e.label},from:t,to:r};this.client.publish(`${n}/events/transition`,JSON.stringify(i))}isConnected(){return this.connected}}},7382(e,t,r){"use strict";const{ObjectSetPrototypeOf:n,Symbol:i}=r(4134);e.exports=l;const{ERR_METHOD_NOT_IMPLEMENTED:o}=r(6371).codes,s=r(3370),{getHighWaterMark:a}=r(5291);n(l.prototype,s.prototype),n(l,s);const c=i("kCallback");function l(e){if(!(this instanceof l))return new l(e);const t=e?a(this,e,"readableHighWaterMark",!0):null;0===t&&(e={...e,highWaterMark:null,readableHighWaterMark:t,writableHighWaterMark:e.writableHighWaterMark||0}),s.call(this,e),this._readableState.sync=!1,this[c]=null,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",d)}function u(e){"function"!=typeof this._flush||this.destroyed?(this.push(null),e&&e()):this._flush((t,r)=>{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())})}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,o=n.length;this._transform(e,t,(e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||o===n.length||n.length<n.highWaterMark?r():this[c]=r)})},l.prototype._read=function(){if(this[c]){const e=this[c];this[c]=null,e()}}},7562(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sdk=t.MixinDeviceBase=t.ScryptedDeviceBase=void 0,i(r(4192),t);const s=o(r(9896)),a=r(4192);r(3339);class c extends a.DeviceBase{constructor(e){super(),this.nativeId=e}get storage(){return this._storage||(this._storage=t.sdk.deviceManager.getDeviceStorage(this.nativeId)),this._storage}get log(){return this._log||(this._log=t.sdk.deviceManager.getDeviceLogger(this.nativeId)),this._log}get console(){return this._console||(this._console=t.sdk.deviceManager.getDeviceConsole(this.nativeId)),this._console}async createMediaObject(e,r){return t.sdk.mediaManager.createMediaObject(e,r,{sourceId:this.id})}getMediaObjectConsole(e){return"string"!=typeof e.sourceId?this.console:t.sdk.deviceManager.getMixinConsole(e.sourceId,this.nativeId)}_lazyLoadDeviceState(){this._deviceState||(this.nativeId?this._deviceState=t.sdk.deviceManager.getDeviceState(this.nativeId):this._deviceState=t.sdk.deviceManager.getDeviceState())}onDeviceEvent(e,r){return t.sdk.deviceManager.onDeviceEvent(this.nativeId,e,r)}}t.ScryptedDeviceBase=c;class l extends a.DeviceBase{constructor(e){super(),this._listeners=new Set,this.mixinDevice=e.mixinDevice,this.mixinDeviceInterfaces=e.mixinDeviceInterfaces,this.mixinStorageSuffix=e.mixinStorageSuffix,this._deviceState=e.mixinDeviceState,this.nativeId=t.sdk.systemManager.getDeviceById(this.id).nativeId,this.mixinProviderNativeId=e.mixinProviderNativeId,this._deviceState.__rpcproxy_traps_all_properties&&"string"==typeof this._deviceState.id&&(this._deviceState=t.sdk.deviceManager.createDeviceState(this._deviceState.id,this._deviceState.setState))}get storage(){if(!this._storage){const e=this.mixinStorageSuffix,r=this.id+(e?":"+e:"");this._storage=t.sdk.deviceManager.getMixinStorage(r,this.mixinProviderNativeId)}return this._storage}get console(){return this._console||(t.sdk.deviceManager.getMixinConsole?this._console=t.sdk.deviceManager.getMixinConsole(this.id,this.mixinProviderNativeId):this._console=t.sdk.deviceManager.getDeviceConsole(this.mixinProviderNativeId)),this._console}async createMediaObject(e,r){return t.sdk.mediaManager.createMediaObject(e,r,{sourceId:this.id})}getMediaObjectConsole(e){return"string"!=typeof e.sourceId?this.console:t.sdk.deviceManager.getMixinConsole(e.sourceId,this.mixinProviderNativeId)}onDeviceEvent(e,r){return t.sdk.deviceManager.onMixinEvent(this.id,this,e,r)}_lazyLoadDeviceState(){}manageListener(e){this._listeners.add(e)}release(){for(const e of this._listeners)e.removeListener()}}t.MixinDeviceBase=l,function(){function e(e){return function(){return this._lazyLoadDeviceState(),this._deviceState?.[e]}}function t(e){return function(t){this._lazyLoadDeviceState(),this._deviceState?this._deviceState[e]=t:console.warn("device state is unavailable. the device must be discovered with deviceManager.onDeviceDiscovered or deviceManager.onDevicesChanged before the state can be set.")}}for(const r of Object.values(a.ScryptedInterfaceProperty))r!==a.ScryptedInterfaceProperty.nativeId&&(Object.defineProperty(c.prototype,r,{set:t(r),get:e(r)}),Object.defineProperty(l.prototype,r,{set:t(r),get:e(r)}))}(),t.sdk={};try{let e=!1;try{process.env.SCRYPTED_SDK_ES_MODULE||process.env.SCRYPTED_SDK_MODULE;const n=process.env.SCRYPTED_SDK_CJS_MODULE||process.env.SCRYPTED_SDK_MODULE;if(n)if("undefined"!=typeof require){const r=require(process.env.SCRYPTED_SDK_MODULE);Object.assign(t.sdk,r.getScryptedStatic()),e=!0}else{const i=r(3891)(n);Object.assign(t.sdk,i.getScryptedStatic()),e=!0}}catch(e){throw console.warn("failed to load sdk module",e),e}if(!e){let e;try{e=pluginRuntimeAPI}catch(e){}Object.assign(t.sdk,{log:deviceManager.getDeviceLogger(void 0),deviceManager,endpointManager,mediaManager,systemManager,pluginHostAPI,...e})}try{let e={...a.ScryptedInterfaceDescriptors};try{const t=JSON.parse(s.default.readFileSync("../sdk.json").toString()).interfaceDescriptors;t&&(e={...e,...t})}catch(e){console.warn("failed to load custom interface descriptors",e)}t.sdk.systemManager.setScryptedInterfaceDescriptors?.(a.TYPES_VERSION,e)?.catch(()=>{})}catch(e){}}catch(e){console.error("sdk initialization error, import @scrypted/types or use @scrypted/client instead",e)}t.default=t.sdk},7575(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1725);class i{constructor(e){if(this.length=0,this._encoding="utf8",this._writeOffset=0,this._readOffset=0,i.isSmartBufferOptions(e))if(e.encoding&&(n.checkEncoding(e.encoding),this._encoding=e.encoding),e.size){if(!(n.isFiniteInteger(e.size)&&e.size>0))throw new Error(n.ERRORS.INVALID_SMARTBUFFER_SIZE);this._buff=Buffer.allocUnsafe(e.size)}else if(e.buff){if(!Buffer.isBuffer(e.buff))throw new Error(n.ERRORS.INVALID_SMARTBUFFER_BUFFER);this._buff=e.buff,this.length=e.buff.length}else this._buff=Buffer.allocUnsafe(4096);else{if("undefined"!=typeof e)throw new Error(n.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(4096)}}static fromSize(e,t){return new this({size:e,encoding:t})}static fromBuffer(e,t){return new this({buff:e,encoding:t})}static fromOptions(e){return new this(e)}static isSmartBufferOptions(e){const t=e;return t&&(void 0!==t.encoding||void 0!==t.size||void 0!==t.buff)}readInt8(e){return this._readNumberValue(Buffer.prototype.readInt8,1,e)}readInt16BE(e){return this._readNumberValue(Buffer.prototype.readInt16BE,2,e)}readInt16LE(e){return this._readNumberValue(Buffer.prototype.readInt16LE,2,e)}readInt32BE(e){return this._readNumberValue(Buffer.prototype.readInt32BE,4,e)}readInt32LE(e){return this._readNumberValue(Buffer.prototype.readInt32LE,4,e)}readBigInt64BE(e){return n.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,e)}readBigInt64LE(e){return n.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,e)}writeInt8(e,t){return this._writeNumberValue(Buffer.prototype.writeInt8,1,e,t),this}insertInt8(e,t){return this._insertNumberValue(Buffer.prototype.writeInt8,1,e,t)}writeInt16BE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,e,t)}insertInt16BE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,e,t)}writeInt16LE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,e,t)}insertInt16LE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,e,t)}writeInt32BE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,e,t)}insertInt32BE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,e,t)}writeInt32LE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,e,t)}insertInt32LE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,e,t)}writeBigInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,e,t)}insertBigInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,e,t)}writeBigInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,e,t)}insertBigInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,e,t)}readUInt8(e){return this._readNumberValue(Buffer.prototype.readUInt8,1,e)}readUInt16BE(e){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,e)}readUInt16LE(e){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,e)}readUInt32BE(e){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,e)}readUInt32LE(e){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,e)}readBigUInt64BE(e){return n.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,e)}readBigUInt64LE(e){return n.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,e)}writeUInt8(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,e,t)}insertUInt8(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,e,t)}writeUInt16BE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,e,t)}insertUInt16BE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,e,t)}writeUInt16LE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,e,t)}insertUInt16LE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,e,t)}writeUInt32BE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,e,t)}insertUInt32BE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,e,t)}writeUInt32LE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,e,t)}insertUInt32LE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,e,t)}writeBigUInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,t)}insertBigUInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,t)}writeBigUInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,t)}insertBigUInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,t)}readFloatBE(e){return this._readNumberValue(Buffer.prototype.readFloatBE,4,e)}readFloatLE(e){return this._readNumberValue(Buffer.prototype.readFloatLE,4,e)}writeFloatBE(e,t){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,e,t)}insertFloatBE(e,t){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,e,t)}writeFloatLE(e,t){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,e,t)}insertFloatLE(e,t){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,e,t)}readDoubleBE(e){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,e)}readDoubleLE(e){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,e)}writeDoubleBE(e,t){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,e,t)}insertDoubleBE(e,t){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,e,t)}writeDoubleLE(e,t){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,e,t)}insertDoubleLE(e,t){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,e,t)}readString(e,t){let r;"number"==typeof e?(n.checkLengthValue(e),r=Math.min(e,this.length-this._readOffset)):(t=e,r=this.length-this._readOffset),"undefined"!=typeof t&&n.checkEncoding(t);const i=this._buff.slice(this._readOffset,this._readOffset+r).toString(t||this._encoding);return this._readOffset+=r,i}insertString(e,t,r){return n.checkOffsetValue(t),this._handleString(e,!0,t,r)}writeString(e,t,r){return this._handleString(e,!1,t,r)}readStringNT(e){"undefined"!=typeof e&&n.checkEncoding(e);let t=this.length;for(let e=this._readOffset;e<this.length;e++)if(0===this._buff[e]){t=e;break}const r=this._buff.slice(this._readOffset,t);return this._readOffset=t+1,r.toString(e||this._encoding)}insertStringNT(e,t,r){return n.checkOffsetValue(t),this.insertString(e,t,r),this.insertUInt8(0,t+e.length),this}writeStringNT(e,t,r){return this.writeString(e,t,r),this.writeUInt8(0,"number"==typeof t?t+e.length:this.writeOffset),this}readBuffer(e){"undefined"!=typeof e&&n.checkLengthValue(e);const t="number"==typeof e?e:this.length,r=Math.min(this.length,this._readOffset+t),i=this._buff.slice(this._readOffset,r);return this._readOffset=r,i}insertBuffer(e,t){return n.checkOffsetValue(t),this._handleBuffer(e,!0,t)}writeBuffer(e,t){return this._handleBuffer(e,!1,t)}readBufferNT(){let e=this.length;for(let t=this._readOffset;t<this.length;t++)if(0===this._buff[t]){e=t;break}const t=this._buff.slice(this._readOffset,e);return this._readOffset=e+1,t}insertBufferNT(e,t){return n.checkOffsetValue(t),this.insertBuffer(e,t),this.insertUInt8(0,t+e.length),this}writeBufferNT(e,t){return"undefined"!=typeof t&&n.checkOffsetValue(t),this.writeBuffer(e,t),this.writeUInt8(0,"number"==typeof t?t+e.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(e){n.checkOffsetValue(e),n.checkTargetOffset(e,this),this._readOffset=e}get writeOffset(){return this._writeOffset}set writeOffset(e){n.checkOffsetValue(e),n.checkTargetOffset(e,this),this._writeOffset=e}get encoding(){return this._encoding}set encoding(e){n.checkEncoding(e),this._encoding=e}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(e){const t="string"==typeof e?e:this._encoding;return n.checkEncoding(t),this._buff.toString(t,0,this.length)}destroy(){return this.clear(),this}_handleString(e,t,r,i){let o=this._writeOffset,s=this._encoding;"number"==typeof r?o=r:"string"==typeof r&&(n.checkEncoding(r),s=r),"string"==typeof i&&(n.checkEncoding(i),s=i);const a=Buffer.byteLength(e,s);return t?this.ensureInsertable(a,o):this._ensureWriteable(a,o),this._buff.write(e,o,a,s),t?this._writeOffset+=a:"number"==typeof r?this._writeOffset=Math.max(this._writeOffset,o+a):this._writeOffset+=a,this}_handleBuffer(e,t,r){const n="number"==typeof r?r:this._writeOffset;return t?this.ensureInsertable(e.length,n):this._ensureWriteable(e.length,n),e.copy(this._buff,n),t?this._writeOffset+=e.length:"number"==typeof r?this._writeOffset=Math.max(this._writeOffset,n+e.length):this._writeOffset+=e.length,this}ensureReadable(e,t){let r=this._readOffset;if("undefined"!=typeof t&&(n.checkOffsetValue(t),r=t),r<0||r+e>this.length)throw new Error(n.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(e,t){n.checkOffsetValue(t),this._ensureCapacity(this.length+e),t<this.length&&this._buff.copy(this._buff,t+e,t,this._buff.length),t+e>this.length?this.length=t+e:this.length+=e}_ensureWriteable(e,t){const r="number"==typeof t?t:this._writeOffset;this._ensureCapacity(r+e),r+e>this.length&&(this.length=r+e)}_ensureCapacity(e){const t=this._buff.length;if(e>t){let r=this._buff,n=3*t/2+1;n<e&&(n=e),this._buff=Buffer.allocUnsafe(n),r.copy(this._buff,0,0,t)}}_readNumberValue(e,t,r){this.ensureReadable(t,r);const n=e.call(this._buff,"number"==typeof r?r:this._readOffset);return"undefined"==typeof r&&(this._readOffset+=t),n}_insertNumberValue(e,t,r,i){return n.checkOffsetValue(i),this.ensureInsertable(t,i),e.call(this._buff,r,i),this._writeOffset+=t,this}_writeNumberValue(e,t,r,i){if("number"==typeof i){if(i<0)throw new Error(n.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);n.checkOffsetValue(i)}const o="number"==typeof i?i:this._writeOffset;return this._ensureWriteable(t,o),e.call(this._buff,r,o),"number"==typeof i?this._writeOffset=Math.max(this._writeOffset,o+t):this._writeOffset+=t,this}}t.SmartBuffer=i},7576(e,t,r){"use strict";const n=r(4422),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:p,SymbolAsyncIterator:f,Symbol:g}=r(4134);e.exports=H,H.ReadableState=W;const{EventEmitter:m}=r(4434),{Stream:b,prependListener:y}=r(4259),{Buffer:_}=r(181),{addAbortSignal:v}=r(4147),S=r(6238);let w=r(7760).debuglog("stream",e=>{w=e});const k=r(345),E=r(5896),{getHighWaterMark:I,getDefaultHighWaterMark:T}=r(5291),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:C,ERR_METHOD_NOT_IMPLEMENTED:A,ERR_OUT_OF_RANGE:x,ERR_STREAM_PUSH_AFTER_EOF:P,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:R},AbortError:M}=r(6371),{validateObject:B}=r(277),N=g("kPaused"),{StringDecoder:j}=r(3141),D=r(6532);u(H.prototype,b.prototype),u(H,b);const L=()=>{},{errorOrDestroy:U}=E,F=2048,$=4096;function V(e){return{enumerable:!1,get(){return 0!==(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function W(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(3370)),this.state=6192,e&&e.objectMode&&(this.state|=1),n&&e&&e.readableObjectMode&&(this.state|=1),this.highWaterMark=e?I(this,e,"readableHighWaterMark",n):T(!1),this.buffer=new k,this.length=0,this.pipes=[],this.flowing=null,this[N]=null,e&&!1===e.emitClose&&(this.state&=-2049),e&&!1===e.autoDestroy&&(this.state&=-4097),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new j(e.encoding),this.encoding=e.encoding)}function H(e){if(!(this instanceof H))return new H(e);const t=this instanceof r(3370);this._readableState=new W(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&v(e.signal,this)),b.call(this,e),E.construct(this,()=>{this._readableState.needReadable&&Y(this,this._readableState)})}function z(e,t,r,n){w("readableAddChunk",t);const i=e._readableState;let o;if(1&i.state||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=_.from(t,r).toString(i.encoding):(t=_.from(t,r),r=""))):t instanceof _?r="":b._isUint8Array(t)?(t=b._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new C("chunk",["string","Buffer","Uint8Array"],t))),o)U(e,o);else if(null===t)i.state&=-9,function(e,t){if(w("onEofChunk"),t.ended)return;if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?K(e):(t.needReadable=!1,t.emittedReadable=!0,Q(e))}(e,i);else if(1&i.state||t&&t.length>0)if(n)if(4&i.state)U(e,new R);else{if(i.destroyed||i.errored)return!1;q(e,i,t,!0)}else if(i.ended)U(e,new P);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?q(e,i,t,!1):Y(e,i)):q(e,i,t,!1)}else n||(i.state&=-9,Y(e,i));return!i.ended&&(i.length<i.highWaterMark||0===i.length)}function q(e,t,r,n){t.flowing&&0===t.length&&!t.sync&&e.listenerCount("data")>0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&K(e)),Y(e,t)}c(W.prototype,{objectMode:V(1),ended:V(2),endEmitted:V(4),reading:V(8),constructed:V(16),sync:V(32),needReadable:V(64),emittedReadable:V(128),readableListening:V(256),resumeScheduled:V(512),errorEmitted:V(1024),emitClose:V(F),autoDestroy:V($),destroyed:V(8192),closed:V(16384),closeEmitted:V(32768),multiAwaitDrain:V(65536),readingMore:V(1<<17),dataEmitted:V(1<<18)}),H.prototype.destroy=E.destroy,H.prototype._undestroy=E.undestroy,H.prototype._destroy=function(e,t){t(e)},H.prototype[m.captureRejectionSymbol]=function(e){this.destroy(e)},H.prototype[p]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new M,this.destroy(e)),new d((t,r)=>S(this,n=>n&&n!==e?r(n):t(null)))},H.prototype.push=function(e,t){return z(this,e,t,!1)},H.prototype.unshift=function(e,t){return z(this,e,t,!0)},H.prototype.isPaused=function(){const e=this._readableState;return!0===e[N]||!1===e.flowing},H.prototype.setEncoding=function(e){const t=new j(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this};function G(e,t){return e<=0||0===t.length&&t.ended?0:1&t.state?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function K(e){const t=e._readableState;w("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(w("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(Q,e))}function Q(e){const t=e._readableState;w("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,te(e)}function Y(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(Z,e,t))}function Z(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){const r=t.length;if(w("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function J(e){const t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!1===t[N]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function X(e){w("readable nexttick read 0"),e.read(0)}function ee(e,t){w("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),te(e),t.flowing&&!t.reading&&e.read(0)}function te(e){const t=e._readableState;for(w("flow",t.flowing);t.flowing&&null!==e.read(););}function re(e,t){"function"!=typeof e.read&&(e=H.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=L;function i(t){this===e?(n(),n=L):n=t}e.on("readable",i);const o=S(e,{writable:!1},e=>{r=e?O(r,e):null,n(),n=L});try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new d(i)}}}catch(e){throw r=O(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):E.destroyer(e,null)}}(e,t);return r.stream=e,r}function ne(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ie(e){const t=e._readableState;w("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(oe,t,e))}function oe(e,t){if(w("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(se,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function se(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ae;function ce(){return void 0===ae&&(ae={}),ae}H.prototype.read=function(e){w("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new x("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return w("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ie(this):K(this),null;if(0===(e=G(e,t))&&t.ended)return 0===t.length&&ie(this),null;let n,i=!!(64&t.state);if(w("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&(i=!0,w("length less than watermark",i)),t.ended||t.reading||t.destroyed||t.errored||!t.constructed)i=!1,w("reading, ended or constructing",i);else if(i){w("do read"),t.state|=40,0===t.length&&(t.state|=64);try{this._read(t.highWaterMark)}catch(e){U(this,e)}t.state&=-33,t.reading||(e=G(r,t))}return n=e>0?ne(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ie(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},H.prototype._read=function(e){throw new A("_read()")},H.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new h(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),w("pipe count=%d opts=%j",i.pipes.length,t);const o=(!t||!1!==t.end)&&e!==n.stdout&&e!==n.stderr?a:m;function s(t,n){w("onunpipe"),t===r&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,function(){w("cleanup"),e.removeListener("close",f),e.removeListener("finish",g),c&&e.removeListener("drain",c);e.removeListener("error",p),e.removeListener("unpipe",s),r.removeListener("end",a),r.removeListener("end",m),r.removeListener("data",d),l=!0,c&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&c()}())}function a(){w("onend"),e.end()}let c;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",s);let l=!1;function u(){l||(1===i.pipes.length&&i.pipes[0]===e?(w("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(w("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),c||(c=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(w("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(w("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",c))}function d(t){w("ondata");const r=e.write(t);w("dest.write",r),!1===r&&u()}function p(t){if(w("onerror",t),m(),e.removeListener("error",p),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?U(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",g),m()}function g(){w("onfinish"),e.removeListener("close",f),m()}function m(){w("unpipe"),r.unpipe(e)}return r.on("data",d),y(e,"error",p),e.once("close",f),e.once("finish",g),e.emit("pipe",r),!0===e.writableNeedDrain?u():i.flowing||(w("pipe resume"),r.resume()),e},H.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t<e.length;t++)e[t].emit("unpipe",this,{hasUnpiped:!1});return this}const r=i(t.pipes,e);return-1===r||(t.pipes.splice(r,1),0===t.pipes.length&&this.pause(),e.emit("unpipe",this,{hasUnpiped:!1})),this},H.prototype.on=function(e,t){const r=b.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,w("on readable",i.length,i.reading),i.length?K(this):i.reading||n.nextTick(X,this))),r},H.prototype.addListener=H.prototype.on,H.prototype.removeListener=function(e,t){const r=b.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(J,this),r},H.prototype.off=H.prototype.removeListener,H.prototype.removeAllListeners=function(e){const t=b.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(J,this),t},H.prototype.resume=function(){const e=this._readableState;return e.flowing||(w("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ee,e,t))}(this,e)),e[N]=!1,this},H.prototype.pause=function(){return w("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(w("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[N]=!0,this},H.prototype.wrap=function(e){let t=!1;e.on("data",r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())}),e.on("end",()=>{this.push(null)}),e.on("error",e=>{U(this,e)}),e.on("close",()=>{this.destroy()}),e.on("destroy",()=>{this.destroy()}),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=l(e);for(let t=1;t<r.length;t++){const n=r[t];void 0===this[n]&&"function"==typeof e[n]&&(this[n]=e[n].bind(e))}return this},H.prototype[f]=function(){return re(this)},H.prototype.iterator=function(e){return void 0!==e&&B(e,"options"),re(this,e)},c(H.prototype,{readable:{__proto__:null,get(){const e=this._readableState;return!(!e||!1===e.readable||e.destroyed||e.errorEmitted||e.endEmitted)},set(e){this._readableState&&(this._readableState.readable=!!e)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._readableState.readable||!this._readableState.destroyed&&!this._readableState.errored||this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.objectMode}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return!!this._readableState&&this._readableState.closed}},destroyed:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.destroyed},set(e){this._readableState&&(this._readableState.destroyed=e)}},readableEnded:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.endEmitted}}}),c(W.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return!1!==this[N]},set(e){this[N]=!!e}}}),H._fromList=ne,H.from=function(e,t){return D(H,e,t)},H.fromWeb=function(e,t){return ce().newStreamReadableFromReadableStream(e,t)},H.toWeb=function(e,t){return ce().newReadableStreamFromStreamReadable(e,t)},H.wrap=function(e,t){var r,n;return new H({objectMode:null===(r=null!==(n=e.readableObjectMode)&&void 0!==n?n:e.objectMode)||void 0===r||r,...t,destroy(t,r){E.destroyer(e,t),r(t)}}).wrap(e)}},7631(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.SocksClientError=t.SocksClient=void 0;const i=r(4434),o=r(9278),s=r(7575),a=r(5438),c=r(7130),l=r(7736),u=r(3763);Object.defineProperty(t,"SocksClientError",{enumerable:!0,get:function(){return u.SocksClientError}});const d=r(9424);class h extends i.EventEmitter{constructor(e){super(),this.options=Object.assign({},e),(0,c.validateSocksClientOptions)(e),this.setState(a.SocksClientState.Created)}static createConnection(e,t){return new Promise((r,n)=>{try{(0,c.validateSocksClientOptions)(e,["connect"])}catch(e){return"function"==typeof t?(t(e),r(e)):n(e)}const i=new h(e);i.connect(e.existing_socket),i.once("established",e=>{i.removeAllListeners(),"function"==typeof t?(t(null,e),r(e)):r(e)}),i.once("error",e=>{i.removeAllListeners(),"function"==typeof t?(t(e),r(e)):n(e)})})}static createConnectionChain(e,t){return new Promise((r,i)=>n(this,void 0,void 0,function*(){try{(0,c.validateSocksClientChainOptions)(e)}catch(e){return"function"==typeof t?(t(e),r(e)):i(e)}e.randomizeChain&&(0,u.shuffleArray)(e.proxies);try{let n;for(let t=0;t<e.proxies.length;t++){const r=e.proxies[t],i=t===e.proxies.length-1?e.destination:{host:e.proxies[t+1].host||e.proxies[t+1].ipaddress,port:e.proxies[t+1].port},o=yield h.createConnection({command:"connect",proxy:r,destination:i,existing_socket:n});n=n||o.socket}"function"==typeof t?(t(null,{socket:n}),r({socket:n})):r({socket:n})}catch(e){"function"==typeof t?(t(e),r(e)):i(e)}}))}static createUDPFrame(e){const t=new s.SmartBuffer;return t.writeUInt16BE(0),t.writeUInt8(e.frameNumber||0),o.isIPv4(e.remoteHost.host)?(t.writeUInt8(a.Socks5HostType.IPv4),t.writeUInt32BE((0,c.ipv4ToInt32)(e.remoteHost.host))):o.isIPv6(e.remoteHost.host)?(t.writeUInt8(a.Socks5HostType.IPv6),t.writeBuffer((0,c.ipToBuffer)(e.remoteHost.host))):(t.writeUInt8(a.Socks5HostType.Hostname),t.writeUInt8(Buffer.byteLength(e.remoteHost.host)),t.writeString(e.remoteHost.host)),t.writeUInt16BE(e.remoteHost.port),t.writeBuffer(e.data),t.toBuffer()}static parseUDPFrame(e){const t=s.SmartBuffer.fromBuffer(e);t.readOffset=2;const r=t.readUInt8(),n=t.readUInt8();let i;i=n===a.Socks5HostType.IPv4?(0,c.int32ToIpv4)(t.readUInt32BE()):n===a.Socks5HostType.IPv6?d.Address6.fromByteArray(Array.from(t.readBuffer(16))).canonicalForm():t.readString(t.readUInt8());return{frameNumber:r,remoteHost:{host:i,port:t.readUInt16BE()},data:t.readBuffer()}}setState(e){this.state!==a.SocksClientState.Error&&(this.state=e)}connect(e){this.onDataReceived=e=>this.onDataReceivedHandler(e),this.onClose=()=>this.onCloseHandler(),this.onError=e=>this.onErrorHandler(e),this.onConnect=()=>this.onConnectHandler();const t=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||a.DEFAULT_TIMEOUT);t.unref&&"function"==typeof t.unref&&t.unref(),this.socket=e||new o.Socket,this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(a.SocksClientState.Connecting),this.receiveBuffer=new l.ReceiveBuffer,e?this.socket.emit("connect"):(this.socket.connect(this.getSocketOptions()),void 0!==this.options.set_tcp_nodelay&&null!==this.options.set_tcp_nodelay&&this.socket.setNoDelay(!!this.options.set_tcp_nodelay)),this.prependOnceListener("established",e=>{setImmediate(()=>{if(this.receiveBuffer.length>0){const t=this.receiveBuffer.get(this.receiveBuffer.length);e.socket.emit("data",t)}e.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){this.state!==a.SocksClientState.Established&&this.state!==a.SocksClientState.BoundWaitingForConnection&&this.closeSocket(a.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){this.setState(a.SocksClientState.Connected),4===this.options.proxy.type?this.sendSocks4InitialHandshake():this.sendSocks5InitialHandshake(),this.setState(a.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(e){this.receiveBuffer.append(e),this.processData()}processData(){for(;this.state!==a.SocksClientState.Established&&this.state!==a.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize;)if(this.state===a.SocksClientState.SentInitialHandshake)4===this.options.proxy.type?this.handleSocks4FinalHandshakeResponse():this.handleInitialSocks5HandshakeResponse();else if(this.state===a.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===a.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else{if(this.state!==a.SocksClientState.BoundWaitingForConnection){this.closeSocket(a.ERRORS.InternalError);break}4===this.options.proxy.type?this.handleSocks4IncomingConnectionResponse():this.handleSocks5IncomingConnectionResponse()}}onCloseHandler(){this.closeSocket(a.ERRORS.SocketClosed)}onErrorHandler(e){this.closeSocket(e.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(e){this.state!==a.SocksClientState.Error&&(this.setState(a.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new u.SocksClientError(e,this.options)))}sendSocks4InitialHandshake(){const e=this.options.proxy.userId||"",t=new s.SmartBuffer;t.writeUInt8(4),t.writeUInt8(a.SocksCommand[this.options.command]),t.writeUInt16BE(this.options.destination.port),o.isIPv4(this.options.destination.host)?(t.writeBuffer((0,c.ipToBuffer)(this.options.destination.host)),t.writeStringNT(e)):(t.writeUInt8(0),t.writeUInt8(0),t.writeUInt8(0),t.writeUInt8(1),t.writeStringNT(e),t.writeStringNT(this.options.destination.host)),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(t.toBuffer())}handleSocks4FinalHandshakeResponse(){const e=this.receiveBuffer.get(8);if(e[1]!==a.Socks4Response.Granted)this.closeSocket(`${a.ERRORS.Socks4ProxyRejectedConnection} - (${a.Socks4Response[e[1]]})`);else if(a.SocksCommand[this.options.command]===a.SocksCommand.bind){const t=s.SmartBuffer.fromBuffer(e);t.readOffset=2;const r={port:t.readUInt16BE(),host:(0,c.int32ToIpv4)(t.readUInt32BE())};"0.0.0.0"===r.host&&(r.host=this.options.proxy.ipaddress),this.setState(a.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:r,socket:this.socket})}else this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){const e=this.receiveBuffer.get(8);if(e[1]!==a.Socks4Response.Granted)this.closeSocket(`${a.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${a.Socks4Response[e[1]]})`);else{const t=s.SmartBuffer.fromBuffer(e);t.readOffset=2;const r={port:t.readUInt16BE(),host:(0,c.int32ToIpv4)(t.readUInt32BE())};this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket})}}sendSocks5InitialHandshake(){const e=new s.SmartBuffer,t=[a.Socks5Auth.NoAuth];(this.options.proxy.userId||this.options.proxy.password)&&t.push(a.Socks5Auth.UserPass),void 0!==this.options.proxy.custom_auth_method&&t.push(this.options.proxy.custom_auth_method),e.writeUInt8(5),e.writeUInt8(t.length);for(const r of t)e.writeUInt8(r);this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(e.toBuffer()),this.setState(a.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){const e=this.receiveBuffer.get(2);5!==e[0]?this.closeSocket(a.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion):e[1]===a.SOCKS5_NO_ACCEPTABLE_AUTH?this.closeSocket(a.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType):e[1]===a.Socks5Auth.NoAuth?(this.socks5ChosenAuthType=a.Socks5Auth.NoAuth,this.sendSocks5CommandRequest()):e[1]===a.Socks5Auth.UserPass?(this.socks5ChosenAuthType=a.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication()):e[1]===this.options.proxy.custom_auth_method?(this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication()):this.closeSocket(a.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){const e=this.options.proxy.userId||"",t=this.options.proxy.password||"",r=new s.SmartBuffer;r.writeUInt8(1),r.writeUInt8(Buffer.byteLength(e)),r.writeString(e),r.writeUInt8(Buffer.byteLength(t)),r.writeString(t),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(r.toBuffer()),this.setState(a.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return n(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(a.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(e){return n(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(e)})}handleSocks5AuthenticationNoAuthHandshakeResponse(e){return n(this,void 0,void 0,function*(){return 0===e[1]})}handleSocks5AuthenticationUserPassHandshakeResponse(e){return n(this,void 0,void 0,function*(){return 0===e[1]})}handleInitialSocks5AuthenticationHandshakeResponse(){return n(this,void 0,void 0,function*(){this.setState(a.SocksClientState.ReceivedAuthenticationResponse);let e=!1;this.socks5ChosenAuthType===a.Socks5Auth.NoAuth?e=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===a.Socks5Auth.UserPass?e=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===this.options.proxy.custom_auth_method&&(e=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size))),e?this.sendSocks5CommandRequest():this.closeSocket(a.ERRORS.Socks5AuthenticationFailed)})}sendSocks5CommandRequest(){const e=new s.SmartBuffer;e.writeUInt8(5),e.writeUInt8(a.SocksCommand[this.options.command]),e.writeUInt8(0),o.isIPv4(this.options.destination.host)?(e.writeUInt8(a.Socks5HostType.IPv4),e.writeBuffer((0,c.ipToBuffer)(this.options.destination.host))):o.isIPv6(this.options.destination.host)?(e.writeUInt8(a.Socks5HostType.IPv6),e.writeBuffer((0,c.ipToBuffer)(this.options.destination.host))):(e.writeUInt8(a.Socks5HostType.Hostname),e.writeUInt8(this.options.destination.host.length),e.writeString(this.options.destination.host)),e.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(e.toBuffer()),this.setState(a.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){const e=this.receiveBuffer.peek(5);if(5!==e[0]||e[1]!==a.Socks5Response.Granted)this.closeSocket(`${a.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${a.Socks5Response[e[1]]}`);else{const t=e[3];let r,n;if(t===a.Socks5HostType.IPv4){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:(0,c.int32ToIpv4)(n.readUInt32BE()),port:n.readUInt16BE()},"0.0.0.0"===r.host&&(r.host=this.options.proxy.ipaddress)}else if(t===a.Socks5HostType.Hostname){const t=e[4],i=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(t);if(this.receiveBuffer.length<i)return void(this.nextRequiredPacketBufferSize=i);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(i).slice(5)),r={host:n.readString(t),port:n.readUInt16BE()}}else if(t===a.Socks5HostType.IPv6){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:d.Address6.fromByteArray(Array.from(n.readBuffer(16))).canonicalForm(),port:n.readUInt16BE()}}this.setState(a.SocksClientState.ReceivedFinalResponse),a.SocksCommand[this.options.command]===a.SocksCommand.connect?(this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket})):a.SocksCommand[this.options.command]===a.SocksCommand.bind?(this.setState(a.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:r,socket:this.socket})):a.SocksCommand[this.options.command]===a.SocksCommand.associate&&(this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket}))}}handleSocks5IncomingConnectionResponse(){const e=this.receiveBuffer.peek(5);if(5!==e[0]||e[1]!==a.Socks5Response.Granted)this.closeSocket(`${a.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${a.Socks5Response[e[1]]}`);else{const t=e[3];let r,n;if(t===a.Socks5HostType.IPv4){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:(0,c.int32ToIpv4)(n.readUInt32BE()),port:n.readUInt16BE()},"0.0.0.0"===r.host&&(r.host=this.options.proxy.ipaddress)}else if(t===a.Socks5HostType.Hostname){const t=e[4],i=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(t);if(this.receiveBuffer.length<i)return void(this.nextRequiredPacketBufferSize=i);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(i).slice(5)),r={host:n.readString(t),port:n.readUInt16BE()}}else if(t===a.Socks5HostType.IPv6){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:d.Address6.fromByteArray(Array.from(n.readBuffer(16))).canonicalForm(),port:n.readUInt16BE()}}this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}t.SocksClient=h},7687(e,t,r){"use strict";const n=r(857),i=r(2018),o=r(5884),{env:s}=process;let a;function c(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(0===a)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(e&&!t&&void 0===a)return 0;const r=a||0;if("dumb"===s.TERM)return r;if("win32"===process.platform){const e=n.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in s)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(e=>e in s)||"codeship"===s.CI_NAME?1:r;if("TEAMCITY_VERSION"in s)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(s.TEAMCITY_VERSION)?1:0;if("truecolor"===s.COLORTERM)return 3;if("TERM_PROGRAM"in s){const e=parseInt((s.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(s.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(s.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(s.TERM)||"COLORTERM"in s?1:r}o("no-color")||o("no-colors")||o("color=false")||o("color=never")?a=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(a=1),"FORCE_COLOR"in s&&(a="true"===s.FORCE_COLOR?1:"false"===s.FORCE_COLOR?0:0===s.FORCE_COLOR.length?1:Math.min(parseInt(s.FORCE_COLOR,10),3)),e.exports={supportsColor:function(e){return c(l(e,e&&e.isTTY))},stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}},7699(e,t,r){"use strict";const n=r(1060);n.createWebSocketStream=r(3719),n.Server=r(1722),n.Receiver=r(6286),n.Sender=r(914),n.WebSocket=n,n.WebSocketServer=n.Server,e.exports=n},7732(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=r(8600),c=s(r(6887)),l={set:a.setInterval,clear:a.clearInterval},u={set:(e,t)=>setInterval(e,t),clear:e=>clearInterval(e)};t.default=e=>{switch(e){case"native":return u;case"worker":return l;default:return!c.default||c.isWebWorker||c.isReactNativeBrowser?u:l}}},7736(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReceiveBuffer=void 0;t.ReceiveBuffer=class{constructor(e=4096){this.buffer=Buffer.allocUnsafe(e),this.offset=0,this.originalSize=e}get length(){return this.offset}append(e){if(!Buffer.isBuffer(e))throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+e.length>=this.buffer.length){const t=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+e.length)),t.copy(this.buffer)}return e.copy(this.buffer,this.offset),this.offset+=e.length}peek(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,e)}get(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");const t=Buffer.allocUnsafe(e);return this.buffer.slice(0,e).copy(t),this.buffer.copyWithin(0,e,e+this.offset-e),this.offset-=e,t}}},7758(e,t,r){const n=r(4422),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(4134),c=r(6238),{once:l}=r(7760),u=r(5896),d=r(3370),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:f,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:m,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:y}=r(6371),{validateFunction:_,validateAbortSignal:v}=r(277),{isIterable:S,isReadable:w,isReadableNodeStream:k,isNodeStream:E,isTransformStream:I,isWebStream:T,isReadableStream:O,isReadableFinished:C}=r(6115),A=globalThis.AbortController||r(6584).AbortController;let x,P,R;function M(e,t,r){let n=!1;e.on("close",()=>{n=!0});return{destroy:t=>{n||(n=!0,u.destroyer(e,t||new m("pipe")))},cleanup:c(e,{readable:t,writable:r},e=>{n=!e})}}function B(e){if(S(e))return e;if(k(e))return async function*(e){P||(P=r(7576));yield*P.prototype[s].call(e)}(e);throw new p("val",["Readable","Iterable","AsyncIterable"],e)}async function N(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o((e,t)=>{i?t(i):s=()=>{i?t(i):e()}});t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function j(e,t,r,{end:n}){I(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function D(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new A,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){F(new y)}let m,b,_;v(l,"options.signal"),R=R||r(7760).addAbortListener,l&&(m=R(l,h));const C=[];let P,D=0;function U(e){F(e,0===--D)}function F(e,r){var i;if(!e||b&&"ERR_STREAM_PREMATURE_CLOSE"!==b.code||(b=e),b||r){for(;C.length;)C.shift()(b);null===(i=m)||void 0===i||i[a](),s.abort(),r&&(b||u.forEach(e=>e()),n.nextTick(t,b,_))}}for(let H=0;H<e.length;H++){const z=e[H],q=H<e.length-1,G=H>0,K=q||!1!==(null==o?void 0:o.end),Q=H===e.length-1;if(E(z)){if(K){const{destroy:Y,cleanup:Z}=M(z,q,G);C.push(Y),w(z)&&Q&&u.push(Z)}function $(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&U(e)}z.on("error",$),w(z)&&Q&&u.push(()=>{z.removeListener("error",$)})}if(0===H)if("function"==typeof z){if(P=z({signal:c}),!S(P))throw new f("Iterable, AsyncIterable or Stream","source",P)}else P=S(z)||k(z)||I(z)?z:d.from(z);else if("function"==typeof z){var V;if(I(P))P=B(null===(V=P)||void 0===V?void 0:V.readable);else P=B(P);if(P=z(P,{signal:c}),q){if(!S(P,!0))throw new f("AsyncIterable",`transform[${H-1}]`,P)}else{var W;x||(x=r(6524));const J=new x({objectMode:!0}),X=null===(W=P)||void 0===W?void 0:W.then;if("function"==typeof X)D++,X.call(P,e=>{_=e,null!=e&&J.write(e),K&&J.end(),n.nextTick(U)},e=>{J.destroy(e),n.nextTick(U,e)});else if(S(P,!0))D++,N(P,J,U,{end:K});else{if(!O(P)&&!I(P))throw new f("AsyncIterable or Promise","destination",P);{const re=P.readable||P;D++,N(re,J,U,{end:K})}}P=J;const{destroy:ee,cleanup:te}=M(P,!1,!0);C.push(ee),Q&&u.push(te)}}else if(E(z)){if(k(P)){D+=2;const ne=L(P,z,U,{end:K});w(z)&&Q&&u.push(ne)}else if(I(P)||O(P)){const ie=P.readable||P;D++,N(ie,z,U,{end:K})}else{if(!S(P))throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],P);D++,N(P,z,U,{end:K})}P=z}else if(T(z)){if(k(P))D++,j(B(P),z,U,{end:K});else if(O(P)||S(P))D++,j(P,z,U,{end:K});else{if(!I(P))throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],P);D++,j(P.readable,z,U,{end:K})}P=z}else P=d.from(z)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),P}function L(e,t,r,{end:i}){let o=!1;if(t.on("close",()=>{o||r(new b)}),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}C(e)?n.nextTick(s):e.once("end",s)}else r();return c(e,{readable:!0,writable:!1},t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)}),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:D,pipeline:function(...e){return D(e,l(function(e){return _(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},7760(e,t,r){"use strict";const n=r(181),{format:i,inspect:o}=r(9231),{codes:{ERR_INVALID_ARG_TYPE:s}}=r(6371),{kResistStopPropagation:a,AggregateError:c,SymbolDispose:l}=r(4134),u=globalThis.AbortSignal||r(6584).AbortSignal,d=globalThis.AbortController||r(6584).AbortController,h=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||n.Blob,f="undefined"!=typeof p?function(e){return e instanceof p}:function(e){return!1},g=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new s(t,"AbortSignal",e)};e.exports={AggregateError:c,kEmptyObject:Object.freeze({}),once(e){let t=!1;return function(...r){t||(t=!0,e.apply(this,r))}},createDeferredPromise:function(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}},promisify:e=>new Promise((t,r)=>{e((e,...n)=>e?r(e):t(...n))}),debuglog:()=>function(){},format:i,inspect:o,types:{isAsyncFunction:e=>e instanceof h,isArrayBufferView:e=>ArrayBuffer.isView(e)},isBlob:f,deprecate:(e,t)=>e,addAbortListener:r(4434).addAbortListener||function(e,t){if(void 0===e)throw new s("signal","AbortSignal",e);let r;return g(e,"signal"),((e,t)=>{if("function"!=typeof e)throw new s(t,"Function",e)})(t,"listener"),e.aborted?queueMicrotask(()=>t()):(e.addEventListener("abort",t,{__proto__:null,once:!0,[a]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[l](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:u.any||function(e){if(1===e.length)return e[0];const t=new d,r=()=>t.abort();return e.forEach(e=>{g(e,"signals"),e.addEventListener("abort",r,{once:!0})}),t.signal.addEventListener("abort",()=>{e.forEach(e=>e.removeEventListener("abort",r))},{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},7813(e,t,r){"use strict";const{Buffer:n}=r(181),i=Symbol.for("BufferList");function o(e){if(!(this instanceof o))return new o(e);o._init.call(this,e)}o._init=function(e){Object.defineProperty(this,i,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},o.prototype._new=function(e){return new o(e)},o.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let r=0;r<this._bufs.length;r++){const n=t+this._bufs[r].length;if(e<n||r===this._bufs.length-1)return[r,e-t];t=n}},o.prototype._reverseOffset=function(e){const t=e[0];let r=e[1];for(let e=0;e<t;e++)r+=this._bufs[e].length;return r},o.prototype.getBuffers=function(){return this._bufs},o.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},o.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},o.prototype.copy=function(e,t,r,i){if(("number"!=typeof r||r<0)&&(r=0),("number"!=typeof i||i>this.length)&&(i=this.length),r>=this.length)return e||n.alloc(0);if(i<=0)return e||n.alloc(0);const o=!!e,s=this._offset(r),a=i-r;let c=a,l=o&&t||0,u=s[1];if(0===r&&i===this.length){if(!o)return 1===this._bufs.length?this._bufs[0]:n.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,l),l+=this._bufs[t].length;return e}if(c<=this._bufs[s[0]].length-u)return o?this._bufs[s[0]].copy(e,t,u,u+c):this._bufs[s[0]].slice(u,u+c);o||(e=n.allocUnsafe(a));for(let t=s[0];t<this._bufs.length;t++){const r=this._bufs[t].length-u;if(!(c>r)){this._bufs[t].copy(e,l,u,u+c),l+=r;break}this._bufs[t].copy(e,l,u),l+=r,c-=r,u&&(u=0)}return e.length>l?e.slice(0,l):e},o.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const r=this._offset(e),n=this._offset(t),i=this._bufs.slice(r[0],n[0]+1);return 0===n[1]?i.pop():i[i.length-1]=i[i.length-1].slice(0,n[1]),0!==r[1]&&(i[0]=i[0].slice(r[1])),this._new(i)},o.prototype.toString=function(e,t,r){return this.slice(t,r).toString(e)},o.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},o.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},o.prototype.append=function(e){return this._attach(e,o.prototype._appendBuffer)},o.prototype.prepend=function(e){return this._attach(e,o.prototype._prependBuffer,!0)},o.prototype._attach=function(e,t,r){if(null==e)return this;if(e.buffer)t.call(this,n.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e)){const[n,i]=r?[e.length-1,-1]:[0,1];for(let o=n;o>=0&&o<e.length;o+=i)this._attach(e[o],t,r)}else if(this._isBufferList(e)){const[n,i]=r?[e._bufs.length-1,-1]:[0,1];for(let o=n;o>=0&&o<e._bufs.length;o+=i)this._attach(e._bufs[o],t,r)}else"number"==typeof e&&(e=e.toString()),t.call(this,n.from(e));return this},o.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},o.prototype._prependBuffer=function(e){this._bufs.unshift(e),this.length+=e.length},o.prototype.indexOf=function(e,t,r){if(void 0===r&&"string"==typeof t&&(r=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=n.from([e]):"string"==typeof e?e=n.from(e,r):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=n.from(e.buffer,e.byteOffset,e.byteLength):n.isBuffer(e)||(e=n.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const i=this._offset(t);let o=i[0],s=i[1];for(;o<this._bufs.length;o++){const t=this._bufs[o];for(;s<t.length;){if(t.length-s>=e.length){const r=t.indexOf(e,s);if(-1!==r)return this._reverseOffset([o,r]);s=t.length-e.length+1}else{const t=this._reverseOffset([o,s]);if(this._match(t,e))return t;s++}}s=0}return-1},o.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let r=0;r<t.length;r++)if(this.get(e+r)!==t[r])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)(function(t){o.prototype[t]=null===e[t]?function(e,r){return this.slice(e,e+r)[t](0,r)}:function(r=0){return this.slice(r,r+e[t])[t](0)}})(t)}(),o.prototype._isBufferList=function(e){return e instanceof o||o.isBufferList(e)},o.isBufferList=function(e){return null!=e&&e[i]},e.exports=o},7830(e,t,r){"use strict";const{pipeline:n}=r(7758),i=r(3370),{destroyer:o}=r(5896),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(6115),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:f,ERR_MISSING_ARGS:g}}=r(6371),m=r(6238);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r<e.length;++r)if(s(e[r])||l(e[r])){if(r<e.length-1&&!(a(e[r])||h(e[r])||u(e[r])))throw new f(`streams[${r}]`,t[r],"must be readable");if(r>0&&!(c(e[r])||d(e[r])||u(e[r])))throw new f(`streams[${r}]`,t[r],"must be writable")}let r,b,y,_,v;const S=e[0],w=n(e,function(e){const t=_;_=null,t?t(e):e?v.destroy(e):E||k||v.destroy()}),k=!!(c(S)||d(S)||u(S)),E=!!(a(w)||h(w)||u(w));if(v=new i({writableObjectMode:!(null==S||!S.writableObjectMode),readableObjectMode:!(null==w||!w.readableObjectMode),writable:k,readable:E}),k){if(s(S))v._write=function(e,t,n){S.write(e,t)?n():r=n},v._final=function(e){S.end(),b=e},S.on("drain",function(){if(r){const e=r;r=null,e()}});else if(l(S)){const e=(u(S)?S.writable:S).getWriter();v._write=async function(t,r,n){try{await e.ready,e.write(t).catch(()=>{}),n()}catch(e){n(e)}},v._final=async function(t){try{await e.ready,e.close().catch(()=>{}),b=t}catch(e){t(e)}}}const e=u(w)?w.readable:w;m(e,()=>{if(b){const e=b;b=null,e()}})}if(E)if(s(w))w.on("readable",function(){if(y){const e=y;y=null,e()}}),w.on("end",function(){v.push(null)}),v._read=function(){for(;;){const e=w.read();if(null===e)return void(y=v._read);if(!v.push(e))return}};else if(l(w)){const e=(u(w)?w.readable:w).getReader();v._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!v.push(t))return;if(r)return void v.push(null)}catch{return}}}return v._destroy=function(e,t){e||null===_||(e=new p),y=null,r=null,b=null,null===_?t(e):(_=t,s(w)&&o(w,e))},v}},7833(e,t,r){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},7927(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.SpatialAwarenessPlugin=void 0;const a=s(r(7562)),c=r(6117),l=r(1554),u=r(4997),d=r(5389),h=r(7136),p=r(4386),f=r(5471),g=r(2846),m=r(7279),b=r(3874),{deviceManager:y,systemManager:_}=a.default,v="tracking-zone:",S="global-tracker";class w extends a.ScryptedDeviceBase{trackingEngine=null;trackingState;alertManager;mqttPublisher=null;devices=new Map;storageSettings=new c.StorageSettings(this,{topology:{title:"Camera Topology",type:"string",description:"JSON configuration of camera relationships",hide:!0},floorPlanImage:{title:"Floor Plan Image",type:"string",hide:!0},correlationWindow:{title:"Correlation Window (seconds)",type:"number",defaultValue:30,description:"Maximum time to wait for an object to appear on connected camera",group:"Tracking"},correlationThreshold:{title:"Correlation Confidence Threshold",type:"number",defaultValue:.6,description:"Minimum confidence (0-1) for automatic object correlation",group:"Tracking"},lostTimeout:{title:"Lost Object Timeout (seconds)",type:"number",defaultValue:300,description:"Time before marking a tracked object as lost",group:"Tracking"},useVisualMatching:{title:"Use Visual Matching",type:"boolean",defaultValue:!0,description:"Use visual embeddings for object correlation (requires compatible detectors)",group:"Tracking"},enableMqtt:{title:"Enable MQTT",type:"boolean",defaultValue:!1,group:"MQTT Integration"},mqttBroker:{title:"MQTT Broker URL",type:"string",placeholder:"mqtt://localhost:1883",group:"MQTT Integration"},mqttUsername:{title:"MQTT Username",type:"string",group:"MQTT Integration"},mqttPassword:{title:"MQTT Password",type:"password",group:"MQTT Integration"},mqttBaseTopic:{title:"MQTT Base Topic",type:"string",defaultValue:"scrypted/spatial-awareness",group:"MQTT Integration"},enableAlerts:{title:"Enable Alerts",type:"boolean",defaultValue:!0,group:"Alerts"},defaultNotifier:{title:"Default Notifier",type:"device",deviceFilter:`interfaces.includes('${a.ScryptedInterface.Notifier}')`,group:"Alerts"},trackedCameras:{title:"Cameras to Track",type:"device",multiple:!0,deviceFilter:`interfaces.includes('${a.ScryptedInterface.ObjectDetector}')`,group:"Cameras",description:"Select cameras with object detection to track"},alertRules:{title:"Alert Rules",type:"string",hide:!0}});constructor(e){super(e),this.trackingState=new d.TrackingState(this.storage,this.console),this.alertManager=new p.AlertManager(this.console,this.storage),process.nextTick(()=>this.initialize())}async initialize(){this.console.log("Initializing Spatial Awareness Plugin"),await y.onDeviceDiscovered({nativeId:S,name:"Global Object Tracker",type:a.ScryptedDeviceType.Sensor,interfaces:[a.ScryptedInterface.OccupancySensor,a.ScryptedInterface.Settings,a.ScryptedInterface.Readme]});const e=this.storage.getItem("topology");if(e)try{const t=JSON.parse(e);await this.startTrackingEngine(t)}catch(e){this.console.error("Failed to parse topology:",e)}const t=this.storage.getItem("alertRules");if(t)try{const e=JSON.parse(t);this.alertManager.setRules(e)}catch(e){this.console.error("Failed to parse alert rules:",e),this.alertManager.setRules((0,u.createDefaultRules)())}else this.alertManager.setRules((0,u.createDefaultRules)());this.storageSettings.values.enableMqtt&&await this.initializeMqtt(),this.console.log("Spatial Awareness Plugin initialized")}async initializeMqtt(){const e=this.storageSettings.values.mqttBroker;if(!e)return void this.console.warn("MQTT enabled but no broker URL configured");const t={broker:e,username:this.storageSettings.values.mqttUsername,password:this.storageSettings.values.mqttPassword,baseTopic:this.storageSettings.values.mqttBaseTopic||"scrypted/spatial-awareness"};this.mqttPublisher=new m.MqttPublisher(t,this.console),await this.mqttPublisher.connect(),this.trackingState.onStateChange(e=>{this.mqttPublisher?.publishState(e)}),this.console.log("MQTT publisher initialized")}async startTrackingEngine(e){this.trackingEngine&&await this.trackingEngine.stopTracking();const t={correlationWindow:1e3*(this.storageSettings.values.correlationWindow||30),correlationThreshold:this.storageSettings.values.correlationThreshold||.6,lostTimeout:1e3*(this.storageSettings.values.lostTimeout||300),useVisualMatching:this.storageSettings.values.useVisualMatching??!0};this.trackingEngine=new h.TrackingEngine(e,this.trackingState,this.alertManager,t,this.console),await this.trackingEngine.startTracking(),this.console.log("Tracking engine started")}async getDevice(e){let t=this.devices.get(e);return t||(e===S?t=new f.GlobalTrackerSensor(this,e,this.trackingState):e.startsWith(v)&&(t=new g.TrackingZone(this,e,this.trackingState)),t&&this.devices.set(e,t)),t}async releaseDevice(e,t){this.devices.delete(t)}async getCreateDeviceSettings(){return[{key:"name",title:"Zone Name",description:"Name for this tracking zone",type:"string"},{key:"type",title:"Zone Type",type:"string",choices:["entry","exit","dwell","restricted"],value:"entry"},{key:"cameras",title:"Cameras",type:"device",multiple:!0,deviceFilter:`interfaces.includes('${a.ScryptedInterface.ObjectDetector}')`}]}async createDevice(e){const t=v+Date.now().toString();return await y.onDeviceDiscovered({nativeId:t,name:e.name||"Tracking Zone",type:a.ScryptedDeviceType.Sensor,interfaces:[a.ScryptedInterface.OccupancySensor,a.ScryptedInterface.MotionSensor,a.ScryptedInterface.Settings]}),this.storage.setItem(`zone:${t}`,JSON.stringify({type:e.type,cameras:e.cameras})),t}async getSettings(){const e=await this.storageSettings.getSettings();e.push({key:"topologyEditor",title:"Topology Editor",type:"html",value:'<iframe src="/endpoint/@blueharford/scrypted-spatial-awareness/ui/editor" style="width: 100%; height: 600px; border: none; border-radius: 8px; background: #1a1a2e;"></iframe>',group:"Topology"});const t=this.trackingState.getActiveCount();e.push({key:"status",title:"Tracking Status",type:"string",readonly:!0,value:this.trackingEngine?`Active: Tracking ${t} object${1!==t?"s":""}`:"Not configured - add cameras and configure topology",group:"Status"});const r=this.alertManager.getRecentAlerts(5);return r.length>0&&e.push({key:"recentAlerts",title:"Recent Alerts",type:"string",readonly:!0,value:r.map(e=>`${e.type}: ${e.message}`).join("\n"),group:"Status"}),e}async putSetting(e,t){if(await this.storageSettings.putSetting(e,t),"trackedCameras"===e||"correlationWindow"===e||"correlationThreshold"===e||"lostTimeout"===e||"useVisualMatching"===e){const e=this.storage.getItem("topology");if(e)try{const t=JSON.parse(e);await this.startTrackingEngine(t)}catch(e){this.console.error("Failed to restart tracking engine:",e)}}"enableMqtt"!==e&&"mqttBroker"!==e&&"mqttUsername"!==e&&"mqttPassword"!==e&&"mqttBaseTopic"!==e||(this.mqttPublisher&&(this.mqttPublisher.disconnect(),this.mqttPublisher=null),this.storageSettings.values.enableMqtt&&await this.initializeMqtt())}async onRequest(e,t){const r=new URL(e.url,"http://localhost").pathname;try{if(r.endsWith("/api/tracked-objects"))return this.handleTrackedObjectsRequest(e,t);if(r.match(/\/api\/journey\/[\w-]+$/)){const e=r.split("/").pop();return this.handleJourneyRequest(e,t)}if(r.endsWith("/api/topology"))return this.handleTopologyRequest(e,t);if(r.endsWith("/api/alerts"))return this.handleAlertsRequest(e,t);if(r.endsWith("/api/floor-plan"))return this.handleFloorPlanRequest(e,t);if(r.endsWith("/ui/editor")||r.endsWith("/ui/editor/"))return this.serveEditorUI(t);if(r.includes("/ui/"))return this.serveStaticFile(r,t);t.send(JSON.stringify({name:"Spatial Awareness Plugin",version:"0.1.0",endpoints:{api:{trackedObjects:"/api/tracked-objects",journey:"/api/journey/{globalId}",topology:"/api/topology",alerts:"/api/alerts",floorPlan:"/api/floor-plan"},ui:{editor:"/ui/editor"}}}),{headers:{"Content-Type":"application/json"}})}catch(e){this.console.error("HTTP request error:",e),t.send(JSON.stringify({error:e.message}),{code:500,headers:{"Content-Type":"application/json"}})}}handleTrackedObjectsRequest(e,t){const r=this.trackingState.getAllObjects();t.send(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}handleJourneyRequest(e,t){const r=this.trackingState.getObject(e);r?t.send(JSON.stringify({globalId:r.globalId,className:r.className,label:r.label,journey:r.journey,sightings:r.sightings.map(e=>({cameraId:e.cameraId,cameraName:e.cameraName,timestamp:e.timestamp})),firstSeen:r.firstSeen,lastSeen:r.lastSeen,state:r.state}),{headers:{"Content-Type":"application/json"}}):t.send(JSON.stringify({error:"Object not found"}),{code:404,headers:{"Content-Type":"application/json"}})}handleTopologyRequest(e,t){if("GET"===e.method){const e=this.storage.getItem("topology"),r=e?JSON.parse(e):(0,l.createEmptyTopology)();t.send(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}else if("PUT"===e.method||"POST"===e.method)try{const r=JSON.parse(e.body);this.storage.setItem("topology",JSON.stringify(r)),this.startTrackingEngine(r),t.send(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(e){t.send(JSON.stringify({error:"Invalid topology JSON"}),{code:400,headers:{"Content-Type":"application/json"}})}}handleAlertsRequest(e,t){const r=this.alertManager.getRecentAlerts();t.send(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}handleFloorPlanRequest(e,t){if("GET"===e.method){const e=this.storage.getItem("floorPlanImage");e?t.send(JSON.stringify({imageData:e}),{headers:{"Content-Type":"application/json"}}):t.send(JSON.stringify({imageData:null}),{headers:{"Content-Type":"application/json"}})}else if("POST"===e.method)try{const r=JSON.parse(e.body);this.storage.setItem("floorPlanImage",r.imageData),t.send(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(e){t.send(JSON.stringify({error:"Invalid request body"}),{code:400,headers:{"Content-Type":"application/json"}})}}serveEditorUI(e){e.send(b.EDITOR_HTML,{headers:{"Content-Type":"text/html"}})}serveStaticFile(e,t){t.send("Not found",{code:404})}async getReadmeMarkdown(){return"\n# Spatial Awareness Plugin\n\nThis plugin enables cross-camera object tracking across your entire NVR system.\n\n## Features\n\n- **Cross-Camera Tracking**: Correlate objects as they move between cameras\n- **Journey History**: Complete path history for each tracked object\n- **Entry/Exit Detection**: Know when objects enter or leave your property\n- **Visual Floor Plan**: Configure camera topology with a visual editor\n- **MQTT Integration**: Export tracking data to Home Assistant\n- **REST API**: Query tracked objects and journeys programmatically\n- **Smart Alerts**: Get notified about property entry/exit, unusual paths, and more\n\n## Setup\n\n1. **Add Cameras**: Select cameras with object detection in the plugin settings\n2. **Configure Topology**: Define camera relationships and transit times\n3. **Enable Integrations**: Optionally enable MQTT for Home Assistant\n4. **Create Zones**: Add tracking zones for specific area monitoring\n\n## API Endpoints\n\n- `GET /api/tracked-objects` - List all tracked objects\n- `GET /api/journey/{id}` - Get journey for specific object\n- `GET /api/topology` - Get camera topology\n- `PUT /api/topology` - Update camera topology\n- `GET /api/alerts` - Get recent alerts\n\n## Visual Editor\n\nAccess the visual topology editor at `/ui/editor` to configure camera relationships using a floor plan.\n\n## Alert Types\n\n- **Property Entry**: Object entered the property\n- **Property Exit**: Object exited the property\n- **Unusual Path**: Object took an unexpected route\n- **Dwell Time**: Object lingered too long in an area\n- **Restricted Zone**: Object entered a restricted area\n"}getTrackingState(){return this.trackingState}getAlertManager(){return this.alertManager}getTopology(){const e=this.storage.getItem("topology");return e?JSON.parse(e):null}}t.SpatialAwarenessPlugin=w,t.default=w},7969(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(4478),i={objectMode:!0},o={clean:!0};t.default=class{options;_inflights;constructor(e){this.options=e||{},this.options={...o,...e},this._inflights=new Map}put(e,t){return this._inflights.set(e.messageId,e),t&&t(),this}createStream(){const e=new n.Readable(i),t=[];let r=!1,o=0;return this._inflights.forEach((e,r)=>{t.push(e)}),e._read=()=>{!r&&o<t.length?e.push(t[o++]):e.push(null)},e.destroy=t=>{if(!r)return r=!0,setTimeout(()=>{e.emit("close")},0),e},e}del(e,t){const r=this._inflights.get(e.messageId);return r?(this._inflights.delete(e.messageId),t(null,r)):t&&t(new Error("missing packet")),this}get(e,t){const r=this._inflights.get(e.messageId);return r?t(null,r):t&&t(new Error("missing packet")),this}close(e){this.options.clean&&(this._inflights=null),e&&e()}}},8194(e,t,r){"use strict";r.d(t,{CD:()=>S});var n,i=(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=function(){function e(e,t){this.ee=1,this.u=void 0,this.p=void 0,this.K=void 0,this.N=void 0,this.rr=void 0,this.u=e,this.p=t}return e.prototype.L=function(){var e=this;if(1===e.ee&&e.rr.rr===e)e=e.N;else if(e.K)for(e=e.K;e.N;)e=e.N;else{for(var t=e.rr;t.K===e;)t=(e=t).rr;e=t}return e},e.prototype.m=function(){var e=this;if(e.N){for(e=e.N;e.K;)e=e.K;return e}for(var t=e.rr;t.N===e;)t=(e=t).rr;return e.N!==t?t:e},e.prototype.ne=function(){var e=this.rr,t=this.N,r=t.K;return e.rr===this?e.rr=t:e.K===this?e.K=t:e.N=t,t.rr=e,t.K=this,this.rr=t,this.N=r,r&&(r.rr=this),t},e.prototype.te=function(){var e=this.rr,t=this.K,r=t.N;return e.rr===this?e.rr=t:e.K===this?e.K=t:e.N=t,t.rr=e,t.N=this,this.rr=t,this.K=r,r&&(r.rr=this),t},e}(),s=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.tr=1,t}return i(t,e),t.prototype.ne=function(){var t=e.prototype.ne.call(this);return this.ie(),t.ie(),t},t.prototype.te=function(){var t=e.prototype.te.call(this);return this.ie(),t.ie(),t},t.prototype.ie=function(){this.tr=1,this.K&&(this.tr+=this.K.tr),this.N&&(this.tr+=this.N.tr)},t}(o),a=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),c=function(){function e(e){void 0===e&&(e=0),this.iteratorType=e}return e.prototype.equals=function(e){return this.o===e.o},e}(),l=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t}(function(){function e(){this.M=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this.M},enumerable:!1,configurable:!0}),e.prototype.size=function(){return this.M},e.prototype.empty=function(){return 0===this.M},e}());function u(){throw new RangeError("Iterator access denied!")}var d=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),h=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},p=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};const f=function(e){function t(t,r){void 0===t&&(t=function(e,t){return e<t?-1:e>t?1:0}),void 0===r&&(r=!1);var n=e.call(this)||this;return n.W=void 0,n.$=t,r?(n.re=s,n.v=function(e,t,r){var n=this.se(e,t,r);if(n){for(var i=n.rr;i!==this.h;)i.tr+=1,i=i.rr;var o=this.fe(n);if(o){var s=o,a=s.parentNode,c=s.grandParent,l=s.curNode;a.ie(),c.ie(),l.ie()}}return this.M},n.G=function(e){for(var t=this.he(e);t!==this.h;)t.tr-=1,t=t.rr}):(n.re=o,n.v=function(e,t,r){var n=this.se(e,t,r);return n&&this.fe(n),this.M},n.G=n.he),n.h=new n.re,n}return d(t,e),t.prototype.U=function(e,t){for(var r=this.h;e;){var n=this.$(e.u,t);if(n<0)e=e.N;else{if(!(n>0))return e;r=e,e=e.K}}return r},t.prototype.X=function(e,t){for(var r=this.h;e;){this.$(e.u,t)<=0?e=e.N:(r=e,e=e.K)}return r},t.prototype.Y=function(e,t){for(var r=this.h;e;){var n=this.$(e.u,t);if(n<0)r=e,e=e.N;else{if(!(n>0))return e;e=e.K}}return r},t.prototype.Z=function(e,t){for(var r=this.h;e;){this.$(e.u,t)<0?(r=e,e=e.N):e=e.K}return r},t.prototype.ue=function(e){for(;;){var t,r=e.rr;if(r===this.h)return;if(1===e.ee)return void(e.ee=0);if(e===r.K)if(1===(t=r.N).ee)t.ee=0,r.ee=1,r===this.W?this.W=r.ne():r.ne();else{if(t.N&&1===t.N.ee)return t.ee=r.ee,r.ee=0,t.N.ee=0,void(r===this.W?this.W=r.ne():r.ne());t.K&&1===t.K.ee?(t.ee=1,t.K.ee=0,t.te()):(t.ee=1,e=r)}else if(1===(t=r.K).ee)t.ee=0,r.ee=1,r===this.W?this.W=r.te():r.te();else{if(t.K&&1===t.K.ee)return t.ee=r.ee,r.ee=0,t.K.ee=0,void(r===this.W?this.W=r.te():r.te());t.N&&1===t.N.ee?(t.ee=1,t.N.ee=0,t.ne()):(t.ee=1,e=r)}}},t.prototype.he=function(e){var t,r;if(1===this.M)return this.clear(),this.h;for(var n=e;n.K||n.N;){if(n.N)for(n=n.N;n.K;)n=n.K;else n=n.K;t=h([n.u,e.u],2),e.u=t[0],n.u=t[1],r=h([n.p,e.p],2),e.p=r[0],n.p=r[1],e=n}this.h.K===n?this.h.K=n.rr:this.h.N===n&&(this.h.N=n.rr),this.ue(n);var i=n.rr;return n===i.K?i.K=void 0:i.N=void 0,this.M-=1,this.W.ee=0,i},t.prototype.ae=function(e,t){return void 0!==e&&(!!this.ae(e.K,t)||(!!t(e)||this.ae(e.N,t)))},t.prototype.fe=function(e){for(;;){var t=e.rr;if(0===t.ee)return;var r=t.rr;if(t===r.K){if((n=r.N)&&1===n.ee){if(n.ee=t.ee=0,r===this.W)return;r.ee=1,e=r;continue}if(e===t.N){if(e.ee=0,e.K&&(e.K.rr=t),e.N&&(e.N.rr=r),t.N=e.K,r.K=e.N,e.K=t,e.N=r,r===this.W)this.W=e,this.h.rr=e;else(i=r.rr).K===r?i.K=e:i.N=e;return e.rr=r.rr,t.rr=e,r.rr=e,r.ee=1,{parentNode:t,grandParent:r,curNode:e}}t.ee=0,r===this.W?this.W=r.te():r.te(),r.ee=1}else{var n;if((n=r.K)&&1===n.ee){if(n.ee=t.ee=0,r===this.W)return;r.ee=1,e=r;continue}if(e===t.K){var i;if(e.ee=0,e.K&&(e.K.rr=r),e.N&&(e.N.rr=t),r.N=e.K,t.K=e.N,e.K=r,e.N=t,r===this.W)this.W=e,this.h.rr=e;else(i=r.rr).K===r?i.K=e:i.N=e;return e.rr=r.rr,t.rr=e,r.rr=e,r.ee=1,{parentNode:t,grandParent:r,curNode:e}}t.ee=0,r===this.W?this.W=r.ne():r.ne(),r.ee=1}return}},t.prototype.se=function(e,t,r){if(void 0===this.W)return this.M+=1,this.W=new this.re(e,t),this.W.ee=0,this.W.rr=this.h,this.h.rr=this.W,this.h.K=this.W,void(this.h.N=this.W);var n,i=this.h.K,o=this.$(i.u,e);if(0!==o){if(o>0)i.K=new this.re(e,t),i.K.rr=i,n=i.K,this.h.K=n;else{var s=this.h.N,a=this.$(s.u,e);if(0===a)return void(s.p=t);if(a<0)s.N=new this.re(e,t),s.N.rr=s,n=s.N,this.h.N=n;else{if(void 0!==r){var c=r.o;if(c!==this.h){var l=this.$(c.u,e);if(0===l)return void(c.p=t);if(l>0){var u=c.L(),d=this.$(u.u,e);if(0===d)return void(u.p=t);d<0&&(n=new this.re(e,t),void 0===u.N?(u.N=n,n.rr=u):(c.K=n,n.rr=c))}}}if(void 0===n)for(n=this.W;;){var h=this.$(n.u,e);if(h>0){if(void 0===n.K){n.K=new this.re(e,t),n.K.rr=n,n=n.K;break}n=n.K}else{if(!(h<0))return void(n.p=t);if(void 0===n.N){n.N=new this.re(e,t),n.N.rr=n,n=n.N;break}n=n.N}}}}return this.M+=1,n}i.p=t},t.prototype.g=function(e,t){for(;e;){var r=this.$(e.u,t);if(r<0)e=e.N;else{if(!(r>0))return e;e=e.K}}return e||this.h},t.prototype.clear=function(){this.M=0,this.W=void 0,this.h.rr=void 0,this.h.K=this.h.N=void 0},t.prototype.updateKeyByIterator=function(e,t){var r=e.o;if(r===this.h&&u(),1===this.M)return r.u=t,!0;if(r===this.h.K)return this.$(r.m().u,t)>0&&(r.u=t,!0);if(r===this.h.N)return this.$(r.L().u,t)<0&&(r.u=t,!0);var n=r.L().u;if(this.$(n,t)>=0)return!1;var i=r.m().u;return!(this.$(i,t)<=0)&&(r.u=t,!0)},t.prototype.eraseElementByPos=function(e){if(e<0||e>this.M-1)throw new RangeError;var t=0,r=this;return this.ae(this.W,function(n){return e===t?(r.G(n),!0):(t+=1,!1)}),this.M},t.prototype.eraseElementByKey=function(e){if(0===this.M)return!1;var t=this.g(this.W,e);return t!==this.h&&(this.G(t),!0)},t.prototype.eraseElementByIterator=function(e){var t=e.o;t===this.h&&u();var r=void 0===t.N;return 0===e.iteratorType?r&&e.next():r&&void 0!==t.K||e.next(),this.G(t),e},t.prototype.forEach=function(e){var t,r,n=0;try{for(var i=p(this),o=i.next();!o.done;o=i.next()){e(o.value,n++,this)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},t.prototype.getElementByPos=function(e){var t,r,n;if(e<0||e>this.M-1)throw new RangeError;var i=0;try{for(var o=p(this),s=o.next();!s.done;s=o.next()){var a=s.value;if(i===e){n=a;break}i+=1}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return n},t.prototype.getHeight=function(){if(0===this.M)return 0;var e=function(t){return t?Math.max(e(t.K),e(t.N))+1:0};return e(this.W)},t}(l);var g=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}();const m=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.o=t,i.h=r,0===i.iteratorType?(i.pre=function(){return this.o===this.h.K&&u(),this.o=this.o.L(),this},i.next=function(){return this.o===this.h&&u(),this.o=this.o.m(),this}):(i.pre=function(){return this.o===this.h.N&&u(),this.o=this.o.m(),this},i.next=function(){return this.o===this.h&&u(),this.o=this.o.L(),this}),i}return g(t,e),Object.defineProperty(t.prototype,"index",{get:function(){var e=this.o,t=this.h.rr;if(e===this.h)return t?t.tr-1:0;var r=0;for(e.K&&(r+=e.K.tr);e!==t;){var n=e.rr;e===n.N&&(r+=1,n.K&&(r+=n.K.tr)),e=n}return r},enumerable:!1,configurable:!0}),t}(c);var b=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),y=function(e,t){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(e){return function(t){return c([e,t])}}function c(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},_=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},v=function(e){function t(t,r,n,i){var o=e.call(this,t,r,i)||this;return o.container=n,o}return b(t,e),Object.defineProperty(t.prototype,"pointer",{get:function(){return this.o===this.h&&u(),this.o.u},enumerable:!1,configurable:!0}),t.prototype.copy=function(){return new t(this.o,this.h,this.container,this.iteratorType)},t}(m);const S=function(e){function t(t,r,n){void 0===t&&(t=[]);var i=e.call(this,r,n)||this,o=i;return t.forEach(function(e){o.insert(e)}),i}return b(t,e),t.prototype.P=function(e){return y(this,function(t){switch(t.label){case 0:return void 0===e?[2]:[5,_(this.P(e.K))];case 1:return t.sent(),[4,e.u];case 2:return t.sent(),[5,_(this.P(e.N))];case 3:return t.sent(),[2]}})},t.prototype.begin=function(){return new v(this.h.K||this.h,this.h,this)},t.prototype.end=function(){return new v(this.h,this.h,this)},t.prototype.rBegin=function(){return new v(this.h.N||this.h,this.h,this,1)},t.prototype.rEnd=function(){return new v(this.h,this.h,this,1)},t.prototype.front=function(){return this.h.K?this.h.K.u:void 0},t.prototype.back=function(){return this.h.N?this.h.N.u:void 0},t.prototype.insert=function(e,t){return this.v(e,void 0,t)},t.prototype.find=function(e){var t=this.g(this.W,e);return new v(t,this.h,this)},t.prototype.lowerBound=function(e){var t=this.U(this.W,e);return new v(t,this.h,this)},t.prototype.upperBound=function(e){var t=this.X(this.W,e);return new v(t,this.h,this)},t.prototype.reverseLowerBound=function(e){var t=this.Y(this.W,e);return new v(t,this.h,this)},t.prototype.reverseUpperBound=function(e){var t=this.Z(this.W,e);return new v(t,this.h,this)},t.prototype.union=function(e){var t=this;return e.forEach(function(e){t.insert(e)}),this.M},t.prototype[Symbol.iterator]=function(){return this.P(this.W)},t}(f)},8203(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.streamBuilder=t.browserStreamBuilder=void 0;const i=r(181),o=n(r(7699)),s=n(r(5753)),a=r(4478),c=n(r(6887)),l=r(2635),u=(0,s.default)("mqttjs:ws"),d=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function h(e,t){let r=`${e.protocol}://${e.hostname}:${e.port}${e.path}`;return"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(e){const t=e;return e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),c.default||e.forceNativeWebSocket||"wss"!==e.protocol||d.forEach(r=>{Object.prototype.hasOwnProperty.call(e,r)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,r)&&(t.wsOptions[r]=e[r])}),t}t.streamBuilder=(e,t)=>{u("streamBuilder");const r=p(t);r.hostname=r.hostname||r.host||"localhost";const n=h(r,e),i=function(e,t,r){u("createWebSocket"),u(`protocol: ${r.protocolId} ${r.protocolVersion}`);const n="MQIsdp"===r.protocolId&&3===r.protocolVersion?"mqttv3.1":"mqtt";let i;return u(`creating new Websocket for url: ${t} and protocol: ${n}`),i=r.createWebsocket?r.createWebsocket(t,[n],r):new o.default(t,[n],r.wsOptions),i}(0,n,r),s=o.default.createWebSocketStream(i,r.wsOptions);return s.url=n,i.on("close",()=>{s.destroy()}),s};t.browserStreamBuilder=(e,t)=>{let r;u("browserStreamBuilder");const n=function(e){const t=p(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=Number(e.port))}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}(t),o=n.browserBufferSize||524288,s=t.browserBufferTimeout||1e3,c=!t.objectMode,d=function(e,t){const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",n=h(t,e);let i;return i=t.createWebsocket?t.createWebsocket(n,[r],t):new WebSocket(n,[r]),i.binaryType="arraybuffer",i}(e,t),f=function(e,t,r){const n=new a.Transform({objectMode:e.objectMode});return n._write=t,n._flush=r,n}(t,function e(t,r,n){if(d.bufferedAmount>o)return void setTimeout(e,s,t,r,n);c&&"string"==typeof t&&(t=i.Buffer.from(t,"utf8"));try{d.send(t)}catch(e){return n(e)}n()},function(e){d.close(),e()});t.objectMode||(f._writev=l.writev.bind(f)),f.on("close",()=>{d.close()});const g="undefined"!=typeof d.addEventListener;function m(){u("WebSocket onOpen"),r instanceof l.BufferedDuplex&&r.socketReady()}function b(e){u("WebSocket onClose",e),r.end(),r.destroy()}function y(e){u("WebSocket onError",e);const t=new Error("WebSocket error");t.event=e,r.destroy(t)}async function _(e){if(!f||!f.readable||!f.writable)return;let{data:t}=e;t=t instanceof ArrayBuffer?i.Buffer.from(t):t instanceof Blob?i.Buffer.from(await new Response(t).arrayBuffer()):i.Buffer.from(t,"utf8"),f.push(t)}return d.readyState===d.OPEN?(r=f,r.socket=d):(r=new l.BufferedDuplex(t,f,d),g?d.addEventListener("open",m):d.onopen=m),g?(d.addEventListener("close",b),d.addEventListener("error",y),d.addEventListener("message",_)):(d.onclose=b,d.onerror=y,d.onmessage=_),r}},8237(e,t,r){"use strict";const{tokenChars:n}=r(5880);e.exports={parse:function(e){const t=new Set;let r=-1,i=-1,o=0;for(;o<e.length;o++){const s=e.charCodeAt(o);if(-1===i&&1===n[s])-1===r&&(r=o);else if(0===o||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${o}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${o}`);-1===i&&(i=o);const n=e.slice(r,i);if(t.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}}else-1===i&&-1!==r&&(i=o)}if(-1===r||-1!==i)throw new SyntaxError("Unexpected end of input");const s=e.slice(r,o);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}}},8584(e,t,r){"use strict";const n=r(4422),{ArrayPrototypeSlice:i,Error:o,FunctionPrototypeSymbolHasInstance:s,ObjectDefineProperty:a,ObjectDefineProperties:c,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:u,Symbol:d,SymbolHasInstance:h}=r(4134);e.exports=B,B.WritableState=R;const{EventEmitter:p}=r(4434),f=r(4259).Stream,{Buffer:g}=r(181),m=r(5896),{addAbortSignal:b}=r(4147),{getHighWaterMark:y,getDefaultHighWaterMark:_}=r(5291),{ERR_INVALID_ARG_TYPE:v,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:w,ERR_STREAM_CANNOT_PIPE:k,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:T,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:C}=r(6371).codes,{errorOrDestroy:A}=m;function x(){}l(B.prototype,f.prototype),l(B,f);const P=d("kOnFinished");function R(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(3370)),this.objectMode=!(!e||!e.objectMode),n&&(this.objectMode=this.objectMode||!(!e||!e.writableObjectMode)),this.highWaterMark=e?y(this,e,"writableHighWaterMark",n):_(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const i=!(!e||!1!==e.decodeStrings);this.decodeStrings=!i,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=L.bind(void 0,t),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,M(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!e||!1!==e.emitClose,this.autoDestroy=!e||!1!==e.autoDestroy,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[P]=[]}function M(e){e.buffered=[],e.bufferedIndex=0,e.allBuffers=!0,e.allNoop=!0}function B(e){const t=this instanceof r(3370);if(!t&&!s(B,this))return new B(e);this._writableState=new R(e,this,t),e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&b(e.signal,this)),f.call(this,e),m.construct(this,()=>{const e=this._writableState;e.writing||V(this,e),z(this,e)})}function N(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new C(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=x)}if(null===t)throw new T;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!f._isUint8Array(t))throw new v("chunk",["string","Buffer","Uint8Array"],t);t=f._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new O:o.destroyed&&(s=new E("write")),s?(n.nextTick(i,s),A(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.length<t.highWaterMark;s||(t.needDrain=!0);t.writing||t.corked||t.errored||!t.constructed?(t.buffered.push({chunk:r,encoding:n,callback:i}),t.allBuffers&&"buffer"!==n&&(t.allBuffers=!1),t.allNoop&&i!==x&&(t.allNoop=!1)):(t.writelen=o,t.writecb=i,t.writing=!0,t.sync=!0,e._write(r,n,t.onwrite),t.sync=!1);return s&&!t.errored&&!t.destroyed}(e,o,t,r,i))}function j(e,t,r,n,i,o,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new E("write")):r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function D(e,t,r,n){--t.pendingcb,n(r),$(t),A(e,r)}function L(e,t){const r=e._writableState,i=r.sync,o=r.writecb;"function"==typeof o?(r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,t?(t.stack,r.errored||(r.errored=t),e._readableState&&!e._readableState.errored&&(e._readableState.errored=t),i?n.nextTick(D,e,r,t,o):D(e,r,t,o)):(r.buffered.length>r.bufferedIndex&&V(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===o?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:o,stream:e,state:r},n.nextTick(U,r.afterWriteTickInfo)):F(e,r,1,o))):A(e,new w)}function U({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,F(e,t,r,n)}function F(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&$(t),z(e,t)}function $(e){if(e.writing)return;for(let r=e.bufferedIndex;r<e.buffered.length;++r){var t;const{chunk:n,callback:i}=e.buffered[r],o=e.objectMode?1:n.length;e.length-=o,i(null!==(t=e.errored)&&void 0!==t?t:new E("write"))}const r=e[P].splice(0);for(let t=0;t<r.length;t++){var n;r[t](null!==(n=e.errored)&&void 0!==n?n:new E("end"))}M(e)}function V(e,t){if(t.corked||t.bufferProcessing||t.destroyed||!t.constructed)return;const{buffered:r,bufferedIndex:n,objectMode:o}=t,s=r.length-n;if(!s)return;let a=n;if(t.bufferProcessing=!0,s>1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?x:e=>{for(let t=a;t<r.length;++t)r[t].callback(e)},o=t.allNoop&&0===a?r:i(r,a);o.allBuffers=t.allBuffers,j(e,t,!0,t.length,o,"",n),M(t)}else{do{const{chunk:n,encoding:i,callback:s}=r[a];r[a++]=null;j(e,t,!1,o?1:n.length,n,i,s)}while(a<r.length&&!t.writing);a===r.length?M(t):a>256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function W(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function H(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)A(e,null!=i?i:w());else if(r=!0,t.pendingcb--,i){const r=t[P].splice(0);for(let e=0;e<r.length;e++)r[e](i);A(e,i,t.sync)}else W(t)&&(t.prefinished=!0,e.emit("prefinish"),t.pendingcb++,n.nextTick(q,e,t))}t.sync=!0,t.pendingcb++;try{e._final(i)}catch(e){i(e)}t.sync=!1}(e,t)))}function z(e,t,r){W(t)&&(H(e,t),0===t.pendingcb&&(r?(t.pendingcb++,n.nextTick((e,t)=>{W(t)?q(e,t):t.pendingcb--},e,t)):W(t)&&(t.pendingcb++,q(e,t))))}function q(e,t){t.pendingcb--,t.finished=!0;const r=t[P].splice(0);for(let e=0;e<r.length;e++)r[e]();if(e.emit("finish"),t.autoDestroy){const t=e._readableState;(!t||t.autoDestroy&&(t.endEmitted||!1===t.readable))&&e.destroy()}}R.prototype.getBuffer=function(){return i(this.buffered,this.bufferedIndex)},a(R.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}}),a(B,h,{__proto__:null,value:function(e){return!!s(this,e)||this===B&&(e&&e._writableState instanceof R)}}),B.prototype.pipe=function(){A(this,new k)},B.prototype.write=function(e,t,r){return!0===N(this,e,t,r)},B.prototype.cork=function(){this._writableState.corked++},B.prototype.uncork=function(){const e=this._writableState;e.corked&&(e.corked--,e.writing||V(this,e))},B.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=u(e)),!g.isEncoding(e))throw new C(e);return this._writableState.defaultEncoding=e,this},B.prototype._write=function(e,t,r){if(!this._writev)throw new S("_write()");this._writev([{chunk:e,encoding:t}],r)},B.prototype._writev=null,B.prototype.end=function(e,t,r){const i=this._writableState;let s;if("function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e){const r=N(this,e,t);r instanceof o&&(s=r)}return i.corked&&(i.corked=1,this.uncork()),s||(i.errored||i.ending?i.finished?s=new I("end"):i.destroyed&&(s=new E("end")):(i.ending=!0,z(this,i,!0),i.ended=!0)),"function"==typeof r&&(s||i.finished?n.nextTick(r,s):i[P].push(r)),this},c(B.prototype,{closed:{__proto__:null,get(){return!!this._writableState&&this._writableState.closed}},destroyed:{__proto__:null,get(){return!!this._writableState&&this._writableState.destroyed},set(e){this._writableState&&(this._writableState.destroyed=e)}},writable:{__proto__:null,get(){const e=this._writableState;return!(!e||!1===e.writable||e.destroyed||e.errored||e.ending||e.ended)},set(e){this._writableState&&(this._writableState.writable=!!e)}},writableFinished:{__proto__:null,get(){return!!this._writableState&&this._writableState.finished}},writableObjectMode:{__proto__:null,get(){return!!this._writableState&&this._writableState.objectMode}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return!!this._writableState&&this._writableState.ending}},writableNeedDrain:{__proto__:null,get(){const e=this._writableState;return!!e&&(!e.destroyed&&!e.ending&&e.needDrain)}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._writableState.writable||!this._writableState.destroyed&&!this._writableState.errored||this._writableState.finished)}}});const G=m.destroy;let K;function Q(){return void 0===K&&(K={}),K}B.prototype.destroy=function(e,t){const r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[P].length)&&n.nextTick($,r),G.call(this,e,t),this},B.prototype._undestroy=m.undestroy,B.prototype._destroy=function(e,t){t(e)},B.prototype[p.captureRejectionSymbol]=function(e){this.destroy(e)},B.fromWeb=function(e,t){return Q().newStreamWritableFromWritableStream(e,t)},B.toWeb=function(e){return Q().newWritableStreamFromStreamWritable(e)}},8600(e,t,r){"use strict";r.r(t),r.d(t,{clearInterval:()=>v,clearTimeout:()=>S,setInterval:()=>w,setTimeout:()=>k});const n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,o=1073741824,s=new WeakMap;var a;const c=((e,t)=>r=>{const s=t.get(r);let a=void 0===s?r.size:s<o?s+1:0;if(!r.has(a))return e(r,a);if(r.size<i){for(;r.has(a);)a=Math.floor(Math.random()*o);return e(r,a)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(a);)a=Math.floor(Math.random()*n);return e(r,a)})((a=s,(e,t)=>(a.set(e,t),t)),s),l=((e=>{})(c),((e,t,r,n)=>i=>{const o=t(i);return t=>{const i=e(t);t.addEventListener("message",({data:e})=>{const{id:t}=e;if(null!==t&&i.has(t)){const{reject:r,resolve:n}=i.get(t);i.delete(t),void 0===e.error?n(e.result):r(new Error(e.error.message))}}),n(t)&&t.start();const s=(e,n=null,o=[])=>new Promise((s,a)=>{const c=r(i);i.set(c,{reject:a,resolve:s}),null===n?t.postMessage({id:c,method:e},o):t.postMessage({id:c,method:e,params:n},o)}),a=(e,r,n=[])=>{t.postMessage({id:null,method:e,params:r},n)};let c={};for(const[e,t]of Object.entries(o))c={...c,[e]:t({call:s,notify:a})};return{...c}}})((d=new WeakMap,e=>{if(d.has(e))return d.get(e);const t=new Map;return d.set(e,t),t}),(u=new WeakMap,e=>({...e,connect:({call:e})=>async()=>{const{port1:t,port2:r}=new MessageChannel,n=await e("connect",{port:t},[t]);return u.set(r,n),r},disconnect:({call:e})=>async t=>{const r=u.get(t);if(void 0===r)throw new Error("The given port is not connected.");await e("disconnect",{portId:r})},isSupported:({call:e})=>()=>e("isSupported")})),c,e=>"function"==typeof e.start));var u,d;const h=new Map([[0,null]]),p=new Map([[0,null]]),f=(e=>t=>r=>{"symbol"==typeof e.get(r)&&(e.set(r,null),t(r).then(()=>{e.delete(r)}))})(h),g=(e=>t=>r=>{"symbol"==typeof e.get(r)&&(e.set(r,null),t(r).then(()=>{e.delete(r)}))})(p),m=((e,t)=>r=>(n,i=0,...o)=>{const s=Symbol(),a=e(t);t.set(a,s);const c=()=>r(i,a).then(()=>{const e=t.get(a);if(void 0===e)throw new Error("The timer is in an undefined state.");e===s&&(n(...o),t.get(a)===s&&c())});return c(),a})(c,h),b=((e,t)=>r=>(n,i=0,...o)=>{const s=Symbol(),a=e(t);return t.set(a,s),r(i,a).then(()=>{const e=t.get(a);if(void 0===e)throw new Error("The timer is in an undefined state.");e===s&&(t.delete(a),n(...o))}),a})(c,p),y=l({clearInterval:({call:e})=>f(t=>e("clear",{timerId:t,timerType:"interval"})),clearTimeout:({call:e})=>g(t=>e("clear",{timerId:t,timerType:"timeout"})),setInterval:({call:e})=>m((t,r)=>e("set",{delay:t,now:performance.timeOrigin+performance.now(),timerId:r,timerType:"interval"})),setTimeout:({call:e})=>b((t,r)=>e("set",{delay:t,now:performance.timeOrigin+performance.now(),timerId:r,timerType:"timeout"}))}),_=((e,t)=>{let r=null;return()=>{if(null!==r)return r;const n=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return r=e(i),setTimeout(()=>URL.revokeObjectURL(i)),r}})(e=>{const t=new Worker(e);return y(t)},'(()=>{var e={455(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),l=t(c);e.addUniqueNumber=l,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o(\'The handler of the method called "\'.concat(t,\'" returned an unexpected result.\'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o(\'The requested method called "\'.concat(e,\'" is not supported.\'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o(\'The handler of the method called "\'.concat(t,\'" returned no required result.\'),e))(i);const l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,()=>{n(),t.close(),u.delete(o)}),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise(e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])})){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},m=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},f=new Map,h=d(globalThis.clearTimeout,f),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=m(f,performance,globalThis.setTimeout,w),T=m(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();'),v=e=>_().clearInterval(e),S=e=>_().clearTimeout(e),w=(...e)=>_().setInterval(...e),k=(...e)=>_().setTimeout(...e)},8611(e){"use strict";e.exports=require("http")},8914(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RE_URL_WITH_PORT=t.RE_URL=t.RE_ZONE_STRING=t.RE_SUBNET_STRING=t.RE_BAD_ADDRESS=t.RE_BAD_CHARACTERS=t.TYPES=t.SCOPES=t.GROUPS=t.BITS=void 0,t.BITS=128,t.GROUPS=8,t.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},t.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},t.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,t.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,t.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,t.RE_ZONE_STRING=/%.*$/,t.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/,t.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/},9023(e){"use strict";e.exports=require("util")},9231(e){"use strict";e.exports={format:(e,...t)=>e.replace(/%([sdifj])/g,function(...[e,r]){const n=t.shift();if("f"===r)return n.toFixed(6);if("j"===r)return JSON.stringify(n);if("s"===r&&"object"==typeof n){return`${n.constructor!==Object?n.constructor.name:""} {}`.trim()}return n.toString()}),inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}}}},9278(e){"use strict";e.exports=require("net")},9291(e,t,r){"use strict";const n=r(8194).CD,i=r(5753)("number-allocator:trace"),o=r(5753)("number-allocator:error");function s(e,t){this.low=e,this.high=t}function a(e,t){if(!(this instanceof a))return new a(e,t);this.min=e,this.max=t,this.ss=new n([],(e,t)=>e.compare(t)),i("Create"),this.clear()}s.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},s.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},a.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},a.prototype.alloc=function(){if(0===this.ss.size())return i("alloc():empty"),null;const e=this.ss.begin(),t=e.pointer.low,r=e.pointer.high,n=t;return n+1<=r?this.ss.updateKeyByIterator(e,new s(t+1,r)):this.ss.eraseElementByPos(0),i("alloc():"+n),n},a.prototype.use=function(e){const t=new s(e,e),r=this.ss.lowerBound(t);if(!r.equals(this.ss.end())){const n=r.pointer.low,o=r.pointer.high;return r.pointer.equals(t)?(this.ss.eraseElementByIterator(r),i("use():"+e),!0):!(n>e)&&(n===e?(this.ss.updateKeyByIterator(r,new s(n+1,o)),i("use():"+e),!0):o===e?(this.ss.updateKeyByIterator(r,new s(n,o-1)),i("use():"+e),!0):(this.ss.updateKeyByIterator(r,new s(e+1,o)),this.ss.insert(new s(n,e-1)),i("use():"+e),!0))}return i("use():failed"),!1},a.prototype.free=function(e){if(e<this.min||e>this.max)return void o("free():"+e+" is out of range");const t=new s(e,e),r=this.ss.upperBound(t);if(r.equals(this.ss.end())){if(r.equals(this.ss.begin()))return void this.ss.insert(t);r.pre();const n=r.pointer.high;r.pointer.high+1===e?this.ss.updateKeyByIterator(r,new s(n,e)):this.ss.insert(t)}else if(r.equals(this.ss.begin()))if(e+1===r.pointer.low){const t=r.pointer.high;this.ss.updateKeyByIterator(r,new s(e,t))}else this.ss.insert(t);else{const n=r.pointer.low,i=r.pointer.high;r.pre();const o=r.pointer.low;r.pointer.high+1===e?e+1===n?(this.ss.eraseElementByIterator(r),this.ss.updateKeyByIterator(r,new s(o,i))):this.ss.updateKeyByIterator(r,new s(o,e)):e+1===n?(this.ss.eraseElementByIterator(r.next()),this.ss.insert(new s(e,i))):this.ss.insert(t)}i("free():"+e)},a.prototype.clear=function(){i("clear()"),this.ss.clear(),this.ss.insert(new s(this.min,this.max))},a.prototype.intervalCount=function(){return this.ss.size()},a.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},e.exports=a},9372(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||i(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0});const c=s(r(1676));t.default=c,a(r(1676),t)},9424(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.v6=t.AddressError=t.Address6=t.Address4=void 0;var s=r(2839);Object.defineProperty(t,"Address4",{enumerable:!0,get:function(){return s.Address4}});var a=r(6329);Object.defineProperty(t,"Address6",{enumerable:!0,get:function(){return a.Address6}});var c=r(2437);Object.defineProperty(t,"AddressError",{enumerable:!0,get:function(){return c.AddressError}});const l=o(r(465));t.v6={helpers:l}},9576(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RE_SUBNET_STRING=t.RE_ADDRESS=t.GROUPS=t.BITS=void 0,t.BITS=32,t.GROUPS=4,t.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,t.RE_SUBNET_STRING=/\/\d{1,2}$/},9777(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const c=a(r(1278)),l=r(4478),u=a(r(3885)),d=a(r(5753)),h=s(r(128)),p=a(r(7969)),f=a(r(6912)),g=a(r(579)),m=a(r(2639)),b=r(4723),y=r(4152),_=a(r(3175)),v=s(r(6887)),S=globalThis.setImmediate||((...e)=>{const t=e.shift();(0,b.nextTick)(()=>{t(...e)})}),w={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class k extends y.TypedEventEmitter{static VERSION=b.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(e,t){super(),this.options=t||{};for(const e in w)"undefined"==typeof this.options[e]?this.options[e]=w[e]:this.options[e]=t[e];this.log=this.options.log||(0,d.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",k.VERSION),v.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",v.default?"browser":"node"),this.log("MqttClient :: options.protocol",t.protocol),this.log("MqttClient :: options.protocolVersion",t.protocolVersion),this.log("MqttClient :: options.username",t.username),this.log("MqttClient :: options.keepalive",t.keepalive),this.log("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",t.properties?t.properties.topicAliasMaximum:void 0),this.options.clientId="string"==typeof t.clientId?t.clientId:k.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:(...e)=>{e[3](null,0)},this.options.writeCache||(c.default.writeToStream.cacheNumbers=!1),this.streamBuilder=e,this.messageIdProvider="undefined"==typeof this.options.messageIdProvider?new g.default:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new p.default,this.incomingStore=t.incomingStore||new p.default,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.properties&&t.properties.topicAliasMaximum>0&&(t.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new m.default(t.properties.topicAliasMaximum)),this.on("connect",()=>{const{queue:e}=this,t=()=>{const r=e.shift();this.log("deliver :: entry %o",r);let n=null;if(!r)return void this._resubscribe();n=r.packet,this.log("deliver :: call _sendPacket for %o",n);let i=!0;n.messageId&&0!==n.messageId&&(this.messageIdProvider.register(n.messageId)||(i=!1)),i?this._sendPacket(n,e=>{r.cb&&r.cb(e),t()}):(this.log("messageId: %d has already used. The message is skipped and removed.",n.messageId),t())};this.log("connect :: sending queued packets"),t()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(e,t){t()}handleMessage(e,t){t()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){const e=new l.Writable,t=c.default.parser(this.options);let r=null;const n=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new p.default,this.outgoingStore=this.options.outgoingStore||new p.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),t.on("packet",e=>{this.log("parser :: on packet push to packets array."),n.push(e)});const i=()=>{this.log("work :: getting next packet in queue");const e=n.shift();if(e)this.log("work :: packet pulled from queue"),(0,f.default)(this,e,o);else{this.log("work :: no packets in queue");const e=r;r=null,this.log("work :: done flag is %s",!!e),e&&e()}},o=()=>{if(n.length)(0,b.nextTick)(i);else{const e=r;r=null,e()}};e._write=(e,n,o)=>{r=o,this.log("writable stream :: parsing buffer"),t.parse(e),i()};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(e),this.stream.on("error",e=>{this.log("streamErrorHandler :: error",e.message),e.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",e)):this.noop(e)}),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");const s={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(s.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(s.properties||(s.properties={}),this.topicAliasRecv&&(s.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(s),t.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket){const e={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(e)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(e,t,r,n){this.log("publish :: message `%s` to topic `%s`",t,e);const{options:i}=this;"function"==typeof r&&(n=r,r=null),r=r||{};r={qos:0,retain:!1,dup:!1,...r};const{qos:o,retain:s,dup:a,properties:c,cbStorePut:l}=r;if(this._checkDisconnecting(n))return this;const u=()=>{let r=0;if((1===o||2===o)&&(r=this._nextId(),null===r))return this.log("No messageId left"),!1;const u={cmd:"publish",topic:e,payload:t,qos:o,retain:s,messageId:r,dup:a};switch(5===i.protocolVersion&&(u.properties=c),this.log("publish :: qos",o),o){case 1:case 2:this.outgoing[u.messageId]={volatile:!1,cb:n||this.noop},this.log("MqttClient:publish: packet cmd: %s",u.cmd),this._sendPacket(u,void 0,l);break;default:this.log("MqttClient:publish: packet cmd: %s",u.cmd),this._sendPacket(u,n,l)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!u())&&this._storeProcessingQueue.push({invoke:u,cbStorePut:r.cbStorePut,callback:n}),this}publishAsync(e,t,r){return new Promise((n,i)=>{this.publish(e,t,r,(e,t)=>{e?i(e):n(t)})})}subscribe(e,t,r){const n=this.options.protocolVersion;"function"==typeof t&&(r=t),r=r||this.noop;let i=!1,o=[];"string"==typeof e?o=e=[e]:Array.isArray(e)?o=e:"object"==typeof e&&(i=e.resubscribe,delete e.resubscribe,o=Object.keys(e));const s=h.validateTopics(o);if(null!==s)return S(r,new Error(`Invalid topic ${s}`)),this;if(this._checkDisconnecting(r))return this.log("subscribe: discconecting true"),this;const a={qos:0};5===n&&(a.nl=!1,a.rap=!1,a.rh=0),t={...a,...t};const{properties:c}=t,l=[],u=(e,r)=>{if(r=r||t,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,e)||this._resubscribeTopics[e].qos<r.qos||i){const t={topic:e,qos:r.qos};5===n&&(t.nl=r.nl,t.rap=r.rap,t.rh=r.rh,t.properties=c),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",t.topic,t.qos),l.push(t)}};if(Array.isArray(e)?e.forEach(e=>{this.log("subscribe: array topic %s",e),u(e)}):Object.keys(e).forEach(t=>{this.log("subscribe: object topic %s, %o",t,e[t]),u(t,e[t])}),!l.length)return r(null,[]),this;const d=(e,t)=>{const r={cmd:"subscribe",subscriptions:e,messageId:t};if(c&&(r.properties=c),this.options.resubscribe){this.log("subscribe :: resubscribe true");const t=[];e.forEach(e=>{if(this.options.reconnectPeriod>0){const r={qos:e.qos};5===n&&(r.nl=e.nl||!1,r.rap=e.rap||!1,r.rh=e.rh||0,r.properties=e.properties),this._resubscribeTopics[e.topic]=r,t.push(e.topic)}}),this.messageIdToTopic[r.messageId]=t}const i=new Promise((t,n)=>{this.outgoing[r.messageId]={volatile:!0,cb(r,i){if(!r){const{granted:t}=i;for(let r=0;r<t.length;r+=1)e[r].qos=t[r]}r?n(new b.ErrorWithSubackPacket(r.message,i)):t(i)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(r),i},p=()=>{const e=this.options.subscribeBatchSize??l.length,t=[];for(let r=0;r<l.length;r+=e){const n=l.slice(r,r+e),i=this._nextId();if(null===i)return this.log("No messageId left"),!1;t.push(d(n,i))}return Promise.all(t).then(e=>{r(null,l,e.at(-1))}).catch(e=>{r(e,l,e.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!p())&&this._storeProcessingQueue.push({invoke:p,callback:r}),this}subscribeAsync(e,t){return new Promise((r,n)=>{this.subscribe(e,t,(e,t)=>{e?n(e):r(t)})})}unsubscribe(e,t,r){"string"==typeof e&&(e=[e]),"function"==typeof t&&(r=t),r=r||this.noop;const n=h.validateTopics(e);if(null!==n)return S(r,new Error(`Invalid topic ${n}`)),this;if(this._checkDisconnecting(r))return this;const i=()=>{const n=this._nextId();if(null===n)return this.log("No messageId left"),!1;const i={cmd:"unsubscribe",messageId:n,unsubscriptions:[]};return"string"==typeof e?i.unsubscriptions=[e]:Array.isArray(e)&&(i.unsubscriptions=e),this.options.resubscribe&&i.unsubscriptions.forEach(e=>{delete this._resubscribeTopics[e]}),"object"==typeof t&&t.properties&&(i.properties=t.properties),this.outgoing[i.messageId]={volatile:!0,cb:r},this.log("unsubscribe: call _sendPacket"),this._sendPacket(i),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!i())&&this._storeProcessingQueue.push({invoke:i,callback:r}),this}unsubscribeAsync(e,t){return new Promise((r,n)=>{this.unsubscribe(e,t,(e,t)=>{e?n(e):r(t)})})}end(e,t,r){this.log("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(r=r||t,t=e,e=!1),"object"!=typeof t&&(r=r||t,t=null),this.log("end :: cb? %s",!!r),r&&"function"==typeof r||(r=this.noop);const n=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(e=>{this.outgoingStore.close(t=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),r){const n=e||t;this.log("end :: closeStores: invoking callback with args"),r(n)}})}),this._deferredReconnect?this._deferredReconnect():(0===this.options.reconnectPeriod||this.options.manualConnect)&&(this.disconnecting=!1)},i=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,e),this._cleanUp(e,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,b.nextTick)(n)},t)};return this.disconnecting?(r(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,i,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),i()),this)}endAsync(e,t){return new Promise((r,n)=>{this.end(e,t,e=>{e?n(e):r()})})}removeOutgoingMessage(e){if(this.outgoing[e]){const{cb:t}=this.outgoing[e];this._removeOutgoingAndStoreMessage(e,()=>{t(new Error("Message removed"))})}return this}reconnect(e){this.log("client reconnect");const t=()=>{e?(this.options.incomingStore=e.incomingStore,this.options.outgoingStore=e.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new p.default,this.outgoingStore=this.options.outgoingStore||new p.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=t:t(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(e=>{this.outgoing[e].volatile&&"function"==typeof this.outgoing[e].cb&&(this.outgoing[e].cb(new Error("Connection closed")),delete this.outgoing[e])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(e=>{"function"==typeof this.outgoing[e].cb&&(this.outgoing[e].cb(new Error("Connection closed")),delete this.outgoing[e])}))}_removeTopicAliasAndRecoverTopicName(e){let t;e.properties&&(t=e.properties.topicAlias);let r=e.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",t,r),0===r.length){if("undefined"==typeof t)return new Error("Unregistered Topic Alias");if(r=this.topicAliasSend.getTopicByAlias(t),"undefined"==typeof r)return new Error("Unregistered Topic Alias");e.topic=r}t&&delete e.properties.topicAlias}_checkDisconnecting(e){return this.disconnecting&&(e&&e!==this.noop?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(e,t,r={}){if(t&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),this.log("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e={cmd:"disconnect",...r};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),S(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}this.disconnecting||this.reconnecting||(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),t&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())}_storeAndSend(e,t,r){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",e.cmd);let n,i=e;if("publish"===i.cmd&&(i=(0,u.default)(e),n=this._removeTopicAliasAndRecoverTopicName(i),n))return t&&t(n);this.outgoingStore.put(i,n=>{if(n)return t&&t(n);r(),this._writePacket(e,t)})}_applyTopicAlias(e){if(5===this.options.protocolVersion&&"publish"===e.cmd){let t;e.properties&&(t=e.properties.topicAlias);const r=e.topic.toString();if(this.topicAliasSend)if(t){if(0!==r.length&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",r,t),!this.topicAliasSend.put(r,t)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,t),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(this.options.autoAssignTopicAlias?(t=this.topicAliasSend.getAliasByTopic(r),t?(e.topic="",e.properties={...e.properties,topicAlias:t},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,t)):(t=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(r,t),e.properties={...e.properties,topicAlias:t},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",r,t))):this.options.autoUseTopicAlias&&(t=this.topicAliasSend.getAliasByTopic(r),t&&(e.topic="",e.properties={...e.properties,topicAlias:t},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",r,t))));else if(t)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,t),new Error("Sending Topic Alias out of range")}}_noop(e){this.log("noop ::",e)}_writePacket(e,t){this.log("_writePacket :: packet: %O",e),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",e),this.log("_writePacket :: writing to stream");const r=c.default.writeToStream(e,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",r),!r&&t&&t!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",t)):t&&(this.log("_writePacket :: invoking cb"),t())}_sendPacket(e,t,r,n){this.log("_sendPacket :: (%s) :: start",this.options.clientId),r=r||this.noop,t=t||this.noop;const i=this._applyTopicAlias(e);if(i)t(i);else{if(!this.connected)return"auth"===e.cmd?void this._writePacket(e,t):(this.log("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,r));if(n)this._writePacket(e,t);else{switch(e.cmd){case"publish":break;case"pubrel":return void this._storeAndSend(e,t,r);default:return void this._writePacket(e,t)}switch(e.qos){case 2:case 1:this._storeAndSend(e,t,r);break;default:this._writePacket(e,t)}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}}}_storePacket(e,t,r){this.log("_storePacket :: packet: %o",e),this.log("_storePacket :: cb? %s",!!t),r=r||this.noop;let n=e;if("publish"===n.cmd){n=(0,u.default)(e);const r=this._removeTopicAliasAndRecoverTopicName(n);if(r)return t&&t(r)}const i=n.qos||0;0===i&&this.queueQoSZero||"publish"!==n.cmd?this.queue.push({packet:n,cb:t}):i>0?(t=this.outgoing[n.messageId]?this.outgoing[n.messageId].cb:null,this.outgoingStore.put(n,e=>{if(e)return t&&t(e);r()})):t&&t(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new _.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(e=!1){this.keepaliveManager&&this.options.keepalive&&(e||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){this.log("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const r={};r[e[t]]=this._resubscribeTopics[e[t]],r.resubscribe=!0,this.subscribe(r,{properties:r[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(e){if(this.disconnected)return void this.emit("connect",e);this.connackPacket=e,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;const t=()=>{let r=this.outgoingStore.createStream();const n=()=>{r.destroy(),r=null,this._flushStoreProcessingQueue(),i()},i=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",n),r.on("error",e=>{i(),this._flushStoreProcessingQueue(),this.removeListener("close",n),this.emit("error",e)});const o=()=>{if(!r)return;const e=r.read(1);let t;e?(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[e.messageId]?o():this.disconnecting||this.reconnectTimer?r.destroy&&r.destroy():(t=this.outgoing[e.messageId]?this.outgoing[e.messageId].cb:null,this.outgoing[e.messageId]={volatile:!1,cb(e,r){t&&t(e,r),o()}},this._packetIdsDuringStoreProcessing[e.messageId]=!0,this.messageIdProvider.register(e.messageId)?this._sendPacket(e,void 0,void 0,!0):this.log("messageId: %d has already used.",e.messageId))):r.once("readable",o)};r.on("end",()=>{let r=!0;for(const e in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[e]){r=!1;break}this.removeListener("close",n),r?(i(),this._invokeAllStoreProcessingQueue(),this.emit("connect",e)):t()}),o()};t()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(e,t){delete this.outgoing[e],this.outgoingStore.del({messageId:e},(r,n)=>{t(r,n),this.messageIdProvider.deallocate(e),this._invokeStoreProcessingQueue()})}}t.default=k},9844(e){"use strict";function t(e){return e instanceof Buffer?Buffer.from(e):new e.constructor(e.buffer.slice(),e.byteOffset,e.length)}e.exports=function(e){if((e=e||{}).circles)return function(e){const r=[],n=[],i=new Map;if(i.set(Date,e=>new Date(e)),i.set(Map,(e,t)=>new Map(s(Array.from(e),t))),i.set(Set,(e,t)=>new Set(s(Array.from(e),t))),e.constructorHandlers)for(const t of e.constructorHandlers)i.set(t[0],t[1]);let o=null;return e.proto?c:a;function s(e,s){const a=Object.keys(e),c=new Array(a.length);for(let l=0;l<a.length;l++){const u=a[l],d=e[u];if("object"!=typeof d||null===d)c[u]=d;else if(d.constructor!==Object&&(o=i.get(d.constructor)))c[u]=o(d,s);else if(ArrayBuffer.isView(d))c[u]=t(d);else{const e=r.indexOf(d);c[u]=-1!==e?n[e]:s(d)}}return c}function a(e){if("object"!=typeof e||null===e)return e;if(Array.isArray(e))return s(e,a);if(e.constructor!==Object&&(o=i.get(e.constructor)))return o(e,a);const c={};r.push(e),n.push(c);for(const s in e){if(!1===Object.hasOwnProperty.call(e,s))continue;const l=e[s];if("object"!=typeof l||null===l)c[s]=l;else if(l.constructor!==Object&&(o=i.get(l.constructor)))c[s]=o(l,a);else if(ArrayBuffer.isView(l))c[s]=t(l);else{const e=r.indexOf(l);c[s]=-1!==e?n[e]:a(l)}}return r.pop(),n.pop(),c}function c(e){if("object"!=typeof e||null===e)return e;if(Array.isArray(e))return s(e,c);if(e.constructor!==Object&&(o=i.get(e.constructor)))return o(e,c);const a={};r.push(e),n.push(a);for(const s in e){const l=e[s];if("object"!=typeof l||null===l)a[s]=l;else if(l.constructor!==Object&&(o=i.get(l.constructor)))a[s]=o(l,c);else if(ArrayBuffer.isView(l))a[s]=t(l);else{const e=r.indexOf(l);a[s]=-1!==e?n[e]:c(l)}}return r.pop(),n.pop(),a}}(e);const r=new Map;if(r.set(Date,e=>new Date(e)),r.set(Map,(e,t)=>new Map(i(Array.from(e),t))),r.set(Set,(e,t)=>new Set(i(Array.from(e),t))),e.constructorHandlers)for(const t of e.constructorHandlers)r.set(t[0],t[1]);let n=null;return e.proto?function e(o){if("object"!=typeof o||null===o)return o;if(Array.isArray(o))return i(o,e);if(o.constructor!==Object&&(n=r.get(o.constructor)))return n(o,e);const s={};for(const i in o){const a=o[i];"object"!=typeof a||null===a?s[i]=a:a.constructor!==Object&&(n=r.get(a.constructor))?s[i]=n(a,e):ArrayBuffer.isView(a)?s[i]=t(a):s[i]=e(a)}return s}:function e(o){if("object"!=typeof o||null===o)return o;if(Array.isArray(o))return i(o,e);if(o.constructor!==Object&&(n=r.get(o.constructor)))return n(o,e);const s={};for(const i in o){if(!1===Object.hasOwnProperty.call(o,i))continue;const a=o[i];"object"!=typeof a||null===a?s[i]=a:a.constructor!==Object&&(n=r.get(a.constructor))?s[i]=n(a,e):ArrayBuffer.isView(a)?s[i]=t(a):s[i]=e(a)}return s};function i(e,i){const o=Object.keys(e),s=new Array(o.length);for(let a=0;a<o.length;a++){const c=o[a],l=e[c];"object"!=typeof l||null===l?s[c]=l:l.constructor!==Object&&(n=r.get(l.constructor))?s[c]=n(l,i):ArrayBuffer.isView(l)?s[c]=t(l):s[c]=i(l)}return s}}},9896(e){"use strict";e.exports=require("fs")}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n=r(7927),i=exports="undefined"==typeof exports?{}:exports;for(var o in n)i[o]=n[o];n.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
|
|
2
|
+
(()=>{var e={128(e,t){"use strict";function r(e){const t=e.split("/");for(let e=0;e<t.length;e++)if("+"!==t[e]){if("#"===t[e])return e===t.length-1;if(-1!==t[e].indexOf("+")||-1!==t[e].indexOf("#"))return!1}return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.validateTopic=r,t.validateTopics=function(e){if(0===e.length)return"empty_topic_list";for(let t=0;t<e.length;t++)if(!r(e[t]))return e[t];return null}},181(e){"use strict";e.exports=require("buffer")},277(e,t,r){"use strict";const{ArrayIsArray:n,ArrayPrototypeIncludes:i,ArrayPrototypeJoin:o,ArrayPrototypeMap:s,NumberIsInteger:a,NumberIsNaN:c,NumberMAX_SAFE_INTEGER:l,NumberMIN_SAFE_INTEGER:u,NumberParseInt:d,ObjectPrototypeHasOwnProperty:h,RegExpPrototypeExec:p,String:f,StringPrototypeToUpperCase:g,StringPrototypeTrim:m}=r(4134),{hideStackFrames:b,codes:{ERR_SOCKET_BAD_PORT:y,ERR_INVALID_ARG_TYPE:_,ERR_INVALID_ARG_VALUE:v,ERR_OUT_OF_RANGE:S,ERR_UNKNOWN_SIGNAL:w}}=r(6371),{normalizeEncoding:k}=r(7760),{isAsyncFunction:E,isArrayBufferView:I}=r(7760).types,T={};const O=/^[0-7]+$/;const C=b((e,t,r=u,n=l)=>{if("number"!=typeof e)throw new _(t,"number",e);if(!a(e))throw new S(t,"an integer",e);if(e<r||e>n)throw new S(t,`>= ${r} && <= ${n}`,e)}),x=b((e,t,r=-2147483648,n=2147483647)=>{if("number"!=typeof e)throw new _(t,"number",e);if(!a(e))throw new S(t,"an integer",e);if(e<r||e>n)throw new S(t,`>= ${r} && <= ${n}`,e)}),A=b((e,t,r=!1)=>{if("number"!=typeof e)throw new _(t,"number",e);if(!a(e))throw new S(t,"an integer",e);const n=r?1:0,i=4294967295;if(e<n||e>i)throw new S(t,`>= ${n} && <= ${i}`,e)});function P(e,t){if("string"!=typeof e)throw new _(t,"string",e)}const R=b((e,t,r)=>{if(!i(r,e)){const n=o(s(r,e=>"string"==typeof e?`'${e}'`:f(e)),", ");throw new v(t,e,"must be one of: "+n)}});function M(e,t){if("boolean"!=typeof e)throw new _(t,"boolean",e)}function B(e,t,r){return null!=e&&h(e,t)?e[t]:r}const N=b((e,t,r=null)=>{const i=B(r,"allowArray",!1),o=B(r,"allowFunction",!1);if(!B(r,"nullable",!1)&&null===e||!i&&n(e)||"object"!=typeof e&&(!o||"function"!=typeof e))throw new _(t,"Object",e)}),j=b((e,t)=>{if(null!=e&&"object"!=typeof e&&"function"!=typeof e)throw new _(t,"a dictionary",e)}),D=b((e,t,r=0)=>{if(!n(e))throw new _(t,"Array",e);if(e.length<r){throw new v(t,e,`must be longer than ${r}`)}});const L=b((e,t="buffer")=>{if(!I(e))throw new _(t,["Buffer","TypedArray","DataView"],e)});const U=b((e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new _(t,"AbortSignal",e)}),F=b((e,t)=>{if("function"!=typeof e)throw new _(t,"Function",e)}),$=b((e,t)=>{if("function"!=typeof e||E(e))throw new _(t,"Function",e)}),V=b((e,t)=>{if(void 0!==e)throw new _(t,"undefined",e)});const W=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function H(e,t){if("undefined"==typeof e||!p(W,e))throw new v(t,e,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}e.exports={isInt32:function(e){return e===(0|e)},isUint32:function(e){return e===e>>>0},parseFileMode:function(e,t,r){if("undefined"==typeof e&&(e=r),"string"==typeof e){if(null===p(O,e))throw new v(t,e,"must be a 32-bit unsigned integer or an octal string");e=d(e,8)}return A(e,t),e},validateArray:D,validateStringArray:function(e,t){D(e,t);for(let r=0;r<e.length;r++)P(e[r],`${t}[${r}]`)},validateBooleanArray:function(e,t){D(e,t);for(let r=0;r<e.length;r++)M(e[r],`${t}[${r}]`)},validateAbortSignalArray:function(e,t){D(e,t);for(let r=0;r<e.length;r++){const n=e[r],i=`${t}[${r}]`;if(null==n)throw new _(i,"AbortSignal",n);U(n,i)}},validateBoolean:M,validateBuffer:L,validateDictionary:j,validateEncoding:function(e,t){const r=k(t),n=e.length;if("hex"===r&&n%2!=0)throw new v("encoding",t,`is invalid for data of length ${n}`)},validateFunction:F,validateInt32:x,validateInteger:C,validateNumber:function(e,t,r=void 0,n){if("number"!=typeof e)throw new _(t,"number",e);if(null!=r&&e<r||null!=n&&e>n||(null!=r||null!=n)&&c(e))throw new S(t,`${null!=r?`>= ${r}`:""}${null!=r&&null!=n?" && ":""}${null!=n?`<= ${n}`:""}`,e)},validateObject:N,validateOneOf:R,validatePlainFunction:$,validatePort:function(e,t="Port",r=!0){if("number"!=typeof e&&"string"!=typeof e||"string"==typeof e&&0===m(e).length||+e!==+e>>>0||e>65535||0===e&&!r)throw new y(t,e,r);return 0|e},validateSignalName:function(e,t="signal"){if(P(e,t),void 0===T[e]){if(void 0!==T[g(e)])throw new w(e+" (signals must use all capital letters)");throw new w(e)}},validateString:P,validateUint32:A,validateUndefined:V,validateUnion:function(e,t,r){if(!i(r,e))throw new _(t,`('${o(r,"|")}')`,e)},validateAbortSignal:U,validateLinkHeaderValue:function(e){if("string"==typeof e)return H(e,"hints"),e;if(n(e)){const t=e.length;let r="";if(0===t)return r;for(let n=0;n<t;n++){const i=e[n];H(i,"hints"),r+=i,n!==t-1&&(r+=", ")}return r}throw new v("hints",e,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}}},321(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ADDRESS_BOUNDARY=void 0,t.groupPossibilities=a,t.padGroup=c,t.simpleRegularExpression=function(e){const t=[];e.forEach((e,r)=>{0===parseInt(e,16)&&t.push(r)});const r=t.map(t=>e.map((e,r)=>{if(r===t){const t=0===r||r===s.GROUPS-1?":":"";return a([c(e),t])}return c(e)}).join(":"));return r.push(e.map(c).join(":")),a(r)},t.possibleElisions=function(e,t,r){const n=t?"":":",i=r?"":":",o=[];t||r||o.push("::");t&&r&&o.push("");(r&&!t||!r&&t)&&o.push(":");o.push(`${n}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let r=1;r<e-t;r++)o.push(`(0{1,4}:){${r}}:(0{1,4}:){${e-r-t-1}}0{1,4}`);return a(o)};const s=o(r(8914));function a(e){return`(${e.join("|")})`}function c(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}t.ADDRESS_BOUNDARY="[^A-Fa-f0-9:]"},345(e,t,r){"use strict";const{StringPrototypeSlice:n,SymbolIterator:i,TypedArrayPrototypeSet:o,Uint8Array:s}=r(4134),{Buffer:a}=r(181),{inspect:c}=r(7760);e.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){const t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}unshift(e){const t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}shift(){if(0===this.length)return;const e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(0===this.length)return"";let t=this.head,r=""+t.data;for(;null!==(t=t.next);)r+=e+t.data;return r}concat(e){if(0===this.length)return a.alloc(0);const t=a.allocUnsafe(e>>>0);let r=this.head,n=0;for(;r;)o(t,r.data,n),n+=r.data.length,r=r.next;return t}consume(e,t){const r=this.head.data;if(e<r.length){const t=r.slice(0,e);return this.head.data=r.slice(e),t}return e===r.length?this.shift():t?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[i](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let t="",r=this.head,i=0;do{const o=r.data;if(!(e>o.length)){e===o.length?(t+=o,++i,r.next?this.head=r.next:this.head=this.tail=null):(t+=n(o,0,e),this.head=r,r.data=n(o,e));break}t+=o,e-=o.length,++i}while(null!==(r=r.next));return this.length-=i,t}_getBuffer(e){const t=a.allocUnsafe(e),r=e;let n=this.head,i=0;do{const a=n.data;if(!(e>a.length)){e===a.length?(o(t,a,r-e),++i,n.next?this.head=n.next:this.head=this.tail=null):(o(t,new s(a.buffer,a.byteOffset,e),r-e),this.head=n,n.data=a.slice(e));break}o(t,a,r-e),e-=a.length,++i}while(null!==(n=n.next));return this.length-=i,t}[Symbol.for("nodejs.util.inspect.custom")](e,t){return c(this,{...t,depth:0,customInspect:!1})}}},397(e,t,r){"use strict";const n=r(181),i=r(4478),o=r(2635);let s,a,c,l=!1;t.A=(e,t)=>{if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";!function(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}(t);const u=function(e,t){const r="alis"===e.protocol?"wss":"ws";let n=`${r}://${e.hostname}${e.path}`;return e.port&&80!==e.port&&443!==e.port&&(n=`${r}://${e.hostname}:${e.port}${e.path}`),"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}(t,e);return s=t.my,s.connectSocket({url:u,protocols:r}),a=function(){const e=new i.Transform;return e._write=(e,t,r)=>{s.sendSocketMessage({data:e.buffer,success(){r()},fail(){r(new Error)}})},e._flush=e=>{s.closeSocket({success(){e()}})},e}(),c=new o.BufferedDuplex(t,a,s),l||(l=!0,s.onSocketOpen(()=>{c.socketReady()}),s.onSocketMessage(e=>{if("string"==typeof e.data){const t=n.Buffer.from(e.data,"base64");a.push(t)}else{const t=new FileReader;t.addEventListener("load",()=>{t.result instanceof ArrayBuffer?a.push(n.Buffer.from(t.result)):a.push(n.Buffer.from(t.result,"utf-8"))}),t.readAsArrayBuffer(e.data)}}),s.onSocketClose(()=>{c.end(),c.destroy()}),s.onSocketError(e=>{c.destroy(e)})),c}},441(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createTrackedObject=function(e,t,r){return{globalId:e,className:t.detection.className,label:t.detection.label,sightings:[t],journey:[],firstSeen:t.timestamp,lastSeen:t.timestamp,activeOnCameras:[t.cameraId],entryCamera:r?t.cameraId:void 0,entryCameraName:r?t.cameraName:void 0,hasExited:!1,totalDwellTime:0,state:"active",visualDescriptor:t.embedding,bestThumbnailId:t.detectionId}},t.addSighting=function(e,t){e.sightings.push(t),e.lastSeen=t.timestamp,e.activeOnCameras.includes(t.cameraId)||e.activeOnCameras.push(t.cameraId);t.embedding&&!e.visualDescriptor&&(e.visualDescriptor=t.embedding);t.detectionId&&t.confidence>.8&&(e.bestThumbnailId=t.detectionId);t.detection.label&&!e.label&&(e.label=t.detection.label)},t.addJourneySegment=function(e,t){e.journey.push(t),e.activeOnCameras=e.activeOnCameras.filter(e=>e!==t.fromCameraId),e.activeOnCameras.includes(t.toCameraId)||e.activeOnCameras.push(t.toCameraId)},t.calculateDwellTime=function(e){return 0===e.sightings.length?0:e.lastSeen-e.firstSeen},t.getLastCamera=function(e){return 0===e.sightings.length?void 0:e.sightings[e.sightings.length-1].cameraId},t.getLastSighting=function(e){return 0===e.sightings.length?void 0:e.sightings[e.sightings.length-1]},t.getJourneySummary=function(e){const t=[];e.entryCamera&&t.push(e.entryCameraName||e.entryCamera);for(const r of e.journey)t.includes(r.toCameraName||r.toCameraId)||t.push(r.toCameraName||r.toCameraId);e.exitCamera&&!t.includes(e.exitCameraName||e.exitCamera)&&t.push(e.exitCameraName||e.exitCamera);return t.join(" → ")}},465(e,t){"use strict";function r(e){return e.replace(/(0+)/g,'<span class="zero">$1</span>')}function n(e){return e.replace(/^(0+)/,'<span class="zero">$1</span>')}Object.defineProperty(t,"__esModule",{value:!0}),t.spanAllZeroes=r,t.spanAll=function(e,t=0){return e.split("").map((e,n)=>`<span class="digit value-${e} position-${n+t}">${r(e)}</span>`).join("")},t.spanLeadingZeroes=function(e){return e.split(":").map(e=>n(e)).join(":")},t.simpleGroup=function(e,t=0){return e.split(":").map((e,r)=>/group-v4/.test(e)?e:`<span class="hover-group group-${r+t}">${n(e)}</span>`)}},495(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(1021),o=n(r(3497)),s=r(4723);t.default=(e,t)=>{e.log("_handleConnack");const{options:r}=e,n=5===r.protocolVersion?t.reasonCode:t.returnCode;if(clearTimeout(e.connackTimer),delete e.topicAliasSend,t.properties){if(t.properties.topicAliasMaximum){if(t.properties.topicAliasMaximum>65535)return void e.emit("error",new Error("topicAliasMaximum from broker is out of range"));t.properties.topicAliasMaximum>0&&(e.topicAliasSend=new o.default(t.properties.topicAliasMaximum))}t.properties.serverKeepAlive&&r.keepalive&&(r.keepalive=t.properties.serverKeepAlive),t.properties.maximumPacketSize&&(r.properties||(r.properties={}),r.properties.maximumPacketSize=t.properties.maximumPacketSize)}if(0===n)e.reconnecting=!1,e._onConnect(t);else if(n>0){const t=new s.ErrorWithReasonCode(`Connection refused: ${i.ReasonCodes[n]}`,n);e.emit("error",t),e.options.reconnectOnConnackError&&e._cleanUp(!0)}}},576(e){e.exports=class{constructor(){this.cmd=null,this.retain=!1,this.qos=0,this.dup=!1,this.length=-1,this.topic=null,this.payload=null}}},579(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=class{nextId;constructor(){this.nextId=Math.max(1,Math.floor(65535*Math.random()))}allocate(){const e=this.nextId++;return 65536===this.nextId&&(this.nextId=1),e}getLastAllocated(){return 1===this.nextId?65535:this.nextId-1}register(e){return!0}deallocate(e){}clear(){}}},597(e,t,r){"use strict";const{kForOnEventAttribute:n,kListener:i}=r(2614),o=Symbol("kCode"),s=Symbol("kData"),a=Symbol("kError"),c=Symbol("kMessage"),l=Symbol("kReason"),u=Symbol("kTarget"),d=Symbol("kType"),h=Symbol("kWasClean");class p{constructor(e){this[u]=null,this[d]=e}get target(){return this[u]}get type(){return this[d]}}Object.defineProperty(p.prototype,"target",{enumerable:!0}),Object.defineProperty(p.prototype,"type",{enumerable:!0});class f extends p{constructor(e,t={}){super(e),this[o]=void 0===t.code?0:t.code,this[l]=void 0===t.reason?"":t.reason,this[h]=void 0!==t.wasClean&&t.wasClean}get code(){return this[o]}get reason(){return this[l]}get wasClean(){return this[h]}}Object.defineProperty(f.prototype,"code",{enumerable:!0}),Object.defineProperty(f.prototype,"reason",{enumerable:!0}),Object.defineProperty(f.prototype,"wasClean",{enumerable:!0});class g extends p{constructor(e,t={}){super(e),this[a]=void 0===t.error?null:t.error,this[c]=void 0===t.message?"":t.message}get error(){return this[a]}get message(){return this[c]}}Object.defineProperty(g.prototype,"error",{enumerable:!0}),Object.defineProperty(g.prototype,"message",{enumerable:!0});class m extends p{constructor(e,t={}){super(e),this[s]=void 0===t.data?null:t.data}get data(){return this[s]}}Object.defineProperty(m.prototype,"data",{enumerable:!0});const b={addEventListener(e,t,r={}){for(const o of this.listeners(e))if(!r[n]&&o[i]===t&&!o[n])return;let o;if("message"===e)o=function(e,r){const n=new m("message",{data:r?e:e.toString()});n[u]=this,y(t,this,n)};else if("close"===e)o=function(e,r){const n=new f("close",{code:e,reason:r.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[u]=this,y(t,this,n)};else if("error"===e)o=function(e){const r=new g("error",{error:e,message:e.message});r[u]=this,y(t,this,r)};else{if("open"!==e)return;o=function(){const e=new p("open");e[u]=this,y(t,this,e)}}o[n]=!!r[n],o[i]=t,r.once?this.once(e,o):this.on(e,o)},removeEventListener(e,t){for(const r of this.listeners(e))if(r[i]===t&&!r[n]){this.removeListener(e,r);break}}};function y(e,t,r){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,r):e.call(t,r)}e.exports={CloseEvent:f,ErrorEvent:g,Event:p,EventTarget:b,MessageEvent:m}},720(e,t,r){const n=r(9291);e.exports.NumberAllocator=n},736(e,t,r){e.exports=function(e){function t(e){let r,i,o,s=null;function a(...e){if(!a.enabled)return;const n=a,i=Number(new Date),o=i-(r||i);n.diff=o,n.prev=r,n.curr=i,r=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(r,i)=>{if("%%"===r)return"%";s++;const o=t.formatters[i];if("function"==typeof o){const t=e[s];r=o.call(n,t),e.splice(s,1),s--}return r}),t.formatArgs.call(n,e);(n.log||t.log).apply(n,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=n,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function n(e,r){const n=t(this.namespace+("undefined"==typeof r?":":r)+e);return n.log=this.log,n}function i(e,t){let r=0,n=0,i=-1,o=0;for(;r<e.length;)if(n<t.length&&(t[n]===e[r]||"*"===t[n]))"*"===t[n]?(i=n,o=r,n++):(r++,n++);else{if(-1===i)return!1;n=i+1,o++,r=o}for(;n<t.length&&"*"===t[n];)n++;return n===t.length}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of r)"-"===e[0]?t.skips.push(e.slice(1)):t.names.push(e)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=r(6585),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}},778(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(9278)),o=n(r(5753)),s=n(r(6968)),a=(0,o.default)("mqttjs:tcp");t.default=(e,t)=>{if(t.port=t.port||1883,t.hostname=t.hostname||t.host||"localhost",t.socksProxy)return(0,s.default)(t.hostname,t.port,t.socksProxy,{timeout:t.socksTimeout});const{port:r,path:n}=t,o=t.hostname;return a("port %d and host %s",r,o),i.default.createConnection({port:r,host:o,path:n})}},823(e,t,r){"use strict";const n=globalThis.AbortController||r(6584).AbortController,{codes:{ERR_INVALID_ARG_VALUE:i,ERR_INVALID_ARG_TYPE:o,ERR_MISSING_ARGS:s,ERR_OUT_OF_RANGE:a},AbortError:c}=r(6371),{validateAbortSignal:l,validateInteger:u,validateObject:d}=r(277),h=r(4134).Symbol("kWeak"),p=r(4134).Symbol("kResistStopPropagation"),{finished:f}=r(6238),g=r(7830),{addAbortSignalNoValidate:m}=r(4147),{isWritable:b,isNodeStream:y}=r(6115),{deprecate:_}=r(7760),{ArrayPrototypePush:v,Boolean:S,MathFloor:w,Number:k,NumberIsNaN:E,Promise:I,PromiseReject:T,PromiseResolve:O,PromisePrototypeThen:C,Symbol:x}=r(4134),A=x("kEmpty"),P=x("kEof");function R(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal");let n=1;null!=(null==t?void 0:t.concurrency)&&(n=w(t.concurrency));let i=n-1;return null!=(null==t?void 0:t.highWaterMark)&&(i=w(t.highWaterMark)),u(n,"options.concurrency",1),u(i,"options.highWaterMark",0),i+=n,async function*(){const o=r(7760).AbortSignalAny([null==t?void 0:t.signal].filter(S)),s=this,a=[],l={signal:o};let u,d,h=!1,p=0;function f(){h=!0,g()}function g(){p-=1,m()}function m(){d&&!h&&p<n&&a.length<i&&(d(),d=null)}!async function(){try{for await(let t of s){if(h)return;if(o.aborted)throw new c;try{if(t=e(t,l),t===A)continue;t=O(t)}catch(e){t=T(e)}p+=1,C(t,g,f),a.push(t),u&&(u(),u=null),!h&&(a.length>=i||p>=n)&&await new I(e=>{d=e})}a.push(P)}catch(e){const t=T(e);C(t,g,f),a.push(t)}finally{h=!0,u&&(u(),u=null)}}();try{for(;;){for(;a.length>0;){const e=await a[0];if(e===P)return;if(o.aborted)throw new c;e!==A&&(yield e),a.shift(),m()}await new I(e=>{u=e})}}finally{h=!0,d&&(d(),d=null)}}.call(this)}async function M(e,t=void 0){for await(const r of B.call(this,e,t))return!0;return!1}function B(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return R.call(this,async function(t,r){return await e(t,r)?t:A},t)}class N extends s{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}}function j(e){if(e=k(e),E(e))return 0;if(e<0)throw new a("number",">= 0",e);return e}e.exports.streamReturningOperators={asIndexedPairs:_(function(e=void 0){return null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal"),async function*(){let t=0;for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c({cause:e.signal.reason});yield[t++,n]}}.call(this)},"readable.asIndexedPairs will be removed in a future version."),drop:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=j(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;e--<=0&&(yield r)}}.call(this)},filter:B,flatMap:function(e,t){const r=R.call(this,e,t);return async function*(){for await(const e of r)yield*e}.call(this)},map:R,take:function(e,t=void 0){return null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),e=j(e),async function*(){var r;if(null!=t&&null!==(r=t.signal)&&void 0!==r&&r.aborted)throw new c;for await(const r of this){var n;if(null!=t&&null!==(n=t.signal)&&void 0!==n&&n.aborted)throw new c;if(e-- >0&&(yield r),e<=0)return}}.call(this)},compose:function(e,t){if(null!=t&&d(t,"options"),null!=(null==t?void 0:t.signal)&&l(t.signal,"options.signal"),y(e)&&!b(e))throw new i("stream",e,"must be writable");const r=g(this,e);return null!=t&&t.signal&&m(t.signal,r),r}},e.exports.promiseReturningOperators={every:async function(e,t=void 0){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);return!await M.call(this,async(...t)=>!await e(...t),t)},forEach:async function(e,t){if("function"!=typeof e)throw new o("fn",["Function","AsyncFunction"],e);for await(const r of R.call(this,async function(t,r){return await e(t,r),A},t));},reduce:async function(e,t,r){var i;if("function"!=typeof e)throw new o("reducer",["Function","AsyncFunction"],e);null!=r&&d(r,"options"),null!=(null==r?void 0:r.signal)&&l(r.signal,"options.signal");let s=arguments.length>1;if(null!=r&&null!==(i=r.signal)&&void 0!==i&&i.aborted){const e=new c(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await f(this.destroy(e)),e}const a=new n,u=a.signal;if(null!=r&&r.signal){const e={once:!0,[h]:this,[p]:!0};r.signal.addEventListener("abort",()=>a.abort(),e)}let g=!1;try{for await(const n of this){var m;if(g=!0,null!=r&&null!==(m=r.signal)&&void 0!==m&&m.aborted)throw new c;s?t=await e(t,n,{signal:u}):(t=n,s=!0)}if(!g&&!s)throw new N}finally{a.abort()}return t},toArray:async function(e){null!=e&&d(e,"options"),null!=(null==e?void 0:e.signal)&&l(e.signal,"options.signal");const t=[];for await(const n of this){var r;if(null!=e&&null!==(r=e.signal)&&void 0!==r&&r.aborted)throw new c(void 0,{cause:e.signal.reason});v(t,n)}return t},some:M,find:async function(e,t){for await(const r of B.call(this,e,t))return r}}},837(e,t){"use strict";function r(e){return e.toString(16).padStart(2,"0")}Object.defineProperty(t,"__esModule",{value:!0}),t.isInSubnet=function(e){if(this.subnetMask<e.subnetMask)return!1;if(this.mask(e.subnetMask)===e.mask())return!0;return!1},t.isCorrect=function(e){return function(){return this.addressMinusSuffix===this.correctForm()&&(this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask))}},t.numberToPaddedHex=r,t.stringToPaddedHex=function(e){return r(parseInt(e,10))},t.testBit=function(e,t){const{length:r}=e;if(t>r)return!1;const n=r-t;return"1"===e.substring(n,n+1)}},857(e){"use strict";e.exports=require("os")},914(e,t,r){"use strict";const{Duplex:n}=r(2203),{randomFillSync:i}=r(6982),o=r(2971),{EMPTY_BUFFER:s,kWebSocket:a,NOOP:c}=r(2614),{isBlob:l,isValidStatusCode:u}=r(5880),{mask:d,toBuffer:h}=r(3338),p=Symbol("kByteLength"),f=Buffer.alloc(4),g=8192;let m,b=g;class y{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=c,this[a]=void 0}static frame(e,t){let r,n,o=!1,s=2,a=!1;t.mask&&(r=t.maskBuffer||f,t.generateMask?t.generateMask(r):(b===g&&(void 0===m&&(m=Buffer.alloc(g)),i(m,0,g),b=0),r[0]=m[b++],r[1]=m[b++],r[2]=m[b++],r[3]=m[b++]),a=0===(r[0]|r[1]|r[2]|r[3]),s=6),"string"==typeof e?n=t.mask&&!a||void 0===t[p]?(e=Buffer.from(e)).length:t[p]:(n=e.length,o=t.mask&&t.readOnly&&!a);let c=n;n>=65536?(s+=8,c=127):n>125&&(s+=2,c=126);const l=Buffer.allocUnsafe(o?n+s:s);return l[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,126===c?l.writeUInt16BE(n,2):127===c&&(l[2]=l[3]=0,l.writeUIntBE(n,4,6)),t.mask?(l[1]|=128,l[s-4]=r[0],l[s-3]=r[1],l[s-2]=r[2],l[s-1]=r[3],a?[l,e]:o?(d(e,r,l,s,n),[l]):(d(e,r,e,0,n),[l,e])):[l,e]}close(e,t,r,n){let i;if(void 0===e)i=s;else{if("number"!=typeof e||!u(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const r=Buffer.byteLength(t);if(r>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+r),i.writeUInt16BE(e,0),"string"==typeof t?i.write(t,2):i.set(t,2)}else i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0)}const o={[p]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,i,!1,o,n]):this.sendFrame(y.frame(i,o),n)}ping(e,t,r){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):l(e)?(n=e.size,i=!1):(n=(e=h(e)).length,i=h.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[p]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};l(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):0!==this._state?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(y.frame(e,o),r)}pong(e,t,r){let n,i;if("string"==typeof e?(n=Buffer.byteLength(e),i=!1):l(e)?(n=e.size,i=!1):(n=(e=h(e)).length,i=h.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[p]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};l(e)?0!==this._state?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):0!==this._state?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(y.frame(e,o),r)}send(e,t,r){const n=this._extensions[o.extensionName];let i,s,a=t.binary?2:1,c=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),s=!1):l(e)?(i=e.size,s=!1):(i=(e=h(e)).length,s=h.readOnly),this._firstFragment?(this._firstFragment=!1,c&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(c=i>=n._threshold),this._compress=c):(c=!1,a=0),t.fin&&(this._firstFragment=!0);const u={[p]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:s,rsv1:c};l(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):0!==this._state?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,t,r,n){this._bufferedBytes+=r[p],this._state=2,e.arrayBuffer().then(e=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(_,this,e,n)}this._bufferedBytes-=r[p];const i=h(e);t?this.dispatch(i,t,r,n):(this._state=0,this.sendFrame(y.frame(i,r),n),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,n)})}dispatch(e,t,r,n){if(!t)return void this.sendFrame(y.frame(e,r),n);const i=this._extensions[o.extensionName];this._bufferedBytes+=r[p],this._state=1,i.compress(e,r.fin,(e,t)=>{if(this._socket.destroyed){return void _(this,new Error("The socket was closed while data was being compressed"),n)}this._bufferedBytes-=r[p],this._state=0,r.readOnly=!1,this.sendFrame(y.frame(t,r),n),this.dequeue()})}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][p],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][p],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}function _(e,t,r){"function"==typeof r&&r(t);for(let r=0;r<e._queue.length;r++){const n=e._queue[r],i=n[n.length-1];"function"==typeof i&&i(t)}}function v(e,t,r){_(e,t,r),e.onerror(t)}e.exports=y},1021(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReasonCodes=void 0;const n=r(4723);t.ReasonCodes={0:"",1:"Unacceptable protocol version",2:"Identifier rejected",3:"Server unavailable",4:"Bad username or password",5:"Not authorized",16:"No matching subscribers",17:"No subscription existed",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",132:"Unsupported Protocol Version",133:"Client Identifier not valid",134:"Bad User Name or Password",135:"Not authorized",136:"Server unavailable",137:"Server busy",138:"Banned",139:"Server shutting down",140:"Bad authentication method",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",145:"Packet identifier in use",146:"Packet Identifier not found",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"};t.default=(e,r)=>{const{messageId:i}=r,o=r.cmd;let s=null;const a=e.outgoing[i]?e.outgoing[i].cb:null;let c=null;if(a){switch(e.log("_handleAck :: packet type",o),o){case"pubcomp":case"puback":{const o=r.reasonCode;o&&o>0&&16!==o?(c=new n.ErrorWithReasonCode(`Publish error: ${t.ReasonCodes[o]}`,o),e._removeOutgoingAndStoreMessage(i,()=>{a(c,r)})):e._removeOutgoingAndStoreMessage(i,a);break}case"pubrec":{s={cmd:"pubrel",qos:2,messageId:i};const o=r.reasonCode;o&&o>0&&16!==o?(c=new n.ErrorWithReasonCode(`Publish error: ${t.ReasonCodes[o]}`,o),e._removeOutgoingAndStoreMessage(i,()=>{a(c,r)})):e._sendPacket(s);break}case"suback":{delete e.outgoing[i],e.messageIdProvider.deallocate(i);const n=r.granted;for(let r=0;r<n.length;r++){const o=n[r];if(128&o){c=new Error(`Subscribe error: ${t.ReasonCodes[o]}`),c.code=o;const r=e.messageIdToTopic[i];r&&r.forEach(t=>{delete e._resubscribeTopics[t]})}}delete e.messageIdToTopic[i],e._invokeStoreProcessingQueue(),a(c,r);break}case"unsuback":delete e.outgoing[i],e.messageIdProvider.deallocate(i),e._invokeStoreProcessingQueue(),a(null,r);break;default:e.emit("error",new Error("unrecognized packet type"))}e.disconnecting&&0===Object.keys(e.outgoing).length&&e.emit("outgoingEmpty")}else e.log("_handleAck :: Server sent an ack in error. Ignoring.")}},1060(e,t,r){"use strict";const n=r(4434),i=r(5692),o=r(8611),s=r(9278),a=r(4756),{randomBytes:c,createHash:l}=r(6982),{Duplex:u,Readable:d}=r(2203),{URL:h}=r(7016),p=r(2971),f=r(6286),g=r(914),{isBlob:m}=r(5880),{BINARY_TYPES:b,EMPTY_BUFFER:y,GUID:_,kForOnEventAttribute:v,kListener:S,kStatusCode:w,kWebSocket:k,NOOP:E}=r(2614),{EventTarget:{addEventListener:I,removeEventListener:T}}=r(597),{format:O,parse:C}=r(5926),{toBuffer:x}=r(3338),A=Symbol("kAborted"),P=[8,13],R=["CONNECTING","OPEN","CLOSING","CLOSED"],M=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class B extends n{constructor(e,t,r){super(),this._binaryType=b[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=y,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=B.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(r=t,t=[]):t=[t]),N(this,e,t,r)):(this._autoPong=r.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){b.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){const n=new f({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new g(e,this._extensions,r.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[k]=this,i[k]=this,e[k]=this,n.on("conclude",$),n.on("drain",V),n.on("error",W),n.on("message",z),n.on("ping",q),n.on("pong",G),i.onerror=Q,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Z),e.on("data",J),e.on("end",X),e.on("error",ee),this._readyState=B.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=B.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[p.extensionName]&&this._extensions[p.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=B.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==B.CLOSED){if(this.readyState===B.CONNECTING){const e="WebSocket was closed before the connection was established";return void U(this,this._req,e)}this.readyState!==B.CLOSING?(this._readyState=B.CLOSING,this._sender.close(e,t,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Y(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==B.CONNECTING&&this.readyState!==B.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===B.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===B.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||y,t,r)):F(this,e,r)}pong(e,t,r){if(this.readyState===B.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(r=e,e=t=void 0):"function"==typeof t&&(r=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===B.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||y,t,r)):F(this,e,r)}resume(){this.readyState!==B.CONNECTING&&this.readyState!==B.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===B.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(r=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==B.OPEN)return void F(this,e,r);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[p.extensionName]||(n.compress=!1),this._sender.send(e||y,n,r)}terminate(){if(this.readyState!==B.CLOSED){if(this.readyState===B.CONNECTING){const e="WebSocket was closed before the connection was established";return void U(this,this._req,e)}this._socket&&(this._readyState=B.CLOSING,this._socket.destroy())}}}function N(e,t,r,n){const s={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:P[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=s.autoPong,!P.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${P.join(", ")})`);let a;if(t instanceof h)a=t;else try{a=new h(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===a.protocol?a.protocol="ws:":"https:"===a.protocol&&(a.protocol="wss:"),e._url=a.href;const u="wss:"===a.protocol,d="ws+unix:"===a.protocol;let f;if("ws:"===a.protocol||u||d?d&&!a.pathname?f="The URL's pathname is empty":a.hash&&(f="The URL contains a fragment identifier"):f='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"',f){const t=new SyntaxError(f);if(0===e._redirects)throw t;return void j(e,t)}const g=u?443:80,m=c(16).toString("base64"),b=u?i.request:o.request,y=new Set;let v,S;if(s.createConnection=s.createConnection||(u?L:D),s.defaultPort=s.defaultPort||g,s.port=a.port||g,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":m,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(v=new p(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=O({[p.extensionName]:v.offer()})),r.length){for(const e of r){if("string"!=typeof e||!M.test(e)||y.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");y.add(e)}s.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),d){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=d,e._originalSecure=u,e._originalHostOrSocketPath=d?s.socketPath:a.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,r]of Object.entries(t))n.headers[e.toLowerCase()]=r}else if(0===e.listenerCount("redirect")){const t=d?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&a.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),S=e._req=b(s),e._redirects&&e.emit("redirect",e.url,S)}else S=e._req=b(s);s.timeout&&S.on("timeout",()=>{U(e,S,"Opening handshake has timed out")}),S.on("error",t=>{null===S||S[A]||(S=e._req=null,j(e,t))}),S.on("response",i=>{const o=i.headers.location,a=i.statusCode;if(o&&s.followRedirects&&a>=300&&a<400){if(++e._redirects>s.maxRedirects)return void U(e,S,"Maximum redirects exceeded");let i;S.abort();try{i=new h(o,t)}catch(t){const r=new SyntaxError(`Invalid URL: ${o}`);return void j(e,r)}N(e,i,r,n)}else e.emit("unexpected-response",S,i)||U(e,S,`Unexpected server response: ${i.statusCode}`)}),S.on("upgrade",(t,r,n)=>{if(e.emit("upgrade",t),e.readyState!==B.CONNECTING)return;S=e._req=null;const i=t.headers.upgrade;if(void 0===i||"websocket"!==i.toLowerCase())return void U(e,r,"Invalid Upgrade header");const o=l("sha1").update(m+_).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void U(e,r,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?y.size?y.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":y.size&&(c="Server sent no subprotocol"),c)return void U(e,r,c);a&&(e._protocol=a);const u=t.headers["sec-websocket-extensions"];if(void 0!==u){if(!v){return void U(e,r,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=C(u)}catch(t){return void U(e,r,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==p.extensionName){return void U(e,r,"Server indicated an extension that was not requested")}try{v.accept(t[p.extensionName])}catch(t){return void U(e,r,"Invalid Sec-WebSocket-Extensions header")}e._extensions[p.extensionName]=v}e.setSocket(r,n,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(S,e):S.end()}function j(e,t){e._readyState=B.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function D(e){return e.path=e.socketPath,s.connect(e)}function L(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=s.isIP(e.host)?"":e.host),a.connect(e)}function U(e,t,r){e._readyState=B.CLOSING;const n=new Error(r);Error.captureStackTrace(n,U),t.setHeader?(t[A]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(j,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function F(e,t,r){if(t){const r=m(t)?t.size:x(t).length;e._socket?e._sender._bufferedBytes+=r:e._bufferedAmount+=r}if(r){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${R[e.readyState]})`);process.nextTick(r,t)}}function $(e,t){const r=this[k];r._closeFrameReceived=!0,r._closeMessage=t,r._closeCode=e,void 0!==r._socket[k]&&(r._socket.removeListener("data",J),process.nextTick(K,r._socket),1005===e?r.close():r.close(e,t))}function V(){const e=this[k];e.isPaused||e._socket.resume()}function W(e){const t=this[k];void 0!==t._socket[k]&&(t._socket.removeListener("data",J),process.nextTick(K,t._socket),t.close(e[w])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function H(){this[k].emitClose()}function z(e,t){this[k].emit("message",e,t)}function q(e){const t=this[k];t._autoPong&&t.pong(e,!this._isServer,E),t.emit("ping",e)}function G(e){this[k].emit("pong",e)}function K(e){e.resume()}function Q(e){const t=this[k];t.readyState!==B.CLOSED&&(t.readyState===B.OPEN&&(t._readyState=B.CLOSING,Y(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Y(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function Z(){const e=this[k];let t;this.removeListener("close",Z),this.removeListener("data",J),this.removeListener("end",X),e._readyState=B.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[k]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",H),e._receiver.on("finish",H))}function J(e){this[k]._receiver.write(e)||this.pause()}function X(){const e=this[k];e._readyState=B.CLOSING,e._receiver.end(),this.end()}function ee(){const e=this[k];this.removeListener("error",ee),this.on("error",E),e&&(e._readyState=B.CLOSING,this.destroy())}Object.defineProperty(B,"CONNECTING",{enumerable:!0,value:R.indexOf("CONNECTING")}),Object.defineProperty(B.prototype,"CONNECTING",{enumerable:!0,value:R.indexOf("CONNECTING")}),Object.defineProperty(B,"OPEN",{enumerable:!0,value:R.indexOf("OPEN")}),Object.defineProperty(B.prototype,"OPEN",{enumerable:!0,value:R.indexOf("OPEN")}),Object.defineProperty(B,"CLOSING",{enumerable:!0,value:R.indexOf("CLOSING")}),Object.defineProperty(B.prototype,"CLOSING",{enumerable:!0,value:R.indexOf("CLOSING")}),Object.defineProperty(B,"CLOSED",{enumerable:!0,value:R.indexOf("CLOSED")}),Object.defineProperty(B.prototype,"CLOSED",{enumerable:!0,value:R.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(e=>{Object.defineProperty(B.prototype,e,{enumerable:!0})}),["open","error","close","message"].forEach(e=>{Object.defineProperty(B.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[v])return t[S];return null},set(t){for(const t of this.listeners(e))if(t[v]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[v]:!0})}})}),B.prototype.addEventListener=I,B.prototype.removeEventListener=T,e.exports=B},1278(e,t,r){t.parser=r(3079).parser,t.generate=r(2535),t.writeToStream=r(3132)},1554(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createEmptyTopology=function(){return{version:"1.0",cameras:[],connections:[],globalZones:[]}},t.findCamera=function(e,t){return e.cameras.find(e=>e.deviceId===t)},t.findConnectionsFrom=function(e,t){return e.connections.filter(e=>e.fromCameraId===t||e.bidirectional&&e.toCameraId===t)},t.findConnection=function(e,t,r){return e.connections.find(e=>e.fromCameraId===t&&e.toCameraId===r||e.bidirectional&&e.fromCameraId===r&&e.toCameraId===t)},t.getEntryPoints=function(e){return e.cameras.filter(e=>e.isEntryPoint)},t.getExitPoints=function(e){return e.cameras.filter(e=>e.isExitPoint)}},1676(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||i(t,e,r)},c=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.ReasonCodes=t.KeepaliveManager=t.UniqueMessageIdProvider=t.DefaultMessageIdProvider=t.Store=t.MqttClient=t.connectAsync=t.connect=t.Client=void 0;const l=c(r(9777));t.MqttClient=l.default;const u=c(r(579));t.DefaultMessageIdProvider=u.default;const d=c(r(2099));t.UniqueMessageIdProvider=d.default;const h=c(r(7969));t.Store=h.default;const p=s(r(2793));t.connect=p.default,Object.defineProperty(t,"connectAsync",{enumerable:!0,get:function(){return p.connectAsync}});const f=c(r(3175));t.KeepaliveManager=f.default,t.Client=l.default,a(r(9777),t),a(r(4723),t);var g=r(1021);Object.defineProperty(t,"ReasonCodes",{enumerable:!0,get:function(){return g.ReasonCodes}})},1722(e,t,r){"use strict";const n=r(4434),i=r(8611),{Duplex:o}=r(2203),{createHash:s}=r(6982),a=r(5926),c=r(2971),l=r(8237),u=r(1060),{GUID:d,kWebSocket:h}=r(2614),p=/^[+/0-9A-Za-z]{22}==$/;function f(e){e._state=2,e.emit("close")}function g(){this.destroy()}function m(e,t,r,n){r=r||i.STATUS_CODES[t],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},e.once("finish",e.destroy),e.end(`HTTP/1.1 ${t} ${i.STATUS_CODES[t]}\r\n`+Object.keys(n).map(e=>`${e}: ${n[e]}`).join("\r\n")+"\r\n\r\n"+r)}function b(e,t,r,n,i,o){if(e.listenerCount("wsClientError")){const n=new Error(i);Error.captureStackTrace(n,b),e.emit("wsClientError",n,r,t)}else m(r,n,i,o)}e.exports=class extends n{constructor(e,t){if(super(),null==(e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:u,...e}).port&&!e.server&&!e.noServer||null!=e.port&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(null!=e.port?(this._server=i.createServer((e,t)=>{const r=i.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){const e=this.emit.bind(this,"connection");this._removeListeners=function(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(t,r,n)=>{this.handleUpgrade(t,r,n,e)}})}!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(2===this._state)return e&&this.once("close",()=>{e(new Error("The server is not running"))}),void process.nextTick(f,this);if(e&&this.once("close",e),1!==this._state)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(f,this);else{const e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{f(this)})}}shouldHandle(e){if(this.options.path){const t=e.url.indexOf("?");if((-1!==t?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,n){t.on("error",g);const i=e.headers["sec-websocket-key"],o=e.headers.upgrade,s=+e.headers["sec-websocket-version"];if("GET"!==e.method){return void b(this,e,t,405,"Invalid HTTP method")}if(void 0===o||"websocket"!==o.toLowerCase()){return void b(this,e,t,400,"Invalid Upgrade header")}if(void 0===i||!p.test(i)){return void b(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header")}if(13!==s&&8!==s){return void b(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"})}if(!this.shouldHandle(e))return void m(t,400);const u=e.headers["sec-websocket-protocol"];let d=new Set;if(void 0!==u)try{d=l.parse(u)}catch(r){return void b(this,e,t,400,"Invalid Sec-WebSocket-Protocol header")}const h=e.headers["sec-websocket-extensions"],f={};if(this.options.perMessageDeflate&&void 0!==h){const r=new c(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const e=a.parse(h);e[c.extensionName]&&(r.accept(e[c.extensionName]),f[c.extensionName]=r)}catch(r){return void b(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header")}}if(this.options.verifyClient){const o={origin:e.headers[""+(8===s?"sec-websocket-origin":"origin")],secure:!(!e.socket.authorized&&!e.socket.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(o,(o,s,a,c)=>{if(!o)return m(t,s||401,a,c);this.completeUpgrade(f,i,d,e,t,r,n)});if(!this.options.verifyClient(o))return m(t,401)}this.completeUpgrade(f,i,d,e,t,r,n)}completeUpgrade(e,t,r,n,i,o,l){if(!i.readable||!i.writable)return i.destroy();if(i[h])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return m(i,503);const u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${s("sha1").update(t+d).digest("base64")}`],p=new this.options.WebSocket(null,void 0,this.options);if(r.size){const e=this.options.handleProtocols?this.options.handleProtocols(r,n):r.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[c.extensionName]){const t=e[c.extensionName].params,r=a.format({[c.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${r}`),p._extensions=e}this.emit("headers",u,n),i.write(u.concat("\r\n").join("\r\n")),i.removeListener("error",g),p.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on("close",()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(f,this)})),l(p,n)}}},1725(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(181),i={INVALID_ENCODING:"Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.",INVALID_SMARTBUFFER_SIZE:"Invalid size provided. Size must be a valid integer greater than zero.",INVALID_SMARTBUFFER_BUFFER:"Invalid Buffer provided in SmartBufferOptions.",INVALID_SMARTBUFFER_OBJECT:"Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.",INVALID_OFFSET:"An invalid offset value was provided.",INVALID_OFFSET_NON_NUMBER:"An invalid offset value was provided. A numeric value is required.",INVALID_LENGTH:"An invalid length value was provided.",INVALID_LENGTH_NON_NUMBER:"An invalid length value was provived. A numeric value is required.",INVALID_TARGET_OFFSET:"Target offset is beyond the bounds of the internal SmartBuffer data.",INVALID_TARGET_LENGTH:"Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.",INVALID_READ_BEYOND_BOUNDS:"Attempted to read beyond the bounds of the managed data.",INVALID_WRITE_BEYOND_BOUNDS:"Attempted to write beyond the bounds of the managed data."};function o(e){return"number"==typeof e&&isFinite(e)&&function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e}(e)}function s(e,t){if("number"!=typeof e)throw new Error(t?i.INVALID_OFFSET_NON_NUMBER:i.INVALID_LENGTH_NON_NUMBER);if(!o(e)||e<0)throw new Error(t?i.INVALID_OFFSET:i.INVALID_LENGTH)}t.ERRORS=i,t.checkEncoding=function(e){if(!n.Buffer.isEncoding(e))throw new Error(i.INVALID_ENCODING)},t.isFiniteInteger=o,t.checkLengthValue=function(e){s(e,!1)},t.checkOffsetValue=function(e){s(e,!0)},t.checkTargetOffset=function(e,t){if(e<0||e>t.length)throw new Error(i.INVALID_TARGET_OFFSET)},t.bigIntAndBufferInt64Check=function(e){if("undefined"==typeof BigInt)throw new Error("Platform does not support JS BigInt type.");if("undefined"==typeof n.Buffer.prototype[e])throw new Error(`Platform does not support Buffer.prototype.${e}.`)}},2017(e,t,r){try{var n=r(9023);if("function"!=typeof n.inherits)throw"";e.exports=n.inherits}catch(t){e.exports=r(6698)}},2018(e){"use strict";e.exports=require("tty")},2099(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(720);t.default=class{numberAllocator;lastId;constructor(){this.numberAllocator=new n.NumberAllocator(1,65535)}allocate(){return this.lastId=this.numberAllocator.alloc(),this.lastId}getLastAllocated(){return this.lastId}register(e){return this.numberAllocator.use(e)}deallocate(e){this.numberAllocator.free(e)}clear(){this.numberAllocator.clear()}}},2203(e){"use strict";e.exports=require("stream")},2250(e){"use strict";e.exports=require("dns")},2437(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AddressError=void 0;class r extends Error{constructor(e,t){super(e),this.name="AddressError",this.parseMessage=t}}t.AddressError=r},2535(e,t,r){const n=r(3132),{EventEmitter:i}=r(4434),{Buffer:o}=r(181);class s extends i{constructor(){super(),this._array=new Array(20),this._i=0}write(e){return this._array[this._i++]=e,!0}concat(){let e=0;const t=new Array(this._array.length),r=this._array;let n,i=0;for(n=0;n<r.length&&void 0!==r[n];n++)"string"!=typeof r[n]?t[n]=r[n].length:t[n]=o.byteLength(r[n]),e+=t[n];const s=o.allocUnsafe(e);for(n=0;n<r.length&&void 0!==r[n];n++)"string"!=typeof r[n]?(r[n].copy(s,i),i+=t[n]):(s.write(r[n],i),i+=t[n]);return s}destroy(e){e&&this.emit("error",e)}}e.exports=function(e,t){const r=new s;return n(e,r,t),r.concat()}},2613(e){"use strict";e.exports=require("assert")},2614(e){"use strict";const t=["nodebuffer","arraybuffer","fragments"],r="undefined"!=typeof Blob;r&&t.push("blob"),e.exports={BINARY_TYPES:t,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:r,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}},2635(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BufferedDuplex=void 0,t.writev=o;const n=r(4478),i=r(181);function o(e,t){const r=new Array(e.length);for(let t=0;t<e.length;t++)"string"==typeof e[t].chunk?r[t]=i.Buffer.from(e[t].chunk,"utf8"):r[t]=e[t].chunk;this._write(i.Buffer.concat(r),"binary",t)}class s extends n.Duplex{socket;proxy;isSocketOpen;writeQueue;constructor(e,t,r){super({objectMode:!0}),this.proxy=t,this.socket=r,this.writeQueue=[],e.objectMode||(this._writev=o.bind(this)),this.isSocketOpen=!1,this.proxy.on("data",e=>{!this.destroyed&&this.readable&&this.push(e)})}_read(e){this.proxy.read(e)}_write(e,t,r){this.isSocketOpen?this.writeToProxy(e,t,r):this.writeQueue.push({chunk:e,encoding:t,cb:r})}_final(e){this.writeQueue=[],this.proxy.end(e)}_destroy(e,t){this.writeQueue=[],this.proxy.destroy(),t(e)}socketReady(){this.emit("connect"),this.isSocketOpen=!0,this.processWriteQueue()}writeToProxy(e,t,r){!1===this.proxy.write(e,t)?this.proxy.once("drain",r):r()}processWriteQueue(){for(;this.writeQueue.length>0;){const{chunk:e,encoding:t,cb:r}=this.writeQueue.shift();this.writeToProxy(e,t,r)}}}t.BufferedDuplex=s},2639(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=class{aliasToTopic;max;length;constructor(e){this.aliasToTopic={},this.max=e}put(e,t){return!(0===t||t>this.max)&&(this.aliasToTopic[t]=e,this.length=Object.keys(this.aliasToTopic).length,!0)}getTopicByAlias(e){return this.aliasToTopic[e]}clear(){this.aliasToTopic={}}}},2793(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.connectAsync=function(e,t,r=!0){return new Promise((n,i)=>{const o=u(e,t),s={connect:e=>{a(),n(o)},end:()=>{a(),n(o)},error:e=>{a(),o.end(),i(e)}};function a(){Object.keys(s).forEach(e=>{o.off(e,s[e])})}!1===r&&(s.close=()=>{s.error(new Error("Couldn't connect to server"))}),Object.keys(s).forEach(e=>{o.on(e,s[e])})})};const i=n(r(5753)),o=n(r(7016)),s=n(r(9777)),a=n(r(6887));"function"!=typeof process?.nextTick&&(process.nextTick=setImmediate);const c=(0,i.default)("mqttjs");let l=null;function u(e,t){if(c("connecting to an MQTT broker..."),"object"!=typeof e||t||(t=e,e=""),t=t||{},e&&"string"==typeof e){const r=o.default.parse(e,!0),n={};if(null!=r.port&&(n.port=Number(r.port)),n.host=r.hostname,n.query=r.query,n.auth=r.auth,n.protocol=r.protocol,n.path=r.path,!(t={...n,...t}).protocol)throw new Error("Missing protocol");t.protocol=t.protocol.replace(/:$/,"")}if(t.unixSocket=t.unixSocket||t.protocol?.includes("+unix"),t.unixSocket?t.protocol=t.protocol.replace("+unix",""):t.protocol?.startsWith("ws")||t.protocol?.startsWith("wx")||delete t.path,function(e){let t;if(e.auth)if(t=e.auth.match(/^(.+):(.+)$/),t){const[,r,n]=t;e.username=r,e.password=n}else e.username=e.auth}(t),t.query&&"string"==typeof t.query.clientId&&(t.clientId=t.query.clientId),a.default||t.unixSocket?t.socksProxy=void 0:void 0===t.socksProxy&&"undefined"!=typeof process&&(t.socksProxy=process.env.MQTTJS_SOCKS_PROXY),t.cert&&t.key){if(!t.protocol)throw new Error("Missing secure protocol key");if(-1===["mqtts","wss","wxs","alis"].indexOf(t.protocol))switch(t.protocol){case"mqtt":t.protocol="mqtts";break;case"ws":t.protocol="wss";break;case"wx":t.protocol="wxs";break;case"ali":t.protocol="alis";break;default:throw new Error(`Unknown protocol for secure connection: "${t.protocol}"!`)}}if(l||(l={},a.default||t.forceNativeWebSocket?(l.ws=r(8203).browserStreamBuilder,l.wss=r(8203).browserStreamBuilder,l.wx=r(5670).A,l.wxs=r(5670).A,l.ali=r(397).A,l.alis=r(397).A):(l.ws=r(8203).streamBuilder,l.wss=r(8203).streamBuilder,l.mqtt=r(778).default,l.tcp=r(778).default,l.ssl=r(3936).default,l.tls=l.ssl,l.mqtts=r(3936).default)),!l[t.protocol]){const e=-1!==["mqtts","wss"].indexOf(t.protocol);t.protocol=["mqtt","mqtts","ws","wss","wx","wxs","ali","alis"].filter((t,r)=>(!e||r%2!=0)&&"function"==typeof l[t])[0]}if(!1===t.clean&&!t.clientId)throw new Error("Missing clientId for unclean clients");t.protocol&&(t.defaultProtocol=t.protocol);const n=new s.default(function(e){return t.servers&&(e._reconnectCount&&e._reconnectCount!==t.servers.length||(e._reconnectCount=0),t.host=t.servers[e._reconnectCount].host,t.port=t.servers[e._reconnectCount].port,t.protocol=t.servers[e._reconnectCount].protocol?t.servers[e._reconnectCount].protocol:t.defaultProtocol,t.hostname=t.host,e._reconnectCount++),c("calling streambuilder for",t.protocol),l[t.protocol](e,t)},t);return n.on("error",()=>{}),n}t.default=u},2839(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Address4=void 0;const s=o(r(837)),a=o(r(9576)),c=r(2437);class l{constructor(e){this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet="",this.subnet="/32",this.subnetMask=32,this.v4=!0,this.isCorrect=s.isCorrect(a.BITS),this.isInSubnet=s.isInSubnet,this.address=e;const t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new c.AddressError("Invalid subnet mask.");e=e.replace(a.RE_SUBNET_STRING,"")}this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(e){try{return new l(e),!0}catch(e){return!1}}parse(e){const t=e.split(".");if(!e.match(a.RE_ADDRESS))throw new c.AddressError("Invalid IPv4 address.");return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(".")}static fromHex(e){const t=e.replace(/:/g,"").padStart(8,"0"),r=[];let n;for(n=0;n<8;n+=2){const e=t.slice(n,n+2);r.push(parseInt(e,16))}return new l(r.join("."))}static fromInteger(e){return l.fromHex(e.toString(16))}static fromArpa(e){const t=e.replace(/(\.in-addr\.arpa)?\.$/,"").split(".").reverse().join(".");return new l(t)}toHex(){return this.parsedAddress.map(e=>s.stringToPaddedHex(e)).join(":")}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){const e=[];let t;for(t=0;t<a.GROUPS;t+=2)e.push(`${s.stringToPaddedHex(this.parsedAddress[t])}${s.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>s.stringToPaddedHex(e)).join("")}`)}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(a.BITS-this.subnetMask)}`)}startAddress(){return l.fromBigInt(this._startAddress())}startAddressExclusive(){const e=BigInt("1");return l.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(a.BITS-this.subnetMask)}`)}endAddress(){return l.fromBigInt(this._endAddress())}endAddressExclusive(){const e=BigInt("1");return l.fromBigInt(this._endAddress()-e)}static fromBigInt(e){return l.fromHex(e.toString(16))}static fromByteArray(e){if(4!==e.length)throw new c.AddressError("IPv4 addresses require exactly 4 bytes");for(let t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)throw new c.AddressError("All bytes must be integers between 0 and 255");return this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(e){if(4!==e.length)throw new c.AddressError("IPv4 addresses require exactly 4 bytes");const t=e.join(".");return new l(t)}mask(e){return void 0===e&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||(e={});const t=this.correctForm().split(".").reverse().join(".");return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isInSubnet(new l("224.0.0.0/4"))}binaryZeroPad(){return this.bigInt().toString(2).padStart(a.BITS,"0")}groupForV6(){const e=this.parsedAddress;return this.address.replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(".")}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(".")}</span>`)}}t.Address4=l},2846(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TrackingZone=void 0;const n=r(7562),i=r(6117);class o extends n.ScryptedDeviceBase{trackingState;plugin;config={type:"entry",cameras:[]};storageSettings=new i.StorageSettings(this,{zoneType:{title:"Zone Type",type:"string",choices:["entry","exit","dwell","restricted"],defaultValue:"entry",description:"Type of zone for alerting purposes"},cameras:{title:"Cameras",type:"device",multiple:!0,deviceFilter:`interfaces.includes('${n.ScryptedInterface.ObjectDetector}')`,description:"Cameras that make up this zone"},dwellThreshold:{title:"Dwell Time Threshold (seconds)",type:"number",defaultValue:60,description:"For dwell zones: alert if object stays longer than this"},trackClasses:{title:"Track Object Types",type:"string",multiple:!0,choices:["person","car","vehicle","animal","package"],description:"Object types to monitor in this zone (empty = all)"}});constructor(e,t,r){super(t),this.plugin=e,this.trackingState=r,this.loadConfig(),r.onStateChange(()=>this.evaluateZone()),this.evaluateZone()}loadConfig(){try{const e=this.storage.getItem("zoneConfig");e&&(this.config=JSON.parse(e))}catch(e){this.console.error("Failed to load zone config:",e)}}saveConfig(){try{this.storage.setItem("zoneConfig",JSON.stringify(this.config))}catch(e){this.console.error("Failed to save zone config:",e)}}configure(e){this.config={...this.config,...e},this.saveConfig(),this.evaluateZone()}evaluateZone(){const e=this.getCameraIds();if(0===e.length)return this.occupied=!1,void(this.motionDetected=!1);const t=this.storageSettings.values.trackClasses||[];let r=!1,n=!1;const i=Date.now();for(const o of e){const e=this.trackingState.getObjectsOnCamera(o);for(const s of e){if(t.length>0&&!t.includes(s.className))continue;r=!0;s.sightings.filter(e=>e.cameraId===o&&i-e.timestamp<5e3).some(e=>e.detection.movement?.moving)&&(n=!0)}}this.occupied=r,this.motionDetected=n}getCameraIds(){const e=this.storageSettings.values.cameras;return Array.isArray(e)?e:e?[e]:this.config.cameras||[]}getObjectsInZone(){const e=this.getCameraIds(),t=this.storageSettings.values.trackClasses||[],r=[],n=new Set;for(const i of e)for(const e of this.trackingState.getObjectsOnCamera(i))n.has(e.globalId)||(n.add(e.globalId),(0===t.length||t.includes(e.className))&&r.push(e));return r}async getSettings(){const e=await this.storageSettings.getSettings(),t=this.getObjectsInZone();return e.push({key:"currentStatus",title:"Current Status",type:"string",readonly:!0,value:this.occupied?`Occupied: ${t.length} object${1!==t.length?"s":""}`:"Empty",group:"Status"}),t.length>0&&e.push({key:"objectsList",title:"Objects in Zone",type:"string",readonly:!0,value:t.map(e=>`${e.className}${e.label?` (${e.label})`:""}`).join(", "),group:"Status"}),e}async putSetting(e,t){await this.storageSettings.putSetting(e,t),this.config.type=this.storageSettings.values.zoneType||"entry",this.config.cameras=this.getCameraIds(),this.config.dwellThreshold=1e3*(this.storageSettings.values.dwellThreshold||60),this.saveConfig(),this.evaluateZone()}}t.TrackingZone=o},2860(e){"use strict";e.exports={version:"5.14.1"}},2861(e,t,r){var n=r(181),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function s(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=n:(o(n,t),t.Buffer=s),s.prototype=Object.create(i.prototype),o(i,s),s.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},s.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},s.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},s.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},2971(e,t,r){"use strict";const n=r(3106),i=r(3338),o=r(4759),{kStatusCode:s}=r(2614),a=Buffer[Symbol.species],c=Buffer.from([0,0,255,255]),l=Symbol("permessage-deflate"),u=Symbol("total-length"),d=Symbol("callback"),h=Symbol("buffers"),p=Symbol("error");let f;function g(e){this[h].push(e),this[u]+=e.length}function m(e){this[u]+=e.length,this[l]._maxPayload<1||this[u]<=this[l]._maxPayload?this[h].push(e):(this[p]=new RangeError("Max payload size exceeded"),this[p].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[p][s]=1009,this.removeListener("data",m),this.reset())}function b(e){this[l]._inflate=null,this[p]?this[d](this[p]):(e[s]=1007,this[d](e))}e.exports=class{constructor(e,t,r){if(this._maxPayload=0|r,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!f){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;f=new o(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[d];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,r=e.find(e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(r.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?r.client_max_window_bits=t.clientMaxWindowBits:!0!==r.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete r.client_max_window_bits,r}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let r=e[t];if(r.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(r=r[0],"client_max_window_bits"===t){if(!0!==r){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}else if("server_max_window_bits"===t){const e=+r;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${r}`);r=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==r)throw new TypeError(`Invalid value for parameter "${t}": ${r}`)}e[t]=r})}),e}decompress(e,t,r){f.add(n=>{this._decompress(e,t,(e,t)=>{n(),r(e,t)})})}compress(e,t,r){f.add(n=>{this._compress(e,t,(e,t)=>{n(),r(e,t)})})}_decompress(e,t,r){const o=this._isServer?"client":"server";if(!this._inflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[l]=this,this._inflate[u]=0,this._inflate[h]=[],this._inflate.on("error",b),this._inflate.on("data",m)}this._inflate[d]=r,this._inflate.write(e),t&&this._inflate.write(c),this._inflate.flush(()=>{const e=this._inflate[p];if(e)return this._inflate.close(),this._inflate=null,void r(e);const n=i.concat(this._inflate[h],this._inflate[u]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[u]=0,this._inflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),r(null,n)})}_compress(e,t,r){const o=this._isServer?"server":"client";if(!this._deflate){const e=`${o}_max_window_bits`,t="number"!=typeof this.params[e]?n.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[u]=0,this._deflate[h]=[],this._deflate.on("data",g)}this._deflate[d]=r,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=i.concat(this._deflate[h],this._deflate[u]);t&&(e=new a(e.buffer,e.byteOffset,e.length-4)),this._deflate[d]=null,this._deflate[u]=0,this._deflate[h]=[],t&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),r(null,e)})}}},3079(e,t,r){const n=r(4829),{EventEmitter:i}=r(4434),o=r(576),s=r(5399),a=r(5753)("mqtt-packet:parser");class c extends i{constructor(){super(),this.parser=this.constructor.parser}static parser(e){return this instanceof c?(this.settings=e||{},this._states=["_parseHeader","_parseLength","_parsePayload","_newPacket"],this._resetState(),this):(new c).parser(e)}_resetState(){a("_resetState: resetting packet, error, _list, and _stateCounter"),this.packet=new o,this.error=null,this._list=n(),this._stateCounter=0}parse(e){for(this.error&&this._resetState(),this._list.append(e),a("parse: current state: %s",this._states[this._stateCounter]);(-1!==this.packet.length||this._list.length>0)&&this[this._states[this._stateCounter]]()&&!this.error;)this._stateCounter++,a("parse: state complete. _stateCounter is now: %d",this._stateCounter),a("parse: packet.length: %d, buffer list length: %d",this.packet.length,this._list.length),this._stateCounter>=this._states.length&&(this._stateCounter=0);return a("parse: exited while loop. packet: %d, buffer list length: %d",this.packet.length,this._list.length),this._list.length}_parseHeader(){const e=this._list.readUInt8(0),t=e>>s.CMD_SHIFT;this.packet.cmd=s.types[t];const r=15&e,n=s.requiredHeaderFlags[t];return null!=n&&r!==n?this._emitError(new Error(s.requiredHeaderFlagsErrors[t])):(this.packet.retain=0!==(e&s.RETAIN_MASK),this.packet.qos=e>>s.QOS_SHIFT&s.QOS_MASK,this.packet.qos>2?this._emitError(new Error("Packet must not have both QoS bits set to 1")):(this.packet.dup=0!==(e&s.DUP_MASK),a("_parseHeader: packet: %o",this.packet),this._list.consume(1),!0))}_parseLength(){const e=this._parseVarByteNum(!0);return e&&(this.packet.length=e.value,this._list.consume(e.bytes)),a("_parseLength %d",e.value),!!e}_parsePayload(){a("_parsePayload: payload %O",this._list);let e=!1;if(0===this.packet.length||this._list.length>=this.packet.length){switch(this._pos=0,this.packet.cmd){case"connect":this._parseConnect();break;case"connack":this._parseConnack();break;case"publish":this._parsePublish();break;case"puback":case"pubrec":case"pubrel":case"pubcomp":this._parseConfirmation();break;case"subscribe":this._parseSubscribe();break;case"suback":this._parseSuback();break;case"unsubscribe":this._parseUnsubscribe();break;case"unsuback":this._parseUnsuback();break;case"pingreq":case"pingresp":break;case"disconnect":this._parseDisconnect();break;case"auth":this._parseAuth();break;default:this._emitError(new Error("Not supported"))}e=!0}return a("_parsePayload complete result: %s",e),e}_parseConnect(){let e,t,r,n;a("_parseConnect");const i={},o=this.packet,c=this._parseString();if(null===c)return this._emitError(new Error("Cannot parse protocolId"));if("MQTT"!==c&&"MQIsdp"!==c)return this._emitError(new Error("Invalid protocolId"));if(o.protocolId=c,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(o.protocolVersion=this._list.readUInt8(this._pos),o.protocolVersion>=128&&(o.bridgeMode=!0,o.protocolVersion=o.protocolVersion-128),3!==o.protocolVersion&&4!==o.protocolVersion&&5!==o.protocolVersion)return this._emitError(new Error("Invalid protocol version"));if(this._pos++,this._pos>=this._list.length)return this._emitError(new Error("Packet too short"));if(1&this._list.readUInt8(this._pos))return this._emitError(new Error("Connect flag bit 0 must be 0, but got 1"));i.username=this._list.readUInt8(this._pos)&s.USERNAME_MASK,i.password=this._list.readUInt8(this._pos)&s.PASSWORD_MASK,i.will=this._list.readUInt8(this._pos)&s.WILL_FLAG_MASK;const l=!!(this._list.readUInt8(this._pos)&s.WILL_RETAIN_MASK),u=(this._list.readUInt8(this._pos)&s.WILL_QOS_MASK)>>s.WILL_QOS_SHIFT;if(i.will)o.will={},o.will.retain=l,o.will.qos=u;else{if(l)return this._emitError(new Error("Will Retain Flag must be set to zero when Will Flag is set to 0"));if(u)return this._emitError(new Error("Will QoS must be set to zero when Will Flag is set to 0"))}if(o.clean=0!==(this._list.readUInt8(this._pos)&s.CLEAN_SESSION_MASK),this._pos++,o.keepalive=this._parseNum(),-1===o.keepalive)return this._emitError(new Error("Packet too short"));if(5===o.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(o.properties=e)}const d=this._parseString();if(null===d)return this._emitError(new Error("Packet too short"));if(o.clientId=d,a("_parseConnect: packet.clientId: %s",o.clientId),i.will){if(5===o.protocolVersion){const e=this._parseProperties();Object.getOwnPropertyNames(e).length&&(o.will.properties=e)}if(e=this._parseString(),null===e)return this._emitError(new Error("Cannot parse will topic"));if(o.will.topic=e,a("_parseConnect: packet.will.topic: %s",o.will.topic),t=this._parseBuffer(),null===t)return this._emitError(new Error("Cannot parse will payload"));o.will.payload=t,a("_parseConnect: packet.will.paylaod: %s",o.will.payload)}if(i.username){if(n=this._parseString(),null===n)return this._emitError(new Error("Cannot parse username"));o.username=n,a("_parseConnect: packet.username: %s",o.username)}if(i.password){if(r=this._parseBuffer(),null===r)return this._emitError(new Error("Cannot parse password"));o.password=r}return this.settings=o,a("_parseConnect: complete"),o}_parseConnack(){a("_parseConnack");const e=this.packet;if(this._list.length<1)return null;const t=this._list.readUInt8(this._pos++);if(t>1)return this._emitError(new Error("Invalid connack flags, bits 7-1 must be set to 0"));if(e.sessionPresent=!!(t&s.SESSIONPRESENT_MASK),5===this.settings.protocolVersion)this._list.length>=2?e.reasonCode=this._list.readUInt8(this._pos++):e.reasonCode=0;else{if(this._list.length<2)return null;e.returnCode=this._list.readUInt8(this._pos++)}if(-1===e.returnCode||-1===e.reasonCode)return this._emitError(new Error("Cannot parse return code"));if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}a("_parseConnack: complete")}_parsePublish(){a("_parsePublish");const e=this.packet;if(e.topic=this._parseString(),null===e.topic)return this._emitError(new Error("Cannot parse topic"));if(!(e.qos>0)||this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}e.payload=this._list.slice(this._pos,e.length),a("_parsePublish: payload from buffer list: %o",e.payload)}}_parseSubscribe(){a("_parseSubscribe");const e=this.packet;let t,r,n,i,o,c,l;if(e.subscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}if(e.length<=0)return this._emitError(new Error("Malformed subscribe, no payload specified"));for(;this._pos<e.length;){if(t=this._parseString(),null===t)return this._emitError(new Error("Cannot parse topic"));if(this._pos>=e.length)return this._emitError(new Error("Malformed Subscribe Payload"));if(r=this._parseByte(),5===this.settings.protocolVersion){if(192&r)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-6 must be 0"))}else if(252&r)return this._emitError(new Error("Invalid subscribe topic flag bits, bits 7-2 must be 0"));if(n=r&s.SUBSCRIBE_OPTIONS_QOS_MASK,n>2)return this._emitError(new Error("Invalid subscribe QoS, must be <= 2"));if(c=0!==(r>>s.SUBSCRIBE_OPTIONS_NL_SHIFT&s.SUBSCRIBE_OPTIONS_NL_MASK),o=0!==(r>>s.SUBSCRIBE_OPTIONS_RAP_SHIFT&s.SUBSCRIBE_OPTIONS_RAP_MASK),i=r>>s.SUBSCRIBE_OPTIONS_RH_SHIFT&s.SUBSCRIBE_OPTIONS_RH_MASK,i>2)return this._emitError(new Error("Invalid retain handling, must be <= 2"));l={topic:t,qos:n},5===this.settings.protocolVersion?(l.nl=c,l.rap=o,l.rh=i):this.settings.bridgeMode&&(l.rh=0,l.rap=!0,l.nl=!0),a("_parseSubscribe: push subscription `%s` to subscription",l),e.subscriptions.push(l)}}}_parseSuback(){a("_parseSuback");const e=this.packet;if(this.packet.granted=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}if(e.length<=0)return this._emitError(new Error("Malformed suback, no payload specified"));for(;this._pos<this.packet.length;){const e=this._list.readUInt8(this._pos++);if(5===this.settings.protocolVersion){if(!s.MQTT5_SUBACK_CODES[e])return this._emitError(new Error("Invalid suback code"))}else if(e>2&&128!==e)return this._emitError(new Error("Invalid suback QoS, must be 0, 1, 2 or 128"));this.packet.granted.push(e)}}}_parseUnsubscribe(){a("_parseUnsubscribe");const e=this.packet;if(e.unsubscriptions=[],this._parseMessageId()){if(5===this.settings.protocolVersion){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}if(e.length<=0)return this._emitError(new Error("Malformed unsubscribe, no payload specified"));for(;this._pos<e.length;){const t=this._parseString();if(null===t)return this._emitError(new Error("Cannot parse topic"));a("_parseUnsubscribe: push topic `%s` to unsubscriptions",t),e.unsubscriptions.push(t)}}}_parseUnsuback(){a("_parseUnsuback");const e=this.packet;if(!this._parseMessageId())return this._emitError(new Error("Cannot parse messageId"));if((3===this.settings.protocolVersion||4===this.settings.protocolVersion)&&2!==e.length)return this._emitError(new Error("Malformed unsuback, payload length must be 2"));if(e.length<=0)return this._emitError(new Error("Malformed unsuback, no payload specified"));if(5===this.settings.protocolVersion){const t=this._parseProperties();for(Object.getOwnPropertyNames(t).length&&(e.properties=t),e.granted=[];this._pos<this.packet.length;){const e=this._list.readUInt8(this._pos++);if(!s.MQTT5_UNSUBACK_CODES[e])return this._emitError(new Error("Invalid unsuback code"));this.packet.granted.push(e)}}}_parseConfirmation(){a("_parseConfirmation: packet.cmd: `%s`",this.packet.cmd);const e=this.packet;if(this._parseMessageId(),5===this.settings.protocolVersion){if(e.length>2){switch(e.reasonCode=this._parseByte(),this.packet.cmd){case"puback":case"pubrec":if(!s.MQTT5_PUBACK_PUBREC_CODES[e.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"));break;case"pubrel":case"pubcomp":if(!s.MQTT5_PUBREL_PUBCOMP_CODES[e.reasonCode])return this._emitError(new Error("Invalid "+this.packet.cmd+" reason code"))}a("_parseConfirmation: packet.reasonCode `%d`",e.reasonCode)}else e.reasonCode=0;if(e.length>3){const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}}return!0}_parseDisconnect(){const e=this.packet;if(a("_parseDisconnect"),5===this.settings.protocolVersion){this._list.length>0?(e.reasonCode=this._parseByte(),s.MQTT5_DISCONNECT_CODES[e.reasonCode]||this._emitError(new Error("Invalid disconnect reason code"))):e.reasonCode=0;const t=this._parseProperties();Object.getOwnPropertyNames(t).length&&(e.properties=t)}return a("_parseDisconnect result: true"),!0}_parseAuth(){a("_parseAuth");const e=this.packet;if(5!==this.settings.protocolVersion)return this._emitError(new Error("Not supported auth packet for this version MQTT"));if(e.reasonCode=this._parseByte(),!s.MQTT5_AUTH_CODES[e.reasonCode])return this._emitError(new Error("Invalid auth reason code"));const t=this._parseProperties();return Object.getOwnPropertyNames(t).length&&(e.properties=t),a("_parseAuth: result: true"),!0}_parseMessageId(){const e=this.packet;return e.messageId=this._parseNum(),null===e.messageId?(this._emitError(new Error("Cannot parse messageId")),!1):(a("_parseMessageId: packet.messageId %d",e.messageId),!0)}_parseString(e){const t=this._parseNum(),r=t+this._pos;if(-1===t||r>this._list.length||r>this.packet.length)return null;const n=this._list.toString("utf8",this._pos,r);return this._pos+=t,a("_parseString: result: %s",n),n}_parseStringPair(){return a("_parseStringPair"),{name:this._parseString(),value:this._parseString()}}_parseBuffer(){const e=this._parseNum(),t=e+this._pos;if(-1===e||t>this._list.length||t>this.packet.length)return null;const r=this._list.slice(this._pos,t);return this._pos+=e,a("_parseBuffer: result: %o",r),r}_parseNum(){if(this._list.length-this._pos<2)return-1;const e=this._list.readUInt16BE(this._pos);return this._pos+=2,a("_parseNum: result: %s",e),e}_parse4ByteNum(){if(this._list.length-this._pos<4)return-1;const e=this._list.readUInt32BE(this._pos);return this._pos+=4,a("_parse4ByteNum: result: %s",e),e}_parseVarByteNum(e){a("_parseVarByteNum");let t,r=0,n=1,i=0,o=!1;const c=this._pos?this._pos:0;for(;r<4&&c+r<this._list.length;){if(t=this._list.readUInt8(c+r++),i+=n*(t&s.VARBYTEINT_MASK),n*=128,0===(t&s.VARBYTEINT_FIN_MASK)){o=!0;break}if(this._list.length<=r)break}return!o&&4===r&&this._list.length>=r&&this._emitError(new Error("Invalid variable byte integer")),c&&(this._pos+=r),o=!!o&&(e?{bytes:r,value:i}:i),a("_parseVarByteNum: result: %o",o),o}_parseByte(){let e;return this._pos<this._list.length&&(e=this._list.readUInt8(this._pos),this._pos++),a("_parseByte: result: %o",e),e}_parseByType(e){switch(a("_parseByType: type: %s",e),e){case"byte":return 0!==this._parseByte();case"int8":return this._parseByte();case"int16":return this._parseNum();case"int32":return this._parse4ByteNum();case"var":return this._parseVarByteNum();case"string":return this._parseString();case"pair":return this._parseStringPair();case"binary":return this._parseBuffer()}}_parseProperties(){a("_parseProperties");const e=this._parseVarByteNum(),t=this._pos+e,r={};for(;this._pos<t;){const e=this._parseByte();if(!e)return this._emitError(new Error("Cannot parse property code type")),!1;const t=s.propertiesCodes[e];if(!t)return this._emitError(new Error("Unknown property")),!1;if("userProperties"===t){r[t]||(r[t]=Object.create(null));const e=this._parseByType(s.propertiesTypes[t]);if(r[t][e.name])if(Array.isArray(r[t][e.name]))r[t][e.name].push(e.value);else{const n=r[t][e.name];r[t][e.name]=[n],r[t][e.name].push(e.value)}else r[t][e.name]=e.value;continue}r[t]?(Array.isArray(r[t])||(r[t]=[r[t]]),r[t].push(this._parseByType(s.propertiesTypes[t]))):r[t]=this._parseByType(s.propertiesTypes[t])}return r}_newPacket(){return a("_newPacket"),this.packet&&(this._list.consume(this.packet.length),a("_newPacket: parser emit packet: packet.cmd: %s, packet.payload: %s, packet.length: %d",this.packet.cmd,this.packet.payload,this.packet.length),this.emit("packet",this.packet)),a("_newPacket: new packet"),this.packet=new o,this._pos=0,!0}_emitError(e){a("_emitError",e),this.error=e,this.emit("error",e)}}e.exports=c},3095(e,t,r){"use strict";const{ArrayPrototypePop:n,Promise:i}=r(4134),{isIterable:o,isNodeStream:s,isWebStream:a}=r(6115),{pipelineImpl:c}=r(7758),{finished:l}=r(6238);r(5506),e.exports={finished:l,pipeline:function(...e){return new i((t,r)=>{let i,l;const u=e[e.length-1];if(u&&"object"==typeof u&&!s(u)&&!o(u)&&!a(u)){const t=n(e);i=t.signal,l=t.end}c(e,(e,n)=>{e?r(e):t(n)},{signal:i,end:l})})}}},3106(e){"use strict";e.exports=require("zlib")},3132(e,t,r){const n=r(5399),{Buffer:i}=r(181),o=i.allocUnsafe(0),s=i.from([0]),a=r(6172),c=r(3225).nextTick,l=r(5753)("mqtt-packet:writeToStream"),u=a.cache,d=a.generateNumber,h=a.generateCache,p=a.genBufVariableByteInt,f=a.generate4ByteBuffer;let g=k,m=!0;function b(e,t,r){switch(l("generate called"),t.cork&&(t.cork(),c(y,t)),m&&(m=!1,h()),l("generate: packet.cmd: %s",e.cmd),e.cmd){case"connect":return function(e,t){const r=e||{},o=r.protocolId||"MQTT";let s=r.protocolVersion||4;const a=r.will;let c=r.clean;const l=r.keepalive||0,u=r.clientId||"",d=r.username,h=r.password,p=r.properties;void 0===c&&(c=!0);let f,m,b=0;if(!o||"string"!=typeof o&&!i.isBuffer(o))return t.destroy(new Error("Invalid protocolId")),!1;b+=o.length+2;if(3!==s&&4!==s&&5!==s)return t.destroy(new Error("Invalid protocol version")),!1;b+=1;if(("string"==typeof u||i.isBuffer(u))&&(u||s>=4)&&(u||c))b+=i.byteLength(u)+2;else{if(s<4)return t.destroy(new Error("clientId must be supplied before 3.1.1")),!1;if(1*c==0)return t.destroy(new Error("clientId must be given if cleanSession set to 0")),!1}if("number"!=typeof l||l<0||l>65535||l%1!=0)return t.destroy(new Error("Invalid keepalive")),!1;b+=2;if(b+=1,5===s){if(f=T(t,p),!f)return!1;b+=f.length}if(a){if("object"!=typeof a)return t.destroy(new Error("Invalid will")),!1;if(!a.topic||"string"!=typeof a.topic)return t.destroy(new Error("Invalid will topic")),!1;if(b+=i.byteLength(a.topic)+2,b+=2,a.payload){if(!(a.payload.length>=0))return t.destroy(new Error("Invalid will payload")),!1;"string"==typeof a.payload?b+=i.byteLength(a.payload):b+=a.payload.length}if(m={},5===s){if(m=T(t,a.properties),!m)return!1;b+=m.length}}let y=!1;if(null!=d){if(!P(d))return t.destroy(new Error("Invalid username")),!1;y=!0,b+=i.byteLength(d)+2}if(null!=h){if(!y)return t.destroy(new Error("Username is required to use password")),!1;if(!P(h))return t.destroy(new Error("Invalid password")),!1;b+=A(h)+2}t.write(n.CONNECT_HEADER),v(t,b),I(t,o),r.bridgeMode&&(s+=128);t.write(131===s?n.VERSION131:132===s?n.VERSION132:4===s?n.VERSION4:5===s?n.VERSION5:n.VERSION3);let _=0;_|=null!=d?n.USERNAME_MASK:0,_|=null!=h?n.PASSWORD_MASK:0,_|=a&&a.retain?n.WILL_RETAIN_MASK:0,_|=a&&a.qos?a.qos<<n.WILL_QOS_SHIFT:0,_|=a?n.WILL_FLAG_MASK:0,_|=c?n.CLEAN_SESSION_MASK:0,t.write(i.from([_])),g(t,l),5===s&&f.write();I(t,u),a&&(5===s&&m.write(),S(t,a.topic),I(t,a.payload));null!=d&&I(t,d);null!=h&&I(t,h);return!0}(e,t);case"connack":return function(e,t,r){const o=r?r.protocolVersion:4,a=e||{},c=5===o?a.reasonCode:a.returnCode,l=a.properties;let u=2;if("number"!=typeof c)return t.destroy(new Error("Invalid return code")),!1;let d=null;if(5===o){if(d=T(t,l),!d)return!1;u+=d.length}t.write(n.CONNACK_HEADER),v(t,u),t.write(a.sessionPresent?n.SESSIONPRESENT_HEADER:s),t.write(i.from([c])),null!=d&&d.write();return!0}(e,t,r);case"publish":return function(e,t,r){l("publish: packet: %o",e);const s=r?r.protocolVersion:4,a=e||{},c=a.qos||0,u=a.retain?n.RETAIN_MASK:0,d=a.topic,h=a.payload||o,p=a.messageId,f=a.properties;let m=0;if("string"==typeof d)m+=i.byteLength(d)+2;else{if(!i.isBuffer(d))return t.destroy(new Error("Invalid topic")),!1;m+=d.length+2}i.isBuffer(h)?m+=h.length:m+=i.byteLength(h);if(c&&"number"!=typeof p)return t.destroy(new Error("Invalid messageId")),!1;c&&(m+=2);let b=null;if(5===s){if(b=T(t,f),!b)return!1;m+=b.length}t.write(n.PUBLISH_HEADER[c][a.dup?1:0][u?1:0]),v(t,m),g(t,A(d)),t.write(d),c>0&&g(t,p);null!=b&&b.write();return l("publish: payload: %o",h),t.write(h)}(e,t,r);case"puback":case"pubrec":case"pubrel":case"pubcomp":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.cmd||"puback",c=s.messageId,l=s.dup&&"pubrel"===a?n.DUP_MASK:0;let u=0;const d=s.reasonCode,h=s.properties;let p=5===o?3:2;"pubrel"===a&&(u=1);if("number"!=typeof c)return t.destroy(new Error("Invalid messageId")),!1;let f=null;if(5===o&&"object"==typeof h){if(f=O(t,h,r,p),!f)return!1;p+=f.length}t.write(n.ACKS[a][u][l][0]),3===p&&(p+=0!==d?1:-1);v(t,p),g(t,c),5===o&&2!==p&&t.write(i.from([d]));null!==f?f.write():4===p&&t.write(i.from([0]));return!0}(e,t,r);case"subscribe":return function(e,t,r){l("subscribe: packet: ");const o=r?r.protocolVersion:4,s=e||{},a=s.dup?n.DUP_MASK:0,c=s.messageId,u=s.subscriptions,d=s.properties;let h=0;if("number"!=typeof c)return t.destroy(new Error("Invalid messageId")),!1;h+=2;let p=null;if(5===o){if(p=T(t,d),!p)return!1;h+=p.length}if("object"!=typeof u||!u.length)return t.destroy(new Error("Invalid subscriptions")),!1;for(let e=0;e<u.length;e+=1){const r=u[e].topic,n=u[e].qos;if("string"!=typeof r)return t.destroy(new Error("Invalid subscriptions - invalid topic")),!1;if("number"!=typeof n)return t.destroy(new Error("Invalid subscriptions - invalid qos")),!1;if(5===o){if("boolean"!=typeof(u[e].nl||!1))return t.destroy(new Error("Invalid subscriptions - invalid No Local")),!1;if("boolean"!=typeof(u[e].rap||!1))return t.destroy(new Error("Invalid subscriptions - invalid Retain as Published")),!1;const r=u[e].rh||0;if("number"!=typeof r||r>2)return t.destroy(new Error("Invalid subscriptions - invalid Retain Handling")),!1}h+=i.byteLength(r)+2+1}l("subscribe: writing to stream: %o",n.SUBSCRIBE_HEADER),t.write(n.SUBSCRIBE_HEADER[1][a?1:0][0]),v(t,h),g(t,c),null!==p&&p.write();let f=!0;for(const e of u){const r=e.topic,s=e.qos,a=+e.nl,c=+e.rap,l=e.rh;let u;S(t,r),u=n.SUBSCRIBE_OPTIONS_QOS[s],5===o&&(u|=a?n.SUBSCRIBE_OPTIONS_NL:0,u|=c?n.SUBSCRIBE_OPTIONS_RAP:0,u|=l?n.SUBSCRIBE_OPTIONS_RH[l]:0),f=t.write(i.from([u]))}return f}(e,t,r);case"suback":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.messageId,c=s.granted,l=s.properties;let u=0;if("number"!=typeof a)return t.destroy(new Error("Invalid messageId")),!1;u+=2;if("object"!=typeof c||!c.length)return t.destroy(new Error("Invalid qos vector")),!1;for(let e=0;e<c.length;e+=1){if("number"!=typeof c[e])return t.destroy(new Error("Invalid qos vector")),!1;u+=1}let d=null;if(5===o){if(d=O(t,l,r,u),!d)return!1;u+=d.length}t.write(n.SUBACK_HEADER),v(t,u),g(t,a),null!==d&&d.write();return t.write(i.from(c))}(e,t,r);case"unsubscribe":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.messageId,c=s.dup?n.DUP_MASK:0,l=s.unsubscriptions,u=s.properties;let d=0;if("number"!=typeof a)return t.destroy(new Error("Invalid messageId")),!1;d+=2;if("object"!=typeof l||!l.length)return t.destroy(new Error("Invalid unsubscriptions")),!1;for(let e=0;e<l.length;e+=1){if("string"!=typeof l[e])return t.destroy(new Error("Invalid unsubscriptions")),!1;d+=i.byteLength(l[e])+2}let h=null;if(5===o){if(h=T(t,u),!h)return!1;d+=h.length}t.write(n.UNSUBSCRIBE_HEADER[1][c?1:0][0]),v(t,d),g(t,a),null!==h&&h.write();let p=!0;for(let e=0;e<l.length;e++)p=S(t,l[e]);return p}(e,t,r);case"unsuback":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.messageId,c=s.dup?n.DUP_MASK:0,l=s.granted,u=s.properties,d=s.cmd,h=0;let p=2;if("number"!=typeof a)return t.destroy(new Error("Invalid messageId")),!1;if(5===o){if("object"!=typeof l||!l.length)return t.destroy(new Error("Invalid qos vector")),!1;for(let e=0;e<l.length;e+=1){if("number"!=typeof l[e])return t.destroy(new Error("Invalid qos vector")),!1;p+=1}}let f=null;if(5===o){if(f=O(t,u,r,p),!f)return!1;p+=f.length}t.write(n.ACKS[d][h][c][0]),v(t,p),g(t,a),null!==f&&f.write();5===o&&t.write(i.from(l));return!0}(e,t,r);case"pingreq":case"pingresp":return function(e,t){return t.write(n.EMPTY[e.cmd])}(e,t);case"disconnect":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.reasonCode,c=s.properties;let l=5===o?1:0,u=null;if(5===o){if(u=O(t,c,r,l),!u)return!1;l+=u.length}t.write(i.from([n.codes.disconnect<<4])),v(t,l),5===o&&t.write(i.from([a]));null!==u&&u.write();return!0}(e,t,r);case"auth":return function(e,t,r){const o=r?r.protocolVersion:4,s=e||{},a=s.reasonCode,c=s.properties;let l=5===o?1:0;5!==o&&t.destroy(new Error("Invalid mqtt version for auth packet"));const u=O(t,c,r,l);if(!u)return!1;l+=u.length,t.write(i.from([n.codes.auth<<4])),v(t,l),t.write(i.from([a])),null!==u&&u.write();return!0}(e,t,r);default:return t.destroy(new Error("Unknown command")),!1}}function y(e){e.uncork()}Object.defineProperty(b,"cacheNumbers",{get:()=>g===k,set(e){e?(u&&0!==Object.keys(u).length||(m=!0),g=k):(m=!1,g=E)}});const _={};function v(e,t){if(t>n.VARBYTEINT_MAX)return e.destroy(new Error(`Invalid variable byte integer: ${t}`)),!1;let r=_[t];return r||(r=p(t),t<16384&&(_[t]=r)),l("writeVarByteInt: writing to stream: %o",r),e.write(r)}function S(e,t){const r=i.byteLength(t);return g(e,r),l("writeString: %s",t),e.write(t,"utf8")}function w(e,t,r){S(e,t),S(e,r)}function k(e,t){return l("writeNumberCached: number: %d",t),l("writeNumberCached: %o",u[t]),e.write(u[t])}function E(e,t){const r=d(t);return l("writeNumberGenerated: %o",r),e.write(r)}function I(e,t){"string"==typeof t?S(e,t):t?(g(e,t.length),e.write(t)):g(e,0)}function T(e,t){if("object"!=typeof t||null!=t.length)return{length:1,write(){x(e,{},0)}};let r=0;function o(t,r){let o=0;switch(n.propertiesTypes[t]){case"byte":if("boolean"!=typeof r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=2;break;case"int8":if("number"!=typeof r||r<0||r>255)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=2;break;case"binary":if(r&&null===r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=1+i.byteLength(r)+2;break;case"int16":if("number"!=typeof r||r<0||r>65535)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=3;break;case"int32":if("number"!=typeof r||r<0||r>4294967295)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=5;break;case"var":if("number"!=typeof r||r<0||r>268435455)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=1+i.byteLength(p(r));break;case"string":if("string"!=typeof r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=3+i.byteLength(r.toString());break;case"pair":if("object"!=typeof r)return e.destroy(new Error(`Invalid ${t}: ${r}`)),!1;o+=Object.getOwnPropertyNames(r).reduce((e,t)=>{const n=r[t];return Array.isArray(n)?e+=n.reduce((e,r)=>e+=3+i.byteLength(t.toString())+2+i.byteLength(r.toString()),0):e+=3+i.byteLength(t.toString())+2+i.byteLength(r[t].toString()),e},0);break;default:return e.destroy(new Error(`Invalid property ${t}: ${r}`)),!1}return o}if(t)for(const e in t){let n=0,i=0;const s=t[e];if(void 0!==s){if(Array.isArray(s))for(let t=0;t<s.length;t++){if(i=o(e,s[t]),!i)return!1;n+=i}else{if(i=o(e,s),!i)return!1;n=i}if(!n)return!1;r+=n}}return{length:i.byteLength(p(r))+r,write(){x(e,t,r)}}}function O(e,t,r,n){const i=["reasonString","userProperties"],o=r&&r.properties&&r.properties.maximumPacketSize?r.properties.maximumPacketSize:0;let s=T(e,t);if(o)for(;n+s.length>o;){const r=i.shift();if(!r||!t[r])return!1;delete t[r],s=T(e,t)}return s}function C(e,t,r){switch(n.propertiesTypes[t]){case"byte":e.write(i.from([n.properties[t]])),e.write(i.from([+r]));break;case"int8":e.write(i.from([n.properties[t]])),e.write(i.from([r]));break;case"binary":e.write(i.from([n.properties[t]])),I(e,r);break;case"int16":e.write(i.from([n.properties[t]])),g(e,r);break;case"int32":e.write(i.from([n.properties[t]])),function(e,t){const r=f(t);l("write4ByteNumber: %o",r),e.write(r)}(e,r);break;case"var":e.write(i.from([n.properties[t]])),v(e,r);break;case"string":e.write(i.from([n.properties[t]])),S(e,r);break;case"pair":Object.getOwnPropertyNames(r).forEach(o=>{const s=r[o];Array.isArray(s)?s.forEach(r=>{e.write(i.from([n.properties[t]])),w(e,o.toString(),r.toString())}):(e.write(i.from([n.properties[t]])),w(e,o.toString(),s.toString()))});break;default:return e.destroy(new Error(`Invalid property ${t} value: ${r}`)),!1}}function x(e,t,r){v(e,r);for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&null!=t[r]){const n=t[r];if(Array.isArray(n))for(let t=0;t<n.length;t++)C(e,r,n[t]);else C(e,r,n)}}function A(e){return e?e instanceof i?e.length:i.byteLength(e):0}function P(e){return"string"==typeof e||e instanceof i}e.exports=b},3141(e,t,r){"use strict";var n=r(2861).Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=u,this.end=d,t=3;break;default:return this.write=h,void(this.end=p)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function s(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,r=function(e,t){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function u(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function d(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function p(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""},o.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t},o.prototype.text=function(e,t){var r=function(e,t,r){var n=t.length-1;if(n<r)return 0;var i=s(t[n]);if(i>=0)return i>0&&(e.lastNeed=i-1),i;if(--n<r||-2===i)return 0;if(i=s(t[n]),i>=0)return i>0&&(e.lastNeed=i-2),i;if(--n<r||-2===i)return 0;if(i=s(t[n]),i>=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},3175(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(7732));t.default=class{_keepalive;timerId;timer;destroyed=!1;counter;client;_keepaliveTimeoutTimestamp;_intervalEvery;get keepaliveTimeoutTimestamp(){return this._keepaliveTimeoutTimestamp}get intervalEvery(){return this._intervalEvery}get keepalive(){return this._keepalive}constructor(e,t){this.client=e,this.timer="object"==typeof t&&"set"in t&&"clear"in t?t:(0,i.default)(t),this.setKeepalive(e.options.keepalive)}clear(){this.timerId&&(this.timer.clear(this.timerId),this.timerId=null)}setKeepalive(e){if(e*=1e3,isNaN(e)||e<=0||e>2147483647)throw new Error(`Keepalive value must be an integer between 0 and 2147483647. Provided value is ${e}`);this._keepalive=e,this.reschedule(),this.client.log(`KeepaliveManager: set keepalive to ${e}ms`)}destroy(){this.clear(),this.destroyed=!0}reschedule(){if(this.destroyed)return;this.clear(),this.counter=0;const e=Math.ceil(1.5*this._keepalive);this._keepaliveTimeoutTimestamp=Date.now()+e,this._intervalEvery=Math.ceil(this._keepalive/2),this.timerId=this.timer.set(()=>{this.destroyed||(this.counter+=1,2===this.counter?this.client.sendPing():this.counter>2&&this.client.onKeepaliveTimeout())},this._intervalEvery)}}},3225(e){"use strict";"undefined"==typeof process||!process.version||0===process.version.indexOf("v0.")||0===process.version.indexOf("v1.")&&0!==process.version.indexOf("v1.8.")?e.exports={nextTick:function(e,t,r,n){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var i,o,s=arguments.length;switch(s){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,t)});case 3:return process.nextTick(function(){e.call(null,t,r)});case 4:return process.nextTick(function(){e.call(null,t,r,n)});default:for(i=new Array(s-1),o=0;o<i.length;)i[o++]=arguments[o];return process.nextTick(function(){e.apply(null,i)})}}}:e.exports=process},3338(e,t,r){"use strict";const{EMPTY_BUFFER:n}=r(2614),i=Buffer[Symbol.species];function o(e,t,r,n,i){for(let o=0;o<i;o++)r[n+o]=e[o]^t[3&o]}function s(e,t){for(let r=0;r<e.length;r++)e[r]^=t[3&r]}if(e.exports={concat:function(e,t){if(0===e.length)return n;if(1===e.length)return e[0];const r=Buffer.allocUnsafe(t);let o=0;for(let t=0;t<e.length;t++){const n=e[t];r.set(n,o),o+=n.length}return o<t?new i(r.buffer,r.byteOffset,o):r},mask:o,toArrayBuffer:function(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let r;return t instanceof ArrayBuffer?r=new i(t):ArrayBuffer.isView(t)?r=new i(t.buffer,t.byteOffset,t.byteLength):(r=Buffer.from(t),e.readOnly=!1),r},unmask:s},!process.env.WS_NO_BUFFER_UTIL)try{const t=r(Object(function(){var e=new Error("Cannot find module 'bufferutil'");throw e.code="MODULE_NOT_FOUND",e}()));e.exports.mask=function(e,r,n,i,s){s<48?o(e,r,n,i,s):t.mask(e,r,n,i,s)},e.exports.unmask=function(e,r){e.length<32?s(e,r):t.unmask(e,r)}}catch(e){}},3339(e){"use strict";e.exports=require("module")},3370(e,t,r){"use strict";const{ObjectDefineProperties:n,ObjectGetOwnPropertyDescriptor:i,ObjectKeys:o,ObjectSetPrototypeOf:s}=r(4134);e.exports=l;const a=r(7576),c=r(8584);s(l.prototype,a.prototype),s(l,a);{const e=o(c.prototype);for(let t=0;t<e.length;t++){const r=e[t];l.prototype[r]||(l.prototype[r]=c.prototype[r])}}function l(e){if(!(this instanceof l))return new l(e);a.call(this,e),c.call(this,e),e?(this.allowHalfOpen=!1!==e.allowHalfOpen,!1===e.readable&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===e.writable&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}let u,d;function h(){return void 0===u&&(u={}),u}n(l.prototype,{writable:{__proto__:null,...i(c.prototype,"writable")},writableHighWaterMark:{__proto__:null,...i(c.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...i(c.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...i(c.prototype,"writableBuffer")},writableLength:{__proto__:null,...i(c.prototype,"writableLength")},writableFinished:{__proto__:null,...i(c.prototype,"writableFinished")},writableCorked:{__proto__:null,...i(c.prototype,"writableCorked")},writableEnded:{__proto__:null,...i(c.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...i(c.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set(e){this._readableState&&this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}}),l.fromWeb=function(e,t){return h().newStreamDuplexFromReadableWritablePair(e,t)},l.toWeb=function(e){return h().newReadableWritablePairFromDuplex(e)},l.from=function(e){return d||(d=r(6706)),d(e,"body")}},3497(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(4966),i=r(720);t.default=class{aliasToTopic;topicToAlias;max;numberAllocator;length;constructor(e){e>0&&(this.aliasToTopic=new n.LRUCache({max:e}),this.topicToAlias={},this.numberAllocator=new i.NumberAllocator(1,e),this.max=e,this.length=0)}put(e,t){if(0===t||t>this.max)return!1;const r=this.aliasToTopic.get(t);return r&&delete this.topicToAlias[r],this.aliasToTopic.set(t,e),this.topicToAlias[e]=t,this.numberAllocator.use(t),this.length=this.aliasToTopic.size,!0}getTopicByAlias(e){return this.aliasToTopic.get(e)}getAliasByTopic(e){const t=this.topicToAlias[e];return"undefined"!=typeof t&&this.aliasToTopic.get(t),t}clear(){this.aliasToTopic.clear(),this.topicToAlias={},this.numberAllocator.clear(),this.length=0}getLruAlias(){const e=this.numberAllocator.firstVacant();return e||[...this.aliasToTopic.keys()][this.aliasToTopic.size-1]}}},3719(e,t,r){"use strict";r(1060);const{Duplex:n}=r(2203);function i(e){e.emit("close")}function o(){!this.destroyed&&this._writableState.finished&&this.destroy()}function s(e){this.removeListener("error",s),this.destroy(),0===this.listenerCount("error")&&this.emit("error",e)}e.exports=function(e,t){let r=!0;const a=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on("message",function(t,r){const n=!r&&a._readableState.objectMode?t.toString():t;a.push(n)||e.pause()}),e.once("error",function(e){a.destroyed||(r=!1,a.destroy(e))}),e.once("close",function(){a.destroyed||a.push(null)}),a._destroy=function(t,n){if(e.readyState===e.CLOSED)return n(t),void process.nextTick(i,a);let o=!1;e.once("error",function(e){o=!0,n(e)}),e.once("close",function(){o||n(t),process.nextTick(i,a)}),r&&e.terminate()},a._final=function(t){e.readyState!==e.CONNECTING?null!==e._socket&&(e._socket._writableState.finished?(t(),a._readableState.endEmitted&&a.destroy()):(e._socket.once("finish",function(){t()}),e.close())):e.once("open",function(){a._final(t)})},a._read=function(){e.isPaused&&e.resume()},a._write=function(t,r,n){e.readyState!==e.CONNECTING?e.send(t,n):e.once("open",function(){a._write(t,r,n)})},a.on("end",o),a.on("error",s),a}},3763(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.shuffleArray=t.SocksClientError=void 0;class r extends Error{constructor(e,t){super(e),this.options=t}}t.SocksClientError=r,t.shuffleArray=function(e){for(let t=e.length-1;t>0;t--){const r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}}},3874(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EDITOR_HTML=void 0,t.EDITOR_HTML='<!DOCTYPE html>\n<html lang="en">\n<head>\n <meta charset="UTF-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>Spatial Awareness - Topology Editor</title>\n <style>\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif; background: #1a1a2e; color: #eee; min-height: 100vh; }\n .container { display: flex; height: 100vh; }\n .sidebar { width: 300px; background: #16213e; border-right: 1px solid #0f3460; display: flex; flex-direction: column; overflow: hidden; }\n .sidebar-header { padding: 20px; border-bottom: 1px solid #0f3460; }\n .sidebar-header h1 { font-size: 18px; font-weight: 600; margin-bottom: 5px; }\n .sidebar-header p { font-size: 12px; color: #888; }\n .sidebar-content { flex: 1; overflow-y: auto; padding: 15px; }\n .section { margin-bottom: 20px; }\n .section-title { font-size: 12px; font-weight: 600; text-transform: uppercase; color: #888; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; }\n .btn { background: #0f3460; color: #fff; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; font-size: 13px; transition: background 0.2s; }\n .btn:hover { background: #1a4a7a; }\n .btn-primary { background: #e94560; }\n .btn-primary:hover { background: #ff6b6b; }\n .btn-small { padding: 4px 8px; font-size: 11px; }\n .camera-item, .connection-item { background: #0f3460; border-radius: 6px; padding: 12px; margin-bottom: 8px; cursor: pointer; transition: background 0.2s; }\n .camera-item:hover, .connection-item:hover { background: #1a4a7a; }\n .camera-item.selected, .connection-item.selected { outline: 2px solid #e94560; }\n .camera-name { font-weight: 500; margin-bottom: 4px; }\n .camera-info { font-size: 11px; color: #888; }\n .editor { flex: 1; display: flex; flex-direction: column; overflow: hidden; }\n .toolbar { background: #16213e; border-bottom: 1px solid #0f3460; padding: 10px 20px; display: flex; gap: 10px; align-items: center; }\n .toolbar-group { display: flex; gap: 5px; padding-right: 15px; border-right: 1px solid #0f3460; margin-right: 5px; }\n .toolbar-group:last-child { border-right: none; }\n .canvas-container { flex: 1; position: relative; overflow: hidden; background: #0f0f1a; }\n #floor-plan-canvas { position: absolute; top: 0; left: 0; }\n .canvas-placeholder { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: #666; }\n .canvas-placeholder h2 { margin-bottom: 15px; }\n .properties-panel { width: 280px; background: #16213e; border-left: 1px solid #0f3460; overflow-y: auto; padding: 15px; }\n .properties-panel h3 { font-size: 14px; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid #0f3460; }\n .form-group { margin-bottom: 15px; }\n .form-group label { display: block; font-size: 12px; color: #888; margin-bottom: 5px; }\n .form-group input, .form-group select { width: 100%; padding: 8px 10px; background: #0f3460; border: 1px solid #1a4a7a; border-radius: 4px; color: #fff; font-size: 13px; }\n .form-group input:focus, .form-group select:focus { outline: none; border-color: #e94560; }\n .checkbox-group { display: flex; align-items: center; gap: 8px; }\n .checkbox-group input[type="checkbox"] { width: auto; }\n .transit-time-inputs { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; }\n .transit-time-inputs input { text-align: center; }\n .transit-time-labels { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; font-size: 10px; color: #666; text-align: center; }\n .modal-overlay { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.7); z-index: 1000; align-items: center; justify-content: center; }\n .modal-overlay.active { display: flex; }\n .modal { background: #16213e; border-radius: 8px; padding: 25px; max-width: 500px; width: 90%; max-height: 80vh; overflow-y: auto; }\n .modal h2 { margin-bottom: 20px; }\n .modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }\n .upload-zone { border: 2px dashed #0f3460; border-radius: 8px; padding: 40px; text-align: center; cursor: pointer; transition: border-color 0.2s, background 0.2s; }\n .upload-zone:hover { border-color: #e94560; background: rgba(233, 69, 96, 0.1); }\n .upload-zone input { display: none; }\n .status-bar { background: #0f3460; padding: 8px 20px; font-size: 12px; color: #888; display: flex; justify-content: space-between; }\n .status-indicator { display: flex; align-items: center; gap: 6px; }\n .status-dot { width: 8px; height: 8px; border-radius: 50%; background: #4caf50; }\n .status-dot.warning { background: #ff9800; }\n .status-dot.error { background: #f44336; }\n </style>\n</head>\n<body>\n <div class="container">\n <div class="sidebar">\n <div class="sidebar-header">\n <h1>Spatial Awareness</h1>\n <p>Topology Editor</p>\n </div>\n <div class="sidebar-content">\n <div class="section">\n <div class="section-title">\n <span>Cameras</span>\n <button class="btn btn-small" onclick="openAddCameraModal()">+ Add</button>\n </div>\n <div id="camera-list">\n <div class="camera-item" style="color: #666; text-align: center; cursor: default;">No cameras configured</div>\n </div>\n </div>\n <div class="section">\n <div class="section-title">\n <span>Connections</span>\n <button class="btn btn-small" onclick="openAddConnectionModal()">+ Add</button>\n </div>\n <div id="connection-list">\n <div class="connection-item" style="color: #666; text-align: center; cursor: default;">No connections configured</div>\n </div>\n </div>\n </div>\n </div>\n <div class="editor">\n <div class="toolbar">\n <div class="toolbar-group">\n <button class="btn" onclick="uploadFloorPlan()">Upload Floor Plan</button>\n </div>\n <div class="toolbar-group">\n <button class="btn" onclick="setTool(\'select\')">Select</button>\n <button class="btn" onclick="setTool(\'camera\')">Place Camera</button>\n <button class="btn" onclick="setTool(\'connect\')">Connect</button>\n </div>\n <div class="toolbar-group">\n <button class="btn btn-primary" onclick="saveTopology()">Save</button>\n </div>\n </div>\n <div class="canvas-container">\n <canvas id="floor-plan-canvas"></canvas>\n <div class="canvas-placeholder" id="canvas-placeholder">\n <h2>Floor Plan Editor</h2>\n <p>Upload a floor plan image to get started</p>\n <br>\n <button class="btn btn-primary" onclick="uploadFloorPlan()">Upload Floor Plan</button>\n </div>\n </div>\n <div class="status-bar">\n <div class="status-indicator">\n <div class="status-dot" id="status-dot"></div>\n <span id="status-text">Ready</span>\n </div>\n <div>\n <span id="camera-count">0</span> cameras | <span id="connection-count">0</span> connections\n </div>\n </div>\n </div>\n <div class="properties-panel" id="properties-panel">\n <h3>Properties</h3>\n <p style="color: #666; font-size: 13px;">Select a camera or connection to edit its properties.</p>\n </div>\n </div>\n\n <div class="modal-overlay" id="add-camera-modal">\n <div class="modal">\n <h2>Add Camera</h2>\n <div class="form-group">\n <label>Camera Device</label>\n <select id="camera-device-select"><option value="">Loading cameras...</option></select>\n </div>\n <div class="form-group">\n <label>Display Name</label>\n <input type="text" id="camera-name-input" placeholder="e.g., Front Door Camera">\n </div>\n <div class="form-group">\n <label class="checkbox-group">\n <input type="checkbox" id="camera-entry-checkbox">\n Entry Point (objects can enter property here)\n </label>\n </div>\n <div class="form-group">\n <label class="checkbox-group">\n <input type="checkbox" id="camera-exit-checkbox">\n Exit Point (objects can exit property here)\n </label>\n </div>\n <div class="modal-actions">\n <button class="btn" onclick="closeModal(\'add-camera-modal\')">Cancel</button>\n <button class="btn btn-primary" onclick="addCamera()">Add Camera</button>\n </div>\n </div>\n </div>\n\n <div class="modal-overlay" id="add-connection-modal">\n <div class="modal">\n <h2>Add Connection</h2>\n <div class="form-group">\n <label>Connection Name</label>\n <input type="text" id="connection-name-input" placeholder="e.g., Driveway to Front Door">\n </div>\n <div class="form-group">\n <label>From Camera</label>\n <select id="connection-from-select"></select>\n </div>\n <div class="form-group">\n <label>To Camera</label>\n <select id="connection-to-select"></select>\n </div>\n <div class="form-group">\n <label>Transit Time (seconds)</label>\n <div class="transit-time-inputs">\n <input type="number" id="transit-min" placeholder="Min" value="3">\n <input type="number" id="transit-typical" placeholder="Typical" value="10">\n <input type="number" id="transit-max" placeholder="Max" value="30">\n </div>\n <div class="transit-time-labels">\n <span>Minimum</span>\n <span>Typical</span>\n <span>Maximum</span>\n </div>\n </div>\n <div class="form-group">\n <label class="checkbox-group">\n <input type="checkbox" id="connection-bidirectional" checked>\n Bidirectional (works both ways)\n </label>\n </div>\n <div class="modal-actions">\n <button class="btn" onclick="closeModal(\'add-connection-modal\')">Cancel</button>\n <button class="btn btn-primary" onclick="addConnection()">Add Connection</button>\n </div>\n </div>\n </div>\n\n <div class="modal-overlay" id="upload-modal">\n <div class="modal">\n <h2>Upload Floor Plan</h2>\n <div class="upload-zone" onclick="document.getElementById(\'floor-plan-input\').click()">\n <p>Click to select an image<br><small>PNG, JPG, or SVG</small></p>\n <input type="file" id="floor-plan-input" accept="image/*" onchange="handleFloorPlanUpload(event)">\n </div>\n <div class="modal-actions">\n <button class="btn" onclick="closeModal(\'upload-modal\')">Cancel</button>\n </div>\n </div>\n </div>\n\n <script>\n let topology = { version: \'1.0\', cameras: [], connections: [], globalZones: [], floorPlan: null };\n let selectedItem = null;\n let currentTool = \'select\';\n let floorPlanImage = null;\n let availableCameras = [];\n const canvas = document.getElementById(\'floor-plan-canvas\');\n const ctx = canvas.getContext(\'2d\');\n\n async function init() {\n await loadTopology();\n await loadAvailableCameras();\n resizeCanvas();\n render();\n updateUI();\n }\n\n async function loadTopology() {\n try {\n const response = await fetch(\'../api/topology\');\n if (response.ok) {\n topology = await response.json();\n if (topology.floorPlan?.imageData) {\n await loadFloorPlanImage(topology.floorPlan.imageData);\n }\n }\n } catch (e) { console.error(\'Failed to load topology:\', e); }\n }\n\n async function loadAvailableCameras() {\n availableCameras = topology.cameras.map(c => ({ id: c.deviceId, name: c.name }));\n updateCameraSelects();\n }\n\n async function saveTopology() {\n try {\n setStatus(\'Saving...\', \'warning\');\n const response = await fetch(\'../api/topology\', {\n method: \'PUT\',\n headers: { \'Content-Type\': \'application/json\' },\n body: JSON.stringify(topology)\n });\n if (response.ok) { setStatus(\'Saved successfully\', \'success\'); }\n else { setStatus(\'Failed to save\', \'error\'); }\n } catch (e) { console.error(\'Failed to save topology:\', e); setStatus(\'Failed to save\', \'error\'); }\n }\n\n function resizeCanvas() {\n const container = canvas.parentElement;\n canvas.width = container.clientWidth;\n canvas.height = container.clientHeight;\n }\n\n function render() {\n ctx.clearRect(0, 0, canvas.width, canvas.height);\n if (floorPlanImage) {\n document.getElementById(\'canvas-placeholder\').style.display = \'none\';\n const scale = Math.min(canvas.width / floorPlanImage.width, canvas.height / floorPlanImage.height) * 0.9;\n const x = (canvas.width - floorPlanImage.width * scale) / 2;\n const y = (canvas.height - floorPlanImage.height * scale) / 2;\n ctx.drawImage(floorPlanImage, x, y, floorPlanImage.width * scale, floorPlanImage.height * scale);\n } else {\n document.getElementById(\'canvas-placeholder\').style.display = \'block\';\n }\n for (const conn of topology.connections) {\n const fromCam = topology.cameras.find(c => c.deviceId === conn.fromCameraId);\n const toCam = topology.cameras.find(c => c.deviceId === conn.toCameraId);\n if (fromCam?.floorPlanPosition && toCam?.floorPlanPosition) {\n drawConnection(fromCam.floorPlanPosition, toCam.floorPlanPosition, conn);\n }\n }\n for (const camera of topology.cameras) {\n if (camera.floorPlanPosition) { drawCamera(camera); }\n }\n }\n\n function drawCamera(camera) {\n const pos = camera.floorPlanPosition;\n const isSelected = selectedItem?.type === \'camera\' && selectedItem?.id === camera.deviceId;\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, 20, 0, Math.PI * 2);\n ctx.fillStyle = isSelected ? \'#e94560\' : \'#0f3460\';\n ctx.fill();\n ctx.strokeStyle = \'#fff\';\n ctx.lineWidth = 2;\n ctx.stroke();\n ctx.fillStyle = \'#fff\';\n ctx.font = \'12px sans-serif\';\n ctx.textAlign = \'center\';\n ctx.textBaseline = \'middle\';\n ctx.fillText(\'CAM\', pos.x, pos.y);\n ctx.fillText(camera.name, pos.x, pos.y + 35);\n }\n\n function drawConnection(from, to, conn) {\n const isSelected = selectedItem?.type === \'connection\' && selectedItem?.id === conn.id;\n ctx.beginPath();\n ctx.moveTo(from.x, from.y);\n ctx.lineTo(to.x, to.y);\n ctx.strokeStyle = isSelected ? \'#e94560\' : \'#4caf50\';\n ctx.lineWidth = isSelected ? 4 : 2;\n ctx.stroke();\n if (!conn.bidirectional) {\n const angle = Math.atan2(to.y - from.y, to.x - from.x);\n const midX = (from.x + to.x) / 2;\n const midY = (from.y + to.y) / 2;\n ctx.beginPath();\n ctx.moveTo(midX, midY);\n ctx.lineTo(midX - 10 * Math.cos(angle - 0.5), midY - 10 * Math.sin(angle - 0.5));\n ctx.lineTo(midX - 10 * Math.cos(angle + 0.5), midY - 10 * Math.sin(angle + 0.5));\n ctx.closePath();\n ctx.fillStyle = isSelected ? \'#e94560\' : \'#4caf50\';\n ctx.fill();\n }\n }\n\n function uploadFloorPlan() { document.getElementById(\'upload-modal\').classList.add(\'active\'); }\n\n async function handleFloorPlanUpload(event) {\n const file = event.target.files[0];\n if (!file) return;\n const reader = new FileReader();\n reader.onload = async (e) => {\n const imageData = e.target.result;\n await loadFloorPlanImage(imageData);\n topology.floorPlan = { imageData, width: floorPlanImage.width, height: floorPlanImage.height };\n closeModal(\'upload-modal\');\n render();\n };\n reader.readAsDataURL(file);\n }\n\n function loadFloorPlanImage(imageData) {\n return new Promise((resolve) => {\n floorPlanImage = new Image();\n floorPlanImage.onload = resolve;\n floorPlanImage.src = imageData;\n });\n }\n\n function openAddCameraModal() { document.getElementById(\'add-camera-modal\').classList.add(\'active\'); }\n\n function addCamera() {\n const deviceId = document.getElementById(\'camera-device-select\').value;\n const name = document.getElementById(\'camera-name-input\').value || \'New Camera\';\n const isEntry = document.getElementById(\'camera-entry-checkbox\').checked;\n const isExit = document.getElementById(\'camera-exit-checkbox\').checked;\n const camera = {\n deviceId: deviceId || \'camera-\' + Date.now(),\n nativeId: \'cam-\' + Date.now(),\n name,\n isEntryPoint: isEntry,\n isExitPoint: isExit,\n trackClasses: [\'person\', \'car\', \'animal\'],\n floorPlanPosition: { x: canvas.width / 2 + Math.random() * 100 - 50, y: canvas.height / 2 + Math.random() * 100 - 50 }\n };\n topology.cameras.push(camera);\n closeModal(\'add-camera-modal\');\n updateUI();\n render();\n }\n\n function openAddConnectionModal() {\n if (topology.cameras.length < 2) { alert(\'Add at least 2 cameras before creating connections\'); return; }\n updateCameraSelects();\n document.getElementById(\'add-connection-modal\').classList.add(\'active\');\n }\n\n function updateCameraSelects() {\n const options = topology.cameras.map(c => \'<option value="\' + c.deviceId + \'">\' + c.name + \'</option>\').join(\'\');\n document.getElementById(\'connection-from-select\').innerHTML = options;\n document.getElementById(\'connection-to-select\').innerHTML = options;\n }\n\n function addConnection() {\n const name = document.getElementById(\'connection-name-input\').value;\n const fromId = document.getElementById(\'connection-from-select\').value;\n const toId = document.getElementById(\'connection-to-select\').value;\n const minTransit = parseInt(document.getElementById(\'transit-min\').value) * 1000;\n const typicalTransit = parseInt(document.getElementById(\'transit-typical\').value) * 1000;\n const maxTransit = parseInt(document.getElementById(\'transit-max\').value) * 1000;\n const bidirectional = document.getElementById(\'connection-bidirectional\').checked;\n if (fromId === toId) { alert(\'Please select different cameras\'); return; }\n const connection = {\n id: \'conn-\' + Date.now(),\n fromCameraId: fromId,\n toCameraId: toId,\n name: name || fromId + \' to \' + toId,\n exitZone: [],\n entryZone: [],\n transitTime: { min: minTransit, typical: typicalTransit, max: maxTransit },\n bidirectional\n };\n topology.connections.push(connection);\n closeModal(\'add-connection-modal\');\n updateUI();\n render();\n }\n\n function updateUI() {\n const cameraList = document.getElementById(\'camera-list\');\n if (topology.cameras.length === 0) {\n cameraList.innerHTML = \'<div class="camera-item" style="color: #666; text-align: center; cursor: default;">No cameras configured</div>\';\n } else {\n cameraList.innerHTML = topology.cameras.map(c => \'<div class="camera-item \' + (selectedItem?.type === \'camera\' && selectedItem?.id === c.deviceId ? \'selected\' : \'\') + \'" onclick="selectCamera(\\\'\' + c.deviceId + \'\\\')"><div class="camera-name">CAM \' + c.name + \'</div><div class="camera-info">\' + (c.isEntryPoint ? \'Entry \' : \'\') + (c.isExitPoint ? \'Exit\' : \'\') + \'</div></div>\').join(\'\');\n }\n const connectionList = document.getElementById(\'connection-list\');\n if (topology.connections.length === 0) {\n connectionList.innerHTML = \'<div class="connection-item" style="color: #666; text-align: center; cursor: default;">No connections configured</div>\';\n } else {\n connectionList.innerHTML = topology.connections.map(c => \'<div class="connection-item \' + (selectedItem?.type === \'connection\' && selectedItem?.id === c.id ? \'selected\' : \'\') + \'" onclick="selectConnection(\\\'\' + c.id + \'\\\')"><div class="camera-name">\' + c.name + \'</div><div class="camera-info">\' + (c.transitTime.typical / 1000) + \'s typical \' + (c.bidirectional ? \'<->\' : \'->\') + \'</div></div>\').join(\'\');\n }\n document.getElementById(\'camera-count\').textContent = topology.cameras.length;\n document.getElementById(\'connection-count\').textContent = topology.connections.length;\n }\n\n function selectCamera(deviceId) {\n selectedItem = { type: \'camera\', id: deviceId };\n const camera = topology.cameras.find(c => c.deviceId === deviceId);\n showCameraProperties(camera);\n updateUI();\n render();\n }\n\n function selectConnection(connId) {\n selectedItem = { type: \'connection\', id: connId };\n const connection = topology.connections.find(c => c.id === connId);\n showConnectionProperties(connection);\n updateUI();\n render();\n }\n\n function showCameraProperties(camera) {\n const panel = document.getElementById(\'properties-panel\');\n panel.innerHTML = \'<h3>Camera Properties</h3><div class="form-group"><label>Name</label><input type="text" value="\' + camera.name + \'" onchange="updateCameraName(\\\'\' + camera.deviceId + \'\\\', this.value)"></div><div class="form-group"><label class="checkbox-group"><input type="checkbox" \' + (camera.isEntryPoint ? \'checked\' : \'\') + \' onchange="updateCameraEntry(\\\'\' + camera.deviceId + \'\\\', this.checked)">Entry Point</label></div><div class="form-group"><label class="checkbox-group"><input type="checkbox" \' + (camera.isExitPoint ? \'checked\' : \'\') + \' onchange="updateCameraExit(\\\'\' + camera.deviceId + \'\\\', this.checked)">Exit Point</label></div><div class="form-group"><button class="btn" style="width: 100%; background: #f44336;" onclick="deleteCamera(\\\'\' + camera.deviceId + \'\\\')">Delete Camera</button></div>\';\n }\n\n function showConnectionProperties(connection) {\n const panel = document.getElementById(\'properties-panel\');\n panel.innerHTML = \'<h3>Connection Properties</h3><div class="form-group"><label>Name</label><input type="text" value="\' + connection.name + \'" onchange="updateConnectionName(\\\'\' + connection.id + \'\\\', this.value)"></div><div class="form-group"><label>Transit Time (seconds)</label><div class="transit-time-inputs"><input type="number" value="\' + (connection.transitTime.min / 1000) + \'" onchange="updateTransitTime(\\\'\' + connection.id + \'\\\', \\\'min\\\', this.value)"><input type="number" value="\' + (connection.transitTime.typical / 1000) + \'" onchange="updateTransitTime(\\\'\' + connection.id + \'\\\', \\\'typical\\\', this.value)"><input type="number" value="\' + (connection.transitTime.max / 1000) + \'" onchange="updateTransitTime(\\\'\' + connection.id + \'\\\', \\\'max\\\', this.value)"></div><div class="transit-time-labels"><span>Min</span><span>Typical</span><span>Max</span></div></div><div class="form-group"><label class="checkbox-group"><input type="checkbox" \' + (connection.bidirectional ? \'checked\' : \'\') + \' onchange="updateConnectionBidi(\\\'\' + connection.id + \'\\\', this.checked)">Bidirectional</label></div><div class="form-group"><button class="btn" style="width: 100%; background: #f44336;" onclick="deleteConnection(\\\'\' + connection.id + \'\\\')">Delete Connection</button></div>\';\n }\n\n function updateCameraName(id, value) { const camera = topology.cameras.find(c => c.deviceId === id); if (camera) camera.name = value; updateUI(); }\n function updateCameraEntry(id, value) { const camera = topology.cameras.find(c => c.deviceId === id); if (camera) camera.isEntryPoint = value; }\n function updateCameraExit(id, value) { const camera = topology.cameras.find(c => c.deviceId === id); if (camera) camera.isExitPoint = value; }\n function updateConnectionName(id, value) { const conn = topology.connections.find(c => c.id === id); if (conn) conn.name = value; updateUI(); }\n function updateTransitTime(id, field, value) { const conn = topology.connections.find(c => c.id === id); if (conn) conn.transitTime[field] = parseInt(value) * 1000; }\n function updateConnectionBidi(id, value) { const conn = topology.connections.find(c => c.id === id); if (conn) conn.bidirectional = value; render(); }\n function deleteCamera(id) { if (!confirm(\'Delete this camera?\')) return; topology.cameras = topology.cameras.filter(c => c.deviceId !== id); topology.connections = topology.connections.filter(c => c.fromCameraId !== id && c.toCameraId !== id); selectedItem = null; document.getElementById(\'properties-panel\').innerHTML = \'<h3>Properties</h3><p style="color: #666;">Select a camera or connection.</p>\'; updateUI(); render(); }\n function deleteConnection(id) { if (!confirm(\'Delete this connection?\')) return; topology.connections = topology.connections.filter(c => c.id !== id); selectedItem = null; document.getElementById(\'properties-panel\').innerHTML = \'<h3>Properties</h3><p style="color: #666;">Select a camera or connection.</p>\'; updateUI(); render(); }\n function setTool(tool) { currentTool = tool; setStatus(\'Tool: \' + tool, \'success\'); }\n function closeModal(id) { document.getElementById(id).classList.remove(\'active\'); }\n function setStatus(text, type) { document.getElementById(\'status-text\').textContent = text; const dot = document.getElementById(\'status-dot\'); dot.className = \'status-dot\'; if (type === \'warning\') dot.classList.add(\'warning\'); if (type === \'error\') dot.classList.add(\'error\'); }\n\n canvas.addEventListener(\'mousedown\', (e) => {\n const rect = canvas.getBoundingClientRect();\n const x = e.clientX - rect.left;\n const y = e.clientY - rect.top;\n if (currentTool === \'select\') {\n for (const camera of topology.cameras) {\n if (camera.floorPlanPosition) {\n const dist = Math.hypot(x - camera.floorPlanPosition.x, y - camera.floorPlanPosition.y);\n if (dist < 25) { selectCamera(camera.deviceId); return; }\n }\n }\n }\n });\n\n let dragging = null;\n canvas.addEventListener(\'mousedown\', (e) => {\n if (currentTool !== \'select\') return;\n const rect = canvas.getBoundingClientRect();\n const x = e.clientX - rect.left;\n const y = e.clientY - rect.top;\n for (const camera of topology.cameras) {\n if (camera.floorPlanPosition) {\n const dist = Math.hypot(x - camera.floorPlanPosition.x, y - camera.floorPlanPosition.y);\n if (dist < 25) { dragging = camera; return; }\n }\n }\n });\n\n canvas.addEventListener(\'mousemove\', (e) => {\n if (!dragging) return;\n const rect = canvas.getBoundingClientRect();\n dragging.floorPlanPosition.x = e.clientX - rect.left;\n dragging.floorPlanPosition.y = e.clientY - rect.top;\n render();\n });\n\n canvas.addEventListener(\'mouseup\', () => { dragging = null; });\n window.addEventListener(\'resize\', () => { resizeCanvas(); render(); });\n init();\n <\/script>\n</body>\n</html>'},3885(e,t,r){"use strict";e.exports=r(9844)()},3891(e){function t(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=3891,e.exports=t},3936(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(4756),o=n(r(9278)),s=n(r(5753)),a=n(r(6968)),c=(0,s.default)("mqttjs:tls");t.default=(e,t)=>{t.port=t.port||8883,t.host=t.hostname||t.host||"localhost",0===o.default.isIP(t.host)&&(t.servername=t.host),t.rejectUnauthorized=!1!==t.rejectUnauthorized,delete t.path,c("port %d host %s rejectUnauthorized %b",t.port,t.host,t.rejectUnauthorized);const r=function(e){const{host:t,port:r,socksProxy:n,...o}=e;if(void 0!==n){const s=(0,a.default)(t,r,n,{timeout:e.socksTimeout});return(0,i.connect)({...o,socket:s})}return(0,i.connect)(e)}(t);function n(n){t.rejectUnauthorized&&e.emit("error",n),r.end()}return r.on("secureConnect",()=>{t.rejectUnauthorized&&!r.authorized?r.emit("error",new Error("TLS not authorized")):r.removeListener("error",n)}),r.on("error",n),r}},4134(e){"use strict";class t extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError("Expected input to be an Array, got "+typeof e);let t="";for(let r=0;r<e.length;r++)t+=` ${e[r].stack}\n`;super(t),this.name="AggregateError",this.errors=e}}e.exports={AggregateError:t,ArrayIsArray:e=>Array.isArray(e),ArrayPrototypeIncludes:(e,t)=>e.includes(t),ArrayPrototypeIndexOf:(e,t)=>e.indexOf(t),ArrayPrototypeJoin:(e,t)=>e.join(t),ArrayPrototypeMap:(e,t)=>e.map(t),ArrayPrototypePop:(e,t)=>e.pop(t),ArrayPrototypePush:(e,t)=>e.push(t),ArrayPrototypeSlice:(e,t,r)=>e.slice(t,r),Error,FunctionPrototypeCall:(e,t,...r)=>e.call(t,...r),FunctionPrototypeSymbolHasInstance:(e,t)=>Function.prototype[Symbol.hasInstance].call(e,t),MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties:(e,t)=>Object.defineProperties(e,t),ObjectDefineProperty:(e,t,r)=>Object.defineProperty(e,t,r),ObjectGetOwnPropertyDescriptor:(e,t)=>Object.getOwnPropertyDescriptor(e,t),ObjectKeys:e=>Object.keys(e),ObjectSetPrototypeOf:(e,t)=>Object.setPrototypeOf(e,t),Promise,PromisePrototypeCatch:(e,t)=>e.catch(t),PromisePrototypeThen:(e,t,r)=>e.then(t,r),PromiseReject:e=>Promise.reject(e),PromiseResolve:e=>Promise.resolve(e),ReflectApply:Reflect.apply,RegExpPrototypeTest:(e,t)=>e.test(t),SafeSet:Set,String,StringPrototypeSlice:(e,t,r)=>e.slice(t,r),StringPrototypeToLowerCase:e=>e.toLowerCase(),StringPrototypeToUpperCase:e=>e.toUpperCase(),StringPrototypeTrim:e=>e.trim(),Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet:(e,t,r)=>e.set(t,r),Boolean,Uint8Array}},4147(e,t,r){"use strict";const{SymbolDispose:n}=r(4134),{AbortError:i,codes:o}=r(6371),{isNodeStream:s,isWebStream:a,kControllerErrorFunction:c}=r(6115),l=r(6238),{ERR_INVALID_ARG_TYPE:u}=o;let d;e.exports.addAbortSignal=function(t,r){if(((e,t)=>{if("object"!=typeof e||!("aborted"in e))throw new u(t,"AbortSignal",e)})(t,"signal"),!s(r)&&!a(r))throw new u("stream",["ReadableStream","WritableStream","Stream"],r);return e.exports.addAbortSignalNoValidate(t,r)},e.exports.addAbortSignalNoValidate=function(e,t){if("object"!=typeof e||!("aborted"in e))return t;const o=s(t)?()=>{t.destroy(new i(void 0,{cause:e.reason}))}:()=>{t[c](new i(void 0,{cause:e.reason}))};if(e.aborted)o();else{d=d||r(7760).addAbortListener;const i=d(e,o);l(t,i[n])}return t}},4152(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TypedEventEmitter=void 0;const i=n(r(4434)),o=r(4723);class s{}t.TypedEventEmitter=s,(0,o.applyMixin)(s,i.default)},4192(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ScryptedMimeTypes=t.ScryptedInterface=t.MediaPlayerState=t.SecuritySystemObstruction=t.SecuritySystemMode=t.AirQuality=t.AirPurifierMode=t.AirPurifierStatus=t.ChargeState=t.LockState=t.PanTiltZoomMovement=t.ThermostatMode=t.TemperatureUnit=t.FanMode=t.HumidityMode=t.ScryptedDeviceType=t.ScryptedInterfaceDescriptors=t.ScryptedInterfaceMethod=t.ScryptedInterfaceProperty=t.DeviceBase=t.TYPES_VERSION=void 0,t.TYPES_VERSION="0.5.51";var r,n,i,o,s,a,c,l,u,d,h,p,f,g,m,b,y,_;t.DeviceBase=class{},function(e){e.id="id",e.info="info",e.interfaces="interfaces",e.mixins="mixins",e.name="name",e.nativeId="nativeId",e.pluginId="pluginId",e.providedInterfaces="providedInterfaces",e.providedName="providedName",e.providedRoom="providedRoom",e.providedType="providedType",e.providerId="providerId",e.room="room",e.type="type",e.scryptedRuntimeArguments="scryptedRuntimeArguments",e.on="on",e.brightness="brightness",e.colorTemperature="colorTemperature",e.rgb="rgb",e.hsv="hsv",e.buttons="buttons",e.sensors="sensors",e.running="running",e.paused="paused",e.docked="docked",e.temperatureSetting="temperatureSetting",e.temperature="temperature",e.temperatureUnit="temperatureUnit",e.humidity="humidity",e.resolution="resolution",e.audioVolumes="audioVolumes",e.recordingActive="recordingActive",e.ptzCapabilities="ptzCapabilities",e.lockState="lockState",e.entryOpen="entryOpen",e.batteryLevel="batteryLevel",e.chargeState="chargeState",e.online="online",e.fromMimeType="fromMimeType",e.toMimeType="toMimeType",e.converters="converters",e.binaryState="binaryState",e.tampered="tampered",e.sleeping="sleeping",e.powerDetected="powerDetected",e.audioDetected="audioDetected",e.motionDetected="motionDetected",e.ambientLight="ambientLight",e.occupied="occupied",e.flooded="flooded",e.ultraviolet="ultraviolet",e.luminance="luminance",e.position="position",e.securitySystemState="securitySystemState",e.pm10Density="pm10Density",e.pm25Density="pm25Density",e.vocDensity="vocDensity",e.noxDensity="noxDensity",e.co2ppm="co2ppm",e.airQuality="airQuality",e.airPurifierState="airPurifierState",e.filterChangeIndication="filterChangeIndication",e.filterLifeLevel="filterLifeLevel",e.humiditySetting="humiditySetting",e.fan="fan",e.applicationInfo="applicationInfo",e.chatCompletionCapabilities="chatCompletionCapabilities",e.systemDevice="systemDevice"}(r||(t.ScryptedInterfaceProperty=r={})),function(e){e.listen="listen",e.probe="probe",e.setMixins="setMixins",e.setName="setName",e.setRoom="setRoom",e.setType="setType",e.getPluginJson="getPluginJson",e.turnOff="turnOff",e.turnOn="turnOn",e.setBrightness="setBrightness",e.getTemperatureMaxK="getTemperatureMaxK",e.getTemperatureMinK="getTemperatureMinK",e.setColorTemperature="setColorTemperature",e.setRgb="setRgb",e.setHsv="setHsv",e.pressButton="pressButton",e.sendNotification="sendNotification",e.start="start",e.stop="stop",e.pause="pause",e.resume="resume",e.dock="dock",e.setTemperature="setTemperature",e.setTemperatureUnit="setTemperatureUnit",e.getPictureOptions="getPictureOptions",e.takePicture="takePicture",e.getAudioStream="getAudioStream",e.setAudioVolumes="setAudioVolumes",e.startDisplay="startDisplay",e.stopDisplay="stopDisplay",e.getVideoStream="getVideoStream",e.getVideoStreamOptions="getVideoStreamOptions",e.getPrivacyMasks="getPrivacyMasks",e.setPrivacyMasks="setPrivacyMasks",e.getVideoTextOverlays="getVideoTextOverlays",e.setVideoTextOverlay="setVideoTextOverlay",e.getRecordingStream="getRecordingStream",e.getRecordingStreamCurrentTime="getRecordingStreamCurrentTime",e.getRecordingStreamOptions="getRecordingStreamOptions",e.getRecordingStreamThumbnail="getRecordingStreamThumbnail",e.deleteRecordingStream="deleteRecordingStream",e.setRecordingActive="setRecordingActive",e.ptzCommand="ptzCommand",e.getRecordedEvents="getRecordedEvents",e.getVideoClip="getVideoClip",e.getVideoClips="getVideoClips",e.getVideoClipThumbnail="getVideoClipThumbnail",e.removeVideoClips="removeVideoClips",e.setVideoStreamOptions="setVideoStreamOptions",e.startIntercom="startIntercom",e.stopIntercom="stopIntercom",e.lock="lock",e.unlock="unlock",e.addPassword="addPassword",e.getPasswords="getPasswords",e.removePassword="removePassword",e.activate="activate",e.deactivate="deactivate",e.isReversible="isReversible",e.closeEntry="closeEntry",e.openEntry="openEntry",e.getDevice="getDevice",e.releaseDevice="releaseDevice",e.adoptDevice="adoptDevice",e.discoverDevices="discoverDevices",e.createDevice="createDevice",e.getCreateDeviceSettings="getCreateDeviceSettings",e.reboot="reboot",e.getRefreshFrequency="getRefreshFrequency",e.refresh="refresh",e.getMediaStatus="getMediaStatus",e.load="load",e.seek="seek",e.skipNext="skipNext",e.skipPrevious="skipPrevious",e.convert="convert",e.convertMedia="convertMedia",e.getSettings="getSettings",e.putSetting="putSetting",e.armSecuritySystem="armSecuritySystem",e.disarmSecuritySystem="disarmSecuritySystem",e.setAirPurifierState="setAirPurifierState",e.getReadmeMarkdown="getReadmeMarkdown",e.getOauthUrl="getOauthUrl",e.onOauthCallback="onOauthCallback",e.canMixin="canMixin",e.getMixin="getMixin",e.releaseMixin="releaseMixin",e.onRequest="onRequest",e.onConnection="onConnection",e.onPush="onPush",e.run="run",e.eval="eval",e.loadScripts="loadScripts",e.saveScript="saveScript",e.forkInterface="forkInterface",e.getDetectionInput="getDetectionInput",e.getObjectTypes="getObjectTypes",e.detectObjects="detectObjects",e.generateObjectDetections="generateObjectDetections",e.getDetectionModel="getDetectionModel",e.setHumidity="setHumidity",e.setFan="setFan",e.startRTCSignalingSession="startRTCSignalingSession",e.createRTCSignalingSession="createRTCSignalingSession",e.getScryptedUserAccessControl="getScryptedUserAccessControl",e.generateVideoFrames="generateVideoFrames",e.connectStream="connectStream",e.getTTYSettings="getTTYSettings",e.getChatCompletion="getChatCompletion",e.streamChatCompletion="streamChatCompletion",e.getTextEmbedding="getTextEmbedding",e.getImageEmbedding="getImageEmbedding",e.callLLMTool="callLLMTool",e.getLLMTools="getLLMTools"}(n||(t.ScryptedInterfaceMethod=n={})),t.ScryptedInterfaceDescriptors={ScryptedDevice:{name:"ScryptedDevice",methods:["listen","probe","setMixins","setName","setRoom","setType"],properties:["id","info","interfaces","mixins","name","nativeId","pluginId","providedInterfaces","providedName","providedRoom","providedType","providerId","room","type"]},ScryptedPlugin:{name:"ScryptedPlugin",methods:["getPluginJson"],properties:[]},ScryptedPluginRuntime:{name:"ScryptedPluginRuntime",methods:[],properties:["scryptedRuntimeArguments"]},OnOff:{name:"OnOff",methods:["turnOff","turnOn"],properties:["on"]},Brightness:{name:"Brightness",methods:["setBrightness"],properties:["brightness"]},ColorSettingTemperature:{name:"ColorSettingTemperature",methods:["getTemperatureMaxK","getTemperatureMinK","setColorTemperature"],properties:["colorTemperature"]},ColorSettingRgb:{name:"ColorSettingRgb",methods:["setRgb"],properties:["rgb"]},ColorSettingHsv:{name:"ColorSettingHsv",methods:["setHsv"],properties:["hsv"]},Buttons:{name:"Buttons",methods:[],properties:["buttons"]},PressButtons:{name:"PressButtons",methods:["pressButton"],properties:[]},Sensors:{name:"Sensors",methods:[],properties:["sensors"]},Notifier:{name:"Notifier",methods:["sendNotification"],properties:[]},StartStop:{name:"StartStop",methods:["start","stop"],properties:["running"]},Pause:{name:"Pause",methods:["pause","resume"],properties:["paused"]},Dock:{name:"Dock",methods:["dock"],properties:["docked"]},TemperatureSetting:{name:"TemperatureSetting",methods:["setTemperature"],properties:["temperatureSetting"]},Thermometer:{name:"Thermometer",methods:["setTemperatureUnit"],properties:["temperature","temperatureUnit"]},HumiditySensor:{name:"HumiditySensor",methods:[],properties:["humidity"]},Camera:{name:"Camera",methods:["getPictureOptions","takePicture"],properties:[]},Resolution:{name:"Resolution",methods:[],properties:["resolution"]},Microphone:{name:"Microphone",methods:["getAudioStream"],properties:[]},AudioVolumeControl:{name:"AudioVolumeControl",methods:["setAudioVolumes"],properties:["audioVolumes"]},Display:{name:"Display",methods:["startDisplay","stopDisplay"],properties:[]},VideoCamera:{name:"VideoCamera",methods:["getVideoStream","getVideoStreamOptions"],properties:[]},VideoCameraMask:{name:"VideoCameraMask",methods:["getPrivacyMasks","setPrivacyMasks"],properties:[]},VideoTextOverlays:{name:"VideoTextOverlays",methods:["getVideoTextOverlays","setVideoTextOverlay"],properties:[]},VideoRecorder:{name:"VideoRecorder",methods:["getRecordingStream","getRecordingStreamCurrentTime","getRecordingStreamOptions","getRecordingStreamThumbnail"],properties:["recordingActive"]},VideoRecorderManagement:{name:"VideoRecorderManagement",methods:["deleteRecordingStream","setRecordingActive"],properties:[]},PanTiltZoom:{name:"PanTiltZoom",methods:["ptzCommand"],properties:["ptzCapabilities"]},EventRecorder:{name:"EventRecorder",methods:["getRecordedEvents"],properties:[]},VideoClips:{name:"VideoClips",methods:["getVideoClip","getVideoClips","getVideoClipThumbnail","removeVideoClips"],properties:[]},VideoCameraConfiguration:{name:"VideoCameraConfiguration",methods:["setVideoStreamOptions"],properties:[]},Intercom:{name:"Intercom",methods:["startIntercom","stopIntercom"],properties:[]},Lock:{name:"Lock",methods:["lock","unlock"],properties:["lockState"]},PasswordStore:{name:"PasswordStore",methods:["addPassword","getPasswords","removePassword"],properties:[]},Scene:{name:"Scene",methods:["activate","deactivate","isReversible"],properties:[]},Entry:{name:"Entry",methods:["closeEntry","openEntry"],properties:[]},EntrySensor:{name:"EntrySensor",methods:[],properties:["entryOpen"]},DeviceProvider:{name:"DeviceProvider",methods:["getDevice","releaseDevice"],properties:[]},DeviceDiscovery:{name:"DeviceDiscovery",methods:["adoptDevice","discoverDevices"],properties:[]},DeviceCreator:{name:"DeviceCreator",methods:["createDevice","getCreateDeviceSettings"],properties:[]},Battery:{name:"Battery",methods:[],properties:["batteryLevel"]},Charger:{name:"Charger",methods:[],properties:["chargeState"]},Reboot:{name:"Reboot",methods:["reboot"],properties:[]},Refresh:{name:"Refresh",methods:["getRefreshFrequency","refresh"],properties:[]},MediaPlayer:{name:"MediaPlayer",methods:["getMediaStatus","load","seek","skipNext","skipPrevious"],properties:[]},Online:{name:"Online",methods:[],properties:["online"]},BufferConverter:{name:"BufferConverter",methods:["convert"],properties:["fromMimeType","toMimeType"]},MediaConverter:{name:"MediaConverter",methods:["convertMedia"],properties:["converters"]},Settings:{name:"Settings",methods:["getSettings","putSetting"],properties:[]},BinarySensor:{name:"BinarySensor",methods:[],properties:["binaryState"]},TamperSensor:{name:"TamperSensor",methods:[],properties:["tampered"]},Sleep:{name:"Sleep",methods:[],properties:["sleeping"]},PowerSensor:{name:"PowerSensor",methods:[],properties:["powerDetected"]},AudioSensor:{name:"AudioSensor",methods:[],properties:["audioDetected"]},MotionSensor:{name:"MotionSensor",methods:[],properties:["motionDetected"]},AmbientLightSensor:{name:"AmbientLightSensor",methods:[],properties:["ambientLight"]},OccupancySensor:{name:"OccupancySensor",methods:[],properties:["occupied"]},FloodSensor:{name:"FloodSensor",methods:[],properties:["flooded"]},UltravioletSensor:{name:"UltravioletSensor",methods:[],properties:["ultraviolet"]},LuminanceSensor:{name:"LuminanceSensor",methods:[],properties:["luminance"]},PositionSensor:{name:"PositionSensor",methods:[],properties:["position"]},SecuritySystem:{name:"SecuritySystem",methods:["armSecuritySystem","disarmSecuritySystem"],properties:["securitySystemState"]},PM10Sensor:{name:"PM10Sensor",methods:[],properties:["pm10Density"]},PM25Sensor:{name:"PM25Sensor",methods:[],properties:["pm25Density"]},VOCSensor:{name:"VOCSensor",methods:[],properties:["vocDensity"]},NOXSensor:{name:"NOXSensor",methods:[],properties:["noxDensity"]},CO2Sensor:{name:"CO2Sensor",methods:[],properties:["co2ppm"]},AirQualitySensor:{name:"AirQualitySensor",methods:[],properties:["airQuality"]},AirPurifier:{name:"AirPurifier",methods:["setAirPurifierState"],properties:["airPurifierState"]},FilterMaintenance:{name:"FilterMaintenance",methods:[],properties:["filterChangeIndication","filterLifeLevel"]},Readme:{name:"Readme",methods:["getReadmeMarkdown"],properties:[]},OauthClient:{name:"OauthClient",methods:["getOauthUrl","onOauthCallback"],properties:[]},MixinProvider:{name:"MixinProvider",methods:["canMixin","getMixin","releaseMixin"],properties:[]},HttpRequestHandler:{name:"HttpRequestHandler",methods:["onRequest"],properties:[]},EngineIOHandler:{name:"EngineIOHandler",methods:["onConnection"],properties:[]},PushHandler:{name:"PushHandler",methods:["onPush"],properties:[]},Program:{name:"Program",methods:["run"],properties:[]},Scriptable:{name:"Scriptable",methods:["eval","loadScripts","saveScript"],properties:[]},ClusterForkInterface:{name:"ClusterForkInterface",methods:["forkInterface"],properties:[]},ObjectDetector:{name:"ObjectDetector",methods:["getDetectionInput","getObjectTypes"],properties:[]},ObjectDetection:{name:"ObjectDetection",methods:["detectObjects","generateObjectDetections","getDetectionModel"],properties:[]},ObjectDetectionPreview:{name:"ObjectDetectionPreview",methods:[],properties:[]},ObjectDetectionGenerator:{name:"ObjectDetectionGenerator",methods:[],properties:[]},HumiditySetting:{name:"HumiditySetting",methods:["setHumidity"],properties:["humiditySetting"]},Fan:{name:"Fan",methods:["setFan"],properties:["fan"]},RTCSignalingChannel:{name:"RTCSignalingChannel",methods:["startRTCSignalingSession"],properties:[]},RTCSignalingClient:{name:"RTCSignalingClient",methods:["createRTCSignalingSession"],properties:[]},LauncherApplication:{name:"LauncherApplication",methods:[],properties:["applicationInfo"]},ScryptedUser:{name:"ScryptedUser",methods:["getScryptedUserAccessControl"],properties:[]},VideoFrameGenerator:{name:"VideoFrameGenerator",methods:["generateVideoFrames"],properties:[]},StreamService:{name:"StreamService",methods:["connectStream"],properties:[]},TTY:{name:"TTY",methods:[],properties:[]},TTYSettings:{name:"TTYSettings",methods:["getTTYSettings"],properties:[]},ChatCompletion:{name:"ChatCompletion",methods:["getChatCompletion","streamChatCompletion"],properties:["chatCompletionCapabilities"]},TextEmbedding:{name:"TextEmbedding",methods:["getTextEmbedding"],properties:[]},ImageEmbedding:{name:"ImageEmbedding",methods:["getImageEmbedding"],properties:[]},LLMTools:{name:"LLMTools",methods:["callLLMTool","getLLMTools"],properties:[]},ScryptedSystemDevice:{name:"ScryptedSystemDevice",methods:[],properties:["systemDevice"]},ScryptedDeviceCreator:{name:"ScryptedDeviceCreator",methods:[],properties:[]},ScryptedSettings:{name:"ScryptedSettings",methods:[],properties:[]}},function(e){e.Builtin="Builtin",e.Internal="Internal",e.Camera="Camera",e.Fan="Fan",e.Light="Light",e.Switch="Switch",e.Outlet="Outlet",e.Sensor="Sensor",e.Scene="Scene",e.Program="Program",e.Automation="Automation",e.Vacuum="Vacuum",e.Notifier="Notifier",e.Thermostat="Thermostat",e.Lock="Lock",e.PasswordControl="PasswordControl",e.Display="Display",e.SmartDisplay="SmartDisplay",e.Speaker="Speaker",e.SmartSpeaker="SmartSpeaker",e.RemoteDesktop="RemoteDesktop",e.Event="Event",e.Entry="Entry",e.Garage="Garage",e.DeviceProvider="DeviceProvider",e.DataSource="DataSource",e.API="API",e.Buttons="Buttons",e.Doorbell="Doorbell",e.Irrigation="Irrigation",e.Valve="Valve",e.Person="Person",e.SecuritySystem="SecuritySystem",e.WindowCovering="WindowCovering",e.Siren="Siren",e.AirPurifier="AirPurifier",e.Internet="Internet",e.Network="Network",e.Bridge="Bridge",e.LLM="LLM",e.Unknown="Unknown"}(i||(t.ScryptedDeviceType=i={})),function(e){e.Humidify="Humidify",e.Dehumidify="Dehumidify",e.Auto="Auto",e.Off="Off"}(o||(t.HumidityMode=o={})),function(e){e.Auto="Auto",e.Manual="Manual"}(s||(t.FanMode=s={})),function(e){e.C="C",e.F="F"}(a||(t.TemperatureUnit=a={})),function(e){e.Off="Off",e.Cool="Cool",e.Heat="Heat",e.HeatCool="HeatCool",e.Auto="Auto",e.FanOnly="FanOnly",e.Purifier="Purifier",e.Eco="Eco",e.Dry="Dry",e.On="On"}(c||(t.ThermostatMode=c={})),function(e){e.Absolute="Absolute",e.Relative="Relative",e.Continuous="Continuous",e.Preset="Preset",e.Home="Home"}(l||(t.PanTiltZoomMovement=l={})),function(e){e.Locked="Locked",e.Unlocked="Unlocked",e.Jammed="Jammed"}(u||(t.LockState=u={})),function(e){e.Trickle="trickle",e.Charging="charging",e.NotCharging="not-charging"}(d||(t.ChargeState=d={})),function(e){e.Inactive="Inactive",e.Idle="Idle",e.Active="Active",e.ActiveNightMode="ActiveNightMode"}(h||(t.AirPurifierStatus=h={})),function(e){e.Manual="Manual",e.Automatic="Automatic"}(p||(t.AirPurifierMode=p={})),function(e){e.Unknown="Unknown",e.Excellent="Excellent",e.Good="Good",e.Fair="Fair",e.Inferior="Inferior",e.Poor="Poor"}(f||(t.AirQuality=f={})),function(e){e.Disarmed="Disarmed",e.HomeArmed="HomeArmed",e.AwayArmed="AwayArmed",e.NightArmed="NightArmed"}(g||(t.SecuritySystemMode=g={})),function(e){e.Sensor="Sensor",e.Occupied="Occupied",e.Time="Time",e.Error="Error"}(m||(t.SecuritySystemObstruction=m={})),function(e){e.Idle="Idle",e.Playing="Playing",e.Paused="Paused",e.Buffering="Buffering"}(b||(t.MediaPlayerState=b={})),function(e){e.ScryptedDevice="ScryptedDevice",e.ScryptedPlugin="ScryptedPlugin",e.ScryptedPluginRuntime="ScryptedPluginRuntime",e.OnOff="OnOff",e.Brightness="Brightness",e.ColorSettingTemperature="ColorSettingTemperature",e.ColorSettingRgb="ColorSettingRgb",e.ColorSettingHsv="ColorSettingHsv",e.Buttons="Buttons",e.PressButtons="PressButtons",e.Sensors="Sensors",e.Notifier="Notifier",e.StartStop="StartStop",e.Pause="Pause",e.Dock="Dock",e.TemperatureSetting="TemperatureSetting",e.Thermometer="Thermometer",e.HumiditySensor="HumiditySensor",e.Camera="Camera",e.Resolution="Resolution",e.Microphone="Microphone",e.AudioVolumeControl="AudioVolumeControl",e.Display="Display",e.VideoCamera="VideoCamera",e.VideoCameraMask="VideoCameraMask",e.VideoTextOverlays="VideoTextOverlays",e.VideoRecorder="VideoRecorder",e.VideoRecorderManagement="VideoRecorderManagement",e.PanTiltZoom="PanTiltZoom",e.EventRecorder="EventRecorder",e.VideoClips="VideoClips",e.VideoCameraConfiguration="VideoCameraConfiguration",e.Intercom="Intercom",e.Lock="Lock",e.PasswordStore="PasswordStore",e.Scene="Scene",e.Entry="Entry",e.EntrySensor="EntrySensor",e.DeviceProvider="DeviceProvider",e.DeviceDiscovery="DeviceDiscovery",e.DeviceCreator="DeviceCreator",e.Battery="Battery",e.Charger="Charger",e.Reboot="Reboot",e.Refresh="Refresh",e.MediaPlayer="MediaPlayer",e.Online="Online",e.BufferConverter="BufferConverter",e.MediaConverter="MediaConverter",e.Settings="Settings",e.BinarySensor="BinarySensor",e.TamperSensor="TamperSensor",e.Sleep="Sleep",e.PowerSensor="PowerSensor",e.AudioSensor="AudioSensor",e.MotionSensor="MotionSensor",e.AmbientLightSensor="AmbientLightSensor",e.OccupancySensor="OccupancySensor",e.FloodSensor="FloodSensor",e.UltravioletSensor="UltravioletSensor",e.LuminanceSensor="LuminanceSensor",e.PositionSensor="PositionSensor",e.SecuritySystem="SecuritySystem",e.PM10Sensor="PM10Sensor",e.PM25Sensor="PM25Sensor",e.VOCSensor="VOCSensor",e.NOXSensor="NOXSensor",e.CO2Sensor="CO2Sensor",e.AirQualitySensor="AirQualitySensor",e.AirPurifier="AirPurifier",e.FilterMaintenance="FilterMaintenance",e.Readme="Readme",e.OauthClient="OauthClient",e.MixinProvider="MixinProvider",e.HttpRequestHandler="HttpRequestHandler",e.EngineIOHandler="EngineIOHandler",e.PushHandler="PushHandler",e.Program="Program",e.Scriptable="Scriptable",e.ClusterForkInterface="ClusterForkInterface",e.ObjectDetector="ObjectDetector",e.ObjectDetection="ObjectDetection",e.ObjectDetectionPreview="ObjectDetectionPreview",e.ObjectDetectionGenerator="ObjectDetectionGenerator",e.HumiditySetting="HumiditySetting",e.Fan="Fan",e.RTCSignalingChannel="RTCSignalingChannel",e.RTCSignalingClient="RTCSignalingClient",e.LauncherApplication="LauncherApplication",e.ScryptedUser="ScryptedUser",e.VideoFrameGenerator="VideoFrameGenerator",e.StreamService="StreamService",e.TTY="TTY",e.TTYSettings="TTYSettings",e.ChatCompletion="ChatCompletion",e.TextEmbedding="TextEmbedding",e.ImageEmbedding="ImageEmbedding",e.LLMTools="LLMTools",e.ScryptedSystemDevice="ScryptedSystemDevice",e.ScryptedDeviceCreator="ScryptedDeviceCreator",e.ScryptedSettings="ScryptedSettings"}(y||(t.ScryptedInterface=y={})),function(e){e.Url="text/x-uri",e.InsecureLocalUrl="text/x-insecure-local-uri",e.LocalUrl="text/x-local-uri",e.ServerId="text/x-server-id",e.PushEndpoint="text/x-push-endpoint",e.SchemePrefix="x-scrypted/x-scrypted-scheme-",e.MediaStreamUrl="text/x-media-url",e.MediaObject="x-scrypted/x-scrypted-media-object",e.RequestMediaObject="x-scrypted/x-scrypted-request-media-object",e.RequestMediaStream="x-scrypted/x-scrypted-request-stream",e.MediaStreamFeedback="x-scrypted/x-media-stream-feedback",e.FFmpegInput="x-scrypted/x-ffmpeg-input",e.FFmpegTranscodeStream="x-scrypted/x-ffmpeg-transcode-stream",e.RTCSignalingChannel="x-scrypted/x-scrypted-rtc-signaling-channel",e.RTCSignalingSession="x-scrypted/x-scrypted-rtc-signaling-session",e.RTCConnectionManagement="x-scrypted/x-scrypted-rtc-connection-management",e.Image="x-scrypted/x-scrypted-image"}(_||(t.ScryptedMimeTypes=_={}))},4259(e,t,r){"use strict";const{ArrayIsArray:n,ObjectSetPrototypeOf:i}=r(4134),{EventEmitter:o}=r(4434);function s(e){o.call(this,e)}function a(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?n(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}i(s.prototype,o.prototype),i(s,o),s.prototype.pipe=function(e,t){const r=this;function n(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function i(){r.readable&&r.resume&&r.resume()}r.on("data",n),e.on("drain",i),e._isStdio||t&&!1===t.end||(r.on("end",c),r.on("close",l));let s=!1;function c(){s||(s=!0,e.end())}function l(){s||(s=!0,"function"==typeof e.destroy&&e.destroy())}function u(e){d(),0===o.listenerCount(this,"error")&&this.emit("error",e)}function d(){r.removeListener("data",n),e.removeListener("drain",i),r.removeListener("end",c),r.removeListener("close",l),r.removeListener("error",u),e.removeListener("error",u),r.removeListener("end",d),r.removeListener("close",d),e.removeListener("close",d)}return a(r,"error",u),a(e,"error",u),r.on("end",d),r.on("close",d),e.on("close",d),e.emit("pipe",r),e},e.exports={Stream:s,prependListener:a}},4264(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.default=(e,t,r)=>{e.log("handling pubrel packet");const n="undefined"!=typeof r?r:e.noop,{messageId:i}=t,o={cmd:"pubcomp",messageId:i};e.incomingStore.get(t,(t,r)=>{t?e._sendPacket(o,n):(e.emit("message",r.topic,r.payload,r),e.handleMessage(r,t=>{if(t)return n(t);e.incomingStore.del(r,e.noop),e._sendPacket(o,n)}))})}},4386(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AlertManager=void 0;const i=n(r(7562)),o=r(4997),{systemManager:s}=i.default;t.AlertManager=class{rules=[];recentAlerts=[];cooldowns=new Map;console;storage;maxAlerts=100;constructor(e,t){this.console=e,this.storage=t,this.loadRules()}async checkAndAlert(e,t,r){const n=this.rules.find(t=>t.type===e&&t.enabled);if(!n)return null;if(n.objectClasses&&n.objectClasses.length>0&&!n.objectClasses.includes(t.className))return null;if(n.cameraIds&&n.cameraIds.length>0&&r.cameraId&&!n.cameraIds.includes(r.cameraId))return null;const i=`${n.id}:${t.globalId}`,s=this.cooldowns.get(i)||0;if(n.cooldown>0&&Date.now()-s<n.cooldown)return null;if(!this.evaluateConditions(n.conditions,t))return null;const a={...r,objectClass:t.className,objectLabel:t.label},c=(0,o.createAlert)(e,t.globalId,a,n.severity,n.id);return this.recentAlerts.unshift(c),this.recentAlerts.length>this.maxAlerts&&this.recentAlerts.pop(),this.cooldowns.set(i,Date.now()),await this.sendNotifications(c,n),this.console.log(`Alert generated: [${c.severity}] ${c.message}`),c}async sendNotifications(e,t){const r=t.notifiers.length>0?t.notifiers:this.getDefaultNotifiers();for(const t of r)try{const r=s.getDeviceById(t);if(!r){this.console.warn(`Notifier not found: ${t}`);continue}await r.sendNotification(this.getNotificationTitle(e),{body:e.message,data:{type:e.type,severity:e.severity,trackedObjectId:e.trackedObjectId,timestamp:e.timestamp}}),this.console.log(`Notification sent to ${t}`)}catch(e){this.console.error(`Failed to send notification to ${t}:`,e)}}getNotificationTitle(e){const t="critical"===e.severity?"🚨 ":"warning"===e.severity?"⚠️ ":"ℹ️ ";switch(e.type){case"property_entry":return`${t}Entry Detected`;case"property_exit":return`${t}Exit Detected`;case"unusual_path":return`${t}Unusual Path`;case"dwell_time":return`${t}Extended Presence`;case"restricted_zone":return`${t}Restricted Zone Alert`;case"lost_tracking":return`${t}Lost Tracking`;case"reappearance":return`${t}Object Reappeared`;default:return`${t}Spatial Awareness Alert`}}getDefaultNotifiers(){try{const e=this.storage.getItem("defaultNotifier");return e?[e]:[]}catch{return[]}}evaluateConditions(e,t){for(const r of e){const e=this.getFieldValue(r.field,t);switch(r.operator){case"equals":if(e!==r.value)return!1;break;case"not_equals":if(e===r.value)return!1;break;case"contains":if(!String(e).includes(String(r.value)))return!1;break;case"greater_than":if(Number(e)<=Number(r.value))return!1;break;case"less_than":if(Number(e)>=Number(r.value))return!1}}return!0}getFieldValue(e,t){const r=e.split(".");let n=t;for(const e of r){if(null==n)return;n=n[e]}return n}getRecentAlerts(e=50){return this.recentAlerts.slice(0,e)}acknowledgeAlert(e){const t=this.recentAlerts.find(t=>t.id===e);return!!t&&(t.acknowledged=!0,!0)}getAlertsForObject(e){return this.recentAlerts.filter(t=>t.trackedObjectId===e)}setRules(e){this.rules=e,this.saveRules()}getRules(){return this.rules}upsertRule(e){const t=this.rules.findIndex(t=>t.id===e.id);t>=0?this.rules[t]=e:this.rules.push(e),this.saveRules()}deleteRule(e){const t=this.rules.findIndex(t=>t.id===e);return t>=0&&(this.rules.splice(t,1),this.saveRules(),!0)}setRuleEnabled(e,t){const r=this.rules.find(t=>t.id===e);return!!r&&(r.enabled=t,this.saveRules(),!0)}loadRules(){try{const e=this.storage.getItem("alertRules");this.rules=e?JSON.parse(e):(0,o.createDefaultRules)()}catch(e){this.console.error("Failed to load alert rules:",e),this.rules=(0,o.createDefaultRules)()}}saveRules(){try{this.storage.setItem("alertRules",JSON.stringify(this.rules))}catch(e){this.console.error("Failed to save alert rules:",e)}}clearCooldowns(){this.cooldowns.clear()}clearHistory(){this.recentAlerts=[]}}},4422(e){e.exports=global.process},4434(e){"use strict";e.exports=require("events")},4478(e,t,r){"use strict";const n=r(2203);if(n&&"disable"===process.env.READABLE_STREAM){const t=n.promises;e.exports._uint8ArrayToBuffer=n._uint8ArrayToBuffer,e.exports._isUint8Array=n._isUint8Array,e.exports.isDisturbed=n.isDisturbed,e.exports.isErrored=n.isErrored,e.exports.isReadable=n.isReadable,e.exports.Readable=n.Readable,e.exports.Writable=n.Writable,e.exports.Duplex=n.Duplex,e.exports.Transform=n.Transform,e.exports.PassThrough=n.PassThrough,e.exports.addAbortSignal=n.addAbortSignal,e.exports.finished=n.finished,e.exports.destroy=n.destroy,e.exports.pipeline=n.pipeline,e.exports.compose=n.compose,Object.defineProperty(n,"promises",{configurable:!0,enumerable:!0,get:()=>t}),e.exports.Stream=n.Stream}else{const t=r(5506),n=r(3095),i=t.Readable.destroy;e.exports=t.Readable,e.exports._uint8ArrayToBuffer=t._uint8ArrayToBuffer,e.exports._isUint8Array=t._isUint8Array,e.exports.isDisturbed=t.isDisturbed,e.exports.isErrored=t.isErrored,e.exports.isReadable=t.isReadable,e.exports.Readable=t.Readable,e.exports.Writable=t.Writable,e.exports.Duplex=t.Duplex,e.exports.Transform=t.Transform,e.exports.PassThrough=t.PassThrough,e.exports.addAbortSignal=t.addAbortSignal,e.exports.finished=t.finished,e.exports.destroy=t.destroy,e.exports.destroy=i,e.exports.pipeline=t.pipeline,e.exports.compose=t.compose,Object.defineProperty(t,"promises",{configurable:!0,enumerable:!0,get:()=>n}),e.exports.Stream=t.Stream}e.exports.default=e.exports},4723(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.MQTTJS_VERSION=t.nextTick=t.ErrorWithSubackPacket=t.ErrorWithReasonCode=void 0,t.applyMixin=function(e,t,r=!1){const n=[t];for(;;){const e=n[0],t=Object.getPrototypeOf(e);if(!t?.prototype)break;n.unshift(t)}for(const t of n)for(const n of Object.getOwnPropertyNames(t.prototype))(r||"constructor"!==n)&&Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)??Object.create(null))};class n extends Error{code;constructor(e,t){super(e),this.code=t,Object.setPrototypeOf(this,n.prototype),Object.getPrototypeOf(this).name="ErrorWithReasonCode"}}t.ErrorWithReasonCode=n;class i extends Error{packet;constructor(e,t){super(e),this.packet=t,Object.setPrototypeOf(this,i.prototype),Object.getPrototypeOf(this).name="ErrorWithSubackPacket"}}t.ErrorWithSubackPacket=i,t.nextTick="function"==typeof process?.nextTick?process.nextTick:e=>{setTimeout(e,0)},t.MQTTJS_VERSION=r(2860).version},4756(e){"use strict";e.exports=require("tls")},4759(e){"use strict";const t=Symbol("kDone"),r=Symbol("kRun");e.exports=class{constructor(e){this[t]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[t])}}}},4829(e,t,r){"use strict";const n=r(4478).Duplex,i=r(2017),o=r(7813);function s(e){if(!(this instanceof s))return new s(e);if("function"==typeof e){this._callback=e;const t=function(e){this._callback&&(this._callback(e),this._callback=null)}.bind(this);this.on("pipe",function(e){e.on("error",t)}),this.on("unpipe",function(e){e.removeListener("error",t)}),e=null}o._init.call(this,e),n.call(this)}i(s,n),Object.assign(s.prototype,o.prototype),s.prototype._new=function(e){return new s(e)},s.prototype._write=function(e,t,r){this._appendBuffer(e),"function"==typeof r&&r()},s.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)},s.prototype.end=function(e){n.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)},s.prototype._destroy=function(e,t){this._bufs.length=0,this.length=0,t(e)},s.prototype._isBufferList=function(e){return e instanceof s||e instanceof o||s.isBufferList(e)},s.isBufferList=o.isBufferList,e.exports=s,e.exports.BufferListStream=s,e.exports.BufferList=o},4959(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=[0,16,128,131,135,144,145,151,153];t.default=(e,t,n)=>{e.log("handlePublish: packet %o",t),n="undefined"!=typeof n?n:e.noop;let i=t.topic.toString();const o=t.payload,{qos:s}=t,{messageId:a}=t,{options:c}=e;if(5===e.options.protocolVersion){let r;if(t.properties&&(r=t.properties.topicAlias),"undefined"!=typeof r)if(0===i.length){if(!(r>0&&r<=65535))return e.log("handlePublish :: topic alias out of range. alias: %d",r),void e.emit("error",new Error("Received Topic Alias is out of range"));{const t=e.topicAliasRecv.getTopicByAlias(r);if(!t)return e.log("handlePublish :: unregistered topic alias. alias: %d",r),void e.emit("error",new Error("Received unregistered Topic Alias"));i=t,e.log("handlePublish :: topic complemented by alias. topic: %s - alias: %d",i,r)}}else{if(!e.topicAliasRecv.put(i,r))return e.log("handlePublish :: topic alias out of range. alias: %d",r),void e.emit("error",new Error("Received Topic Alias is out of range"));e.log("handlePublish :: registered topic: %s - alias: %d",i,r)}}switch(e.log("handlePublish: qos %d",s),s){case 2:c.customHandleAcks(i,o,t,(i,o)=>("number"==typeof i&&(o=i,i=null),i?e.emit("error",i):-1===r.indexOf(o)?e.emit("error",new Error("Wrong reason code for pubrec")):void(o?e._sendPacket({cmd:"pubrec",messageId:a,reasonCode:o},n):e.incomingStore.put(t,()=>{e._sendPacket({cmd:"pubrec",messageId:a},n)}))));break;case 1:c.customHandleAcks(i,o,t,(s,c)=>("number"==typeof s&&(c=s,s=null),s?e.emit("error",s):-1===r.indexOf(c)?e.emit("error",new Error("Wrong reason code for puback")):(c||e.emit("message",i,o,t),void e.handleMessage(t,t=>{if(t)return n&&n(t);e._sendPacket({cmd:"puback",messageId:a,reasonCode:c},n)}))));break;case 0:e.emit("message",i,o,t),e.handleMessage(t,n);break;default:e.log("handlePublish: unknown QoS. Doing nothing.")}}},4966(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LRUCache=void 0;const r="object"==typeof performance&&performance&&"function"==typeof performance.now?performance:Date,n=new Set,i="object"==typeof process&&process?process:{},o=(e,t,r,n)=>{"function"==typeof i.emitWarning?i.emitWarning(e,t,r,n):console.error(`[${r}] ${t}: ${e}`)};let s=globalThis.AbortController,a=globalThis.AbortSignal;if("undefined"==typeof s){a=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(e,t){this._onabort.push(t)}},s=class{constructor(){t()}signal=new a;abort(e){if(!this.signal.aborted){this.signal.reason=e,this.signal.aborted=!0;for(const t of this.signal._onabort)t(e);this.signal.onabort?.(e)}}};let e="1"!==i.env?.LRU_CACHE_IGNORE_AC_WARNING;const t=()=>{e&&(e=!1,o("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",t))}}Symbol("type");const c=e=>e&&e===Math.floor(e)&&e>0&&isFinite(e),l=e=>c(e)?e<=Math.pow(2,8)?Uint8Array:e<=Math.pow(2,16)?Uint16Array:e<=Math.pow(2,32)?Uint32Array:e<=Number.MAX_SAFE_INTEGER?u:null:null;class u extends Array{constructor(e){super(e),this.fill(0)}}class d{heap;length;static#e=!1;static create(e){const t=l(e);if(!t)return[];d.#e=!0;const r=new d(e,t);return d.#e=!1,r}constructor(e,t){if(!d.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}}class h{#t;#r;#n;#i;#o;#s;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#a;#c;#l;#u;#d;#h;#p;#f;#g;#m;#b;#y;#_;#v;#S;#w;#k;static unsafeExposeInternals(e){return{starts:e.#_,ttls:e.#v,sizes:e.#y,keyMap:e.#l,keyList:e.#u,valList:e.#d,next:e.#h,prev:e.#p,get head(){return e.#f},get tail(){return e.#g},free:e.#m,isBackgroundFetch:t=>e.#E(t),backgroundFetch:(t,r,n,i)=>e.#I(t,r,n,i),moveToTail:t=>e.#T(t),indexes:t=>e.#O(t),rindexes:t=>e.#C(t),isStale:t=>e.#x(t)}}get max(){return this.#t}get maxSize(){return this.#r}get calculatedSize(){return this.#c}get size(){return this.#a}get fetchMethod(){return this.#o}get memoMethod(){return this.#s}get dispose(){return this.#n}get disposeAfter(){return this.#i}constructor(e){const{max:t=0,ttl:r,ttlResolution:i=1,ttlAutopurge:s,updateAgeOnGet:a,updateAgeOnHas:u,allowStale:p,dispose:f,disposeAfter:g,noDisposeOnSet:m,noUpdateTTL:b,maxSize:y=0,maxEntrySize:_=0,sizeCalculation:v,fetchMethod:S,memoMethod:w,noDeleteOnFetchRejection:k,noDeleteOnStaleGet:E,allowStaleOnFetchRejection:I,allowStaleOnFetchAbort:T,ignoreFetchAbort:O}=e;if(0!==t&&!c(t))throw new TypeError("max option must be a nonnegative integer");const C=t?l(t):Array;if(!C)throw new Error("invalid max value: "+t);if(this.#t=t,this.#r=y,this.maxEntrySize=_||this.#r,this.sizeCalculation=v,this.sizeCalculation){if(!this.#r&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if("function"!=typeof this.sizeCalculation)throw new TypeError("sizeCalculation set to non-function")}if(void 0!==w&&"function"!=typeof w)throw new TypeError("memoMethod must be a function if defined");if(this.#s=w,void 0!==S&&"function"!=typeof S)throw new TypeError("fetchMethod must be a function if specified");if(this.#o=S,this.#w=!!S,this.#l=new Map,this.#u=new Array(t).fill(void 0),this.#d=new Array(t).fill(void 0),this.#h=new C(t),this.#p=new C(t),this.#f=0,this.#g=0,this.#m=d.create(t),this.#a=0,this.#c=0,"function"==typeof f&&(this.#n=f),"function"==typeof g?(this.#i=g,this.#b=[]):(this.#i=void 0,this.#b=void 0),this.#S=!!this.#n,this.#k=!!this.#i,this.noDisposeOnSet=!!m,this.noUpdateTTL=!!b,this.noDeleteOnFetchRejection=!!k,this.allowStaleOnFetchRejection=!!I,this.allowStaleOnFetchAbort=!!T,this.ignoreFetchAbort=!!O,0!==this.maxEntrySize){if(0!==this.#r&&!c(this.#r))throw new TypeError("maxSize must be a positive integer if specified");if(!c(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#A()}if(this.allowStale=!!p,this.noDeleteOnStaleGet=!!E,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!u,this.ttlResolution=c(i)||0===i?i:1,this.ttlAutopurge=!!s,this.ttl=r||0,this.ttl){if(!c(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(0===this.#t&&0===this.ttl&&0===this.#r)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#t&&!this.#r){const e="LRU_CACHE_UNBOUNDED";if((e=>!n.has(e))(e)){n.add(e);o("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",e,h)}}}getRemainingTTL(e){return this.#l.has(e)?1/0:0}#P(){const e=new u(this.#t),t=new u(this.#t);this.#v=e,this.#_=t,this.#R=(n,i,o=r.now())=>{if(t[n]=0!==i?o:0,e[n]=i,0!==i&&this.ttlAutopurge){const e=setTimeout(()=>{this.#x(n)&&this.#M(this.#u[n],"expire")},i+1);e.unref&&e.unref()}},this.#B=n=>{t[n]=0!==e[n]?r.now():0},this.#N=(r,o)=>{if(e[o]){const s=e[o],a=t[o];if(!s||!a)return;r.ttl=s,r.start=a,r.now=n||i();const c=r.now-a;r.remainingTTL=s-c}};let n=0;const i=()=>{const e=r.now();if(this.ttlResolution>0){n=e;const t=setTimeout(()=>n=0,this.ttlResolution);t.unref&&t.unref()}return e};this.getRemainingTTL=r=>{const o=this.#l.get(r);if(void 0===o)return 0;const s=e[o],a=t[o];if(!s||!a)return 1/0;return s-((n||i())-a)},this.#x=r=>{const o=t[r],s=e[r];return!!s&&!!o&&(n||i())-o>s}}#B=()=>{};#N=()=>{};#R=()=>{};#x=()=>!1;#A(){const e=new u(this.#t);this.#c=0,this.#y=e,this.#j=t=>{this.#c-=e[t],e[t]=0},this.#D=(e,t,r,n)=>{if(this.#E(t))return 0;if(!c(r)){if(!n)throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");if("function"!=typeof n)throw new TypeError("sizeCalculation must be a function");if(r=n(t,e),!c(r))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}return r},this.#L=(t,r,n)=>{if(e[t]=r,this.#r){const r=this.#r-e[t];for(;this.#c>r;)this.#U(!0)}this.#c+=e[t],n&&(n.entrySize=r,n.totalCalculatedSize=this.#c)}}#j=e=>{};#L=(e,t,r)=>{};#D=(e,t,r,n)=>{if(r||n)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#O({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#g;this.#F(t)&&(!e&&this.#x(t)||(yield t),t!==this.#f);)t=this.#p[t]}*#C({allowStale:e=this.allowStale}={}){if(this.#a)for(let t=this.#f;this.#F(t)&&(!e&&this.#x(t)||(yield t),t!==this.#g);)t=this.#h[t]}#F(e){return void 0!==e&&this.#l.get(this.#u[e])===e}*entries(){for(const e of this.#O())void 0===this.#d[e]||void 0===this.#u[e]||this.#E(this.#d[e])||(yield[this.#u[e],this.#d[e]])}*rentries(){for(const e of this.#C())void 0===this.#d[e]||void 0===this.#u[e]||this.#E(this.#d[e])||(yield[this.#u[e],this.#d[e]])}*keys(){for(const e of this.#O()){const t=this.#u[e];void 0===t||this.#E(this.#d[e])||(yield t)}}*rkeys(){for(const e of this.#C()){const t=this.#u[e];void 0===t||this.#E(this.#d[e])||(yield t)}}*values(){for(const e of this.#O()){void 0===this.#d[e]||this.#E(this.#d[e])||(yield this.#d[e])}}*rvalues(){for(const e of this.#C()){void 0===this.#d[e]||this.#E(this.#d[e])||(yield this.#d[e])}}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(const r of this.#O()){const n=this.#d[r],i=this.#E(n)?n.__staleWhileFetching:n;if(void 0!==i&&e(i,this.#u[r],this))return this.get(this.#u[r],t)}}forEach(e,t=this){for(const r of this.#O()){const n=this.#d[r],i=this.#E(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#u[r],this)}}rforEach(e,t=this){for(const r of this.#C()){const n=this.#d[r],i=this.#E(n)?n.__staleWhileFetching:n;void 0!==i&&e.call(t,i,this.#u[r],this)}}purgeStale(){let e=!1;for(const t of this.#C({allowStale:!0}))this.#x(t)&&(this.#M(this.#u[t],"expire"),e=!0);return e}info(e){const t=this.#l.get(e);if(void 0===t)return;const n=this.#d[t],i=this.#E(n)?n.__staleWhileFetching:n;if(void 0===i)return;const o={value:i};if(this.#v&&this.#_){const e=this.#v[t],n=this.#_[t];if(e&&n){const t=e-(r.now()-n);o.ttl=t,o.start=Date.now()}}return this.#y&&(o.size=this.#y[t]),o}dump(){const e=[];for(const t of this.#O({allowStale:!0})){const n=this.#u[t],i=this.#d[t],o=this.#E(i)?i.__staleWhileFetching:i;if(void 0===o||void 0===n)continue;const s={value:o};if(this.#v&&this.#_){s.ttl=this.#v[t];const e=r.now()-this.#_[t];s.start=Math.floor(Date.now()-e)}this.#y&&(s.size=this.#y[t]),e.unshift([n,s])}return e}load(e){this.clear();for(const[t,n]of e){if(n.start){const e=Date.now()-n.start;n.start=r.now()-e}this.set(t,n.value,n)}}set(e,t,r={}){if(void 0===t)return this.delete(e),this;const{ttl:n=this.ttl,start:i,noDisposeOnSet:o=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:a}=r;let{noUpdateTTL:c=this.noUpdateTTL}=r;const l=this.#D(e,t,r.size||0,s);if(this.maxEntrySize&&l>this.maxEntrySize)return a&&(a.set="miss",a.maxEntrySizeExceeded=!0),this.#M(e,"set"),this;let u=0===this.#a?void 0:this.#l.get(e);if(void 0===u)u=0===this.#a?this.#g:0!==this.#m.length?this.#m.pop():this.#a===this.#t?this.#U(!1):this.#a,this.#u[u]=e,this.#d[u]=t,this.#l.set(e,u),this.#h[this.#g]=u,this.#p[u]=this.#g,this.#g=u,this.#a++,this.#L(u,l,a),a&&(a.set="add"),c=!1;else{this.#T(u);const r=this.#d[u];if(t!==r){if(this.#w&&this.#E(r)){r.__abortController.abort(new Error("replaced"));const{__staleWhileFetching:t}=r;void 0===t||o||(this.#S&&this.#n?.(t,e,"set"),this.#k&&this.#b?.push([t,e,"set"]))}else o||(this.#S&&this.#n?.(r,e,"set"),this.#k&&this.#b?.push([r,e,"set"]));if(this.#j(u),this.#L(u,l,a),this.#d[u]=t,a){a.set="replace";const e=r&&this.#E(r)?r.__staleWhileFetching:r;void 0!==e&&(a.oldValue=e)}}else a&&(a.set="update")}if(0===n||this.#v||this.#P(),this.#v&&(c||this.#R(u,n,i),a&&this.#N(a,u)),!o&&this.#k&&this.#b){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}return this}pop(){try{for(;this.#a;){const e=this.#d[this.#f];if(this.#U(!0),this.#E(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(void 0!==e)return e}}finally{if(this.#k&&this.#b){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}}}#U(e){const t=this.#f,r=this.#u[t],n=this.#d[t];return this.#w&&this.#E(n)?n.__abortController.abort(new Error("evicted")):(this.#S||this.#k)&&(this.#S&&this.#n?.(n,r,"evict"),this.#k&&this.#b?.push([n,r,"evict"])),this.#j(t),e&&(this.#u[t]=void 0,this.#d[t]=void 0,this.#m.push(t)),1===this.#a?(this.#f=this.#g=0,this.#m.length=0):this.#f=this.#h[t],this.#l.delete(r),this.#a--,t}has(e,t={}){const{updateAgeOnHas:r=this.updateAgeOnHas,status:n}=t,i=this.#l.get(e);if(void 0!==i){const e=this.#d[i];if(this.#E(e)&&void 0===e.__staleWhileFetching)return!1;if(!this.#x(i))return r&&this.#B(i),n&&(n.has="hit",this.#N(n,i)),!0;n&&(n.has="stale",this.#N(n,i))}else n&&(n.has="miss");return!1}peek(e,t={}){const{allowStale:r=this.allowStale}=t,n=this.#l.get(e);if(void 0===n||!r&&this.#x(n))return;const i=this.#d[n];return this.#E(i)?i.__staleWhileFetching:i}#I(e,t,r,n){const i=void 0===t?void 0:this.#d[t];if(this.#E(i))return i;const o=new s,{signal:a}=r;a?.addEventListener("abort",()=>o.abort(a.reason),{signal:o.signal});const c={signal:o.signal,options:r,context:n},l=(n,i=!1)=>{const{aborted:s}=o.signal,a=r.ignoreFetchAbort&&void 0!==n;if(r.status&&(s&&!i?(r.status.fetchAborted=!0,r.status.fetchError=o.signal.reason,a&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),s&&!a&&!i)return u(o.signal.reason);const l=d;return this.#d[t]===d&&(void 0===n?l.__staleWhileFetching?this.#d[t]=l.__staleWhileFetching:this.#M(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,n,c.options))),n},u=n=>{const{aborted:i}=o.signal,s=i&&r.allowStaleOnFetchAbort,a=s||r.allowStaleOnFetchRejection,c=a||r.noDeleteOnFetchRejection,l=d;if(this.#d[t]===d){!c||void 0===l.__staleWhileFetching?this.#M(e,"fetch"):s||(this.#d[t]=l.__staleWhileFetching)}if(a)return r.status&&void 0!==l.__staleWhileFetching&&(r.status.returnedStale=!0),l.__staleWhileFetching;if(l.__returned===l)throw n};r.status&&(r.status.fetchDispatched=!0);const d=new Promise((t,n)=>{const s=this.#o?.(e,i,c);s&&s instanceof Promise&&s.then(e=>t(void 0===e?void 0:e),n),o.signal.addEventListener("abort",()=>{r.ignoreFetchAbort&&!r.allowStaleOnFetchAbort||(t(void 0),r.allowStaleOnFetchAbort&&(t=e=>l(e,!0)))})}).then(l,e=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=e),u(e))),h=Object.assign(d,{__abortController:o,__staleWhileFetching:i,__returned:void 0});return void 0===t?(this.set(e,h,{...c.options,status:void 0}),t=this.#l.get(e)):this.#d[t]=h,h}#E(e){if(!this.#w)return!1;const t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof s}async fetch(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:o=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:a=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:l=this.noUpdateTTL,noDeleteOnFetchRejection:u=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:d=this.allowStaleOnFetchRejection,ignoreFetchAbort:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:p=this.allowStaleOnFetchAbort,context:f,forceRefresh:g=!1,status:m,signal:b}=t;if(!this.#w)return m&&(m.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,status:m});const y={allowStale:r,updateAgeOnGet:n,noDeleteOnStaleGet:i,ttl:o,noDisposeOnSet:s,size:a,sizeCalculation:c,noUpdateTTL:l,noDeleteOnFetchRejection:u,allowStaleOnFetchRejection:d,allowStaleOnFetchAbort:p,ignoreFetchAbort:h,status:m,signal:b};let _=this.#l.get(e);if(void 0===_){m&&(m.fetch="miss");const t=this.#I(e,_,y,f);return t.__returned=t}{const t=this.#d[_];if(this.#E(t)){const e=r&&void 0!==t.__staleWhileFetching;return m&&(m.fetch="inflight",e&&(m.returnedStale=!0)),e?t.__staleWhileFetching:t.__returned=t}const i=this.#x(_);if(!g&&!i)return m&&(m.fetch="hit"),this.#T(_),n&&this.#B(_),m&&this.#N(m,_),t;const o=this.#I(e,_,y,f),s=void 0!==o.__staleWhileFetching&&r;return m&&(m.fetch=i?"stale":"refresh",s&&i&&(m.returnedStale=!0)),s?o.__staleWhileFetching:o.__returned=o}}async forceFetch(e,t={}){const r=await this.fetch(e,t);if(void 0===r)throw new Error("fetch() returned undefined");return r}memo(e,t={}){const r=this.#s;if(!r)throw new Error("no memoMethod provided to constructor");const{context:n,forceRefresh:i,...o}=t,s=this.get(e,o);if(!i&&void 0!==s)return s;const a=r(e,s,{options:o,context:n});return this.set(e,a,o),a}get(e,t={}){const{allowStale:r=this.allowStale,updateAgeOnGet:n=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:o}=t,s=this.#l.get(e);if(void 0!==s){const t=this.#d[s],a=this.#E(t);return o&&this.#N(o,s),this.#x(s)?(o&&(o.get="stale"),a?(o&&r&&void 0!==t.__staleWhileFetching&&(o.returnedStale=!0),r?t.__staleWhileFetching:void 0):(i||this.#M(e,"expire"),o&&r&&(o.returnedStale=!0),r?t:void 0)):(o&&(o.get="hit"),a?t.__staleWhileFetching:(this.#T(s),n&&this.#B(s),t))}o&&(o.get="miss")}#$(e,t){this.#p[t]=e,this.#h[e]=t}#T(e){e!==this.#g&&(e===this.#f?this.#f=this.#h[e]:this.#$(this.#p[e],this.#h[e]),this.#$(this.#g,e),this.#g=e)}delete(e){return this.#M(e,"delete")}#M(e,t){let r=!1;if(0!==this.#a){const n=this.#l.get(e);if(void 0!==n)if(r=!0,1===this.#a)this.#V(t);else{this.#j(n);const r=this.#d[n];if(this.#E(r)?r.__abortController.abort(new Error("deleted")):(this.#S||this.#k)&&(this.#S&&this.#n?.(r,e,t),this.#k&&this.#b?.push([r,e,t])),this.#l.delete(e),this.#u[n]=void 0,this.#d[n]=void 0,n===this.#g)this.#g=this.#p[n];else if(n===this.#f)this.#f=this.#h[n];else{const e=this.#p[n];this.#h[e]=this.#h[n];const t=this.#h[n];this.#p[t]=this.#p[n]}this.#a--,this.#m.push(n)}}if(this.#k&&this.#b?.length){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}return r}clear(){return this.#V("delete")}#V(e){for(const t of this.#C({allowStale:!0})){const r=this.#d[t];if(this.#E(r))r.__abortController.abort(new Error("deleted"));else{const n=this.#u[t];this.#S&&this.#n?.(r,n,e),this.#k&&this.#b?.push([r,n,e])}}if(this.#l.clear(),this.#d.fill(void 0),this.#u.fill(void 0),this.#v&&this.#_&&(this.#v.fill(0),this.#_.fill(0)),this.#y&&this.#y.fill(0),this.#f=0,this.#g=0,this.#m.length=0,this.#c=0,this.#a=0,this.#k&&this.#b){const e=this.#b;let t;for(;t=e?.shift();)this.#i?.(...t)}}}t.LRUCache=h},4988(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r=new WeakMap,n=new WeakMap;function i(e){const t=r.get(e);return console.assert(null!=t,"'this' is expected an Event object, but got",e),t}function o(e){null==e.passiveListener?e.event.cancelable&&(e.canceled=!0,"function"==typeof e.event.preventDefault&&e.event.preventDefault()):"undefined"!=typeof console&&"function"==typeof console.error&&console.error("Unable to preventDefault inside passive event listener invocation.",e.passiveListener)}function s(e,t){r.set(this,{eventTarget:e,event:t,eventPhase:2,currentTarget:e,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:t.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});const n=Object.keys(t);for(let e=0;e<n.length;++e){const t=n[e];t in this||Object.defineProperty(this,t,a(t))}}function a(e){return{get(){return i(this).event[e]},set(t){i(this).event[e]=t},configurable:!0,enumerable:!0}}function c(e){return{value(){const t=i(this).event;return t[e].apply(t,arguments)},configurable:!0,enumerable:!0}}function l(e){if(null==e||e===Object.prototype)return s;let t=n.get(e);return null==t&&(t=function(e,t){const r=Object.keys(t);if(0===r.length)return e;function n(t,r){e.call(this,t,r)}n.prototype=Object.create(e.prototype,{constructor:{value:n,configurable:!0,writable:!0}});for(let i=0;i<r.length;++i){const o=r[i];if(!(o in e.prototype)){const e="function"==typeof Object.getOwnPropertyDescriptor(t,o).value;Object.defineProperty(n.prototype,o,e?c(o):a(o))}}return n}(l(Object.getPrototypeOf(e)),e),n.set(e,t)),t}function u(e){return i(e).immediateStopped}function d(e,t){i(e).passiveListener=t}s.prototype={get type(){return i(this).event.type},get target(){return i(this).eventTarget},get currentTarget(){return i(this).currentTarget},composedPath(){const e=i(this).currentTarget;return null==e?[]:[e]},get NONE(){return 0},get CAPTURING_PHASE(){return 1},get AT_TARGET(){return 2},get BUBBLING_PHASE(){return 3},get eventPhase(){return i(this).eventPhase},stopPropagation(){const e=i(this);e.stopped=!0,"function"==typeof e.event.stopPropagation&&e.event.stopPropagation()},stopImmediatePropagation(){const e=i(this);e.stopped=!0,e.immediateStopped=!0,"function"==typeof e.event.stopImmediatePropagation&&e.event.stopImmediatePropagation()},get bubbles(){return Boolean(i(this).event.bubbles)},get cancelable(){return Boolean(i(this).event.cancelable)},preventDefault(){o(i(this))},get defaultPrevented(){return i(this).canceled},get composed(){return Boolean(i(this).event.composed)},get timeStamp(){return i(this).timeStamp},get srcElement(){return i(this).eventTarget},get cancelBubble(){return i(this).stopped},set cancelBubble(e){if(!e)return;const t=i(this);t.stopped=!0,"boolean"==typeof t.event.cancelBubble&&(t.event.cancelBubble=!0)},get returnValue(){return!i(this).canceled},set returnValue(e){e||o(i(this))},initEvent(){}},Object.defineProperty(s.prototype,"constructor",{value:s,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.Event&&(Object.setPrototypeOf(s.prototype,window.Event.prototype),n.set(window.Event.prototype,s));const h=new WeakMap;function p(e){return null!==e&&"object"==typeof e}function f(e){const t=h.get(e);if(null==t)throw new TypeError("'this' is expected an EventTarget object, but got another value.");return t}function g(e,t){Object.defineProperty(e,`on${t}`,function(e){return{get(){let t=f(this).get(e);for(;null!=t;){if(3===t.listenerType)return t.listener;t=t.next}return null},set(t){"function"==typeof t||p(t)||(t=null);const r=f(this);let n=null,i=r.get(e);for(;null!=i;)3===i.listenerType?null!==n?n.next=i.next:null!==i.next?r.set(e,i.next):r.delete(e):n=i,i=i.next;if(null!==t){const i={listener:t,listenerType:3,passive:!1,once:!1,next:null};null===n?r.set(e,i):n.next=i}},configurable:!0,enumerable:!0}}(t))}function m(e){function t(){b.call(this)}t.prototype=Object.create(b.prototype,{constructor:{value:t,configurable:!0,writable:!0}});for(let r=0;r<e.length;++r)g(t.prototype,e[r]);return t}function b(){if(!(this instanceof b)){if(1===arguments.length&&Array.isArray(arguments[0]))return m(arguments[0]);if(arguments.length>0){const e=new Array(arguments.length);for(let t=0;t<arguments.length;++t)e[t]=arguments[t];return m(e)}throw new TypeError("Cannot call a class as a function")}h.set(this,new Map)}b.prototype={addEventListener(e,t,r){if(null==t)return;if("function"!=typeof t&&!p(t))throw new TypeError("'listener' should be a function or an object.");const n=f(this),i=p(r),o=(i?Boolean(r.capture):Boolean(r))?1:2,s={listener:t,listenerType:o,passive:i&&Boolean(r.passive),once:i&&Boolean(r.once),next:null};let a=n.get(e);if(void 0===a)return void n.set(e,s);let c=null;for(;null!=a;){if(a.listener===t&&a.listenerType===o)return;c=a,a=a.next}c.next=s},removeEventListener(e,t,r){if(null==t)return;const n=f(this),i=(p(r)?Boolean(r.capture):Boolean(r))?1:2;let o=null,s=n.get(e);for(;null!=s;){if(s.listener===t&&s.listenerType===i)return void(null!==o?o.next=s.next:null!==s.next?n.set(e,s.next):n.delete(e));o=s,s=s.next}},dispatchEvent(e){if(null==e||"string"!=typeof e.type)throw new TypeError('"event.type" should be a string.');const t=f(this),r=e.type;let n=t.get(r);if(null==n)return!0;const o=function(e,t){return new(l(Object.getPrototypeOf(t)))(e,t)}(this,e);let s=null;for(;null!=n;){if(n.once?null!==s?s.next=n.next:null!==n.next?t.set(r,n.next):t.delete(r):s=n,d(o,n.passive?n.listener:null),"function"==typeof n.listener)try{n.listener.call(this,o)}catch(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e)}else 3!==n.listenerType&&"function"==typeof n.listener.handleEvent&&n.listener.handleEvent(o);if(u(o))break;n=n.next}return d(o,null),function(e,t){i(e).eventPhase=t}(o,0),function(e,t){i(e).currentTarget=t}(o,null),!o.defaultPrevented}},Object.defineProperty(b.prototype,"constructor",{value:b,configurable:!0,writable:!0}),"undefined"!=typeof window&&"undefined"!=typeof window.EventTarget&&Object.setPrototypeOf(b.prototype,window.EventTarget.prototype),t.defineEventAttribute=g,t.EventTarget=b,t.default=b,e.exports=b,e.exports.EventTarget=e.exports.default=b,e.exports.defineEventAttribute=g},4997(e,t){"use strict";function r(e,t){const r=t.objectLabel?`${t.objectClass} (${t.objectLabel})`:t.objectClass||"Object";switch(e){case"property_entry":return`${r} entered property via ${t.cameraName||"unknown camera"}`;case"property_exit":return`${r} exited property via ${t.cameraName||"unknown camera"}`;case"unusual_path":return`${r} took unusual path: ${t.actualPath||"unknown"}`;case"dwell_time":return`${r} has been present for ${Math.round((t.dwellTime||0)/6e4)} minutes in ${t.zoneName||t.cameraName||"area"}`;case"restricted_zone":return`${r} entered restricted zone: ${t.zoneName}`;case"lost_tracking":return`Lost tracking of ${r} near ${t.cameraName||"unknown location"}`;case"reappearance":return`${r} reappeared on ${t.cameraName}`;case"zone_entry":return`${r} entered ${t.zoneName}`;case"zone_exit":return`${r} exited ${t.zoneName}`;default:return`Tracking event: ${e}`}}Object.defineProperty(t,"__esModule",{value:!0}),t.createDefaultRules=function(){return[{id:"property-entry",name:"Property Entry",enabled:!0,type:"property_entry",conditions:[],severity:"info",notifiers:[],cooldown:3e5},{id:"property-exit",name:"Property Exit",enabled:!0,type:"property_exit",conditions:[],severity:"info",notifiers:[],cooldown:3e5},{id:"unusual-path",name:"Unusual Path Detected",enabled:!0,type:"unusual_path",conditions:[],severity:"warning",notifiers:[],cooldown:6e5},{id:"dwell-time",name:"Extended Dwell Time",enabled:!0,type:"dwell_time",conditions:[{field:"totalDwellTime",operator:"greater_than",value:3e5}],severity:"warning",notifiers:[],cooldown:6e5},{id:"restricted-zone",name:"Restricted Zone Entry",enabled:!0,type:"restricted_zone",conditions:[],severity:"critical",notifiers:[],cooldown:0},{id:"lost-tracking",name:"Lost Object Tracking",enabled:!1,type:"lost_tracking",conditions:[],severity:"info",notifiers:[],cooldown:3e5}]},t.generateAlertMessage=r,t.createAlert=function(e,t,n,i="info",o){return{id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`,type:e,severity:i,timestamp:Date.now(),trackedObjectId:t,message:r(e,n),details:n,acknowledged:!1,ruleId:o}}},5228(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(4723),i=r(1021);t.default=(e,t)=>{const{options:r}=e,o=r.protocolVersion,s=5===o?t.reasonCode:t.returnCode;if(5!==o){const t=new n.ErrorWithReasonCode(`Protocol error: Auth packets are only supported in MQTT 5. Your version:${o}`,s);return void e.emit("error",t)}e.handleAuth(t,(t,r)=>{if(t)e.emit("error",t);else if(24===s)e.reconnecting=!1,e._sendPacket(r);else{const t=new n.ErrorWithReasonCode(`Connection refused: ${i.ReasonCodes[s]}`,s);e.emit("error",t)}})}},5291(e,t,r){"use strict";const{MathFloor:n,NumberIsInteger:i}=r(4134),{validateInteger:o}=r(277),{ERR_INVALID_ARG_VALUE:s}=r(6371).codes;let a=16384,c=16;function l(e){return e?c:a}e.exports={getHighWaterMark:function(e,t,r,o){const a=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,o,r);if(null!=a){if(!i(a)||a<0){throw new s(o?`options.${r}`:"options.highWaterMark",a)}return n(a)}return l(e.objectMode)},getDefaultHighWaterMark:l,setDefaultHighWaterMark:function(e,t){o(t,"value",0),e?c=t:a=t}}},5389(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TrackingState=void 0;const n=r(441);t.TrackingState=class{objects=new Map;objectsByCamera=new Map;changeCallbacks=[];storage;console;constructor(e,t){this.storage=e,this.console=t,this.loadPersistedState()}createObject(e,t,r){const i=(0,n.createTrackedObject)(e,t,r);return this.upsertObject(i),i}upsertObject(e){const t=this.objects.get(e.globalId);if(t)for(const r of t.activeOnCameras)this.objectsByCamera.get(r)?.delete(e.globalId);for(const t of e.activeOnCameras)this.objectsByCamera.has(t)||this.objectsByCamera.set(t,new Set),this.objectsByCamera.get(t).add(e.globalId);this.objects.set(e.globalId,e),this.notifyChange(),this.persistState()}addSighting(e,t){const r=this.objects.get(e);return!!r&&((0,n.addSighting)(r,t),this.objectsByCamera.has(t.cameraId)||this.objectsByCamera.set(t.cameraId,new Set),this.objectsByCamera.get(t.cameraId).add(e),this.notifyChange(),this.persistState(),!0)}addJourney(e,t){const r=this.objects.get(e);return!!r&&((0,n.addJourneySegment)(r,t),this.objectsByCamera.get(t.fromCameraId)?.delete(e),this.objectsByCamera.has(t.toCameraId)||this.objectsByCamera.set(t.toCameraId,new Set),this.objectsByCamera.get(t.toCameraId).add(e),this.notifyChange(),this.persistState(),!0)}getObject(e){return this.objects.get(e)}getActiveObjects(){return Array.from(this.objects.values()).filter(e=>"active"===e.state||"pending"===e.state)}getObjectsOnCamera(e){const t=this.objectsByCamera.get(e)||new Set;return Array.from(t).map(e=>this.objects.get(e)).filter(e=>!!e&&"active"===e.state)}getAllObjects(){return Array.from(this.objects.values())}getActiveCount(){return this.getActiveObjects().length}getJourney(e){return this.objects.get(e)?.journey}markExited(e,t,r){const n=this.objects.get(e);if(n){n.state="exited",n.hasExited=!0,n.exitCamera=t,n.exitCameraName=r,n.activeOnCameras=[];for(const[t,r]of this.objectsByCamera.entries())r.delete(e);this.notifyChange(),this.persistState()}}markLost(e){const t=this.objects.get(e);if(t){t.state="lost",t.activeOnCameras=[];for(const[t,r]of this.objectsByCamera.entries())r.delete(e);this.notifyChange(),this.persistState()}}markPending(e){const t=this.objects.get(e);t&&"active"===t.state&&(t.state="pending",this.notifyChange())}reactivate(e){const t=this.objects.get(e);t&&"pending"===t.state&&(t.state="active",this.notifyChange())}onStateChange(e){this.changeCallbacks.push(e)}offStateChange(e){const t=this.changeCallbacks.indexOf(e);-1!==t&&this.changeCallbacks.splice(t,1)}notifyChange(){const e=this.getAllObjects();for(const t of this.changeCallbacks)try{t(e)}catch(e){this.console.error("State change callback error:",e)}}persistState(){try{const e=Date.now(),t=Array.from(this.objects.values()).filter(t=>"active"===t.state||"pending"===t.state||e-t.lastSeen<36e5);this.storage.setItem("tracked-objects",JSON.stringify(t))}catch(e){this.console.error("Failed to persist tracking state:",e)}}loadPersistedState(){try{const e=this.storage.getItem("tracked-objects");if(e){const t=JSON.parse(e),r=Date.now();for(const e of t){"active"===e.state&&r-e.lastSeen>3e5&&(e.state="lost",e.activeOnCameras=[]),this.objects.set(e.globalId,e);for(const t of e.activeOnCameras)this.objectsByCamera.has(t)||this.objectsByCamera.set(t,new Set),this.objectsByCamera.get(t).add(e.globalId)}this.console.log(`Loaded ${t.length} persisted tracked objects`)}}catch(e){this.console.error("Failed to load persisted tracking state:",e)}}cleanup(e=864e5){const t=Date.now();let r=0;for(const[n,i]of this.objects.entries())t-i.lastSeen>e&&"active"!==i.state&&(this.objects.delete(n),r++);r>0&&(this.console.log(`Cleaned up ${r} old tracked objects`),this.persistState())}generateId(){return`${Date.now()}-${Math.random().toString(36).slice(2,9)}`}}},5399(e,t,r){const n=e.exports,{Buffer:i}=r(181);n.types={0:"reserved",1:"connect",2:"connack",3:"publish",4:"puback",5:"pubrec",6:"pubrel",7:"pubcomp",8:"subscribe",9:"suback",10:"unsubscribe",11:"unsuback",12:"pingreq",13:"pingresp",14:"disconnect",15:"auth"},n.requiredHeaderFlags={1:0,2:0,4:0,5:0,6:2,7:0,8:2,9:0,10:2,11:0,12:0,13:0,14:0,15:0},n.requiredHeaderFlagsErrors={};for(const e in n.requiredHeaderFlags){const t=n.requiredHeaderFlags[e];n.requiredHeaderFlagsErrors[e]="Invalid header flag bits, must be 0x"+t.toString(16)+" for "+n.types[e]+" packet"}n.codes={};for(const e in n.types){const t=n.types[e];n.codes[t]=e}n.CMD_SHIFT=4,n.CMD_MASK=240,n.DUP_MASK=8,n.QOS_MASK=3,n.QOS_SHIFT=1,n.RETAIN_MASK=1,n.VARBYTEINT_MASK=127,n.VARBYTEINT_FIN_MASK=128,n.VARBYTEINT_MAX=268435455,n.SESSIONPRESENT_MASK=1,n.SESSIONPRESENT_HEADER=i.from([n.SESSIONPRESENT_MASK]),n.CONNACK_HEADER=i.from([n.codes.connack<<n.CMD_SHIFT]),n.USERNAME_MASK=128,n.PASSWORD_MASK=64,n.WILL_RETAIN_MASK=32,n.WILL_QOS_MASK=24,n.WILL_QOS_SHIFT=3,n.WILL_FLAG_MASK=4,n.CLEAN_SESSION_MASK=2,n.CONNECT_HEADER=i.from([n.codes.connect<<n.CMD_SHIFT]),n.properties={sessionExpiryInterval:17,willDelayInterval:24,receiveMaximum:33,maximumPacketSize:39,topicAliasMaximum:34,requestResponseInformation:25,requestProblemInformation:23,userProperties:38,authenticationMethod:21,authenticationData:22,payloadFormatIndicator:1,messageExpiryInterval:2,contentType:3,responseTopic:8,correlationData:9,maximumQoS:36,retainAvailable:37,assignedClientIdentifier:18,reasonString:31,wildcardSubscriptionAvailable:40,subscriptionIdentifiersAvailable:41,sharedSubscriptionAvailable:42,serverKeepAlive:19,responseInformation:26,serverReference:28,topicAlias:35,subscriptionIdentifier:11},n.propertiesCodes={};for(const e in n.properties){const t=n.properties[e];n.propertiesCodes[t]=e}function o(e){return[0,1,2].map(t=>[0,1].map(r=>[0,1].map(o=>{const s=i.alloc(1);return s.writeUInt8(n.codes[e]<<n.CMD_SHIFT|(r?n.DUP_MASK:0)|t<<n.QOS_SHIFT|o,0,!0),s})))}n.propertiesTypes={sessionExpiryInterval:"int32",willDelayInterval:"int32",receiveMaximum:"int16",maximumPacketSize:"int32",topicAliasMaximum:"int16",requestResponseInformation:"byte",requestProblemInformation:"byte",userProperties:"pair",authenticationMethod:"string",authenticationData:"binary",payloadFormatIndicator:"byte",messageExpiryInterval:"int32",contentType:"string",responseTopic:"string",correlationData:"binary",maximumQoS:"int8",retainAvailable:"byte",assignedClientIdentifier:"string",reasonString:"string",wildcardSubscriptionAvailable:"byte",subscriptionIdentifiersAvailable:"byte",sharedSubscriptionAvailable:"byte",serverKeepAlive:"int16",responseInformation:"string",serverReference:"string",topicAlias:"int16",subscriptionIdentifier:"var"},n.PUBLISH_HEADER=o("publish"),n.SUBSCRIBE_HEADER=o("subscribe"),n.SUBSCRIBE_OPTIONS_QOS_MASK=3,n.SUBSCRIBE_OPTIONS_NL_MASK=1,n.SUBSCRIBE_OPTIONS_NL_SHIFT=2,n.SUBSCRIBE_OPTIONS_RAP_MASK=1,n.SUBSCRIBE_OPTIONS_RAP_SHIFT=3,n.SUBSCRIBE_OPTIONS_RH_MASK=3,n.SUBSCRIBE_OPTIONS_RH_SHIFT=4,n.SUBSCRIBE_OPTIONS_RH=[0,16,32],n.SUBSCRIBE_OPTIONS_NL=4,n.SUBSCRIBE_OPTIONS_RAP=8,n.SUBSCRIBE_OPTIONS_QOS=[0,1,2],n.UNSUBSCRIBE_HEADER=o("unsubscribe"),n.ACKS={unsuback:o("unsuback"),puback:o("puback"),pubcomp:o("pubcomp"),pubrel:o("pubrel"),pubrec:o("pubrec")},n.SUBACK_HEADER=i.from([n.codes.suback<<n.CMD_SHIFT]),n.VERSION3=i.from([3]),n.VERSION4=i.from([4]),n.VERSION5=i.from([5]),n.VERSION131=i.from([131]),n.VERSION132=i.from([132]),n.QOS=[0,1,2].map(e=>i.from([e])),n.EMPTY={pingreq:i.from([n.codes.pingreq<<4,0]),pingresp:i.from([n.codes.pingresp<<4,0]),disconnect:i.from([n.codes.disconnect<<4,0])},n.MQTT5_PUBACK_PUBREC_CODES={0:"Success",16:"No matching subscribers",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",144:"Topic Name invalid",145:"Packet identifier in use",151:"Quota exceeded",153:"Payload format invalid"},n.MQTT5_PUBREL_PUBCOMP_CODES={0:"Success",146:"Packet Identifier not found"},n.MQTT5_SUBACK_CODES={0:"Granted QoS 0",1:"Granted QoS 1",2:"Granted QoS 2",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use",151:"Quota exceeded",158:"Shared Subscriptions not supported",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},n.MQTT5_UNSUBACK_CODES={0:"Success",17:"No subscription existed",128:"Unspecified error",131:"Implementation specific error",135:"Not authorized",143:"Topic Filter invalid",145:"Packet Identifier in use"},n.MQTT5_DISCONNECT_CODES={0:"Normal disconnection",4:"Disconnect with Will Message",128:"Unspecified error",129:"Malformed Packet",130:"Protocol Error",131:"Implementation specific error",135:"Not authorized",137:"Server busy",139:"Server shutting down",141:"Keep Alive timeout",142:"Session taken over",143:"Topic Filter invalid",144:"Topic Name invalid",147:"Receive Maximum exceeded",148:"Topic Alias invalid",149:"Packet too large",150:"Message rate too high",151:"Quota exceeded",152:"Administrative action",153:"Payload format invalid",154:"Retain not supported",155:"QoS not supported",156:"Use another server",157:"Server moved",158:"Shared Subscriptions not supported",159:"Connection rate exceeded",160:"Maximum connect time",161:"Subscription Identifiers not supported",162:"Wildcard Subscriptions not supported"},n.MQTT5_AUTH_CODES={0:"Success",24:"Continue authentication",25:"Re-authenticate"}},5438(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SOCKS5_NO_ACCEPTABLE_AUTH=t.SOCKS5_CUSTOM_AUTH_END=t.SOCKS5_CUSTOM_AUTH_START=t.SOCKS_INCOMING_PACKET_SIZES=t.SocksClientState=t.Socks5Response=t.Socks5HostType=t.Socks5Auth=t.Socks4Response=t.SocksCommand=t.ERRORS=t.DEFAULT_TIMEOUT=void 0;t.DEFAULT_TIMEOUT=3e4;t.ERRORS={InvalidSocksCommand:"An invalid SOCKS command was provided. Valid options are connect, bind, and associate.",InvalidSocksCommandForOperation:"An invalid SOCKS command was provided. Only a subset of commands are supported for this operation.",InvalidSocksCommandChain:"An invalid SOCKS command was provided. Chaining currently only supports the connect command.",InvalidSocksClientOptionsDestination:"An invalid destination host was provided.",InvalidSocksClientOptionsExistingSocket:"An invalid existing socket was provided. This should be an instance of stream.Duplex.",InvalidSocksClientOptionsProxy:"Invalid SOCKS proxy details were provided.",InvalidSocksClientOptionsTimeout:"An invalid timeout value was provided. Please enter a value above 0 (in ms).",InvalidSocksClientOptionsProxiesLength:"At least two socks proxies must be provided for chaining.",InvalidSocksClientOptionsCustomAuthRange:"Custom auth must be a value between 0x80 and 0xFE.",InvalidSocksClientOptionsCustomAuthOptions:"When a custom_auth_method is provided, custom_auth_request_handler, custom_auth_response_size, and custom_auth_response_handler must also be provided and valid.",NegotiationError:"Negotiation error",SocketClosed:"Socket closed",ProxyConnectionTimedOut:"Proxy connection timed out",InternalError:"SocksClient internal error (this should not happen)",InvalidSocks4HandshakeResponse:"Received invalid Socks4 handshake response",Socks4ProxyRejectedConnection:"Socks4 Proxy rejected connection",InvalidSocks4IncomingConnectionResponse:"Socks4 invalid incoming connection response",Socks4ProxyRejectedIncomingBoundConnection:"Socks4 Proxy rejected incoming bound connection",InvalidSocks5InitialHandshakeResponse:"Received invalid Socks5 initial handshake response",InvalidSocks5IntiailHandshakeSocksVersion:"Received invalid Socks5 initial handshake (invalid socks version)",InvalidSocks5InitialHandshakeNoAcceptedAuthType:"Received invalid Socks5 initial handshake (no accepted authentication type)",InvalidSocks5InitialHandshakeUnknownAuthType:"Received invalid Socks5 initial handshake (unknown authentication type)",Socks5AuthenticationFailed:"Socks5 Authentication failed",InvalidSocks5FinalHandshake:"Received invalid Socks5 final handshake response",InvalidSocks5FinalHandshakeRejected:"Socks5 proxy rejected connection",InvalidSocks5IncomingConnectionResponse:"Received invalid Socks5 incoming connection response",Socks5ProxyRejectedIncomingBoundConnection:"Socks5 Proxy rejected incoming bound connection"};var r,n,i;t.SOCKS_INCOMING_PACKET_SIZES={Socks5InitialHandshakeResponse:2,Socks5UserPassAuthenticationResponse:2,Socks5ResponseHeader:5,Socks5ResponseIPv4:10,Socks5ResponseIPv6:22,Socks5ResponseHostname:e=>e+7,Socks4Response:8},function(e){e[e.connect=1]="connect",e[e.bind=2]="bind",e[e.associate=3]="associate"}(r||(t.SocksCommand=r={})),function(e){e[e.Granted=90]="Granted",e[e.Failed=91]="Failed",e[e.Rejected=92]="Rejected",e[e.RejectedIdent=93]="RejectedIdent"}(n||(t.Socks4Response=n={})),function(e){e[e.NoAuth=0]="NoAuth",e[e.GSSApi=1]="GSSApi",e[e.UserPass=2]="UserPass"}(i||(t.Socks5Auth=i={}));t.SOCKS5_CUSTOM_AUTH_START=128;t.SOCKS5_CUSTOM_AUTH_END=254;var o,s,a;t.SOCKS5_NO_ACCEPTABLE_AUTH=255,function(e){e[e.Granted=0]="Granted",e[e.Failure=1]="Failure",e[e.NotAllowed=2]="NotAllowed",e[e.NetworkUnreachable=3]="NetworkUnreachable",e[e.HostUnreachable=4]="HostUnreachable",e[e.ConnectionRefused=5]="ConnectionRefused",e[e.TTLExpired=6]="TTLExpired",e[e.CommandNotSupported=7]="CommandNotSupported",e[e.AddressNotSupported=8]="AddressNotSupported"}(o||(t.Socks5Response=o={})),function(e){e[e.IPv4=1]="IPv4",e[e.Hostname=3]="Hostname",e[e.IPv6=4]="IPv6"}(s||(t.Socks5HostType=s={})),function(e){e[e.Created=0]="Created",e[e.Connecting=1]="Connecting",e[e.Connected=2]="Connected",e[e.SentInitialHandshake=3]="SentInitialHandshake",e[e.ReceivedInitialHandshakeResponse=4]="ReceivedInitialHandshakeResponse",e[e.SentAuthentication=5]="SentAuthentication",e[e.ReceivedAuthenticationResponse=6]="ReceivedAuthenticationResponse",e[e.SentFinalHandshake=7]="SentFinalHandshake",e[e.ReceivedFinalResponse=8]="ReceivedFinalResponse",e[e.BoundWaitingForConnection=9]="BoundWaitingForConnection",e[e.Established=10]="Established",e[e.Disconnected=11]="Disconnected",e[e.Error=99]="Error"}(a||(t.SocksClientState=a={}))},5471(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalTrackerSensor=void 0;const n=r(7562),i=r(441);class o extends n.ScryptedDeviceBase{trackingState;plugin;constructor(e,t,r){super(t),this.plugin=e,this.trackingState=r,r.onStateChange(()=>this.updateOccupancy()),this.updateOccupancy()}updateOccupancy(){const e=this.trackingState.getActiveCount();this.occupied=e>0}async getSettings(){const e=this.trackingState.getActiveObjects(),t=this.trackingState.getAllObjects(),r=[];if(r.push({key:"activeCount",title:"Currently Active",type:"string",readonly:!0,value:`${e.length} object${1!==e.length?"s":""}`,group:"Status"}),r.push({key:"totalTracked",title:"Total Tracked (24h)",type:"string",readonly:!0,value:`${t.length} object${1!==t.length?"s":""}`,group:"Status"}),e.length>0){r.push({key:"activeObjectsHeader",title:"Active Objects",type:"html",value:'<h4 style="margin: 0;">Currently Tracked</h4>',group:"Active Objects"});for(const t of e.slice(0,10)){const e=(0,i.calculateDwellTime)(t),n=Math.round(e/6e4);r.push({key:`active-${t.globalId}`,title:`${t.className}${t.label?` (${t.label})`:""}`,type:"string",readonly:!0,value:`Cameras: ${t.activeOnCameras.join(", ")} | Time: ${n}m`,group:"Active Objects"})}e.length>10&&r.push({key:"moreActive",title:"More",type:"string",readonly:!0,value:`...and ${e.length-10} more`,group:"Active Objects"})}const n=t.filter(e=>"exited"===e.state).sort((e,t)=>t.lastSeen-e.lastSeen).slice(0,5);if(n.length>0){r.push({key:"recentExitsHeader",title:"Recent Exits",type:"html",value:'<h4 style="margin: 0;">Recently Exited</h4>',group:"Recent Activity"});for(const e of n){const t=new Date(e.lastSeen).toLocaleTimeString(),n=(0,i.getJourneySummary)(e);r.push({key:`exit-${e.globalId}`,title:`${e.className} at ${t}`,type:"string",readonly:!0,value:n||"No journey recorded",group:"Recent Activity"})}}return r}async putSetting(e,t){}async getReadmeMarkdown(){const e=this.trackingState.getActiveObjects(),t=this.trackingState.getAllObjects(),r=e.filter(e=>"person"===e.className).length,n=e.filter(e=>["car","vehicle","truck"].includes(e.className)).length,i=e.filter(e=>"animal"===e.className).length;let o="";return r>0&&(o+=`- People: ${r}\n`),n>0&&(o+=`- Vehicles: ${n}\n`),i>0&&(o+=`- Animals: ${i}\n`),`\n# Global Object Tracker\n\nThis sensor tracks the presence of objects across all connected cameras in your property.\n\n## Current Status\n\n**Occupied**: ${this.occupied?"Yes":"No"}\n\n**Active Objects**: ${e.length}\n${o||"- None currently"}\n\n**Total Tracked (24h)**: ${t.length}\n\n## How It Works\n\nThe Global Tracker combines detection events from all configured cameras to maintain a unified view of objects on your property. When an object moves from one camera's view to another, the system correlates these sightings to track the object's journey.\n\n## States\n\n- **Active**: Object is currently visible on camera\n- **Pending**: Object left camera view, waiting for correlation\n- **Exited**: Object left the property\n- **Lost**: Object disappeared without exiting (timeout)\n\n## Integration\n\nThis sensor can be used in automations:\n- Trigger actions when property becomes occupied/unoccupied\n- Create presence-based automations\n- Monitor overall property activity\n`}}t.GlobalTrackerSensor=o},5506(e,t,r){"use strict";const{Buffer:n}=r(181),{ObjectDefineProperty:i,ObjectKeys:o,ReflectApply:s}=r(4134),{promisify:{custom:a}}=r(7760),{streamReturningOperators:c,promiseReturningOperators:l}=r(823),{codes:{ERR_ILLEGAL_CONSTRUCTOR:u}}=r(6371),d=r(7830),{setDefaultHighWaterMark:h,getDefaultHighWaterMark:p}=r(5291),{pipeline:f}=r(7758),{destroyer:g}=r(5896),m=r(6238),b=r(3095),y=r(6115),_=e.exports=r(4259).Stream;_.isDestroyed=y.isDestroyed,_.isDisturbed=y.isDisturbed,_.isErrored=y.isErrored,_.isReadable=y.isReadable,_.isWritable=y.isWritable,_.Readable=r(7576);for(const S of o(c)){const w=c[S];function k(...e){if(new.target)throw u();return _.Readable.from(s(w,this,e))}i(k,"name",{__proto__:null,value:w.name}),i(k,"length",{__proto__:null,value:w.length}),i(_.Readable.prototype,S,{__proto__:null,value:k,enumerable:!1,configurable:!0,writable:!0})}for(const E of o(l)){const I=l[E];function T(...e){if(new.target)throw u();return s(I,this,e)}i(T,"name",{__proto__:null,value:I.name}),i(T,"length",{__proto__:null,value:I.length}),i(_.Readable.prototype,E,{__proto__:null,value:T,enumerable:!1,configurable:!0,writable:!0})}_.Writable=r(8584),_.Duplex=r(3370),_.Transform=r(7382),_.PassThrough=r(6524),_.pipeline=f;const{addAbortSignal:v}=r(4147);_.addAbortSignal=v,_.finished=m,_.destroy=g,_.compose=d,_.setDefaultHighWaterMark=h,_.getDefaultHighWaterMark=p,i(_,"promises",{__proto__:null,configurable:!0,enumerable:!0,get:()=>b}),i(f,a,{__proto__:null,enumerable:!0,get:()=>b.pipeline}),i(m,a,{__proto__:null,enumerable:!0,get:()=>b.finished}),_.Stream=_,_._isUint8Array=function(e){return e instanceof Uint8Array},_._uint8ArrayToBuffer=function(e){return n.from(e.buffer,e.byteOffset,e.byteLength)}},5670(e,t,r){"use strict";const n=r(181),i=r(4478),o=r(2635);let s,a,c;t.A=(e,t)=>{if(t.hostname=t.hostname||t.host,!t.hostname)throw new Error("Could not determine host. Specify host manually.");const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt";!function(e){e.hostname||(e.hostname="localhost"),e.path||(e.path="/"),e.wsOptions||(e.wsOptions={})}(t);const l=function(e,t){const r="wxs"===e.protocol?"wss":"ws";let n=`${r}://${e.hostname}${e.path}`;return e.port&&80!==e.port&&443!==e.port&&(n=`${r}://${e.hostname}:${e.port}${e.path}`),"function"==typeof e.transformWsUrl&&(n=e.transformWsUrl(n,e,t)),n}(t,e);s=wx.connectSocket({url:l,protocols:[r]}),a=function(){const e=new i.Transform;return e._write=(e,t,r)=>{s.send({data:e.buffer,success(){r()},fail(e){r(new Error(e))}})},e._flush=e=>{s.close({success(){e()}})},e}(),c=new o.BufferedDuplex(t,a,s),c._destroy=(e,t)=>{s.close({success(){t&&t(e)}})};const u=c.destroy;return c.destroy=(e,t)=>(c.destroy=u,setTimeout(()=>{s.close({fail(){c._destroy(e,t)}})},0),c),s.onOpen(()=>{c.socketReady()}),s.onMessage(e=>{let{data:t}=e;t=t instanceof ArrayBuffer?n.Buffer.from(t):n.Buffer.from(t,"utf8"),a.push(t)}),s.onClose(()=>{c.emit("close"),c.end(),c.destroy()}),s.onError(e=>{const t=new Error(e.errMsg);c.destroy(t)}),c}},5692(e){"use strict";e.exports=require("https")},5753(e,t,r){"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?e.exports=r(7833):e.exports=r(6033)},5861(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(7631),t)},5880(e,t,r){"use strict";const{isUtf8:n}=r(181),{hasBlob:i}=r(2614);function o(e){const t=e.length;let r=0;for(;r<t;)if(128&e[r])if(192==(224&e[r])){if(r+1===t||128!=(192&e[r+1])||192==(254&e[r]))return!1;r+=2}else if(224==(240&e[r])){if(r+2>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||224===e[r]&&128==(224&e[r+1])||237===e[r]&&160==(224&e[r+1]))return!1;r+=3}else{if(240!=(248&e[r]))return!1;if(r+3>=t||128!=(192&e[r+1])||128!=(192&e[r+2])||128!=(192&e[r+3])||240===e[r]&&128==(240&e[r+1])||244===e[r]&&e[r+1]>143||e[r]>244)return!1;r+=4}else r++;return!0}if(e.exports={isBlob:function(e){return i&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:o,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},n)e.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const t=r(Object(function(){var e=new Error("Cannot find module 'utf-8-validate'");throw e.code="MODULE_NOT_FOUND",e}()));e.exports.isValidUTF8=function(e){return e.length<32?o(e):t(e)}}catch(e){}},5884(e){"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),i=t.indexOf("--");return-1!==n&&(-1===i||n<i)}},5896(e,t,r){"use strict";const n=r(4422),{aggregateTwoErrors:i,codes:{ERR_MULTIPLE_CALLBACK:o},AbortError:s}=r(6371),{Symbol:a}=r(4134),{kIsDestroyed:c,isDestroyed:l,isFinished:u,isServerRequest:d}=r(6115),h=a("kDestroy"),p=a("kConstruct");function f(e,t,r){e&&(e.stack,t&&!t.errored&&(t.errored=e),r&&!r.errored&&(r.errored=e))}function g(e,t,r){let i=!1;function o(t){if(i)return;i=!0;const o=e._readableState,s=e._writableState;f(t,s,o),s&&(s.closed=!0),o&&(o.closed=!0),"function"==typeof r&&r(t),t?n.nextTick(m,e,t):n.nextTick(b,e)}try{e._destroy(t||null,o)}catch(t){o(t)}}function m(e,t){y(e,t),b(e)}function b(e){const t=e._readableState,r=e._writableState;r&&(r.closeEmitted=!0),t&&(t.closeEmitted=!0),(null!=r&&r.emitClose||null!=t&&t.emitClose)&&e.emit("close")}function y(e,t){const r=e._readableState,n=e._writableState;null!=n&&n.errorEmitted||null!=r&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),e.emit("error",t))}function _(e,t,r){const i=e._readableState,o=e._writableState;if(null!=o&&o.destroyed||null!=i&&i.destroyed)return this;null!=i&&i.autoDestroy||null!=o&&o.autoDestroy?e.destroy(t):t&&(t.stack,o&&!o.errored&&(o.errored=t),i&&!i.errored&&(i.errored=t),r?n.nextTick(y,e,t):y(e,t))}function v(e){let t=!1;function r(r){if(t)return void _(e,null!=r?r:new o);t=!0;const i=e._readableState,s=e._writableState,a=s||i;i&&(i.constructed=!0),s&&(s.constructed=!0),a.destroyed?e.emit(h,r):r?_(e,r,!0):n.nextTick(S,e)}try{e._construct(e=>{n.nextTick(r,e)})}catch(e){n.nextTick(r,e)}}function S(e){e.emit(p)}function w(e){return(null==e?void 0:e.setHeader)&&"function"==typeof e.abort}function k(e){e.emit("close")}function E(e,t){e.emit("error",t),n.nextTick(k,e)}e.exports={construct:function(e,t){if("function"!=typeof e._construct)return;const r=e._readableState,i=e._writableState;r&&(r.constructed=!1),i&&(i.constructed=!1),e.once(p,t),e.listenerCount(p)>1||n.nextTick(v,e)},destroyer:function(e,t){e&&!l(e)&&(t||u(e)||(t=new s),d(e)?(e.socket=null,e.destroy(t)):w(e)?e.abort():w(e.req)?e.req.abort():"function"==typeof e.destroy?e.destroy(t):"function"==typeof e.close?e.close():t?n.nextTick(E,e,t):n.nextTick(k,e),e.destroyed||(e[c]=!0))},destroy:function(e,t){const r=this._readableState,n=this._writableState,o=n||r;return null!=n&&n.destroyed||null!=r&&r.destroyed?("function"==typeof t&&t(),this):(f(e,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),o.constructed?g(this,e,t):this.once(h,function(r){g(this,i(r,e),t)}),this)},undestroy:function(){const e=this._readableState,t=this._writableState;e&&(e.constructed=!0,e.closed=!1,e.closeEmitted=!1,e.destroyed=!1,e.errored=null,e.errorEmitted=!1,e.reading=!1,e.ended=!1===e.readable,e.endEmitted=!1===e.readable),t&&(t.constructed=!0,t.destroyed=!1,t.closed=!1,t.closeEmitted=!1,t.errored=null,t.errorEmitted=!1,t.finalCalled=!1,t.prefinished=!1,t.ended=!1===t.writable,t.ending=!1===t.writable,t.finished=!1===t.writable)},errorOrDestroy:_}},5926(e,t,r){"use strict";const{tokenChars:n}=r(5880);function i(e,t,r){void 0===e[t]?e[t]=[r]:e[t].push(r)}e.exports={format:function(e){return Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>[t].concat(Object.keys(e).map(t=>{let r=e[t];return Array.isArray(r)||(r=[r]),r.map(e=>!0===e?t:`${t}=${e}`).join("; ")})).join("; ")).join(", ")}).join(", ")},parse:function(e){const t=Object.create(null);let r,o,s=Object.create(null),a=!1,c=!1,l=!1,u=-1,d=-1,h=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),void 0===r)if(-1===h&&1===n[d])-1===u&&(u=p);else if(0===p||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${p}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);const n=e.slice(u,h);44===d?(i(t,n,s),s=Object.create(null)):r=n,u=h=-1}}else-1===h&&-1!==u&&(h=p);else if(void 0===o)if(-1===h&&1===n[d])-1===u&&(u=p);else if(32===d||9===d)-1===h&&-1!==u&&(h=p);else if(59===d||44===d){if(-1===u)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p),i(s,e.slice(u,h),!0),44===d&&(i(t,r,s),s=Object.create(null),r=void 0),u=h=-1}else{if(61!==d||-1===u||-1!==h)throw new SyntaxError(`Unexpected character at index ${p}`);o=e.slice(u,p),u=h=-1}else if(c){if(1!==n[d])throw new SyntaxError(`Unexpected character at index ${p}`);-1===u?u=p:a||(a=!0),c=!1}else if(l)if(1===n[d])-1===u&&(u=p);else if(34===d&&-1!==u)l=!1,h=p;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${p}`);c=!0}else if(34===d&&61===e.charCodeAt(p-1))l=!0;else if(-1===h&&1===n[d])-1===u&&(u=p);else if(-1===u||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${p}`);{if(-1===u)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);let n=e.slice(u,h);a&&(n=n.replace(/\\/g,""),a=!1),i(s,o,n),44===d&&(i(t,r,s),s=Object.create(null),r=void 0),o=void 0,u=h=-1}}else-1===h&&(h=p);if(-1===u||l||32===d||9===d)throw new SyntaxError("Unexpected end of input");-1===h&&(h=p);const f=e.slice(u,h);return void 0===r?i(t,f,s):(void 0===o?i(s,f,!0):i(s,o,a?f.replace(/\\/g,""):f),i(t,r,s)),t}}},6033(e,t,r){const n=r(2018),i=r(9023);t.init=function(e){e.inspectOpts={};const r=Object.keys(t.inspectOpts);for(let n=0;n<r.length;n++)e.inspectOpts[r[n]]=t.inspectOpts[r[n]]},t.log=function(...e){return process.stderr.write(i.formatWithOptions(t.inspectOpts,...e)+"\n")},t.formatArgs=function(r){const{namespace:n,useColors:i}=this;if(i){const t=this.color,i="[3"+(t<8?t:"8;5;"+t),o=` ${i};1m${n} [0m`;r[0]=o+r[0].split("\n").join("\n"+o),r.push(i+"m+"+e.exports.humanize(this.diff)+"[0m")}else r[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+n+" "+r[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):n.isatty(process.stderr.fd)},t.destroy=i.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=r(7687);e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[r]=n,e},{}),e.exports=r(736)(t);const{formatters:o}=e.exports;o.o=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},o.O=function(e){return this.inspectOpts.colors=this.useColors,i.inspect(e,this.inspectOpts)}},6115(e,t,r){"use strict";const{SymbolAsyncIterator:n,SymbolIterator:i,SymbolFor:o}=r(4134),s=o("nodejs.stream.destroyed"),a=o("nodejs.stream.errored"),c=o("nodejs.stream.readable"),l=o("nodejs.stream.writable"),u=o("nodejs.stream.disturbed"),d=o("nodejs.webstream.isClosedPromise"),h=o("nodejs.webstream.controllerErrorFunction");function p(e,t=!1){var r;return!(!e||"function"!=typeof e.pipe||"function"!=typeof e.on||t&&("function"!=typeof e.pause||"function"!=typeof e.resume)||e._writableState&&!1===(null===(r=e._readableState)||void 0===r?void 0:r.readable)||e._writableState&&!e._readableState)}function f(e){var t;return!(!e||"function"!=typeof e.write||"function"!=typeof e.on||e._readableState&&!1===(null===(t=e._writableState)||void 0===t?void 0:t.writable))}function g(e){return e&&(e._readableState||e._writableState||"function"==typeof e.write&&"function"==typeof e.on||"function"==typeof e.pipe&&"function"==typeof e.on)}function m(e){return!(!e||g(e)||"function"!=typeof e.pipeThrough||"function"!=typeof e.getReader||"function"!=typeof e.cancel)}function b(e){return!(!e||g(e)||"function"!=typeof e.getWriter||"function"!=typeof e.abort)}function y(e){return!(!e||g(e)||"object"!=typeof e.readable||"object"!=typeof e.writable)}function _(e){if(!g(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!!(e.destroyed||e[s]||null!=n&&n.destroyed)}function v(e){if(!f(e))return null;if(!0===e.writableEnded)return!0;const t=e._writableState;return(null==t||!t.errored)&&("boolean"!=typeof(null==t?void 0:t.ended)?null:t.ended)}function S(e,t){if(!p(e))return null;const r=e._readableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.endEmitted)?null:!!(r.endEmitted||!1===t&&!0===r.ended&&0===r.length))}function w(e){return e&&null!=e[c]?e[c]:"boolean"!=typeof(null==e?void 0:e.readable)?null:!_(e)&&(p(e)&&e.readable&&!S(e))}function k(e){return e&&null!=e[l]?e[l]:"boolean"!=typeof(null==e?void 0:e.writable)?null:!_(e)&&(f(e)&&e.writable&&!v(e))}function E(e){return"boolean"==typeof e._closed&&"boolean"==typeof e._defaultKeepAlive&&"boolean"==typeof e._removedConnection&&"boolean"==typeof e._removedContLen}function I(e){return"boolean"==typeof e._sent100&&E(e)}e.exports={isDestroyed:_,kIsDestroyed:s,isDisturbed:function(e){var t;return!(!e||!(null!==(t=e[u])&&void 0!==t?t:e.readableDidRead||e.readableAborted))},kIsDisturbed:u,isErrored:function(e){var t,r,n,i,o,s,c,l,u,d;return!(!e||!(null!==(t=null!==(r=null!==(n=null!==(i=null!==(o=null!==(s=e[a])&&void 0!==s?s:e.readableErrored)&&void 0!==o?o:e.writableErrored)&&void 0!==i?i:null===(c=e._readableState)||void 0===c?void 0:c.errorEmitted)&&void 0!==n?n:null===(l=e._writableState)||void 0===l?void 0:l.errorEmitted)&&void 0!==r?r:null===(u=e._readableState)||void 0===u?void 0:u.errored)&&void 0!==t?t:null===(d=e._writableState)||void 0===d?void 0:d.errored))},kIsErrored:a,isReadable:w,kIsReadable:c,kIsClosedPromise:d,kControllerErrorFunction:h,kIsWritable:l,isClosed:function(e){if(!g(e))return null;if("boolean"==typeof e.closed)return e.closed;const t=e._writableState,r=e._readableState;return"boolean"==typeof(null==t?void 0:t.closed)||"boolean"==typeof(null==r?void 0:r.closed)?(null==t?void 0:t.closed)||(null==r?void 0:r.closed):"boolean"==typeof e._closed&&E(e)?e._closed:null},isDuplexNodeStream:function(e){return!(!e||"function"!=typeof e.pipe||!e._readableState||"function"!=typeof e.on||"function"!=typeof e.write)},isFinished:function(e,t){return g(e)?!!_(e)||(!1===(null==t?void 0:t.readable)||!w(e))&&(!1===(null==t?void 0:t.writable)||!k(e)):null},isIterable:function(e,t){return null!=e&&(!0===t?"function"==typeof e[n]:!1===t?"function"==typeof e[i]:"function"==typeof e[n]||"function"==typeof e[i])},isReadableNodeStream:p,isReadableStream:m,isReadableEnded:function(e){if(!p(e))return null;if(!0===e.readableEnded)return!0;const t=e._readableState;return!(!t||t.errored)&&("boolean"!=typeof(null==t?void 0:t.ended)?null:t.ended)},isReadableFinished:S,isReadableErrored:function(e){var t,r;return g(e)?e.readableErrored?e.readableErrored:null!==(t=null===(r=e._readableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isNodeStream:g,isWebStream:function(e){return m(e)||b(e)||y(e)},isWritable:k,isWritableNodeStream:f,isWritableStream:b,isWritableEnded:v,isWritableFinished:function(e,t){if(!f(e))return null;if(!0===e.writableFinished)return!0;const r=e._writableState;return(null==r||!r.errored)&&("boolean"!=typeof(null==r?void 0:r.finished)?null:!!(r.finished||!1===t&&!0===r.ended&&0===r.length))},isWritableErrored:function(e){var t,r;return g(e)?e.writableErrored?e.writableErrored:null!==(t=null===(r=e._writableState)||void 0===r?void 0:r.errored)&&void 0!==t?t:null:null},isServerRequest:function(e){var t;return"boolean"==typeof e._consuming&&"boolean"==typeof e._dumped&&void 0===(null===(t=e.req)||void 0===t?void 0:t.upgradeOrConnect)},isServerResponse:I,willEmitClose:function(e){if(!g(e))return null;const t=e._writableState,r=e._readableState,n=t||r;return!n&&I(e)||!!(n&&n.autoDestroy&&n.emitClose&&!1===n.closed)},isTransformStream:y}},6117(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.StorageSettings=void 0;const a=s(r(7562)),{systemManager:c}=a.default;t.StorageSettings=class{constructor(e,t){this.device=e,this.settings=t,this.values={},this.hasValue={};for(const e of Object.keys(t)){const r=t[e],n=()=>this.getItem(e);let i;i="clippath"!==r.type?n:()=>{try{return JSON.parse(n())}catch(e){}},Object.defineProperty(this.values,e,{get:i,set:t=>this.putSetting(e,t),enumerable:!0}),Object.defineProperty(this.hasValue,e,{get:()=>null!=this.device.storage.getItem(e),enumerable:!0})}}get keys(){const e={};for(const t of Object.keys(this.settings))e[t]=t;return e}async getSettings(){const e=await(this.options?.onGet?.()),t=[];for(const[r,n]of Object.entries(this.settings)){let i=Object.assign({},n);e?.[r]&&(i=Object.assign(i,e[r])),i.onGet&&(i=Object.assign(i,await i.onGet())),i.hide||await(this.options?.hide?.[r]?.())||(i.key=r,i.value=this.getItemInternal(r,i,!0),"function"==typeof i.deviceFilter&&(i.deviceFilter=i.deviceFilter.toString()),t.push(i),delete i.onPut,delete i.onGet,delete i.mapPut,delete i.mapGet)}return t}async putSetting(e,t){const r=this.settings[e];let n;return r&&(n=this.getItemInternal(e,r)),this.putSettingInternal(r,n,e,t)}putSettingInternal(e,t,r,n){e?.noStore||(e?.mapPut&&(n=e.mapPut(t,n)),null==n?this.device.storage.removeItem(r):"object"==typeof n?this.device.storage.setItem(r,JSON.stringify(n)):this.device.storage.setItem(r,n?.toString())),e?.onPut?.(t,n),e?.hide||this.device.onDeviceEvent(a.ScryptedInterface.Settings,void 0)}getItemInternal(e,t,r){if(!t)return this.device.storage.getItem(e);const n=function(e,t,r,n){if(null==e)return r();const i=t.multiple?"array":t.type;if("boolean"===i)return"true"===e||"false"!==e&&(r()||!1);if("number"===i){const t=parseFloat(e);return isNaN(t)?r()||0:t}if("integer"===i){const t=parseInt(e);return isNaN(t)?r()||0:t}if("array"===i){if(!e)return r()||[];try{return JSON.parse(e)}catch(e){return r()||[]}}if("device"===i)return n?e:c.getDeviceById(e)||c.getDeviceById(r());if(e&&t.json)try{return JSON.parse(e)}catch(e){return r()}return e||r()}(this.device.storage.getItem(e),t,()=>null!=t.persistedDefaultValue?(this.putSettingInternal(t,void 0,e,t.persistedDefaultValue),t.persistedDefaultValue):t.defaultValue,r);return t.mapGet?t.mapGet(n):n}getItem(e){return this.getItemInternal(e,this.settings[e])}}},6172(e,t,r){const{Buffer:n}=r(181),i={},o=n.isBuffer(n.from([1,2]).subarray(0,1));function s(e){const t=n.allocUnsafe(2);return t.writeUInt8(e>>8,0),t.writeUInt8(255&e,1),t}e.exports={cache:i,generateCache:function(){for(let e=0;e<65536;e++)i[e]=s(e)},generateNumber:s,genBufVariableByteInt:function(e){let t=0,r=0;const i=n.allocUnsafe(4);do{t=e%128|0,(e=e/128|0)>0&&(t|=128),i.writeUInt8(t,r++)}while(e>0&&r<4);return e>0&&(r=0),o?i.subarray(0,r):i.slice(0,r)},generate4ByteBuffer:function(e){const t=n.allocUnsafe(4);return t.writeUInt32BE(e,0),t}}},6238(e,t,r){"use strict";const n=r(4422),{AbortError:i,codes:o}=r(6371),{ERR_INVALID_ARG_TYPE:s,ERR_STREAM_PREMATURE_CLOSE:a}=o,{kEmptyObject:c,once:l}=r(7760),{validateAbortSignal:u,validateFunction:d,validateObject:h,validateBoolean:p}=r(277),{Promise:f,PromisePrototypeThen:g,SymbolDispose:m}=r(4134),{isClosed:b,isReadable:y,isReadableNodeStream:_,isReadableStream:v,isReadableFinished:S,isReadableErrored:w,isWritable:k,isWritableNodeStream:E,isWritableStream:I,isWritableFinished:T,isWritableErrored:O,isNodeStream:C,willEmitClose:x,kIsClosedPromise:A}=r(6115);let P;const R=()=>{};function M(e,t,o){var p,f;if(2===arguments.length?(o=t,t=c):null==t?t=c:h(t,"options"),d(o,"callback"),u(t.signal,"options.signal"),o=l(o),v(e)||I(e))return function(e,t,o){let s=!1,a=R;if(t.signal)if(a=()=>{s=!0,o.call(e,new i(void 0,{cause:t.signal.reason}))},t.signal.aborted)n.nextTick(a);else{P=P||r(7760).addAbortListener;const n=P(t.signal,a),i=o;o=l((...t)=>{n[m](),i.apply(e,t)})}const c=(...t)=>{s||n.nextTick(()=>o.apply(e,t))};return g(e[A].promise,c,c),R}(e,t,o);if(!C(e))throw new s("stream",["ReadableStream","WritableStream","Stream"],e);const M=null!==(p=t.readable)&&void 0!==p?p:_(e),B=null!==(f=t.writable)&&void 0!==f?f:E(e),N=e._writableState,j=e._readableState,D=()=>{e.writable||F()};let L=x(e)&&_(e)===M&&E(e)===B,U=T(e,!1);const F=()=>{U=!0,e.destroyed&&(L=!1),(!L||e.readable&&!M)&&(M&&!$||o.call(e))};let $=S(e,!1);const V=()=>{$=!0,e.destroyed&&(L=!1),(!L||e.writable&&!B)&&(B&&!U||o.call(e))},W=t=>{o.call(e,t)};let H=b(e);const z=()=>{H=!0;const t=O(e)||w(e);return t&&"boolean"!=typeof t?o.call(e,t):M&&!$&&_(e,!0)&&!S(e,!1)?o.call(e,new a):!B||U||T(e,!1)?void o.call(e):o.call(e,new a)},q=()=>{H=!0;const t=O(e)||w(e);if(t&&"boolean"!=typeof t)return o.call(e,t);o.call(e)},G=()=>{e.req.on("finish",F)};!function(e){return e.setHeader&&"function"==typeof e.abort}(e)?B&&!N&&(e.on("end",D),e.on("close",D)):(e.on("complete",F),L||e.on("abort",z),e.req?G():e.on("request",G)),L||"boolean"!=typeof e.aborted||e.on("aborted",z),e.on("end",V),e.on("finish",F),!1!==t.error&&e.on("error",W),e.on("close",z),H?n.nextTick(z):null!=N&&N.errorEmitted||null!=j&&j.errorEmitted?L||n.nextTick(q):(M||L&&!y(e)||!U&&!1!==k(e))&&(B||L&&!k(e)||!$&&!1!==y(e))?j&&e.req&&e.aborted&&n.nextTick(q):n.nextTick(q);const K=()=>{o=R,e.removeListener("aborted",z),e.removeListener("complete",F),e.removeListener("abort",z),e.removeListener("request",G),e.req&&e.req.removeListener("finish",F),e.removeListener("end",D),e.removeListener("close",D),e.removeListener("finish",F),e.removeListener("end",V),e.removeListener("error",W),e.removeListener("close",z)};if(t.signal&&!H){const s=()=>{const r=o;K(),r.call(e,new i(void 0,{cause:t.signal.reason}))};if(t.signal.aborted)n.nextTick(s);else{P=P||r(7760).addAbortListener;const n=P(t.signal,s),i=o;o=l((...t)=>{n[m](),i.apply(e,t)})}}return K}e.exports=M,e.exports.finished=function(e,t){var r;let n=!1;return null===t&&(t=c),null!==(r=t)&&void 0!==r&&r.cleanup&&(p(t.cleanup,"cleanup"),n=t.cleanup),new f((r,i)=>{const o=M(e,t,e=>{n&&o(),e?i(e):r()})})}},6286(e,t,r){"use strict";const{Writable:n}=r(2203),i=r(2971),{BINARY_TYPES:o,EMPTY_BUFFER:s,kStatusCode:a,kWebSocket:c}=r(2614),{concat:l,toArrayBuffer:u,unmask:d}=r(3338),{isValidStatusCode:h,isValidUTF8:p}=r(5880),f=Buffer[Symbol.species];e.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||o[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[c]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,r){if(8===this._opcode&&0==this._state)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=new f(t.buffer,t.byteOffset+e,t.length-e),new f(t.buffer,t.byteOffset,e)}const t=Buffer.allocUnsafe(e);do{const r=this._buffers[0],n=t.length-e;e>=r.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),n),this._buffers[0]=new f(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const r=!(64&~t[0]);if(r&&!this._extensions[i.extensionName]){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=r}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(r){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){return void e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}this._payloadLength=r*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){return void e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=s;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!==(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&d(t,this._mask)}if(this._opcode>7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[i.extensionName].decompress(e,this._fin,(e,r)=>{if(e)return t(e);if(r.length){if(this._messageLength+=r.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(r)}this.dataMessage(t),0===this._state&&this.startLoop(t)})}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let n;n="nodebuffer"===this._binaryType?l(r,t):"arraybuffer"===this._binaryType?u(l(r,t)):"blob"===this._binaryType?new Blob(r):r,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!0),this._state=0,this.startLoop(e)}))}else{const n=l(r,t);if(!this._skipUTF8Validation&&!p(n)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit("message",n,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)}));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,s),this.end();else{const r=e.readUInt16BE(0);if(!h(r)){const e=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const n=new f(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!p(n)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",r,n),this.end()}this._state=0}}createError(e,t,r,n,i){this._loop=!1,this._errored=!0;const o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[a]=n,o}}},6329(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Address6=void 0;const s=o(r(837)),a=o(r(9576)),c=o(r(8914)),l=o(r(465)),u=r(2839),d=r(321),h=r(2437),p=r(837);function f(e){if(!e)throw new Error("Assertion failed.")}function g(e){return e=(e=e.replace(/^(0{1,})([1-9]+)$/,'<span class="parse-error">$1</span>$2')).replace(/^(0{1,})(0)$/,'<span class="parse-error">$1</span>$2')}function m(e){return parseInt(e,16).toString(16).padStart(4,"0")}function b(e){return 255&e}class y{constructor(e,t){this.addressMinusSuffix="",this.parsedSubnet="",this.subnet="/128",this.subnetMask=128,this.v4=!1,this.zone="",this.isInSubnet=s.isInSubnet,this.isCorrect=s.isCorrect(c.BITS),this.groups=void 0===t?c.GROUPS:t,this.address=e;const r=c.RE_SUBNET_STRING.exec(e);if(r){if(this.parsedSubnet=r[0].replace("/",""),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>c.BITS)throw new h.AddressError("Invalid subnet mask.");e=e.replace(c.RE_SUBNET_STRING,"")}else if(/\//.test(e))throw new h.AddressError("Invalid subnet mask.");const n=c.RE_ZONE_STRING.exec(e);n&&(this.zone=n[0],e=e.replace(c.RE_ZONE_STRING,"")),this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(e){try{return new y(e),!0}catch(e){return!1}}static fromBigInt(e){const t=e.toString(16).padStart(32,"0"),r=[];let n;for(n=0;n<c.GROUPS;n++)r.push(t.slice(4*n,4*(n+1)));return new y(r.join(":"))}static fromURL(e){let t,r,n=null;if(-1!==e.indexOf("[")&&-1!==e.indexOf("]:")){if(r=c.RE_URL_WITH_PORT.exec(e),null===r)return{error:"failed to parse address with port",address:null,port:null};t=r[1],n=r[2]}else if(-1!==e.indexOf("/")){if(e=e.replace(/^[a-z0-9]+:\/\//,""),r=c.RE_URL.exec(e),null===r)return{error:"failed to parse address from URL",address:null,port:null};t=r[1]}else t=e;return n?(n=parseInt(n,10),(n<0||n>65536)&&(n=null)):n=null,{address:new y(t),port:n}}static fromAddress4(e){const t=new u.Address4(e),r=c.BITS-(a.BITS-t.subnetMask);return new y(`::ffff:${t.correctForm()}/${r}`)}static fromArpa(e){let t=e.replace(/(\.ip6\.arpa)?\.$/,"");if(63!==t.length)throw new h.AddressError("Invalid 'ip6.arpa' form.");const r=t.split(".").reverse();for(let e=7;e>0;e--){const t=4*e;r.splice(t,0,":")}return t=r.join(""),new y(t)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,"-")}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){const t=c.BITS-this.subnetMask-Math.abs(e-c.BITS);return t<0?"0":function(e){const t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,"$1,$2");return e}((BigInt("2")**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+"0".repeat(c.BITS-this.subnetMask)}`)}startAddress(){return y.fromBigInt(this._startAddress())}startAddressExclusive(){const e=BigInt("1");return y.fromBigInt(this._startAddress()+e)}_endAddress(){return BigInt(`0b${this.mask()+"1".repeat(c.BITS-this.subnetMask)}`)}endAddress(){return y.fromBigInt(this._endAddress())}endAddressExclusive(){const e=BigInt("1");return y.fromBigInt(this._endAddress()-e)}getScope(){let e=c.SCOPES[parseInt(this.getBits(12,16).toString(10),10)];return"Global unicast"===this.getType()&&"Link local"!==e&&(e="Global"),e||"Unknown"}getType(){for(const e of Object.keys(c.TYPES))if(this.isInSubnet(new y(e)))return c.TYPES[e];return"Global unicast"}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){const r=t-e;if(r%4!=0)throw new Error("Length of bits to retrieve must be divisible by four");return this.getBits(e,t).toString(16).padStart(r/4,"0")}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,c.BITS)}reverseForm(e){e||(e={});const t=Math.floor(this.subnetMask/4),r=this.canonicalForm().replace(/:/g,"").split("").slice(0,t).reverse().join(".");return t>0?e.omitSuffix?r:`${r}.ip6.arpa.`:e.omitSuffix?"":"ip6.arpa."}correctForm(){let e,t=[],r=0;const n=[];for(e=0;e<this.parsedAddress.length;e++){const t=parseInt(this.parsedAddress[e],16);0===t&&r++,0!==t&&r>0&&(r>1&&n.push([e-r,e-1]),r=0)}r>1&&n.push([this.parsedAddress.length-r,this.parsedAddress.length-1]);const i=n.map(e=>e[1]-e[0]+1);if(n.length>0){const e=i.indexOf(Math.max(...i));t=function(e,t){const r=[],n=[];let i;for(i=0;i<e.length;i++)i<t[0]?r.push(e[i]):i>t[1]&&n.push(e[i]);return r.concat(["compact"]).concat(n)}(this.parsedAddress,n[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)"compact"!==t[e]&&(t[e]=parseInt(t[e],16).toString(16));let o=t.join(":");return o=o.replace(/^compact$/,"::"),o=o.replace(/(^compact)|(compact$)/,":"),o=o.replace(/compact/,""),o}binaryZeroPad(){return this.bigInt().toString(2).padStart(c.BITS,"0")}parse4in6(e){const t=e.split(":"),r=t.slice(-1)[0].match(a.RE_ADDRESS);if(r){this.parsedAddress4=r[0],this.address4=new u.Address4(this.parsedAddress4);for(let t=0;t<this.address4.groups;t++)if(/^0[0-9]+/.test(this.address4.parsedAddress[t]))throw new h.AddressError("IPv4 addresses can't have leading zeroes.",e.replace(a.RE_ADDRESS,this.address4.parsedAddress.map(g).join(".")));this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(":")}return e}parse(e){const t=(e=this.parse4in6(e)).match(c.RE_BAD_CHARACTERS);if(t)throw new h.AddressError(`Bad character${t.length>1?"s":""} detected in address: ${t.join("")}`,e.replace(c.RE_BAD_CHARACTERS,'<span class="parse-error">$1</span>'));const r=e.match(c.RE_BAD_ADDRESS);if(r)throw new h.AddressError(`Address failed regex: ${r.join("")}`,e.replace(c.RE_BAD_ADDRESS,'<span class="parse-error">$1</span>'));let n=[];const i=e.split("::");if(2===i.length){let e=i[0].split(":"),t=i[1].split(":");1===e.length&&""===e[0]&&(e=[]),1===t.length&&""===t[0]&&(t=[]);const r=this.groups-(e.length+t.length);if(!r)throw new h.AddressError("Error parsing groups");this.elidedGroups=r,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,n=n.concat(e);for(let e=0;e<r;e++)n.push("0");n=n.concat(t)}else{if(1!==i.length)throw new h.AddressError("Too many :: groups found");n=e.split(":"),this.elidedGroups=0}if(n=n.map(e=>parseInt(e,16).toString(16)),n.length!==this.groups)throw new h.AddressError("Incorrect number of groups found");return n}canonicalForm(){return this.parsedAddress.map(m).join(":")}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,"0")).join(":")}bigInt(){return BigInt(`0x${this.parsedAddress.map(m).join("")}`)}to4(){const e=this.binaryZeroPad().split("");return u.Address4.fromHex(BigInt(`0b${e.slice(96,128).join("")}`).toString(16))}to4in6(){const e=this.to4(),t=new y(this.parsedAddress.slice(0,6).join(":"),6).correctForm();let r="";return/:$/.test(t)||(r=":"),t+r+e.address}inspectTeredo(){const e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt("0xffff")).toString(),r=u.Address4.fromHex(this.getBitsBase16(32,64)),n=this.getBits(96,128),i=u.Address4.fromHex((n^BigInt("0xffffffff")).toString(16)),o=this.getBitsBase2(64,80),s=(0,p.testBit)(o,15),a=(0,p.testBit)(o,14),c=(0,p.testBit)(o,8),l=(0,p.testBit)(o,9),d=BigInt(`0b${o.slice(2,6)+o.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:r.address,client4:i.address,flags:o,coneNat:s,microsoft:{reserved:a,universalLocal:l,groupIndividual:c,nonce:d},udpPort:t}}inspect6to4(){const e=this.getBitsBase16(0,16),t=u.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;const e=["2002",this.getBitsBase16(96,112),this.getBitsBase16(112,128),"","/16"].join(":");return new y(e)}toByteArray(){const e=this.bigInt().toString(16),t=`${"0".repeat(e.length%2)}${e}`,r=[];for(let e=0,n=t.length;e<n;e+=2)r.push(parseInt(t.substring(e,e+2),16));return r}toUnsignedByteArray(){return this.toByteArray().map(b)}static fromByteArray(e){return this.fromUnsignedByteArray(e.map(b))}static fromUnsignedByteArray(e){const t=BigInt("256");let r=BigInt("0"),n=BigInt("1");for(let i=e.length-1;i>=0;i--)r+=n*BigInt(e[i].toString(10)),n*=t;return y.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){return"1111111010000000000000000000000000000000000000000000000000000000"===this.getBitsBase2(0,64)}isMulticast(){return"Multicast"===this.getType()}is4(){return this.v4}isTeredo(){return this.isInSubnet(new y("2001::/32"))}is6to4(){return this.isInSubnet(new y("2002::/16"))}isLoopback(){return"Loopback"===this.getType()}href(e){return e=void 0===e?"":`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||(e={}),void 0===e.className&&(e.className=""),void 0===e.prefix&&(e.prefix="/#address="),void 0===e.v4&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);const r=t.call(this);return e.className?`<a href="${e.prefix}${r}" class="${e.className}">${r}</a>`:`<a href="${e.prefix}${r}">${r}</a>`}group(){if(0===this.elidedGroups)return l.simpleGroup(this.address).join(":");f("number"==typeof this.elidedGroups),f("number"==typeof this.elisionBegin);const e=[],[t,r]=this.address.split("::");t.length?e.push(...l.simpleGroup(t)):e.push("");const n=["hover-group"];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)n.push(`group-${e}`);return e.push(`<span class="${n.join(" ")}"></span>`),r.length?e.push(...l.simpleGroup(r,this.elisionEnd)):e.push(""),this.is4()&&(f(this.address4 instanceof u.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(":")}regularExpressionString(e=!1){let t=[];const r=new y(this.correctForm());if(0===r.elidedGroups)t.push((0,d.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===c.GROUPS)t.push((0,d.possibleElisions)(c.GROUPS));else{const e=r.address.split("::");e[0].length&&t.push((0,d.simpleRegularExpression)(e[0].split(":"))),f("number"==typeof r.elidedGroups),t.push((0,d.possibleElisions)(r.elidedGroups,0!==e[0].length,0!==e[1].length)),e[1].length&&t.push((0,d.simpleRegularExpression)(e[1].split(":"))),t=[t.join(":")]}return e||(t=["(?=^|",d.ADDRESS_BOUNDARY,"|[^\\w\\:])(",...t,")(?=[^\\w\\:]|",d.ADDRESS_BOUNDARY,"|$)"]),t.join("")}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),"i")}}t.Address6=y},6371(e,t,r){"use strict";const{format:n,inspect:i}=r(9231),{AggregateError:o}=r(4134),s=globalThis.AggregateError||o,a=Symbol("kIsNodeError"),c=["string","function","number","object","Function","Object","boolean","bigint","symbol"],l=/^([A-Z][a-z0-9]*)+$/,u={};function d(e,t){if(!e)throw new u.ERR_INTERNAL_ASSERTION(t)}function h(e){let t="",r=e.length;const n="-"===e[0]?1:0;for(;r>=n+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function p(e,t,r){r||(r=Error);class i extends r{constructor(...r){super(function(e,t,r){if("function"==typeof t)return d(t.length<=r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${t.length}).`),t(...r);const i=(t.match(/%[dfijoOs]/g)||[]).length;return d(i===r.length,`Code: ${e}; The provided arguments length (${r.length}) does not match the required ones (${i}).`),0===r.length?t:n(t,...r)}(e,t,r))}toString(){return`${this.name} [${e}]: ${this.message}`}}Object.defineProperties(i.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${e}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),i.prototype.code=e,i.prototype[a]=!0,u[e]=i}function f(e){const t="__node_internal_"+e.name;return Object.defineProperty(e,"name",{value:t}),e}class g extends Error{constructor(e="The operation was aborted",t=void 0){if(void 0!==t&&"object"!=typeof t)throw new u.ERR_INVALID_ARG_TYPE("options","Object",t);super(e,t),this.code="ABORT_ERR",this.name="AbortError"}}p("ERR_ASSERTION","%s",Error),p("ERR_INVALID_ARG_TYPE",(e,t,r)=>{d("string"==typeof e,"'name' must be a string"),Array.isArray(t)||(t=[t]);let n="The ";e.endsWith(" argument")?n+=`${e} `:n+=`"${e}" ${e.includes(".")?"property":"argument"} `,n+="must be ";const o=[],s=[],a=[];for(const e of t)d("string"==typeof e,"All expected entries have to be of type string"),c.includes(e)?o.push(e.toLowerCase()):l.test(e)?s.push(e):(d("object"!==e,'The value "object" should be written as "Object"'),a.push(e));if(s.length>0){const e=o.indexOf("object");-1!==e&&(o.splice(o,e,1),s.push("Object"))}if(o.length>0){switch(o.length){case 1:n+=`of type ${o[0]}`;break;case 2:n+=`one of type ${o[0]} or ${o[1]}`;break;default:{const e=o.pop();n+=`one of type ${o.join(", ")}, or ${e}`}}(s.length>0||a.length>0)&&(n+=" or ")}if(s.length>0){switch(s.length){case 1:n+=`an instance of ${s[0]}`;break;case 2:n+=`an instance of ${s[0]} or ${s[1]}`;break;default:{const e=s.pop();n+=`an instance of ${s.join(", ")}, or ${e}`}}a.length>0&&(n+=" or ")}switch(a.length){case 0:break;case 1:a[0].toLowerCase()!==a[0]&&(n+="an "),n+=`${a[0]}`;break;case 2:n+=`one of ${a[0]} or ${a[1]}`;break;default:{const e=a.pop();n+=`one of ${a.join(", ")}, or ${e}`}}if(null==r)n+=`. Received ${r}`;else if("function"==typeof r&&r.name)n+=`. Received function ${r.name}`;else if("object"==typeof r){var u;if(null!==(u=r.constructor)&&void 0!==u&&u.name)n+=`. Received an instance of ${r.constructor.name}`;else{n+=`. Received ${i(r,{depth:-1})}`}}else{let e=i(r,{colors:!1});e.length>25&&(e=`${e.slice(0,25)}...`),n+=`. Received type ${typeof r} (${e})`}return n},TypeError),p("ERR_INVALID_ARG_VALUE",(e,t,r="is invalid")=>{let n=i(t);n.length>128&&(n=n.slice(0,128)+"...");return`The ${e.includes(".")?"property":"argument"} '${e}' ${r}. Received ${n}`},TypeError),p("ERR_INVALID_RETURN_VALUE",(e,t,r)=>{var n;return`Expected ${e} to be returned from the "${t}" function but got ${null!=r&&null!==(n=r.constructor)&&void 0!==n&&n.name?`instance of ${r.constructor.name}`:"type "+typeof r}.`},TypeError),p("ERR_MISSING_ARGS",(...e)=>{let t;d(e.length>0,"At least one arg needs to be specified");const r=e.length;switch(e=(Array.isArray(e)?e:[e]).map(e=>`"${e}"`).join(" or "),r){case 1:t+=`The ${e[0]} argument`;break;case 2:t+=`The ${e[0]} and ${e[1]} arguments`;break;default:{const r=e.pop();t+=`The ${e.join(", ")}, and ${r} arguments`}}return`${t} must be specified`},TypeError),p("ERR_OUT_OF_RANGE",(e,t,r)=>{let n;if(d(t,'Missing "range" argument'),Number.isInteger(r)&&Math.abs(r)>2**32)n=h(String(r));else if("bigint"==typeof r){n=String(r);const e=BigInt(2)**BigInt(32);(r>e||r<-e)&&(n=h(n)),n+="n"}else n=i(r);return`The value of "${e}" is out of range. It must be ${t}. Received ${n}`},RangeError),p("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error),p("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error),p("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error),p("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error),p("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error),p("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),p("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error),p("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error),p("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error),p("ERR_STREAM_WRITE_AFTER_END","write after end",Error),p("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError),e.exports={AbortError:g,aggregateTwoErrors:f(function(e,t){if(e&&t&&e!==t){if(Array.isArray(t.errors))return t.errors.push(e),t;const r=new s([t,e],t.message);return r.code=t.code,r}return e||t}),hideStackFrames:f,codes:u}},6524(e,t,r){"use strict";const{ObjectSetPrototypeOf:n}=r(4134);e.exports=o;const i=r(7382);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e)}n(o.prototype,i.prototype),n(o,i),o.prototype._transform=function(e,t,r){r(null,e)}},6532(e,t,r){"use strict";const n=r(4422),{PromisePrototypeThen:i,SymbolAsyncIterator:o,SymbolIterator:s}=r(4134),{Buffer:a}=r(181),{ERR_INVALID_ARG_TYPE:c,ERR_STREAM_NULL_VALUES:l}=r(6371).codes;e.exports=function(e,t,r){let u,d;if("string"==typeof t||t instanceof a)return new e({objectMode:!0,...r,read(){this.push(t),this.push(null)}});if(t&&t[o])d=!0,u=t[o]();else{if(!t||!t[s])throw new c("iterable",["Iterable"],t);d=!1,u=t[s]()}const h=new e({objectMode:!0,highWaterMark:1,...r});let p=!1;return h._read=function(){p||(p=!0,async function(){for(;;){try{const{value:e,done:t}=d?await u.next():u.next();if(t)h.push(null);else{const t=e&&"function"==typeof e.then?await e:e;if(null===t)throw p=!1,new l;if(h.push(t))continue;p=!1}}catch(e){h.destroy(e)}break}}())},h._destroy=function(e,t){i(async function(e){const t=null!=e,r="function"==typeof u.throw;if(t&&r){const{value:t,done:r}=await u.throw(e);if(await t,r)return}if("function"==typeof u.return){const{value:e}=await u.return();await e}}(e),()=>n.nextTick(t,e),r=>n.nextTick(t,r||e))},h}},6584(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(4988);class i extends n.EventTarget{constructor(){throw super(),new TypeError("AbortSignal cannot be constructed directly")}get aborted(){const e=o.get(this);if("boolean"!=typeof e)throw new TypeError("Expected 'this' to be an 'AbortSignal' object, but got "+(null===this?"null":typeof this));return e}}n.defineEventAttribute(i.prototype,"abort");const o=new WeakMap;Object.defineProperties(i.prototype,{aborted:{enumerable:!0}}),"function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(i.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortSignal"});class s{constructor(){a.set(this,function(){const e=Object.create(i.prototype);return n.EventTarget.call(e),o.set(e,!1),e}())}get signal(){return c(this)}abort(){var e;e=c(this),!1===o.get(e)&&(o.set(e,!0),e.dispatchEvent({type:"abort"}))}}const a=new WeakMap;function c(e){const t=a.get(e);if(null==t)throw new TypeError("Expected 'this' to be an 'AbortController' object, but got "+(null===e?"null":typeof e));return t}Object.defineProperties(s.prototype,{signal:{enumerable:!0},abort:{enumerable:!0}}),"function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag&&Object.defineProperty(s.prototype,Symbol.toStringTag,{configurable:!0,value:"AbortController"}),t.AbortController=s,t.AbortSignal=i,t.default=s,e.exports=s,e.exports.AbortController=e.exports.default=s,e.exports.AbortSignal=i},6585(e){var t=1e3,r=60*t,n=60*r,i=24*n,o=7*i,s=365.25*i;function a(e,t,r,n){var i=t>=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}e.exports=function(e,c){c=c||{};var l=typeof e;if("string"===l&&e.length>0)return function(e){if((e=String(e)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*s;case"weeks":case"week":case"w":return c*o;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*n;case"minutes":case"minute":case"mins":case"min":case"m":return c*r;case"seconds":case"second":case"secs":case"sec":case"s":return c*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(e);if("number"===l&&isFinite(e))return c.long?function(e){var o=Math.abs(e);if(o>=i)return a(e,o,i,"day");if(o>=n)return a(e,o,n,"hour");if(o>=r)return a(e,o,r,"minute");if(o>=t)return a(e,o,t,"second");return e+" ms"}(e):function(e){var o=Math.abs(e);if(o>=i)return Math.round(e/i)+"d";if(o>=n)return Math.round(e/n)+"h";if(o>=r)return Math.round(e/r)+"m";if(o>=t)return Math.round(e/t)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},6698(e){"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},6706(e,t,r){const n=r(4422),i=r(181),{isReadable:o,isWritable:s,isIterable:a,isNodeStream:c,isReadableNodeStream:l,isWritableNodeStream:u,isDuplexNodeStream:d,isReadableStream:h,isWritableStream:p}=r(6115),f=r(6238),{AbortError:g,codes:{ERR_INVALID_ARG_TYPE:m,ERR_INVALID_RETURN_VALUE:b}}=r(6371),{destroyer:y}=r(5896),_=r(3370),v=r(7576),S=r(8584),{createDeferredPromise:w}=r(7760),k=r(6532),E=globalThis.Blob||i.Blob,I="undefined"!=typeof E?function(e){return e instanceof E}:function(e){return!1},T=globalThis.AbortController||r(6584).AbortController,{FunctionPrototypeCall:O}=r(4134);class C extends _{constructor(e){super(e),!1===(null==e?void 0:e.readable)&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),!1===(null==e?void 0:e.writable)&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}}function x(e){const t=e.readable&&"function"!=typeof e.readable.read?v.wrap(e.readable):e.readable,r=e.writable;let n,i,a,c,l,u=!!o(t),d=!!s(r);function h(e){const t=c;c=null,t?t(e):e&&l.destroy(e)}return l=new C({readableObjectMode:!(null==t||!t.readableObjectMode),writableObjectMode:!(null==r||!r.writableObjectMode),readable:u,writable:d}),d&&(f(r,e=>{d=!1,e&&y(t,e),h(e)}),l._write=function(e,t,i){r.write(e,t)?i():n=i},l._final=function(e){r.end(),i=e},r.on("drain",function(){if(n){const e=n;n=null,e()}}),r.on("finish",function(){if(i){const e=i;i=null,e()}})),u&&(f(t,e=>{u=!1,e&&y(t,e),h(e)}),t.on("readable",function(){if(a){const e=a;a=null,e()}}),t.on("end",function(){l.push(null)}),l._read=function(){for(;;){const e=t.read();if(null===e)return void(a=l._read);if(!l.push(e))return}}),l._destroy=function(e,o){e||null===c||(e=new g),a=null,n=null,i=null,null===c?o(e):(c=o,y(r,e),y(t,e))},l}e.exports=function e(t,r){if(d(t))return t;if(l(t))return x({readable:t});if(u(t))return x({writable:t});if(c(t))return x({writable:!1,readable:!1});if(h(t))return x({readable:v.fromWeb(t)});if(p(t))return x({writable:S.fromWeb(t)});if("function"==typeof t){const{value:e,write:i,final:o,destroy:s}=function(e){let{promise:t,resolve:r}=w();const i=new T,o=i.signal,s=e(async function*(){for(;;){const e=t;t=null;const{chunk:i,done:s,cb:a}=await e;if(n.nextTick(a),s)return;if(o.aborted)throw new g(void 0,{cause:o.reason});({promise:t,resolve:r}=w()),yield i}}(),{signal:o});return{value:s,write(e,t,n){const i=r;r=null,i({chunk:e,done:!1,cb:n})},final(e){const t=r;r=null,t({done:!0,cb:e})},destroy(e,t){i.abort(),t(e)}}}(t);if(a(e))return k(C,e,{objectMode:!0,write:i,final:o,destroy:s});const c=null==e?void 0:e.then;if("function"==typeof c){let t;const r=O(c,e,e=>{if(null!=e)throw new b("nully","body",e)},e=>{y(t,e)});return t=new C({objectMode:!0,readable:!1,write:i,final(e){o(async()=>{try{await r,n.nextTick(e,null)}catch(t){n.nextTick(e,t)}})},destroy:s})}throw new b("Iterable, AsyncIterable or AsyncFunction",r,e)}if(I(t))return e(t.arrayBuffer());if(a(t))return k(C,t,{objectMode:!0,writable:!1});if(h(null==t?void 0:t.readable)&&p(null==t?void 0:t.writable))return C.fromWeb(t);if("object"==typeof(null==t?void 0:t.writable)||"object"==typeof(null==t?void 0:t.readable)){return x({readable:null!=t&&t.readable?l(null==t?void 0:t.readable)?null==t?void 0:t.readable:e(t.readable):void 0,writable:null!=t&&t.writable?u(null==t?void 0:t.writable)?null==t?void 0:t.writable:e(t.writable):void 0})}const i=null==t?void 0:t.then;if("function"==typeof i){let e;return O(i,t,t=>{null!=t&&e.push(t),e.push(null)},t=>{y(e,t)}),e=new C({objectMode:!0,writable:!1,read(){}})}throw new m(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],t)}},6751(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectCorrelator=void 0;const n=r(1554),i=r(441);t.ObjectCorrelator=class{topology;config;constructor(e,t){this.topology=e,this.config=t}async findBestMatch(e,t){const r=[];for(const n of t){const t=await this.evaluateCandidate(n,e);t.confidence>=this.config.correlationThreshold&&r.push(t)}return 0===r.length?null:(r.sort((e,t)=>t.confidence-e.confidence),r[0])}async evaluateCandidate(e,t){const r={timing:this.evaluateTimingFactor(e,t),visual:await this.evaluateVisualFactor(e,t),spatial:this.evaluateSpatialFactor(e,t),class:this.evaluateClassFactor(e,t)};if(0===r.class)return{trackedObject:e,newSighting:t,confidence:0,factors:r};if(0===r.timing)return{trackedObject:e,newSighting:t,confidence:0,factors:r};return{trackedObject:e,newSighting:t,confidence:.3*r.timing+.35*r.visual+.25*r.spatial+.1*r.class,factors:r}}evaluateTimingFactor(e,t){const r=(0,i.getLastSighting)(e);if(!r)return 0;if(r.cameraId===t.cameraId)return 1;const o=(0,n.findConnection)(this.topology,r.cameraId,t.cameraId);if(!o)return.2;const s=t.timestamp-r.timestamp,{min:a,typical:c,max:l}=o.transitTime;if(s<.5*a||s>2*l)return 0;if(s<a||s>l)return s<a?s/a*.3:l/s*.3;const u=Math.abs(s-c),d=(l-a)/2;return 0===d?1:Math.max(.5,1-u/d*.5)}async evaluateVisualFactor(e,t){if(!this.config.useVisualMatching)return.5;if(!e.visualDescriptor||!t.embedding)return.5;try{return(this.cosineSimilarity(e.visualDescriptor,t.embedding)+1)/2}catch(e){return.5}}evaluateSpatialFactor(e,t){const r=(0,i.getLastSighting)(e);if(!r)return.5;if(r.cameraId===t.cameraId)return 1;const o=(0,n.findConnection)(this.topology,r.cameraId,t.cameraId);if(!o)return.3;let s=0;if(r.position&&o.exitZone.length>0){this.isPointNearZone(r.position,o.exitZone,.2)&&(s+=.5)}else s+=.25;if(t.position&&o.entryZone.length>0){this.isPointNearZone(t.position,o.entryZone,.2)&&(s+=.5)}else s+=.25;return s}evaluateClassFactor(e,t){if(e.className===t.detection.className)return 1;return({car:["vehicle","truck","suv"],vehicle:["car","truck","suv"],truck:["vehicle","car"],person:["human"],human:["person"]}[e.className]||[]).includes(t.detection.className)?.8:0}cosineSimilarity(e,t){try{const r=this.decodeEmbedding(e),n=this.decodeEmbedding(t);if(r.length!==n.length||0===r.length)return 0;let i=0,o=0,s=0;for(let e=0;e<r.length;e++)i+=r[e]*n[e],o+=r[e]*r[e],s+=n[e]*n[e];return o=Math.sqrt(o),s=Math.sqrt(s),0===o||0===s?0:i/(o*s)}catch(e){return 0}}decodeEmbedding(e){try{const t=Buffer.from(e,"base64"),r=[];for(let e=0;e<t.length;e+=4)r.push(t.readFloatLE(e));return r}catch(e){return[]}}isPointNearZone(e,t,r){if(t.length<3)return!1;const n=100*e.x,i=100*e.y;let o=!1;for(let e=0,r=t.length-1;e<t.length;r=e++){const s=t[e][0],a=t[e][1],c=t[r][0],l=t[r][1];a>i!=l>i&&n<(c-s)*(i-a)/(l-a)+s&&(o=!o)}if(o)return!0;for(const e of t){const t=Math.abs(n-e[0])/100,o=Math.abs(i-e[1])/100;if(t<r&&o<r)return!0}return!1}}},6887(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isReactNativeBrowser=t.isWebWorker=void 0;const r=()=>Boolean("object"==typeof self&&self?.constructor?.name?.includes("WorkerGlobalScope")&&"undefined"==typeof Deno),n=()=>"undefined"!=typeof navigator&&"ReactNative"===navigator.product,i=(()=>{if("undefined"!=typeof window){if("undefined"!=typeof navigator&&navigator.userAgent?.toLowerCase().indexOf(" electron/")>-1&&process?.versions){return!Object.prototype.hasOwnProperty.call(process.versions,"electron")}return"undefined"!=typeof window.document}return!1})()||r()||n();t.isWebWorker=r(),t.isReactNativeBrowser=n(),t.default=i},6912(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=n(r(4959)),o=n(r(5228)),s=n(r(495)),a=n(r(1021)),c=n(r(4264));t.default=(e,t,r)=>{const{options:n}=e;if(5===n.protocolVersion&&n.properties&&n.properties.maximumPacketSize&&n.properties.maximumPacketSize<t.length)return e.emit("error",new Error(`exceeding packets size ${t.cmd}`)),e.end({reasonCode:149,properties:{reasonString:"Maximum packet size was exceeded"}}),e;switch(e.log("_handlePacket :: emitting packetreceive"),e.emit("packetreceive",t),t.cmd){case"publish":(0,i.default)(e,t,r);break;case"puback":case"pubrec":case"pubcomp":case"suback":case"unsuback":e.reschedulePing(),(0,a.default)(e,t),r();break;case"pubrel":e.reschedulePing(),(0,c.default)(e,t,r);break;case"connack":(0,s.default)(e,t),r();break;case"auth":e.reschedulePing(),(0,o.default)(e,t),r();break;case"pingresp":e.log("_handlePacket :: received pingresp"),e.reschedulePing(!0),r();break;case"disconnect":e.emit("disconnect",t),r();break;default:e.log("_handlePacket :: unknown command"),r()}}},6968(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r,n){f("SOCKS connection to %s:%d via %s",e,t,r);const i=new g;return async function(e,t,r,n,i={}){const o=i.lookup??(0,h.promisify)(d.lookup),[s,a]=function(e){const t=new URL(e);if(t.pathname||t.hash||t.search)throw m(new Error("bad SOCKS URL"));const[r,n]=function(e){switch(e){case"socks5h:":return[5,!0];case"socks4a:":return[4,!0];case"socks5:":return[5,!1];case"socks4:":return[4,!1];default:return[void 0,!1]}}(t.protocol);if(!r)throw m(new Error("bad SOCKS URL: invalid protocol"));const i=parseInt(t.port,10);if(Number.isNaN(i))throw m(new Error("bad SOCKS URL: invalid port"));const o={host:t.hostname,port:i,type:r};return[o,n]}(r);a||(f("resolving %s locally",e),e=(await o(e,{family:4===s.type?4:0})).address);f("establishing SOCKS%d connection to %s:%d via %s:%d",s.type,e,t,s.host,s.port);const c=new u.SocksClient({command:"connect",destination:{host:e,port:t},proxy:{...s},timeout:i.timeout});c.connect(),c.on("established",({socket:e})=>n._start(e)),c.on("error",e=>{f("SOCKS failed: %s",e),n.destroy(m(e))})}(e,t,r,i,n).catch(e=>{f("SOCKS failed: %s",e),i.destroy(e)}),i};const c=a(r(5753)),l=r(2203),u=r(5861),d=s(r(2250)),h=r(9023),p=a(r(2613)),f=(0,c.default)("mqttjs:socks");class g extends l.Duplex{_flowing=!1;_socket;constructor(){super({autoDestroy:!1}),this.cork()}_start(e){f("proxy stream started"),(0,p.default)(!this._socket),this.destroyed?e.destroy(this.errored):(this._socket=e,this._flowing||e.pause(),e.on("data",this._onData),e.on("end",this._onEnd),e.on("error",this._onError),e.on("close",this._onClose),e.emit("connect"),this.uncork())}_write(e,t,r){(0,p.default)(this._socket),this._socket.write(e,r)}_read(e){this._flowing=!0,this._socket?.resume?.()}_destroy(e,t){this._socket?.destroy?.(e),t(e)}_onData=e=>{(0,p.default)(this._socket),this._flowing=this.push(e),this._flowing||this._socket.pause()};_onEnd=()=>{f("proxy stream received EOF"),this.push(null)};_onClose=()=>{f("proxy stream closed"),this.destroy()};_onError=e=>{f("proxy stream died with error %s",e),this.destroy(e)}}function m(e){try{return void 0===e.code&&(e.code="SOCKS"),e}catch{return e}}},6982(e){"use strict";e.exports=require("crypto")},7016(e){"use strict";e.exports=require("url")},7130(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ipToBuffer=t.int32ToIpv4=t.ipv4ToInt32=t.validateSocksClientChainOptions=t.validateSocksClientOptions=void 0;const n=r(3763),i=r(5438),o=r(2203),s=r(9424),a=r(9278);function c(e,t){if(void 0!==e.custom_auth_method){if(e.custom_auth_method<i.SOCKS5_CUSTOM_AUTH_START||e.custom_auth_method>i.SOCKS5_CUSTOM_AUTH_END)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthRange,t);if(void 0===e.custom_auth_request_handler||"function"!=typeof e.custom_auth_request_handler)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,t);if(void 0===e.custom_auth_response_size)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,t);if(void 0===e.custom_auth_response_handler||"function"!=typeof e.custom_auth_response_handler)throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsCustomAuthOptions,t)}}function l(e){return e&&"string"==typeof e.host&&Buffer.byteLength(e.host)<256&&"number"==typeof e.port&&e.port>=0&&e.port<=65535}function u(e){return e&&("string"==typeof e.host||"string"==typeof e.ipaddress)&&"number"==typeof e.port&&e.port>=0&&e.port<=65535&&(4===e.type||5===e.type)}function d(e){return"number"==typeof e&&e>0}t.validateSocksClientOptions=function(e,t=["connect","bind","associate"]){if(!i.SocksCommand[e.command])throw new n.SocksClientError(i.ERRORS.InvalidSocksCommand,e);if(-1===t.indexOf(e.command))throw new n.SocksClientError(i.ERRORS.InvalidSocksCommandForOperation,e);if(!l(e.destination))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsDestination,e);if(!u(e.proxy))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsProxy,e);if(c(e.proxy,e),e.timeout&&!d(e.timeout))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsTimeout,e);if(e.existing_socket&&!(e.existing_socket instanceof o.Duplex))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsExistingSocket,e)},t.validateSocksClientChainOptions=function(e){if("connect"!==e.command)throw new n.SocksClientError(i.ERRORS.InvalidSocksCommandChain,e);if(!l(e.destination))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsDestination,e);if(!(e.proxies&&Array.isArray(e.proxies)&&e.proxies.length>=2))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsProxiesLength,e);if(e.proxies.forEach(t=>{if(!u(t))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsProxy,e);c(t,e)}),e.timeout&&!d(e.timeout))throw new n.SocksClientError(i.ERRORS.InvalidSocksClientOptionsTimeout,e)},t.ipv4ToInt32=function(e){return new s.Address4(e).toArray().reduce((e,t)=>(e<<8)+t,0)>>>0},t.int32ToIpv4=function(e){return[e>>>24&255,e>>>16&255,e>>>8&255,255&e].join(".")},t.ipToBuffer=function(e){if(a.isIPv4(e)){const t=new s.Address4(e);return Buffer.from(t.toArray())}if(a.isIPv6(e)){const t=new s.Address6(e);return Buffer.from(t.canonicalForm().split(":").map(e=>e.padStart(4,"0")).join(""),"hex")}throw new Error("Invalid IP address format")}},7136(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.TrackingEngine=void 0;const a=s(r(7562)),c=r(1554),l=r(441),u=r(6751),{systemManager:d}=a.default;t.TrackingEngine=class{topology;state;alertManager;config;console;correlator;listeners=new Map;pendingTimers=new Map;lostCheckInterval=null;constructor(e,t,r,n,i){this.topology=e,this.state=t,this.alertManager=r,this.config=n,this.console=i,this.correlator=new u.ObjectCorrelator(e,n)}async startTracking(){this.console.log("Starting tracking engine..."),await this.stopTracking();for(const e of this.topology.cameras)try{const t=d.getDeviceById(e.deviceId);if(!t){this.console.warn(`Camera not found: ${e.deviceId} (${e.name})`);continue}if(!t.interfaces?.includes(a.ScryptedInterface.ObjectDetector)){this.console.warn(`Camera ${e.name} does not support object detection`);continue}const r=t.listen(a.ScryptedInterface.ObjectDetector,(t,r,n)=>{this.handleDetection(e.deviceId,e.name,n)});this.listeners.set(e.deviceId,r),this.console.log(`Listening to camera: ${e.name}`)}catch(t){this.console.error(`Failed to subscribe to camera ${e.name}:`,t)}this.lostCheckInterval=setInterval(()=>{this.checkForLostObjects()},3e4),this.console.log(`Tracking engine started with ${this.listeners.size} cameras`)}async stopTracking(){for(const[e,t]of this.listeners.entries())try{t.removeListener()}catch(t){this.console.error(`Failed to remove listener for ${e}:`,t)}this.listeners.clear();for(const e of this.pendingTimers.values())clearTimeout(e);this.pendingTimers.clear(),this.lostCheckInterval&&(clearInterval(this.lostCheckInterval),this.lostCheckInterval=null),this.console.log("Tracking engine stopped")}async handleDetection(e,t,r){if(!r.detections||0===r.detections.length)return;const n=(0,c.findCamera)(this.topology,e);if(!n)return;const i=r.timestamp||Date.now();for(const o of r.detections){if(o.score<.5)continue;if(n.trackClasses.length>0&&!n.trackClasses.includes(o.className))continue;const s={detection:o,cameraId:e,cameraName:t,timestamp:i,confidence:o.score,embedding:o.embedding,detectionId:r.detectionId,position:o.boundingBox?{x:(o.boundingBox[0]+o.boundingBox[2]/2)/100,y:(o.boundingBox[1]+o.boundingBox[3]/2)/100}:void 0};await this.processSighting(s,n.isEntryPoint,n.isExitPoint)}}async processSighting(e,t,r){const n=await this.correlateDetection(e);if(n){const t=n.trackedObject,i=(0,l.getLastSighting)(t);i&&i.cameraId!==e.cameraId&&(this.state.addJourney(t.globalId,{fromCameraId:i.cameraId,fromCameraName:i.cameraName,toCameraId:e.cameraId,toCameraName:e.cameraName,exitTime:i.timestamp,entryTime:e.timestamp,transitDuration:e.timestamp-i.timestamp,correlationConfidence:n.confidence}),this.console.log(`Object ${t.globalId.slice(0,8)} transited: ${i.cameraName} → ${e.cameraName} (confidence: ${(100*n.confidence).toFixed(0)}%)`)),this.state.addSighting(t.globalId,e);const o=this.pendingTimers.get(t.globalId);o&&(clearTimeout(o),this.pendingTimers.delete(t.globalId)),this.state.reactivate(t.globalId),r&&this.isLeavingFrame(e)&&this.handlePotentialExit(t,e)}else{const r=this.state.generateId(),n=this.state.createObject(r,e,t);this.console.log(`New ${e.detection.className} detected on ${e.cameraName} (ID: ${r.slice(0,8)})`),t&&await this.alertManager.checkAndAlert("property_entry",n,{cameraId:e.cameraId,cameraName:e.cameraName,objectClass:e.detection.className,objectLabel:e.detection.label,detectionId:e.detectionId})}}async correlateDetection(e){const t=this.state.getActiveObjects();if(0===t.length)return null;for(const r of t){const t=(0,l.getLastSighting)(r);if(t&&t.cameraId===e.cameraId&&t.detection.id===e.detection.id)return{trackedObject:r,newSighting:e,confidence:1,factors:{timing:1,visual:1,spatial:1,class:1}}}return await this.correlator.findBestMatch(e,t)}isLeavingFrame(e){if(!e.position)return!1;const t=.1;return e.position.x<t||e.position.x>.9||e.position.y<t||e.position.y>.9}handlePotentialExit(e,t){this.state.markPending(e.globalId);const r=setTimeout(async()=>{const r=this.state.getObject(e.globalId);r&&"pending"===r.state&&(this.state.markExited(e.globalId,t.cameraId,t.cameraName),this.console.log(`Object ${e.globalId.slice(0,8)} exited via ${t.cameraName}`),await this.alertManager.checkAndAlert("property_exit",r,{cameraId:t.cameraId,cameraName:t.cameraName,objectClass:r.className,objectLabel:r.label})),this.pendingTimers.delete(e.globalId)},this.config.correlationWindow);this.pendingTimers.set(e.globalId,r)}checkForLostObjects(){const e=Date.now(),t=this.state.getActiveObjects();for(const r of t){const t=e-r.lastSeen;t>this.config.lostTimeout&&(this.state.markLost(r.globalId),this.console.log(`Object ${r.globalId.slice(0,8)} marked as lost (not seen for ${Math.round(t/1e3)}s)`),this.alertManager.checkAndAlert("lost_tracking",r,{objectClass:r.className,objectLabel:r.label}))}}updateTopology(e){this.topology=e,this.correlator=new u.ObjectCorrelator(e,this.config)}getTopology(){return this.topology}getTrackedObjects(){return this.state.getAllObjects()}getTrackedObject(e){return this.state.getObject(e)}}},7279(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MqttPublisher=void 0;const i=n(r(9372));t.MqttPublisher=class{client=null;config;console;connected=!1;reconnectTimer=null;constructor(e,t){this.config=e,this.console=t}async connect(){if(this.client)return;const e={clientId:`scrypted-spatial-awareness-${Date.now()}`,clean:!0,connectTimeout:1e4,reconnectPeriod:5e3};this.config.username&&(e.username=this.config.username,e.password=this.config.password);try{this.client=i.default.connect(this.config.broker,e),this.client.on("connect",()=>{this.connected=!0,this.console.log(`MQTT connected to ${this.config.broker}`),this.publishDiscovery()}),this.client.on("error",e=>{this.console.error("MQTT error:",e)}),this.client.on("close",()=>{this.connected=!1,this.console.log("MQTT connection closed")}),this.client.on("offline",()=>{this.connected=!1,this.console.log("MQTT offline")})}catch(e){this.console.error("Failed to connect to MQTT:",e)}}disconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.client&&(this.client.end(),this.client=null,this.connected=!1)}publishDiscovery(){if(!this.client||!this.connected)return;const e=this.config.baseTopic,t={name:"Property Occupancy",unique_id:"spatial_awareness_occupancy",state_topic:`${e}/occupancy/state`,device_class:"occupancy",payload_on:"ON",payload_off:"OFF",device:{identifiers:["spatial_awareness"],name:"Spatial Awareness",model:"Cross-Camera Tracker",manufacturer:"Scrypted"}};this.client.publish("homeassistant/binary_sensor/spatial_awareness_occupancy/config",JSON.stringify(t),{retain:!0});const r={name:"Active Tracked Objects",unique_id:"spatial_awareness_count",state_topic:`${e}/count/state`,icon:"mdi:account-multiple",device:{identifiers:["spatial_awareness"]}};this.client.publish("homeassistant/sensor/spatial_awareness_count/config",JSON.stringify(r),{retain:!0});const n={name:"People on Property",unique_id:"spatial_awareness_person_count",state_topic:`${e}/person_count/state`,icon:"mdi:account-group",device:{identifiers:["spatial_awareness"]}};this.client.publish("homeassistant/sensor/spatial_awareness_person_count/config",JSON.stringify(n),{retain:!0});const i={name:"Vehicles on Property",unique_id:"spatial_awareness_vehicle_count",state_topic:`${e}/vehicle_count/state`,icon:"mdi:car",device:{identifiers:["spatial_awareness"]}};this.client.publish("homeassistant/sensor/spatial_awareness_vehicle_count/config",JSON.stringify(i),{retain:!0}),this.console.log("MQTT discovery published")}publishState(e){if(!this.client||!this.connected)return;const t=this.config.baseTopic,r=e.filter(e=>"active"===e.state||"pending"===e.state),n=r.length>0;this.client.publish(`${t}/occupancy/state`,n?"ON":"OFF",{retain:!0}),this.client.publish(`${t}/count/state`,String(r.length),{retain:!0});const i=r.filter(e=>"person"===e.className).length;this.client.publish(`${t}/person_count/state`,String(i),{retain:!0});const o=r.filter(e=>["car","vehicle","truck"].includes(e.className)).length;this.client.publish(`${t}/vehicle_count/state`,String(o),{retain:!0});const s={timestamp:Date.now(),occupied:n,activeCount:r.length,personCount:i,vehicleCount:o,objects:r.map(e=>({id:e.globalId,class:e.className,label:e.label,cameras:e.activeOnCameras,firstSeen:e.firstSeen,lastSeen:e.lastSeen,state:e.state}))};this.client.publish(`${t}/state`,JSON.stringify(s),{retain:!0})}publishAlert(e){if(!this.client||!this.connected)return;const t=this.config.baseTopic,r={id:e.id,type:e.type,severity:e.severity,message:e.message,timestamp:e.timestamp,objectId:e.trackedObjectId,details:e.details};this.client.publish(`${t}/alerts`,JSON.stringify(r)),this.client.publish(`${t}/alerts/${e.type}`,JSON.stringify(r))}publishEntry(e,t){if(!this.client||!this.connected)return;const r=this.config.baseTopic,n={event:"entry",timestamp:Date.now(),object:{id:e.globalId,class:e.className,label:e.label},camera:t};this.client.publish(`${r}/events/entry`,JSON.stringify(n))}publishExit(e,t){if(!this.client||!this.connected)return;const r=this.config.baseTopic,n={event:"exit",timestamp:Date.now(),object:{id:e.globalId,class:e.className,label:e.label,dwellTime:e.lastSeen-e.firstSeen},camera:t};this.client.publish(`${r}/events/exit`,JSON.stringify(n))}publishTransition(e,t,r){if(!this.client||!this.connected)return;const n=this.config.baseTopic,i={event:"transition",timestamp:Date.now(),object:{id:e.globalId,class:e.className,label:e.label},from:t,to:r};this.client.publish(`${n}/events/transition`,JSON.stringify(i))}isConnected(){return this.connected}}},7382(e,t,r){"use strict";const{ObjectSetPrototypeOf:n,Symbol:i}=r(4134);e.exports=l;const{ERR_METHOD_NOT_IMPLEMENTED:o}=r(6371).codes,s=r(3370),{getHighWaterMark:a}=r(5291);n(l.prototype,s.prototype),n(l,s);const c=i("kCallback");function l(e){if(!(this instanceof l))return new l(e);const t=e?a(this,e,"readableHighWaterMark",!0):null;0===t&&(e={...e,highWaterMark:null,readableHighWaterMark:t,writableHighWaterMark:e.writableHighWaterMark||0}),s.call(this,e),this._readableState.sync=!1,this[c]=null,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",d)}function u(e){"function"!=typeof this._flush||this.destroyed?(this.push(null),e&&e()):this._flush((t,r)=>{t?e?e(t):this.destroy(t):(null!=r&&this.push(r),this.push(null),e&&e())})}function d(){this._final!==u&&u.call(this)}l.prototype._final=u,l.prototype._transform=function(e,t,r){throw new o("_transform()")},l.prototype._write=function(e,t,r){const n=this._readableState,i=this._writableState,o=n.length;this._transform(e,t,(e,t)=>{e?r(e):(null!=t&&this.push(t),i.ended||o===n.length||n.length<n.highWaterMark?r():this[c]=r)})},l.prototype._read=function(){if(this[c]){const e=this[c];this[c]=null,e()}}},7562(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.sdk=t.MixinDeviceBase=t.ScryptedDeviceBase=void 0,i(r(4192),t);const s=o(r(9896)),a=r(4192);r(3339);class c extends a.DeviceBase{constructor(e){super(),this.nativeId=e}get storage(){return this._storage||(this._storage=t.sdk.deviceManager.getDeviceStorage(this.nativeId)),this._storage}get log(){return this._log||(this._log=t.sdk.deviceManager.getDeviceLogger(this.nativeId)),this._log}get console(){return this._console||(this._console=t.sdk.deviceManager.getDeviceConsole(this.nativeId)),this._console}async createMediaObject(e,r){return t.sdk.mediaManager.createMediaObject(e,r,{sourceId:this.id})}getMediaObjectConsole(e){return"string"!=typeof e.sourceId?this.console:t.sdk.deviceManager.getMixinConsole(e.sourceId,this.nativeId)}_lazyLoadDeviceState(){this._deviceState||(this.nativeId?this._deviceState=t.sdk.deviceManager.getDeviceState(this.nativeId):this._deviceState=t.sdk.deviceManager.getDeviceState())}onDeviceEvent(e,r){return t.sdk.deviceManager.onDeviceEvent(this.nativeId,e,r)}}t.ScryptedDeviceBase=c;class l extends a.DeviceBase{constructor(e){super(),this._listeners=new Set,this.mixinDevice=e.mixinDevice,this.mixinDeviceInterfaces=e.mixinDeviceInterfaces,this.mixinStorageSuffix=e.mixinStorageSuffix,this._deviceState=e.mixinDeviceState,this.nativeId=t.sdk.systemManager.getDeviceById(this.id).nativeId,this.mixinProviderNativeId=e.mixinProviderNativeId,this._deviceState.__rpcproxy_traps_all_properties&&"string"==typeof this._deviceState.id&&(this._deviceState=t.sdk.deviceManager.createDeviceState(this._deviceState.id,this._deviceState.setState))}get storage(){if(!this._storage){const e=this.mixinStorageSuffix,r=this.id+(e?":"+e:"");this._storage=t.sdk.deviceManager.getMixinStorage(r,this.mixinProviderNativeId)}return this._storage}get console(){return this._console||(t.sdk.deviceManager.getMixinConsole?this._console=t.sdk.deviceManager.getMixinConsole(this.id,this.mixinProviderNativeId):this._console=t.sdk.deviceManager.getDeviceConsole(this.mixinProviderNativeId)),this._console}async createMediaObject(e,r){return t.sdk.mediaManager.createMediaObject(e,r,{sourceId:this.id})}getMediaObjectConsole(e){return"string"!=typeof e.sourceId?this.console:t.sdk.deviceManager.getMixinConsole(e.sourceId,this.mixinProviderNativeId)}onDeviceEvent(e,r){return t.sdk.deviceManager.onMixinEvent(this.id,this,e,r)}_lazyLoadDeviceState(){}manageListener(e){this._listeners.add(e)}release(){for(const e of this._listeners)e.removeListener()}}t.MixinDeviceBase=l,function(){function e(e){return function(){return this._lazyLoadDeviceState(),this._deviceState?.[e]}}function t(e){return function(t){this._lazyLoadDeviceState(),this._deviceState?this._deviceState[e]=t:console.warn("device state is unavailable. the device must be discovered with deviceManager.onDeviceDiscovered or deviceManager.onDevicesChanged before the state can be set.")}}for(const r of Object.values(a.ScryptedInterfaceProperty))r!==a.ScryptedInterfaceProperty.nativeId&&(Object.defineProperty(c.prototype,r,{set:t(r),get:e(r)}),Object.defineProperty(l.prototype,r,{set:t(r),get:e(r)}))}(),t.sdk={};try{let e=!1;try{process.env.SCRYPTED_SDK_ES_MODULE||process.env.SCRYPTED_SDK_MODULE;const n=process.env.SCRYPTED_SDK_CJS_MODULE||process.env.SCRYPTED_SDK_MODULE;if(n)if("undefined"!=typeof require){const r=require(process.env.SCRYPTED_SDK_MODULE);Object.assign(t.sdk,r.getScryptedStatic()),e=!0}else{const i=r(3891)(n);Object.assign(t.sdk,i.getScryptedStatic()),e=!0}}catch(e){throw console.warn("failed to load sdk module",e),e}if(!e){let e;try{e=pluginRuntimeAPI}catch(e){}Object.assign(t.sdk,{log:deviceManager.getDeviceLogger(void 0),deviceManager,endpointManager,mediaManager,systemManager,pluginHostAPI,...e})}try{let e={...a.ScryptedInterfaceDescriptors};try{const t=JSON.parse(s.default.readFileSync("../sdk.json").toString()).interfaceDescriptors;t&&(e={...e,...t})}catch(e){console.warn("failed to load custom interface descriptors",e)}t.sdk.systemManager.setScryptedInterfaceDescriptors?.(a.TYPES_VERSION,e)?.catch(()=>{})}catch(e){}}catch(e){console.error("sdk initialization error, import @scrypted/types or use @scrypted/client instead",e)}t.default=t.sdk},7575(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(1725);class i{constructor(e){if(this.length=0,this._encoding="utf8",this._writeOffset=0,this._readOffset=0,i.isSmartBufferOptions(e))if(e.encoding&&(n.checkEncoding(e.encoding),this._encoding=e.encoding),e.size){if(!(n.isFiniteInteger(e.size)&&e.size>0))throw new Error(n.ERRORS.INVALID_SMARTBUFFER_SIZE);this._buff=Buffer.allocUnsafe(e.size)}else if(e.buff){if(!Buffer.isBuffer(e.buff))throw new Error(n.ERRORS.INVALID_SMARTBUFFER_BUFFER);this._buff=e.buff,this.length=e.buff.length}else this._buff=Buffer.allocUnsafe(4096);else{if("undefined"!=typeof e)throw new Error(n.ERRORS.INVALID_SMARTBUFFER_OBJECT);this._buff=Buffer.allocUnsafe(4096)}}static fromSize(e,t){return new this({size:e,encoding:t})}static fromBuffer(e,t){return new this({buff:e,encoding:t})}static fromOptions(e){return new this(e)}static isSmartBufferOptions(e){const t=e;return t&&(void 0!==t.encoding||void 0!==t.size||void 0!==t.buff)}readInt8(e){return this._readNumberValue(Buffer.prototype.readInt8,1,e)}readInt16BE(e){return this._readNumberValue(Buffer.prototype.readInt16BE,2,e)}readInt16LE(e){return this._readNumberValue(Buffer.prototype.readInt16LE,2,e)}readInt32BE(e){return this._readNumberValue(Buffer.prototype.readInt32BE,4,e)}readInt32LE(e){return this._readNumberValue(Buffer.prototype.readInt32LE,4,e)}readBigInt64BE(e){return n.bigIntAndBufferInt64Check("readBigInt64BE"),this._readNumberValue(Buffer.prototype.readBigInt64BE,8,e)}readBigInt64LE(e){return n.bigIntAndBufferInt64Check("readBigInt64LE"),this._readNumberValue(Buffer.prototype.readBigInt64LE,8,e)}writeInt8(e,t){return this._writeNumberValue(Buffer.prototype.writeInt8,1,e,t),this}insertInt8(e,t){return this._insertNumberValue(Buffer.prototype.writeInt8,1,e,t)}writeInt16BE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt16BE,2,e,t)}insertInt16BE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt16BE,2,e,t)}writeInt16LE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt16LE,2,e,t)}insertInt16LE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt16LE,2,e,t)}writeInt32BE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt32BE,4,e,t)}insertInt32BE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt32BE,4,e,t)}writeInt32LE(e,t){return this._writeNumberValue(Buffer.prototype.writeInt32LE,4,e,t)}insertInt32LE(e,t){return this._insertNumberValue(Buffer.prototype.writeInt32LE,4,e,t)}writeBigInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigInt64BE,8,e,t)}insertBigInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigInt64BE,8,e,t)}writeBigInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigInt64LE,8,e,t)}insertBigInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigInt64LE,8,e,t)}readUInt8(e){return this._readNumberValue(Buffer.prototype.readUInt8,1,e)}readUInt16BE(e){return this._readNumberValue(Buffer.prototype.readUInt16BE,2,e)}readUInt16LE(e){return this._readNumberValue(Buffer.prototype.readUInt16LE,2,e)}readUInt32BE(e){return this._readNumberValue(Buffer.prototype.readUInt32BE,4,e)}readUInt32LE(e){return this._readNumberValue(Buffer.prototype.readUInt32LE,4,e)}readBigUInt64BE(e){return n.bigIntAndBufferInt64Check("readBigUInt64BE"),this._readNumberValue(Buffer.prototype.readBigUInt64BE,8,e)}readBigUInt64LE(e){return n.bigIntAndBufferInt64Check("readBigUInt64LE"),this._readNumberValue(Buffer.prototype.readBigUInt64LE,8,e)}writeUInt8(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt8,1,e,t)}insertUInt8(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt8,1,e,t)}writeUInt16BE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt16BE,2,e,t)}insertUInt16BE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt16BE,2,e,t)}writeUInt16LE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt16LE,2,e,t)}insertUInt16LE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt16LE,2,e,t)}writeUInt32BE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt32BE,4,e,t)}insertUInt32BE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt32BE,4,e,t)}writeUInt32LE(e,t){return this._writeNumberValue(Buffer.prototype.writeUInt32LE,4,e,t)}insertUInt32LE(e,t){return this._insertNumberValue(Buffer.prototype.writeUInt32LE,4,e,t)}writeBigUInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,t)}insertBigUInt64BE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64BE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64BE,8,e,t)}writeBigUInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._writeNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,t)}insertBigUInt64LE(e,t){return n.bigIntAndBufferInt64Check("writeBigUInt64LE"),this._insertNumberValue(Buffer.prototype.writeBigUInt64LE,8,e,t)}readFloatBE(e){return this._readNumberValue(Buffer.prototype.readFloatBE,4,e)}readFloatLE(e){return this._readNumberValue(Buffer.prototype.readFloatLE,4,e)}writeFloatBE(e,t){return this._writeNumberValue(Buffer.prototype.writeFloatBE,4,e,t)}insertFloatBE(e,t){return this._insertNumberValue(Buffer.prototype.writeFloatBE,4,e,t)}writeFloatLE(e,t){return this._writeNumberValue(Buffer.prototype.writeFloatLE,4,e,t)}insertFloatLE(e,t){return this._insertNumberValue(Buffer.prototype.writeFloatLE,4,e,t)}readDoubleBE(e){return this._readNumberValue(Buffer.prototype.readDoubleBE,8,e)}readDoubleLE(e){return this._readNumberValue(Buffer.prototype.readDoubleLE,8,e)}writeDoubleBE(e,t){return this._writeNumberValue(Buffer.prototype.writeDoubleBE,8,e,t)}insertDoubleBE(e,t){return this._insertNumberValue(Buffer.prototype.writeDoubleBE,8,e,t)}writeDoubleLE(e,t){return this._writeNumberValue(Buffer.prototype.writeDoubleLE,8,e,t)}insertDoubleLE(e,t){return this._insertNumberValue(Buffer.prototype.writeDoubleLE,8,e,t)}readString(e,t){let r;"number"==typeof e?(n.checkLengthValue(e),r=Math.min(e,this.length-this._readOffset)):(t=e,r=this.length-this._readOffset),"undefined"!=typeof t&&n.checkEncoding(t);const i=this._buff.slice(this._readOffset,this._readOffset+r).toString(t||this._encoding);return this._readOffset+=r,i}insertString(e,t,r){return n.checkOffsetValue(t),this._handleString(e,!0,t,r)}writeString(e,t,r){return this._handleString(e,!1,t,r)}readStringNT(e){"undefined"!=typeof e&&n.checkEncoding(e);let t=this.length;for(let e=this._readOffset;e<this.length;e++)if(0===this._buff[e]){t=e;break}const r=this._buff.slice(this._readOffset,t);return this._readOffset=t+1,r.toString(e||this._encoding)}insertStringNT(e,t,r){return n.checkOffsetValue(t),this.insertString(e,t,r),this.insertUInt8(0,t+e.length),this}writeStringNT(e,t,r){return this.writeString(e,t,r),this.writeUInt8(0,"number"==typeof t?t+e.length:this.writeOffset),this}readBuffer(e){"undefined"!=typeof e&&n.checkLengthValue(e);const t="number"==typeof e?e:this.length,r=Math.min(this.length,this._readOffset+t),i=this._buff.slice(this._readOffset,r);return this._readOffset=r,i}insertBuffer(e,t){return n.checkOffsetValue(t),this._handleBuffer(e,!0,t)}writeBuffer(e,t){return this._handleBuffer(e,!1,t)}readBufferNT(){let e=this.length;for(let t=this._readOffset;t<this.length;t++)if(0===this._buff[t]){e=t;break}const t=this._buff.slice(this._readOffset,e);return this._readOffset=e+1,t}insertBufferNT(e,t){return n.checkOffsetValue(t),this.insertBuffer(e,t),this.insertUInt8(0,t+e.length),this}writeBufferNT(e,t){return"undefined"!=typeof t&&n.checkOffsetValue(t),this.writeBuffer(e,t),this.writeUInt8(0,"number"==typeof t?t+e.length:this._writeOffset),this}clear(){return this._writeOffset=0,this._readOffset=0,this.length=0,this}remaining(){return this.length-this._readOffset}get readOffset(){return this._readOffset}set readOffset(e){n.checkOffsetValue(e),n.checkTargetOffset(e,this),this._readOffset=e}get writeOffset(){return this._writeOffset}set writeOffset(e){n.checkOffsetValue(e),n.checkTargetOffset(e,this),this._writeOffset=e}get encoding(){return this._encoding}set encoding(e){n.checkEncoding(e),this._encoding=e}get internalBuffer(){return this._buff}toBuffer(){return this._buff.slice(0,this.length)}toString(e){const t="string"==typeof e?e:this._encoding;return n.checkEncoding(t),this._buff.toString(t,0,this.length)}destroy(){return this.clear(),this}_handleString(e,t,r,i){let o=this._writeOffset,s=this._encoding;"number"==typeof r?o=r:"string"==typeof r&&(n.checkEncoding(r),s=r),"string"==typeof i&&(n.checkEncoding(i),s=i);const a=Buffer.byteLength(e,s);return t?this.ensureInsertable(a,o):this._ensureWriteable(a,o),this._buff.write(e,o,a,s),t?this._writeOffset+=a:"number"==typeof r?this._writeOffset=Math.max(this._writeOffset,o+a):this._writeOffset+=a,this}_handleBuffer(e,t,r){const n="number"==typeof r?r:this._writeOffset;return t?this.ensureInsertable(e.length,n):this._ensureWriteable(e.length,n),e.copy(this._buff,n),t?this._writeOffset+=e.length:"number"==typeof r?this._writeOffset=Math.max(this._writeOffset,n+e.length):this._writeOffset+=e.length,this}ensureReadable(e,t){let r=this._readOffset;if("undefined"!=typeof t&&(n.checkOffsetValue(t),r=t),r<0||r+e>this.length)throw new Error(n.ERRORS.INVALID_READ_BEYOND_BOUNDS)}ensureInsertable(e,t){n.checkOffsetValue(t),this._ensureCapacity(this.length+e),t<this.length&&this._buff.copy(this._buff,t+e,t,this._buff.length),t+e>this.length?this.length=t+e:this.length+=e}_ensureWriteable(e,t){const r="number"==typeof t?t:this._writeOffset;this._ensureCapacity(r+e),r+e>this.length&&(this.length=r+e)}_ensureCapacity(e){const t=this._buff.length;if(e>t){let r=this._buff,n=3*t/2+1;n<e&&(n=e),this._buff=Buffer.allocUnsafe(n),r.copy(this._buff,0,0,t)}}_readNumberValue(e,t,r){this.ensureReadable(t,r);const n=e.call(this._buff,"number"==typeof r?r:this._readOffset);return"undefined"==typeof r&&(this._readOffset+=t),n}_insertNumberValue(e,t,r,i){return n.checkOffsetValue(i),this.ensureInsertable(t,i),e.call(this._buff,r,i),this._writeOffset+=t,this}_writeNumberValue(e,t,r,i){if("number"==typeof i){if(i<0)throw new Error(n.ERRORS.INVALID_WRITE_BEYOND_BOUNDS);n.checkOffsetValue(i)}const o="number"==typeof i?i:this._writeOffset;return this._ensureWriteable(t,o),e.call(this._buff,r,o),"number"==typeof i?this._writeOffset=Math.max(this._writeOffset,o+t):this._writeOffset+=t,this}}t.SmartBuffer=i},7576(e,t,r){"use strict";const n=r(4422),{ArrayPrototypeIndexOf:i,NumberIsInteger:o,NumberIsNaN:s,NumberParseInt:a,ObjectDefineProperties:c,ObjectKeys:l,ObjectSetPrototypeOf:u,Promise:d,SafeSet:h,SymbolAsyncDispose:p,SymbolAsyncIterator:f,Symbol:g}=r(4134);e.exports=H,H.ReadableState=W;const{EventEmitter:m}=r(4434),{Stream:b,prependListener:y}=r(4259),{Buffer:_}=r(181),{addAbortSignal:v}=r(4147),S=r(6238);let w=r(7760).debuglog("stream",e=>{w=e});const k=r(345),E=r(5896),{getHighWaterMark:I,getDefaultHighWaterMark:T}=r(5291),{aggregateTwoErrors:O,codes:{ERR_INVALID_ARG_TYPE:C,ERR_METHOD_NOT_IMPLEMENTED:x,ERR_OUT_OF_RANGE:A,ERR_STREAM_PUSH_AFTER_EOF:P,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:R},AbortError:M}=r(6371),{validateObject:B}=r(277),N=g("kPaused"),{StringDecoder:j}=r(3141),D=r(6532);u(H.prototype,b.prototype),u(H,b);const L=()=>{},{errorOrDestroy:U}=E,F=2048,$=4096;function V(e){return{enumerable:!1,get(){return 0!==(this.state&e)},set(t){t?this.state|=e:this.state&=~e}}}function W(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(3370)),this.state=6192,e&&e.objectMode&&(this.state|=1),n&&e&&e.readableObjectMode&&(this.state|=1),this.highWaterMark=e?I(this,e,"readableHighWaterMark",n):T(!1),this.buffer=new k,this.length=0,this.pipes=[],this.flowing=null,this[N]=null,e&&!1===e.emitClose&&(this.state&=-2049),e&&!1===e.autoDestroy&&(this.state&=-4097),this.errored=null,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,e&&e.encoding&&(this.decoder=new j(e.encoding),this.encoding=e.encoding)}function H(e){if(!(this instanceof H))return new H(e);const t=this instanceof r(3370);this._readableState=new W(e,this,t),e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&!t&&v(e.signal,this)),b.call(this,e),E.construct(this,()=>{this._readableState.needReadable&&Y(this,this._readableState)})}function z(e,t,r,n){w("readableAddChunk",t);const i=e._readableState;let o;if(1&i.state||("string"==typeof t?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?t=_.from(t,r).toString(i.encoding):(t=_.from(t,r),r=""))):t instanceof _?r="":b._isUint8Array(t)?(t=b._uint8ArrayToBuffer(t),r=""):null!=t&&(o=new C("chunk",["string","Buffer","Uint8Array"],t))),o)U(e,o);else if(null===t)i.state&=-9,function(e,t){if(w("onEofChunk"),t.ended)return;if(t.decoder){const e=t.decoder.end();e&&e.length&&(t.buffer.push(e),t.length+=t.objectMode?1:e.length)}t.ended=!0,t.sync?K(e):(t.needReadable=!1,t.emittedReadable=!0,Q(e))}(e,i);else if(1&i.state||t&&t.length>0)if(n)if(4&i.state)U(e,new R);else{if(i.destroyed||i.errored)return!1;q(e,i,t,!0)}else if(i.ended)U(e,new P);else{if(i.destroyed||i.errored)return!1;i.state&=-9,i.decoder&&!r?(t=i.decoder.write(t),i.objectMode||0!==t.length?q(e,i,t,!1):Y(e,i)):q(e,i,t,!1)}else n||(i.state&=-9,Y(e,i));return!i.ended&&(i.length<i.highWaterMark||0===i.length)}function q(e,t,r,n){t.flowing&&0===t.length&&!t.sync&&e.listenerCount("data")>0?(65536&t.state?t.awaitDrainWriters.clear():t.awaitDrainWriters=null,t.dataEmitted=!0,e.emit("data",r)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),64&t.state&&K(e)),Y(e,t)}c(W.prototype,{objectMode:V(1),ended:V(2),endEmitted:V(4),reading:V(8),constructed:V(16),sync:V(32),needReadable:V(64),emittedReadable:V(128),readableListening:V(256),resumeScheduled:V(512),errorEmitted:V(1024),emitClose:V(F),autoDestroy:V($),destroyed:V(8192),closed:V(16384),closeEmitted:V(32768),multiAwaitDrain:V(65536),readingMore:V(1<<17),dataEmitted:V(1<<18)}),H.prototype.destroy=E.destroy,H.prototype._undestroy=E.undestroy,H.prototype._destroy=function(e,t){t(e)},H.prototype[m.captureRejectionSymbol]=function(e){this.destroy(e)},H.prototype[p]=function(){let e;return this.destroyed||(e=this.readableEnded?null:new M,this.destroy(e)),new d((t,r)=>S(this,n=>n&&n!==e?r(n):t(null)))},H.prototype.push=function(e,t){return z(this,e,t,!1)},H.prototype.unshift=function(e,t){return z(this,e,t,!0)},H.prototype.isPaused=function(){const e=this._readableState;return!0===e[N]||!1===e.flowing},H.prototype.setEncoding=function(e){const t=new j(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;const r=this._readableState.buffer;let n="";for(const e of r)n+=t.write(e);return r.clear(),""!==n&&r.push(n),this._readableState.length=n.length,this};function G(e,t){return e<=0||0===t.length&&t.ended?0:1&t.state?1:s(e)?t.flowing&&t.length?t.buffer.first().length:t.length:e<=t.length?e:t.ended?t.length:0}function K(e){const t=e._readableState;w("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(w("emitReadable",t.flowing),t.emittedReadable=!0,n.nextTick(Q,e))}function Q(e){const t=e._readableState;w("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||t.errored||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,te(e)}function Y(e,t){!t.readingMore&&t.constructed&&(t.readingMore=!0,n.nextTick(Z,e,t))}function Z(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){const r=t.length;if(w("maybeReadMore read 0"),e.read(0),r===t.length)break}t.readingMore=!1}function J(e){const t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!1===t[N]?t.flowing=!0:e.listenerCount("data")>0?e.resume():t.readableListening||(t.flowing=null)}function X(e){w("readable nexttick read 0"),e.read(0)}function ee(e,t){w("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),te(e),t.flowing&&!t.reading&&e.read(0)}function te(e){const t=e._readableState;for(w("flow",t.flowing);t.flowing&&null!==e.read(););}function re(e,t){"function"!=typeof e.read&&(e=H.wrap(e,{objectMode:!0}));const r=async function*(e,t){let r,n=L;function i(t){this===e?(n(),n=L):n=t}e.on("readable",i);const o=S(e,{writable:!1},e=>{r=e?O(r,e):null,n(),n=L});try{for(;;){const t=e.destroyed?null:e.read();if(null!==t)yield t;else{if(r)throw r;if(null===r)return;await new d(i)}}}catch(e){throw r=O(r,e),r}finally{!r&&!1===(null==t?void 0:t.destroyOnReturn)||void 0!==r&&!e._readableState.autoDestroy?(e.off("readable",i),o()):E.destroyer(e,null)}}(e,t);return r.stream=e,r}function ne(e,t){if(0===t.length)return null;let r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r}function ie(e){const t=e._readableState;w("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,n.nextTick(oe,t,e))}function oe(e,t){if(w("endReadableNT",e.endEmitted,e.length),!e.errored&&!e.closeEmitted&&!e.endEmitted&&0===e.length)if(e.endEmitted=!0,t.emit("end"),t.writable&&!1===t.allowHalfOpen)n.nextTick(se,t);else if(e.autoDestroy){const e=t._writableState;(!e||e.autoDestroy&&(e.finished||!1===e.writable))&&t.destroy()}}function se(e){e.writable&&!e.writableEnded&&!e.destroyed&&e.end()}let ae;function ce(){return void 0===ae&&(ae={}),ae}H.prototype.read=function(e){w("read",e),void 0===e?e=NaN:o(e)||(e=a(e,10));const t=this._readableState,r=e;if(e>t.highWaterMark&&(t.highWaterMark=function(e){if(e>1073741824)throw new A("size","<= 1GiB",e);return e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,++e}(e)),0!==e&&(t.state&=-129),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return w("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?ie(this):K(this),null;if(0===(e=G(e,t))&&t.ended)return 0===t.length&&ie(this),null;let n,i=!!(64&t.state);if(w("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&(i=!0,w("length less than watermark",i)),t.ended||t.reading||t.destroyed||t.errored||!t.constructed)i=!1,w("reading, ended or constructing",i);else if(i){w("do read"),t.state|=40,0===t.length&&(t.state|=64);try{this._read(t.highWaterMark)}catch(e){U(this,e)}t.state&=-33,t.reading||(e=G(r,t))}return n=e>0?ne(e,t):null,null===n?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.multiAwaitDrain?t.awaitDrainWriters.clear():t.awaitDrainWriters=null),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&ie(this)),null===n||t.errorEmitted||t.closeEmitted||(t.dataEmitted=!0,this.emit("data",n)),n},H.prototype._read=function(e){throw new x("_read()")},H.prototype.pipe=function(e,t){const r=this,i=this._readableState;1===i.pipes.length&&(i.multiAwaitDrain||(i.multiAwaitDrain=!0,i.awaitDrainWriters=new h(i.awaitDrainWriters?[i.awaitDrainWriters]:[]))),i.pipes.push(e),w("pipe count=%d opts=%j",i.pipes.length,t);const o=(!t||!1!==t.end)&&e!==n.stdout&&e!==n.stderr?a:m;function s(t,n){w("onunpipe"),t===r&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,function(){w("cleanup"),e.removeListener("close",f),e.removeListener("finish",g),c&&e.removeListener("drain",c);e.removeListener("error",p),e.removeListener("unpipe",s),r.removeListener("end",a),r.removeListener("end",m),r.removeListener("data",d),l=!0,c&&i.awaitDrainWriters&&(!e._writableState||e._writableState.needDrain)&&c()}())}function a(){w("onend"),e.end()}let c;i.endEmitted?n.nextTick(o):r.once("end",o),e.on("unpipe",s);let l=!1;function u(){l||(1===i.pipes.length&&i.pipes[0]===e?(w("false write response, pause",0),i.awaitDrainWriters=e,i.multiAwaitDrain=!1):i.pipes.length>1&&i.pipes.includes(e)&&(w("false write response, pause",i.awaitDrainWriters.size),i.awaitDrainWriters.add(e)),r.pause()),c||(c=function(e,t){return function(){const r=e._readableState;r.awaitDrainWriters===t?(w("pipeOnDrain",1),r.awaitDrainWriters=null):r.multiAwaitDrain&&(w("pipeOnDrain",r.awaitDrainWriters.size),r.awaitDrainWriters.delete(t)),r.awaitDrainWriters&&0!==r.awaitDrainWriters.size||!e.listenerCount("data")||e.resume()}}(r,e),e.on("drain",c))}function d(t){w("ondata");const r=e.write(t);w("dest.write",r),!1===r&&u()}function p(t){if(w("onerror",t),m(),e.removeListener("error",p),0===e.listenerCount("error")){const r=e._writableState||e._readableState;r&&!r.errorEmitted?U(e,t):e.emit("error",t)}}function f(){e.removeListener("finish",g),m()}function g(){w("onfinish"),e.removeListener("close",f),m()}function m(){w("unpipe"),r.unpipe(e)}return r.on("data",d),y(e,"error",p),e.once("close",f),e.once("finish",g),e.emit("pipe",r),!0===e.writableNeedDrain?u():i.flowing||(w("pipe resume"),r.resume()),e},H.prototype.unpipe=function(e){const t=this._readableState;if(0===t.pipes.length)return this;if(!e){const e=t.pipes;t.pipes=[],this.pause();for(let t=0;t<e.length;t++)e[t].emit("unpipe",this,{hasUnpiped:!1});return this}const r=i(t.pipes,e);return-1===r||(t.pipes.splice(r,1),0===t.pipes.length&&this.pause(),e.emit("unpipe",this,{hasUnpiped:!1})),this},H.prototype.on=function(e,t){const r=b.prototype.on.call(this,e,t),i=this._readableState;return"data"===e?(i.readableListening=this.listenerCount("readable")>0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,w("on readable",i.length,i.reading),i.length?K(this):i.reading||n.nextTick(X,this))),r},H.prototype.addListener=H.prototype.on,H.prototype.removeListener=function(e,t){const r=b.prototype.removeListener.call(this,e,t);return"readable"===e&&n.nextTick(J,this),r},H.prototype.off=H.prototype.removeListener,H.prototype.removeAllListeners=function(e){const t=b.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||n.nextTick(J,this),t},H.prototype.resume=function(){const e=this._readableState;return e.flowing||(w("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(ee,e,t))}(this,e)),e[N]=!1,this},H.prototype.pause=function(){return w("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(w("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[N]=!0,this},H.prototype.wrap=function(e){let t=!1;e.on("data",r=>{!this.push(r)&&e.pause&&(t=!0,e.pause())}),e.on("end",()=>{this.push(null)}),e.on("error",e=>{U(this,e)}),e.on("close",()=>{this.destroy()}),e.on("destroy",()=>{this.destroy()}),this._read=()=>{t&&e.resume&&(t=!1,e.resume())};const r=l(e);for(let t=1;t<r.length;t++){const n=r[t];void 0===this[n]&&"function"==typeof e[n]&&(this[n]=e[n].bind(e))}return this},H.prototype[f]=function(){return re(this)},H.prototype.iterator=function(e){return void 0!==e&&B(e,"options"),re(this,e)},c(H.prototype,{readable:{__proto__:null,get(){const e=this._readableState;return!(!e||!1===e.readable||e.destroyed||e.errorEmitted||e.endEmitted)},set(e){this._readableState&&(this._readableState.readable=!!e)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._readableState.readable||!this._readableState.destroyed&&!this._readableState.errored||this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.objectMode}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return!!this._readableState&&this._readableState.closed}},destroyed:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.destroyed},set(e){this._readableState&&(this._readableState.destroyed=e)}},readableEnded:{__proto__:null,enumerable:!1,get(){return!!this._readableState&&this._readableState.endEmitted}}}),c(W.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return!1!==this[N]},set(e){this[N]=!!e}}}),H._fromList=ne,H.from=function(e,t){return D(H,e,t)},H.fromWeb=function(e,t){return ce().newStreamReadableFromReadableStream(e,t)},H.toWeb=function(e,t){return ce().newReadableStreamFromStreamReadable(e,t)},H.wrap=function(e,t){var r,n;return new H({objectMode:null===(r=null!==(n=e.readableObjectMode)&&void 0!==n?n:e.objectMode)||void 0===r||r,...t,destroy(t,r){E.destroyer(e,t),r(t)}}).wrap(e)}},7631(e,t,r){"use strict";var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})};Object.defineProperty(t,"__esModule",{value:!0}),t.SocksClientError=t.SocksClient=void 0;const i=r(4434),o=r(9278),s=r(7575),a=r(5438),c=r(7130),l=r(7736),u=r(3763);Object.defineProperty(t,"SocksClientError",{enumerable:!0,get:function(){return u.SocksClientError}});const d=r(9424);class h extends i.EventEmitter{constructor(e){super(),this.options=Object.assign({},e),(0,c.validateSocksClientOptions)(e),this.setState(a.SocksClientState.Created)}static createConnection(e,t){return new Promise((r,n)=>{try{(0,c.validateSocksClientOptions)(e,["connect"])}catch(e){return"function"==typeof t?(t(e),r(e)):n(e)}const i=new h(e);i.connect(e.existing_socket),i.once("established",e=>{i.removeAllListeners(),"function"==typeof t?(t(null,e),r(e)):r(e)}),i.once("error",e=>{i.removeAllListeners(),"function"==typeof t?(t(e),r(e)):n(e)})})}static createConnectionChain(e,t){return new Promise((r,i)=>n(this,void 0,void 0,function*(){try{(0,c.validateSocksClientChainOptions)(e)}catch(e){return"function"==typeof t?(t(e),r(e)):i(e)}e.randomizeChain&&(0,u.shuffleArray)(e.proxies);try{let n;for(let t=0;t<e.proxies.length;t++){const r=e.proxies[t],i=t===e.proxies.length-1?e.destination:{host:e.proxies[t+1].host||e.proxies[t+1].ipaddress,port:e.proxies[t+1].port},o=yield h.createConnection({command:"connect",proxy:r,destination:i,existing_socket:n});n=n||o.socket}"function"==typeof t?(t(null,{socket:n}),r({socket:n})):r({socket:n})}catch(e){"function"==typeof t?(t(e),r(e)):i(e)}}))}static createUDPFrame(e){const t=new s.SmartBuffer;return t.writeUInt16BE(0),t.writeUInt8(e.frameNumber||0),o.isIPv4(e.remoteHost.host)?(t.writeUInt8(a.Socks5HostType.IPv4),t.writeUInt32BE((0,c.ipv4ToInt32)(e.remoteHost.host))):o.isIPv6(e.remoteHost.host)?(t.writeUInt8(a.Socks5HostType.IPv6),t.writeBuffer((0,c.ipToBuffer)(e.remoteHost.host))):(t.writeUInt8(a.Socks5HostType.Hostname),t.writeUInt8(Buffer.byteLength(e.remoteHost.host)),t.writeString(e.remoteHost.host)),t.writeUInt16BE(e.remoteHost.port),t.writeBuffer(e.data),t.toBuffer()}static parseUDPFrame(e){const t=s.SmartBuffer.fromBuffer(e);t.readOffset=2;const r=t.readUInt8(),n=t.readUInt8();let i;i=n===a.Socks5HostType.IPv4?(0,c.int32ToIpv4)(t.readUInt32BE()):n===a.Socks5HostType.IPv6?d.Address6.fromByteArray(Array.from(t.readBuffer(16))).canonicalForm():t.readString(t.readUInt8());return{frameNumber:r,remoteHost:{host:i,port:t.readUInt16BE()},data:t.readBuffer()}}setState(e){this.state!==a.SocksClientState.Error&&(this.state=e)}connect(e){this.onDataReceived=e=>this.onDataReceivedHandler(e),this.onClose=()=>this.onCloseHandler(),this.onError=e=>this.onErrorHandler(e),this.onConnect=()=>this.onConnectHandler();const t=setTimeout(()=>this.onEstablishedTimeout(),this.options.timeout||a.DEFAULT_TIMEOUT);t.unref&&"function"==typeof t.unref&&t.unref(),this.socket=e||new o.Socket,this.socket.once("close",this.onClose),this.socket.once("error",this.onError),this.socket.once("connect",this.onConnect),this.socket.on("data",this.onDataReceived),this.setState(a.SocksClientState.Connecting),this.receiveBuffer=new l.ReceiveBuffer,e?this.socket.emit("connect"):(this.socket.connect(this.getSocketOptions()),void 0!==this.options.set_tcp_nodelay&&null!==this.options.set_tcp_nodelay&&this.socket.setNoDelay(!!this.options.set_tcp_nodelay)),this.prependOnceListener("established",e=>{setImmediate(()=>{if(this.receiveBuffer.length>0){const t=this.receiveBuffer.get(this.receiveBuffer.length);e.socket.emit("data",t)}e.socket.resume()})})}getSocketOptions(){return Object.assign(Object.assign({},this.options.socket_options),{host:this.options.proxy.host||this.options.proxy.ipaddress,port:this.options.proxy.port})}onEstablishedTimeout(){this.state!==a.SocksClientState.Established&&this.state!==a.SocksClientState.BoundWaitingForConnection&&this.closeSocket(a.ERRORS.ProxyConnectionTimedOut)}onConnectHandler(){this.setState(a.SocksClientState.Connected),4===this.options.proxy.type?this.sendSocks4InitialHandshake():this.sendSocks5InitialHandshake(),this.setState(a.SocksClientState.SentInitialHandshake)}onDataReceivedHandler(e){this.receiveBuffer.append(e),this.processData()}processData(){for(;this.state!==a.SocksClientState.Established&&this.state!==a.SocksClientState.Error&&this.receiveBuffer.length>=this.nextRequiredPacketBufferSize;)if(this.state===a.SocksClientState.SentInitialHandshake)4===this.options.proxy.type?this.handleSocks4FinalHandshakeResponse():this.handleInitialSocks5HandshakeResponse();else if(this.state===a.SocksClientState.SentAuthentication)this.handleInitialSocks5AuthenticationHandshakeResponse();else if(this.state===a.SocksClientState.SentFinalHandshake)this.handleSocks5FinalHandshakeResponse();else{if(this.state!==a.SocksClientState.BoundWaitingForConnection){this.closeSocket(a.ERRORS.InternalError);break}4===this.options.proxy.type?this.handleSocks4IncomingConnectionResponse():this.handleSocks5IncomingConnectionResponse()}}onCloseHandler(){this.closeSocket(a.ERRORS.SocketClosed)}onErrorHandler(e){this.closeSocket(e.message)}removeInternalSocketHandlers(){this.socket.pause(),this.socket.removeListener("data",this.onDataReceived),this.socket.removeListener("close",this.onClose),this.socket.removeListener("error",this.onError),this.socket.removeListener("connect",this.onConnect)}closeSocket(e){this.state!==a.SocksClientState.Error&&(this.setState(a.SocksClientState.Error),this.socket.destroy(),this.removeInternalSocketHandlers(),this.emit("error",new u.SocksClientError(e,this.options)))}sendSocks4InitialHandshake(){const e=this.options.proxy.userId||"",t=new s.SmartBuffer;t.writeUInt8(4),t.writeUInt8(a.SocksCommand[this.options.command]),t.writeUInt16BE(this.options.destination.port),o.isIPv4(this.options.destination.host)?(t.writeBuffer((0,c.ipToBuffer)(this.options.destination.host)),t.writeStringNT(e)):(t.writeUInt8(0),t.writeUInt8(0),t.writeUInt8(0),t.writeUInt8(1),t.writeStringNT(e),t.writeStringNT(this.options.destination.host)),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks4Response,this.socket.write(t.toBuffer())}handleSocks4FinalHandshakeResponse(){const e=this.receiveBuffer.get(8);if(e[1]!==a.Socks4Response.Granted)this.closeSocket(`${a.ERRORS.Socks4ProxyRejectedConnection} - (${a.Socks4Response[e[1]]})`);else if(a.SocksCommand[this.options.command]===a.SocksCommand.bind){const t=s.SmartBuffer.fromBuffer(e);t.readOffset=2;const r={port:t.readUInt16BE(),host:(0,c.int32ToIpv4)(t.readUInt32BE())};"0.0.0.0"===r.host&&(r.host=this.options.proxy.ipaddress),this.setState(a.SocksClientState.BoundWaitingForConnection),this.emit("bound",{remoteHost:r,socket:this.socket})}else this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{socket:this.socket})}handleSocks4IncomingConnectionResponse(){const e=this.receiveBuffer.get(8);if(e[1]!==a.Socks4Response.Granted)this.closeSocket(`${a.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${a.Socks4Response[e[1]]})`);else{const t=s.SmartBuffer.fromBuffer(e);t.readOffset=2;const r={port:t.readUInt16BE(),host:(0,c.int32ToIpv4)(t.readUInt32BE())};this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket})}}sendSocks5InitialHandshake(){const e=new s.SmartBuffer,t=[a.Socks5Auth.NoAuth];(this.options.proxy.userId||this.options.proxy.password)&&t.push(a.Socks5Auth.UserPass),void 0!==this.options.proxy.custom_auth_method&&t.push(this.options.proxy.custom_auth_method),e.writeUInt8(5),e.writeUInt8(t.length);for(const r of t)e.writeUInt8(r);this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse,this.socket.write(e.toBuffer()),this.setState(a.SocksClientState.SentInitialHandshake)}handleInitialSocks5HandshakeResponse(){const e=this.receiveBuffer.get(2);5!==e[0]?this.closeSocket(a.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion):e[1]===a.SOCKS5_NO_ACCEPTABLE_AUTH?this.closeSocket(a.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType):e[1]===a.Socks5Auth.NoAuth?(this.socks5ChosenAuthType=a.Socks5Auth.NoAuth,this.sendSocks5CommandRequest()):e[1]===a.Socks5Auth.UserPass?(this.socks5ChosenAuthType=a.Socks5Auth.UserPass,this.sendSocks5UserPassAuthentication()):e[1]===this.options.proxy.custom_auth_method?(this.socks5ChosenAuthType=this.options.proxy.custom_auth_method,this.sendSocks5CustomAuthentication()):this.closeSocket(a.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType)}sendSocks5UserPassAuthentication(){const e=this.options.proxy.userId||"",t=this.options.proxy.password||"",r=new s.SmartBuffer;r.writeUInt8(1),r.writeUInt8(Buffer.byteLength(e)),r.writeString(e),r.writeUInt8(Buffer.byteLength(t)),r.writeString(t),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse,this.socket.write(r.toBuffer()),this.setState(a.SocksClientState.SentAuthentication)}sendSocks5CustomAuthentication(){return n(this,void 0,void 0,function*(){this.nextRequiredPacketBufferSize=this.options.proxy.custom_auth_response_size,this.socket.write(yield this.options.proxy.custom_auth_request_handler()),this.setState(a.SocksClientState.SentAuthentication)})}handleSocks5CustomAuthHandshakeResponse(e){return n(this,void 0,void 0,function*(){return yield this.options.proxy.custom_auth_response_handler(e)})}handleSocks5AuthenticationNoAuthHandshakeResponse(e){return n(this,void 0,void 0,function*(){return 0===e[1]})}handleSocks5AuthenticationUserPassHandshakeResponse(e){return n(this,void 0,void 0,function*(){return 0===e[1]})}handleInitialSocks5AuthenticationHandshakeResponse(){return n(this,void 0,void 0,function*(){this.setState(a.SocksClientState.ReceivedAuthenticationResponse);let e=!1;this.socks5ChosenAuthType===a.Socks5Auth.NoAuth?e=yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===a.Socks5Auth.UserPass?e=yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2)):this.socks5ChosenAuthType===this.options.proxy.custom_auth_method&&(e=yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size))),e?this.sendSocks5CommandRequest():this.closeSocket(a.ERRORS.Socks5AuthenticationFailed)})}sendSocks5CommandRequest(){const e=new s.SmartBuffer;e.writeUInt8(5),e.writeUInt8(a.SocksCommand[this.options.command]),e.writeUInt8(0),o.isIPv4(this.options.destination.host)?(e.writeUInt8(a.Socks5HostType.IPv4),e.writeBuffer((0,c.ipToBuffer)(this.options.destination.host))):o.isIPv6(this.options.destination.host)?(e.writeUInt8(a.Socks5HostType.IPv6),e.writeBuffer((0,c.ipToBuffer)(this.options.destination.host))):(e.writeUInt8(a.Socks5HostType.Hostname),e.writeUInt8(this.options.destination.host.length),e.writeString(this.options.destination.host)),e.writeUInt16BE(this.options.destination.port),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.socket.write(e.toBuffer()),this.setState(a.SocksClientState.SentFinalHandshake)}handleSocks5FinalHandshakeResponse(){const e=this.receiveBuffer.peek(5);if(5!==e[0]||e[1]!==a.Socks5Response.Granted)this.closeSocket(`${a.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${a.Socks5Response[e[1]]}`);else{const t=e[3];let r,n;if(t===a.Socks5HostType.IPv4){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:(0,c.int32ToIpv4)(n.readUInt32BE()),port:n.readUInt16BE()},"0.0.0.0"===r.host&&(r.host=this.options.proxy.ipaddress)}else if(t===a.Socks5HostType.Hostname){const t=e[4],i=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(t);if(this.receiveBuffer.length<i)return void(this.nextRequiredPacketBufferSize=i);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(i).slice(5)),r={host:n.readString(t),port:n.readUInt16BE()}}else if(t===a.Socks5HostType.IPv6){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:d.Address6.fromByteArray(Array.from(n.readBuffer(16))).canonicalForm(),port:n.readUInt16BE()}}this.setState(a.SocksClientState.ReceivedFinalResponse),a.SocksCommand[this.options.command]===a.SocksCommand.connect?(this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket})):a.SocksCommand[this.options.command]===a.SocksCommand.bind?(this.setState(a.SocksClientState.BoundWaitingForConnection),this.nextRequiredPacketBufferSize=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader,this.emit("bound",{remoteHost:r,socket:this.socket})):a.SocksCommand[this.options.command]===a.SocksCommand.associate&&(this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket}))}}handleSocks5IncomingConnectionResponse(){const e=this.receiveBuffer.peek(5);if(5!==e[0]||e[1]!==a.Socks5Response.Granted)this.closeSocket(`${a.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${a.Socks5Response[e[1]]}`);else{const t=e[3];let r,n;if(t===a.Socks5HostType.IPv4){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:(0,c.int32ToIpv4)(n.readUInt32BE()),port:n.readUInt16BE()},"0.0.0.0"===r.host&&(r.host=this.options.proxy.ipaddress)}else if(t===a.Socks5HostType.Hostname){const t=e[4],i=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(t);if(this.receiveBuffer.length<i)return void(this.nextRequiredPacketBufferSize=i);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(i).slice(5)),r={host:n.readString(t),port:n.readUInt16BE()}}else if(t===a.Socks5HostType.IPv6){const e=a.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;if(this.receiveBuffer.length<e)return void(this.nextRequiredPacketBufferSize=e);n=s.SmartBuffer.fromBuffer(this.receiveBuffer.get(e).slice(4)),r={host:d.Address6.fromByteArray(Array.from(n.readBuffer(16))).canonicalForm(),port:n.readUInt16BE()}}this.setState(a.SocksClientState.Established),this.removeInternalSocketHandlers(),this.emit("established",{remoteHost:r,socket:this.socket})}}get socksClientOptions(){return Object.assign({},this.options)}}t.SocksClient=h},7687(e,t,r){"use strict";const n=r(857),i=r(2018),o=r(5884),{env:s}=process;let a;function c(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function l(e,t){if(0===a)return 0;if(o("color=16m")||o("color=full")||o("color=truecolor"))return 3;if(o("color=256"))return 2;if(e&&!t&&void 0===a)return 0;const r=a||0;if("dumb"===s.TERM)return r;if("win32"===process.platform){const e=n.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in s)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some(e=>e in s)||"codeship"===s.CI_NAME?1:r;if("TEAMCITY_VERSION"in s)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(s.TEAMCITY_VERSION)?1:0;if("truecolor"===s.COLORTERM)return 3;if("TERM_PROGRAM"in s){const e=parseInt((s.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(s.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(s.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(s.TERM)||"COLORTERM"in s?1:r}o("no-color")||o("no-colors")||o("color=false")||o("color=never")?a=0:(o("color")||o("colors")||o("color=true")||o("color=always"))&&(a=1),"FORCE_COLOR"in s&&(a="true"===s.FORCE_COLOR?1:"false"===s.FORCE_COLOR?0:0===s.FORCE_COLOR.length?1:Math.min(parseInt(s.FORCE_COLOR,10),3)),e.exports={supportsColor:function(e){return c(l(e,e&&e.isTTY))},stdout:c(l(!0,i.isatty(1))),stderr:c(l(!0,i.isatty(2)))}},7699(e,t,r){"use strict";const n=r(1060);n.createWebSocketStream=r(3719),n.Server=r(1722),n.Receiver=r(6286),n.Sender=r(914),n.WebSocket=n,n.WebSocketServer=n.Server,e.exports=n},7732(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0});const a=r(8600),c=s(r(6887)),l={set:a.setInterval,clear:a.clearInterval},u={set:(e,t)=>setInterval(e,t),clear:e=>clearInterval(e)};t.default=e=>{switch(e){case"native":return u;case"worker":return l;default:return!c.default||c.isWebWorker||c.isReactNativeBrowser?u:l}}},7736(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ReceiveBuffer=void 0;t.ReceiveBuffer=class{constructor(e=4096){this.buffer=Buffer.allocUnsafe(e),this.offset=0,this.originalSize=e}get length(){return this.offset}append(e){if(!Buffer.isBuffer(e))throw new Error("Attempted to append a non-buffer instance to ReceiveBuffer.");if(this.offset+e.length>=this.buffer.length){const t=this.buffer;this.buffer=Buffer.allocUnsafe(Math.max(this.buffer.length+this.originalSize,this.buffer.length+e.length)),t.copy(this.buffer)}return e.copy(this.buffer,this.offset),this.offset+=e.length}peek(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");return this.buffer.slice(0,e)}get(e){if(e>this.offset)throw new Error("Attempted to read beyond the bounds of the managed internal data.");const t=Buffer.allocUnsafe(e);return this.buffer.slice(0,e).copy(t),this.buffer.copyWithin(0,e,e+this.offset-e),this.offset-=e,t}}},7758(e,t,r){const n=r(4422),{ArrayIsArray:i,Promise:o,SymbolAsyncIterator:s,SymbolDispose:a}=r(4134),c=r(6238),{once:l}=r(7760),u=r(5896),d=r(3370),{aggregateTwoErrors:h,codes:{ERR_INVALID_ARG_TYPE:p,ERR_INVALID_RETURN_VALUE:f,ERR_MISSING_ARGS:g,ERR_STREAM_DESTROYED:m,ERR_STREAM_PREMATURE_CLOSE:b},AbortError:y}=r(6371),{validateFunction:_,validateAbortSignal:v}=r(277),{isIterable:S,isReadable:w,isReadableNodeStream:k,isNodeStream:E,isTransformStream:I,isWebStream:T,isReadableStream:O,isReadableFinished:C}=r(6115),x=globalThis.AbortController||r(6584).AbortController;let A,P,R;function M(e,t,r){let n=!1;e.on("close",()=>{n=!0});return{destroy:t=>{n||(n=!0,u.destroyer(e,t||new m("pipe")))},cleanup:c(e,{readable:t,writable:r},e=>{n=!e})}}function B(e){if(S(e))return e;if(k(e))return async function*(e){P||(P=r(7576));yield*P.prototype[s].call(e)}(e);throw new p("val",["Readable","Iterable","AsyncIterable"],e)}async function N(e,t,r,{end:n}){let i,s=null;const a=e=>{if(e&&(i=e),s){const e=s;s=null,e()}},l=()=>new o((e,t)=>{i?t(i):s=()=>{i?t(i):e()}});t.on("drain",a);const u=c(t,{readable:!1},a);try{t.writableNeedDrain&&await l();for await(const r of e)t.write(r)||await l();n&&(t.end(),await l()),r()}catch(e){r(i!==e?h(i,e):e)}finally{u(),t.off("drain",a)}}async function j(e,t,r,{end:n}){I(t)&&(t=t.writable);const i=t.getWriter();try{for await(const t of e)await i.ready,i.write(t).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(e){try{await i.abort(e),r(e)}catch(e){r(e)}}}function D(e,t,o){if(1===e.length&&i(e[0])&&(e=e[0]),e.length<2)throw new g("streams");const s=new x,c=s.signal,l=null==o?void 0:o.signal,u=[];function h(){F(new y)}let m,b,_;v(l,"options.signal"),R=R||r(7760).addAbortListener,l&&(m=R(l,h));const C=[];let P,D=0;function U(e){F(e,0===--D)}function F(e,r){var i;if(!e||b&&"ERR_STREAM_PREMATURE_CLOSE"!==b.code||(b=e),b||r){for(;C.length;)C.shift()(b);null===(i=m)||void 0===i||i[a](),s.abort(),r&&(b||u.forEach(e=>e()),n.nextTick(t,b,_))}}for(let H=0;H<e.length;H++){const z=e[H],q=H<e.length-1,G=H>0,K=q||!1!==(null==o?void 0:o.end),Q=H===e.length-1;if(E(z)){if(K){const{destroy:Y,cleanup:Z}=M(z,q,G);C.push(Y),w(z)&&Q&&u.push(Z)}function $(e){e&&"AbortError"!==e.name&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code&&U(e)}z.on("error",$),w(z)&&Q&&u.push(()=>{z.removeListener("error",$)})}if(0===H)if("function"==typeof z){if(P=z({signal:c}),!S(P))throw new f("Iterable, AsyncIterable or Stream","source",P)}else P=S(z)||k(z)||I(z)?z:d.from(z);else if("function"==typeof z){var V;if(I(P))P=B(null===(V=P)||void 0===V?void 0:V.readable);else P=B(P);if(P=z(P,{signal:c}),q){if(!S(P,!0))throw new f("AsyncIterable",`transform[${H-1}]`,P)}else{var W;A||(A=r(6524));const J=new A({objectMode:!0}),X=null===(W=P)||void 0===W?void 0:W.then;if("function"==typeof X)D++,X.call(P,e=>{_=e,null!=e&&J.write(e),K&&J.end(),n.nextTick(U)},e=>{J.destroy(e),n.nextTick(U,e)});else if(S(P,!0))D++,N(P,J,U,{end:K});else{if(!O(P)&&!I(P))throw new f("AsyncIterable or Promise","destination",P);{const re=P.readable||P;D++,N(re,J,U,{end:K})}}P=J;const{destroy:ee,cleanup:te}=M(P,!1,!0);C.push(ee),Q&&u.push(te)}}else if(E(z)){if(k(P)){D+=2;const ne=L(P,z,U,{end:K});w(z)&&Q&&u.push(ne)}else if(I(P)||O(P)){const ie=P.readable||P;D++,N(ie,z,U,{end:K})}else{if(!S(P))throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],P);D++,N(P,z,U,{end:K})}P=z}else if(T(z)){if(k(P))D++,j(B(P),z,U,{end:K});else if(O(P)||S(P))D++,j(P,z,U,{end:K});else{if(!I(P))throw new p("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],P);D++,j(P.readable,z,U,{end:K})}P=z}else P=d.from(z)}return(null!=c&&c.aborted||null!=l&&l.aborted)&&n.nextTick(h),P}function L(e,t,r,{end:i}){let o=!1;if(t.on("close",()=>{o||r(new b)}),e.pipe(t,{end:!1}),i){function s(){o=!0,t.end()}C(e)?n.nextTick(s):e.once("end",s)}else r();return c(e,{readable:!0,writable:!1},t=>{const n=e._readableState;t&&"ERR_STREAM_PREMATURE_CLOSE"===t.code&&n&&n.ended&&!n.errored&&!n.errorEmitted?e.once("end",r).once("error",r):r(t)}),c(t,{readable:!1,writable:!0},r)}e.exports={pipelineImpl:D,pipeline:function(...e){return D(e,l(function(e){return _(e[e.length-1],"streams[stream.length - 1]"),e.pop()}(e)))}}},7760(e,t,r){"use strict";const n=r(181),{format:i,inspect:o}=r(9231),{codes:{ERR_INVALID_ARG_TYPE:s}}=r(6371),{kResistStopPropagation:a,AggregateError:c,SymbolDispose:l}=r(4134),u=globalThis.AbortSignal||r(6584).AbortSignal,d=globalThis.AbortController||r(6584).AbortController,h=Object.getPrototypeOf(async function(){}).constructor,p=globalThis.Blob||n.Blob,f="undefined"!=typeof p?function(e){return e instanceof p}:function(e){return!1},g=(e,t)=>{if(void 0!==e&&(null===e||"object"!=typeof e||!("aborted"in e)))throw new s(t,"AbortSignal",e)};e.exports={AggregateError:c,kEmptyObject:Object.freeze({}),once(e){let t=!1;return function(...r){t||(t=!0,e.apply(this,r))}},createDeferredPromise:function(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}},promisify:e=>new Promise((t,r)=>{e((e,...n)=>e?r(e):t(...n))}),debuglog:()=>function(){},format:i,inspect:o,types:{isAsyncFunction:e=>e instanceof h,isArrayBufferView:e=>ArrayBuffer.isView(e)},isBlob:f,deprecate:(e,t)=>e,addAbortListener:r(4434).addAbortListener||function(e,t){if(void 0===e)throw new s("signal","AbortSignal",e);let r;return g(e,"signal"),((e,t)=>{if("function"!=typeof e)throw new s(t,"Function",e)})(t,"listener"),e.aborted?queueMicrotask(()=>t()):(e.addEventListener("abort",t,{__proto__:null,once:!0,[a]:!0}),r=()=>{e.removeEventListener("abort",t)}),{__proto__:null,[l](){var e;null===(e=r)||void 0===e||e()}}},AbortSignalAny:u.any||function(e){if(1===e.length)return e[0];const t=new d,r=()=>t.abort();return e.forEach(e=>{g(e,"signals"),e.addEventListener("abort",r,{once:!0})}),t.signal.addEventListener("abort",()=>{e.forEach(e=>e.removeEventListener("abort",r))},{once:!0}),t.signal}},e.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")},7813(e,t,r){"use strict";const{Buffer:n}=r(181),i=Symbol.for("BufferList");function o(e){if(!(this instanceof o))return new o(e);o._init.call(this,e)}o._init=function(e){Object.defineProperty(this,i,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)},o.prototype._new=function(e){return new o(e)},o.prototype._offset=function(e){if(0===e)return[0,0];let t=0;for(let r=0;r<this._bufs.length;r++){const n=t+this._bufs[r].length;if(e<n||r===this._bufs.length-1)return[r,e-t];t=n}},o.prototype._reverseOffset=function(e){const t=e[0];let r=e[1];for(let e=0;e<t;e++)r+=this._bufs[e].length;return r},o.prototype.getBuffers=function(){return this._bufs},o.prototype.get=function(e){if(e>this.length||e<0)return;const t=this._offset(e);return this._bufs[t[0]][t[1]]},o.prototype.slice=function(e,t){return"number"==typeof e&&e<0&&(e+=this.length),"number"==typeof t&&t<0&&(t+=this.length),this.copy(null,0,e,t)},o.prototype.copy=function(e,t,r,i){if(("number"!=typeof r||r<0)&&(r=0),("number"!=typeof i||i>this.length)&&(i=this.length),r>=this.length)return e||n.alloc(0);if(i<=0)return e||n.alloc(0);const o=!!e,s=this._offset(r),a=i-r;let c=a,l=o&&t||0,u=s[1];if(0===r&&i===this.length){if(!o)return 1===this._bufs.length?this._bufs[0]:n.concat(this._bufs,this.length);for(let t=0;t<this._bufs.length;t++)this._bufs[t].copy(e,l),l+=this._bufs[t].length;return e}if(c<=this._bufs[s[0]].length-u)return o?this._bufs[s[0]].copy(e,t,u,u+c):this._bufs[s[0]].slice(u,u+c);o||(e=n.allocUnsafe(a));for(let t=s[0];t<this._bufs.length;t++){const r=this._bufs[t].length-u;if(!(c>r)){this._bufs[t].copy(e,l,u,u+c),l+=r;break}this._bufs[t].copy(e,l,u),l+=r,c-=r,u&&(u=0)}return e.length>l?e.slice(0,l):e},o.prototype.shallowSlice=function(e,t){if(e=e||0,t="number"!=typeof t?this.length:t,e<0&&(e+=this.length),t<0&&(t+=this.length),e===t)return this._new();const r=this._offset(e),n=this._offset(t),i=this._bufs.slice(r[0],n[0]+1);return 0===n[1]?i.pop():i[i.length-1]=i[i.length-1].slice(0,n[1]),0!==r[1]&&(i[0]=i[0].slice(r[1])),this._new(i)},o.prototype.toString=function(e,t,r){return this.slice(t,r).toString(e)},o.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;){if(!(e>=this._bufs[0].length)){this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift()}return this},o.prototype.duplicate=function(){const e=this._new();for(let t=0;t<this._bufs.length;t++)e.append(this._bufs[t]);return e},o.prototype.append=function(e){return this._attach(e,o.prototype._appendBuffer)},o.prototype.prepend=function(e){return this._attach(e,o.prototype._prependBuffer,!0)},o.prototype._attach=function(e,t,r){if(null==e)return this;if(e.buffer)t.call(this,n.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e)){const[n,i]=r?[e.length-1,-1]:[0,1];for(let o=n;o>=0&&o<e.length;o+=i)this._attach(e[o],t,r)}else if(this._isBufferList(e)){const[n,i]=r?[e._bufs.length-1,-1]:[0,1];for(let o=n;o>=0&&o<e._bufs.length;o+=i)this._attach(e._bufs[o],t,r)}else"number"==typeof e&&(e=e.toString()),t.call(this,n.from(e));return this},o.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length},o.prototype._prependBuffer=function(e){this._bufs.unshift(e),this.length+=e.length},o.prototype.indexOf=function(e,t,r){if(void 0===r&&"string"==typeof t&&(r=t,t=void 0),"function"==typeof e||Array.isArray(e))throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if("number"==typeof e?e=n.from([e]):"string"==typeof e?e=n.from(e,r):this._isBufferList(e)?e=e.slice():Array.isArray(e.buffer)?e=n.from(e.buffer,e.byteOffset,e.byteLength):n.isBuffer(e)||(e=n.from(e)),t=Number(t||0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;const i=this._offset(t);let o=i[0],s=i[1];for(;o<this._bufs.length;o++){const t=this._bufs[o];for(;s<t.length;){if(t.length-s>=e.length){const r=t.indexOf(e,s);if(-1!==r)return this._reverseOffset([o,r]);s=t.length-e.length+1}else{const t=this._reverseOffset([o,s]);if(this._match(t,e))return t;s++}}s=0}return-1},o.prototype._match=function(e,t){if(this.length-e<t.length)return!1;for(let r=0;r<t.length;r++)if(this.get(e+r)!==t[r])return!1;return!0},function(){const e={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readBigInt64BE:8,readBigInt64LE:8,readBigUInt64BE:8,readBigUInt64LE:8,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(const t in e)(function(t){o.prototype[t]=null===e[t]?function(e,r){return this.slice(e,e+r)[t](0,r)}:function(r=0){return this.slice(r,r+e[t])[t](0)}})(t)}(),o.prototype._isBufferList=function(e){return e instanceof o||o.isBufferList(e)},o.isBufferList=function(e){return null!=e&&e[i]},e.exports=o},7830(e,t,r){"use strict";const{pipeline:n}=r(7758),i=r(3370),{destroyer:o}=r(5896),{isNodeStream:s,isReadable:a,isWritable:c,isWebStream:l,isTransformStream:u,isWritableStream:d,isReadableStream:h}=r(6115),{AbortError:p,codes:{ERR_INVALID_ARG_VALUE:f,ERR_MISSING_ARGS:g}}=r(6371),m=r(6238);e.exports=function(...e){if(0===e.length)throw new g("streams");if(1===e.length)return i.from(e[0]);const t=[...e];if("function"==typeof e[0]&&(e[0]=i.from(e[0])),"function"==typeof e[e.length-1]){const t=e.length-1;e[t]=i.from(e[t])}for(let r=0;r<e.length;++r)if(s(e[r])||l(e[r])){if(r<e.length-1&&!(a(e[r])||h(e[r])||u(e[r])))throw new f(`streams[${r}]`,t[r],"must be readable");if(r>0&&!(c(e[r])||d(e[r])||u(e[r])))throw new f(`streams[${r}]`,t[r],"must be writable")}let r,b,y,_,v;const S=e[0],w=n(e,function(e){const t=_;_=null,t?t(e):e?v.destroy(e):E||k||v.destroy()}),k=!!(c(S)||d(S)||u(S)),E=!!(a(w)||h(w)||u(w));if(v=new i({writableObjectMode:!(null==S||!S.writableObjectMode),readableObjectMode:!(null==w||!w.readableObjectMode),writable:k,readable:E}),k){if(s(S))v._write=function(e,t,n){S.write(e,t)?n():r=n},v._final=function(e){S.end(),b=e},S.on("drain",function(){if(r){const e=r;r=null,e()}});else if(l(S)){const e=(u(S)?S.writable:S).getWriter();v._write=async function(t,r,n){try{await e.ready,e.write(t).catch(()=>{}),n()}catch(e){n(e)}},v._final=async function(t){try{await e.ready,e.close().catch(()=>{}),b=t}catch(e){t(e)}}}const e=u(w)?w.readable:w;m(e,()=>{if(b){const e=b;b=null,e()}})}if(E)if(s(w))w.on("readable",function(){if(y){const e=y;y=null,e()}}),w.on("end",function(){v.push(null)}),v._read=function(){for(;;){const e=w.read();if(null===e)return void(y=v._read);if(!v.push(e))return}};else if(l(w)){const e=(u(w)?w.readable:w).getReader();v._read=async function(){for(;;)try{const{value:t,done:r}=await e.read();if(!v.push(t))return;if(r)return void v.push(null)}catch{return}}}return v._destroy=function(e,t){e||null===_||(e=new p),y=null,r=null,b=null,null===_?t(e):(_=t,s(w)&&o(w,e))},v}},7833(e,t,r){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let n=0,i=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(n++,"%c"===e&&(i=n))}),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r(736)(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},7927(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.SpatialAwarenessPlugin=void 0;const a=s(r(7562)),c=r(6117),l=r(1554),u=r(4997),d=r(5389),h=r(7136),p=r(4386),f=r(5471),g=r(2846),m=r(7279),b=r(3874),{deviceManager:y,systemManager:_}=a.default,v="tracking-zone:",S="global-tracker";class w extends a.ScryptedDeviceBase{trackingEngine=null;trackingState;alertManager;mqttPublisher=null;devices=new Map;storageSettings=new c.StorageSettings(this,{topology:{title:"Camera Topology",type:"string",description:"JSON configuration of camera relationships",hide:!0},floorPlanImage:{title:"Floor Plan Image",type:"string",hide:!0},correlationWindow:{title:"Correlation Window (seconds)",type:"number",defaultValue:30,description:"Maximum time to wait for an object to appear on connected camera",group:"Tracking"},correlationThreshold:{title:"Correlation Confidence Threshold",type:"number",defaultValue:.6,description:"Minimum confidence (0-1) for automatic object correlation",group:"Tracking"},lostTimeout:{title:"Lost Object Timeout (seconds)",type:"number",defaultValue:300,description:"Time before marking a tracked object as lost",group:"Tracking"},useVisualMatching:{title:"Use Visual Matching",type:"boolean",defaultValue:!0,description:"Use visual embeddings for object correlation (requires compatible detectors)",group:"Tracking"},enableMqtt:{title:"Enable MQTT",type:"boolean",defaultValue:!1,group:"MQTT Integration"},mqttBroker:{title:"MQTT Broker URL",type:"string",placeholder:"mqtt://localhost:1883",group:"MQTT Integration"},mqttUsername:{title:"MQTT Username",type:"string",group:"MQTT Integration"},mqttPassword:{title:"MQTT Password",type:"password",group:"MQTT Integration"},mqttBaseTopic:{title:"MQTT Base Topic",type:"string",defaultValue:"scrypted/spatial-awareness",group:"MQTT Integration"},enableAlerts:{title:"Enable Alerts",type:"boolean",defaultValue:!0,group:"Alerts"},defaultNotifier:{title:"Default Notifier",type:"device",deviceFilter:`interfaces.includes('${a.ScryptedInterface.Notifier}')`,group:"Alerts"},trackedCameras:{title:"Cameras to Track",type:"device",multiple:!0,deviceFilter:`interfaces.includes('${a.ScryptedInterface.ObjectDetector}')`,group:"Cameras",description:"Select cameras with object detection to track"},alertRules:{title:"Alert Rules",type:"string",hide:!0}});constructor(e){super(e),this.trackingState=new d.TrackingState(this.storage,this.console),this.alertManager=new p.AlertManager(this.console,this.storage),process.nextTick(()=>this.initialize())}async initialize(){this.console.log("Initializing Spatial Awareness Plugin"),await y.onDeviceDiscovered({nativeId:S,name:"Global Object Tracker",type:a.ScryptedDeviceType.Sensor,interfaces:[a.ScryptedInterface.OccupancySensor,a.ScryptedInterface.Settings,a.ScryptedInterface.Readme]});const e=this.storage.getItem("topology");if(e)try{const t=JSON.parse(e);await this.startTrackingEngine(t)}catch(e){this.console.error("Failed to parse topology:",e)}const t=this.storage.getItem("alertRules");if(t)try{const e=JSON.parse(t);this.alertManager.setRules(e)}catch(e){this.console.error("Failed to parse alert rules:",e),this.alertManager.setRules((0,u.createDefaultRules)())}else this.alertManager.setRules((0,u.createDefaultRules)());this.storageSettings.values.enableMqtt&&await this.initializeMqtt(),this.console.log("Spatial Awareness Plugin initialized")}async initializeMqtt(){const e=this.storageSettings.values.mqttBroker;if(!e)return void this.console.warn("MQTT enabled but no broker URL configured");const t={broker:e,username:this.storageSettings.values.mqttUsername,password:this.storageSettings.values.mqttPassword,baseTopic:this.storageSettings.values.mqttBaseTopic||"scrypted/spatial-awareness"};this.mqttPublisher=new m.MqttPublisher(t,this.console),await this.mqttPublisher.connect(),this.trackingState.onStateChange(e=>{this.mqttPublisher?.publishState(e)}),this.console.log("MQTT publisher initialized")}async startTrackingEngine(e){this.trackingEngine&&await this.trackingEngine.stopTracking();const t={correlationWindow:1e3*(this.storageSettings.values.correlationWindow||30),correlationThreshold:this.storageSettings.values.correlationThreshold||.6,lostTimeout:1e3*(this.storageSettings.values.lostTimeout||300),useVisualMatching:this.storageSettings.values.useVisualMatching??!0};this.trackingEngine=new h.TrackingEngine(e,this.trackingState,this.alertManager,t,this.console),await this.trackingEngine.startTracking(),this.console.log("Tracking engine started")}async getDevice(e){let t=this.devices.get(e);return t||(e===S?t=new f.GlobalTrackerSensor(this,e,this.trackingState):e.startsWith(v)&&(t=new g.TrackingZone(this,e,this.trackingState)),t&&this.devices.set(e,t)),t}async releaseDevice(e,t){this.devices.delete(t)}async getCreateDeviceSettings(){return[{key:"name",title:"Zone Name",description:"Name for this tracking zone",type:"string"},{key:"type",title:"Zone Type",type:"string",choices:["entry","exit","dwell","restricted"],value:"entry"},{key:"cameras",title:"Cameras",type:"device",multiple:!0,deviceFilter:`interfaces.includes('${a.ScryptedInterface.ObjectDetector}')`}]}async createDevice(e){const t=v+Date.now().toString();return await y.onDeviceDiscovered({nativeId:t,name:e.name||"Tracking Zone",type:a.ScryptedDeviceType.Sensor,interfaces:[a.ScryptedInterface.OccupancySensor,a.ScryptedInterface.MotionSensor,a.ScryptedInterface.Settings]}),this.storage.setItem(`zone:${t}`,JSON.stringify({type:e.type,cameras:e.cameras})),t}async getSettings(){const e=await this.storageSettings.getSettings();e.push({key:"topologyEditor",title:"Topology Editor",type:"html",value:'\n <style>\n .sa-modal-overlay {\n display: none;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n background: rgba(0, 0, 0, 0.85);\n z-index: 10000;\n align-items: center;\n justify-content: center;\n }\n .sa-modal-overlay.active {\n display: flex;\n }\n .sa-modal-container {\n width: 95vw;\n height: 90vh;\n max-width: 1600px;\n background: #1a1a2e;\n border-radius: 12px;\n overflow: hidden;\n position: relative;\n box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5);\n }\n .sa-modal-close {\n position: absolute;\n top: 10px;\n right: 10px;\n z-index: 10001;\n background: #e94560;\n color: white;\n border: none;\n width: 36px;\n height: 36px;\n border-radius: 50%;\n font-size: 20px;\n cursor: pointer;\n display: flex;\n align-items: center;\n justify-content: center;\n }\n .sa-modal-close:hover {\n background: #ff6b6b;\n }\n .sa-modal-iframe {\n width: 100%;\n height: 100%;\n border: none;\n }\n .sa-open-btn {\n background: linear-gradient(135deg, #e94560 0%, #0f3460 100%);\n color: white;\n border: none;\n padding: 14px 28px;\n border-radius: 8px;\n font-size: 15px;\n font-weight: 600;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n gap: 10px;\n transition: transform 0.2s, box-shadow 0.2s;\n }\n .sa-open-btn:hover {\n transform: translateY(-2px);\n box-shadow: 0 8px 20px rgba(233, 69, 96, 0.4);\n }\n .sa-btn-container {\n padding: 20px;\n background: #16213e;\n border-radius: 8px;\n text-align: center;\n }\n .sa-btn-desc {\n color: #888;\n margin-bottom: 15px;\n font-size: 14px;\n }\n </style>\n <div class="sa-btn-container">\n <p class="sa-btn-desc">Configure camera positions, connections, and transit times</p>\n <button class="sa-open-btn" onclick="document.getElementById(\'sa-topology-modal\').classList.add(\'active\')">\n <span>⚙</span> Open Topology Editor\n </button>\n </div>\n <div id="sa-topology-modal" class="sa-modal-overlay" onclick="if(event.target===this)this.classList.remove(\'active\')">\n <div class="sa-modal-container">\n <button class="sa-modal-close" onclick="document.getElementById(\'sa-topology-modal\').classList.remove(\'active\')">×</button>\n <iframe class="sa-modal-iframe" src="/endpoint/@blueharford/scrypted-spatial-awareness/ui/editor"></iframe>\n </div>\n </div>\n ',group:"Topology"});const t=this.trackingState.getActiveCount();e.push({key:"status",title:"Tracking Status",type:"string",readonly:!0,value:this.trackingEngine?`Active: Tracking ${t} object${1!==t?"s":""}`:"Not configured - add cameras and configure topology",group:"Status"});const r=this.alertManager.getRecentAlerts(5);return r.length>0&&e.push({key:"recentAlerts",title:"Recent Alerts",type:"string",readonly:!0,value:r.map(e=>`${e.type}: ${e.message}`).join("\n"),group:"Status"}),e}async putSetting(e,t){if(await this.storageSettings.putSetting(e,t),"trackedCameras"===e||"correlationWindow"===e||"correlationThreshold"===e||"lostTimeout"===e||"useVisualMatching"===e){const e=this.storage.getItem("topology");if(e)try{const t=JSON.parse(e);await this.startTrackingEngine(t)}catch(e){this.console.error("Failed to restart tracking engine:",e)}}"enableMqtt"!==e&&"mqttBroker"!==e&&"mqttUsername"!==e&&"mqttPassword"!==e&&"mqttBaseTopic"!==e||(this.mqttPublisher&&(this.mqttPublisher.disconnect(),this.mqttPublisher=null),this.storageSettings.values.enableMqtt&&await this.initializeMqtt())}async onRequest(e,t){const r=new URL(e.url,"http://localhost").pathname;try{if(r.endsWith("/api/tracked-objects"))return this.handleTrackedObjectsRequest(e,t);if(r.match(/\/api\/journey\/[\w-]+$/)){const e=r.split("/").pop();return this.handleJourneyRequest(e,t)}if(r.endsWith("/api/topology"))return this.handleTopologyRequest(e,t);if(r.endsWith("/api/alerts"))return this.handleAlertsRequest(e,t);if(r.endsWith("/api/floor-plan"))return this.handleFloorPlanRequest(e,t);if(r.endsWith("/ui/editor")||r.endsWith("/ui/editor/"))return this.serveEditorUI(t);if(r.includes("/ui/"))return this.serveStaticFile(r,t);t.send(JSON.stringify({name:"Spatial Awareness Plugin",version:"0.1.0",endpoints:{api:{trackedObjects:"/api/tracked-objects",journey:"/api/journey/{globalId}",topology:"/api/topology",alerts:"/api/alerts",floorPlan:"/api/floor-plan"},ui:{editor:"/ui/editor"}}}),{headers:{"Content-Type":"application/json"}})}catch(e){this.console.error("HTTP request error:",e),t.send(JSON.stringify({error:e.message}),{code:500,headers:{"Content-Type":"application/json"}})}}handleTrackedObjectsRequest(e,t){const r=this.trackingState.getAllObjects();t.send(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}handleJourneyRequest(e,t){const r=this.trackingState.getObject(e);r?t.send(JSON.stringify({globalId:r.globalId,className:r.className,label:r.label,journey:r.journey,sightings:r.sightings.map(e=>({cameraId:e.cameraId,cameraName:e.cameraName,timestamp:e.timestamp})),firstSeen:r.firstSeen,lastSeen:r.lastSeen,state:r.state}),{headers:{"Content-Type":"application/json"}}):t.send(JSON.stringify({error:"Object not found"}),{code:404,headers:{"Content-Type":"application/json"}})}handleTopologyRequest(e,t){if("GET"===e.method){const e=this.storage.getItem("topology"),r=e?JSON.parse(e):(0,l.createEmptyTopology)();t.send(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}else if("PUT"===e.method||"POST"===e.method)try{const r=JSON.parse(e.body);this.storage.setItem("topology",JSON.stringify(r)),this.startTrackingEngine(r),t.send(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(e){t.send(JSON.stringify({error:"Invalid topology JSON"}),{code:400,headers:{"Content-Type":"application/json"}})}}handleAlertsRequest(e,t){const r=this.alertManager.getRecentAlerts();t.send(JSON.stringify(r),{headers:{"Content-Type":"application/json"}})}handleFloorPlanRequest(e,t){if("GET"===e.method){const e=this.storage.getItem("floorPlanImage");e?t.send(JSON.stringify({imageData:e}),{headers:{"Content-Type":"application/json"}}):t.send(JSON.stringify({imageData:null}),{headers:{"Content-Type":"application/json"}})}else if("POST"===e.method)try{const r=JSON.parse(e.body);this.storage.setItem("floorPlanImage",r.imageData),t.send(JSON.stringify({success:!0}),{headers:{"Content-Type":"application/json"}})}catch(e){t.send(JSON.stringify({error:"Invalid request body"}),{code:400,headers:{"Content-Type":"application/json"}})}}serveEditorUI(e){e.send(b.EDITOR_HTML,{headers:{"Content-Type":"text/html"}})}serveStaticFile(e,t){t.send("Not found",{code:404})}async getReadmeMarkdown(){return"\n# Spatial Awareness Plugin\n\nThis plugin enables cross-camera object tracking across your entire NVR system.\n\n## Features\n\n- **Cross-Camera Tracking**: Correlate objects as they move between cameras\n- **Journey History**: Complete path history for each tracked object\n- **Entry/Exit Detection**: Know when objects enter or leave your property\n- **Visual Floor Plan**: Configure camera topology with a visual editor\n- **MQTT Integration**: Export tracking data to Home Assistant\n- **REST API**: Query tracked objects and journeys programmatically\n- **Smart Alerts**: Get notified about property entry/exit, unusual paths, and more\n\n## Setup\n\n1. **Add Cameras**: Select cameras with object detection in the plugin settings\n2. **Configure Topology**: Define camera relationships and transit times\n3. **Enable Integrations**: Optionally enable MQTT for Home Assistant\n4. **Create Zones**: Add tracking zones for specific area monitoring\n\n## API Endpoints\n\n- `GET /api/tracked-objects` - List all tracked objects\n- `GET /api/journey/{id}` - Get journey for specific object\n- `GET /api/topology` - Get camera topology\n- `PUT /api/topology` - Update camera topology\n- `GET /api/alerts` - Get recent alerts\n\n## Visual Editor\n\nAccess the visual topology editor at `/ui/editor` to configure camera relationships using a floor plan.\n\n## Alert Types\n\n- **Property Entry**: Object entered the property\n- **Property Exit**: Object exited the property\n- **Unusual Path**: Object took an unexpected route\n- **Dwell Time**: Object lingered too long in an area\n- **Restricted Zone**: Object entered a restricted area\n"}getTrackingState(){return this.trackingState}getAlertManager(){return this.alertManager}getTopology(){const e=this.storage.getItem("topology");return e?JSON.parse(e):null}}t.SpatialAwarenessPlugin=w,t.default=w},7969(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=r(4478),i={objectMode:!0},o={clean:!0};t.default=class{options;_inflights;constructor(e){this.options=e||{},this.options={...o,...e},this._inflights=new Map}put(e,t){return this._inflights.set(e.messageId,e),t&&t(),this}createStream(){const e=new n.Readable(i),t=[];let r=!1,o=0;return this._inflights.forEach((e,r)=>{t.push(e)}),e._read=()=>{!r&&o<t.length?e.push(t[o++]):e.push(null)},e.destroy=t=>{if(!r)return r=!0,setTimeout(()=>{e.emit("close")},0),e},e}del(e,t){const r=this._inflights.get(e.messageId);return r?(this._inflights.delete(e.messageId),t(null,r)):t&&t(new Error("missing packet")),this}get(e,t){const r=this._inflights.get(e.messageId);return r?t(null,r):t&&t(new Error("missing packet")),this}close(e){this.options.clean&&(this._inflights=null),e&&e()}}},8194(e,t,r){"use strict";r.d(t,{CD:()=>S});var n,i=(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=function(){function e(e,t){this.ee=1,this.u=void 0,this.p=void 0,this.K=void 0,this.N=void 0,this.rr=void 0,this.u=e,this.p=t}return e.prototype.L=function(){var e=this;if(1===e.ee&&e.rr.rr===e)e=e.N;else if(e.K)for(e=e.K;e.N;)e=e.N;else{for(var t=e.rr;t.K===e;)t=(e=t).rr;e=t}return e},e.prototype.m=function(){var e=this;if(e.N){for(e=e.N;e.K;)e=e.K;return e}for(var t=e.rr;t.N===e;)t=(e=t).rr;return e.N!==t?t:e},e.prototype.ne=function(){var e=this.rr,t=this.N,r=t.K;return e.rr===this?e.rr=t:e.K===this?e.K=t:e.N=t,t.rr=e,t.K=this,this.rr=t,this.N=r,r&&(r.rr=this),t},e.prototype.te=function(){var e=this.rr,t=this.K,r=t.N;return e.rr===this?e.rr=t:e.K===this?e.K=t:e.N=t,t.rr=e,t.N=this,this.rr=t,this.K=r,r&&(r.rr=this),t},e}(),s=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t.tr=1,t}return i(t,e),t.prototype.ne=function(){var t=e.prototype.ne.call(this);return this.ie(),t.ie(),t},t.prototype.te=function(){var t=e.prototype.te.call(this);return this.ie(),t.ie(),t},t.prototype.ie=function(){this.tr=1,this.K&&(this.tr+=this.K.tr),this.N&&(this.tr+=this.N.tr)},t}(o),a=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),c=function(){function e(e){void 0===e&&(e=0),this.iteratorType=e}return e.prototype.equals=function(e){return this.o===e.o},e}(),l=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return a(t,e),t}(function(){function e(){this.M=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this.M},enumerable:!1,configurable:!0}),e.prototype.size=function(){return this.M},e.prototype.empty=function(){return 0===this.M},e}());function u(){throw new RangeError("Iterator access denied!")}var d=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),h=function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},p=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};const f=function(e){function t(t,r){void 0===t&&(t=function(e,t){return e<t?-1:e>t?1:0}),void 0===r&&(r=!1);var n=e.call(this)||this;return n.W=void 0,n.$=t,r?(n.re=s,n.v=function(e,t,r){var n=this.se(e,t,r);if(n){for(var i=n.rr;i!==this.h;)i.tr+=1,i=i.rr;var o=this.fe(n);if(o){var s=o,a=s.parentNode,c=s.grandParent,l=s.curNode;a.ie(),c.ie(),l.ie()}}return this.M},n.G=function(e){for(var t=this.he(e);t!==this.h;)t.tr-=1,t=t.rr}):(n.re=o,n.v=function(e,t,r){var n=this.se(e,t,r);return n&&this.fe(n),this.M},n.G=n.he),n.h=new n.re,n}return d(t,e),t.prototype.U=function(e,t){for(var r=this.h;e;){var n=this.$(e.u,t);if(n<0)e=e.N;else{if(!(n>0))return e;r=e,e=e.K}}return r},t.prototype.X=function(e,t){for(var r=this.h;e;){this.$(e.u,t)<=0?e=e.N:(r=e,e=e.K)}return r},t.prototype.Y=function(e,t){for(var r=this.h;e;){var n=this.$(e.u,t);if(n<0)r=e,e=e.N;else{if(!(n>0))return e;e=e.K}}return r},t.prototype.Z=function(e,t){for(var r=this.h;e;){this.$(e.u,t)<0?(r=e,e=e.N):e=e.K}return r},t.prototype.ue=function(e){for(;;){var t,r=e.rr;if(r===this.h)return;if(1===e.ee)return void(e.ee=0);if(e===r.K)if(1===(t=r.N).ee)t.ee=0,r.ee=1,r===this.W?this.W=r.ne():r.ne();else{if(t.N&&1===t.N.ee)return t.ee=r.ee,r.ee=0,t.N.ee=0,void(r===this.W?this.W=r.ne():r.ne());t.K&&1===t.K.ee?(t.ee=1,t.K.ee=0,t.te()):(t.ee=1,e=r)}else if(1===(t=r.K).ee)t.ee=0,r.ee=1,r===this.W?this.W=r.te():r.te();else{if(t.K&&1===t.K.ee)return t.ee=r.ee,r.ee=0,t.K.ee=0,void(r===this.W?this.W=r.te():r.te());t.N&&1===t.N.ee?(t.ee=1,t.N.ee=0,t.ne()):(t.ee=1,e=r)}}},t.prototype.he=function(e){var t,r;if(1===this.M)return this.clear(),this.h;for(var n=e;n.K||n.N;){if(n.N)for(n=n.N;n.K;)n=n.K;else n=n.K;t=h([n.u,e.u],2),e.u=t[0],n.u=t[1],r=h([n.p,e.p],2),e.p=r[0],n.p=r[1],e=n}this.h.K===n?this.h.K=n.rr:this.h.N===n&&(this.h.N=n.rr),this.ue(n);var i=n.rr;return n===i.K?i.K=void 0:i.N=void 0,this.M-=1,this.W.ee=0,i},t.prototype.ae=function(e,t){return void 0!==e&&(!!this.ae(e.K,t)||(!!t(e)||this.ae(e.N,t)))},t.prototype.fe=function(e){for(;;){var t=e.rr;if(0===t.ee)return;var r=t.rr;if(t===r.K){if((n=r.N)&&1===n.ee){if(n.ee=t.ee=0,r===this.W)return;r.ee=1,e=r;continue}if(e===t.N){if(e.ee=0,e.K&&(e.K.rr=t),e.N&&(e.N.rr=r),t.N=e.K,r.K=e.N,e.K=t,e.N=r,r===this.W)this.W=e,this.h.rr=e;else(i=r.rr).K===r?i.K=e:i.N=e;return e.rr=r.rr,t.rr=e,r.rr=e,r.ee=1,{parentNode:t,grandParent:r,curNode:e}}t.ee=0,r===this.W?this.W=r.te():r.te(),r.ee=1}else{var n;if((n=r.K)&&1===n.ee){if(n.ee=t.ee=0,r===this.W)return;r.ee=1,e=r;continue}if(e===t.K){var i;if(e.ee=0,e.K&&(e.K.rr=r),e.N&&(e.N.rr=t),r.N=e.K,t.K=e.N,e.K=r,e.N=t,r===this.W)this.W=e,this.h.rr=e;else(i=r.rr).K===r?i.K=e:i.N=e;return e.rr=r.rr,t.rr=e,r.rr=e,r.ee=1,{parentNode:t,grandParent:r,curNode:e}}t.ee=0,r===this.W?this.W=r.ne():r.ne(),r.ee=1}return}},t.prototype.se=function(e,t,r){if(void 0===this.W)return this.M+=1,this.W=new this.re(e,t),this.W.ee=0,this.W.rr=this.h,this.h.rr=this.W,this.h.K=this.W,void(this.h.N=this.W);var n,i=this.h.K,o=this.$(i.u,e);if(0!==o){if(o>0)i.K=new this.re(e,t),i.K.rr=i,n=i.K,this.h.K=n;else{var s=this.h.N,a=this.$(s.u,e);if(0===a)return void(s.p=t);if(a<0)s.N=new this.re(e,t),s.N.rr=s,n=s.N,this.h.N=n;else{if(void 0!==r){var c=r.o;if(c!==this.h){var l=this.$(c.u,e);if(0===l)return void(c.p=t);if(l>0){var u=c.L(),d=this.$(u.u,e);if(0===d)return void(u.p=t);d<0&&(n=new this.re(e,t),void 0===u.N?(u.N=n,n.rr=u):(c.K=n,n.rr=c))}}}if(void 0===n)for(n=this.W;;){var h=this.$(n.u,e);if(h>0){if(void 0===n.K){n.K=new this.re(e,t),n.K.rr=n,n=n.K;break}n=n.K}else{if(!(h<0))return void(n.p=t);if(void 0===n.N){n.N=new this.re(e,t),n.N.rr=n,n=n.N;break}n=n.N}}}}return this.M+=1,n}i.p=t},t.prototype.g=function(e,t){for(;e;){var r=this.$(e.u,t);if(r<0)e=e.N;else{if(!(r>0))return e;e=e.K}}return e||this.h},t.prototype.clear=function(){this.M=0,this.W=void 0,this.h.rr=void 0,this.h.K=this.h.N=void 0},t.prototype.updateKeyByIterator=function(e,t){var r=e.o;if(r===this.h&&u(),1===this.M)return r.u=t,!0;if(r===this.h.K)return this.$(r.m().u,t)>0&&(r.u=t,!0);if(r===this.h.N)return this.$(r.L().u,t)<0&&(r.u=t,!0);var n=r.L().u;if(this.$(n,t)>=0)return!1;var i=r.m().u;return!(this.$(i,t)<=0)&&(r.u=t,!0)},t.prototype.eraseElementByPos=function(e){if(e<0||e>this.M-1)throw new RangeError;var t=0,r=this;return this.ae(this.W,function(n){return e===t?(r.G(n),!0):(t+=1,!1)}),this.M},t.prototype.eraseElementByKey=function(e){if(0===this.M)return!1;var t=this.g(this.W,e);return t!==this.h&&(this.G(t),!0)},t.prototype.eraseElementByIterator=function(e){var t=e.o;t===this.h&&u();var r=void 0===t.N;return 0===e.iteratorType?r&&e.next():r&&void 0!==t.K||e.next(),this.G(t),e},t.prototype.forEach=function(e){var t,r,n=0;try{for(var i=p(this),o=i.next();!o.done;o=i.next()){e(o.value,n++,this)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},t.prototype.getElementByPos=function(e){var t,r,n;if(e<0||e>this.M-1)throw new RangeError;var i=0;try{for(var o=p(this),s=o.next();!s.done;s=o.next()){var a=s.value;if(i===e){n=a;break}i+=1}}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}return n},t.prototype.getHeight=function(){if(0===this.M)return 0;var e=function(t){return t?Math.max(e(t.K),e(t.N))+1:0};return e(this.W)},t}(l);var g=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}();const m=function(e){function t(t,r,n){var i=e.call(this,n)||this;return i.o=t,i.h=r,0===i.iteratorType?(i.pre=function(){return this.o===this.h.K&&u(),this.o=this.o.L(),this},i.next=function(){return this.o===this.h&&u(),this.o=this.o.m(),this}):(i.pre=function(){return this.o===this.h.N&&u(),this.o=this.o.m(),this},i.next=function(){return this.o===this.h&&u(),this.o=this.o.L(),this}),i}return g(t,e),Object.defineProperty(t.prototype,"index",{get:function(){var e=this.o,t=this.h.rr;if(e===this.h)return t?t.tr-1:0;var r=0;for(e.K&&(r+=e.K.tr);e!==t;){var n=e.rr;e===n.N&&(r+=1,n.K&&(r+=n.K.tr)),e=n}return r},enumerable:!1,configurable:!0}),t}(c);var b=function(){var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},e(t,r)};return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}}(),y=function(e,t){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(e){return function(t){return c([e,t])}}function c(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}},_=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},v=function(e){function t(t,r,n,i){var o=e.call(this,t,r,i)||this;return o.container=n,o}return b(t,e),Object.defineProperty(t.prototype,"pointer",{get:function(){return this.o===this.h&&u(),this.o.u},enumerable:!1,configurable:!0}),t.prototype.copy=function(){return new t(this.o,this.h,this.container,this.iteratorType)},t}(m);const S=function(e){function t(t,r,n){void 0===t&&(t=[]);var i=e.call(this,r,n)||this,o=i;return t.forEach(function(e){o.insert(e)}),i}return b(t,e),t.prototype.P=function(e){return y(this,function(t){switch(t.label){case 0:return void 0===e?[2]:[5,_(this.P(e.K))];case 1:return t.sent(),[4,e.u];case 2:return t.sent(),[5,_(this.P(e.N))];case 3:return t.sent(),[2]}})},t.prototype.begin=function(){return new v(this.h.K||this.h,this.h,this)},t.prototype.end=function(){return new v(this.h,this.h,this)},t.prototype.rBegin=function(){return new v(this.h.N||this.h,this.h,this,1)},t.prototype.rEnd=function(){return new v(this.h,this.h,this,1)},t.prototype.front=function(){return this.h.K?this.h.K.u:void 0},t.prototype.back=function(){return this.h.N?this.h.N.u:void 0},t.prototype.insert=function(e,t){return this.v(e,void 0,t)},t.prototype.find=function(e){var t=this.g(this.W,e);return new v(t,this.h,this)},t.prototype.lowerBound=function(e){var t=this.U(this.W,e);return new v(t,this.h,this)},t.prototype.upperBound=function(e){var t=this.X(this.W,e);return new v(t,this.h,this)},t.prototype.reverseLowerBound=function(e){var t=this.Y(this.W,e);return new v(t,this.h,this)},t.prototype.reverseUpperBound=function(e){var t=this.Z(this.W,e);return new v(t,this.h,this)},t.prototype.union=function(e){var t=this;return e.forEach(function(e){t.insert(e)}),this.M},t.prototype[Symbol.iterator]=function(){return this.P(this.W)},t}(f)},8203(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.streamBuilder=t.browserStreamBuilder=void 0;const i=r(181),o=n(r(7699)),s=n(r(5753)),a=r(4478),c=n(r(6887)),l=r(2635),u=(0,s.default)("mqttjs:ws"),d=["rejectUnauthorized","ca","cert","key","pfx","passphrase"];function h(e,t){let r=`${e.protocol}://${e.hostname}:${e.port}${e.path}`;return"function"==typeof e.transformWsUrl&&(r=e.transformWsUrl(r,e,t)),r}function p(e){const t=e;return e.port||("wss"===e.protocol?t.port=443:t.port=80),e.path||(t.path="/"),e.wsOptions||(t.wsOptions={}),c.default||e.forceNativeWebSocket||"wss"!==e.protocol||d.forEach(r=>{Object.prototype.hasOwnProperty.call(e,r)&&!Object.prototype.hasOwnProperty.call(e.wsOptions,r)&&(t.wsOptions[r]=e[r])}),t}t.streamBuilder=(e,t)=>{u("streamBuilder");const r=p(t);r.hostname=r.hostname||r.host||"localhost";const n=h(r,e),i=function(e,t,r){u("createWebSocket"),u(`protocol: ${r.protocolId} ${r.protocolVersion}`);const n="MQIsdp"===r.protocolId&&3===r.protocolVersion?"mqttv3.1":"mqtt";let i;return u(`creating new Websocket for url: ${t} and protocol: ${n}`),i=r.createWebsocket?r.createWebsocket(t,[n],r):new o.default(t,[n],r.wsOptions),i}(0,n,r),s=o.default.createWebSocketStream(i,r.wsOptions);return s.url=n,i.on("close",()=>{s.destroy()}),s};t.browserStreamBuilder=(e,t)=>{let r;u("browserStreamBuilder");const n=function(e){const t=p(e);if(t.hostname||(t.hostname=t.host),!t.hostname){if("undefined"==typeof document)throw new Error("Could not determine host. Specify host manually.");const e=new URL(document.URL);t.hostname=e.hostname,t.port||(t.port=Number(e.port))}return void 0===t.objectMode&&(t.objectMode=!(!0===t.binary||void 0===t.binary)),t}(t),o=n.browserBufferSize||524288,s=t.browserBufferTimeout||1e3,c=!t.objectMode,d=function(e,t){const r="MQIsdp"===t.protocolId&&3===t.protocolVersion?"mqttv3.1":"mqtt",n=h(t,e);let i;return i=t.createWebsocket?t.createWebsocket(n,[r],t):new WebSocket(n,[r]),i.binaryType="arraybuffer",i}(e,t),f=function(e,t,r){const n=new a.Transform({objectMode:e.objectMode});return n._write=t,n._flush=r,n}(t,function e(t,r,n){if(d.bufferedAmount>o)return void setTimeout(e,s,t,r,n);c&&"string"==typeof t&&(t=i.Buffer.from(t,"utf8"));try{d.send(t)}catch(e){return n(e)}n()},function(e){d.close(),e()});t.objectMode||(f._writev=l.writev.bind(f)),f.on("close",()=>{d.close()});const g="undefined"!=typeof d.addEventListener;function m(){u("WebSocket onOpen"),r instanceof l.BufferedDuplex&&r.socketReady()}function b(e){u("WebSocket onClose",e),r.end(),r.destroy()}function y(e){u("WebSocket onError",e);const t=new Error("WebSocket error");t.event=e,r.destroy(t)}async function _(e){if(!f||!f.readable||!f.writable)return;let{data:t}=e;t=t instanceof ArrayBuffer?i.Buffer.from(t):t instanceof Blob?i.Buffer.from(await new Response(t).arrayBuffer()):i.Buffer.from(t,"utf8"),f.push(t)}return d.readyState===d.OPEN?(r=f,r.socket=d):(r=new l.BufferedDuplex(t,f,d),g?d.addEventListener("open",m):d.onopen=m),g?(d.addEventListener("close",b),d.addEventListener("error",y),d.addEventListener("message",_)):(d.onclose=b,d.onerror=y,d.onmessage=_),r}},8237(e,t,r){"use strict";const{tokenChars:n}=r(5880);e.exports={parse:function(e){const t=new Set;let r=-1,i=-1,o=0;for(;o<e.length;o++){const s=e.charCodeAt(o);if(-1===i&&1===n[s])-1===r&&(r=o);else if(0===o||32!==s&&9!==s){if(44!==s)throw new SyntaxError(`Unexpected character at index ${o}`);{if(-1===r)throw new SyntaxError(`Unexpected character at index ${o}`);-1===i&&(i=o);const n=e.slice(r,i);if(t.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}}else-1===i&&-1!==r&&(i=o)}if(-1===r||-1!==i)throw new SyntaxError("Unexpected end of input");const s=e.slice(r,o);if(t.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return t.add(s),t}}},8584(e,t,r){"use strict";const n=r(4422),{ArrayPrototypeSlice:i,Error:o,FunctionPrototypeSymbolHasInstance:s,ObjectDefineProperty:a,ObjectDefineProperties:c,ObjectSetPrototypeOf:l,StringPrototypeToLowerCase:u,Symbol:d,SymbolHasInstance:h}=r(4134);e.exports=B,B.WritableState=R;const{EventEmitter:p}=r(4434),f=r(4259).Stream,{Buffer:g}=r(181),m=r(5896),{addAbortSignal:b}=r(4147),{getHighWaterMark:y,getDefaultHighWaterMark:_}=r(5291),{ERR_INVALID_ARG_TYPE:v,ERR_METHOD_NOT_IMPLEMENTED:S,ERR_MULTIPLE_CALLBACK:w,ERR_STREAM_CANNOT_PIPE:k,ERR_STREAM_DESTROYED:E,ERR_STREAM_ALREADY_FINISHED:I,ERR_STREAM_NULL_VALUES:T,ERR_STREAM_WRITE_AFTER_END:O,ERR_UNKNOWN_ENCODING:C}=r(6371).codes,{errorOrDestroy:x}=m;function A(){}l(B.prototype,f.prototype),l(B,f);const P=d("kOnFinished");function R(e,t,n){"boolean"!=typeof n&&(n=t instanceof r(3370)),this.objectMode=!(!e||!e.objectMode),n&&(this.objectMode=this.objectMode||!(!e||!e.writableObjectMode)),this.highWaterMark=e?y(this,e,"writableHighWaterMark",n):_(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;const i=!(!e||!1!==e.decodeStrings);this.decodeStrings=!i,this.defaultEncoding=e&&e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=L.bind(void 0,t),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,M(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!e||!1!==e.emitClose,this.autoDestroy=!e||!1!==e.autoDestroy,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[P]=[]}function M(e){e.buffered=[],e.bufferedIndex=0,e.allBuffers=!0,e.allNoop=!0}function B(e){const t=this instanceof r(3370);if(!t&&!s(B,this))return new B(e);this._writableState=new R(e,this,t),e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final),"function"==typeof e.construct&&(this._construct=e.construct),e.signal&&b(e.signal,this)),f.call(this,e),m.construct(this,()=>{const e=this._writableState;e.writing||V(this,e),z(this,e)})}function N(e,t,r,i){const o=e._writableState;if("function"==typeof r)i=r,r=o.defaultEncoding;else{if(r){if("buffer"!==r&&!g.isEncoding(r))throw new C(r)}else r=o.defaultEncoding;"function"!=typeof i&&(i=A)}if(null===t)throw new T;if(!o.objectMode)if("string"==typeof t)!1!==o.decodeStrings&&(t=g.from(t,r),r="buffer");else if(t instanceof g)r="buffer";else{if(!f._isUint8Array(t))throw new v("chunk",["string","Buffer","Uint8Array"],t);t=f._uint8ArrayToBuffer(t),r="buffer"}let s;return o.ending?s=new O:o.destroyed&&(s=new E("write")),s?(n.nextTick(i,s),x(e,s,!0),s):(o.pendingcb++,function(e,t,r,n,i){const o=t.objectMode?1:r.length;t.length+=o;const s=t.length<t.highWaterMark;s||(t.needDrain=!0);t.writing||t.corked||t.errored||!t.constructed?(t.buffered.push({chunk:r,encoding:n,callback:i}),t.allBuffers&&"buffer"!==n&&(t.allBuffers=!1),t.allNoop&&i!==A&&(t.allNoop=!1)):(t.writelen=o,t.writecb=i,t.writing=!0,t.sync=!0,e._write(r,n,t.onwrite),t.sync=!1);return s&&!t.errored&&!t.destroyed}(e,o,t,r,i))}function j(e,t,r,n,i,o,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new E("write")):r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function D(e,t,r,n){--t.pendingcb,n(r),$(t),x(e,r)}function L(e,t){const r=e._writableState,i=r.sync,o=r.writecb;"function"==typeof o?(r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,t?(t.stack,r.errored||(r.errored=t),e._readableState&&!e._readableState.errored&&(e._readableState.errored=t),i?n.nextTick(D,e,r,t,o):D(e,r,t,o)):(r.buffered.length>r.bufferedIndex&&V(e,r),i?null!==r.afterWriteTickInfo&&r.afterWriteTickInfo.cb===o?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:o,stream:e,state:r},n.nextTick(U,r.afterWriteTickInfo)):F(e,r,1,o))):x(e,new w)}function U({stream:e,state:t,count:r,cb:n}){return t.afterWriteTickInfo=null,F(e,t,r,n)}function F(e,t,r,n){for(!t.ending&&!e.destroyed&&0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"));r-- >0;)t.pendingcb--,n();t.destroyed&&$(t),z(e,t)}function $(e){if(e.writing)return;for(let r=e.bufferedIndex;r<e.buffered.length;++r){var t;const{chunk:n,callback:i}=e.buffered[r],o=e.objectMode?1:n.length;e.length-=o,i(null!==(t=e.errored)&&void 0!==t?t:new E("write"))}const r=e[P].splice(0);for(let t=0;t<r.length;t++){var n;r[t](null!==(n=e.errored)&&void 0!==n?n:new E("end"))}M(e)}function V(e,t){if(t.corked||t.bufferProcessing||t.destroyed||!t.constructed)return;const{buffered:r,bufferedIndex:n,objectMode:o}=t,s=r.length-n;if(!s)return;let a=n;if(t.bufferProcessing=!0,s>1&&e._writev){t.pendingcb-=s-1;const n=t.allNoop?A:e=>{for(let t=a;t<r.length;++t)r[t].callback(e)},o=t.allNoop&&0===a?r:i(r,a);o.allBuffers=t.allBuffers,j(e,t,!0,t.length,o,"",n),M(t)}else{do{const{chunk:n,encoding:i,callback:s}=r[a];r[a++]=null;j(e,t,!1,o?1:n.length,n,i,s)}while(a<r.length&&!t.writing);a===r.length?M(t):a>256?(r.splice(0,a),t.bufferedIndex=0):t.bufferedIndex=a}t.bufferProcessing=!1}function W(e){return e.ending&&!e.destroyed&&e.constructed&&0===e.length&&!e.errored&&0===e.buffered.length&&!e.finished&&!e.writing&&!e.errorEmitted&&!e.closeEmitted}function H(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.finalCalled=!0,function(e,t){let r=!1;function i(i){if(r)x(e,null!=i?i:w());else if(r=!0,t.pendingcb--,i){const r=t[P].splice(0);for(let e=0;e<r.length;e++)r[e](i);x(e,i,t.sync)}else W(t)&&(t.prefinished=!0,e.emit("prefinish"),t.pendingcb++,n.nextTick(q,e,t))}t.sync=!0,t.pendingcb++;try{e._final(i)}catch(e){i(e)}t.sync=!1}(e,t)))}function z(e,t,r){W(t)&&(H(e,t),0===t.pendingcb&&(r?(t.pendingcb++,n.nextTick((e,t)=>{W(t)?q(e,t):t.pendingcb--},e,t)):W(t)&&(t.pendingcb++,q(e,t))))}function q(e,t){t.pendingcb--,t.finished=!0;const r=t[P].splice(0);for(let e=0;e<r.length;e++)r[e]();if(e.emit("finish"),t.autoDestroy){const t=e._readableState;(!t||t.autoDestroy&&(t.endEmitted||!1===t.readable))&&e.destroy()}}R.prototype.getBuffer=function(){return i(this.buffered,this.bufferedIndex)},a(R.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}}),a(B,h,{__proto__:null,value:function(e){return!!s(this,e)||this===B&&(e&&e._writableState instanceof R)}}),B.prototype.pipe=function(){x(this,new k)},B.prototype.write=function(e,t,r){return!0===N(this,e,t,r)},B.prototype.cork=function(){this._writableState.corked++},B.prototype.uncork=function(){const e=this._writableState;e.corked&&(e.corked--,e.writing||V(this,e))},B.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=u(e)),!g.isEncoding(e))throw new C(e);return this._writableState.defaultEncoding=e,this},B.prototype._write=function(e,t,r){if(!this._writev)throw new S("_write()");this._writev([{chunk:e,encoding:t}],r)},B.prototype._writev=null,B.prototype.end=function(e,t,r){const i=this._writableState;let s;if("function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e){const r=N(this,e,t);r instanceof o&&(s=r)}return i.corked&&(i.corked=1,this.uncork()),s||(i.errored||i.ending?i.finished?s=new I("end"):i.destroyed&&(s=new E("end")):(i.ending=!0,z(this,i,!0),i.ended=!0)),"function"==typeof r&&(s||i.finished?n.nextTick(r,s):i[P].push(r)),this},c(B.prototype,{closed:{__proto__:null,get(){return!!this._writableState&&this._writableState.closed}},destroyed:{__proto__:null,get(){return!!this._writableState&&this._writableState.destroyed},set(e){this._writableState&&(this._writableState.destroyed=e)}},writable:{__proto__:null,get(){const e=this._writableState;return!(!e||!1===e.writable||e.destroyed||e.errored||e.ending||e.ended)},set(e){this._writableState&&(this._writableState.writable=!!e)}},writableFinished:{__proto__:null,get(){return!!this._writableState&&this._writableState.finished}},writableObjectMode:{__proto__:null,get(){return!!this._writableState&&this._writableState.objectMode}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return!!this._writableState&&this._writableState.ending}},writableNeedDrain:{__proto__:null,get(){const e=this._writableState;return!!e&&(!e.destroyed&&!e.ending&&e.needDrain)}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!(!1===this._writableState.writable||!this._writableState.destroyed&&!this._writableState.errored||this._writableState.finished)}}});const G=m.destroy;let K;function Q(){return void 0===K&&(K={}),K}B.prototype.destroy=function(e,t){const r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[P].length)&&n.nextTick($,r),G.call(this,e,t),this},B.prototype._undestroy=m.undestroy,B.prototype._destroy=function(e,t){t(e)},B.prototype[p.captureRejectionSymbol]=function(e){this.destroy(e)},B.fromWeb=function(e,t){return Q().newStreamWritableFromWritableStream(e,t)},B.toWeb=function(e){return Q().newWritableStreamFromStreamWritable(e)}},8600(e,t,r){"use strict";r.r(t),r.d(t,{clearInterval:()=>v,clearTimeout:()=>S,setInterval:()=>w,setTimeout:()=>k});const n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,i=536870912,o=1073741824,s=new WeakMap;var a;const c=((e,t)=>r=>{const s=t.get(r);let a=void 0===s?r.size:s<o?s+1:0;if(!r.has(a))return e(r,a);if(r.size<i){for(;r.has(a);)a=Math.floor(Math.random()*o);return e(r,a)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(a);)a=Math.floor(Math.random()*n);return e(r,a)})((a=s,(e,t)=>(a.set(e,t),t)),s),l=((e=>{})(c),((e,t,r,n)=>i=>{const o=t(i);return t=>{const i=e(t);t.addEventListener("message",({data:e})=>{const{id:t}=e;if(null!==t&&i.has(t)){const{reject:r,resolve:n}=i.get(t);i.delete(t),void 0===e.error?n(e.result):r(new Error(e.error.message))}}),n(t)&&t.start();const s=(e,n=null,o=[])=>new Promise((s,a)=>{const c=r(i);i.set(c,{reject:a,resolve:s}),null===n?t.postMessage({id:c,method:e},o):t.postMessage({id:c,method:e,params:n},o)}),a=(e,r,n=[])=>{t.postMessage({id:null,method:e,params:r},n)};let c={};for(const[e,t]of Object.entries(o))c={...c,[e]:t({call:s,notify:a})};return{...c}}})((d=new WeakMap,e=>{if(d.has(e))return d.get(e);const t=new Map;return d.set(e,t),t}),(u=new WeakMap,e=>({...e,connect:({call:e})=>async()=>{const{port1:t,port2:r}=new MessageChannel,n=await e("connect",{port:t},[t]);return u.set(r,n),r},disconnect:({call:e})=>async t=>{const r=u.get(t);if(void 0===r)throw new Error("The given port is not connected.");await e("disconnect",{portId:r})},isSupported:({call:e})=>()=>e("isSupported")})),c,e=>"function"==typeof e.start));var u,d;const h=new Map([[0,null]]),p=new Map([[0,null]]),f=(e=>t=>r=>{"symbol"==typeof e.get(r)&&(e.set(r,null),t(r).then(()=>{e.delete(r)}))})(h),g=(e=>t=>r=>{"symbol"==typeof e.get(r)&&(e.set(r,null),t(r).then(()=>{e.delete(r)}))})(p),m=((e,t)=>r=>(n,i=0,...o)=>{const s=Symbol(),a=e(t);t.set(a,s);const c=()=>r(i,a).then(()=>{const e=t.get(a);if(void 0===e)throw new Error("The timer is in an undefined state.");e===s&&(n(...o),t.get(a)===s&&c())});return c(),a})(c,h),b=((e,t)=>r=>(n,i=0,...o)=>{const s=Symbol(),a=e(t);return t.set(a,s),r(i,a).then(()=>{const e=t.get(a);if(void 0===e)throw new Error("The timer is in an undefined state.");e===s&&(t.delete(a),n(...o))}),a})(c,p),y=l({clearInterval:({call:e})=>f(t=>e("clear",{timerId:t,timerType:"interval"})),clearTimeout:({call:e})=>g(t=>e("clear",{timerId:t,timerType:"timeout"})),setInterval:({call:e})=>m((t,r)=>e("set",{delay:t,now:performance.timeOrigin+performance.now(),timerId:r,timerType:"interval"})),setTimeout:({call:e})=>b((t,r)=>e("set",{delay:t,now:performance.timeOrigin+performance.now(),timerId:r,timerType:"timeout"}))}),_=((e,t)=>{let r=null;return()=>{if(null!==r)return r;const n=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(n);return r=e(i),setTimeout(()=>URL.revokeObjectURL(i)),r}})(e=>{const t=new Worker(e);return y(t)},'(()=>{var e={455(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),l=t(c);e.addUniqueNumber=l,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o(\'The handler of the method called "\'.concat(t,\'" returned an unexpected result.\'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o(\'The requested method called "\'.concat(e,\'" is not supported.\'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o(\'The handler of the method called "\'.concat(t,\'" returned no required result.\'),e))(i);const l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,()=>{n(),t.close(),u.delete(o)}),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o(\'The specified parameter called "portId" with the given value "\'.concat(e,\'" does not identify a port connected to this worker.\'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise(e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])})){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},m=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},f=new Map,h=d(globalThis.clearTimeout,f),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=m(f,performance,globalThis.setTimeout,w),T=m(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();'),v=e=>_().clearInterval(e),S=e=>_().clearTimeout(e),w=(...e)=>_().setInterval(...e),k=(...e)=>_().setTimeout(...e)},8611(e){"use strict";e.exports=require("http")},8914(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RE_URL_WITH_PORT=t.RE_URL=t.RE_ZONE_STRING=t.RE_SUBNET_STRING=t.RE_BAD_ADDRESS=t.RE_BAD_CHARACTERS=t.TYPES=t.SCOPES=t.GROUPS=t.BITS=void 0,t.BITS=128,t.GROUPS=8,t.SCOPES={0:"Reserved",1:"Interface local",2:"Link local",4:"Admin local",5:"Site local",8:"Organization local",14:"Global",15:"Reserved"},t.TYPES={"ff01::1/128":"Multicast (All nodes on this interface)","ff01::2/128":"Multicast (All routers on this interface)","ff02::1/128":"Multicast (All nodes on this link)","ff02::2/128":"Multicast (All routers on this link)","ff05::2/128":"Multicast (All routers in this site)","ff02::5/128":"Multicast (OSPFv3 AllSPF routers)","ff02::6/128":"Multicast (OSPFv3 AllDR routers)","ff02::9/128":"Multicast (RIP routers)","ff02::a/128":"Multicast (EIGRP routers)","ff02::d/128":"Multicast (PIM routers)","ff02::16/128":"Multicast (MLDv2 reports)","ff01::fb/128":"Multicast (mDNSv6)","ff02::fb/128":"Multicast (mDNSv6)","ff05::fb/128":"Multicast (mDNSv6)","ff02::1:2/128":"Multicast (All DHCP servers and relay agents on this link)","ff05::1:2/128":"Multicast (All DHCP servers and relay agents in this site)","ff02::1:3/128":"Multicast (All DHCP servers on this link)","ff05::1:3/128":"Multicast (All DHCP servers in this site)","::/128":"Unspecified","::1/128":"Loopback","ff00::/8":"Multicast","fe80::/10":"Link-local unicast"},t.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,t.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,t.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,t.RE_ZONE_STRING=/%.*$/,t.RE_URL=/^\[{0,1}([0-9a-f:]+)\]{0,1}/,t.RE_URL_WITH_PORT=/\[([0-9a-f:]+)\]:([0-9]{1,5})/},9023(e){"use strict";e.exports=require("util")},9231(e){"use strict";e.exports={format:(e,...t)=>e.replace(/%([sdifj])/g,function(...[e,r]){const n=t.shift();if("f"===r)return n.toFixed(6);if("j"===r)return JSON.stringify(n);if("s"===r&&"object"==typeof n){return`${n.constructor!==Object?n.constructor.name:""} {}`.trim()}return n.toString()}),inspect(e){switch(typeof e){case"string":if(e.includes("'")){if(!e.includes('"'))return`"${e}"`;if(!e.includes("`")&&!e.includes("${"))return`\`${e}\``}return`'${e}'`;case"number":return isNaN(e)?"NaN":Object.is(e,-0)?String(e):e;case"bigint":return`${String(e)}n`;case"boolean":case"undefined":return String(e);case"object":return"{}"}}}},9278(e){"use strict";e.exports=require("net")},9291(e,t,r){"use strict";const n=r(8194).CD,i=r(5753)("number-allocator:trace"),o=r(5753)("number-allocator:error");function s(e,t){this.low=e,this.high=t}function a(e,t){if(!(this instanceof a))return new a(e,t);this.min=e,this.max=t,this.ss=new n([],(e,t)=>e.compare(t)),i("Create"),this.clear()}s.prototype.equals=function(e){return this.low===e.low&&this.high===e.high},s.prototype.compare=function(e){return this.low<e.low&&this.high<e.low?-1:e.low<this.low&&e.high<this.low?1:0},a.prototype.firstVacant=function(){return 0===this.ss.size()?null:this.ss.front().low},a.prototype.alloc=function(){if(0===this.ss.size())return i("alloc():empty"),null;const e=this.ss.begin(),t=e.pointer.low,r=e.pointer.high,n=t;return n+1<=r?this.ss.updateKeyByIterator(e,new s(t+1,r)):this.ss.eraseElementByPos(0),i("alloc():"+n),n},a.prototype.use=function(e){const t=new s(e,e),r=this.ss.lowerBound(t);if(!r.equals(this.ss.end())){const n=r.pointer.low,o=r.pointer.high;return r.pointer.equals(t)?(this.ss.eraseElementByIterator(r),i("use():"+e),!0):!(n>e)&&(n===e?(this.ss.updateKeyByIterator(r,new s(n+1,o)),i("use():"+e),!0):o===e?(this.ss.updateKeyByIterator(r,new s(n,o-1)),i("use():"+e),!0):(this.ss.updateKeyByIterator(r,new s(e+1,o)),this.ss.insert(new s(n,e-1)),i("use():"+e),!0))}return i("use():failed"),!1},a.prototype.free=function(e){if(e<this.min||e>this.max)return void o("free():"+e+" is out of range");const t=new s(e,e),r=this.ss.upperBound(t);if(r.equals(this.ss.end())){if(r.equals(this.ss.begin()))return void this.ss.insert(t);r.pre();const n=r.pointer.high;r.pointer.high+1===e?this.ss.updateKeyByIterator(r,new s(n,e)):this.ss.insert(t)}else if(r.equals(this.ss.begin()))if(e+1===r.pointer.low){const t=r.pointer.high;this.ss.updateKeyByIterator(r,new s(e,t))}else this.ss.insert(t);else{const n=r.pointer.low,i=r.pointer.high;r.pre();const o=r.pointer.low;r.pointer.high+1===e?e+1===n?(this.ss.eraseElementByIterator(r),this.ss.updateKeyByIterator(r,new s(o,i))):this.ss.updateKeyByIterator(r,new s(o,e)):e+1===n?(this.ss.eraseElementByIterator(r.next()),this.ss.insert(new s(e,i))):this.ss.insert(t)}i("free():"+e)},a.prototype.clear=function(){i("clear()"),this.ss.clear(),this.ss.insert(new s(this.min,this.max))},a.prototype.intervalCount=function(){return this.ss.size()},a.prototype.dump=function(){console.log("length:"+this.ss.size());for(const e of this.ss)console.log(e)},e.exports=a},9372(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||i(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0});const c=s(r(1676));t.default=c,a(r(1676),t)},9424(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&n(t,e,r);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.v6=t.AddressError=t.Address6=t.Address4=void 0;var s=r(2839);Object.defineProperty(t,"Address4",{enumerable:!0,get:function(){return s.Address4}});var a=r(6329);Object.defineProperty(t,"Address6",{enumerable:!0,get:function(){return a.Address6}});var c=r(2437);Object.defineProperty(t,"AddressError",{enumerable:!0,get:function(){return c.AddressError}});const l=o(r(465));t.v6={helpers:l}},9576(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RE_SUBNET_STRING=t.RE_ADDRESS=t.GROUPS=t.BITS=void 0,t.BITS=32,t.GROUPS=4,t.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/g,t.RE_SUBNET_STRING=/\/\d{1,2}$/},9777(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),s=0;s<r.length;s++)"default"!==r[s]&&i(t,e,r[s]);return o(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const c=a(r(1278)),l=r(4478),u=a(r(3885)),d=a(r(5753)),h=s(r(128)),p=a(r(7969)),f=a(r(6912)),g=a(r(579)),m=a(r(2639)),b=r(4723),y=r(4152),_=a(r(3175)),v=s(r(6887)),S=globalThis.setImmediate||((...e)=>{const t=e.shift();(0,b.nextTick)(()=>{t(...e)})}),w={keepalive:60,reschedulePings:!0,protocolId:"MQTT",protocolVersion:4,reconnectPeriod:1e3,connectTimeout:3e4,clean:!0,resubscribe:!0,subscribeBatchSize:null,writeCache:!0,timerVariant:"auto"};class k extends y.TypedEventEmitter{static VERSION=b.MQTTJS_VERSION;connected;disconnecting;disconnected;reconnecting;incomingStore;outgoingStore;options;queueQoSZero;_reconnectCount;log;messageIdProvider;outgoing;messageIdToTopic;noop;keepaliveManager;stream;queue;streamBuilder;_resubscribeTopics;connackTimer;reconnectTimer;_storeProcessing;_packetIdsDuringStoreProcessing;_storeProcessingQueue;_firstConnection;topicAliasRecv;topicAliasSend;_deferredReconnect;connackPacket;static defaultId(){return`mqttjs_${Math.random().toString(16).substr(2,8)}`}constructor(e,t){super(),this.options=t||{};for(const e in w)"undefined"==typeof this.options[e]?this.options[e]=w[e]:this.options[e]=t[e];this.log=this.options.log||(0,d.default)("mqttjs:client"),this.noop=this._noop.bind(this),this.log("MqttClient :: version:",k.VERSION),v.isWebWorker?this.log("MqttClient :: environment","webworker"):this.log("MqttClient :: environment",v.default?"browser":"node"),this.log("MqttClient :: options.protocol",t.protocol),this.log("MqttClient :: options.protocolVersion",t.protocolVersion),this.log("MqttClient :: options.username",t.username),this.log("MqttClient :: options.keepalive",t.keepalive),this.log("MqttClient :: options.reconnectPeriod",t.reconnectPeriod),this.log("MqttClient :: options.rejectUnauthorized",t.rejectUnauthorized),this.log("MqttClient :: options.properties.topicAliasMaximum",t.properties?t.properties.topicAliasMaximum:void 0),this.options.clientId="string"==typeof t.clientId?t.clientId:k.defaultId(),this.log("MqttClient :: clientId",this.options.clientId),this.options.customHandleAcks=5===t.protocolVersion&&t.customHandleAcks?t.customHandleAcks:(...e)=>{e[3](null,0)},this.options.writeCache||(c.default.writeToStream.cacheNumbers=!1),this.streamBuilder=e,this.messageIdProvider="undefined"==typeof this.options.messageIdProvider?new g.default:this.options.messageIdProvider,this.outgoingStore=t.outgoingStore||new p.default,this.incomingStore=t.incomingStore||new p.default,this.queueQoSZero=void 0===t.queueQoSZero||t.queueQoSZero,this._resubscribeTopics={},this.messageIdToTopic={},this.keepaliveManager=null,this.connected=!1,this.disconnecting=!1,this.reconnecting=!1,this.queue=[],this.connackTimer=null,this.reconnectTimer=null,this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={},this._storeProcessingQueue=[],this.outgoing={},this._firstConnection=!0,t.properties&&t.properties.topicAliasMaximum>0&&(t.properties.topicAliasMaximum>65535?this.log("MqttClient :: options.properties.topicAliasMaximum is out of range"):this.topicAliasRecv=new m.default(t.properties.topicAliasMaximum)),this.on("connect",()=>{const{queue:e}=this,t=()=>{const r=e.shift();this.log("deliver :: entry %o",r);let n=null;if(!r)return void this._resubscribe();n=r.packet,this.log("deliver :: call _sendPacket for %o",n);let i=!0;n.messageId&&0!==n.messageId&&(this.messageIdProvider.register(n.messageId)||(i=!1)),i?this._sendPacket(n,e=>{r.cb&&r.cb(e),t()}):(this.log("messageId: %d has already used. The message is skipped and removed.",n.messageId),t())};this.log("connect :: sending queued packets"),t()}),this.on("close",()=>{this.log("close :: connected set to `false`"),this.connected=!1,this.log("close :: clearing connackTimer"),clearTimeout(this.connackTimer),this._destroyKeepaliveManager(),this.topicAliasRecv&&this.topicAliasRecv.clear(),this.log("close :: calling _setupReconnect"),this._setupReconnect()}),this.options.manualConnect||(this.log("MqttClient :: setting up stream"),this.connect())}handleAuth(e,t){t()}handleMessage(e,t){t()}_nextId(){return this.messageIdProvider.allocate()}getLastMessageId(){return this.messageIdProvider.getLastAllocated()}connect(){const e=new l.Writable,t=c.default.parser(this.options);let r=null;const n=[];this.log("connect :: calling method to clear reconnect"),this._clearReconnect(),this.disconnected&&!this.reconnecting&&(this.incomingStore=this.options.incomingStore||new p.default,this.outgoingStore=this.options.outgoingStore||new p.default,this.disconnecting=!1,this.disconnected=!1),this.log("connect :: using streamBuilder provided to client to create stream"),this.stream=this.streamBuilder(this),t.on("packet",e=>{this.log("parser :: on packet push to packets array."),n.push(e)});const i=()=>{this.log("work :: getting next packet in queue");const e=n.shift();if(e)this.log("work :: packet pulled from queue"),(0,f.default)(this,e,o);else{this.log("work :: no packets in queue");const e=r;r=null,this.log("work :: done flag is %s",!!e),e&&e()}},o=()=>{if(n.length)(0,b.nextTick)(i);else{const e=r;r=null,e()}};e._write=(e,n,o)=>{r=o,this.log("writable stream :: parsing buffer"),t.parse(e),i()};this.log("connect :: pipe stream to writable stream"),this.stream.pipe(e),this.stream.on("error",e=>{this.log("streamErrorHandler :: error",e.message),e.code?(this.log("streamErrorHandler :: emitting error"),this.emit("error",e)):this.noop(e)}),this.stream.on("close",()=>{this.log("(%s)stream :: on close",this.options.clientId),this._flushVolatile(),this.log("stream: emit close to MqttClient"),this.emit("close")}),this.log("connect: sending packet `connect`");const s={cmd:"connect",protocolId:this.options.protocolId,protocolVersion:this.options.protocolVersion,clean:this.options.clean,clientId:this.options.clientId,keepalive:this.options.keepalive,username:this.options.username,password:this.options.password,properties:this.options.properties};if(this.options.will&&(s.will={...this.options.will,payload:this.options.will?.payload}),this.topicAliasRecv&&(s.properties||(s.properties={}),this.topicAliasRecv&&(s.properties.topicAliasMaximum=this.topicAliasRecv.max)),this._writePacket(s),t.on("error",this.emit.bind(this,"error")),this.options.properties){if(!this.options.properties.authenticationMethod&&this.options.properties.authenticationData)return this.end(()=>this.emit("error",new Error("Packet has no Authentication Method"))),this;if(this.options.properties.authenticationMethod&&this.options.authPacket&&"object"==typeof this.options.authPacket){const e={cmd:"auth",reasonCode:0,...this.options.authPacket};this._writePacket(e)}}return this.stream.setMaxListeners(1e3),clearTimeout(this.connackTimer),this.connackTimer=setTimeout(()=>{this.log("!!connectTimeout hit!! Calling _cleanUp with force `true`"),this.emit("error",new Error("connack timeout")),this._cleanUp(!0)},this.options.connectTimeout),this}publish(e,t,r,n){this.log("publish :: message `%s` to topic `%s`",t,e);const{options:i}=this;"function"==typeof r&&(n=r,r=null),r=r||{};r={qos:0,retain:!1,dup:!1,...r};const{qos:o,retain:s,dup:a,properties:c,cbStorePut:l}=r;if(this._checkDisconnecting(n))return this;const u=()=>{let r=0;if((1===o||2===o)&&(r=this._nextId(),null===r))return this.log("No messageId left"),!1;const u={cmd:"publish",topic:e,payload:t,qos:o,retain:s,messageId:r,dup:a};switch(5===i.protocolVersion&&(u.properties=c),this.log("publish :: qos",o),o){case 1:case 2:this.outgoing[u.messageId]={volatile:!1,cb:n||this.noop},this.log("MqttClient:publish: packet cmd: %s",u.cmd),this._sendPacket(u,void 0,l);break;default:this.log("MqttClient:publish: packet cmd: %s",u.cmd),this._sendPacket(u,n,l)}return!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!u())&&this._storeProcessingQueue.push({invoke:u,cbStorePut:r.cbStorePut,callback:n}),this}publishAsync(e,t,r){return new Promise((n,i)=>{this.publish(e,t,r,(e,t)=>{e?i(e):n(t)})})}subscribe(e,t,r){const n=this.options.protocolVersion;"function"==typeof t&&(r=t),r=r||this.noop;let i=!1,o=[];"string"==typeof e?o=e=[e]:Array.isArray(e)?o=e:"object"==typeof e&&(i=e.resubscribe,delete e.resubscribe,o=Object.keys(e));const s=h.validateTopics(o);if(null!==s)return S(r,new Error(`Invalid topic ${s}`)),this;if(this._checkDisconnecting(r))return this.log("subscribe: discconecting true"),this;const a={qos:0};5===n&&(a.nl=!1,a.rap=!1,a.rh=0),t={...a,...t};const{properties:c}=t,l=[],u=(e,r)=>{if(r=r||t,!Object.prototype.hasOwnProperty.call(this._resubscribeTopics,e)||this._resubscribeTopics[e].qos<r.qos||i){const t={topic:e,qos:r.qos};5===n&&(t.nl=r.nl,t.rap=r.rap,t.rh=r.rh,t.properties=c),this.log("subscribe: pushing topic `%s` and qos `%s` to subs list",t.topic,t.qos),l.push(t)}};if(Array.isArray(e)?e.forEach(e=>{this.log("subscribe: array topic %s",e),u(e)}):Object.keys(e).forEach(t=>{this.log("subscribe: object topic %s, %o",t,e[t]),u(t,e[t])}),!l.length)return r(null,[]),this;const d=(e,t)=>{const r={cmd:"subscribe",subscriptions:e,messageId:t};if(c&&(r.properties=c),this.options.resubscribe){this.log("subscribe :: resubscribe true");const t=[];e.forEach(e=>{if(this.options.reconnectPeriod>0){const r={qos:e.qos};5===n&&(r.nl=e.nl||!1,r.rap=e.rap||!1,r.rh=e.rh||0,r.properties=e.properties),this._resubscribeTopics[e.topic]=r,t.push(e.topic)}}),this.messageIdToTopic[r.messageId]=t}const i=new Promise((t,n)=>{this.outgoing[r.messageId]={volatile:!0,cb(r,i){if(!r){const{granted:t}=i;for(let r=0;r<t.length;r+=1)e[r].qos=t[r]}r?n(new b.ErrorWithSubackPacket(r.message,i)):t(i)}}});return this.log("subscribe :: call _sendPacket"),this._sendPacket(r),i},p=()=>{const e=this.options.subscribeBatchSize??l.length,t=[];for(let r=0;r<l.length;r+=e){const n=l.slice(r,r+e),i=this._nextId();if(null===i)return this.log("No messageId left"),!1;t.push(d(n,i))}return Promise.all(t).then(e=>{r(null,l,e.at(-1))}).catch(e=>{r(e,l,e.packet)}),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!p())&&this._storeProcessingQueue.push({invoke:p,callback:r}),this}subscribeAsync(e,t){return new Promise((r,n)=>{this.subscribe(e,t,(e,t)=>{e?n(e):r(t)})})}unsubscribe(e,t,r){"string"==typeof e&&(e=[e]),"function"==typeof t&&(r=t),r=r||this.noop;const n=h.validateTopics(e);if(null!==n)return S(r,new Error(`Invalid topic ${n}`)),this;if(this._checkDisconnecting(r))return this;const i=()=>{const n=this._nextId();if(null===n)return this.log("No messageId left"),!1;const i={cmd:"unsubscribe",messageId:n,unsubscriptions:[]};return"string"==typeof e?i.unsubscriptions=[e]:Array.isArray(e)&&(i.unsubscriptions=e),this.options.resubscribe&&i.unsubscriptions.forEach(e=>{delete this._resubscribeTopics[e]}),"object"==typeof t&&t.properties&&(i.properties=t.properties),this.outgoing[i.messageId]={volatile:!0,cb:r},this.log("unsubscribe: call _sendPacket"),this._sendPacket(i),!0};return(this._storeProcessing||this._storeProcessingQueue.length>0||!i())&&this._storeProcessingQueue.push({invoke:i,callback:r}),this}unsubscribeAsync(e,t){return new Promise((r,n)=>{this.unsubscribe(e,t,(e,t)=>{e?n(e):r(t)})})}end(e,t,r){this.log("end :: (%s)",this.options.clientId),null!=e&&"boolean"==typeof e||(r=r||t,t=e,e=!1),"object"!=typeof t&&(r=r||t,t=null),this.log("end :: cb? %s",!!r),r&&"function"==typeof r||(r=this.noop);const n=()=>{this.log("end :: closeStores: closing incoming and outgoing stores"),this.disconnected=!0,this.incomingStore.close(e=>{this.outgoingStore.close(t=>{if(this.log("end :: closeStores: emitting end"),this.emit("end"),r){const n=e||t;this.log("end :: closeStores: invoking callback with args"),r(n)}})}),this._deferredReconnect?this._deferredReconnect():(0===this.options.reconnectPeriod||this.options.manualConnect)&&(this.disconnecting=!1)},i=()=>{this.log("end :: (%s) :: finish :: calling _cleanUp with force %s",this.options.clientId,e),this._cleanUp(e,()=>{this.log("end :: finish :: calling process.nextTick on closeStores"),(0,b.nextTick)(n)},t)};return this.disconnecting?(r(),this):(this._clearReconnect(),this.disconnecting=!0,!e&&Object.keys(this.outgoing).length>0?(this.log("end :: (%s) :: calling finish in 10ms once outgoing is empty",this.options.clientId),this.once("outgoingEmpty",setTimeout.bind(null,i,10))):(this.log("end :: (%s) :: immediately calling finish",this.options.clientId),i()),this)}endAsync(e,t){return new Promise((r,n)=>{this.end(e,t,e=>{e?n(e):r()})})}removeOutgoingMessage(e){if(this.outgoing[e]){const{cb:t}=this.outgoing[e];this._removeOutgoingAndStoreMessage(e,()=>{t(new Error("Message removed"))})}return this}reconnect(e){this.log("client reconnect");const t=()=>{e?(this.options.incomingStore=e.incomingStore,this.options.outgoingStore=e.outgoingStore):(this.options.incomingStore=null,this.options.outgoingStore=null),this.incomingStore=this.options.incomingStore||new p.default,this.outgoingStore=this.options.outgoingStore||new p.default,this.disconnecting=!1,this.disconnected=!1,this._deferredReconnect=null,this._reconnect()};return this.disconnecting&&!this.disconnected?this._deferredReconnect=t:t(),this}_flushVolatile(){this.outgoing&&(this.log("_flushVolatile :: deleting volatile messages from the queue and setting their callbacks as error function"),Object.keys(this.outgoing).forEach(e=>{this.outgoing[e].volatile&&"function"==typeof this.outgoing[e].cb&&(this.outgoing[e].cb(new Error("Connection closed")),delete this.outgoing[e])}))}_flush(){this.outgoing&&(this.log("_flush: queue exists? %b",!!this.outgoing),Object.keys(this.outgoing).forEach(e=>{"function"==typeof this.outgoing[e].cb&&(this.outgoing[e].cb(new Error("Connection closed")),delete this.outgoing[e])}))}_removeTopicAliasAndRecoverTopicName(e){let t;e.properties&&(t=e.properties.topicAlias);let r=e.topic.toString();if(this.log("_removeTopicAliasAndRecoverTopicName :: alias %d, topic %o",t,r),0===r.length){if("undefined"==typeof t)return new Error("Unregistered Topic Alias");if(r=this.topicAliasSend.getTopicByAlias(t),"undefined"==typeof r)return new Error("Unregistered Topic Alias");e.topic=r}t&&delete e.properties.topicAlias}_checkDisconnecting(e){return this.disconnecting&&(e&&e!==this.noop?e(new Error("client disconnecting")):this.emit("error",new Error("client disconnecting"))),this.disconnecting}_reconnect(){this.log("_reconnect: emitting reconnect to client"),this.emit("reconnect"),this.connected?(this.end(()=>{this.connect()}),this.log("client already connected. disconnecting first.")):(this.log("_reconnect: calling connect"),this.connect())}_setupReconnect(){!this.disconnecting&&!this.reconnectTimer&&this.options.reconnectPeriod>0?(this.reconnecting||(this.log("_setupReconnect :: emit `offline` state"),this.emit("offline"),this.log("_setupReconnect :: set `reconnecting` to `true`"),this.reconnecting=!0),this.log("_setupReconnect :: setting reconnectTimer for %d ms",this.options.reconnectPeriod),this.reconnectTimer=setInterval(()=>{this.log("reconnectTimer :: reconnect triggered!"),this._reconnect()},this.options.reconnectPeriod)):this.log("_setupReconnect :: doing nothing...")}_clearReconnect(){this.log("_clearReconnect : clearing reconnect timer"),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null)}_cleanUp(e,t,r={}){if(t&&(this.log("_cleanUp :: done callback provided for on stream close"),this.stream.on("close",t)),this.log("_cleanUp :: forced? %s",e),e)0===this.options.reconnectPeriod&&this.options.clean&&this._flush(),this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),this.stream.destroy();else{const e={cmd:"disconnect",...r};this.log("_cleanUp :: (%s) :: call _sendPacket with disconnect packet",this.options.clientId),this._sendPacket(e,()=>{this.log("_cleanUp :: (%s) :: destroying stream",this.options.clientId),S(()=>{this.stream.end(()=>{this.log("_cleanUp :: (%s) :: stream destroyed",this.options.clientId)})})})}this.disconnecting||this.reconnecting||(this.log("_cleanUp :: client not disconnecting/reconnecting. Clearing and resetting reconnect."),this._clearReconnect(),this._setupReconnect()),this._destroyKeepaliveManager(),t&&!this.connected&&(this.log("_cleanUp :: (%s) :: removing stream `done` callback `close` listener",this.options.clientId),this.stream.removeListener("close",t),t())}_storeAndSend(e,t,r){this.log("storeAndSend :: store packet with cmd %s to outgoingStore",e.cmd);let n,i=e;if("publish"===i.cmd&&(i=(0,u.default)(e),n=this._removeTopicAliasAndRecoverTopicName(i),n))return t&&t(n);this.outgoingStore.put(i,n=>{if(n)return t&&t(n);r(),this._writePacket(e,t)})}_applyTopicAlias(e){if(5===this.options.protocolVersion&&"publish"===e.cmd){let t;e.properties&&(t=e.properties.topicAlias);const r=e.topic.toString();if(this.topicAliasSend)if(t){if(0!==r.length&&(this.log("applyTopicAlias :: register topic: %s - alias: %d",r,t),!this.topicAliasSend.put(r,t)))return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,t),new Error("Sending Topic Alias out of range")}else 0!==r.length&&(this.options.autoAssignTopicAlias?(t=this.topicAliasSend.getAliasByTopic(r),t?(e.topic="",e.properties={...e.properties,topicAlias:t},this.log("applyTopicAlias :: auto assign(use) topic: %s - alias: %d",r,t)):(t=this.topicAliasSend.getLruAlias(),this.topicAliasSend.put(r,t),e.properties={...e.properties,topicAlias:t},this.log("applyTopicAlias :: auto assign topic: %s - alias: %d",r,t))):this.options.autoUseTopicAlias&&(t=this.topicAliasSend.getAliasByTopic(r),t&&(e.topic="",e.properties={...e.properties,topicAlias:t},this.log("applyTopicAlias :: auto use topic: %s - alias: %d",r,t))));else if(t)return this.log("applyTopicAlias :: error out of range. topic: %s - alias: %d",r,t),new Error("Sending Topic Alias out of range")}}_noop(e){this.log("noop ::",e)}_writePacket(e,t){this.log("_writePacket :: packet: %O",e),this.log("_writePacket :: emitting `packetsend`"),this.emit("packetsend",e),this.log("_writePacket :: writing to stream");const r=c.default.writeToStream(e,this.stream,this.options);this.log("_writePacket :: writeToStream result %s",r),!r&&t&&t!==this.noop?(this.log("_writePacket :: handle events on `drain` once through callback."),this.stream.once("drain",t)):t&&(this.log("_writePacket :: invoking cb"),t())}_sendPacket(e,t,r,n){this.log("_sendPacket :: (%s) :: start",this.options.clientId),r=r||this.noop,t=t||this.noop;const i=this._applyTopicAlias(e);if(i)t(i);else{if(!this.connected)return"auth"===e.cmd?void this._writePacket(e,t):(this.log("_sendPacket :: client not connected. Storing packet offline."),void this._storePacket(e,t,r));if(n)this._writePacket(e,t);else{switch(e.cmd){case"publish":break;case"pubrel":return void this._storeAndSend(e,t,r);default:return void this._writePacket(e,t)}switch(e.qos){case 2:case 1:this._storeAndSend(e,t,r);break;default:this._writePacket(e,t)}this.log("_sendPacket :: (%s) :: end",this.options.clientId)}}}_storePacket(e,t,r){this.log("_storePacket :: packet: %o",e),this.log("_storePacket :: cb? %s",!!t),r=r||this.noop;let n=e;if("publish"===n.cmd){n=(0,u.default)(e);const r=this._removeTopicAliasAndRecoverTopicName(n);if(r)return t&&t(r)}const i=n.qos||0;0===i&&this.queueQoSZero||"publish"!==n.cmd?this.queue.push({packet:n,cb:t}):i>0?(t=this.outgoing[n.messageId]?this.outgoing[n.messageId].cb:null,this.outgoingStore.put(n,e=>{if(e)return t&&t(e);r()})):t&&t(new Error("No connection to broker"))}_setupKeepaliveManager(){this.log("_setupKeepaliveManager :: keepalive %d (seconds)",this.options.keepalive),!this.keepaliveManager&&this.options.keepalive&&(this.keepaliveManager=new _.default(this,this.options.timerVariant))}_destroyKeepaliveManager(){this.keepaliveManager&&(this.log("_destroyKeepaliveManager :: destroying keepalive manager"),this.keepaliveManager.destroy(),this.keepaliveManager=null)}reschedulePing(e=!1){this.keepaliveManager&&this.options.keepalive&&(e||this.options.reschedulePings)&&this._reschedulePing()}_reschedulePing(){this.log("_reschedulePing :: rescheduling ping"),this.keepaliveManager.reschedule()}sendPing(){this.log("_sendPing :: sending pingreq"),this._sendPacket({cmd:"pingreq"})}onKeepaliveTimeout(){this.emit("error",new Error("Keepalive timeout")),this.log("onKeepaliveTimeout :: calling _cleanUp with force true"),this._cleanUp(!0)}_resubscribe(){this.log("_resubscribe");const e=Object.keys(this._resubscribeTopics);if(!this._firstConnection&&(this.options.clean||this.options.protocolVersion>=4&&!this.connackPacket.sessionPresent)&&e.length>0)if(this.options.resubscribe)if(5===this.options.protocolVersion){this.log("_resubscribe: protocolVersion 5");for(let t=0;t<e.length;t++){const r={};r[e[t]]=this._resubscribeTopics[e[t]],r.resubscribe=!0,this.subscribe(r,{properties:r[e[t]].properties})}}else this._resubscribeTopics.resubscribe=!0,this.subscribe(this._resubscribeTopics);else this._resubscribeTopics={};this._firstConnection=!1}_onConnect(e){if(this.disconnected)return void this.emit("connect",e);this.connackPacket=e,this.messageIdProvider.clear(),this._setupKeepaliveManager(),this.connected=!0;const t=()=>{let r=this.outgoingStore.createStream();const n=()=>{r.destroy(),r=null,this._flushStoreProcessingQueue(),i()},i=()=>{this._storeProcessing=!1,this._packetIdsDuringStoreProcessing={}};this.once("close",n),r.on("error",e=>{i(),this._flushStoreProcessingQueue(),this.removeListener("close",n),this.emit("error",e)});const o=()=>{if(!r)return;const e=r.read(1);let t;e?(this._storeProcessing=!0,this._packetIdsDuringStoreProcessing[e.messageId]?o():this.disconnecting||this.reconnectTimer?r.destroy&&r.destroy():(t=this.outgoing[e.messageId]?this.outgoing[e.messageId].cb:null,this.outgoing[e.messageId]={volatile:!1,cb(e,r){t&&t(e,r),o()}},this._packetIdsDuringStoreProcessing[e.messageId]=!0,this.messageIdProvider.register(e.messageId)?this._sendPacket(e,void 0,void 0,!0):this.log("messageId: %d has already used.",e.messageId))):r.once("readable",o)};r.on("end",()=>{let r=!0;for(const e in this._packetIdsDuringStoreProcessing)if(!this._packetIdsDuringStoreProcessing[e]){r=!1;break}this.removeListener("close",n),r?(i(),this._invokeAllStoreProcessingQueue(),this.emit("connect",e)):t()}),o()};t()}_invokeStoreProcessingQueue(){if(!this._storeProcessing&&this._storeProcessingQueue.length>0){const e=this._storeProcessingQueue[0];if(e&&e.invoke())return this._storeProcessingQueue.shift(),!0}return!1}_invokeAllStoreProcessingQueue(){for(;this._invokeStoreProcessingQueue(););}_flushStoreProcessingQueue(){for(const e of this._storeProcessingQueue)e.cbStorePut&&e.cbStorePut(new Error("Connection closed")),e.callback&&e.callback(new Error("Connection closed"));this._storeProcessingQueue.splice(0)}_removeOutgoingAndStoreMessage(e,t){delete this.outgoing[e],this.outgoingStore.del({messageId:e},(r,n)=>{t(r,n),this.messageIdProvider.deallocate(e),this._invokeStoreProcessingQueue()})}}t.default=k},9844(e){"use strict";function t(e){return e instanceof Buffer?Buffer.from(e):new e.constructor(e.buffer.slice(),e.byteOffset,e.length)}e.exports=function(e){if((e=e||{}).circles)return function(e){const r=[],n=[],i=new Map;if(i.set(Date,e=>new Date(e)),i.set(Map,(e,t)=>new Map(s(Array.from(e),t))),i.set(Set,(e,t)=>new Set(s(Array.from(e),t))),e.constructorHandlers)for(const t of e.constructorHandlers)i.set(t[0],t[1]);let o=null;return e.proto?c:a;function s(e,s){const a=Object.keys(e),c=new Array(a.length);for(let l=0;l<a.length;l++){const u=a[l],d=e[u];if("object"!=typeof d||null===d)c[u]=d;else if(d.constructor!==Object&&(o=i.get(d.constructor)))c[u]=o(d,s);else if(ArrayBuffer.isView(d))c[u]=t(d);else{const e=r.indexOf(d);c[u]=-1!==e?n[e]:s(d)}}return c}function a(e){if("object"!=typeof e||null===e)return e;if(Array.isArray(e))return s(e,a);if(e.constructor!==Object&&(o=i.get(e.constructor)))return o(e,a);const c={};r.push(e),n.push(c);for(const s in e){if(!1===Object.hasOwnProperty.call(e,s))continue;const l=e[s];if("object"!=typeof l||null===l)c[s]=l;else if(l.constructor!==Object&&(o=i.get(l.constructor)))c[s]=o(l,a);else if(ArrayBuffer.isView(l))c[s]=t(l);else{const e=r.indexOf(l);c[s]=-1!==e?n[e]:a(l)}}return r.pop(),n.pop(),c}function c(e){if("object"!=typeof e||null===e)return e;if(Array.isArray(e))return s(e,c);if(e.constructor!==Object&&(o=i.get(e.constructor)))return o(e,c);const a={};r.push(e),n.push(a);for(const s in e){const l=e[s];if("object"!=typeof l||null===l)a[s]=l;else if(l.constructor!==Object&&(o=i.get(l.constructor)))a[s]=o(l,c);else if(ArrayBuffer.isView(l))a[s]=t(l);else{const e=r.indexOf(l);a[s]=-1!==e?n[e]:c(l)}}return r.pop(),n.pop(),a}}(e);const r=new Map;if(r.set(Date,e=>new Date(e)),r.set(Map,(e,t)=>new Map(i(Array.from(e),t))),r.set(Set,(e,t)=>new Set(i(Array.from(e),t))),e.constructorHandlers)for(const t of e.constructorHandlers)r.set(t[0],t[1]);let n=null;return e.proto?function e(o){if("object"!=typeof o||null===o)return o;if(Array.isArray(o))return i(o,e);if(o.constructor!==Object&&(n=r.get(o.constructor)))return n(o,e);const s={};for(const i in o){const a=o[i];"object"!=typeof a||null===a?s[i]=a:a.constructor!==Object&&(n=r.get(a.constructor))?s[i]=n(a,e):ArrayBuffer.isView(a)?s[i]=t(a):s[i]=e(a)}return s}:function e(o){if("object"!=typeof o||null===o)return o;if(Array.isArray(o))return i(o,e);if(o.constructor!==Object&&(n=r.get(o.constructor)))return n(o,e);const s={};for(const i in o){if(!1===Object.hasOwnProperty.call(o,i))continue;const a=o[i];"object"!=typeof a||null===a?s[i]=a:a.constructor!==Object&&(n=r.get(a.constructor))?s[i]=n(a,e):ArrayBuffer.isView(a)?s[i]=t(a):s[i]=e(a)}return s};function i(e,i){const o=Object.keys(e),s=new Array(o.length);for(let a=0;a<o.length;a++){const c=o[a],l=e[c];"object"!=typeof l||null===l?s[c]=l:l.constructor!==Object&&(n=r.get(l.constructor))?s[c]=n(l,i):ArrayBuffer.isView(l)?s[c]=t(l):s[c]=i(l)}return s}}},9896(e){"use strict";e.exports=require("fs")}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n=r(7927),i=exports="undefined"==typeof exports?{}:exports;for(var o in n)i[o]=n[o];n.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
|
|
3
3
|
//# sourceMappingURL=main.nodejs.js.map
|