hypha-rpc 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc +4 -0
- package/.prettierignore +3 -0
- package/LICENSE +21 -0
- package/README.md +27 -0
- package/dist/hypha-rpc-sse.js +4419 -0
- package/dist/hypha-rpc-sse.js.map +1 -0
- package/dist/hypha-rpc-sse.min.js +2 -0
- package/dist/hypha-rpc-sse.min.js.map +1 -0
- package/dist/hypha-rpc-websocket.js +4741 -0
- package/dist/hypha-rpc-websocket.js.map +1 -0
- package/dist/hypha-rpc-websocket.min.js +2 -0
- package/dist/hypha-rpc-websocket.min.js.map +1 -0
- package/index.d.ts +96 -0
- package/index.js +1 -0
- package/karma.conf.js +114 -0
- package/package.json +65 -0
- package/report.html +39 -0
- package/src/rpc.js +1578 -0
- package/src/sse-client.js +251 -0
- package/src/utils.js +331 -0
- package/src/webrtc-client.js +205 -0
- package/src/websocket-client.js +572 -0
- package/tests/.eslintrc.js +8 -0
- package/tests/test_sse_client.js +182 -0
- package/tests/websocket_client_test.js +203 -0
- package/webpack.config.js +46 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("hyphaWebsocketClient",[],t):"object"==typeof exports?exports.hyphaWebsocketClient=t():e.hyphaWebsocketClient=t()}(this,(()=>(()=>{"use strict";var __webpack_modules__={887:(e,t,i)=>{i.d(t,{m:()=>o,y:()=>d});var r=i(413),n=i(506),s=i(118);const o="0.3.0",a=512e3,c=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function h(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer}function l(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?l(e,t.split(".")):0===t.length?e:l(e[t[0]],t.slice(1))}class _{constructor(e,t,i,r){this._timeout=e,this._callback=t,this._args=i,this._label=r||"timer",this._task=null,this.started=!1}start(){this.started?this.reset():(this._task=setTimeout((()=>{this._callback.apply(this,this._args)}),1e3*this._timeout),this.started=!0)}clear(){this._task?(clearTimeout(this._task),this._task=null,this.started=!1):console.warn(`Clearing a timer (${this._label}) which is not started`)}reset(){this._task&&clearTimeout(this._task),this._task=setTimeout((()=>{this._callback.apply(this,this._args)}),1e3*this._timeout),this.started=!0}}class d extends r.sw{constructor(e,{client_id:t=null,manager_id:i=null,default_context:n=null,name:s=null,codecs:o=null,method_timeout:a=null,max_message_buffer_size:c=0,debug:h=!1,workspace:l=null,silent:_=!1,app_id:d=null}){super(h),this._codecs=o||{},(0,r.vA)(t&&"string"==typeof t),(0,r.vA)(t,"client_id is required"),this._client_id=t,this._name=s,this._app_id=d,this._local_workspace=l,this.manager_id=i,this._silent=_,this.default_context=n||{},this._method_annotations=new WeakMap,this._manager_service=null,this._max_message_buffer_size=c,this._chunk_store={},this._method_timeout=a||30,this._services={},this._object_store={services:this._services},e?(this.add_service({id:"built-in",type:"built-in",name:`Built-in services for ${this._local_workspace}/${this._client_id}`,config:{require_context:!0,visibility:"public"},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),register_service:this.register_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this.on("method",this._handle_method.bind(this)),(0,r.vA)(e.emit_message&&e.on_message),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e,e.on_connect((async()=>{if(!this._silent&&this.manager_id){console.log("Connection established, reporting services...");for(let e of Object.values(this._services)){const t=this._extract_service_info(e);await this.emit({type:"service-added",to:this.manager_id,service:t})}}}))):this._emit_message=function(){console.log("No connection to emit message")}}register_codec(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(this._codecs))this._codecs[t].type!==e.type&&t!==e.name||(delete this._codecs[t],console.warn("Remove duplicated codec: "+t));this._codecs[e.name]=e}async _ping(e,t){return(0,r.vA)("ping"==e),"pong"}async ping(e,t){let i=this._generate_remote_method({_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0,_rdoc:"Ping a remote client",_rsig:"ping(msg)"});(0,r.vA)("pong"==await i("ping",t))}_create_message(e,t,i,r){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}if(this._object_store.message_cache||(this._object_store.message_cache={}),!i&&this._object_store.message_cache[e])throw new Error(`Message with the same key (${e}) already exists in the cache store, please use overwrite=true or remove it first.`);this._object_store.message_cache[e]=[]}_append_message(e,t,i,n){if(i){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const s=this._object_store.message_cache;if(!s[e])throw new Error(`Message with key ${e} does not exists.`);(0,r.vA)(t instanceof c),s[e].push(t)}_remove_message(e,t){const i=this._object_store.message_cache;if(!i[e])throw new Error(`Message with key ${e} does not exists.`);delete i[e]}_process_message(e,t,i){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const s=this._object_store.message_cache;if((0,r.vA)(!!i,"Context is required"),!s[e])throw new Error(`Message with key ${e} does not exists.`);var o,a,c,h;s[e]=(c=(a=(o=s[e]).map((function(e){return e.byteLength}))).reduce((function(e,t){return e+t}),0),h=new Uint8Array(c),a.reduce((function(e,t,i){return h.set(new Uint8Array(o[i]),e),e+t}),0),h.buffer),console.debug(`Processing message ${e} (bytes=${s[e].byteLength})`);let l=(0,n.UN)(s[e]);const{done:_,value:d}=l.next(),f=d;if(Object.assign(f,{from:i.from,to:i.to,user:i.user}),f.ctx=JSON.parse(JSON.stringify(f)),Object.assign(f.ctx,this.default_context),!_){let e=l.next();Object.assign(f,e.value)}this._fire(f.type,f),console.debug(this._client_id,`Processed message ${e} (bytes=${s[e].byteLength})`),delete s[e]}_on_message(e){try{(0,r.vA)(e instanceof ArrayBuffer);let t=(0,n.UN)(e);const{done:i,value:s}=t.next(),o=s;if(o.ctx=JSON.parse(JSON.stringify(o)),Object.assign(o.ctx,this.default_context),!i){let e=t.next();Object.assign(o,e.value)}this._fire(o.type,o)}catch(e){console.error("Failed to process message",e)}}reset(){this._event_handlers={},this._services={}}async disconnect(){this._fire("disconnect"),await this._connection.disconnect()}async get_manager_service(e){this.manager_id&&!this._manager_service&&(this._manager_service=await this.get_remote_service(`${this.manager_id}:default`,e))}get_all_local_services(){return this._services}get_local_service(e,t){(0,r.vA)(e);const[i,n]=t.to.split("/");(0,r.vA)(n===this._client_id,"Services can only be accessed locally");const s=this._services[e];if(!s)throw new Error("Service not found: "+e);if(s.config.workspace=i,"public"==s.config.visibility)return s;if(t.from.startsWith(i+"/"))return s;throw new Error(`Permission denied for protected service: ${e}, workspace mismatch: ${i} != ${t.from}`)}async get_remote_service(e,t){t=void 0===t?this._method_timeout:t,!e&&this.manager_id?e=this.manager_id:e.includes(":")||(e=this._client_id+":"+e);const i=e.split(":")[0];let n=e.split(":")[1];if(n.includes("@")){n=n.split("@")[0];const t=e.split("@")[1];this._app_id&&(0,r.vA)(t===this._app_id,`Invalid app id: ${t} != ${this._app_id}`)}(0,r.vA)(i,`Invalid service uri: ${e}`);try{const s=this._generate_remote_method({_rtarget:i,_rmethod:"services.built-in.get_service",_rpromise:!0,_rdoc:"Get a remote service",_rsig:"get_service(service_id)"}),o=await(0,r.fm)(s(n),t,"Timeout Error: Failed to get remote service: "+e);return o.id=`${i}:${n}`,o}catch(t){throw console.error("Failed to get remote service: "+e,t),t}}_annotate_service_methods(e,t,i,r,n){if("function"==typeof e){let s=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(i)?i.includes(s):!!i,run_in_executor:r,method_id:"services."+t,visibility:n})}else if(e instanceof Array||e instanceof Object)for(let s of Object.keys(e)){let o=e[s];if("function"==typeof o&&o.__rpc_object__){let t=o.__rpc_object__._rtarget;if(t.includes("/")&&(t=t.split("/")[1]),this._client_id!==t)throw new Error(`Local method not found: ${o.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${t}`);e instanceof Array&&(e=e.slice()),e[s]=l(this._object_store,o.__rpc_object__._rmethod),o=e[s]}this._annotate_service_methods(o,t+"."+s,i,r,n)}}add_service(e,t){if(!e||Array.isArray(e))throw new Error("Invalid service object");if(e.constructor===Object)e=Object.assign({},e);else{const t={},i=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let r of i)"constructor"!==r&&("function"==typeof e[r]?t[r]=e[r].bind(e):t[r]=e[r]);e.id=e.id||"default",e=t}(0,r.vA)(e.id&&"string"==typeof e.id,`Service id not found: ${e}`),e.name||(e.name=e.id),e.config||(e.config={}),e.type||(e.type="generic");let i=!1,n=!1;e.config.require_context&&(i=e.config.require_context),e.config.run_in_executor&&(n=!0);const s=e.config.visibility||"protected";if((0,r.vA)(["protected","public"].includes(s)),this._annotate_service_methods(e,e.id,i,n,s),this._services[e.id]){if(!t)throw new Error(`Service already exists: ${e.id}, please specify a different id (not ${e.id}) or overwrite=true`);delete this._services[e.id]}return this._services[e.id]=e,e}_extract_service_info(e){return{id:`${this._client_id}:${e.id}`,type:e.type,name:e.name,description:e.description||"",config:e.config,app_id:this._app_id}}async register_service(e,t,i,n){if(void 0===i&&(i=!0),n){const[e,t]=n.to.split("/");(0,r.vA)(t===this._client_id),(0,r.vA)(e===n.from.split("/")[0],"Services can only be registered from the same workspace")}const s=this.add_service(e,t),o=this._extract_service_info(s);return i&&(this.manager_id?this.emit({type:"service-added",to:this.manager_id,service:o}):this.emit({type:"service-added",to:"*",service:o})),o}async unregister_service(e,t){if(e instanceof Object&&(e=e.id),!this._services[e])throw new Error(`Service not found: ${e}`);const i=this._services[e];if(delete this._services[e],t){const e=this._extract_service_info(i);this.manager_id?this.emit({type:"service-removed",to:this.manager_id,service:e}):this.emit({type:"service-removed",to:"*",service:e})}}_ndarray(e,t,i){const n=(0,r.D4)(e);if(i&&i!==n)throw"dtype doesn't match the type of the array: "+n+" != "+i;return t=t||[e.length],{_rtype:"ndarray",_rvalue:e.buffer,_rshape:t,_rdtype:n}}_encode_callback(e,t,i,r,n,s){let o=`${i}.${e}`,a={_rtype:"method",_rtarget:s?`${s}/${this._client_id}`:this._client_id,_rmethod:o,_rpromise:!1};const c=this;return[a,function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){console.error("Error in callback:",o,e)}finally{r&&c._object_store[i]&&delete c._object_store[i],n&&n.started&&n.clear()}}]}async _encode_promise(e,t,i,n,s,o){let a=this._get_session_store(i,!0);(0,r.vA)(a,`Failed to create session store ${i} due to invalid parent`);let c={};return s&&t&&this._method_timeout?(c.heartbeat=await this._encode(s.reset.bind(s),i,o),c.interval=this._method_timeout/2,a.timer=s):s=null,[c.resolve,a.resolve]=this._encode_callback("resolve",e,i,n,s,o),[c.reject,a.reject]=this._encode_callback("reject",t,i,n,s,o),c}async _send_chunks(e,t,i){let n=await this.get_remote_service(`${t}:built-in`);(0,r.vA)(n.message_cache,"Remote client does not support message caching for long message.");let s=n.message_cache,o=i||(0,r.bq)();await s.create(o,!!i);let c=e.length,h=Math.ceil(c/a);for(let t=0;t<h;t++){let r=t*a;await s.append(o,e.slice(r,r+a),!!i),console.log(`Sending chunk ${t+1}/${h} (${c} bytes)`)}await s.process(o,!!i)}emit(e,t){(0,r.vA)("object"==typeof e&&e.type,"Invalid message, must be an object with a type field.");let i=(0,s.l)(e);if(t){const e=(0,s.l)(t);i=new Uint8Array([...i,...e])}if(i.length<=513024)return this._emit_message(i);throw new Error("Message is too large to send in one go.")}_generate_remote_method(e,t,i,n,o){let a=e._rtarget;n&&!a.includes("/")&&(n!==a&&(a=n+"/"+a),e._rtarget=a);let c=e._rmethod,h=e._rpromise;const l=this;function d(){return new Promise((async(e,n)=>{let d=(0,r.bq)();i&&(d=i+"."+d);let f=l._get_session_store(d,!0);if(!f)return void n(new Error(`Runtime Error: Failed to get session store ${d}`));f.target_id=a;const p=await l._encode(Array.prototype.slice.call(arguments),d,o),u=p.length,y=u>0&&"object"==typeof p[u-1]&&null!==p[u-1]&&p[u-1]._rkwargs;let w;y&&delete p[u-1]._rkwargs,w=l._local_workspace?"*"===l._local_workspace?a.split("/")[0]+"/"+l._client_id:l._local_workspace+"/"+l._client_id:l._client_id;let g={type:"method",from:w,to:a,method:c},m={};p&&(m.args=p),y&&(m.with_kwargs=y),t&&(g.parent=t);let v=null;if(h){g.session=d;let t=`${a}:${c}`;v=new _(l._method_timeout,n,[`Method call time out: ${t}`],t);let i=!0;for(let e of p)if("object"==typeof e&&!0===e._rintf){i=!1;break}m.promise=await l._encode_promise(e,n,d,i,v,o)}let b=(0,s.l)(g);if(m){const e=(0,s.l)(m);b=new Uint8Array([...b,...e])}b.length<=513024?l._emit_message(b).then((function(){v&&v.start()})):l._send_chunks(b,a,t).then((function(){v&&v.start()})).catch((function(e){console.error("Failed to send message",e),n(e)}))}))}d.__rpc_object__=e;const f=c.split(".");return d.__name__=f[f.length-1],d.__doc__=e._rdoc,d.__sig__=e._rsig,d}async _notify_service_update(){if(this.manager_id)try{await this.get_manager_service(30),(0,r.vA)(this._manager_service),await this._manager_service.update_client_info(this.get_client_info())}catch(e){console.warn("Failed to notify service update to",this.manager_id,e)}else console.warn("No manager id provided, cannot notify service update")}get_client_info(){const e=[];for(let t of Object.values(this._services))e.push(this._extract_service_info(t));return{id:this._client_id,services:e}}async _handle_method(e){let t=null;try{(0,r.vA)(e.method&&e.ctx&&e.from);const i=e.from+":"+e.method,n=e.from.split("/")[0];let s;e.to=e.to.includes("/")?e.to:n+"/"+e.to,e.ctx.to=e.to,this._local_workspace?"*"===this._local_workspace?s=n:(this._local_workspace&&(0,r.vA)(e.to.split("/")[0]===this._local_workspace,"Workspace mismatch: "+e.to.split("/")[0]+" != "+this._local_workspace),s=this._local_workspace):s=e.to.split("/")[0];const o=e.parent;let a,c,h,_;if(e.promise){const d=await this._decode(e.promise,e.session,o,n,s);if(a=d.resolve,c=d.reject,d.heartbeat&&d.interval){async function f(){try{console.log("Reset heartbeat timer: "+e.method),await d.heartbeat()}catch(e){console.error(e)}}t=setInterval(f,1e3*d.interval)}}try{h=l(this._object_store,e.method)}catch(p){throw console.debug("Failed to find method",i,p),new Error(`Method not found: ${i}`)}if((0,r.vA)(h&&"function"==typeof h,"Invalid method: "+i),this._method_annotations.has(h)){if("protected"===this._method_annotations.get(h).visibility&&s!==n)throw new Error("Permission denied for protected method "+i+", workspace mismatch: "+s+" != "+n)}else{let u=this._object_store[e.method.split(".")[0]].target_id;if(s===n&&u&&-1===u.indexOf("/")&&(u=s+"/"+u),"*"!==this._local_workspace&&u!==e.from)throw new Error("Access denied for method call ("+i+") from "+e.from+" to target "+u)}if(o&&(0,r.vA)(null!==this._get_session_store(o,!0),"Parent session was closed: "+o),_=e.args?await this._decode(e.args,e.session,null,n,null):[],this._method_annotations.has(h)&&this._method_annotations.get(h).require_context&&_.push(e.ctx),e.promise){const y=h.apply(null,_);y instanceof Promise?y.then((e=>{a(e),clearInterval(t)})).catch((e=>{c(e),clearInterval(t)})):(a(y),clearInterval(t))}else h.apply(null,_),clearInterval(t)}catch(w){console.error("Error during calling method: ",w),clearInterval(t)}}encode(e,t){return this._encode(e,t)}_get_session_store(e,t){let i=this._object_store;const r=e.split(".");if(t){const e=r.length-1;for(let t of r.slice(0,e)){if(!i[t])return null;i=i[t]}return i[r[e]]||(i[r[e]]={}),i[r[e]]}for(let e of r){if(!i[e])return null;i=i[e]}return i}async _encode(e,t,i){const n=typeof e;if("number"===n||"string"===n||"boolean"===n||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__)return e.__rpc_object__;let s;if(e.constructor instanceof Object&&e._rtype){const a=e._rtype;return delete e._rtype,s=await this._encode(e,t,i),s._rtype=a,s}if("function"==typeof e){if(this._method_annotations.has(e)){let h=this._method_annotations.get(e);s={_rtype:"method",_rtarget:this._client_id,_rmethod:h.method_id,_rpromise:!0}}else{let l;(0,r.vA)("string"==typeof t),l=e.__name__?`${(0,r.bq)()}-${e.__name__}`:(0,r.bq)(),s={_rtype:"method",_rtarget:this._client_id,_rmethod:`${t}.${l}`,_rpromise:!0};let _=this._get_session_store(t,!0);(0,r.vA)(null!==_,`Failed to create session store ${t} due to invalid parent`),_[l]=e}if(s._rdoc=e.__doc__,s._rsig=e.__sig__,!s._rdoc||!s._rsig)try{const d=function(e){const t=e.toString(),i=t.match(/function\s*(\w*)/),r=i&&i[1]||"",n=t.match(/\(([^)]*)\)/);let s="";n&&(s=n[1].split(",").map((e=>e.replace(/\/\*.*?\*\//g,"").replace(/\/\/.*$/g,""))).filter((e=>e.trim().length>0)).map((e=>e.trim())).join(", "));let o=t.match(/\)\s*\{\s*\/\*([\s\S]*?)\*\//);const a=o&&o[1].trim()||"";o=t.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);const c=o&&o[1].split("\n").map((e=>e.replace(/^\/\/\s*/,"").trim())).join("\n")||"",h=a||c;return r&&s.length>0&&{name:r,sig:s,doc:h}}(e);d&&!s._rdoc&&(s._rdoc=`${d.doc}`),d&&!s._rsig&&(s._rsig=`${d.name}(${d.sig})`)}catch(f){console.error("Failed to extract function docstring:",e)}return s}const o=Array.isArray(e);for(let p of Object.keys(this._codecs)){const u=this._codecs[p];if(u.encoder&&e instanceof u.type){let y=await Promise.resolve(u.encoder(e));if(y&&!y._rtype&&(y._rtype=u.name),"object"==typeof y){const w=y._rtype;delete y._rtype,y=await this._encode(y,t,i),y._rtype=w}return s=y,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const g=e.dataSync();s={_rtype:"ndarray",_rvalue:new Uint8Array(g.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const m=(0,r.D4)(e.selection.data);s={_rtype:"ndarray",_rvalue:new Uint8Array(e.selection.data.buffer),_rshape:e.shape,_rdtype:m}}else if(e instanceof Error)console.error(e),s={_rtype:"error",_rvalue:e.toString(),_rtrace:e.stack};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(e instanceof Blob){let v=0;async function b(t){let i;i=t?e.slice(v,v+t):e.slice(v);const r=new Uint8Array(await i.arrayBuffer());return v+=r.byteLength,r}function k(e){v=e}s={_rtype:"iostream",_rnative:"js:blob",type:e.type,name:e.name,size:e.size,path:e._path||e.webkitRelativePath,read:await this._encode(b,t,i),seek:await this._encode(k,t,i)}}else if(e instanceof c){const U=(0,r.D4)(e);s={_rtype:"typedarray",_rvalue:new Uint8Array(e.buffer),_rdtype:U}}else if(e instanceof DataView)s={_rtype:"memoryview",_rvalue:new Uint8Array(e.buffer)};else if(e instanceof Set)s={_rtype:"set",_rvalue:await this._encode(Array.from(e),t,i)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,i)};else{if(!(e.constructor instanceof Object||Array.isArray(e)))throw`hypha-rpc: Unsupported data type: ${e}, you can register a custom codec to encode/decode the object.`;{s=o?[]:{};const S=Object.keys(e);for(let E of S)s[E]=await this._encode(e[E],t,i)}}if(!s)throw new Error("Failed to encode object");return s}async decode(e){return await this._decode(e)}async _decode(e,t,i,n,s){if(!e)return e;let o;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const r=e._rtype;delete e._rtype,(e=await this._decode(e,t,i,n,s))._rtype=r,o=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)o=this._generate_remote_method(e,t,i,n,s);else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(h)),o=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(h));const t=r.RR[e._rdtype];o=tf.tensor(new t(e._rvalue),e._rshape,e._rdtype)}else o=e;else if("error"===e._rtype)o=new Error("RemoteError: "+e._rvalue+"\n"+(e._rtrace||""));else if("typedarray"===e._rtype){const t=r.RR[e._rdtype];if(!t)throw new Error("unsupported dtype: "+e._rdtype);o=new t(e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength))}else if("memoryview"===e._rtype)o=e._rvalue.buffer.slice(e._rvalue.byteOffset,e._rvalue.byteOffset+e._rvalue.byteLength);else if("iostream"===e._rtype){if("js:blob"===e._rnative){const r=await this._generate_remote_method(e.read,t,i,n,s),a=await r();o=new Blob([a],{type:e.type,name:e.name})}else{o={};for(let r of Object.keys(e))r.startsWith("_")||(o[r]=await this._decode(e[r],t,i,n,s))}o.__rpc_object__=e}else if("orderedmap"===e._rtype)o=new Map(await this._decode(e._rvalue,t,i,n,s));else if("set"===e._rtype)o=new Set(await this._decode(e._rvalue,t,i,n,s));else{const r=e._rtype;delete e._rtype,o=await this._decode(e,t,i,n,s),o._rtype=r}else if(e.constructor===Object||Array.isArray(e)){const r=Array.isArray(e);o=r?[]:{};for(let a of Object.keys(e))if(r||e.hasOwnProperty(a)){const r=e[a];o[a]=await this._decode(r,t,i,n,s)}}else o=e;if(void 0===o)throw new Error("Failed to decode object");return o}}},413:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}__webpack_require__.d(__webpack_exports__,{D4:()=>typedArrayToDtype,RR:()=>dtypeToTypedArray,V0:()=>loadRequirements,bq:()=>randId,fm:()=>waitFor,sw:()=>MessageEmitter,vA:()=>assert});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,i)=>{var r=document.createElement("script");r.src=e,r.type="text/javascript",r.onload=t,r.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||t()},r.onerror=i,document.head.appendChild(r)}))}async function i(){for(var e=Array.prototype.slice.call(arguments),i=e.length,r=0;r<i;r++)await t(e[r])}if(e&&(Array.isArray(e)||"string"==typeof e))try{var r;if(e="string"==typeof e?[e]:e,!Array.isArray(e))throw"unsupported requirements definition";for(var n=0;n<e.length;n++)e[n].toLowerCase().endsWith(".css")||e[n].startsWith("css:")?(e[n].startsWith("css:")&&(e[n]=e[n].slice(4)),(r=document.createElement("link")).rel="stylesheet",r.href=e[n],document.head.appendChild(r)):e[n].toLowerCase().endsWith(".mjs")||e[n].startsWith("mjs:")?(e[n].startsWith("mjs:")&&(e[n]=e[n].slice(4)),await import(e[n])):e[n].toLowerCase().endsWith(".js")||e[n].startsWith("js:")?(e[n].startsWith("js:")&&(e[n]=e[n].slice(3)),await i(e[n])):e[n].startsWith("http")?await i(e[n]):e[n].startsWith("cache:")||console.log("Unprocessed requirements url: "+e[n])}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,i)=>("function"!=typeof e[i]&&(t[i]=e[i]),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 i=Object.getPrototypeOf(e);for(const e of typedArrayToDtypeKeys)if(i instanceof e){t=typedArrayToDtypeMapping[e.name];break}}return t}function cacheUrlInServiceWorker(e){return new Promise((function(t,i){const r={command:"add",url:e};if(!navigator.serviceWorker||!navigator.serviceWorker.register)return void i("Service worker is not supported.");const n=new MessageChannel;n.port1.onmessage=function(e){e.data&&e.data.error?i(e.data.error):t(e.data&&e.data.result)},navigator.serviceWorker&&navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage(r,[n.port2]):i("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 assert(e,t){if(!e)throw new Error(t||"Assertion failed")}function urlJoin(...e){return e.join("/").replace(/[\/]+/g,"/").replace(/^(.+):\//,"$1://").replace(/^file:/,"file:/").replace(/\/(\?|&|#[^!])/g,"$1").replace(/\?/g,"&").replace("&","?")}function waitFor(e,t,i){let r;return Promise.race([e,new Promise(((e,n)=>r=setTimeout((()=>{n(i||"Timeout Error")}),1e3*t)))]).finally((()=>clearTimeout(r)))}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 i=this._event_handlers[e].indexOf(t);i>=0&&this._event_handlers[e].splice(i,1)}}else this._event_handlers={}}_fire(e,t){if(this._event_handlers[e])for(var i=this._event_handlers[e].length;i--;){const r=this._event_handlers[e][i];try{r(t)}catch(e){console.error(e)}finally{r.___event_run_once&&this._event_handlers[e].splice(i,1)}}else this._debug&&console.warn("unhandled event",e,t)}}},831:(e,t,i)=>{i.d(t,{b:()=>a,e:()=>c});var r=i(887),n=i(413);class s{constructor(e){this._data_channel=e,this._handle_message=null,this._reconnection_token=null,this._data_channel.onmessage=async e=>{let t=e.data;t instanceof Blob&&(t=await t.arrayBuffer()),this._handle_message(t)};const t=this;this._data_channel.onclose=function(){console.log("websocket closed"),t._data_channel=null}}set_reconnection_token(e){this._reconnection_token=e}on_message(e){(0,n.vA)(e,"handler is required"),this._handle_message=e}async emit_message(e){(0,n.vA)(this._handle_message,"No handler for message");try{this._data_channel.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}async disconnect(e){this._data_channel=null,console.info(`data channel connection disconnected (${e})`)}}async function o(e){(0,n.vA)(e.channel,"No channel provided"),(0,n.vA)(e.workspace,"No workspace provided");const t=e.channel,i=e.client_id||(0,n.bq)(),o=new s(t);return e.context=e.context||{},e.context.connection_type="webrtc",new r.y(o,{client_id:i,manager_id:null,default_context:e.context,name:e.name,method_timeout:e.method_timeout||10,workspace:e.workspace})}async function a(e,t,i){(i=i||{}).peer_id=i.peer_id||(0,n.bq)();const r=new RTCPeerConnection({iceServers:i.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});return new Promise((async(n,s)=>{try{r.addEventListener("connectionstatechange",(()=>{"failed"===r.connectionState&&(r.close(),s(new Error("Connection failed")))}),!1),i.on_init&&(await i.on_init(r),delete i.on_init);let a=r.createDataChannel(i.peer_id,{ordered:!0});a.binaryType="arraybuffer";const c=await r.createOffer();await r.setLocalDescription(c);const h=await e.getService(t),l=await h.offer({sdp:r.localDescription.sdp,type:r.localDescription.type});a.onopen=()=>{i.channel=a,i.workspace=l.workspace,setTimeout((async()=>{const e=await o(i);async function t(t){return await e.get_remote_service(i.peer_id+":"+t)}r.rpc=e,r.get_service=t,r.getService=t,r.disconnect=async function(){await e.disconnect(),r.close()},r.register_codec=e.register_codec,r.registerCodec=e.register_codec,n(r)}),500)},a.onclose=()=>s(new Error("Data channel closed")),await r.setRemoteDescription(new RTCSessionDescription({sdp:l.sdp,type:l.type}))}catch(e){s(e)}}))}async function c(e,t,i){const r=(i=i||{visibility:"protected",require_context:!0}).on_init;delete i.on_init,await e.registerService({id:t,config:i,offer:(t,n)=>async function(e,t,i,r,n){i=i||{};let s=new RTCSessionDescription({sdp:e.sdp,type:e.type}),a=new RTCPeerConnection({iceServers:i.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});t&&a.addEventListener("datachannel",(async e=>{const i=e.channel;let r=null;n&&n.user&&(r={user:n.user}),(await o({channel:i,client_id:i.label,workspace:t.config.workspace,context:r}))._services=t.rpc._services})),r&&await r(a),await a.setRemoteDescription(s);let c=await a.createAnswer();return await a.setLocalDescription(c),{sdp:a.localDescription.sdp,type:a.localDescription.type,workspace:t.config.workspace}}(t,e,i,r,n)})}},881:(e,t,i)=>{i.d(t,{s:()=>n});var r=i(579),n=function(){function e(e,t){void 0===e&&(e=16),void 0===t&&(t=16),this.maxKeyLength=e,this.maxLengthPerKey=t,this.hit=0,this.miss=0,this.caches=[];for(var i=0;i<this.maxKeyLength;i++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,i){e:for(var r=0,n=this.caches[i-1];r<n.length;r++){for(var s=n[r],o=s.bytes,a=0;a<i;a++)if(o[a]!==e[t+a])continue e;return s.str}return null},e.prototype.store=function(e,t){var i=this.caches[e.length-1],r={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=r:i.push(r)},e.prototype.decode=function(e,t,i){var n=this.find(e,t,i);if(null!=n)return this.hit++,n;this.miss++;var s=(0,r.Zf)(e,t,i),o=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(o,s),s},e}()},448:(e,t,i)=>{i.d(t,{X:()=>s});var r,n=(r=function(e,t){return r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},r(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}r(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),s=function(e){function t(i){var r=e.call(this,i)||this,n=Object.create(t.prototype);return Object.setPrototypeOf(r,n),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:t.name}),r}return n(t,e),t}(Error)},328:(e,t,i)=>{i.d(t,{X:()=>g});var r=i(136),n=i(959),s=i(989),o=i(579),a=i(876),c=i(881),h=i(448),l=function(e,t){var i,r,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(s){return function(a){return function(s){if(i)throw new TypeError("Generator is already executing.");for(;o;)try{if(i=1,r&&(n=2&s[0]?r.return:s[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,s[1])).done)return n;switch(r=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((n=(n=o.trys).length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){o.label=s[1];break}if(6===s[0]&&o.label<n[1]){o.label=n[1],n=s;break}if(n&&o.label<n[2]){o.label=n[2],o.ops.push(s);break}n[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{i=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},_=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(i){t[i]=e[i]&&function(t){return new Promise((function(r,n){!function(e,t,i,r){Promise.resolve(r).then((function(t){e({value:t,done:i})}),t)}(r,n,(t=e[i](t)).done,t.value)}))}}},d=function(e){return this instanceof d?(this.v=e,this):new d(e)},f=new DataView(new ArrayBuffer(0)),p=new Uint8Array(f.buffer),u=function(){try{f.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),y=new u("Insufficient data"),w=new c.s,g=function(){function e(e,t,i,r,o,a,c,h){void 0===e&&(e=n.g.defaultCodec),void 0===t&&(t=void 0),void 0===i&&(i=s.f7),void 0===r&&(r=s.f7),void 0===o&&(o=s.f7),void 0===a&&(a=s.f7),void 0===c&&(c=s.f7),void 0===h&&(h=w),this.extensionCodec=e,this.context=t,this.maxStrLength=i,this.maxBinLength=r,this.maxArrayLength=o,this.maxMapLength=a,this.maxExtLength=c,this.keyDecoder=h,this.totalPos=0,this.pos=0,this.view=f,this.bytes=p,this.headByte=-1,this.stack=[]}return e.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=-1,this.stack.length=0},e.prototype.setBuffer=function(e){this.bytes=(0,a.C)(e),this.view=(0,a.o)(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),i=(0,a.C)(e),r=new Uint8Array(t.length+i.length);r.set(t),r.set(i,t.length),this.setBuffer(r)}else this.setBuffer(e)},e.prototype.hasRemaining=function(e){return this.view.byteLength-this.pos>=e},e.prototype.createExtraByteError=function(e){var t=this.view,i=this.pos;return new RangeError("Extra ".concat(t.byteLength-i," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return l(this,(function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}}))},e.prototype.decodeAsync=function(e){var t,i,n,s,o,a,c,h;return o=this,a=void 0,h=function(){var o,a,c,h,d,f,p,y;return l(this,(function(l){switch(l.label){case 0:o=!1,l.label=1;case 1:l.trys.push([1,6,7,12]),t=_(e),l.label=2;case 2:return[4,t.next()];case 3:if((i=l.sent()).done)return[3,5];if(c=i.value,o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{a=this.doDecodeSync(),o=!0}catch(e){if(!(e instanceof u))throw e}this.totalPos+=this.pos,l.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return h=l.sent(),n={error:h},[3,12];case 7:return l.trys.push([7,,10,11]),i&&!i.done&&(s=t.return)?[4,s.call(t)]:[3,9];case 8:l.sent(),l.label=9;case 9:return[3,11];case 10:if(n)throw n.error;return[7];case 11:return[7];case 12:if(o){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,a]}throw f=(d=this).headByte,p=d.pos,y=d.totalPos,new RangeError("Insufficient data in parsing ".concat((0,r.B)(f)," at ").concat(y," (").concat(p," in the current buffer)"))}}))},new((c=void 0)||(c=Promise))((function(e,t){function i(e){try{n(h.next(e))}catch(e){t(e)}}function r(e){try{n(h.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof c?n:new c((function(e){e(n)}))).then(i,r)}n((h=h.apply(o,a||[])).next())}))},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,n=i.apply(e,t||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(e){n[e]&&(r[e]=function(t){return new Promise((function(i,r){s.push([e,t,i,r])>1||a(e,t)}))})}function a(e,t){try{(i=n[e](t)).value instanceof d?Promise.resolve(i.value.v).then(c,h):l(s[0][2],i)}catch(e){l(s[0][3],e)}var i}function c(e){a("next",e)}function h(e){a("throw",e)}function l(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}(this,arguments,(function(){var i,r,n,s,o,a,c,h,f;return l(this,(function(l){switch(l.label){case 0:i=t,r=-1,l.label=1;case 1:l.trys.push([1,13,14,19]),n=_(e),l.label=2;case 2:return[4,d(n.next())];case 3:if((s=l.sent()).done)return[3,12];if(o=s.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(r=this.readArraySize(),i=!1,this.complete()),l.label=4;case 4:l.trys.push([4,9,,10]),l.label=5;case 5:return[4,d(this.doDecodeSync())];case 6:return[4,l.sent()];case 7:return l.sent(),0==--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=l.sent())instanceof u))throw a;return[3,10];case 10:this.totalPos+=this.pos,l.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return c=l.sent(),h={error:c},[3,19];case 14:return l.trys.push([14,,17,18]),s&&!s.done&&(f=n.return)?[4,d(f.call(n))]:[3,16];case 15:l.sent(),l.label=16;case 16:return[3,18];case 17:if(h)throw h.error;return[7];case 18:return[7];case 19:return[2]}}))}))},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(n=e-128)){this.pushMapState(n),this.complete();continue e}t={}}else if(e<160){if(0!=(n=e-144)){this.pushArrayState(n),this.complete();continue e}t=[]}else{var i=e-160;t=this.decodeUtf8String(i,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)i=this.lookU8(),t=this.decodeUtf8String(i,1);else if(218===e)i=this.lookU16(),t=this.decodeUtf8String(i,2);else if(219===e)i=this.lookU32(),t=this.decodeUtf8String(i,4);else if(220===e){if(0!==(n=this.readU16())){this.pushArrayState(n),this.complete();continue e}t=[]}else if(221===e){if(0!==(n=this.readU32())){this.pushArrayState(n),this.complete();continue e}t=[]}else if(222===e){if(0!==(n=this.readU16())){this.pushMapState(n),this.complete();continue e}t={}}else if(223===e){if(0!==(n=this.readU32())){this.pushMapState(n),this.complete();continue e}t={}}else if(196===e){var n=this.lookU8();t=this.decodeBinary(n,1)}else if(197===e)n=this.lookU16(),t=this.decodeBinary(n,2);else if(198===e)n=this.lookU32(),t=this.decodeBinary(n,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)n=this.lookU8(),t=this.decodeExtension(n,1);else if(200===e)n=this.lookU16(),t=this.decodeExtension(n,2);else{if(201!==e)throw new h.X("Unrecognized type byte: ".concat((0,r.B)(e)));n=this.lookU32(),t=this.decodeExtension(n,4)}this.complete();for(var s=this.stack;s.length>0;){var o=s[s.length-1];if(0===o.type){if(o.array[o.position]=t,o.position++,o.position!==o.size)continue e;s.pop(),t=o.array}else{if(1===o.type){if(void 0,"string"!=(a=typeof t)&&"number"!==a)throw new h.X("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new h.X("The key __proto__ is not allowed");o.key=t,o.type=2;continue e}if(o.map[o.key]=t,o.readCount++,o.readCount!==o.size){o.key=null,o.type=1;continue e}s.pop(),t=o.map}}return t}var a},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new h.X("Unrecognized array type byte: ".concat((0,r.B)(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new h.X("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new h.X("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var i;if(e>this.maxStrLength)throw new h.X("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw y;var r,n=this.pos+t;return r=this.stateIsMapKey()&&(null===(i=this.keyDecoder)||void 0===i?void 0:i.canBeCached(e))?this.keyDecoder.decode(this.bytes,n,e):e>o.F6?(0,o.Q$)(this.bytes,n,e):(0,o.Zf)(this.bytes,n,e),this.pos+=t+e,r},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new h.X("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw y;var i=this.pos+t,r=this.bytes.subarray(i,i+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new h.X("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var i=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,i,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e=(0,s.Hn)(this.view,this.pos);return this.pos+=8,e},e.prototype.readI64=function(){var e=(0,s.eN)(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}()},124:(e,t,i)=>{i.d(t,{Nz:()=>a});var r=i(579),n=i(959),s=i(989),o=i(876),a=function(){function e(e,t,i,r,s,o,a,c){void 0===e&&(e=n.g.defaultCodec),void 0===t&&(t=void 0),void 0===i&&(i=100),void 0===r&&(r=2048),void 0===s&&(s=!1),void 0===o&&(o=!1),void 0===a&&(a=!1),void 0===c&&(c=!1),this.extensionCodec=e,this.context=t,this.maxDepth=i,this.initialBufferSize=r,this.sortKeys=s,this.forceFloat32=o,this.ignoreUndefined=a,this.forceIntegerToFloat=c,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return e.prototype.reinitializeState=function(){this.pos=0},e.prototype.encodeSharedRef=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)},e.prototype.encode=function(e){return this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)},e.prototype.doEncode=function(e,t){if(t>this.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(2*t)},e.prototype.resizeBuffer=function(e){var t=new ArrayBuffer(e),i=new Uint8Array(t),r=new DataView(t);i.set(this.bytes),this.view=r,this.bytes=i},e.prototype.encodeNil=function(){this.writeU8(192)},e.prototype.encodeBoolean=function(e){!1===e?this.writeU8(194):this.writeU8(195)},e.prototype.encodeNumber=function(e){Number.isSafeInteger(e)&&!this.forceIntegerToFloat?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>r.TF){var t=(0,r.dS)(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.jW)(e,this.bytes,this.pos),this.pos+=t}else t=(0,r.dS)(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),(0,r.Hc)(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var i=this.extensionCodec.tryToEncode(e,this.context);if(null!=i)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var i=(0,o.C)(e);this.writeU8a(i)},e.prototype.encodeArray=function(e,t){var i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error("Too large array: ".concat(i));this.writeU8(221),this.writeU32(i)}for(var r=0,n=e;r<n.length;r++){var s=n[r];this.doEncode(s,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var i=0,r=0,n=t;r<n.length;r++)void 0!==e[n[r]]&&i++;return i},e.prototype.encodeMap=function(e,t){var i=Object.keys(e);this.sortKeys&&i.sort();var r=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(r<16)this.writeU8(128+r);else if(r<65536)this.writeU8(222),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large map object: ".concat(r));this.writeU8(223),this.writeU32(r)}for(var n=0,s=i;n<s.length;n++){var o=s[n],a=e[o];this.ignoreUndefined&&void 0===a||(this.encodeString(o),this.doEncode(a,t+1))}},e.prototype.encodeExtension=function(e){var t=e.data.length;if(1===t)this.writeU8(212);else if(2===t)this.writeU8(213);else if(4===t)this.writeU8(214);else if(8===t)this.writeU8(215);else if(16===t)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large extension object: ".concat(t));this.writeU8(201),this.writeU32(t)}this.writeI8(e.type),this.writeU8a(e.data)},e.prototype.writeU8=function(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++},e.prototype.writeU8a=function(e){var t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t},e.prototype.writeI8=function(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++},e.prototype.writeU16=function(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2},e.prototype.writeI16=function(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2},e.prototype.writeU32=function(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4},e.prototype.writeI32=function(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4},e.prototype.writeF32=function(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4},e.prototype.writeF64=function(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8},e.prototype.writeU64=function(e){this.ensureBufferSizeToWrite(8),(0,s.X3)(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),(0,s._j)(this.view,this.pos,e),this.pos+=8},e}()},749:(e,t,i)=>{i.d(t,{o:()=>r});var r=function(e,t){this.type=e,this.data=t}},959:(e,t,i)=>{i.d(t,{g:()=>s});var r=i(749),n=i(272),s=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(n.CW)}return e.prototype.register=function(e){var t=e.type,i=e.encode,r=e.decode;if(t>=0)this.encoders[t]=i,this.decoders[t]=r;else{var n=1+t;this.builtInEncoders[n]=i,this.builtInDecoders[n]=r}},e.prototype.tryToEncode=function(e,t){for(var i=0;i<this.builtInEncoders.length;i++)if(null!=(s=this.builtInEncoders[i])&&null!=(o=s(e,t))){var n=-1-i;return new r.o(n,o)}for(i=0;i<this.encoders.length;i++){var s,o;if(null!=(s=this.encoders[i])&&null!=(o=s(e,t)))return n=i,new r.o(n,o)}return e instanceof r.o?e:null},e.prototype.decode=function(e,t,i){var n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,i):new r.o(t,e)},e.defaultCodec=new e,e}()},506:(e,t,i)=>{i.d(t,{UN:()=>s});var r=i(328),n={};function s(e,t){return void 0===t&&(t=n),new r.X(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decodeMulti(e)}},118:(e,t,i)=>{i.d(t,{l:()=>s});var r=i(124),n={};function s(e,t){return void 0===t&&(t=n),new r.Nz(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat).encodeSharedRef(e)}},272:(e,t,i)=>{i.d(t,{CW:()=>s});var r=i(448),n=i(989),s={type:-1,encode:function(e){var t,i,r,s;return e instanceof Date?function(e){var t,i=e.sec,r=e.nsec;if(i>=0&&r>=0&&i<=17179869183){if(0===r&&i<=4294967295){var s=new Uint8Array(4);return(t=new DataView(s.buffer)).setUint32(0,i),s}var o=i/4294967296,a=4294967295&i;return s=new Uint8Array(8),(t=new DataView(s.buffer)).setUint32(0,r<<2|3&o),t.setUint32(4,a),s}return s=new Uint8Array(12),(t=new DataView(s.buffer)).setUint32(0,r),(0,n._j)(t,4,i),s}((r=1e6*((t=e.getTime())-1e3*(i=Math.floor(t/1e3))),{sec:i+(s=Math.floor(r/1e9)),nsec:r-1e9*s})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var i=t.getUint32(0);return{sec:4294967296*(3&i)+t.getUint32(4),nsec:i>>>2};case 12:return{sec:(0,n.eN)(t,4),nsec:t.getUint32(0)};default:throw new r.X("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}}},989:(e,t,i)=>{i.d(t,{Hn:()=>a,X3:()=>n,_j:()=>s,eN:()=>o,f7:()=>r});var r=4294967295;function n(e,t,i){var r=i/4294967296,n=i;e.setUint32(t,r),e.setUint32(t+4,n)}function s(e,t,i){var r=Math.floor(i/4294967296),n=i;e.setUint32(t,r),e.setUint32(t+4,n)}function o(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}function a(e,t){return 4294967296*e.getUint32(t)+e.getUint32(t+4)}},136:(e,t,i)=>{function r(e){return"".concat(e<0?"-":"","0x").concat(Math.abs(e).toString(16).padStart(2,"0"))}i.d(t,{B:()=>r})},876:(e,t,i)=>{function r(e){return e instanceof Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof ArrayBuffer?new Uint8Array(e):Uint8Array.from(e)}function n(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=r(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}i.d(t,{C:()=>r,o:()=>n})},579:(e,t,i)=>{i.d(t,{F6:()=>y,Hc:()=>h,Q$:()=>w,TF:()=>_,Zf:()=>p,dS:()=>c,jW:()=>d});var r,n,s,o=i(989),a=("undefined"==typeof process||"never"!==(null===(r=null===process||void 0===process?void 0:process.env)||void 0===r?void 0:r.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function c(e){for(var t=e.length,i=0,r=0;r<t;){var n=e.charCodeAt(r++);if(4294967168&n)if(4294965248&n){if(n>=55296&&n<=56319&&r<t){var s=e.charCodeAt(r);56320==(64512&s)&&(++r,n=((1023&n)<<10)+(1023&s)+65536)}i+=4294901760&n?4:3}else i+=2;else i++}return i}function h(e,t,i){for(var r=e.length,n=i,s=0;s<r;){var o=e.charCodeAt(s++);if(4294967168&o){if(4294965248&o){if(o>=55296&&o<=56319&&s<r){var a=e.charCodeAt(s);56320==(64512&a)&&(++s,o=((1023&o)<<10)+(1023&a)+65536)}4294901760&o?(t[n++]=o>>18&7|240,t[n++]=o>>12&63|128,t[n++]=o>>6&63|128):(t[n++]=o>>12&15|224,t[n++]=o>>6&63|128)}else t[n++]=o>>6&31|192;t[n++]=63&o|128}else t[n++]=o}}var l=a?new TextEncoder:void 0,_=a?"undefined"!=typeof process&&"force"!==(null===(n=null===process||void 0===process?void 0:process.env)||void 0===n?void 0:n.TEXT_ENCODING)?200:0:o.f7,d=(null==l?void 0:l.encodeInto)?function(e,t,i){l.encodeInto(e,t.subarray(i))}:function(e,t,i){t.set(l.encode(e),i)},f=4096;function p(e,t,i){for(var r=t,n=r+i,s=[],o="";r<n;){var a=e[r++];if(128&a)if(192==(224&a)){var c=63&e[r++];s.push((31&a)<<6|c)}else if(224==(240&a)){c=63&e[r++];var h=63&e[r++];s.push((31&a)<<12|c<<6|h)}else if(240==(248&a)){var l=(7&a)<<18|(c=63&e[r++])<<12|(h=63&e[r++])<<6|63&e[r++];l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|1023&l),s.push(l)}else s.push(a);else s.push(a);s.length>=f&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(o+=String.fromCharCode.apply(String,s)),o}var u=a?new TextDecoder:null,y=a?"undefined"!=typeof process&&"force"!==(null===(s=null===process||void 0===process?void 0:process.env)||void 0===s?void 0:s.TEXT_DECODER)?200:0:o.f7;function w(e,t,i){var r=e.subarray(t,t+i);return u.decode(r)}},330:e=>{e.exports={rE:"0.1.0"}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var i=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](i,i.exports,__webpack_require__),i.exports}__webpack_require__.d=(e,t)=>{for(var i in t)__webpack_require__.o(t,i)&&!__webpack_require__.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__={};__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,{API_VERSION:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.m,RPC:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.y,VERSION:()=>_package_json__WEBPACK_IMPORTED_MODULE_3__.rE,connectToServer:()=>connectToServer,getRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.b,loadRequirements:()=>_utils_js__WEBPACK_IMPORTED_MODULE_1__.V0,login:()=>login,registerRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.e,setupLocalClient:()=>setupLocalClient});var _rpc_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(887),_utils_js__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(413),_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(831),_package_json__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(330);const MAX_RETRY=1e4;class WebsocketRPCConnection{constructor(e,t,i,r,n=60,s=null){(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.vA)(e&&t,"server_url and client_id are required"),this._server_url=e,this._client_id=t,this._workspace=i,this._token=r,this._reconnection_token=null,this._websocket=null,this._handle_message=null,this._handle_connect=null,this._disconnect_handler=null,this._timeout=1e3*n,this._WebSocketClass=s||WebSocket,this._opening=null,this._closing=!1,this._legacy_auth=null,this.connection_info=null}on_message(e){(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.vA)(e,"handler is required"),this._handle_message=e}on_connect(e){this._handle_connect=e,this._websocket&&this._websocket.readyState===WebSocket.OPEN&&this._handle_connect(this)}on_disconnected(e){this._disconnect_handler=e}set_reconnection_token(e){this._reconnection_token=e}async _attempt_connection(e,t=!0){return new Promise(((i,r)=>{this._legacy_auth=!1;const n=new this._WebSocketClass(e);n.binaryType="arraybuffer",n.onopen=()=>{console.info("WebSocket connection established"),i(n)},n.onerror=e=>{console.error("WebSocket connection error:",e),r(e)},n.onclose=n=>{1003===n.code&&t?(console.info("Received 1003 error, attempting connection with query parameters."),this._attempt_connection_with_query_params(e).then(i).catch(r)):this._disconnect_handler&&this._disconnect_handler(this,n.reason)}}))}async _attempt_connection_with_query_params(e){const t=[];this._client_id&&t.push(`client_id=${encodeURIComponent(this._client_id)}`),this._workspace&&t.push(`workspace=${encodeURIComponent(this._workspace)}`),this._token&&t.push(`token=${encodeURIComponent(this._token)}`),this._reconnection_token&&t.push(`reconnection_token=${encodeURIComponent(this._reconnection_token)}`);const i=e+(t.length>0?`?${t.join("&")}`:"");return this._legacy_auth=!0,await this._attempt_connection(i,!1)}async open(){if(!this._closing&&!this._websocket)try{if(this._opening=!0,this._websocket=await this._attempt_connection(this._server_url),!this._legacy_auth){const e=JSON.stringify({client_id:this._client_id,workspace:this._workspace,token:this._token,reconnection_token:this._reconnection_token});this._websocket.send(e),await(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.fm)(new Promise(((e,t)=>{this._websocket.onmessage=i=>{const r=i.data,n=JSON.parse(r);if(n.success)n&&(console.log("Successfully connected: "+JSON.stringify(n)),this.connection_info=n);else{const e=n.error||"Unknown error";console.error("Failed to connect, "+e),this.connection_info=None,t(new Error(e))}e()}})),this._timeout/1e3,"Failed to receive the first message from the server")}this._websocket.onmessage=e=>{const t=e.data;this._handle_message(t)},this._handle_connect&&await this._handle_connect(this)}catch(e){console.error("Failed to connect to",this._server_url,e)}finally{this._opening=!1}}async emit_message(e){if(this._closing)throw new Error("Connection is closing");if(await this._opening,!this._websocket||this._websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket connection is not open");try{this._websocket.send(e)}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}disconnect(e){this._closing=!0,this._websocket&&this._websocket.readyState===WebSocket.OPEN&&(this._websocket.close(1e3,e),console.info(`WebSocket connection disconnected (${e})`))}}function normalizeServerUrl(e){if(!e)throw new Error("server_url is required");return e.startsWith("http://")?e=e.replace("http://","ws://").replace(/\/$/,"")+"/ws":e.startsWith("https://")&&(e=e.replace("https://","wss://").replace(/\/$/,"")+"/ws"),e}async function login(e){const t=e.login_service_id||"public/*:hypha-login",i=e.login_timeout||60,r=e.login_callback,n=await connectToServer({name:"initial login client",server_url:e.server_url});try{const e=await n.get_service(t),s=await e.start();return r?await r(s):console.log(`Please open your browser and login at ${s.login_url}`),await e.check(s.key,i)}catch(e){throw e}finally{await n.disconnect()}}async function connectToServer(e){e.server&&(e.server_url=e.server_url||e.server.url,e.WebSocketClass=e.WebSocketClass||e.server.WebSocketClass);let t=e.client_id;t||(t=(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.bq)(),e.client_id=t);let i=normalizeServerUrl(e.server_url),r=new WebsocketRPCConnection(i,t,e.workspace,e.token,e.method_timeout||60,e.WebSocketClass);await r.open();let n=e.workspace;r.connection_info&&(n=r.connection_info.workspace);const s=new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.y(r,{client_id:t,workspace:n,manager_id:"workspace-manager",default_context:{connection_type:"websocket"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id}),o=await s.get_remote_service("workspace-manager:default");async function a(){await s.disconnect(),await r.disconnect()}if(o.rpc=s,o.config.client_id=t,o.export=async function(t){t.id="default",t.name=t.name||e.name||t.id,t.description=t.description||e.description,t.docs=t.docs||e.docs,await s.register_service(t,!0)},o.getPlugin=async function(e){return await o.get_service(e+":default")},o.listPlugins=o.listServices,o.disconnect=a,o.registerCodec=s.register_codec.bind(s),o.emit=s.emit,o.on=s.on,s.manager_id&&s.on("force-exit",(async e=>{e.from.endsWith("/"+s.manager_id)&&(console.log("Disconnecting from server, reason:",e.reason),await a())})),e.webrtc&&await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.e)(o,t+"-rtc",e.webrtc_config),o.get_service||o.getService){const e=o.get_service||o.getService;o.get_service=async function(t,i,r){(0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.vA)([void 0,!0,!1,"auto"].includes(i),"webrtc must be true, false or 'auto'");const n=await e(t);if(!0===i||"auto"===i){if(n.id.includes(":")&&n.id.includes("/")){const e=n.id.split(":")[0];try{const t=await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.b)(o,e+":"+e.split("/")[1]+"-rtc",r),i=await t.get_service(n.id.split(":")[1]);return i._webrtc=!0,i._peer=t,i._service=n,i}catch(e){console.warn("Failed to get webrtc service, using websocket connection",e)}}if(!0===i)throw new Error("Failed to get the service via webrtc")}return n},o.getService=o.get_service}return o}class LocalWebSocket{constructor(e,t,i){this.url=e,this.onopen=()=>{},this.onmessage=()=>{},this.onclose=()=>{},this.onerror=()=>{},this.client_id=t,this.workspace=i;const r="undefined"!=typeof window?window:self,n="undefined"!=typeof window;if(this.postMessage=e=>{n?window.parent.postMessage(e,"*"):self.postMessage(e)},this.readyState=WebSocket.CONNECTING,r.addEventListener("message",(e=>{const{type:t,data:i,to:r}=e.data;if(r===this.client_id)switch(t){case"message":this.readyState===WebSocket.OPEN&&this.onmessage&&this.onmessage({data:i});break;case"connected":this.readyState=WebSocket.OPEN,this.onopen(e);break;case"closed":this.readyState=WebSocket.CLOSED,this.onclose(e)}else console.debug("message not for me",r,this.client_id)}),!1),!this.client_id)throw new Error("client_id is required");if(!this.workspace)throw new Error("workspace is required");this.postMessage({type:"connect",url:this.url,from:this.client_id,workspace:this.workspace})}send(e){this.readyState===WebSocket.OPEN&&this.postMessage({type:"message",data:e,from:this.client_id,workspace:this.workspace})}close(){this.readyState=WebSocket.CLOSING,this.postMessage({type:"close",from:this.client_id,workspace:this.workspace}),this.onclose()}addEventListener(e,t){"message"===e&&(this.onmessage=t),"open"===e&&(this.onopen=t),"close"===e&&(this.onclose=t),"error"===e&&(this.onerror=t)}}function setupLocalClient({enable_execution=!1,on_ready=null}){return new Promise(((resolve,reject)=>{const context="undefined"!=typeof window?window:self,isWindow="undefined"!=typeof window;context.addEventListener("message",(event=>{const{type,server_url,workspace,client_id,token,method_timeout,name,config}=event.data;if("initializeHyphaClient"===type){if(!server_url||!workspace||!client_id)return void console.error("server_url, workspace, and client_id are required.");if(!server_url.startsWith("https://local-hypha-server:"))return void console.error("server_url should start with https://local-hypha-server:");connectToServer({server_url,workspace,client_id,token,method_timeout,name}).then((async server=>{globalThis.api=server;try{if(isWindow&&enable_execution){function e(e){return new Promise(((t,i)=>{const r=document.createElement("script");r.innerHTML=e.content,r.lang=e.lang,r.onload=()=>t(),r.onerror=e=>i(e),document.head.appendChild(r)}))}if(config.styles&&config.styles.length>0)for(const t of config.styles){const i=document.createElement("style");i.innerHTML=t.content,i.lang=t.lang,document.head.appendChild(i)}if(config.links&&config.links.length>0)for(const r of config.links){const n=document.createElement("a");n.href=r.url,n.innerText=r.text,document.body.appendChild(n)}if(config.windows&&config.windows.length>0)for(const s of config.windows){document.body.innerHTML=s.content;break}if(config.scripts&&config.scripts.length>0)for(const o of config.scripts){if("javascript"!==o.lang)throw new Error("Only javascript scripts are supported");await e(o)}}else if(!isWindow&&enable_execution&&config.scripts&&config.scripts.length>0)for(const script of config.scripts){if("javascript"!==script.lang)throw new Error("Only javascript scripts are supported");eval(script.content)}on_ready&&await on_ready(server,config),resolve(server)}catch(a){await server.update_client_info({id:client_id,error:a.message}),reject(a)}}))}}),!1),isWindow?window.parent.postMessage({type:"hyphaClientReady"},"*"):self.postMessage({type:"hyphaClientReady"})}))}return __webpack_exports__})()));
|
|
2
|
+
//# sourceMappingURL=hypha-rpc-websocket.min.js.map
|