-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimjoy-rpc-socketio.min.js
11 lines (11 loc) · 114 KB
/
imjoy-rpc-socketio.min.js
1
2
3
4
5
6
7
8
9
10
11
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("imjoyRPCSocketIO",[],t):"object"==typeof exports?exports.imjoyRPCSocketIO=t():e.imjoyRPCSocketIO=t()}(window,(function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=29)}([,function(module,__webpack_exports__,__webpack_require__){"use strict";function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}__webpack_require__.d(__webpack_exports__,"f",(function(){return randId})),__webpack_require__.d(__webpack_exports__,"b",(function(){return dtypeToTypedArray})),__webpack_require__.d(__webpack_exports__,"d",(function(){return loadRequirementsInWindow})),__webpack_require__.d(__webpack_exports__,"c",(function(){return loadRequirements})),__webpack_require__.d(__webpack_exports__,"e",(function(){return normalizeConfig})),__webpack_require__.d(__webpack_exports__,"h",(function(){return typedArrayToDtype})),__webpack_require__.d(__webpack_exports__,"g",(function(){return setupServiceWorker})),__webpack_require__.d(__webpack_exports__,"a",(function(){return MessageEmitter}));const dtypeToTypedArray={int8:Int8Array,int16:Int16Array,int32:Int32Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,float32:Float32Array,float64:Float64Array,array:Array};async function loadRequirementsInWindow(e){function t(e){return new Promise((t,r)=>{var n=document.createElement("script");n.src=e,n.type="text/javascript",n.onload=t,n.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},n.onerror=r,document.head.appendChild(n)})}async function r(){for(var e=Array.prototype.slice.call(arguments),r=e.length,n=0;n<r;n++)await t(e[n])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var n;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var i=0;i<e.length;i++)e[i].toLowerCase().endsWith(".css")||e[i].startsWith("css:")?(e[i].startsWith("css:")&&(e[i]=e[i].slice(4)),(n=document.createElement("link")).rel="stylesheet",n.href=e[i],document.head.appendChild(n)):e[i].toLowerCase().endsWith(".mjs")||e[i].startsWith("mjs:")?(e[i].startsWith("mjs:")&&(e[i]=e[i].slice(4)),await import(e[i])):e[i].toLowerCase().endsWith(".js")||e[i].startsWith("js:")?(e[i].startsWith("js:")&&(e[i]=e[i].slice(3)),await r(e[i])):e[i].startsWith("http")?await r(e[i]):e[i].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[i])}catch(t){throw"failed to import required scripts: "+e.toString()}}async function loadRequirementsInWebworker(e){if(e&&(Array.isArray(e)||"string"==typeof e))try{Array.isArray(e)||(e=[e]);for(var t=0;t<e.length;t++){if(e[t].toLowerCase().endsWith(".css")||e[t].startsWith("css:"))throw"unable to import css in a webworker";e[t].toLowerCase().endsWith(".js")||e[t].startsWith("js:")?(e[t].startsWith("js:")&&(e[t]=e[t].slice(3)),importScripts(e[t])):e[t].startsWith("http")?importScripts(e[t]):e[t].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[t])}}catch(t){throw"failed to import required scripts: "+e.toString()}}function loadRequirements(e){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?loadRequirementsInWebworker(e):loadRequirementsInWindow(e)}function normalizeConfig(e){return e.version=e.version||"0.1.0",e.description=e.description||`[TODO: add description for ${e.name} ]`,e.type=e.type||"rpc-window",e.id=e.id||randId(),e.target_origin=e.target_origin||"*",e.allow_execution=e.allow_execution||!1,e=Object.keys(e).reduce((t,r)=>("function"!=typeof e[r]&&(t[r]=e[r]),t),{})}const typedArrayToDtypeMapping={Int8Array:"int8",Int16Array:"int16",Int32Array:"int32",Uint8Array:"uint8",Uint16Array:"uint16",Uint32Array:"uint32",Float32Array:"float32",Float64Array:"float64",Array:"array"},typedArrayToDtypeKeys=[];for(const arrType of Object.keys(typedArrayToDtypeMapping))typedArrayToDtypeKeys.push(eval(arrType));function typedArrayToDtype(e){let t=typedArrayToDtypeMapping[e.constructor.name];if(!t){const r=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(r instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise((function(t,r){const n={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void r("Service worker is not supported.");const i=new MessageChannel;i.port1.onmessage=function(e){e.data&&e.data.error?r(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(n,[i.port2]):r("Service worker controller is not available")}))}async function cacheRequirements(e){e=e||[],Array.isArray(e)||(e=[e]);for(let t of e)t.startsWith("js:")&&(t=t.slice(3)),t.startsWith("css:")&&(t=t.slice(4)),t.startsWith("cache:")&&(t=t.slice(6)),t.startsWith("http")&&await cacheUrlInServiceWorker(t).catch(e=>{console.error(e)})}function setupServiceWorker(e,t,r){if("serviceWorker"in navigator){if(e=e||"/",navigator.serviceWorker.register(e+"plugin-service-worker.js").then((function(e){console.log("ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("ServiceWorker registration failed: ",e)})),t=t||"*",(r=r||cacheRequirements)&&"function"!=typeof r)throw new Error("config.cache_requirements must be a function");window.addEventListener("message",(function(e){if("*"===t||e.origin===t){const t=e.data;"cacheRequirements"===t.type&&r(t.requirements)}}))}}function urlJoin(...e){return e.join("/").replace(/[\/]+/g,"/").replace(/^(.+):\//,"$1://").replace(/^file:/,"file:/").replace(/\/(\?|&|#[^!])/g,"$1").replace(/\?/g,"&").replace("&","?")}class MessageEmitter{constructor(e){this._event_handlers={},this._once_handlers={},this._debug=e}emit(){throw new Error("emit is not implemented")}on(e,t){this._event_handlers[e]||(this._event_handlers[e]=[]),this._event_handlers[e].push(t)}once(e,t){t.___event_run_once=!0,this.on(e,t)}off(e,t){if(e||t){if(e&&!t)this._event_handlers[e]&&(this._event_handlers[e]=[]);else if(this._event_handlers[e]){const r=this._event_handlers[e].indexOf(t);r>=0&&this._event_handlers[e].splice(r,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var r=this._event_handlers[e].length;r--;){const n=this._event_handlers[e][r];try{n(t)}catch(e){console.error(e)}finally{n.___event_run_once&&this._event_handlers[e].splice(r,1)}}else this._debug&&console.warn("unhandled event",e,t)}}},function(e,t,r){"use strict";r.d(t,"a",(function(){return i})),r.d(t,"b",(function(){return c}));var n=r(1);const i="0.2.3",o=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function s(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer}function a(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?a(e,t.split(".")):0===t.length?e:a(e[t[0]],t.slice(1))}class c extends n.a{constructor(e,t,r){super(t&&t.debug),this._connection=e,this.config=t||{},this._codecs=r||{},this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._remote_set=!1;const n=this.config.name;this._connection.execute=this._connection.execute||function(){throw new Error(`connection.execute not implemented (in "${n}")`)},this._store=new h,this._method_refs=new h,this._method_refs.onReady(()=>{this._fire("remoteIdle")}),this._method_refs.onBusy(()=>{this._fire("remoteBusy")}),this._setupMessageHanlders()}init(){this._connection.emit({type:"initialized",config:this.config,peer_id:this._connection.peer_id})}setConfig(e){if(e)for(const t of Object.keys(e))this.config[t]=e[t]}getRemoteCallStack(){return this._method_refs.getStack()}getRemote(){return this._remote_interface}setInterface(e,t){if(t=t||{},this.config.name=t.name||this.config.name,this.config.description=t.description||this.config.description,this.config.forwarding_functions)for(let t of this.config.forwarding_functions){const r=this._remote_interface;r[t]&&(e.constructor===Object?e[t]||(e[t]=(...e)=>{r[t](...e)}):e.constructor.constructor===Function&&(e.constructor.prototype[t]||(e.constructor.prototype[t]=(...e)=>{r[t](...e)})))}return this._local_api=e,this._remote_set?this.sendInterface():this._fire("interfaceAvailable"),new Promise(e=>{this.once("interfaceSetAsRemote",e)})}sendInterface(){if(!this._local_api)throw new Error("interface is not set.");this._encode(this._local_api,!0).then(e=>{this._connection.emit({type:"setInterface",api:e})})}_disposeObject(e){if(!this._object_store[e])throw new Error(`Object (id=${e}) not found.`);delete this._object_store[e]}disposeObject(e){return new Promise((t,r)=>{if(!this._object_weakmap.has(e))throw new Error("Invalid object");{const n=this._object_weakmap.get(e);this._connection.once("disposed",e=>{e.error?r(new Error(e.error)):t()}),this._connection.emit({type:"disposeObject",object_id:n})}})}_setupMessageHanlders(){this._connection.on("init",this.init),this._connection.on("execute",e=>{Promise.resolve(this._connection.execute(e.code)).then(()=>{this._connection.emit({type:"executed"})}).catch(e=>{console.error(e),this._connection.emit({type:"executed",error:String(e)})})}),this._connection.on("method",async e=>{let t,r,n,i,o,s;try{e.promise&&([t,r]=await this._unwrap(e.promise,!1));const c=this._object_store[e.object_id];if(n=a(c,e.name),e.name.includes(".")){const t=e.name.split(".");i=a(c,t.slice(0,t.length-1).join("."))}else i=c;o=await this._unwrap(e.args,!0),e.promise?(s=n.apply(i,o),s instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?s.then(t).catch(r):t(s)):n.apply(i,o)}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("callback",async e=>{let t,r,n,i,o;try{if(e.promise&&([t,r]=await this._unwrap(e.promise,!1)),e.promise){if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");o=n.apply(null,i),o instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?o.then(t).catch(r):t(o)}else{if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Please notice that callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");n.apply(null,i)}}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("disposeObject",e=>{try{this._disposeObject(e.object_id),this._connection.emit({type:"disposed"})}catch(e){console.error(e),this._connection.emit({type:"disposed",error:String(e)})}}),this._connection.on("setInterface",e=>{this._setRemoteInterface(e.api)}),this._connection.on("getInterface",()=>{this._fire("getInterface"),this._local_api?this.sendInterface():this.once("interfaceAvailable",()=>{this.sendInterface()})}),this._connection.on("interfaceSetAsRemote",()=>{this._remote_set=!0,this._fire("interfaceSetAsRemote")}),this._connection.on("disconnect",()=>{this._fire("beforeDisconnect"),this._connection.disconnect(),this._fire("disconnected")})}requestRemote(){this._connection.emit({type:"getInterface"})}_ndarray(e,t,r){const i=Object(n.h)(e);if(r&&r!==i)throw"dtype doesn't match the type of the array: "+i+" != "+r;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:i}}_setRemoteInterface(e){this._decode(e).then(e=>{if(this._remote_interface){for(let e in this._remote_interface)delete this._remote_interface[e];Object.assign(this._remote_interface,e)}else this._remote_interface=e;this._fire("remoteReady"),this._reportRemoteSet()})}_genRemoteMethod(e,t,r){const n=this,i=function(){return new Promise(async(i,o)=>{let s=null;try{s=n._method_refs.put(r?r+"/"+t:t);const a=function(){return null!==s&&n._method_refs.fetch(s),i.apply(this,arguments)},c=function(){return null!==s&&n._method_refs.fetch(s),o.apply(this,arguments)},h=await n._wrap([a,c]);a.__promise_pair=h[1]._rvalue,c.__promise_pair=h[0]._rvalue;let u=Array.prototype.slice.call(arguments);const f=u.length,l=f>0&&"object"==typeof u[f-1]&&null!==u[f-1]&&u[f-1]._rkwargs;l&&delete u[f-1]._rkwargs,u="register"===t||"registerService"===t||"register_service"===t||"export"===t||"on"===t?await n._wrap(u,!0):await n._wrap(u);const p=u.__transferables__;p&&delete u.__transferables__,n._connection.emit({type:"method",target_id:e,name:t,object_id:r,args:u,promise:h,with_kwargs:l},p)}catch(e){s&&n._method_refs.fetch(s),o(`Failed to exectue remote method (interface: ${r||n.id}, method: ${t}), error: ${e}`)}})};return i.__remote_method=!0,i}_reportRemoteSet(){this._connection.emit({type:"interfaceSetAsRemote"})}async _encode(e,t,r){const i=typeof e;if("number"===i||"string"===i||"boolean"===i||null==e||e instanceof ArrayBuffer)return e;let s;if("function"==typeof e){if(t){if(!r)throw new Error("objectId is not specified.");s={_rtype:"interface",_rtarget_id:this._connection.peer_id,_rintf:r,_rvalue:t},this._method_weakmap.set(e,s)}else if(this._method_weakmap.has(e))s=this._method_weakmap.get(e);else{const t=this._store.put(e);s={_rtype:"callback",_rtarget_id:this._connection.peer_id,_rname:e.constructor&&e.constructor.name||t,_rvalue:t}}return s}if(e.constructor instanceof Object&&e._rtype){if(e._rintf){const n=e._rtype;delete e._rtype,s=await this._encode(e,t,r),s._rtype=n}else s=e;return s}const a=[],c=e._transfer,h=Array.isArray(e);for(let n of Object.keys(this._codecs)){const i=this._codecs[n];if(i.encoder&&e instanceof i.type){let n=await Promise.resolve(i.encoder(e));if(n&&!n._rtype&&(n._rtype=i.name),n&&n._rintf){const e=n._rtype;delete n._rtype,n=await this._encode(n,t,r),n._rtype=e}return s=n,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const t=e.dataSync();(e._transfer||c)&&(a.push(t.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:t.buffer,_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const t=Object(n.h)(e.selection.data);(e._transfer||c)&&(a.push(e.selection.data.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:e.selection.data.buffer,_rshape:e.shape,_rdtype:t}}else if(e instanceof Error)console.error(e),s={_rtype:"error",_rvalue:e.toString()};else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ImageData||"undefined"!=typeof FileList&&e instanceof FileList||"undefined"!=typeof FileSystemDirectoryHandle&&e instanceof FileSystemDirectoryHandle||"undefined"!=typeof FileSystemFileHandle&&e instanceof FileSystemFileHandle||"undefined"!=typeof FileSystemHandle&&e instanceof FileSystemHandle||"undefined"!=typeof FileSystemWritableFileStream&&e instanceof FileSystemWritableFileStream)s=e;else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rname:e.name,_rmime:e.type,_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e instanceof Blob)s={_rtype:"blob",_rvalue:e};else if(e instanceof o){(e._transfer||c)&&(a.push(e.buffer),delete e._transfer);const t=Object(n.h)(e);s={_rtype:"typedarray",_rvalue:e.buffer,_rdtype:t}}else if(e instanceof DataView)(e._transfer||c)&&(a.push(e.buffer),delete e._transfer),s={_rtype:"memoryview",_rvalue:e.buffer};else if(e instanceof Set)s={_rtype:"set",_rvalue:await this._encode(Array.from(e),t)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t)};else if(e.constructor instanceof Object||Array.isArray(e)){let i;if(s=h?[]:{},e.constructor===Object||Array.isArray(e))i=Object.keys(e);else{if(e.constructor===Function)throw new Error("Please instantiate the class before exportting it.");if(e.constructor.constructor!==Function)throw Error("Unsupported interface type");i=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),t=!0}let o=!1;if(e._rintf||t){r||(r="string"==typeof e._rintf&&e._rintf.length>0?e._rintf:Object(n.f)(),this._object_store[r]&&console.warn("Overwritting interface object with the same id: "+r),this._object_store[r]=e);for(let n of i)"constructor"!==n&&(n.startsWith("_")||(s[n]=await this._encode(e[n],"string"==typeof t?t+"."+n:n,r),"function"==typeof e[n]&&(o=!0)));o&&(s._rintf=r),e.on&&"function"==typeof e.on&&e.on("close",()=>{delete this._object_store[r]})}else for(let t of i)["hasOwnProperty","constructor"].includes(t)||(s[t]=await this._encode(e[t]))}else{if("object"!=typeof e)throw"imjoy-rpc: Unsupported data type:"+e;{const t=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),r=Object(n.f)();for(let r of t)["hasOwnProperty","constructor"].includes(r)||(s[r]=await this._encode(e[r],r,s));s._rintf=r}}if(a.length>0&&(s.__transferables__=a),!s)throw new Error("Failed to encode object");return s}async _decode(e,t){if(!e)return e;let r;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){if(e._rintf){const r=e._rtype;delete e._rtype,(e=await this._decode(e,t))._rtype=r}r=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("callback"===e._rtype)r=this._genRemoteCallback(e._rtarget_id,e._rvalue,t);else if("interface"===e._rtype)r=this._genRemoteMethod(e._rtarget_id,e._rvalue,e._rintf);else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s)),r=nj.array(new Uint8(e._rvalue),e._rdtype).reshape(e._rshape);else if("undefined"!=typeof tf&&tf.Tensor){Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s));const t=n.b[e._rdtype];r=tf.tensor(new t(e._rvalue),e._rshape,e._rdtype)}else r=e;else if("error"===e._rtype)r=new Error(e._rvalue);else if("file"===e._rtype)e._rvalue instanceof File?(r=e._rvalue,r._path=e._rpath):(r=new File([e._rvalue],e._rname,{type:e._rmime}),r._path=e._rpath);else if("typedarray"===e._rtype){const t=n.b[e._rdtype];if(!t)throw new Error("unsupported dtype: "+e._rdtype);r=new t(e._rvalue)}else if("memoryview"===e._rtype)r=new DataView(e._rvalue);else if("blob"===e._rtype)r=e._rvalue instanceof Blob?e._rvalue:new Blob([e._rvalue],{type:e._rmime});else if("orderedmap"===e._rtype)r=new Map(await this._decode(e._rvalue,t));else if("set"===e._rtype)r=new Set(await this._decode(e._rvalue,t));else if(e._rintf){const n=e._rtype;delete e._rtype,r=await this._decode(e,t),r._rtype=n}else r=e;else if(e.constructor===Object||Array.isArray(e)){const n=Array.isArray(e);r=n?[]:{};for(let i of Object.keys(e))if(n||e.hasOwnProperty(i)){const n=e[i];r[i]=await this._decode(n,t)}}else r=e;if(void 0===r)throw new Error("Failed to decode object");return e._rintf&&this._object_weakmap.set(r,e._rintf),r}async _wrap(e,t){return await this._encode(e,t)}async _unwrap(e,t){return await this._decode(e,t)}_genRemoteCallback(e,t,r){const n=this;let i;return r?(i=function(){return new Promise(async(r,i)=>{const o=await n._wrap(Array.prototype.slice.call(arguments)),s=o.length,a=s>0&&"object"==typeof o[s-1]&&null!==o[s-1]&&o[s-1]._rkwargs;a&&delete o[s-1]._rkwargs;const c=o.__transferables__;c&&delete o.__transferables__;const h=await n._wrap([r,i]);r.__promise_pair=h[1]._rvalue,i.__promise_pair=h[0]._rvalue;try{n._connection.emit({type:"callback",target_id:e,id:t,args:o,promise:h,with_kwargs:a},c)}catch(e){i(`Failed to exectue remote callback ( id: ${t}).`)}})},i):(i=async function(){const r=await n._wrap(Array.prototype.slice.call(arguments)),i=r.length,o=i>0&&"object"==typeof r[i-1]&&null!==r[i-1]&&r[i-1]._rkwargs;o&&delete r[i-1]._rkwargs;const s=r.__transferables__;return s&&delete r.__transferables__,n._connection.emit({type:"callback",target_id:e,id:t,args:r,with_kwargs:o},s)},i)}reset(){this._event_handlers={},this._once_handlers={},this._remote_interface=null,this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._store=new h,this._method_refs=new h}disconnect(){this._connection.emit({type:"disconnect"}),this.reset(),setTimeout(()=>{this._connection.disconnect()},2e3)}}class h{constructor(){this._store={},this._indices=[0],this._readyHandler=function(){},this._busyHandler=function(){},this._readyHandler()}onReady(e){this._readyHandler=e||function(){}}onBusy(e){this._busyHandler=e||function(){}}getStack(){return Object.keys(this._store).length}_genId(){let e;return e=1===this._indices.length?this._indices[0]++:this._indices.shift(),e}_releaseId(e){for(let t=0;t<this._indices.length;t++)if(e<this._indices[t]){this._indices.splice(t,0,e);break}for(let e=this._indices.length-1;e>=0&&this._indices[e]-1===this._indices[e-1];e--)this._indices.pop()}put(e){this._busyHandler&&0===Object.keys(this._store).length&&this._busyHandler();const t=this._genId();return this._store[t]=e,t}fetch(e){const t=this._store[e];return t&&!t.__remote_method&&(delete this._store[e],this._releaseId(e),this._readyHandler&&0===Object.keys(this._store).length&&this._readyHandler()),t&&t.__promise_pair&&this.fetch(t.__promise_pair),t}}},function(e,t){function r(e){if(e)return function(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}(e)}t.Emitter=r,r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var i=0;i<n.length;i++)if((r=n[i])===t||r.fn===t){n.splice(i,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},r.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(r){n=0;for(var i=(r=r.slice(0)).length;n<i;++n)r[n].apply(this,t)}return this},r.prototype.emitReserved=r.prototype.emit,r.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},r.prototype.hasListeners=function(e){return!!this.listeners(e).length}},function(e,t,r){"use strict";t.a="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(e,t,r){"use strict";r.d(t,"b",(function(){return i})),r.d(t,"a",(function(){return a}));var n=r(4);function i(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const o=setTimeout,s=clearTimeout;function a(e,t){t.useNativeTimers?(e.setTimeoutFn=o.bind(n.a),e.clearTimeoutFn=s.bind(n.a)):(e.setTimeoutFn=setTimeout.bind(n.a),e.clearTimeoutFn=clearTimeout.bind(n.a))}},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.d(__webpack_exports__,"a",(function(){return setupIframe}));var _pluginCore_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(10),_rpc_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(2),_utils_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(1);function _htmlToElement(e){var t=document.createElement("template");return e=e.trim(),t.innerHTML=e,t.content.firstChild}const _inWebWorker="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope;async function executeEsModule(e){const t="data:text/javascript;charset=utf-8,"+encodeURIComponent(e);await import(t)}class Connection extends _utils_js__WEBPACK_IMPORTED_MODULE_2__.a{constructor(e){super(e&&e.debug),this.config=e||{},this.peer_id=Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__.f)()}connect(){this.config.target_origin=this.config.target_origin||"*",this.config.broadcastChannel?this.broadcastChannel=new BroadcastChannel(this.config.broadcastChannel):this.broadcastChannel=null,this.broadcastChannel?this.broadcastChannel.addEventListener("message",this):globalThis.addEventListener("message",this),this.emit({type:"initialized",config:this.config,origin:globalThis.location.origin,peer_id:this.peer_id}),this._fire("connected")}handleEvent(e){"message"!==e.type||!this.broadcastChannel&&"*"!==this.config.target_origin&&e.origin&&e.origin!==this.config.target_origin||(e.data.peer_id===this.peer_id?this._fire(e.data.type,e.data):this.config.debug&&console.log(`connection peer id mismatch ${e.data.peer_id} !== ${this.peer_id}`))}disconnect(){this._fire("beforeDisconnect"),globalThis.removeEventListener("message",this),this._fire("disconnected")}emit(e){let t;this.broadcastChannel?this.broadcastChannel.postMessage(e):e.__transferables__?(t=e.__transferables__,delete e.__transferables__):_inWebWorker?self.postMessage(e,t):parent.postMessage(e,this.config.target_origin,t)}async execute(code){try{if("requirements"===code.type)await Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__.d)(code.requirements);else if("script"===code.type)if(code.src){var script_node=document.createElement("script");script_node.setAttribute("type",code.attrs.type),script_node.setAttribute("src",code.src),document.head.appendChild(script_node)}else if(code.content&&"javascript"===code.attrs.lang)"module"===code.attrs.type?await executeEsModule(code.content):eval(code.content);else{var node=document.createElement("script");for(let e in code.attrs)node.setAttribute(e,code.attrs[e]);node.appendChild(document.createTextNode(code.content)),document.body.appendChild(node)}else if("style"===code.type){const e=document.createElement("style");code.src&&(e.src=code.src),e.innerHTML=code.content,document.head.appendChild(e)}else if("link"===code.type){const e=document.createElement("link");code.rel&&(e.rel=code.rel),code.href&&(e.href=code.href),code.attrs&&code.attrs.type&&(e.type=code.attrs.type),document.head.appendChild(e)}else{if("html"!==code.type)throw"unsupported code type.";document.body.appendChild(_htmlToElement(code.content))}_inWebWorker?self.postMessage({type:"executed"}):parent.postMessage({type:"executed"},this.config.target_origin)}catch(e){console.error("failed to execute scripts: ",code,e),_inWebWorker?self.postMessage({type:"executed",error:e.stack||String(e)}):parent.postMessage({type:"executed",error:e.stack||String(e)},this.config.target_origin)}}}function setupIframe(e){(e=e||{}).dedicated_thread=!1,e.lang="javascript",e.api_version=_rpc_js__WEBPACK_IMPORTED_MODULE_1__.a;const t=new Connection(e);Object(_pluginCore_js__WEBPACK_IMPORTED_MODULE_0__.a)(t,e),t.connect()}},function(e,t,r){"use strict";r.d(t,"c",(function(){return i})),r.d(t,"a",(function(){return o})),r.d(t,"d",(function(){return s})),r.d(t,"b",(function(){return a}));var n=r(4);const i="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),o=n.a.WebSocket||n.a.MozWebSocket,s=!0,a="arraybuffer"},function(e){e.exports=JSON.parse('{"a":"0.5.9"}')},function(e,t,r){"use strict";r.d(t,"e",(function(){return b})),r.d(t,"c",(function(){return h})),r.d(t,"d",(function(){return g})),r.d(t,"a",(function(){return y})),r.d(t,"b",(function(){return w}));const n=Object.create(null);n.open="0",n.close="1",n.ping="2",n.pong="3",n.message="4",n.upgrade="5",n.noop="6";const i=Object.create(null);Object.keys(n).forEach(e=>{i[n[e]]=e});const o={type:"error",data:"parser error"},s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),a="function"==typeof ArrayBuffer,c=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+e)},r.readAsDataURL(e)};for(var h=({type:e,data:t},r,i)=>{return s&&t instanceof Blob?r?i(t):c(t,i):a&&(t instanceof ArrayBuffer||(o=t,"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(o):o&&o.buffer instanceof ArrayBuffer))?r?i(t):c(new Blob([t]),i):i(n[e]+(t||""));var o},u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",f="undefined"==typeof Uint8Array?[]:new Uint8Array(256),l=0;l<u.length;l++)f[u.charCodeAt(l)]=l;const p="function"==typeof ArrayBuffer,d=(e,t)=>{if(p){const r=function(e){var t,r,n,i,o,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);var h=new ArrayBuffer(s),u=new Uint8Array(h);for(t=0;t<a;t+=4)r=f[e.charCodeAt(t)],n=f[e.charCodeAt(t+1)],i=f[e.charCodeAt(t+2)],o=f[e.charCodeAt(t+3)],u[c++]=r<<2|n>>4,u[c++]=(15&n)<<4|i>>2,u[c++]=(3&i)<<6|63&o;return h}(e);return _(r,t)}return{base64:!0,data:e}},_=(e,t)=>{switch(t){case"blob":return e instanceof ArrayBuffer?new Blob([e]):e;case"arraybuffer":default:return e}};var y=(e,t)=>{if("string"!=typeof e)return{type:"message",data:_(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:d(e.substring(1),t)};return i[r]?e.length>1?{type:i[r],data:e.substring(1)}:{type:i[r]}:o};const m=String.fromCharCode(30),g=(e,t)=>{const r=e.length,n=new Array(r);let i=0;e.forEach((e,o)=>{h(e,!1,e=>{n[o]=e,++i===r&&t(n.join(m))})})},w=(e,t)=>{const r=e.split(m),n=[];for(let e=0;e<r.length;e++){const i=y(r[e],t);if(n.push(i),"error"===i.type)break}return n},b=4},function(e,t,r){"use strict";r.d(t,"a",(function(){return i}));var n=r(2);function i(e,t){t=t||{};const r={},i=new n.b(e,t,r);i.on("getInterface",(function(){a()})),i.on("remoteReady",(function(){const e=i.getRemote()||{};e.registerCodec=function(e){if(!e.name||!e.encoder&&!e.decoder)throw new Error("Invalid codec format, please make sure you provide a name, type, encoder and decoder.");if(e.type)for(let t of Object.keys(r))r[t].type!==e.type&&t!==e.name||(delete r[t],console.warn("Remove duplicated codec: "+t));r[e.name]=e},e.init=function(e){i.setInterface({setup(){}},e)},e.disposeObject=function(e){i.disposeObject(e)},e.export=function(e,t){i.setInterface(e,t)},e.onLoad=function(e){e=c(e),o?e():s.push(e)},e.dispose=function(e){i.disconnect()},e._rpc=i,"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?(self.api=e,self.postMessage({type:"imjoy_remote_api_ready"}),self.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))):window.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))}));let o=!1;const s=[],a=function(){if(!o){let e;for(o=!0;e=s.pop();)e()}},c=function(e){const t=typeof e;if("function"!==t){throw new Error("A function may only be subsribed to the event, "+t+" was provided instead")}return e};return i}},,function(e,t,r){"use strict";r.d(t,"a",(function(){return s}));var n=r(9),i=r(3),o=r(5);class s extends i.Emitter{constructor(e){super(),this.writable=!1,Object(o.a)(this,e),this.opts=e,this.query=e.query,this.readyState="",this.socket=e.socket}onError(e,t){const r=new Error(e);return r.type="TransportError",r.description=t,super.emit("error",r),this}open(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emit("open")}onData(e){const t=Object(n.a)(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emit("packet",e)}onClose(){this.readyState="closed",super.emit("close")}}},function(e,t){t.encode=function(e){var t="";for(var r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t},t.decode=function(e){for(var t={},r=e.split("&"),n=0,i=r.length;n<i;n++){var o=r[n].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}},function(e,t,r){"use strict";r.r(t),r.d(t,"waitForInitialization",(function(){return u})),r.d(t,"setupRPC",(function(){return f}));var n=r(15),i=r.n(n),o=r(6),s=r(1);r.d(t,"loadRequirements",(function(){return s.c}));var a=r(2);r.d(t,"RPC",(function(){return a.b})),r.d(t,"API_VERSION",(function(){return a.a}));var c=r(8);function h(){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope}function u(e){h()&&(globalThis.parent=self),(e=e||{}).enable_service_worker&&(Object(s.g)(e.base_url,e.target_origin,e.cache_requirements),e.enable_service_worker=!1),e.cache_requirements&&delete e.cache_requirements;const t=e.target_origin||"*";if(e.credential_required&&"function"!=typeof e.verify_credential)throw new Error("Please also provide the `verify_credential` function with `credential_required`.");if(e.credential_required&&"*"===t)throw new Error("`target_origin` was set to `*` with `credential_required=true`, there is a security risk that you may leak the credential to website from other origin. Please specify the `target_origin` explicitly.");const r=Object(s.f)(),n=i=>{if("message"===i.type&&(!i.origin||"*"===t||i.origin===t)){if("initialize"!==i.data.type)throw new Error("unrecognized message: "+i.data);{globalThis.removeEventListener("message",n),i.data.peer_id!==r&&console.warn(`${i.data.config&&i.data.config.name}: connection peer id mismatch ${i.data.peer_id} !== ${r}`);const o=i.data.config;"*"!==t&&(o.target_origin=t),e.credential_required?e.verify_credential(o.credential).then(e=>{if(!e||!e.auth||e.error)throw new Error("Failed to verify the credentail:"+(e&&e.error));o.auth=e.auth,f(o).then(()=>{console.log("ImJoy RPC loaded successfully!")})}):f(o).then(()=>{console.log("ImJoy RPC loaded successfully!")})}}};globalThis.addEventListener("message",n),h()?parent.postMessage({type:"imjoyRPCReady",config:e,peer_id:r}):parent.postMessage({type:"imjoyRPCReady",config:e,peer_id:r},"*")}function f(e){return(e=e||{}).name=e.name||Object(s.f)(),(e=Object(s.e)(e)).enable_service_worker&&Object(s.g)(e.base_url,e.target_origin,e.cache_requirements),e.cache_requirements&&delete e.cache_requirements,new Promise((t,r)=>{const n=r=>{const i=r.detail;e.expose_api_globally&&(globalThis.api=i),t(i),globalThis.removeEventListener("imjoy_remote_api_ready",n)};if(function(){try{return window.self!==window.top}catch(e){return!0}}()){if("web-worker"===e.type)try{!function(e){if(!e.allow_execution)throw new Error("web-worker plugin can only work with allow_execution=true");let t=null;e.broadcastChannel&&(t=new BroadcastChannel(e.broadcastChannel));const r=new i.a,n=setTimeout((function(){r.terminate(),console.warn("Plugin failed to start as a web-worker, running in an iframe instead."),Object(o.a)(e)}),2e3),a=Object(s.f)();r.addEventListener("message",(function(i){let o=void 0;const s=i.data;if("worker-ready"===s.type)return r.postMessage({type:"connectRPC",config:e}),void clearTimeout(n);"initialized"===s.type?(s.config=Object.assign({},e,s.config),s.origin=window.location.origin,s.peer_id=a):"imjoy_remote_api_ready"===s.type?window.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:null})):"cacheRequirements"===s.type&&"function"==typeof cache_requirements?cache_requirements(s.requirements):"disconnect"===s.type?r.terminate():s.__transferables__&&(o=s.__transferables__,delete s.__transferables__),t?t.postMessage(s):parent.postMessage(s,e.target_origin||"*",o)})),(t||window).addEventListener("message",(function(n){if("message"===n.type&&(t||"*"===e.target_origin||n.origin===e.target_origin)){let t=void 0;const i=n.data;i.__transferables__&&(t=i.__transferables__,delete i.__transferables__),i.peer_id===a?r.postMessage(i,t):e.debug&&console.log(`connection peer id mismatch ${i.peer_id} !== ${a}`)}}))}(e)}catch(t){Object(o.a)(e)}else{if(!["rpc-window","rpc-worker","iframe","window"].includes(e.type))return console.error("Unsupported plugin type: "+e.type),void r("Unsupported plugin type: "+e.type);Object(o.a)(e)}globalThis.addEventListener("imjoy_remote_api_ready",n)}else h()?Object(o.a)(e):r(new Error("imjoy-rpc should only run inside an iframe or a webworker."))})}r.d(t,"VERSION",(function(){return c.a}))},function(e,t,r){e.exports=function(){return r(18)('!function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)r.d(n,i,function(t){return e[t]}.bind(null,i));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=3)}([function(module,__webpack_exports__,__webpack_require__){"use strict";function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}__webpack_require__.d(__webpack_exports__,"d",(function(){return randId})),__webpack_require__.d(__webpack_exports__,"b",(function(){return dtypeToTypedArray})),__webpack_require__.d(__webpack_exports__,"c",(function(){return loadRequirementsInWebworker})),__webpack_require__.d(__webpack_exports__,"e",(function(){return typedArrayToDtype})),__webpack_require__.d(__webpack_exports__,"a",(function(){return MessageEmitter}));const dtypeToTypedArray={int8:Int8Array,int16:Int16Array,int32:Int32Array,uint8:Uint8Array,uint16:Uint16Array,uint32:Uint32Array,float32:Float32Array,float64:Float64Array,array:Array};async function loadRequirementsInWindow(e){function t(e){return new Promise((t,r)=>{var n=document.createElement("script");n.src=e,n.type="text/javascript",n.onload=t,n.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},n.onerror=r,document.head.appendChild(n)})}async function r(){for(var e=Array.prototype.slice.call(arguments),r=e.length,n=0;n<r;n++)await t(e[n])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var n;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var i=0;i<e.length;i++)e[i].toLowerCase().endsWith(".css")||e[i].startsWith("css:")?(e[i].startsWith("css:")&&(e[i]=e[i].slice(4)),(n=document.createElement("link")).rel="stylesheet",n.href=e[i],document.head.appendChild(n)):e[i].toLowerCase().endsWith(".mjs")||e[i].startsWith("mjs:")?(e[i].startsWith("mjs:")&&(e[i]=e[i].slice(4)),await import(e[i])):e[i].toLowerCase().endsWith(".js")||e[i].startsWith("js:")?(e[i].startsWith("js:")&&(e[i]=e[i].slice(3)),await r(e[i])):e[i].startsWith("http")?await r(e[i]):e[i].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[i])}catch(t){throw"failed to import required scripts: "+e.toString()}}async function loadRequirementsInWebworker(e){if(e&&(Array.isArray(e)||"string"==typeof e))try{Array.isArray(e)||(e=[e]);for(var t=0;t<e.length;t++){if(e[t].toLowerCase().endsWith(".css")||e[t].startsWith("css:"))throw"unable to import css in a webworker";e[t].toLowerCase().endsWith(".js")||e[t].startsWith("js:")?(e[t].startsWith("js:")&&(e[t]=e[t].slice(3)),importScripts(e[t])):e[t].startsWith("http")?importScripts(e[t]):e[t].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[t])}}catch(t){throw"failed to import required scripts: "+e.toString()}}function loadRequirements(e){return"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?loadRequirementsInWebworker(e):loadRequirementsInWindow(e)}function normalizeConfig(e){return e.version=e.version||"0.1.0",e.description=e.description||`[TODO: add description for ${e.name} ]`,e.type=e.type||"rpc-window",e.id=e.id||randId(),e.target_origin=e.target_origin||"*",e.allow_execution=e.allow_execution||!1,e=Object.keys(e).reduce((t,r)=>("function"!=typeof e[r]&&(t[r]=e[r]),t),{})}const typedArrayToDtypeMapping={Int8Array:"int8",Int16Array:"int16",Int32Array:"int32",Uint8Array:"uint8",Uint16Array:"uint16",Uint32Array:"uint32",Float32Array:"float32",Float64Array:"float64",Array:"array"},typedArrayToDtypeKeys=[];for(const arrType of Object.keys(typedArrayToDtypeMapping))typedArrayToDtypeKeys.push(eval(arrType));function typedArrayToDtype(e){let t=typedArrayToDtypeMapping[e.constructor.name];if(!t){const r=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(r instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise((function(t,r){const n={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void r("Service worker is not supported.");const i=new MessageChannel;i.port1.onmessage=function(e){e.data&&e.data.error?r(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(n,[i.port2]):r("Service worker controller is not available")}))}async function cacheRequirements(e){e=e||[],Array.isArray(e)||(e=[e]);for(let t of e)t.startsWith("js:")&&(t=t.slice(3)),t.startsWith("css:")&&(t=t.slice(4)),t.startsWith("cache:")&&(t=t.slice(6)),t.startsWith("http")&&await cacheUrlInServiceWorker(t).catch(e=>{console.error(e)})}function setupServiceWorker(e,t,r){if("serviceWorker"in navigator){if(e=e||"/",navigator.serviceWorker.register(e+"plugin-service-worker.js").then((function(e){console.log("ServiceWorker registration successful with scope: ",e.scope)}),(function(e){console.log("ServiceWorker registration failed: ",e)})),t=t||"*",(r=r||cacheRequirements)&&"function"!=typeof r)throw new Error("config.cache_requirements must be a function");window.addEventListener("message",(function(e){if("*"===t||e.origin===t){const t=e.data;"cacheRequirements"===t.type&&r(t.requirements)}}))}}function urlJoin(...e){return e.join("/").replace(/[\\/]+/g,"/").replace(/^(.+):\\//,"$1://").replace(/^file:/,"file:/").replace(/\\/(\\?|&|#[^!])/g,"$1").replace(/\\?/g,"&").replace("&","?")}class MessageEmitter{constructor(e){this._event_handlers={},this._once_handlers={},this._debug=e}emit(){throw new Error("emit is not implemented")}on(e,t){this._event_handlers[e]||(this._event_handlers[e]=[]),this._event_handlers[e].push(t)}once(e,t){t.___event_run_once=!0,this.on(e,t)}off(e,t){if(e||t){if(e&&!t)this._event_handlers[e]&&(this._event_handlers[e]=[]);else if(this._event_handlers[e]){const r=this._event_handlers[e].indexOf(t);r>=0&&this._event_handlers[e].splice(r,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var r=this._event_handlers[e].length;r--;){const n=this._event_handlers[e][r];try{n(t)}catch(e){console.error(e)}finally{n.___event_run_once&&this._event_handlers[e].splice(r,1)}}else this._debug&&console.warn("unhandled event",e,t)}}},function(e,t,r){"use strict";r.d(t,"a",(function(){return i})),r.d(t,"b",(function(){return c}));var n=r(0);const i="0.2.3",o=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function s(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e),0),r.set(new Uint8Array(t),e.byteLength),r.buffer}function a(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?a(e,t.split(".")):0===t.length?e:a(e[t[0]],t.slice(1))}class c extends n.a{constructor(e,t,r){super(t&&t.debug),this._connection=e,this.config=t||{},this._codecs=r||{},this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._remote_set=!1;const n=this.config.name;this._connection.execute=this._connection.execute||function(){throw new Error(`connection.execute not implemented (in "${n}")`)},this._store=new _,this._method_refs=new _,this._method_refs.onReady(()=>{this._fire("remoteIdle")}),this._method_refs.onBusy(()=>{this._fire("remoteBusy")}),this._setupMessageHanlders()}init(){this._connection.emit({type:"initialized",config:this.config,peer_id:this._connection.peer_id})}setConfig(e){if(e)for(const t of Object.keys(e))this.config[t]=e[t]}getRemoteCallStack(){return this._method_refs.getStack()}getRemote(){return this._remote_interface}setInterface(e,t){if(t=t||{},this.config.name=t.name||this.config.name,this.config.description=t.description||this.config.description,this.config.forwarding_functions)for(let t of this.config.forwarding_functions){const r=this._remote_interface;r[t]&&(e.constructor===Object?e[t]||(e[t]=(...e)=>{r[t](...e)}):e.constructor.constructor===Function&&(e.constructor.prototype[t]||(e.constructor.prototype[t]=(...e)=>{r[t](...e)})))}return this._local_api=e,this._remote_set?this.sendInterface():this._fire("interfaceAvailable"),new Promise(e=>{this.once("interfaceSetAsRemote",e)})}sendInterface(){if(!this._local_api)throw new Error("interface is not set.");this._encode(this._local_api,!0).then(e=>{this._connection.emit({type:"setInterface",api:e})})}_disposeObject(e){if(!this._object_store[e])throw new Error(`Object (id=${e}) not found.`);delete this._object_store[e]}disposeObject(e){return new Promise((t,r)=>{if(!this._object_weakmap.has(e))throw new Error("Invalid object");{const n=this._object_weakmap.get(e);this._connection.once("disposed",e=>{e.error?r(new Error(e.error)):t()}),this._connection.emit({type:"disposeObject",object_id:n})}})}_setupMessageHanlders(){this._connection.on("init",this.init),this._connection.on("execute",e=>{Promise.resolve(this._connection.execute(e.code)).then(()=>{this._connection.emit({type:"executed"})}).catch(e=>{console.error(e),this._connection.emit({type:"executed",error:String(e)})})}),this._connection.on("method",async e=>{let t,r,n,i,o,s;try{e.promise&&([t,r]=await this._unwrap(e.promise,!1));const c=this._object_store[e.object_id];if(n=a(c,e.name),e.name.includes(".")){const t=e.name.split(".");i=a(c,t.slice(0,t.length-1).join("."))}else i=c;o=await this._unwrap(e.args,!0),e.promise?(s=n.apply(i,o),s instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?s.then(t).catch(r):t(s)):n.apply(i,o)}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("callback",async e=>{let t,r,n,i,o;try{if(e.promise&&([t,r]=await this._unwrap(e.promise,!1)),e.promise){if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");o=n.apply(null,i),o instanceof Promise||n.constructor&&"AsyncFunction"===n.constructor.name?o.then(t).catch(r):t(o)}else{if(n=this._store.fetch(e.id),i=await this._unwrap(e.args,!0),!n)throw new Error("Please notice that callback function can only called once, if you want to call a function for multiple times, please make it as a plugin api function. See https://imjoy.io/docs for more details.");n.apply(null,i)}}catch(e){console.error(this.config.name,e),r&&r(e)}}),this._connection.on("disposeObject",e=>{try{this._disposeObject(e.object_id),this._connection.emit({type:"disposed"})}catch(e){console.error(e),this._connection.emit({type:"disposed",error:String(e)})}}),this._connection.on("setInterface",e=>{this._setRemoteInterface(e.api)}),this._connection.on("getInterface",()=>{this._fire("getInterface"),this._local_api?this.sendInterface():this.once("interfaceAvailable",()=>{this.sendInterface()})}),this._connection.on("interfaceSetAsRemote",()=>{this._remote_set=!0,this._fire("interfaceSetAsRemote")}),this._connection.on("disconnect",()=>{this._fire("beforeDisconnect"),this._connection.disconnect(),this._fire("disconnected")})}requestRemote(){this._connection.emit({type:"getInterface"})}_ndarray(e,t,r){const i=Object(n.e)(e);if(r&&r!==i)throw"dtype doesn\'t match the type of the array: "+i+" != "+r;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:i}}_setRemoteInterface(e){this._decode(e).then(e=>{if(this._remote_interface){for(let e in this._remote_interface)delete this._remote_interface[e];Object.assign(this._remote_interface,e)}else this._remote_interface=e;this._fire("remoteReady"),this._reportRemoteSet()})}_genRemoteMethod(e,t,r){const n=this,i=function(){return new Promise(async(i,o)=>{let s=null;try{s=n._method_refs.put(r?r+"/"+t:t);const a=function(){return null!==s&&n._method_refs.fetch(s),i.apply(this,arguments)},c=function(){return null!==s&&n._method_refs.fetch(s),o.apply(this,arguments)},_=await n._wrap([a,c]);a.__promise_pair=_[1]._rvalue,c.__promise_pair=_[0]._rvalue;let l=Array.prototype.slice.call(arguments);const f=l.length,d=f>0&&"object"==typeof l[f-1]&&null!==l[f-1]&&l[f-1]._rkwargs;d&&delete l[f-1]._rkwargs,l="register"===t||"registerService"===t||"register_service"===t||"export"===t||"on"===t?await n._wrap(l,!0):await n._wrap(l);const p=l.__transferables__;p&&delete l.__transferables__,n._connection.emit({type:"method",target_id:e,name:t,object_id:r,args:l,promise:_,with_kwargs:d},p)}catch(e){s&&n._method_refs.fetch(s),o(`Failed to exectue remote method (interface: ${r||n.id}, method: ${t}), error: ${e}`)}})};return i.__remote_method=!0,i}_reportRemoteSet(){this._connection.emit({type:"interfaceSetAsRemote"})}async _encode(e,t,r){const i=typeof e;if("number"===i||"string"===i||"boolean"===i||null==e||e instanceof ArrayBuffer)return e;let s;if("function"==typeof e){if(t){if(!r)throw new Error("objectId is not specified.");s={_rtype:"interface",_rtarget_id:this._connection.peer_id,_rintf:r,_rvalue:t},this._method_weakmap.set(e,s)}else if(this._method_weakmap.has(e))s=this._method_weakmap.get(e);else{const t=this._store.put(e);s={_rtype:"callback",_rtarget_id:this._connection.peer_id,_rname:e.constructor&&e.constructor.name||t,_rvalue:t}}return s}if(e.constructor instanceof Object&&e._rtype){if(e._rintf){const n=e._rtype;delete e._rtype,s=await this._encode(e,t,r),s._rtype=n}else s=e;return s}const a=[],c=e._transfer,_=Array.isArray(e);for(let n of Object.keys(this._codecs)){const i=this._codecs[n];if(i.encoder&&e instanceof i.type){let n=await Promise.resolve(i.encoder(e));if(n&&!n._rtype&&(n._rtype=i.name),n&&n._rintf){const e=n._rtype;delete n._rtype,n=await this._encode(n,t,r),n._rtype=e}return s=n,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const t=e.dataSync();(e._transfer||c)&&(a.push(t.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:t.buffer,_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const t=Object(n.e)(e.selection.data);(e._transfer||c)&&(a.push(e.selection.data.buffer),delete e._transfer),s={_rtype:"ndarray",_rvalue:e.selection.data.buffer,_rshape:e.shape,_rdtype:t}}else if(e instanceof Error)console.error(e),s={_rtype:"error",_rvalue:e.toString()};else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e!==Object(e)||e instanceof Boolean||e instanceof String||e instanceof Date||e instanceof RegExp||e instanceof ImageData||"undefined"!=typeof FileList&&e instanceof FileList||"undefined"!=typeof FileSystemDirectoryHandle&&e instanceof FileSystemDirectoryHandle||"undefined"!=typeof FileSystemFileHandle&&e instanceof FileSystemFileHandle||"undefined"!=typeof FileSystemHandle&&e instanceof FileSystemHandle||"undefined"!=typeof FileSystemWritableFileStream&&e instanceof FileSystemWritableFileStream)s=e;else if("undefined"!=typeof File&&e instanceof File)s={_rtype:"file",_rname:e.name,_rmime:e.type,_rvalue:e,_rpath:e._path||e.webkitRelativePath};else if(e instanceof Blob)s={_rtype:"blob",_rvalue:e};else if(e instanceof o){(e._transfer||c)&&(a.push(e.buffer),delete e._transfer);const t=Object(n.e)(e);s={_rtype:"typedarray",_rvalue:e.buffer,_rdtype:t}}else if(e instanceof DataView)(e._transfer||c)&&(a.push(e.buffer),delete e._transfer),s={_rtype:"memoryview",_rvalue:e.buffer};else if(e instanceof Set)s={_rtype:"set",_rvalue:await this._encode(Array.from(e),t)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t)};else if(e.constructor instanceof Object||Array.isArray(e)){let i;if(s=_?[]:{},e.constructor===Object||Array.isArray(e))i=Object.keys(e);else{if(e.constructor===Function)throw new Error("Please instantiate the class before exportting it.");if(e.constructor.constructor!==Function)throw Error("Unsupported interface type");i=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),t=!0}let o=!1;if(e._rintf||t){r||(r="string"==typeof e._rintf&&e._rintf.length>0?e._rintf:Object(n.d)(),this._object_store[r]&&console.warn("Overwritting interface object with the same id: "+r),this._object_store[r]=e);for(let n of i)"constructor"!==n&&(n.startsWith("_")||(s[n]=await this._encode(e[n],"string"==typeof t?t+"."+n:n,r),"function"==typeof e[n]&&(o=!0)));o&&(s._rintf=r),e.on&&"function"==typeof e.on&&e.on("close",()=>{delete this._object_store[r]})}else for(let t of i)["hasOwnProperty","constructor"].includes(t)||(s[t]=await this._encode(e[t]))}else{if("object"!=typeof e)throw"imjoy-rpc: Unsupported data type:"+e;{const t=Object.getOwnPropertyNames(Object.getPrototypeOf(e)).concat(Object.keys(e)),r=Object(n.d)();for(let r of t)["hasOwnProperty","constructor"].includes(r)||(s[r]=await this._encode(e[r],r,s));s._rintf=r}}if(a.length>0&&(s.__transferables__=a),!s)throw new Error("Failed to encode object");return s}async _decode(e,t){if(!e)return e;let r;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){if(e._rintf){const r=e._rtype;delete e._rtype,(e=await this._decode(e,t))._rtype=r}r=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("callback"===e._rtype)r=this._genRemoteCallback(e._rtarget_id,e._rvalue,t);else if("interface"===e._rtype)r=this._genRemoteMethod(e._rtarget_id,e._rvalue,e._rintf);else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s)),r=nj.array(new Uint8(e._rvalue),e._rdtype).reshape(e._rshape);else if("undefined"!=typeof tf&&tf.Tensor){Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(s));const t=n.b[e._rdtype];r=tf.tensor(new t(e._rvalue),e._rshape,e._rdtype)}else r=e;else if("error"===e._rtype)r=new Error(e._rvalue);else if("file"===e._rtype)e._rvalue instanceof File?(r=e._rvalue,r._path=e._rpath):(r=new File([e._rvalue],e._rname,{type:e._rmime}),r._path=e._rpath);else if("typedarray"===e._rtype){const t=n.b[e._rdtype];if(!t)throw new Error("unsupported dtype: "+e._rdtype);r=new t(e._rvalue)}else if("memoryview"===e._rtype)r=new DataView(e._rvalue);else if("blob"===e._rtype)r=e._rvalue instanceof Blob?e._rvalue:new Blob([e._rvalue],{type:e._rmime});else if("orderedmap"===e._rtype)r=new Map(await this._decode(e._rvalue,t));else if("set"===e._rtype)r=new Set(await this._decode(e._rvalue,t));else if(e._rintf){const n=e._rtype;delete e._rtype,r=await this._decode(e,t),r._rtype=n}else r=e;else if(e.constructor===Object||Array.isArray(e)){const n=Array.isArray(e);r=n?[]:{};for(let i of Object.keys(e))if(n||e.hasOwnProperty(i)){const n=e[i];r[i]=await this._decode(n,t)}}else r=e;if(void 0===r)throw new Error("Failed to decode object");return e._rintf&&this._object_weakmap.set(r,e._rintf),r}async _wrap(e,t){return await this._encode(e,t)}async _unwrap(e,t){return await this._decode(e,t)}_genRemoteCallback(e,t,r){const n=this;let i;return r?(i=function(){return new Promise(async(r,i)=>{const o=await n._wrap(Array.prototype.slice.call(arguments)),s=o.length,a=s>0&&"object"==typeof o[s-1]&&null!==o[s-1]&&o[s-1]._rkwargs;a&&delete o[s-1]._rkwargs;const c=o.__transferables__;c&&delete o.__transferables__;const _=await n._wrap([r,i]);r.__promise_pair=_[1]._rvalue,i.__promise_pair=_[0]._rvalue;try{n._connection.emit({type:"callback",target_id:e,id:t,args:o,promise:_,with_kwargs:a},c)}catch(e){i(`Failed to exectue remote callback ( id: ${t}).`)}})},i):(i=async function(){const r=await n._wrap(Array.prototype.slice.call(arguments)),i=r.length,o=i>0&&"object"==typeof r[i-1]&&null!==r[i-1]&&r[i-1]._rkwargs;o&&delete r[i-1]._rkwargs;const s=r.__transferables__;return s&&delete r.__transferables__,n._connection.emit({type:"callback",target_id:e,id:t,args:r,with_kwargs:o},s)},i)}reset(){this._event_handlers={},this._once_handlers={},this._remote_interface=null,this._object_store={},this._method_weakmap=new WeakMap,this._object_weakmap=new WeakMap,this._local_api=null,this._store=new _,this._method_refs=new _}disconnect(){this._connection.emit({type:"disconnect"}),this.reset(),setTimeout(()=>{this._connection.disconnect()},2e3)}}class _{constructor(){this._store={},this._indices=[0],this._readyHandler=function(){},this._busyHandler=function(){},this._readyHandler()}onReady(e){this._readyHandler=e||function(){}}onBusy(e){this._busyHandler=e||function(){}}getStack(){return Object.keys(this._store).length}_genId(){let e;return e=1===this._indices.length?this._indices[0]++:this._indices.shift(),e}_releaseId(e){for(let t=0;t<this._indices.length;t++)if(e<this._indices[t]){this._indices.splice(t,0,e);break}for(let e=this._indices.length-1;e>=0&&this._indices[e]-1===this._indices[e-1];e--)this._indices.pop()}put(e){this._busyHandler&&0===Object.keys(this._store).length&&this._busyHandler();const t=this._genId();return this._store[t]=e,t}fetch(e){const t=this._store[e];return t&&!t.__remote_method&&(delete this._store[e],this._releaseId(e),this._readyHandler&&0===Object.keys(this._store).length&&this._readyHandler()),t&&t.__promise_pair&&this.fetch(t.__promise_pair),t}}},function(e,t,r){"use strict";r.d(t,"a",(function(){return i}));var n=r(1);function i(e,t){t=t||{};const r={},i=new n.b(e,t,r);i.on("getInterface",(function(){a()})),i.on("remoteReady",(function(){const e=i.getRemote()||{};e.registerCodec=function(e){if(!e.name||!e.encoder&&!e.decoder)throw new Error("Invalid codec format, please make sure you provide a name, type, encoder and decoder.");if(e.type)for(let t of Object.keys(r))r[t].type!==e.type&&t!==e.name||(delete r[t],console.warn("Remove duplicated codec: "+t));r[e.name]=e},e.init=function(e){i.setInterface({setup(){}},e)},e.disposeObject=function(e){i.disposeObject(e)},e.export=function(e,t){i.setInterface(e,t)},e.onLoad=function(e){e=c(e),o?e():s.push(e)},e.dispose=function(e){i.disconnect()},e._rpc=i,"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?(self.api=e,self.postMessage({type:"imjoy_remote_api_ready"}),self.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))):window.dispatchEvent(new CustomEvent("imjoy_remote_api_ready",{detail:e}))}));let o=!1;const s=[],a=function(){if(!o){let e;for(o=!0;e=s.pop();)e()}},c=function(e){const t=typeof e;if("function"!==t){throw new Error("A function may only be subsribed to the event, "+t+" was provided instead")}return e};return i}},function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);var _pluginCore_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(2),_rpc_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(1),_utils_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(0);if(!("undefined"!=typeof WorkerGlobalScope&&self&&self instanceof WorkerGlobalScope))throw new Error("This script can only loaded in a webworker");async function executeEsModule(e){const t="data:text/javascript;charset=utf-8,"+encodeURIComponent(e);await import(t)}class Connection extends _utils_js__WEBPACK_IMPORTED_MODULE_2__.a{constructor(e){super(e&&e.debug),this.config=e||{}}connect(){self.addEventListener("message",e=>{this._fire(e.data.type,e.data)}),this.emit({type:"initialized",config:this.config})}disconnect(){this._fire("beforeDisconnect"),self.close(),this._fire("disconnected")}emit(e){let t=void 0;e.__transferables__&&(t=e.__transferables__,delete e.__transferables__),self.postMessage(e,t)}async execute(code){if("requirements"===code.type)await Object(_utils_js__WEBPACK_IMPORTED_MODULE_2__.c)(code.requirements);else{if("script"!==code.type)throw"unsupported code type.";try{"module"===code.attrs.type?await executeEsModule(code.content):eval(code.content)}catch(e){throw console.error(e.message,e.stack),e}}"requirements"===code.type&&self.postMessage({type:"cacheRequirements",requirements:code.requirements})}}const config={type:"web-worker",dedicated_thread:!0,allow_execution:!0,lang:"javascript",api_version:_rpc_js__WEBPACK_IMPORTED_MODULE_1__.a},conn=new Connection(config);conn.on("connectRPC",e=>{Object(_pluginCore_js__WEBPACK_IMPORTED_MODULE_0__.a)(conn,Object.assign(e.config,config))}),conn.connect(),self.postMessage({type:"worker-ready"})}]);\n//# sourceMappingURL=plugin.webworker.js.map',null)}},function(e,t){var r=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];e.exports=function(e){var t=e,i=e.indexOf("["),o=e.indexOf("]");-1!=i&&-1!=o&&(e=e.substring(0,i)+e.substring(i,o).replace(/:/g,";")+e.substring(o,e.length));for(var s,a,c=r.exec(e||""),h={},u=14;u--;)h[n[u]]=c[u]||"";return-1!=i&&-1!=o&&(h.source=t,h.host=h.host.substring(1,h.host.length-1).replace(/;/g,":"),h.authority=h.authority.replace("[","").replace("]","").replace(/;/g,":"),h.ipv6uri=!0),h.pathNames=function(e,t){var r=t.replace(/\/{2,9}/g,"/").split("/");"/"!=t.substr(0,1)&&0!==t.length||r.splice(0,1);"/"==t.substr(t.length-1,1)&&r.splice(r.length-1,1);return r}(0,h.path),h.queryKey=(s=h.query,a={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,r){t&&(a[t]=r)})),a),h}},function(e,t,r){"use strict";var n,i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),o={},s=0,a=0;function c(e){var t="";do{t=i[e%64]+t,e=Math.floor(e/64)}while(e>0);return t}function h(){var e=c(+new Date);return e!==n?(s=0,n=e):e+"."+c(s++)}for(;a<64;a++)o[i[a]]=a;h.encode=c,h.decode=function(e){var t=0;for(a=0;a<e.length;a++)t=64*t+o[e.charAt(a)];return t},e.exports=h},function(e,t,r){"use strict";var n=window.URL||window.webkitURL;e.exports=function(e,t){try{try{var r;try{(r=new(window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder)).append(e),r=r.getBlob()}catch(t){r=new Blob([e])}return new Worker(n.createObjectURL(r))}catch(t){return new Worker("data:application/javascript,"+encodeURIComponent(e))}}catch(e){if(!t)throw Error("Inline worker is not supported");return new Worker(t)}}},function(e,t){try{e.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){e.exports=!1}},function(e,t,r){"use strict";(function(e){r.d(t,"a",(function(){return l}));var n=r(12),i=r(13),o=r.n(i),s=r(17),a=r.n(s),c=r(5),h=r(7),u=r(9);const f="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class l extends n.a{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,r=f?{}:Object(c.b)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=h.d&&!f?t?new h.a(e,t):new h.a(e):new h.a(e,t,r)}catch(e){return this.emit("error",e)}this.ws.binaryType=this.socket.binaryType||h.b,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=this.onClose.bind(this),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(t){this.writable=!1;for(let r=0;r<t.length;r++){const n=t[r],i=r===t.length-1;Object(u.c)(n,this.supportsBinary,t=>{const r={};if(!h.d&&(n.options&&(r.compress=n.options.compress),this.opts.perMessageDeflate)){("string"==typeof t?e.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(r.compress=!1)}try{h.d?this.ws.send(t):this.ws.send(t,r)}catch(e){}i&&Object(h.c)(()=>{this.writable=!0,this.emit("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let r="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=a()()),this.supportsBinary||(e.b64=1);const n=o.a.encode(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}check(){return!(!h.a||"__initialize"in h.a&&this.name===l.prototype.name)}}}).call(this,r(23).Buffer)},function(e,t){function r(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}e.exports=r,r.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-r:e+r}return 0|Math.min(e,this.max)},r.prototype.reset=function(){this.attempts=0},r.prototype.setMin=function(e){this.ms=e},r.prototype.setMax=function(e){this.max=e},r.prototype.setJitter=function(e){this.jitter=e}},,function(e,t,r){"use strict";(function(e){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
var n=r(25),i=r(26),o=r(27);function s(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(s()<t)throw new RangeError("Invalid typed array length");return c.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t)).__proto__=c.prototype:(null===e&&(e=new c(t)),e.length=t),e}function c(e,t,r){if(!(c.TYPED_ARRAY_SUPPORT||this instanceof c))return new c(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return f(this,e)}return h(this,e,t,r)}function h(e,t,r,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?function(e,t,r,n){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");t=void 0===r&&void 0===n?new Uint8Array(t):void 0===n?new Uint8Array(t,r):new Uint8Array(t,r,n);c.TYPED_ARRAY_SUPPORT?(e=t).__proto__=c.prototype:e=l(e,t);return e}(e,t,r,n):"string"==typeof t?function(e,t,r){"string"==typeof r&&""!==r||(r="utf8");if(!c.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|d(t,r),i=(e=a(e,n)).write(t,r);i!==n&&(e=e.slice(0,i));return e}(e,t,r):function(e,t){if(c.isBuffer(t)){var r=0|p(t.length);return 0===(e=a(e,r)).length||t.copy(e,0,0,r),e}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||(n=t.length)!=n?a(e,0):l(e,t);if("Buffer"===t.type&&o(t.data))return l(e,t.data)}var n;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(e,t)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function f(e,t){if(u(t),e=a(e,t<0?0:0|p(t)),!c.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function l(e,t){var r=t.length<0?0:0|p(t.length);e=a(e,r);for(var n=0;n<r;n+=1)e[n]=255&t[n];return e}function p(e){if(e>=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|e}function d(e,t){if(c.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return N(e).length;default:if(n)return q(e).length;t=(""+t).toLowerCase(),n=!0}}function _(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,r);case"utf8":case"utf-8":return O(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return S(this,t,r);case"base64":return j(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function y(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function m(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=c.from(t,n)),c.isBuffer(t))return 0===t.length?-1:g(e,t,r,n,i);if("number"==typeof t)return t&=255,c.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):g(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function g(e,t,r,n,i){var o,s=1,a=e.length,c=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function h(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(i){var u=-1;for(o=r;o<a;o++)if(h(e,o)===h(t,-1===u?0:o-u)){if(-1===u&&(u=o),o-u+1===c)return u*s}else-1!==u&&(o-=o-u),u=-1}else for(r+c>a&&(r=a-c),o=r;o>=0;o--){for(var f=!0,l=0;l<c;l++)if(h(e,o+l)!==h(t,l)){f=!1;break}if(f)return o}return-1}function w(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var s=0;s<n;++s){var a=parseInt(t.substr(2*s,2),16);if(isNaN(a))return s;e[r+s]=a}return s}function b(e,t,r,n){return F(q(t,e.length-r),e,r,n)}function v(e,t,r,n){return F(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,n)}function k(e,t,r,n){return v(e,t,r,n)}function A(e,t,r,n){return F(N(t),e,r,n)}function E(e,t,r,n){return F(function(e,t){for(var r,n,i,o=[],s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function j(e,t,r){return 0===t&&r===e.length?n.fromByteArray(e):n.fromByteArray(e.slice(t,r))}function O(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i<r;){var o,s,a,c,h=e[i],u=null,f=h>239?4:h>223?3:h>191?2:1;if(i+f<=r)switch(f){case 1:h<128&&(u=h);break;case 2:128==(192&(o=e[i+1]))&&(c=(31&h)<<6|63&o)>127&&(u=c);break;case 3:o=e[i+1],s=e[i+2],128==(192&o)&&128==(192&s)&&(c=(15&h)<<12|(63&o)<<6|63&s)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:o=e[i+1],s=e[i+2],a=e[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(c=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&c<1114112&&(u=c)}null===u?(u=65533,f=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),i+=f}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=4096));return r}(n)}t.Buffer=c,t.SlowBuffer=function(e){+e!=e&&(e=0);return c.alloc(+e)},t.INSPECT_MAX_BYTES=50,c.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:function(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}(),t.kMaxLength=s(),c.poolSize=8192,c._augment=function(e){return e.__proto__=c.prototype,e},c.from=function(e,t,r){return h(null,e,t,r)},c.TYPED_ARRAY_SUPPORT&&(c.prototype.__proto__=Uint8Array.prototype,c.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&c[Symbol.species]===c&&Object.defineProperty(c,Symbol.species,{value:null,configurable:!0})),c.alloc=function(e,t,r){return function(e,t,r,n){return u(t),t<=0?a(e,t):void 0!==r?"string"==typeof n?a(e,t).fill(r,n):a(e,t).fill(r):a(e,t)}(null,e,t,r)},c.allocUnsafe=function(e){return f(null,e)},c.allocUnsafeSlow=function(e){return f(null,e)},c.isBuffer=function(e){return!(null==e||!e._isBuffer)},c.compare=function(e,t){if(!c.isBuffer(e)||!c.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i<o;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:n<r?1:0},c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(e,t){if(!o(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=c.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){var s=e[r];if(!c.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(n,i),i+=s.length}return n},c.byteLength=d,c.prototype._isBuffer=!0,c.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)y(this,t,t+1);return this},c.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},c.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},c.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?O(this,0,e):_.apply(this,arguments)},c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"},c.prototype.compare=function(e,t,r,n,i){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),s=(r>>>=0)-(t>>>=0),a=Math.min(o,s),h=this.slice(n,i),u=e.slice(t,r),f=0;f<a;++f)if(h[f]!==u[f]){o=h[f],s=u[f];break}return o<s?-1:s<o?1:0},c.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},c.prototype.indexOf=function(e,t,r){return m(this,e,t,r,!0)},c.prototype.lastIndexOf=function(e,t,r){return m(this,e,t,r,!1)},c.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return b(this,e,t,r);case"ascii":return v(this,e,t,r);case"latin1":case"binary":return k(this,e,t,r);case"base64":return A(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function R(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}function S(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}function T(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var i="",o=t;o<r;++o)i+=D(e[o]);return i}function C(e,t,r){for(var n=e.slice(t,r),i="",o=0;o<n.length;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function x(e,t,r,n,i,o){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<o)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function I(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i<o;++i)e[r+i]=(t&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function B(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i<o;++i)e[r+i]=t>>>8*(n?i:3-i)&255}function M(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,n,o){return o||M(e,0,r,4),i.write(e,t,r,n,23,4),r+4}function W(e,t,r,n,o){return o||M(e,0,r,8),i.write(e,t,r,n,52,8),r+8}c.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e),c.TYPED_ARRAY_SUPPORT)(r=this.subarray(e,t)).__proto__=c.prototype;else{var i=t-e;r=new c(i,void 0);for(var o=0;o<i;++o)r[o]=this[o+e]}return r},c.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=this[e],i=1,o=0;++o<t&&(i*=256);)n+=this[e+o]*i;return n},c.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},c.prototype.readUInt8=function(e,t){return t||P(e,1,this.length),this[e]},c.prototype.readUInt16LE=function(e,t){return t||P(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUInt16BE=function(e,t){return t||P(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUInt32LE=function(e,t){return t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUInt32BE=function(e,t){return t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=this[e],i=1,o=0;++o<t&&(i*=256);)n+=this[e+o]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},c.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||P(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},c.prototype.readInt8=function(e,t){return t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){t||P(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt16BE=function(e,t){t||P(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},c.prototype.readInt32LE=function(e,t){return t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readFloatLE=function(e,t){return t||P(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return t||P(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return t||P(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return t||P(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||x(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o<r&&(i*=256);)this[t+o]=e/i&255;return t+r},c.prototype.writeUIntBE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||x(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},c.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,1,255,0),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},c.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):I(this,e,t,!0),t+2},c.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,2,65535,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):I(this,e,t,!1),t+2},c.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):B(this,e,t,!0),t+4},c.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,4,4294967295,0),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},c.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);x(this,e,t,r,i-1,-i)}var o=0,s=1,a=0;for(this[t]=255&e;++o<r&&(s*=256);)e<0&&0===a&&0!==this[t+o-1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+r},c.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);x(this,e,t,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[t+o]=255&e;--o>=0&&(s*=256);)e<0&&0===a&&0!==this[t+o+1]&&(a=1),this[t+o]=(e/s>>0)-a&255;return t+r},c.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,1,127,-128),c.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):I(this,e,t,!0),t+2},c.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,2,32767,-32768),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):I(this,e,t,!1),t+2},c.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,4,2147483647,-2147483648),c.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):B(this,e,t,!0),t+4},c.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||x(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),c.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):B(this,e,t,!1),t+4},c.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},c.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},c.prototype.writeDoubleLE=function(e,t,r){return W(this,e,t,!0,r)},c.prototype.writeDoubleBE=function(e,t,r){return W(this,e,t,!1,r)},c.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);var i,o=n-r;if(this===e&&r<t&&t<n)for(i=o-1;i>=0;--i)e[i+t]=this[i+r];else if(o<1e3||!c.TYPED_ARRAY_SUPPORT)for(i=0;i<o;++i)e[i+t]=this[i+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+o),t);return o},c.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===e.length){var i=e.charCodeAt(0);i<256&&(e=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!c.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{var s=c.isBuffer(e)?e:q(new c(e,n).toString()),a=s.length;for(o=0;o<r-t;++o)this[o+t]=s[o%a]}return this};var U=/[^+\/0-9A-Za-z-_]/g;function D(e){return e<16?"0"+e.toString(16):e.toString(16)}function q(e,t){var r;t=t||1/0;for(var n=e.length,i=null,o=[],s=0;s<n;++s){if((r=e.charCodeAt(s))>55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function N(e){return n.toByteArray(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(U,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function F(e,t,r,n){for(var i=0;i<n&&!(i+r>=t.length||i>=e.length);++i)t[i+r]=e[i];return i}}).call(this,r(24))},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";t.byteLength=function(e){var t=h(e),r=t[0],n=t[1];return 3*(r+n)/4-n},t.toByteArray=function(e){var t,r,n=h(e),s=n[0],a=n[1],c=new o(function(e,t,r){return 3*(t+r)/4-r}(0,s,a)),u=0,f=a>0?s-4:s;for(r=0;r<f;r+=4)t=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],c[u++]=t>>16&255,c[u++]=t>>8&255,c[u++]=255&t;2===a&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,c[u++]=255&t);1===a&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t);return c},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],s=0,a=r-i;s<a;s+=16383)o.push(u(e,s,s+16383>a?a:s+16383));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,c=s.length;a<c;++a)n[a]=s[a],i[s.charCodeAt(a)]=a;function h(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,r){for(var i,o,s=[],a=t;a<r;a+=3)i=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),s.push(n[(o=i)>>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},function(e,t){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
t.read=function(e,t,r,n,i){var o,s,a=8*i-n-1,c=(1<<a)-1,h=c>>1,u=-7,f=r?i-1:0,l=r?-1:1,p=e[t+f];for(f+=l,o=p&(1<<-u)-1,p>>=-u,u+=a;u>0;o=256*o+e[t+f],f+=l,u-=8);for(s=o&(1<<-u)-1,o>>=-u,u+=n;u>0;s=256*s+e[t+f],f+=l,u-=8);if(0===o)o=1-h;else{if(o===c)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,n),o-=h}return(p?-1:1)*s*Math.pow(2,o-n)},t.write=function(e,t,r,n,i,o){var s,a,c,h=8*o-i-1,u=(1<<h)-1,f=u>>1,l=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,_=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+f>=1?l/c:l*Math.pow(2,1-f))*c>=2&&(s++,c/=2),s+f>=u?(a=0,s=u):s+f>=1?(a=(t*c-1)*Math.pow(2,i),s+=f):(a=t*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;e[r+p]=255&a,p+=d,a/=256,i-=8);for(s=s<<i|a,h+=i;h>0;e[r+p]=255&s,p+=d,s/=256,h-=8);e[r+p-d]|=128*_}},function(e,t){var r={}.toString;e.exports=Array.isArray||function(e){return"[object Array]"==r.call(e)}},,function(e,t,r){"use strict";r.r(t),r.d(t,"setupRPC",(function(){return V.setupRPC})),r.d(t,"waitForInitialization",(function(){return V.waitForInitialization})),r.d(t,"VERSION",(function(){return G.a})),r.d(t,"RPC",(function(){return o.b})),r.d(t,"API_VERSION",(function(){return o.a})),r.d(t,"loadRequirements",(function(){return s.c})),r.d(t,"Connection",(function(){return J})),r.d(t,"connectToServer",(function(){return X}));var n={};r.r(n),r.d(n,"protocol",(function(){return M})),r.d(n,"PacketType",(function(){return L})),r.d(n,"Encoder",(function(){return W})),r.d(n,"Decoder",(function(){return U}));var i=r(10),o=r(2),s=r(1),a=r(16),c=r.n(a);var h=r(19),u=r.n(h),f=r(4),l=function(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||u.a))return new XMLHttpRequest}catch(e){}if(!t)try{return new(f.a[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}},p=r(5),d=r(3),_=r(12),y=r(17),m=r.n(y),g=r(13),w=r.n(g),b=r(9);class v extends _.a{constructor(){super(...arguments),this.polling=!1}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emit("poll")}onData(e){Object(b.b)(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose(),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,Object(b.d)(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emit("drain")})})}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let r="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=m()()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(r=":"+this.opts.port);const n=w.a.encode(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+r+this.opts.path+(n.length?"?"+n:"")}}function k(){}const A=null!=new l({xdomain:!1}).responseType;class E extends d.Emitter{constructor(e,t){super(),Object(p.a)(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=Object(p.b)(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new l(e);try{t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn(()=>{this.onError("number"==typeof t.status?t.status:0)},0))},t.send(this.data)}catch(e){return void this.setTimeoutFn(()=>{this.onError(e)},0)}"undefined"!=typeof document&&(this.index=E.requestsCount++,E.requests[this.index]=this)}onSuccess(){this.emit("success"),this.cleanup()}onData(e){this.emit("data",e),this.onSuccess()}onError(e){this.emit("error",e),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=k,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete E.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&this.onData(e)}abort(){this.cleanup()}}if(E.requestsCount=0,E.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",j);else if("function"==typeof addEventListener){const e="onpagehide"in f.a?"pagehide":"unload";addEventListener(e,j,!1)}function j(){for(let e in E.requests)E.requests.hasOwnProperty(e)&&E.requests[e].abort()}const O={websocket:r(20).a,polling:class extends v{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=A&&!t}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new E(this.uri(),e)}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",e=>{this.onError("xhr post error",e)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",e=>{this.onError("xhr poll error",e)}),this.pollXhr=e}}};class R extends d.Emitter{constructor(e,t={}){super(),e&&"object"==typeof e&&(t=e,e=null),e?(e=c()(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=c()(t.host).host),Object(p.a)(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+"/","string"==typeof this.opts.query&&(this.opts.query=w.a.decode(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&addEventListener("beforeunload",()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},!1),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close")},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=function(e){const t={};for(let r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}(this.opts.query);t.EIO=b.e,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new O[e](r)}open(){let e;if(this.opts.rememberUpgrade&&R.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",()=>{this.onClose("transport close")})}probe(e){let t=this.createTransport(e),r=!1;R.priorWebsocketSuccess=!1;const n=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;R.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(h(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function i(){r||(r=!0,h(),t.close(),t=null)}const o=e=>{const r=new Error("probe error: "+e);r.transport=t.name,i(),this.emitReserved("upgradeError",r)};function s(){o("transport closed")}function a(){o("socket closed")}function c(e){t&&e.name!==t.name&&i()}const h=()=>{t.removeListener("open",n),t.removeListener("error",o),t.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};t.once("open",n),t.once("error",o),t.once("close",s),this.once("close",a),this.once("upgrading",c),t.open()}onOpen(){if(this.readyState="open",R.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade&&this.transport.pause){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn(()=>{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emitReserved("flush"))}write(e,t,r){return this.sendPacket("message",e,t,r),this}send(e,t,r){return this.sendPacket("message",e,t,r),this}sendPacket(e,t,r,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof r&&(n=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}onError(e){R.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&removeEventListener("offline",this.offlineEventListener,!1),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let r=0;const n=e.length;for(;r<n;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}R.protocol=b.e;R.protocol;const S="function"==typeof ArrayBuffer,T=Object.prototype.toString,C="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===T.call(Blob),P="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===T.call(File);function x(e){return S&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||C&&e instanceof Blob||P&&e instanceof File}function I(e){const t=[],r=e.data,n=e;return n.data=function e(t,r){if(!t)return t;if(x(t)){const e={_placeholder:!0,num:r.length};return r.push(t),e}if(Array.isArray(t)){const n=new Array(t.length);for(let i=0;i<t.length;i++)n[i]=e(t[i],r);return n}if("object"==typeof t&&!(t instanceof Date)){const n={};for(const i in t)t.hasOwnProperty(i)&&(n[i]=e(t[i],r));return n}return t}(r,t),n.attachments=t.length,{packet:n,buffers:t}}function B(e,t){return e.data=function e(t,r){if(!t)return t;if(t&&t._placeholder)return r[t.num];if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=e(t[n],r);else if("object"==typeof t)for(const n in t)t.hasOwnProperty(n)&&(t[n]=e(t[n],r));return t}(e.data,t),e.attachments=void 0,e}const M=5;var L;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(L||(L={}));class W{encode(e){return e.type!==L.EVENT&&e.type!==L.ACK||!function e(t,r){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(e(t[r]))return!0;return!1}if(x(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return e(t.toJSON(),!0);for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)&&e(t[r]))return!0;return!1}(e)?[this.encodeAsString(e)]:(e.type=e.type===L.EVENT?L.BINARY_EVENT:L.BINARY_ACK,this.encodeAsBinary(e))}encodeAsString(e){let t=""+e.type;return e.type!==L.BINARY_EVENT&&e.type!==L.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data)),t}encodeAsBinary(e){const t=I(e),r=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(r),n}}class U extends d.Emitter{constructor(){super()}add(e){let t;if("string"==typeof e)t=this.decodeString(e),t.type===L.BINARY_EVENT||t.type===L.BINARY_ACK?(this.reconstructor=new D(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t);else{if(!x(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===L[r.type])throw new Error("unknown packet type "+r.type);if(r.type===L.BINARY_EVENT||r.type===L.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const i=e.substring(n,t);if(i!=Number(i)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(i)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(n,t)}else r.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=function(e){try{return JSON.parse(e)}catch(e){return!1}}(e.substr(t));if(!U.isPayloadValid(r.type,n))throw new Error("invalid payload");r.data=n}return r}static isPayloadValid(e,t){switch(e){case L.CONNECT:return"object"==typeof t;case L.DISCONNECT:return void 0===t;case L.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case L.EVENT:case L.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case L.ACK:case L.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&this.reconstructor.finishedReconstruction()}}class D{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=B(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}function q(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const N=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class F extends d.Emitter{constructor(e,t,r){super(),this.connected=!1,this.disconnected=!0,this.receiveBuffer=[],this.sendBuffer=[],this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this.io._autoConnect&&this.open()}subEvents(){if(this.subs)return;const e=this.io;this.subs=[q(e,"open",this.onopen.bind(this)),q(e,"packet",this.onpacket.bind(this)),q(e,"error",this.onerror.bind(this)),q(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(N.hasOwnProperty(e))throw new Error('"'+e+'" is a reserved event name');t.unshift(e);const r={type:L.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),r.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?this.packet(r):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){const r=this.flags.timeout;if(void 0===r)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},r);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,[null,...e])}}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this.packet({type:L.CONNECT,data:e})}):this.packet({type:L.CONNECT,data:this.auth})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e){this.connected=!1,this.disconnected=!0,delete this.id,this.emitReserved("disconnect",e)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case L.CONNECT:if(e.data&&e.data.sid){const t=e.data.sid;this.onconnect(t)}else this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case L.EVENT:case L.BINARY_EVENT:this.onevent(e);break;case L.ACK:case L.BINARY_ACK:this.onack(e);break;case L.DISCONNECT:this.ondisconnect();break;case L.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e)}ack(e){const t=this;let r=!1;return function(...n){r||(r=!0,t.packet({type:L.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e){this.id=e,this.connected=!0,this.disconnected=!1,this.emitBuffered(),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>this.packet(e)),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:L.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}}var Y=r(21),H=r.n(Y);class z extends d.Emitter{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Object(p.a)(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new H.a({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||n;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new R(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const n=q(t,"open",(function(){r.onopen(),e&&e()})),i=q(t,"error",t=>{r.cleanup(),r._readyState="closed",this.emitReserved("error",t),e?e(t):r.maybeReconnectOnOpen()});if(!1!==this._timeout){const e=this._timeout;0===e&&n();const r=this.setTimeoutFn(()=>{n(),t.close(),t.emit("error",new Error("timeout"))},e);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}return this.subs.push(n),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(q(e,"ping",this.onping.bind(this)),q(e,"data",this.ondata.bind(this)),q(e,"error",this.onerror.bind(this)),q(e,"close",this.onclose.bind(this)),q(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){this.decoder.add(e)}ondecoded(e){this.emitReserved("packet",e)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r||(r=new F(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push((function(){clearTimeout(r)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const K={};function $(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let n=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),n=c()(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+t,n.href=n.protocol+"://"+i+(r&&r.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=r.source,i=r.id,o=r.path,s=K[i]&&o in K[i].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new z(n,t):(K[i]||(K[i]=new z(n,t)),a=K[i]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign($,{Manager:z,Socket:F,io:$,connect:$});var V=r(14),G=r(8);class J extends s.a{constructor(e){super(e&&e.debug),this.config=e||{},this.peer_id=Object(s.f)()}init(){return new Promise((e,t)=>{const r=this.config,n=r.server_url,o={};r.token&&(o.Authorization="Bearer "+r.token);const s=new URL(n).pathname,a=$(n,{withCredentials:!0,extraHeaders:o,path:(s.endsWith("/")?s.slice(0,-1):s)+"/socket.io"});let c=!1;a.on("connect",()=>{c?console.warn("Skipping reconnect to the server"):(a.emit("register_plugin",r,n=>{if(!n.success)return console.error(n.detail),void t(n.detail);c=!0,this.plugin_id=n.plugin_id,a.on("plugin_message",e=>{e.peer_id===this.peer_id?this._fire(e.type,e):this.config.debug&&console.log(`connection peer id mismatch ${e.peer_id} !== ${this.peer_id}`)}),this.once("initialize",()=>{this.rpc?this.rpc.once("remoteReady",()=>{this.rpc.sendInterface()}):this.rpc=Object(i.a)(this,r),this.connect(),e()}),this.emit({type:"imjoyRPCReady",config:r,peer_id:this.peer_id})}),this._disconnected=!1)}),a.on("connect_error",()=>{t("connection error"),this._fire("connectFailure")}),a.on("disconnect",()=>{t("disconnected"),this.disconnect(),this._fire("disconnected")}),this.socket=a})}connect(){this.emit({type:"initialized",config:this.config,origin:globalThis.location.origin,peer_id:this.peer_id}),this._fire("connected")}reset(){this._event_handlers={},this._once_handlers={}}execute(){throw new Error("Execution is not allowed for socketio connection")}disconnect(){this._fire("beforeDisconnect"),this.socket.disconnect(),this.init(),this._fire("disconnected")}emit(e){e.plugin_id=this.plugin_id,this.socket.emit("plugin_message",e,t=>{t.success||this._fire("error",e.detail)})}}function X(e){if(!(e=e||{}).server_url)throw new Error("Server URL is not specified.");return e.name=e.name||Object(s.f)(),e=Object(s.e)(e),new Promise((t,r)=>{const n=r=>{const i=r.detail;e.expose_api_globally&&(globalThis.api=i),t(i),globalThis.removeEventListener("imjoy_remote_api_ready",n)};globalThis.addEventListener("imjoy_remote_api_ready",n),(e=e||{}).dedicated_thread=!1,e.lang="javascript",e.api_version=o.a;new J(e).init().catch(r)})}}])}));
//# sourceMappingURL=imjoy-rpc-socketio.min.js.map