hypha-rpc 0.20.54 → 0.20.55

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.
@@ -1,2 +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__={164:(e,t,r)=>{r.d(t,{m:()=>F,y:()=>J});var n=r(878),i=r(287);function s(e){return"".concat(e<0?"-":"","0x").concat(Math.abs(e).toString(16).padStart(2,"0"))}var o,a=function(e,t){this.type=e,this.data=t},c=(o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},o(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),_=function(e){function t(r){var n=e.call(this,r)||this,i=Object.create(t.prototype);return Object.setPrototypeOf(n,i),Object.defineProperty(n,"name",{configurable:!0,enumerable:!1,value:t.name}),n}return c(t,e),t}(Error),h=4294967295;function l(e,t,r){var n=Math.floor(r/4294967296),i=r;e.setUint32(t,n),e.setUint32(t+4,i)}function d(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var p,u,f,y={type:-1,encode:function(e){var t,r,n,i;return e instanceof Date?function(e){var t,r=e.sec,n=e.nsec;if(r>=0&&n>=0&&r<=17179869183){if(0===n&&r<=4294967295){var i=new Uint8Array(4);return(t=new DataView(i.buffer)).setUint32(0,r),i}var s=r/4294967296,o=4294967295&r;return i=new Uint8Array(8),(t=new DataView(i.buffer)).setUint32(0,n<<2|3&s),t.setUint32(4,o),i}return i=new Uint8Array(12),(t=new DataView(i.buffer)).setUint32(0,n),l(t,4,r),i}((n=1e6*((t=e.getTime())-1e3*(r=Math.floor(t/1e3))),{sec:r+(i=Math.floor(n/1e9)),nsec:n-1e9*i})):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 r=t.getUint32(0);return{sec:4294967296*(3&r)+t.getUint32(4),nsec:r>>>2};case 12:return{sec:d(t,4),nsec:t.getUint32(0)};default:throw new _("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},m=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(y)}return e.prototype.register=function(e){var t=e.type,r=e.encode,n=e.decode;if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{var i=1+t;this.builtInEncoders[i]=r,this.builtInDecoders[i]=n}},e.prototype.tryToEncode=function(e,t){for(var r=0;r<this.builtInEncoders.length;r++)if(null!=(n=this.builtInEncoders[r])&&null!=(i=n(e,t)))return new a(-1-r,i);for(r=0;r<this.encoders.length;r++){var n,i;if(null!=(n=this.encoders[r])&&null!=(i=n(e,t)))return new a(r,i)}return e instanceof a?e:null},e.prototype.decode=function(e,t,r){var n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,r):new a(t,e)},e.defaultCodec=new e,e}(),w=("undefined"==typeof process||"never"!==(null===(p=null===process||void 0===process?void 0:process.env)||void 0===p?void 0:p.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function g(e){for(var t=e.length,r=0,n=0;n<t;){var i=e.charCodeAt(n++);if(4294967168&i)if(4294965248&i){if(i>=55296&&i<=56319&&n<t){var s=e.charCodeAt(n);56320==(64512&s)&&(++n,i=((1023&i)<<10)+(1023&s)+65536)}r+=4294901760&i?4:3}else r+=2;else r++}return r}var v=w?new TextEncoder:void 0,b=w?"undefined"!=typeof process&&"force"!==(null===(u=null===process||void 0===process?void 0:process.env)||void 0===u?void 0:u.TEXT_ENCODING)?200:0:h,k=(null==v?void 0:v.encodeInto)?function(e,t,r){v.encodeInto(e,t.subarray(r))}:function(e,t,r){t.set(v.encode(e),r)};function E(e,t,r){for(var n=t,i=n+r,s=[],o="";n<i;){var a=e[n++];if(128&a)if(192==(224&a)){var c=63&e[n++];s.push((31&a)<<6|c)}else if(224==(240&a)){c=63&e[n++];var _=63&e[n++];s.push((31&a)<<12|c<<6|_)}else if(240==(248&a)){var h=(7&a)<<18|(c=63&e[n++])<<12|(_=63&e[n++])<<6|63&e[n++];h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|1023&h),s.push(h)}else s.push(a);else s.push(a);s.length>=4096&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(o+=String.fromCharCode.apply(String,s)),o}var A=w?new TextDecoder:null,S=w?"undefined"!=typeof process&&"force"!==(null===(f=null===process||void 0===process?void 0:process.env)||void 0===f?void 0:f.TEXT_DECODER)?200:0:h;function U(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)}var x=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 r=0;r<this.maxKeyLength;r++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,r){e:for(var n=0,i=this.caches[r-1];n<i.length;n++){for(var s=i[n],o=s.bytes,a=0;a<r;a++)if(o[a]!==e[t+a])continue e;return s.str}return null},e.prototype.store=function(e,t){var r=this.caches[e.length-1],n={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)},e.prototype.decode=function(e,t,r){var n=this.find(e,t,r);if(null!=n)return this.hit++,n;this.miss++;var i=E(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,i),i},e}(),j=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[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(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,a])}}},O=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,i,(t=e[r](t)).done,t.value)}))}}},T=function(e){return this instanceof T?(this.v=e,this):new T(e)},C=new DataView(new ArrayBuffer(0)),D=new Uint8Array(C.buffer),I=function(){try{C.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),P=new I("Insufficient data"),M=new x,$=function(){function e(e,t,r,n,i,s,o,a){void 0===e&&(e=m.defaultCodec),void 0===t&&(t=void 0),void 0===r&&(r=h),void 0===n&&(n=h),void 0===i&&(i=h),void 0===s&&(s=h),void 0===o&&(o=h),void 0===a&&(a=M),this.extensionCodec=e,this.context=t,this.maxStrLength=r,this.maxBinLength=n,this.maxArrayLength=i,this.maxMapLength=s,this.maxExtLength=o,this.keyDecoder=a,this.totalPos=0,this.pos=0,this.view=C,this.bytes=D,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=U(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=U(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),r=U(e),n=new Uint8Array(t.length+r.length);n.set(t),n.set(r,t.length),this.setBuffer(n)}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,r=this.pos;return new RangeError("Extra ".concat(t.byteLength-r," 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 j(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,r,n,i,o,a,c,_;return o=this,a=void 0,_=function(){var o,a,c,_,h,l,d,p;return j(this,(function(u){switch(u.label){case 0:o=!1,u.label=1;case 1:u.trys.push([1,6,7,12]),t=O(e),u.label=2;case 2:return[4,t.next()];case 3:if((r=u.sent()).done)return[3,5];if(c=r.value,o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{a=this.doDecodeSync(),o=!0}catch(e){if(!(e instanceof I))throw e}this.totalPos+=this.pos,u.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return _=u.sent(),n={error:_},[3,12];case 7:return u.trys.push([7,,10,11]),r&&!r.done&&(i=t.return)?[4,i.call(t)]:[3,9];case 8:u.sent(),u.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 l=(h=this).headByte,d=h.pos,p=h.totalPos,new RangeError("Insufficient data in parsing ".concat(s(l)," at ").concat(p," (").concat(d," in the current buffer)"))}}))},new((c=void 0)||(c=Promise))((function(e,t){function r(e){try{i(_.next(e))}catch(e){t(e)}}function n(e){try{i(_.throw(e))}catch(e){t(e)}}function i(t){var i;t.done?e(t.value):(i=t.value,i instanceof c?i:new c((function(e){e(i)}))).then(r,n)}i((_=_.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,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(e){i[e]&&(n[e]=function(t){return new Promise((function(r,n){s.push([e,t,r,n])>1||a(e,t)}))})}function a(e,t){try{(r=i[e](t)).value instanceof T?Promise.resolve(r.value.v).then(c,_):h(s[0][2],r)}catch(e){h(s[0][3],e)}var r}function c(e){a("next",e)}function _(e){a("throw",e)}function h(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}(this,arguments,(function(){var r,n,i,s,o,a,c,_,h;return j(this,(function(l){switch(l.label){case 0:r=t,n=-1,l.label=1;case 1:l.trys.push([1,13,14,19]),i=O(e),l.label=2;case 2:return[4,T(i.next())];case 3:if((s=l.sent()).done)return[3,12];if(o=s.value,t&&0===n)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(n=this.readArraySize(),r=!1,this.complete()),l.label=4;case 4:l.trys.push([4,9,,10]),l.label=5;case 5:return[4,T(this.doDecodeSync())];case 6:return[4,l.sent()];case 7:return l.sent(),0==--n?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((a=l.sent())instanceof I))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(),_={error:c},[3,19];case 14:return l.trys.push([14,,17,18]),s&&!s.done&&(h=i.return)?[4,T(h.call(i))]:[3,16];case 15:l.sent(),l.label=16;case 16:return[3,18];case 17:if(_)throw _.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 r=e-160;t=this.decodeUtf8String(r,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)r=this.lookU8(),t=this.decodeUtf8String(r,1);else if(218===e)r=this.lookU16(),t=this.decodeUtf8String(r,2);else if(219===e)r=this.lookU32(),t=this.decodeUtf8String(r,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 _("Unrecognized type byte: ".concat(s(e)));n=this.lookU32(),t=this.decodeExtension(n,4)}this.complete();for(var i=this.stack;i.length>0;){var o=i[i.length-1];if(0===o.type){if(o.array[o.position]=t,o.position++,o.position!==o.size)continue e;i.pop(),t=o.array}else{if(1===o.type){if(void 0,"string"!=(a=typeof t)&&"number"!==a)throw new _("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new _("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}i.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 _("Unrecognized array type byte: ".concat(s(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new _("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 _("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 r;if(e>this.maxStrLength)throw new _("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw P;var n,i=this.pos+t;return n=this.stateIsMapKey()&&(null===(r=this.keyDecoder)||void 0===r?void 0:r.canBeCached(e))?this.keyDecoder.decode(this.bytes,i,e):e>S?function(e,t,r){var n=e.subarray(t,t+r);return A.decode(n)}(this.bytes,i,e):E(this.bytes,i,e),this.pos+=t+e,n},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 _("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw P;var r=this.pos+t,n=this.bytes.subarray(r,r+e);return this.pos+=t+e,n},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new _("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var r=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,r,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,t,r=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,r},e.prototype.readI64=function(){var e=d(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}(),W={};function L(e,t){return void 0===t&&(t=W),new $(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decodeMulti(e)}var R=function(){function e(e,t,r,n,i,s,o,a){void 0===e&&(e=m.defaultCodec),void 0===t&&(t=void 0),void 0===r&&(r=100),void 0===n&&(n=2048),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===o&&(o=!1),void 0===a&&(a=!1),this.extensionCodec=e,this.context=t,this.maxDepth=r,this.initialBufferSize=n,this.sortKeys=i,this.forceFloat32=s,this.ignoreUndefined=o,this.forceIntegerToFloat=a,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),r=new Uint8Array(t),n=new DataView(t);r.set(this.bytes),this.view=n,this.bytes=r},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>b){var t=g(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),k(e,this.bytes,this.pos),this.pos+=t}else t=g(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,r){for(var n=e.length,i=r,s=0;s<n;){var o=e.charCodeAt(s++);if(4294967168&o){if(4294965248&o){if(o>=55296&&o<=56319&&s<n){var a=e.charCodeAt(s);56320==(64512&a)&&(++s,o=((1023&o)<<10)+(1023&a)+65536)}4294901760&o?(t[i++]=o>>18&7|240,t[i++]=o>>12&63|128,t[i++]=o>>6&63|128):(t[i++]=o>>12&15|224,t[i++]=o>>6&63|128)}else t[i++]=o>>6&31|192;t[i++]=63&o|128}else t[i++]=o}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var r=this.extensionCodec.tryToEncode(e,this.context);if(null!=r)this.encodeExtension(r);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 r=U(e);this.writeU8a(r)},e.prototype.encodeArray=function(e,t){var r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large array: ".concat(r));this.writeU8(221),this.writeU32(r)}for(var n=0,i=e;n<i.length;n++){var s=i[n];this.doEncode(s,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var r=0,n=0,i=t;n<i.length;n++)void 0!==e[i[n]]&&r++;return r},e.prototype.encodeMap=function(e,t){var r=Object.keys(e);this.sortKeys&&r.sort();var n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large map object: ".concat(n));this.writeU8(223),this.writeU32(n)}for(var i=0,s=r;i<s.length;i++){var o=s[i],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),function(e,t,r){var n=r/4294967296,i=r;e.setUint32(t,n),e.setUint32(t+4,i)}(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),l(this.view,this.pos,e),this.pos+=8},e}(),B={};function q(e,t){return void 0===t&&(t=B),new R(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat).encodeSharedRef(e)}const F=3,z=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function K(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 N(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?N(e,t.split(".")):0===t.length?e:N(e[t[0]],t.slice(1))}function G(e,t=null,r=!1){if(Array.isArray(e))return e.map(((e,t)=>G(e,null,r)));if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=G(e[n],n,r);return t}if("function"==typeof e){if(e.__schema__){const n=JSON.parse(JSON.stringify(e.__schema__));return t&&(n.name=t,e.__schema__.name=t),r&&n.parameters&&n.parameters.properties&&delete n.parameters.properties.context,{type:"function",function:n}}return{type:"function"}}return"number"==typeof e?{type:"number"}:"string"==typeof e?{type:"string"}:"boolean"==typeof e?{type:"boolean"}:null===e?{type:"null"}:{}}class H{constructor(e,t,r,n){this._timeout=e,this._callback=t,this._args=r,this._label=n||"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&&this.started?(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 V extends Object{}class J extends n.sw{constructor(e,{client_id:t=null,default_context:r=null,name:i=null,codecs:s=null,method_timeout:o=null,max_message_buffer_size:a=0,debug:c=!1,workspace:_=null,silent:h=!1,app_id:l=null,server_base_url:d=null,long_message_chunk_size:p=null}){if(super(c),this._codecs=s||{},(0,n.vA)(t&&"string"==typeof t),(0,n.vA)(t,"client_id is required"),this._client_id=t,this._name=i,this._app_id=l||"*",this._local_workspace=_,this._silent=h,this.default_context=r||{},this._method_annotations=new WeakMap,this._max_message_buffer_size=a,this._chunk_store={},this._method_timeout=o||30,this._server_base_url=d,this._long_message_chunk_size=p||262144,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",api_version:F},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),set:this._set_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this.on("method",this._handle_method.bind(this)),this.on("error",console.error),(0,n.vA)(e.emit_message&&e.on_message),(0,n.vA)(void 0!==e.manager_id,"Connection must have manager_id"),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e;const t=async e=>{if(!this._silent&&this._connection.manager_id){console.debug("Connection established, reporting services...");try{const e=await this.get_manager_service({timeout:10,case_conversion:"camel"}),t=Object.values(this._services),r=t.length;let n=0;for(let r of t)try{const t=this._extract_service_info(r);await e.registerService(t),n++}catch(e){console.error(`Failed to register service ${r.id||"unknown"}: ${e}`)}n===r?console.info(`Successfully registered all ${n} services with the server`):console.warn(`Only registered ${n} out of ${r} services with the server`)}catch(e){console.error(`Failed to get manager service for registering services: ${e}`)}}e&&(e.public_base_url&&(this._server_base_url=e.public_base_url),this._fire("connected",e))};e.on_connected(t),t()}else 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,n.vA)("ping"==e),"pong"}async ping(e,t){let r=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0,_rdoc:"Ping a remote client"});(0,n.vA)("pong"==await r("ping",t))}_create_message(e,t,r,n){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={}),!r&&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,r,i){if(r){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,n.vA)(t instanceof z),s[e].push(t)}_set_message(e,t,r,i,s){if(i){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const o=this._object_store.message_cache;if(!o[e])throw new Error(`Message with key ${e} does not exists.`);(0,n.vA)(r instanceof z),o[e][t]=r}_remove_message(e,t){const r=this._object_store.message_cache;if(!r[e])throw new Error(`Message with key ${e} does not exists.`);delete r[e]}_process_message(e,t,r){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const i=this._object_store.message_cache;if((0,n.vA)(!!r,"Context is required"),!i[e])throw new Error(`Message with key ${e} does not exists.`);var s,o,a,c;i[e]=(a=(o=(s=i[e]).map((function(e){return e.byteLength}))).reduce((function(e,t){return e+t}),0),c=new Uint8Array(a),o.reduce((function(e,t,r){return c.set(new Uint8Array(s[r]),e),e+t}),0),c.buffer);let _=L(i[e]);const{done:h,value:l}=_.next(),d=l;if(Object.assign(d,{from:r.from,to:r.to,ws:r.ws,user:r.user}),d.ctx=JSON.parse(JSON.stringify(d)),Object.assign(d.ctx,this.default_context),!h){let e=_.next();Object.assign(d,e.value)}this._fire(d.type,d),delete i[e]}_on_message(e){if("string"==typeof e){const t=JSON.parse(e);this._fire(t.type,t)}else if(e instanceof ArrayBuffer){let t=L(e);const{done:r,value:n}=t.next(),i=n;if(i.ctx=JSON.parse(JSON.stringify(i)),Object.assign(i.ctx,this.default_context),!r){let e=t.next();Object.assign(i,e.value)}this._fire(i.type,i)}else{if("object"!=typeof e)throw new Error("Invalid message format");this._fire(e.type,e)}}reset(){this._event_handlers={},this._services={}}async disconnect(){this._fire("disconnected"),await this._connection.disconnect()}async get_manager_service(e){e=e||{};for(let t=0;t<20;t++){if(!this._connection.manager_id){if(t<19){console.warn(`Manager ID not set, retrying in 500ms (attempt ${t+1}/20)`),await new Promise((e=>setTimeout(e,500)));continue}throw new Error("Manager ID not set after maximum retries")}try{return await this.get_remote_service(`*/${this._connection.manager_id}:default`,e)}catch(e){if(!(t<19))throw e;console.warn(`Failed to get manager service, retrying in 500ms: ${e.message}`),await new Promise((e=>setTimeout(e,500)))}}}get_all_local_services(){return this._services}get_local_service(e,t){(0,n.vA)(e);const[r,i]=t.to.split("/");(0,n.vA)(i===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=t.ws,"public"==s.config.visibility)return s;if(t.ws===r)return s;throw new Error(`Permission denied for getting protected service: ${e}, workspace mismatch: ${r} != ${t.ws}`)}async get_remote_service(e,t){let{timeout:r,case_conversion:i,kwargs_expansion:s}=t||{};r=void 0===r?this._method_timeout:r,!e&&this._connection.manager_id?e="*/"+this._connection.manager_id:e.includes(":")||(e=this._client_id+":"+e);const o=e.split(":")[0];let a=e.split(":")[1];if(a.includes("@")){a=a.split("@")[0];const t=e.split("@")[1];this._app_id&&"*"!==this._app_id&&(0,n.vA)(t===this._app_id,`Invalid app id: ${t} != ${this._app_id}`)}(0,n.vA)(o,`Invalid service uri: ${e}`);try{const t=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:o,_rmethod:"services.built-in.get_service",_rpromise:!0,_rdoc:"Get a remote service"});let c=await(0,n.fm)(t(a),r,"Timeout Error: Failed to get remote service: "+e);return c.id=`${o}:${a}`,s&&(c=(0,n.uX)(c)),i?Object.assign(new V,(0,n.gX)(c,i)):Object.assign(new V,c)}catch(t){throw console.warn("Failed to get remote service: "+e,t),t}}_annotate_service_methods(e,t,r,n,i){if("function"==typeof e){let s=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(r)?r.includes(s):!!r,run_in_executor:n,method_id:"services."+t,visibility:i})}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]=N(this._object_store,o.__rpc_object__._rmethod),o=e[s]}this._annotate_service_methods(o,t+"."+s,r,n,i)}}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={},r=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let n of r)"constructor"!==n&&("function"==typeof e[n]?t[n]=e[n].bind(e):t[n]=e[n]);e.id=e.id||"default",e=t}(0,n.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 r=!1,i=!1;e.config.require_context&&(r=e.config.require_context),e.config.run_in_executor&&(i=!0);const s=e.config.visibility||"protected";if((0,n.vA)(["protected","public"].includes(s)),this._annotate_service_methods(e,e.id,r,i,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){const t=e.config||{};t.workspace=t.workspace||this._local_workspace||this._connection.workspace;const r=G(e,null,t.require_context);return{config:t,id:`${t.workspace}/${this._client_id}:${e.id}`,name:e.name||e.id,description:e.description||"",type:e.type||"generic",docs:e.docs||null,app_id:this._app_id,service_schema:r}}async get_service_schema(e){return G(e,null,e.config.require_context)}async register_service(e,t){let r,{check_type:n,notify:s,overwrite:o}=t||{};if(s=void 0===s||s,n&&e.type)try{r=await this.get_manager_service({timeout:10,case_conversion:"camel"}),e=function(e,t){function r(e,t,r="root"){for(let n in t)if(!e.hasOwnProperty(n))throw new Error(`Missing key '${n}' in service at path '${r}'`);for(let n in e)if("type"!==n&&!t.hasOwnProperty(n))throw new Error(`Unexpected key '${n}' in service at path '${r}'`)}return r(e,t.definition),function e(t,n,s="root"){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t)){if(t.length!==n.length)throw new Error(`Length mismatch at path '${s}'`);t.forEach(((r,o)=>{let a=`${s}[${o}]`;if("object"!=typeof r||Array.isArray(r)){if("function"==typeof r){if(!n.hasOwnProperty(o))throw new Error(`Missing schema for function at index ${o} in path '${a}'`);t[o]=(0,i.G)(r,{name:n[o].name,description:n[o].description||"",parameters:n[o].parameters})}}else e(r,n[o],a)}))}}else{r(t,n,s);for(let r in t){let o=t[r],a=`${s}.${r}`;if("object"!=typeof o||Array.isArray(o)){if("function"==typeof o){if(!n.hasOwnProperty(r))throw new Error(`Missing schema for function '${r}' at path '${a}'`);t[r]=(0,i.G)(o,{name:n[r].name,description:n[r].description||"",parameters:n[r].parameters})}}else e(o,n[r],a)}}}(e,t.definition),e}(e,await r.get_service_type(e.type))}catch(t){throw new Error(`Failed to get service type ${e.type}, error: ${t}`)}const a=this.add_service(e,o),c=this._extract_service_info(a);if(s)try{r=r||await this.get_manager_service({timeout:10,case_conversion:"camel"}),await r.registerService(c)}catch(e){throw new Error(`Failed to notify workspace manager: ${e}`)}return c}async unregister_service(e,t){let r;if(t=void 0===t||t,r="string"==typeof e?e:e.id,(0,n.vA)(r&&"string"==typeof r,`Invalid service id: ${r}`),r.includes(":")&&(r=r.split(":")[1]),r.includes("@")&&(r=r.split("@")[0]),!this._services[r])throw new Error(`Service not found: ${r}`);if(t){const e=await this.get_manager_service({timeout:10,case_conversion:"camel"});await e.unregisterService(r)}delete this._services[r]}_ndarray(e,t,r){const i=(0,n.D4)(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}}_encode_callback(e,t,r,n,i,s,o){let a=`${r}.${e}`,c={_rtype:"method",_rtarget:s?`${s}/${this._client_id}`:this._client_id,_rmethod:a,_rpromise:!1};const _=this;let h=function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){console.error(`Error in callback(${a}, ${o}): ${e}`)}finally{i&&i.started&&i.clear(),n&&_._object_store[r]&&delete _._object_store[r]}};return h.__name__=`callback(${a})`,[c,h]}async _encode_promise(e,t,r,i,s,o,a){let c=this._get_session_store(r,!0);(0,n.vA)(c,`Failed to create session store ${r} due to invalid parent`);let _={};return s&&t&&this._method_timeout?([_.heartbeat,c.heartbeat]=this._encode_callback("heartbeat",s.reset.bind(s),r,!1,null,o),c.timer=s,_.interval=this._method_timeout/2):s=null,[_.resolve,c.resolve]=this._encode_callback("resolve",e,r,i,s,o,`resolve (${a})`),[_.reject,c.reject]=this._encode_callback("reject",t,r,i,s,o,`reject (${a})`),_}async _send_chunks(e,t,r){const i=await this.get_remote_service(`${t}:built-in`);if(!i.message_cache)throw new Error("Remote client does not support message caching for large messages.");const s=i.message_cache,o=r||(0,n.bq)(),a=e.length,c=Date.now(),_=Math.ceil(a/this._long_message_chunk_size);if(i.config.api_version>=3){await s.create(o,!!r);const t=new n.jf(30),i=[];for(let n=0;n<_;n++){const c=n*this._long_message_chunk_size,h=e.slice(c,c+this._long_message_chunk_size),l=async()=>{await s.set(o,n,h,!!r),console.debug(`Sending chunk ${n+1}/${_} (total=${a} bytes)`)};i.push(t.run(l))}await Promise.all(i)}else{await s.create(o,!!r);for(let t=0;t<_;t++){const n=t*this._long_message_chunk_size,i=e.slice(n,n+this._long_message_chunk_size);await s.append(o,i,!!r),console.debug(`Sending chunk ${t+1}/${_} (total=${a} bytes)`)}}await s.process(o,!!r);const h=((Date.now()-c)/1e3).toFixed(2);console.debug(`All chunks (${a} bytes) sent in ${h} s`)}emit(e,t){if((0,n.vA)("object"==typeof e&&e.type,"Invalid message, must be an object with a `type` fields."),!e.to)return void this._fire(e.type,e);let r=q(e);if(t){const e=q(t);r=new Uint8Array([...r,...e])}const i=r.length;return i>this._long_message_chunk_size+1024&&console.warn(`Sending large message (size=${i})`),this._emit_message(r)}_generate_remote_method(e,t,r,i,s){let o=e._rtarget;i&&!o.includes("/")&&(i!==o&&(o=i+"/"+o),e._rtarget=o);let a=e._rmethod,c=e._rpromise||!1;const _=`method: ${a}, docs: ${e._rdoc}`,h=this;function l(){return new Promise((async(e,i)=>{let d=(0,n.bq)();r&&(d=r+"."+d);let p=h._get_session_store(d,!0);if(!p)return void i(new Error(`Runtime Error: Failed to get session store ${d} (context: ${_})`));p.target_id=o;const u=await h._encode(Array.prototype.slice.call(arguments),d,s),f=u.length,y=f>0&&"object"==typeof u[f-1]&&null!==u[f-1]&&u[f-1]._rkwargs;let m;y&&delete u[f-1]._rkwargs,m=h._local_workspace?h._local_workspace+"/"+h._client_id:h._client_id;let w={type:"method",from:m,to:o,method:a},g={};u&&(g.args=u),y&&(g.with_kwargs=y),t&&(w.parent=t);let v=null;if(c){w.session=d;let t=`${o}:${a}`;v=new H(h._method_timeout,i,[`Method call time out: ${t}, context: ${_}`],t);let r=!0;for(let e of u)if("object"==typeof e&&!0===e._rintf){r=!1;break}const n=await h._encode_promise(e,i,d,r,v,s,_);if(!0===c)g.promise=n;else{if("*"!==c)throw new Error(`Unsupported promise type: ${c}`);g.promise="*",g.t=h._method_timeout/2}}let b=q(w);if(g){const e=q(g);b=new Uint8Array([...b,...e])}b.length<=h._long_message_chunk_size+1024||l.__no_chunk__?h._emit_message(b).then((function(){v&&v.reset()})).catch((function(e){console.error("Failed to send message",e),i(e),v&&v.clear()})):h._send_chunks(b,o,t).then((function(){v&&v.reset()})).catch((function(e){console.error("Failed to send message",e),i(e),v&&v.clear()}))}))}l.__rpc_object__=e;const d=a.split(".");return l.__name__=e._rname||d[d.length-1],l.__name__.includes("#")&&(l.__name__=l.__name__.split("#")[1]),l.__doc__=e._rdoc||`Remote method: ${a}`,l.__schema__=e._rschema,l.__no_chunk__="services.built-in.message_cache.append"===e._rmethod,l}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,n.vA)(e.method&&e.ctx&&e.from);const r=e.from+":"+e.method,i=e.from.split("/")[0],s=e.from.split("/")[1];let o;e.to=e.to.includes("/")?e.to:i+"/"+e.to,e.ctx.to=e.to,this._local_workspace?(this._local_workspace&&"*"!==this._local_workspace&&(0,n.vA)(e.to.split("/")[0]===this._local_workspace,"Workspace mismatch: "+e.to.split("/")[0]+" != "+this._local_workspace),o=this._local_workspace):o=e.to.split("/")[0];const a=e.parent;let c,_,h,l;if(e.promise){const d=await this._decode("*"===e.promise?this._expand_promise(e):e.promise,e.session,a,i,o);if(c=d.resolve,_=d.reject,d.heartbeat&&d.interval){async function p(){try{await d.heartbeat()}catch(e){console.error(e)}}t=setInterval(p,1e3*d.interval)}}try{h=N(this._object_store,e.method)}catch(u){throw new Error(`Method not found: ${r} at ${this._client_id}`)}if((0,n.vA)(h&&"function"==typeof h,"Invalid method: "+r),this._method_annotations.has(h)){if("protected"===this._method_annotations.get(h).visibility&&o!==i&&("*"!==i||s!==this._connection.manager_id))throw new Error("Permission denied for invoking protected method "+r+", workspace mismatch: "+o+" != "+i)}else{let f=this._object_store[e.method.split(".")[0]].target_id;if(o===i&&f&&-1===f.indexOf("/")&&(f=o+"/"+f),f!==e.from)throw new Error("Access denied for method call ("+r+") from "+e.from+" to target "+f)}if(a&&(0,n.vA)(null!==this._get_session_store(a,!0),"Parent session was closed: "+a),l=e.args?await this._decode(e.args,e.session,null,i,null):[],this._method_annotations.has(h)&&this._method_annotations.get(h).require_context){if(l.length+1<h.length)for(let y=l.length;y<h.length-1;y++)l.push(void 0);l.push(e.ctx),(0,n.vA)(l.length===h.length,`Runtime Error: Invalid number of arguments for method ${r}, expected ${h.length} but got ${l.length}`)}if(e.promise){const m=h.apply(null,l);m instanceof Promise?m.then((e=>{c(e),clearInterval(t)})).catch((e=>{_(e),clearInterval(t)})):(c(m),clearInterval(t))}else h.apply(null,l),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 r=this._object_store;const n=e.split(".");if(t){const e=n.length-1;for(let t of n.slice(0,e)){if(!r[t])return null;r=r[t]}return r[n[e]]||(r[n[e]]={}),r[n[e]]}for(let e of n){if(!r[e])return null;r=r[e]}return r}async _encode(e,t,r){const i=typeof e;if("number"===i||"string"===i||"boolean"===i||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__&&(e.__rpc_object__._rserver||this._server_base_url)===this._server_base_url)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,r),s._rtype=a,s}if((0,n.WH)(e)||(0,n.aU)(e)){(0,n.vA)(t&&"string"==typeof t,"Session ID is required for generator encoding");const c=(0,n.bq)(),_=this._get_session_store(t,!0);(0,n.vA)(null!==_,`Failed to create session store ${t} due to invalid parent`);const h=(0,n.aU)(e),l=async()=>{if(h){const t=e,r=await t.next();return r.done?(delete _[c],{_rtype:"stop_iteration"}):r.value}{const t=e.next();return t.done?(delete _[c],{_rtype:"stop_iteration"}):t.value}};return _[c]=l,s={_rtype:"generator",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${c}`,_rpromise:"*",_rdoc:"Remote generator"},s}if("function"==typeof e){if(this._method_annotations.has(e)){let d=this._method_annotations.get(e);s={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:d.method_id,_rpromise:"*",_rname:e.name}}else{let p;(0,n.vA)("string"==typeof t),p=e.__name__?`${(0,n.bq)()}#${e.__name__}`:(0,n.bq)(),s={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${p}`,_rpromise:"*",_rname:e.name};let u=this._get_session_store(t,!0);(0,n.vA)(null!==u,`Failed to create session store ${t} due to invalid parent`),u[p]=e}if(s._rdoc=e.__doc__,!s._rdoc)try{const f=function(e){const t=e.toString(),r=t.match(/function\s*(\w*)/),n=r&&r[1]||"",i=t.match(/\(([^)]*)\)/);let s="";i&&(s=i[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")||"",_=a||c;return n&&s.length>0&&{name:n,sig:s,doc:_}}(e);f&&!s._rdoc&&(s._rdoc=`${f.doc}`)}catch(y){console.error("Failed to extract function docstring:",e)}return s._rschema=e.__schema__,s}const o=Array.isArray(e);for(let m of Object.keys(this._codecs)){const w=this._codecs[m];if(w.encoder&&e instanceof w.type){let g=await Promise.resolve(w.encoder(e));if(g&&!g._rtype&&(g._rtype=w.name),"object"==typeof g){const v=g._rtype;delete g._rtype,g=await this._encode(g,t,r),g._rtype=v}return s=g,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const b=e.dataSync();s={_rtype:"ndarray",_rvalue:new Uint8Array(b.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const k=(0,n.D4)(e.selection.data);s={_rtype:"ndarray",_rvalue:new Uint8Array(e.selection.data.buffer),_rshape:e.shape,_rdtype:k}}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 E=0;async function A(t){let r;r=t?e.slice(E,E+t):e.slice(E);const n=new Uint8Array(await r.arrayBuffer());return E+=n.byteLength,n}function S(e){E=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(A,t,r),seek:await this._encode(S,t,r)}}else if(e instanceof z){const U=(0,n.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,r)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,r)};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 x=Object.keys(e);for(let j of x)s[j]=await this._encode(e[j],t,r)}}if(!s)throw new Error("Failed to encode object");return s}async decode(e){return await this._decode(e)}async _decode(e,t,r,i,s){if(!e)return e;let o;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const a=e._rtype;delete e._rtype,(e=await this._decode(e,t,r,i,s))._rtype=a,o=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)o=this._generate_remote_method(e,t,r,i,s);else if("generator"===e._rtype){const c=this._generate_remote_method(e,t,r,i,s);async function*_(){try{for(;;)try{const e=await c();if(e&&"stop_iteration"===e._rtype)break;yield e}catch(e){throw console.error("Error in generator:",e),e}}catch(e){throw console.error("Error in generator:",e),e}}o=_()}else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(K)),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(K));const h=n.RR[e._rdtype];o=tf.tensor(new h(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 l=n.RR[e._rdtype];if(!l)throw new Error("unsupported dtype: "+e._rdtype);o=new l(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 d=await this._generate_remote_method(e.read,t,r,i,s),p=await d();o=new Blob([p],{type:e.type,name:e.name})}else{o={};for(let u of Object.keys(e))u.startsWith("_")||(o[u]=await this._decode(e[u],t,r,i,s))}o.__rpc_object__=e}else if("orderedmap"===e._rtype)o=new Map(await this._decode(e._rvalue,t,r,i,s));else if("set"===e._rtype)o=new Set(await this._decode(e._rvalue,t,r,i,s));else{const f=e._rtype;delete e._rtype,o=await this._decode(e,t,r,i,s),o._rtype=f}else if(e.constructor===Object||Array.isArray(e)){const y=Array.isArray(e);o=y?[]:{};for(let m of Object.keys(e))if(y||e.hasOwnProperty(m)){const w=e[m];o[m]=await this._decode(w,t,r,i,s)}}else o=e;if(void 0===o)throw new Error("Failed to decode object");return o}_expand_promise(e){return{heartbeat:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".heartbeat",_rdoc:`heartbeat callback for method: ${e.method}`},resolve:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".resolve",_rdoc:`resolve callback for method: ${e.method}`},reject:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".reject",_rdoc:`reject callback for method: ${e.method}`},interval:e.t}}}},878:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}function toCamelCase(e){return e.includes("_")?e.replace(/_./g,(e=>e[1].toUpperCase())):e}function toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function expandKwargs(e){if("object"!=typeof e||null===e)return e;const t=Array.isArray(e)?[]:{};for(const r in e)if(e.hasOwnProperty(r)){const n=e[r];"function"==typeof n?(t[r]=(...e)=>{if(0===e.length)throw new Error(`Function "${r}" expects at least one argument.`);const t=e[e.length-1];let i={};return"object"!=typeof t||null===t||Array.isArray(t)||(i={...t,_rkwarg:!0},e=e.slice(0,-1)),n(...e,i)},t[r].__name__=r,n.__schema__&&(t[r].__schema__={...n.__schema__},t[r].__schema__.name=r)):t[r]=expandKwargs(n)}return t}function convertCase(e,t){if("object"!=typeof e||null===e||!t)return e;const r=Array.isArray(e)?[]:{};for(const n in e)if(e.hasOwnProperty(n)){const i=e[n],s=toCamelCase(n),o=toSnakeCase(n);"camel"===t?(r[s]=convertCase(i,t),"function"==typeof i&&(r[s].__name__=s,i.__schema__&&(r[s].__schema__={...i.__schema__},r[s].__schema__.name=s))):"snake"===t?(r[o]=convertCase(i,t),"function"==typeof i&&(r[o].__name__=o,i.__schema__&&(r[o].__schema__={...i.__schema__},r[o].__schema__.name=o))):(t.includes("camel")&&(r[s]=convertCase(i,"camel")),t.includes("snake")&&(r[o]=convertCase(i,"snake")))}return r}function parseServiceUrl(e){e=e.replace(/\/$/,"");const t=new RegExp("^(https?:\\/\\/[^/]+)\\/([a-z0-9_-]+)\\/services\\/(?:(?<clientId>[a-zA-Z0-9_-]+):)?(?<serviceId>[a-zA-Z0-9_-]+)(?:@(?<appId>[a-zA-Z0-9_-]+))?"),r=e.match(t);if(!r)throw new Error("URL does not match the expected pattern");const n=r[1],i=r[2],s=r.groups?.clientId||"*",o=r.groups?.serviceId;return{serverUrl:n,workspace:i,clientId:s,serviceId:o,appId:r.groups?.appId||"*"}}__webpack_require__.d(__webpack_exports__,{D4:()=>typedArrayToDtype,RR:()=>dtypeToTypedArray,V0:()=>loadRequirements,WH:()=>isGenerator,aU:()=>isAsyncGenerator,bq:()=>randId,fm:()=>waitFor,gX:()=>convertCase,iO:()=>parseServiceUrl,jf:()=>Semaphore,sw:()=>MessageEmitter,uX:()=>expandKwargs,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,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 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,r){let n;return Promise.race([e,new Promise(((e,i)=>n=setTimeout((()=>{i(r||"Timeout Error")}),1e3*t)))]).finally((()=>clearTimeout(n)))}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)}waitFor(e,t){return new Promise(((r,n)=>{const i=e=>{clearTimeout(s),r(e)};this.once(e,i);const s=setTimeout((()=>{this.off(e,i),n(new Error("Timeout"))}),t)}))}}class Semaphore{constructor(e){this.max=e,this.queue=[],this.current=0}async run(e){this.current>=this.max&&await new Promise((e=>this.queue.push(e))),this.current++;try{return await e()}finally{this.current--,this.queue.length>0&&this.queue.shift()()}}}function isGenerator(e){return!!e&&"object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return}function isAsyncGenerator(e){return!!e&&"object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return&&Symbol.asyncIterator in Object(e)&&"AsyncGenerator"===e[Symbol.toStringTag]}},287:(e,t,r)=>{r.d(t,{G:()=>i});var n=r(878);function i(e,{schema_type:t="auto",name:r=null,description:i=null,parameters:s=null}){if(!e||"function"!=typeof e)throw Error("func should be a function");return(0,n.vA)("auto"===t,"schema_type should be auto"),(0,n.vA)(r,"name should not be null"),(0,n.vA)(s&&"object"===s.type,"parameters should be an object"),e.__schema__={name:r,description:i,parameters:s||[]},e}},831:(e,t,r)=>{r.d(t,{b:()=>c,e:()=>_});var n=r(164),i=r(878),s=r(287);class o{constructor(e){this._data_channel=e,this._handle_message=null,this._reconnection_token=null,this._handle_disconnected=null,this._handle_connected=()=>{},this.manager_id=null,this._last_message=null,this._data_channel.onopen=async()=>{this._last_message&&(console.info("Resending last message after connection established"),this._data_channel.send(this._last_message),this._last_message=null),this._handle_connected&&this._handle_connected({channel:this._data_channel})},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(){this._handle_disconnected&&this._handle_disconnected("closed"),console.log("websocket closed"),t._data_channel=null}}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}on_message(e){(0,i.vA)(e,"handler is required"),this._handle_message=e}async emit_message(e){(0,i.vA)(this._handle_message,"No handler for message");try{this._last_message=e,this._data_channel.send(e),this._last_message=null}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}async disconnect(e){this._last_message=null,this._data_channel=null,console.info(`data channel connection disconnected (${e})`)}}async function a(e){(0,i.vA)(e.channel,"No channel provided"),(0,i.vA)(e.workspace,"No workspace provided");const t=e.channel,r=e.client_id||(0,i.bq)(),s=new o(t);return e.context=e.context||{},e.context.connection_type="webrtc",new n.y(s,{client_id:r,default_context:e.context,name:e.name,method_timeout:e.method_timeout||10,workspace:e.workspace,app_id:e.app_id,long_message_chunk_size:e.long_message_chunk_size})}async function c(e,t,r){(r=r||{}).peer_id=r.peer_id||(0,i.bq)();const n=new RTCPeerConnection({iceServers:r.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});return new Promise((async(o,c)=>{try{n.addEventListener("connectionstatechange",(()=>{"failed"===n.connectionState?(n.close(),c(new Error("WebRTC Connection failed"))):"closed"===n.connectionState?c(new Error("WebRTC Connection closed")):console.log("WebRTC Connection state: ",n.connectionState)}),!1),r.on_init&&(await r.on_init(n),delete r.on_init);let _=n.createDataChannel(r.peer_id,{ordered:!0});_.binaryType="arraybuffer";const h=await n.createOffer();await n.setLocalDescription(h);const l=await e.getService(t),d=await l.offer({sdp:n.localDescription.sdp,type:n.localDescription.type});_.onopen=()=>{r.channel=_,r.workspace=d.workspace,setTimeout((async()=>{const e=await a(r);n.rpc=e,n.getService=(0,s.G)((async function(t,...n){return(0,i.vA)(!t.includes(":"),"WebRTC service name should not contain ':'"),(0,i.vA)(!t.includes("/"),"WebRTC service name should not contain '/'"),await e.get_remote_service(r.workspace+"/"+r.peer_id+":"+t,...n)}),{name:"getService",description:"Get a remote service via webrtc",parameters:{type:"object",properties:{service_id:{type:"string",description:"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'"},config:{type:"object",description:"Options for the service"}},required:["id"]}}),n.disconnect=(0,s.G)((async function(){await e.disconnect(),n.close()}),{name:"disconnect",description:"Disconnect from the webrtc connection via webrtc",parameters:{type:"object",properties:{}}}),n.registerCodec=(0,s.G)(e.register_codec,{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),o(n)}),500)},_.onclose=()=>c(new Error("Data channel closed")),await n.setRemoteDescription(new RTCSessionDescription({sdp:d.sdp,type:d.type}))}catch(e){c(e)}}))}async function _(e,t,r){const n=(r=r||{visibility:"protected",require_context:!0}).on_init;return delete r.on_init,await e.registerService({id:t,config:r,offer:(t,i)=>async function(e,t,r,n,i){r=r||{};let s=new RTCSessionDescription({sdp:e.sdp,type:e.type}),o=new RTCPeerConnection({iceServers:r.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});t&&o.addEventListener("datachannel",(async e=>{const r=e.channel;let n=null;i&&i.user&&(n={user:i.user,ws:i.ws}),(await a({channel:r,client_id:r.label,workspace:t.config.workspace,context:n}))._services=t.rpc._services})),n&&await n(o),await o.setRemoteDescription(s);let c=await o.createAnswer();return await o.setLocalDescription(c),{sdp:o.localDescription.sdp,type:o.localDescription.type,workspace:t.config.workspace}}(t,e,r,n,i)})}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](r,r.exports,__webpack_require__),r.exports}__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__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,LocalWebSocket:()=>LocalWebSocket,RPC:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.y,connectToServer:()=>connectToServer,getRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.b,getRemoteService:()=>getRemoteService,loadRequirements:()=>_utils__WEBPACK_IMPORTED_MODULE_1__.V0,login:()=>login,registerRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.e,schemaFunction:()=>_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G,setupLocalClient:()=>setupLocalClient});var _rpc_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(164),_utils__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(878),_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(287),_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(831);const MAX_RETRY=1e6;class WebsocketRPCConnection{constructor(e,t,r,n,i=null,s=60,o=null,a=7200){(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(e&&t,"server_url and client_id are required"),this._server_url=e,this._client_id=t,this._workspace=r,this._token=n,this._reconnection_token=i,this._websocket=null,this._handle_message=null,this._handle_connected=null,this._handle_disconnected=null,this._timeout=s,this._WebSocketClass=o||WebSocket,this._closed=!1,this._legacy_auth=null,this.connection_info=null,this._enable_reconnect=!1,this._token_refresh_interval=a,this.manager_id=null,this._refresh_token_task=null,this._last_message=null}on_message(e){(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(e,"handler is required"),this._handle_message=e}on_connected(e){this._handle_connected=e}on_disconnected(e){this._handle_disconnected=e}async _attempt_connection(e,t=!0){return new Promise(((r,n)=>{this._legacy_auth=!1;const i=new this._WebSocketClass(e);i.binaryType="arraybuffer",i.onopen=()=>{console.info("WebSocket connection established"),r(i)},i.onerror=e=>{console.error("WebSocket connection error:",e),n(new Error(`WebSocket connection error: ${e}`))},i.onclose=i=>{1003===i.code&&t?(console.info("Received 1003 error, attempting connection with query parameters."),this._legacy_auth=!0,this._attempt_connection_with_query_params(e).then(r).catch(n)):this._handle_disconnected&&this._handle_disconnected(i.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 r=e+(t.length>0?`?${t.join("&")}`:"");return await this._attempt_connection(r,!1)}_establish_connection(){return new Promise(((e,t)=>{this._websocket.onmessage=r=>{const n=r.data,i=JSON.parse(n);if("connection_info"!=i.type){if("error"==i.type){const e="ConnectionAbortedError: "+i.message;return console.error("Failed to connect, "+e),void t(new Error(e))}return console.error("ConnectionAbortedError: Unexpected message received from the server:",n),void t(new Error("ConnectionAbortedError: Unexpected message received from the server"))}this.connection_info=i,this._workspace&&(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(this.connection_info.workspace===this._workspace,`Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`),this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time&&this.token_refresh_interval>this.connection_info.reconnection_token_life_time/1.5&&(console.warn(`Token refresh interval is too long (${this.token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`),this.token_refresh_interval=this.connection_info.reconnection_token_life_time/1.5),this.manager_id=this.connection_info.manager_id||null,console.log(`Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`),this.connection_info.announcement&&console.log(`${this.connection_info.announcement}`),e(this.connection_info)}}))}async open(){console.log("Creating a new websocket connection to",this._server_url.split("?")[0]);try{if(this._websocket=await this._attempt_connection(this._server_url),this._legacy_auth)throw new Error("NotImplementedError: Legacy authentication is not supported");const e=JSON.stringify({client_id:this._client_id,workspace:this._workspace,token:this._token,reconnection_token:this._reconnection_token});return this._websocket.send(e),await(0,_utils__WEBPACK_IMPORTED_MODULE_1__.fm)(this._establish_connection(),this._timeout,"Failed to receive the first message from the server"),this._token_refresh_interval>0&&setTimeout((()=>{this._send_refresh_token(),this._refresh_token_task=setInterval((()=>{this._send_refresh_token()}),1e3*this._token_refresh_interval)}),2e3),this._enable_reconnect=!0,this._closed=!1,this._websocket.onmessage=e=>{if("string"==typeof e.data){const t=JSON.parse(e.data);"reconnection_token"===t.type?(this._reconnection_token=t.reconnection_token,console.log("Reconnection token received")):console.log("Received message from the server:",t)}else this._handle_message(e.data)},this._websocket.onerror=e=>{console.error("WebSocket connection error:",e)},this._websocket.onclose=this._handle_close.bind(this),this._handle_connected&&this._handle_connected(this.connection_info),this.connection_info}catch(e){throw console.error("Failed to connect to",this._server_url.split("?")[0],e),e}}_send_refresh_token(){if(this._websocket&&this._websocket.readyState===WebSocket.OPEN){const e=JSON.stringify({type:"refresh_token"});this._websocket.send(e),console.log("Requested refresh token")}}_handle_close(e){if(!this._closed&&this._websocket&&this._websocket.readyState===WebSocket.CLOSED){if([1e3,1001].includes(e.code))console.info(`Websocket connection closed (code: ${e.code}): ${e.reason}`),this._handle_disconnected&&this._handle_disconnected(e.reason),this._closed=!0;else if(this._enable_reconnect){console.warn("Websocket connection closed unexpectedly (code: %s): %s",e.code,e.reason);let t=0;const r=async()=>{try{console.warn(`Reconnecting to ${this._server_url.split("?")[0]} (attempt #${t})`),await this.open(),await new Promise((e=>setTimeout(e,500))),this._last_message&&(console.info("Resending last message after reconnection"),this._websocket.send(this._last_message),this._last_message=null),console.warn(`Successfully reconnected to server ${this._server_url} (services re-registered)`)}catch(e){if(`${e}`.includes("ConnectionAbortedError:"))return void console.warn("Failed to reconnect, connection aborted:",e);if(`${e}`.includes("NotImplementedError:"))return void console.error(`${e}\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`);if(await new Promise((e=>setTimeout(e,1e3))),this._websocket&&this._websocket.readyState===WebSocket.CONNECTED)return;t+=1,t<MAX_RETRY?await r():console.error("Failed to reconnect after",MAX_RETRY,"attempts")}};r()}}else this._handle_disconnected&&this._handle_disconnected(e.reason)}async emit_message(e){if(this._closed)throw new Error("Connection is closed");this._websocket&&this._websocket.readyState===WebSocket.OPEN||await this.open();try{this._last_message=e,this._websocket.send(e),this._last_message=null}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}disconnect(e){this._closed=!0,this._last_message=null,this._websocket&&this._websocket.readyState!==WebSocket.CLOSED&&this._websocket.readyState!==WebSocket.CLOSING&&this._websocket.close(1e3,e),this._refresh_token_task&&clearInterval(this._refresh_token_task),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",r=e.workspace,n=e.expires_in,i=e.login_timeout||60,s=e.login_callback,o=e.profile,a=await connectToServer({name:"initial login client",server_url:e.server_url});try{const e=await a.getService(t);let c;return(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(e,`Failed to get the login service: ${t}`),c=r?await e.start({workspace:r,expires_in:n,_rkwargs:!0}):await e.start(),s?await s(c):console.log(`Please open your browser and login at ${c.login_url}`),await e.check(c.key,{timeout:i,profile:o,_rkwargs:!0})}catch(e){throw e}finally{await a.disconnect()}}async function webrtcGetService(e,t,r,n){const i=(n=n||{}).webrtc,s=n.webrtc_config;void 0!==n.webrtc&&delete n.webrtc,void 0!==n.webrtc_config&&delete n.webrtc_config,(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)([void 0,!0,!1,"auto"].includes(i),"webrtc must be true, false or 'auto'");const o=await e.getService(r,n);if(!0===i||"auto"===i){if(o.id.includes(":")&&o.id.includes("/"))try{const r=await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.b)(e,t,s),i=await r.getService(o.id.split(":")[1],n);return i._webrtc=!0,i._peer=r,i._service=o,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 o}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__WEBPACK_IMPORTED_MODULE_1__.bq)(),e.client_id=t);let r=normalizeServerUrl(e.server_url),n=new WebsocketRPCConnection(r,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||60,e.WebSocketClass);const i=await n.open();if((0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(i,"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version."),await new Promise((e=>setTimeout(e,100))),!n.manager_id){console.warn("Manager ID not set immediately, waiting...");const e=5e3,t=100,r=Date.now();for(;!n.manager_id&&Date.now()-r<e;)await new Promise((e=>setTimeout(e,t)));if(!n.manager_id)throw console.error("Manager ID still not set after waiting"),new Error("Failed to get manager ID from server");console.info(`Manager ID set after waiting: ${n.manager_id}`)}if(e.workspace&&i.workspace!==e.workspace)throw new Error(`Connected to the wrong workspace: ${i.workspace}, expected: ${e.workspace}`);const s=i.workspace,o=new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.y(n,{client_id:t,workspace:s,default_context:{connection_type:"websocket"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:i.public_base_url,long_message_chunk_size:e.long_message_chunk_size}),a=await o.get_manager_service({timeout:e.method_timeout,case_conversion:"camel",kwargs_expansion:e.kwargs_expansion||!1});if(a.rpc=o,i&&(a.config=Object.assign(a.config,i)),a.export=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(t){t.id="default",t.name=t.name||e.name||t.id,t.description=t.description||e.description,await o.register_service(t,{overwrite:!0})}),{name:"export",description:"Export the api.",parameters:{properties:{api:{description:"The api to export",type:"object"}},required:["api"],type:"object"}}),a.getApp=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(e){return e=e||"*",(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(!e.includes(":"),"clientId should not contain ':'"),e.includes("/")||(e=i.workspace+"/"+e),(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(2===e.split("/").length,"clientId should match pattern workspace/clientId"),await a.getService(`${e}:default`)}),{name:"getApp",description:"Get the app.",parameters:{properties:{clientId:{default:"*",description:"The clientId",type:"string"}},type:"object"}}),a.listApps=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(e){e=e||s,(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(!e.includes(":"),"workspace should not contain ':'"),(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(!e.includes("/"),"workspace should not contain '/'");const t={workspace:e,service_id:"default"};return await a.listServices(t)}),{name:"listApps",description:"List the apps.",parameters:{properties:{workspace:{default:s,description:"The workspace",type:"string"}},type:"object"}}),a.disconnect=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.disconnect.bind(o),{name:"disconnect",description:"Disconnect from the server.",parameters:{type:"object",properties:{},required:[]}}),a.registerCodec=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.register_codec.bind(o),{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),a.emit=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.emit.bind(o),{name:"emit",description:"Emit a message.",parameters:{properties:{data:{description:"The data to emit",type:"object"}},required:["data"],type:"object"}}),a.on=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.on.bind(o),{name:"on",description:"Register a message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),a.off=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.off.bind(o),{name:"off",description:"Remove a message handler.",parameters:{properties:{event:{description:"The event to remove",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),a.once=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.once.bind(o),{name:"once",description:"Register a one-time message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),a.getServiceSchema=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.get_service_schema,{name:"getServiceSchema",description:"Get the service schema.",parameters:{properties:{service:{description:"The service to extract schema",type:"object"}},required:["service"],type:"object"}}),a.registerService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.register_service.bind(o),{name:"registerService",description:"Register a service.",parameters:{properties:{service:{description:"The service to register",type:"object"},force:{default:!1,description:"Force to register the service",type:"boolean"}},required:["service"],type:"object"}}),a.unregisterService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.unregister_service.bind(o),{name:"unregisterService",description:"Unregister a service.",parameters:{properties:{service:{description:"The service id to unregister",type:"string"},notify:{default:!0,description:"Notify the workspace manager",type:"boolean"}},required:["service"],type:"object"}}),n.manager_id&&o.on("force-exit",(async e=>{e.from==="*/"+n.manager_id&&(console.log("Disconnecting from server, reason:",e.reason),await o.disconnect())})),e.webrtc){await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.e)(a,`${t}-rtc`,e.webrtc_config);const r=Object.assign({},a),n=r.getService.__schema__.description,i=r.getService.__schema__.parameters;a.getService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(webrtcGetService.bind(null,r,`${s}/${t}-rtc`),{name:"getService",description:n,parameters:i}),a.getRTCService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.b.bind(null,a),{name:"getRTCService",description:"Get the webrtc connection, returns a peer connection.",parameters:{properties:{config:{description:"The config for the webrtc service",type:"object"}},required:["config"],type:"object"}})}else{const e=a.getService;a.getService=(t,r)=>e(t,r=r||{}),a.getService.__schema__=e.__schema__}return a.registerProbes=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(e){return e.id="probes",e.name="Probes",e.config={visibility:"public"},e.type="probes",e.description=`Probes Service, visit ${r}/${s}services/probes for the available probes.`,await a.registerService(e,{overwrite:!0})}),{name:"registerProbes",description:"Register probes service",parameters:{properties:{probes:{description:"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",type:"object"}},required:["probes"],type:"object"}}),a}async function getRemoteService(e,t={}){const{serverUrl:r,workspace:n,clientId:i,serviceId:s,appId:o}=(0,_utils__WEBPACK_IMPORTED_MODULE_1__.iO)(e),a=`${n}/${i}:${s}@${o}`;if(t.serverUrl&&t.serverUrl!==r)throw new Error("server_url in config does not match the server_url in the url");t.serverUrl=r;const c=await connectToServer(t);return await c.getService(a)}class LocalWebSocket{constructor(e,t,r){this.url=e,this.onopen=()=>{},this.onmessage=()=>{},this.onclose=()=>{},this.onerror=()=>{},this.client_id=t,this.workspace=r;const n="undefined"!=typeof window?window:self,i="undefined"!=typeof window;if(this.postMessage=e=>{i?window.parent.postMessage(e,"*"):self.postMessage(e)},this.readyState=WebSocket.CONNECTING,n.addEventListener("message",(e=>{const{type:t,data:r,to:n}=e.data;if(n===this.client_id)switch(t){case"message":this.readyState===WebSocket.OPEN&&this.onmessage&&this.onmessage({data:r});break;case"connected":this.readyState=WebSocket.OPEN,this.onopen(e);break;case"closed":this.readyState=WebSocket.CLOSED,this.onclose(e)}}),!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:");class FixedLocalWebSocket extends LocalWebSocket{constructor(e){super(e,client_id,workspace)}}connectToServer({server_url,workspace,client_id,token,method_timeout,name,WebSocketClass:FixedLocalWebSocket}).then((async server=>{globalThis.api=server;try{if(isWindow&&enable_execution){function e(e){return new Promise(((t,r)=>{const n=document.createElement("script");n.innerHTML=e.content,n.lang=e.lang,n.onload=()=>t(),n.onerror=e=>r(e),document.head.appendChild(n)}))}if(config.styles&&config.styles.length>0)for(const t of config.styles){const r=document.createElement("style");r.innerHTML=t.content,r.lang=t.lang,document.head.appendChild(r)}if(config.links&&config.links.length>0)for(const n of config.links){const i=document.createElement("a");i.href=n.url,i.innerText=n.text,document.body.appendChild(i)}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){reject(a)}}))}}),!1),isWindow?window.parent.postMessage({type:"hyphaClientReady"},"*"):self.postMessage({type:"hyphaClientReady"})}))}return __webpack_exports__})()));
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__={164:(e,t,r)=>{r.d(t,{m:()=>F,y:()=>J});var n=r(878),i=r(287);function s(e){return"".concat(e<0?"-":"","0x").concat(Math.abs(e).toString(16).padStart(2,"0"))}var o,c=function(e,t){this.type=e,this.data=t},a=(o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},o(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),_=function(e){function t(r){var n=e.call(this,r)||this,i=Object.create(t.prototype);return Object.setPrototypeOf(n,i),Object.defineProperty(n,"name",{configurable:!0,enumerable:!1,value:t.name}),n}return a(t,e),t}(Error),h=4294967295;function l(e,t,r){var n=Math.floor(r/4294967296),i=r;e.setUint32(t,n),e.setUint32(t+4,i)}function d(e,t){return 4294967296*e.getInt32(t)+e.getUint32(t+4)}var p,u,f,y={type:-1,encode:function(e){var t,r,n,i;return e instanceof Date?function(e){var t,r=e.sec,n=e.nsec;if(r>=0&&n>=0&&r<=17179869183){if(0===n&&r<=4294967295){var i=new Uint8Array(4);return(t=new DataView(i.buffer)).setUint32(0,r),i}var s=r/4294967296,o=4294967295&r;return i=new Uint8Array(8),(t=new DataView(i.buffer)).setUint32(0,n<<2|3&s),t.setUint32(4,o),i}return i=new Uint8Array(12),(t=new DataView(i.buffer)).setUint32(0,n),l(t,4,r),i}((n=1e6*((t=e.getTime())-1e3*(r=Math.floor(t/1e3))),{sec:r+(i=Math.floor(n/1e9)),nsec:n-1e9*i})):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 r=t.getUint32(0);return{sec:4294967296*(3&r)+t.getUint32(4),nsec:r>>>2};case 12:return{sec:d(t,4),nsec:t.getUint32(0)};default:throw new _("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},m=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(y)}return e.prototype.register=function(e){var t=e.type,r=e.encode,n=e.decode;if(t>=0)this.encoders[t]=r,this.decoders[t]=n;else{var i=1+t;this.builtInEncoders[i]=r,this.builtInDecoders[i]=n}},e.prototype.tryToEncode=function(e,t){for(var r=0;r<this.builtInEncoders.length;r++)if(null!=(n=this.builtInEncoders[r])&&null!=(i=n(e,t)))return new c(-1-r,i);for(r=0;r<this.encoders.length;r++){var n,i;if(null!=(n=this.encoders[r])&&null!=(i=n(e,t)))return new c(r,i)}return e instanceof c?e:null},e.prototype.decode=function(e,t,r){var n=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return n?n(e,t,r):new c(t,e)},e.defaultCodec=new e,e}(),w=("undefined"==typeof process||"never"!==(null===(p=null===process||void 0===process?void 0:process.env)||void 0===p?void 0:p.TEXT_ENCODING))&&"undefined"!=typeof TextEncoder&&"undefined"!=typeof TextDecoder;function g(e){for(var t=e.length,r=0,n=0;n<t;){var i=e.charCodeAt(n++);if(4294967168&i)if(4294965248&i){if(i>=55296&&i<=56319&&n<t){var s=e.charCodeAt(n);56320==(64512&s)&&(++n,i=((1023&i)<<10)+(1023&s)+65536)}r+=4294901760&i?4:3}else r+=2;else r++}return r}var v=w?new TextEncoder:void 0,b=w?"undefined"!=typeof process&&"force"!==(null===(u=null===process||void 0===process?void 0:process.env)||void 0===u?void 0:u.TEXT_ENCODING)?200:0:h,k=(null==v?void 0:v.encodeInto)?function(e,t,r){v.encodeInto(e,t.subarray(r))}:function(e,t,r){t.set(v.encode(e),r)};function E(e,t,r){for(var n=t,i=n+r,s=[],o="";n<i;){var c=e[n++];if(128&c)if(192==(224&c)){var a=63&e[n++];s.push((31&c)<<6|a)}else if(224==(240&c)){a=63&e[n++];var _=63&e[n++];s.push((31&c)<<12|a<<6|_)}else if(240==(248&c)){var h=(7&c)<<18|(a=63&e[n++])<<12|(_=63&e[n++])<<6|63&e[n++];h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|1023&h),s.push(h)}else s.push(c);else s.push(c);s.length>=4096&&(o+=String.fromCharCode.apply(String,s),s.length=0)}return s.length>0&&(o+=String.fromCharCode.apply(String,s)),o}var A=w?new TextDecoder:null,S=w?"undefined"!=typeof process&&"force"!==(null===(f=null===process||void 0===process?void 0:process.env)||void 0===f?void 0:f.TEXT_DECODER)?200:0:h;function U(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)}var x=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 r=0;r<this.maxKeyLength;r++)this.caches.push([])}return e.prototype.canBeCached=function(e){return e>0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,r){e:for(var n=0,i=this.caches[r-1];n<i.length;n++){for(var s=i[n],o=s.bytes,c=0;c<r;c++)if(o[c]!==e[t+c])continue e;return s.str}return null},e.prototype.store=function(e,t){var r=this.caches[e.length-1],n={bytes:e,str:t};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)},e.prototype.decode=function(e,t,r){var n=this.find(e,t,r);if(null!=n)return this.hit++,n;this.miss++;var i=E(e,t,r),s=Uint8Array.prototype.slice.call(e,t,t+r);return this.store(s,i),i},e}(),j=function(e,t){var r,n,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function c(s){return function(c){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((i=(i=o.trys).length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}},O=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof __values?__values(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){!function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)}(n,i,(t=e[r](t)).done,t.value)}))}}},T=function(e){return this instanceof T?(this.v=e,this):new T(e)},C=new DataView(new ArrayBuffer(0)),D=new Uint8Array(C.buffer),I=function(){try{C.getInt8(0)}catch(e){return e.constructor}throw new Error("never reached")}(),P=new I("Insufficient data"),M=new x,$=function(){function e(e,t,r,n,i,s,o,c){void 0===e&&(e=m.defaultCodec),void 0===t&&(t=void 0),void 0===r&&(r=h),void 0===n&&(n=h),void 0===i&&(i=h),void 0===s&&(s=h),void 0===o&&(o=h),void 0===c&&(c=M),this.extensionCodec=e,this.context=t,this.maxStrLength=r,this.maxBinLength=n,this.maxArrayLength=i,this.maxMapLength=s,this.maxExtLength=o,this.keyDecoder=c,this.totalPos=0,this.pos=0,this.view=C,this.bytes=D,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=U(e),this.view=function(e){if(e instanceof ArrayBuffer)return new DataView(e);var t=U(e);return new DataView(t.buffer,t.byteOffset,t.byteLength)}(this.bytes),this.pos=0},e.prototype.appendBuffer=function(e){if(-1!==this.headByte||this.hasRemaining(1)){var t=this.bytes.subarray(this.pos),r=U(e),n=new Uint8Array(t.length+r.length);n.set(t),n.set(r,t.length),this.setBuffer(n)}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,r=this.pos;return new RangeError("Extra ".concat(t.byteLength-r," 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 j(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,r,n,i,o,c,a,_;return o=this,c=void 0,_=function(){var o,c,a,_,h,l,d,p;return j(this,(function(u){switch(u.label){case 0:o=!1,u.label=1;case 1:u.trys.push([1,6,7,12]),t=O(e),u.label=2;case 2:return[4,t.next()];case 3:if((r=u.sent()).done)return[3,5];if(a=r.value,o)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{c=this.doDecodeSync(),o=!0}catch(e){if(!(e instanceof I))throw e}this.totalPos+=this.pos,u.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return _=u.sent(),n={error:_},[3,12];case 7:return u.trys.push([7,,10,11]),r&&!r.done&&(i=t.return)?[4,i.call(t)]:[3,9];case 8:u.sent(),u.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,c]}throw l=(h=this).headByte,d=h.pos,p=h.totalPos,new RangeError("Insufficient data in parsing ".concat(s(l)," at ").concat(p," (").concat(d," in the current buffer)"))}}))},new((a=void 0)||(a=Promise))((function(e,t){function r(e){try{i(_.next(e))}catch(e){t(e)}}function n(e){try{i(_.throw(e))}catch(e){t(e)}}function i(t){var i;t.done?e(t.value):(i=t.value,i instanceof a?i:new a((function(e){e(i)}))).then(r,n)}i((_=_.apply(o,c||[])).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,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(e){i[e]&&(n[e]=function(t){return new Promise((function(r,n){s.push([e,t,r,n])>1||c(e,t)}))})}function c(e,t){try{(r=i[e](t)).value instanceof T?Promise.resolve(r.value.v).then(a,_):h(s[0][2],r)}catch(e){h(s[0][3],e)}var r}function a(e){c("next",e)}function _(e){c("throw",e)}function h(e,t){e(t),s.shift(),s.length&&c(s[0][0],s[0][1])}}(this,arguments,(function(){var r,n,i,s,o,c,a,_,h;return j(this,(function(l){switch(l.label){case 0:r=t,n=-1,l.label=1;case 1:l.trys.push([1,13,14,19]),i=O(e),l.label=2;case 2:return[4,T(i.next())];case 3:if((s=l.sent()).done)return[3,12];if(o=s.value,t&&0===n)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(n=this.readArraySize(),r=!1,this.complete()),l.label=4;case 4:l.trys.push([4,9,,10]),l.label=5;case 5:return[4,T(this.doDecodeSync())];case 6:return[4,l.sent()];case 7:return l.sent(),0==--n?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((c=l.sent())instanceof I))throw c;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 a=l.sent(),_={error:a},[3,19];case 14:return l.trys.push([14,,17,18]),s&&!s.done&&(h=i.return)?[4,T(h.call(i))]:[3,16];case 15:l.sent(),l.label=16;case 16:return[3,18];case 17:if(_)throw _.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 r=e-160;t=this.decodeUtf8String(r,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)r=this.lookU8(),t=this.decodeUtf8String(r,1);else if(218===e)r=this.lookU16(),t=this.decodeUtf8String(r,2);else if(219===e)r=this.lookU32(),t=this.decodeUtf8String(r,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 _("Unrecognized type byte: ".concat(s(e)));n=this.lookU32(),t=this.decodeExtension(n,4)}this.complete();for(var i=this.stack;i.length>0;){var o=i[i.length-1];if(0===o.type){if(o.array[o.position]=t,o.position++,o.position!==o.size)continue e;i.pop(),t=o.array}else{if(1===o.type){if(void 0,"string"!=(c=typeof t)&&"number"!==c)throw new _("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new _("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}i.pop(),t=o.map}}return t}var c},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 _("Unrecognized array type byte: ".concat(s(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new _("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 _("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 r;if(e>this.maxStrLength)throw new _("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+t+e)throw P;var n,i=this.pos+t;return n=this.stateIsMapKey()&&(null===(r=this.keyDecoder)||void 0===r?void 0:r.canBeCached(e))?this.keyDecoder.decode(this.bytes,i,e):e>S?function(e,t,r){var n=e.subarray(t,t+r);return A.decode(n)}(this.bytes,i,e):E(this.bytes,i,e),this.pos+=t+e,n},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 _("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw P;var r=this.pos+t,n=this.bytes.subarray(r,r+e);return this.pos+=t+e,n},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new _("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var r=this.view.getInt8(this.pos+t),n=this.decodeBinary(e,t+1);return this.extensionCodec.decode(n,r,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,t,r=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,r},e.prototype.readI64=function(){var e=d(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}(),W={};function L(e,t){return void 0===t&&(t=W),new $(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength).decodeMulti(e)}var R=function(){function e(e,t,r,n,i,s,o,c){void 0===e&&(e=m.defaultCodec),void 0===t&&(t=void 0),void 0===r&&(r=100),void 0===n&&(n=2048),void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===o&&(o=!1),void 0===c&&(c=!1),this.extensionCodec=e,this.context=t,this.maxDepth=r,this.initialBufferSize=n,this.sortKeys=i,this.forceFloat32=s,this.ignoreUndefined=o,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),r=new Uint8Array(t),n=new DataView(t);r.set(this.bytes),this.view=n,this.bytes=r},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>b){var t=g(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),k(e,this.bytes,this.pos),this.pos+=t}else t=g(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,r){for(var n=e.length,i=r,s=0;s<n;){var o=e.charCodeAt(s++);if(4294967168&o){if(4294965248&o){if(o>=55296&&o<=56319&&s<n){var c=e.charCodeAt(s);56320==(64512&c)&&(++s,o=((1023&o)<<10)+(1023&c)+65536)}4294901760&o?(t[i++]=o>>18&7|240,t[i++]=o>>12&63|128,t[i++]=o>>6&63|128):(t[i++]=o>>12&15|224,t[i++]=o>>6&63|128)}else t[i++]=o>>6&31|192;t[i++]=63&o|128}else t[i++]=o}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var r=this.extensionCodec.tryToEncode(e,this.context);if(null!=r)this.encodeExtension(r);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 r=U(e);this.writeU8a(r)},e.prototype.encodeArray=function(e,t){var r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else{if(!(r<4294967296))throw new Error("Too large array: ".concat(r));this.writeU8(221),this.writeU32(r)}for(var n=0,i=e;n<i.length;n++){var s=i[n];this.doEncode(s,t+1)}},e.prototype.countWithoutUndefined=function(e,t){for(var r=0,n=0,i=t;n<i.length;n++)void 0!==e[i[n]]&&r++;return r},e.prototype.encodeMap=function(e,t){var r=Object.keys(e);this.sortKeys&&r.sort();var n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else{if(!(n<4294967296))throw new Error("Too large map object: ".concat(n));this.writeU8(223),this.writeU32(n)}for(var i=0,s=r;i<s.length;i++){var o=s[i],c=e[o];this.ignoreUndefined&&void 0===c||(this.encodeString(o),this.doEncode(c,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),function(e,t,r){var n=r/4294967296,i=r;e.setUint32(t,n),e.setUint32(t+4,i)}(this.view,this.pos,e),this.pos+=8},e.prototype.writeI64=function(e){this.ensureBufferSizeToWrite(8),l(this.view,this.pos,e),this.pos+=8},e}(),B={};function q(e,t){return void 0===t&&(t=B),new R(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat).encodeSharedRef(e)}const F=3,z=Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;function K(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 N(e,t){if(!t)throw new Error("undefined index");return"string"==typeof t?N(e,t.split(".")):0===t.length?e:N(e[t[0]],t.slice(1))}function G(e,t=null,r=!1){if(Array.isArray(e))return e.map(((e,t)=>G(e,null,r)));if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=G(e[n],n,r);return t}if("function"==typeof e){if(e.__schema__){const n=JSON.parse(JSON.stringify(e.__schema__));return t&&(n.name=t,e.__schema__.name=t),r&&n.parameters&&n.parameters.properties&&delete n.parameters.properties.context,{type:"function",function:n}}return{type:"function"}}return"number"==typeof e?{type:"number"}:"string"==typeof e?{type:"string"}:"boolean"==typeof e?{type:"boolean"}:null===e?{type:"null"}:{}}class H{constructor(e,t,r,n){this._timeout=e,this._callback=t,this._args=r,this._label=n||"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&&this.started?(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 V extends Object{}class J extends n.sw{constructor(e,{client_id:t=null,default_context:r=null,name:i=null,codecs:s=null,method_timeout:o=null,max_message_buffer_size:c=0,debug:a=!1,workspace:_=null,silent:h=!1,app_id:l=null,server_base_url:d=null,long_message_chunk_size:p=null}){if(super(a),this._codecs=s||{},(0,n.vA)(t&&"string"==typeof t),(0,n.vA)(t,"client_id is required"),this._client_id=t,this._name=i,this._app_id=l||"*",this._local_workspace=_,this._silent=h,this.default_context=r||{},this._method_annotations=new WeakMap,this._max_message_buffer_size=c,this._chunk_store={},this._method_timeout=o||30,this._server_base_url=d,this._long_message_chunk_size=p||262144,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",api_version:F},ping:this._ping.bind(this),get_service:this.get_local_service.bind(this),message_cache:{create:this._create_message.bind(this),append:this._append_message.bind(this),set:this._set_message.bind(this),process:this._process_message.bind(this),remove:this._remove_message.bind(this)}}),this.on("method",this._handle_method.bind(this)),this.on("error",console.error),(0,n.vA)(e.emit_message&&e.on_message),(0,n.vA)(void 0!==e.manager_id,"Connection must have manager_id"),this._emit_message=e.emit_message.bind(e),e.on_message(this._on_message.bind(this)),this._connection=e;const t=async e=>{if(!this._silent&&this._connection.manager_id){console.debug("Connection established, reporting services...");try{const e=await this.get_manager_service({timeout:10,case_conversion:"camel"}),t=Object.values(this._services),r=t.length;let n=0;for(let r of t)try{const t=this._extract_service_info(r);await e.registerService(t),n++}catch(e){console.error(`Failed to register service ${r.id||"unknown"}: ${e}`)}n===r?console.info(`Successfully registered all ${n} services with the server`):console.warn(`Only registered ${n} out of ${r} services with the server`)}catch(e){console.error(`Failed to get manager service for registering services: ${e}`)}}e&&(e.public_base_url&&(this._server_base_url=e.public_base_url),this._fire("connected",e))};e.on_connected(t),t()}else 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,n.vA)("ping"==e),"pong"}async ping(e,t){let r=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:e,_rmethod:"services.built-in.ping",_rpromise:!0,_rdoc:"Ping a remote client"});(0,n.vA)("pong"==await r("ping",t))}_create_message(e,t,r,n){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={}),!r&&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,r,i){if(r){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,n.vA)(t instanceof z),s[e].push(t)}_set_message(e,t,r,i,s){if(i){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const o=this._object_store.message_cache;if(!o[e])throw new Error(`Message with key ${e} does not exists.`);(0,n.vA)(r instanceof z),o[e][t]=r}_remove_message(e,t){const r=this._object_store.message_cache;if(!r[e])throw new Error(`Message with key ${e} does not exists.`);delete r[e]}_process_message(e,t,r){if(t){if(!this._object_store[e])throw new Error(`session does not exist anymore: ${e}`);this._object_store[e].timer.reset()}const i=this._object_store.message_cache;if((0,n.vA)(!!r,"Context is required"),!i[e])throw new Error(`Message with key ${e} does not exists.`);var s,o,c,a;i[e]=(c=(o=(s=i[e]).map((function(e){return e.byteLength}))).reduce((function(e,t){return e+t}),0),a=new Uint8Array(c),o.reduce((function(e,t,r){return a.set(new Uint8Array(s[r]),e),e+t}),0),a.buffer);let _=L(i[e]);const{done:h,value:l}=_.next(),d=l;if(Object.assign(d,{from:r.from,to:r.to,ws:r.ws,user:r.user}),d.ctx=JSON.parse(JSON.stringify(d)),Object.assign(d.ctx,this.default_context),!h){let e=_.next();Object.assign(d,e.value)}this._fire(d.type,d),delete i[e]}_on_message(e){if("string"==typeof e){const t=JSON.parse(e);this._fire(t.type,t)}else if(e instanceof ArrayBuffer){let t=L(e);const{done:r,value:n}=t.next(),i=n;if(i.ctx=JSON.parse(JSON.stringify(i)),Object.assign(i.ctx,this.default_context),!r){let e=t.next();Object.assign(i,e.value)}this._fire(i.type,i)}else{if("object"!=typeof e)throw new Error("Invalid message format");this._fire(e.type,e)}}reset(){this._event_handlers={},this._services={}}async disconnect(){this._fire("disconnected"),await this._connection.disconnect()}async get_manager_service(e){e=e||{};for(let t=0;t<20;t++){if(!this._connection.manager_id){if(t<19){console.warn(`Manager ID not set, retrying in 500ms (attempt ${t+1}/20)`),await new Promise((e=>setTimeout(e,500)));continue}throw new Error("Manager ID not set after maximum retries")}try{return await this.get_remote_service(`*/${this._connection.manager_id}:default`,e)}catch(e){if(!(t<19))throw e;console.warn(`Failed to get manager service, retrying in 500ms: ${e.message}`),await new Promise((e=>setTimeout(e,500)))}}}get_all_local_services(){return this._services}get_local_service(e,t){(0,n.vA)(e);const[r,i]=t.to.split("/");(0,n.vA)(i===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=t.ws,"public"==s.config.visibility)return s;if(t.ws===r)return s;throw new Error(`Permission denied for getting protected service: ${e}, workspace mismatch: ${r} != ${t.ws}`)}async get_remote_service(e,t){let{timeout:r,case_conversion:i,kwargs_expansion:s}=t||{};r=void 0===r?this._method_timeout:r,!e&&this._connection.manager_id?e="*/"+this._connection.manager_id:e.includes(":")||(e=this._client_id+":"+e);const o=e.split(":")[0];let c=e.split(":")[1];if(c.includes("@")){c=c.split("@")[0];const t=e.split("@")[1];this._app_id&&"*"!==this._app_id&&(0,n.vA)(t===this._app_id,`Invalid app id: ${t} != ${this._app_id}`)}(0,n.vA)(o,`Invalid service uri: ${e}`);try{const t=this._generate_remote_method({_rserver:this._server_base_url,_rtarget:o,_rmethod:"services.built-in.get_service",_rpromise:!0,_rdoc:"Get a remote service"});let a=await(0,n.fm)(t(c),r,"Timeout Error: Failed to get remote service: "+e);return a.id=`${o}:${c}`,s&&(a=(0,n.uX)(a)),i?Object.assign(new V,(0,n.gX)(a,i)):Object.assign(new V,a)}catch(t){throw console.warn("Failed to get remote service: "+e,t),t}}_annotate_service_methods(e,t,r,n,i){if("function"==typeof e){let s=t.split(".")[1];this._method_annotations.set(e,{require_context:Array.isArray(r)?r.includes(s):!!r,run_in_executor:n,method_id:"services."+t,visibility:i})}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]=N(this._object_store,o.__rpc_object__._rmethod),o=e[s]}this._annotate_service_methods(o,t+"."+s,r,n,i)}}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={},r=Object.getOwnPropertyNames(e).concat(Object.getOwnPropertyNames(Object.getPrototypeOf(e)));for(let n of r)"constructor"!==n&&("function"==typeof e[n]?t[n]=e[n].bind(e):t[n]=e[n]);e.id=e.id||"default",e=t}(0,n.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 r=!1,i=!1;e.config.require_context&&(r=e.config.require_context),e.config.run_in_executor&&(i=!0);const s=e.config.visibility||"protected";if((0,n.vA)(["protected","public"].includes(s)),this._annotate_service_methods(e,e.id,r,i,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){const t=e.config||{};t.workspace=t.workspace||this._local_workspace||this._connection.workspace;const r=G(e,null,t.require_context);return{config:t,id:`${t.workspace}/${this._client_id}:${e.id}`,name:e.name||e.id,description:e.description||"",type:e.type||"generic",docs:e.docs||null,app_id:this._app_id,service_schema:r}}async get_service_schema(e){return G(e,null,e.config.require_context)}async register_service(e,t){let r,{check_type:n,notify:s,overwrite:o}=t||{};if(s=void 0===s||s,n&&e.type)try{r=await this.get_manager_service({timeout:10,case_conversion:"camel"}),e=function(e,t){function r(e,t,r="root"){for(let n in t)if(!e.hasOwnProperty(n))throw new Error(`Missing key '${n}' in service at path '${r}'`);for(let n in e)if("type"!==n&&!t.hasOwnProperty(n))throw new Error(`Unexpected key '${n}' in service at path '${r}'`)}return r(e,t.definition),function e(t,n,s="root"){if("object"!=typeof t||Array.isArray(t)){if(Array.isArray(t)){if(t.length!==n.length)throw new Error(`Length mismatch at path '${s}'`);t.forEach(((r,o)=>{let c=`${s}[${o}]`;if("object"!=typeof r||Array.isArray(r)){if("function"==typeof r){if(!n.hasOwnProperty(o))throw new Error(`Missing schema for function at index ${o} in path '${c}'`);t[o]=(0,i.G)(r,{name:n[o].name,description:n[o].description||"",parameters:n[o].parameters})}}else e(r,n[o],c)}))}}else{r(t,n,s);for(let r in t){let o=t[r],c=`${s}.${r}`;if("object"!=typeof o||Array.isArray(o)){if("function"==typeof o){if(!n.hasOwnProperty(r))throw new Error(`Missing schema for function '${r}' at path '${c}'`);t[r]=(0,i.G)(o,{name:n[r].name,description:n[r].description||"",parameters:n[r].parameters})}}else e(o,n[r],c)}}}(e,t.definition),e}(e,await r.get_service_type(e.type))}catch(t){throw new Error(`Failed to get service type ${e.type}, error: ${t}`)}const c=this.add_service(e,o),a=this._extract_service_info(c);if(s)try{r=r||await this.get_manager_service({timeout:10,case_conversion:"camel"}),await r.registerService(a)}catch(e){throw new Error(`Failed to notify workspace manager: ${e}`)}return a}async unregister_service(e,t){let r;if(t=void 0===t||t,r="string"==typeof e?e:e.id,(0,n.vA)(r&&"string"==typeof r,`Invalid service id: ${r}`),r.includes(":")&&(r=r.split(":")[1]),r.includes("@")&&(r=r.split("@")[0]),!this._services[r])throw new Error(`Service not found: ${r}`);if(t){const e=await this.get_manager_service({timeout:10,case_conversion:"camel"});await e.unregisterService(r)}delete this._services[r]}_ndarray(e,t,r){const i=(0,n.D4)(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}}_encode_callback(e,t,r,n,i,s,o){let c=`${r}.${e}`,a={_rtype:"method",_rtarget:s?`${s}/${this._client_id}`:this._client_id,_rmethod:c,_rpromise:!1};const _=this;let h=function(){try{t.apply(null,Array.prototype.slice.call(arguments))}catch(e){console.error(`Error in callback(${c}, ${o}): ${e}`)}finally{i&&i.started&&i.clear(),n&&_._object_store[r]&&delete _._object_store[r]}};return h.__name__=`callback(${c})`,[a,h]}async _encode_promise(e,t,r,i,s,o,c){let a=this._get_session_store(r,!0);(0,n.vA)(a,`Failed to create session store ${r} due to invalid parent`);let _={};return s&&t&&this._method_timeout?([_.heartbeat,a.heartbeat]=this._encode_callback("heartbeat",s.reset.bind(s),r,!1,null,o),a.timer=s,_.interval=this._method_timeout/2):s=null,[_.resolve,a.resolve]=this._encode_callback("resolve",e,r,i,s,o,`resolve (${c})`),[_.reject,a.reject]=this._encode_callback("reject",t,r,i,s,o,`reject (${c})`),_}async _send_chunks(e,t,r){const i=await this.get_remote_service(`${t}:built-in`);if(!i.message_cache)throw new Error("Remote client does not support message caching for large messages.");const s=i.message_cache,o=r||(0,n.bq)(),c=e.length,a=Date.now(),_=Math.ceil(c/this._long_message_chunk_size);if(i.config.api_version>=3){await s.create(o,!!r);const t=new n.jf(30),i=[];for(let n=0;n<_;n++){const a=n*this._long_message_chunk_size,h=e.slice(a,a+this._long_message_chunk_size),l=async()=>{await s.set(o,n,h,!!r),console.debug(`Sending chunk ${n+1}/${_} (total=${c} bytes)`)};i.push(t.run(l))}await Promise.all(i)}else{await s.create(o,!!r);for(let t=0;t<_;t++){const n=t*this._long_message_chunk_size,i=e.slice(n,n+this._long_message_chunk_size);await s.append(o,i,!!r),console.debug(`Sending chunk ${t+1}/${_} (total=${c} bytes)`)}}await s.process(o,!!r);const h=((Date.now()-a)/1e3).toFixed(2);console.debug(`All chunks (${c} bytes) sent in ${h} s`)}emit(e,t){if((0,n.vA)("object"==typeof e&&e.type,"Invalid message, must be an object with a `type` fields."),!e.to)return void this._fire(e.type,e);let r=q(e);if(t){const e=q(t);r=new Uint8Array([...r,...e])}const i=r.length;return i>this._long_message_chunk_size+1024&&console.warn(`Sending large message (size=${i})`),this._emit_message(r)}_generate_remote_method(e,t,r,i,s){let o=e._rtarget;i&&!o.includes("/")&&(i!==o&&(o=i+"/"+o),e._rtarget=o);let c=e._rmethod,a=e._rpromise||!1;const _=`method: ${c}, docs: ${e._rdoc}`,h=this;function l(){return new Promise((async(e,i)=>{let d=(0,n.bq)();r&&(d=r+"."+d);let p=h._get_session_store(d,!0);if(!p)return void i(new Error(`Runtime Error: Failed to get session store ${d} (context: ${_})`));p.target_id=o;const u=await h._encode(Array.prototype.slice.call(arguments),d,s),f=u.length,y=f>0&&"object"==typeof u[f-1]&&null!==u[f-1]&&u[f-1]._rkwargs;let m;y&&delete u[f-1]._rkwargs,m=h._local_workspace?h._local_workspace+"/"+h._client_id:h._client_id;let w={type:"method",from:m,to:o,method:c},g={};u&&(g.args=u),y&&(g.with_kwargs=y),t&&(w.parent=t);let v=null;if(a){w.session=d;let t=`${o}:${c}`;v=new H(h._method_timeout,i,[`Method call time out: ${t}, context: ${_}`],t);let r=!0;for(let e of u)if("object"==typeof e&&!0===e._rintf){r=!1;break}const n=await h._encode_promise(e,i,d,r,v,s,_);if(!0===a)g.promise=n;else{if("*"!==a)throw new Error(`Unsupported promise type: ${a}`);g.promise="*",g.t=h._method_timeout/2}}let b=q(w);if(g){const e=q(g);b=new Uint8Array([...b,...e])}b.length<=h._long_message_chunk_size+1024||l.__no_chunk__?h._emit_message(b).then((function(){v&&v.reset()})).catch((function(e){console.error("Failed to send message",e),i(e),v&&v.clear()})):h._send_chunks(b,o,t).then((function(){v&&v.reset()})).catch((function(e){console.error("Failed to send message",e),i(e),v&&v.clear()}))}))}l.__rpc_object__=e;const d=c.split(".");return l.__name__=e._rname||d[d.length-1],l.__name__.includes("#")&&(l.__name__=l.__name__.split("#")[1]),l.__doc__=e._rdoc||`Remote method: ${c}`,l.__schema__=e._rschema,l.__no_chunk__="services.built-in.message_cache.append"===e._rmethod,l}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,n.vA)(e.method&&e.ctx&&e.from);const r=e.from+":"+e.method,i=e.from.split("/")[0],s=e.from.split("/")[1];let o;e.to=e.to.includes("/")?e.to:i+"/"+e.to,e.ctx.to=e.to,this._local_workspace?(this._local_workspace&&"*"!==this._local_workspace&&(0,n.vA)(e.to.split("/")[0]===this._local_workspace,"Workspace mismatch: "+e.to.split("/")[0]+" != "+this._local_workspace),o=this._local_workspace):o=e.to.split("/")[0];const c=e.parent;let a,_,h,l;if(e.promise){const d=await this._decode("*"===e.promise?this._expand_promise(e):e.promise,e.session,c,i,o);if(a=d.resolve,_=d.reject,d.heartbeat&&d.interval){async function p(){try{await d.heartbeat()}catch(e){console.error(e)}}t=setInterval(p,1e3*d.interval)}}try{h=N(this._object_store,e.method)}catch(u){throw new Error(`Method not found: ${r} at ${this._client_id}`)}if((0,n.vA)(h&&"function"==typeof h,"Invalid method: "+r),this._method_annotations.has(h)){if("protected"===this._method_annotations.get(h).visibility&&o!==i&&("*"!==i||s!==this._connection.manager_id))throw new Error("Permission denied for invoking protected method "+r+", workspace mismatch: "+o+" != "+i)}else{let f=this._object_store[e.method.split(".")[0]].target_id;if(o===i&&f&&-1===f.indexOf("/")&&(f=o+"/"+f),f!==e.from)throw new Error("Access denied for method call ("+r+") from "+e.from+" to target "+f)}if(c&&(0,n.vA)(null!==this._get_session_store(c,!0),"Parent session was closed: "+c),l=e.args?await this._decode(e.args,e.session,null,i,null):[],this._method_annotations.has(h)&&this._method_annotations.get(h).require_context){if(l.length+1<h.length)for(let y=l.length;y<h.length-1;y++)l.push(void 0);l.push(e.ctx),(0,n.vA)(l.length===h.length,`Runtime Error: Invalid number of arguments for method ${r}, expected ${h.length} but got ${l.length}`)}if(e.promise){const m=h.apply(null,l);m instanceof Promise?m.then((e=>{a(e),clearInterval(t)})).catch((e=>{_(e),clearInterval(t)})):(a(m),clearInterval(t))}else h.apply(null,l),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 r=this._object_store;const n=e.split(".");if(t){const e=n.length-1;for(let t of n.slice(0,e)){if(!r[t])return null;r=r[t]}return r[n[e]]||(r[n[e]]={}),r[n[e]]}for(let e of n){if(!r[e])return null;r=r[e]}return r}async _encode(e,t,r){const i=typeof e;if("number"===i||"string"===i||"boolean"===i||null==e||e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return{_rtype:"memoryview",_rvalue:new Uint8Array(e)};if(e.__rpc_object__&&(e.__rpc_object__._rserver||this._server_base_url)===this._server_base_url)return e.__rpc_object__;let s;if(e.constructor instanceof Object&&e._rtype){const c=e._rtype;return delete e._rtype,s=await this._encode(e,t,r),s._rtype=c,s}if((0,n.WH)(e)||(0,n.aU)(e)){(0,n.vA)(t&&"string"==typeof t,"Session ID is required for generator encoding");const a=(0,n.bq)(),_=this._get_session_store(t,!0);(0,n.vA)(null!==_,`Failed to create session store ${t} due to invalid parent`);const h=(0,n.aU)(e),l=async()=>{if(h){const t=e,r=await t.next();return r.done?(delete _[a],{_rtype:"stop_iteration"}):r.value}{const t=e.next();return t.done?(delete _[a],{_rtype:"stop_iteration"}):t.value}};return _[a]=l,s={_rtype:"generator",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${a}`,_rpromise:"*",_rdoc:"Remote generator"},s}if("function"==typeof e){if(this._method_annotations.has(e)){let d=this._method_annotations.get(e);s={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:d.method_id,_rpromise:"*",_rname:e.name}}else{let p;(0,n.vA)("string"==typeof t),p=e.__name__?`${(0,n.bq)()}#${e.__name__}`:(0,n.bq)(),s={_rtype:"method",_rserver:this._server_base_url,_rtarget:this._client_id,_rmethod:`${t}.${p}`,_rpromise:"*",_rname:e.name};let u=this._get_session_store(t,!0);(0,n.vA)(null!==u,`Failed to create session store ${t} due to invalid parent`),u[p]=e}if(s._rdoc=e.__doc__,!s._rdoc)try{const f=function(e){const t=e.toString(),r=t.match(/function\s*(\w*)/),n=r&&r[1]||"",i=t.match(/\(([^)]*)\)/);let s="";i&&(s=i[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 c=o&&o[1].trim()||"";o=t.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);const a=o&&o[1].split("\n").map((e=>e.replace(/^\/\/\s*/,"").trim())).join("\n")||"",_=c||a;return n&&s.length>0&&{name:n,sig:s,doc:_}}(e);f&&!s._rdoc&&(s._rdoc=`${f.doc}`)}catch(y){console.error("Failed to extract function docstring:",e)}return s._rschema=e.__schema__,s}const o=Array.isArray(e);for(let m of Object.keys(this._codecs)){const w=this._codecs[m];if(w.encoder&&e instanceof w.type){let g=await Promise.resolve(w.encoder(e));if(g&&!g._rtype&&(g._rtype=w.name),"object"==typeof g){const v=g._rtype;delete g._rtype,g=await this._encode(g,t,r),g._rtype=v}return s=g,s}}if("undefined"!=typeof tf&&tf.Tensor&&e instanceof tf.Tensor){const b=e.dataSync();s={_rtype:"ndarray",_rvalue:new Uint8Array(b.buffer),_rshape:e.shape,_rdtype:e.dtype}}else if("undefined"!=typeof nj&&nj.NdArray&&e instanceof nj.NdArray){const k=(0,n.D4)(e.selection.data);s={_rtype:"ndarray",_rvalue:new Uint8Array(e.selection.data.buffer),_rshape:e.shape,_rdtype:k}}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 E=0;async function A(t){let r;r=t?e.slice(E,E+t):e.slice(E);const n=new Uint8Array(await r.arrayBuffer());return E+=n.byteLength,n}function S(e){E=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(A,t,r),seek:await this._encode(S,t,r)}}else if(e instanceof z){const U=(0,n.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,r)};else if(e instanceof Map)s={_rtype:"orderedmap",_rvalue:await this._encode(Array.from(e),t,r)};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 x=Object.keys(e);for(let j of x)s[j]=await this._encode(e[j],t,r)}}if(!s)throw new Error("Failed to encode object");return s}async decode(e){return await this._decode(e)}async _decode(e,t,r,i,s){if(!e)return e;let o;if(e._rtype)if(this._codecs[e._rtype]&&this._codecs[e._rtype].decoder){const c=e._rtype;delete e._rtype,(e=await this._decode(e,t,r,i,s))._rtype=c,o=await Promise.resolve(this._codecs[e._rtype].decoder(e))}else if("method"===e._rtype)o=this._generate_remote_method(e,t,r,i,s);else if("generator"===e._rtype){const a=this._generate_remote_method(e,t,r,i,s);async function*_(){try{for(;;)try{const e=await a();if(e&&"stop_iteration"===e._rtype)break;yield e}catch(e){throw console.error("Error in generator:",e),e}}catch(e){throw console.error("Error in generator:",e),e}}o=_()}else if("ndarray"===e._rtype)if("undefined"!=typeof nj&&nj.array)Array.isArray(e._rvalue)&&(e._rvalue=e._rvalue.reduce(K)),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(K));const h=n.RR[e._rdtype];o=tf.tensor(new h(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 l=n.RR[e._rdtype];if(!l)throw new Error("unsupported dtype: "+e._rdtype);o=new l(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 d=await this._generate_remote_method(e.read,t,r,i,s),p=await d();o=new Blob([p],{type:e.type,name:e.name})}else{o={};for(let u of Object.keys(e))u.startsWith("_")||(o[u]=await this._decode(e[u],t,r,i,s))}o.__rpc_object__=e}else if("orderedmap"===e._rtype)o=new Map(await this._decode(e._rvalue,t,r,i,s));else if("set"===e._rtype)o=new Set(await this._decode(e._rvalue,t,r,i,s));else{const f=e._rtype;delete e._rtype,o=await this._decode(e,t,r,i,s),o._rtype=f}else if(e.constructor===Object||Array.isArray(e)){const y=Array.isArray(e);o=y?[]:{};for(let m of Object.keys(e))if(y||e.hasOwnProperty(m)){const w=e[m];o[m]=await this._decode(w,t,r,i,s)}}else o=e;if(void 0===o)throw new Error("Failed to decode object");return o}_expand_promise(e){return{heartbeat:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".heartbeat",_rdoc:`heartbeat callback for method: ${e.method}`},resolve:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".resolve",_rdoc:`resolve callback for method: ${e.method}`},reject:{_rtype:"method",_rtarget:e.from.split("/")[1],_rmethod:e.session+".reject",_rdoc:`reject callback for method: ${e.method}`},interval:e.t}}}},878:(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{function randId(){return Math.random().toString(36).substr(2,10)+(new Date).getTime()}function toCamelCase(e){return e.includes("_")?e.replace(/_./g,(e=>e[1].toUpperCase())):e}function toSnakeCase(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase()}function expandKwargs(e){if("object"!=typeof e||null===e)return e;const t=Array.isArray(e)?[]:{};for(const r in e)if(e.hasOwnProperty(r)){const n=e[r];"function"==typeof n?(t[r]=(...e)=>{if(0===e.length)throw new Error(`Function "${r}" expects at least one argument.`);const t=e[e.length-1];let i={};return"object"!=typeof t||null===t||Array.isArray(t)||(i={...t,_rkwarg:!0},e=e.slice(0,-1)),n(...e,i)},t[r].__name__=r,n.__schema__&&(t[r].__schema__={...n.__schema__},t[r].__schema__.name=r)):t[r]=expandKwargs(n)}return t}function convertCase(e,t){if("object"!=typeof e||null===e||!t)return e;const r=Array.isArray(e)?[]:{};for(const n in e)if(e.hasOwnProperty(n)){const i=e[n],s=toCamelCase(n),o=toSnakeCase(n);"camel"===t?(r[s]=convertCase(i,t),"function"==typeof i&&(r[s].__name__=s,i.__schema__&&(r[s].__schema__={...i.__schema__},r[s].__schema__.name=s))):"snake"===t?(r[o]=convertCase(i,t),"function"==typeof i&&(r[o].__name__=o,i.__schema__&&(r[o].__schema__={...i.__schema__},r[o].__schema__.name=o))):(t.includes("camel")&&(r[s]=convertCase(i,"camel")),t.includes("snake")&&(r[o]=convertCase(i,"snake")))}return r}function parseServiceUrl(e){e=e.replace(/\/$/,"");const t=new RegExp("^(https?:\\/\\/[^/]+)\\/([a-z0-9_-]+)\\/services\\/(?:(?<clientId>[a-zA-Z0-9_-]+):)?(?<serviceId>[a-zA-Z0-9_-]+)(?:@(?<appId>[a-zA-Z0-9_-]+))?"),r=e.match(t);if(!r)throw new Error("URL does not match the expected pattern");const n=r[1],i=r[2],s=r.groups?.clientId||"*",o=r.groups?.serviceId;return{serverUrl:n,workspace:i,clientId:s,serviceId:o,appId:r.groups?.appId||"*"}}__webpack_require__.d(__webpack_exports__,{D4:()=>typedArrayToDtype,RR:()=>dtypeToTypedArray,V0:()=>loadRequirements,WH:()=>isGenerator,aU:()=>isAsyncGenerator,bq:()=>randId,fm:()=>waitFor,gX:()=>convertCase,iO:()=>parseServiceUrl,jf:()=>Semaphore,sw:()=>MessageEmitter,uX:()=>expandKwargs,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,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 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,r){let n;return Promise.race([e,new Promise(((e,i)=>n=setTimeout((()=>{i(r||"Timeout Error")}),1e3*t)))]).finally((()=>clearTimeout(n)))}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)}waitFor(e,t){return new Promise(((r,n)=>{const i=e=>{clearTimeout(s),r(e)};this.once(e,i);const s=setTimeout((()=>{this.off(e,i),n(new Error("Timeout"))}),t)}))}}class Semaphore{constructor(e){this.max=e,this.queue=[],this.current=0}async run(e){this.current>=this.max&&await new Promise((e=>this.queue.push(e))),this.current++;try{return await e()}finally{this.current--,this.queue.length>0&&this.queue.shift()()}}}function isGenerator(e){return!!e&&"object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return}function isAsyncGenerator(e){return!!e&&"object"==typeof e&&"function"==typeof e.next&&"function"==typeof e.throw&&"function"==typeof e.return&&Symbol.asyncIterator in Object(e)&&"AsyncGenerator"===e[Symbol.toStringTag]}},287:(e,t,r)=>{r.d(t,{G:()=>i});var n=r(878);function i(e,{schema_type:t="auto",name:r=null,description:i=null,parameters:s=null}){if(!e||"function"!=typeof e)throw Error("func should be a function");return(0,n.vA)("auto"===t,"schema_type should be auto"),(0,n.vA)(r,"name should not be null"),(0,n.vA)(s&&"object"===s.type,"parameters should be an object"),e.__schema__={name:r,description:i,parameters:s||[]},e}},831:(e,t,r)=>{r.d(t,{b:()=>a,e:()=>_});var n=r(164),i=r(878),s=r(287);class o{constructor(e){this._data_channel=e,this._handle_message=null,this._reconnection_token=null,this._handle_disconnected=null,this._handle_connected=()=>{},this.manager_id=null,this._last_message=null,this._data_channel.onopen=async()=>{this._last_message&&(console.info("Resending last message after connection established"),this._data_channel.send(this._last_message),this._last_message=null),this._handle_connected&&this._handle_connected({channel:this._data_channel})},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(){this._handle_disconnected&&this._handle_disconnected("closed"),console.log("websocket closed"),t._data_channel=null}}on_disconnected(e){this._handle_disconnected=e}on_connected(e){this._handle_connected=e}on_message(e){(0,i.vA)(e,"handler is required"),this._handle_message=e}async emit_message(e){(0,i.vA)(this._handle_message,"No handler for message");try{this._last_message=e,this._data_channel.send(e),this._last_message=null}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}async disconnect(e){this._last_message=null,this._data_channel=null,console.info(`data channel connection disconnected (${e})`)}}async function c(e){(0,i.vA)(e.channel,"No channel provided"),(0,i.vA)(e.workspace,"No workspace provided");const t=e.channel,r=e.client_id||(0,i.bq)(),s=new o(t);return e.context=e.context||{},e.context.connection_type="webrtc",e.context.ws=e.workspace,new n.y(s,{client_id:r,default_context:e.context,name:e.name,method_timeout:e.method_timeout||10,workspace:e.workspace,app_id:e.app_id,long_message_chunk_size:e.long_message_chunk_size})}async function a(e,t,r){(r=r||{}).peer_id=r.peer_id||(0,i.bq)();const n=new RTCPeerConnection({iceServers:r.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});return new Promise((async(o,a)=>{try{n.addEventListener("connectionstatechange",(()=>{"failed"===n.connectionState?(n.close(),a(new Error("WebRTC Connection failed"))):"closed"===n.connectionState?a(new Error("WebRTC Connection closed")):console.log("WebRTC Connection state: ",n.connectionState)}),!1),r.on_init&&(await r.on_init(n),delete r.on_init);let _=n.createDataChannel(r.peer_id,{ordered:!0});_.binaryType="arraybuffer";const h=await n.createOffer();await n.setLocalDescription(h);const l=await e.getService(t),d=await l.offer({sdp:n.localDescription.sdp,type:n.localDescription.type});_.onopen=()=>{r.channel=_,r.workspace=d.workspace,setTimeout((async()=>{const e=await c(r);n.rpc=e,n.getService=(0,s.G)((async function(t,...n){return(0,i.vA)(!t.includes(":"),"WebRTC service name should not contain ':'"),(0,i.vA)(!t.includes("/"),"WebRTC service name should not contain '/'"),await e.get_remote_service(r.workspace+"/"+r.peer_id+":"+t,...n)}),{name:"getService",description:"Get a remote service via webrtc",parameters:{type:"object",properties:{service_id:{type:"string",description:"Service ID. This should be a service id in the format: 'workspace/service_id', 'workspace/client_id:service_id' or 'workspace/client_id:service_id@app_id'"},config:{type:"object",description:"Options for the service"}},required:["id"]}}),n.disconnect=(0,s.G)((async function(){await e.disconnect(),n.close()}),{name:"disconnect",description:"Disconnect from the webrtc connection via webrtc",parameters:{type:"object",properties:{}}}),n.registerCodec=(0,s.G)(e.register_codec,{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),o(n)}),500)},_.onclose=()=>a(new Error("Data channel closed")),await n.setRemoteDescription(new RTCSessionDescription({sdp:d.sdp,type:d.type}))}catch(e){a(e)}}))}async function _(e,t,r){const n=(r=r||{visibility:"protected",require_context:!0}).on_init;return delete r.on_init,await e.registerService({id:t,config:r,offer:(t,i)=>async function(e,t,r,n,i){r=r||{};let s=new RTCSessionDescription({sdp:e.sdp,type:e.type}),o=new RTCPeerConnection({iceServers:r.ice_servers||[{urls:["stun:stun.l.google.com:19302"]}],sdpSemantics:"unified-plan"});t&&o.addEventListener("datachannel",(async e=>{const r=e.channel;let n=null;i&&i.user&&(n={user:i.user,ws:i.ws}),(await c({channel:r,client_id:r.label,workspace:t.config.workspace,context:n}))._services=t.rpc._services})),n&&await n(o),await o.setRemoteDescription(s);let a=await o.createAnswer();return await o.setLocalDescription(a),{sdp:o.localDescription.sdp,type:o.localDescription.type,workspace:t.config.workspace}}(t,e,r,n,i)})}}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](r,r.exports,__webpack_require__),r.exports}__webpack_require__.d=(e,t)=>{for(var r in t)__webpack_require__.o(t,r)&&!__webpack_require__.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},__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,LocalWebSocket:()=>LocalWebSocket,RPC:()=>_rpc_js__WEBPACK_IMPORTED_MODULE_0__.y,connectToServer:()=>connectToServer,getRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.b,getRemoteService:()=>getRemoteService,loadRequirements:()=>_utils__WEBPACK_IMPORTED_MODULE_1__.V0,login:()=>login,registerRTCService:()=>_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.e,schemaFunction:()=>_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G,setupLocalClient:()=>setupLocalClient});var _rpc_js__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(164),_utils__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(878),_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(287),_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(831);const MAX_RETRY=1e6;class WebsocketRPCConnection{constructor(e,t,r,n,i=null,s=60,o=null,c=7200){(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(e&&t,"server_url and client_id are required"),this._server_url=e,this._client_id=t,this._workspace=r,this._token=n,this._reconnection_token=i,this._websocket=null,this._handle_message=null,this._handle_connected=null,this._handle_disconnected=null,this._timeout=s,this._WebSocketClass=o||WebSocket,this._closed=!1,this._legacy_auth=null,this.connection_info=null,this._enable_reconnect=!1,this._token_refresh_interval=c,this.manager_id=null,this._refresh_token_task=null,this._last_message=null}on_message(e){(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(e,"handler is required"),this._handle_message=e}on_connected(e){this._handle_connected=e}on_disconnected(e){this._handle_disconnected=e}async _attempt_connection(e,t=!0){return new Promise(((r,n)=>{this._legacy_auth=!1;const i=new this._WebSocketClass(e);i.binaryType="arraybuffer",i.onopen=()=>{console.info("WebSocket connection established"),r(i)},i.onerror=e=>{console.error("WebSocket connection error:",e),n(new Error(`WebSocket connection error: ${e}`))},i.onclose=i=>{1003===i.code&&t?(console.info("Received 1003 error, attempting connection with query parameters."),this._legacy_auth=!0,this._attempt_connection_with_query_params(e).then(r).catch(n)):this._handle_disconnected&&this._handle_disconnected(i.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 r=e+(t.length>0?`?${t.join("&")}`:"");return await this._attempt_connection(r,!1)}_establish_connection(){return new Promise(((e,t)=>{this._websocket.onmessage=r=>{const n=r.data,i=JSON.parse(n);if("connection_info"!=i.type){if("error"==i.type){const e="ConnectionAbortedError: "+i.message;return console.error("Failed to connect, "+e),void t(new Error(e))}return console.error("ConnectionAbortedError: Unexpected message received from the server:",n),void t(new Error("ConnectionAbortedError: Unexpected message received from the server"))}this.connection_info=i,this._workspace&&(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(this.connection_info.workspace===this._workspace,`Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`),this.connection_info.reconnection_token&&(this._reconnection_token=this.connection_info.reconnection_token),this.connection_info.reconnection_token_life_time&&this.token_refresh_interval>this.connection_info.reconnection_token_life_time/1.5&&(console.warn(`Token refresh interval is too long (${this.token_refresh_interval}), setting it to 1.5 times of the token life time(${this.connection_info.reconnection_token_life_time}).`),this.token_refresh_interval=this.connection_info.reconnection_token_life_time/1.5),this.manager_id=this.connection_info.manager_id||null,console.log(`Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`),this.connection_info.announcement&&console.log(`${this.connection_info.announcement}`),e(this.connection_info)}}))}async open(){console.log("Creating a new websocket connection to",this._server_url.split("?")[0]);try{if(this._websocket=await this._attempt_connection(this._server_url),this._legacy_auth)throw new Error("NotImplementedError: Legacy authentication is not supported");const e=JSON.stringify({client_id:this._client_id,workspace:this._workspace,token:this._token,reconnection_token:this._reconnection_token});return this._websocket.send(e),await(0,_utils__WEBPACK_IMPORTED_MODULE_1__.fm)(this._establish_connection(),this._timeout,"Failed to receive the first message from the server"),this._token_refresh_interval>0&&setTimeout((()=>{this._send_refresh_token(),this._refresh_token_task=setInterval((()=>{this._send_refresh_token()}),1e3*this._token_refresh_interval)}),2e3),this._enable_reconnect=!0,this._closed=!1,this._websocket.onmessage=e=>{if("string"==typeof e.data){const t=JSON.parse(e.data);"reconnection_token"===t.type?(this._reconnection_token=t.reconnection_token,console.log("Reconnection token received")):console.log("Received message from the server:",t)}else this._handle_message(e.data)},this._websocket.onerror=e=>{console.error("WebSocket connection error:",e)},this._websocket.onclose=this._handle_close.bind(this),this._handle_connected&&this._handle_connected(this.connection_info),this.connection_info}catch(e){throw console.error("Failed to connect to",this._server_url.split("?")[0],e),e}}_send_refresh_token(){if(this._websocket&&this._websocket.readyState===WebSocket.OPEN){const e=JSON.stringify({type:"refresh_token"});this._websocket.send(e),console.log("Requested refresh token")}}_handle_close(e){if(!this._closed&&this._websocket&&this._websocket.readyState===WebSocket.CLOSED){if([1e3,1001].includes(e.code))console.info(`Websocket connection closed (code: ${e.code}): ${e.reason}`),this._handle_disconnected&&this._handle_disconnected(e.reason),this._closed=!0;else if(this._enable_reconnect){console.warn("Websocket connection closed unexpectedly (code: %s): %s",e.code,e.reason);let t=0;const r=async()=>{try{console.warn(`Reconnecting to ${this._server_url.split("?")[0]} (attempt #${t})`),await this.open(),await new Promise((e=>setTimeout(e,500))),this._last_message&&(console.info("Resending last message after reconnection"),this._websocket.send(this._last_message),this._last_message=null),console.warn(`Successfully reconnected to server ${this._server_url} (services re-registered)`)}catch(e){if(`${e}`.includes("ConnectionAbortedError:"))return void console.warn("Failed to reconnect, connection aborted:",e);if(`${e}`.includes("NotImplementedError:"))return void console.error(`${e}\nIt appears that you are trying to connect to a hypha server that is older than 0.20.0, please upgrade the hypha server or use the websocket client in imjoy-rpc(https://www.npmjs.com/package/imjoy-rpc) instead`);if(await new Promise((e=>setTimeout(e,1e3))),this._websocket&&this._websocket.readyState===WebSocket.CONNECTED)return;t+=1,t<MAX_RETRY?await r():console.error("Failed to reconnect after",MAX_RETRY,"attempts")}};r()}}else this._handle_disconnected&&this._handle_disconnected(e.reason)}async emit_message(e){if(this._closed)throw new Error("Connection is closed");this._websocket&&this._websocket.readyState===WebSocket.OPEN||await this.open();try{this._last_message=e,this._websocket.send(e),this._last_message=null}catch(e){throw console.error(`Failed to send data, error: ${e}`),e}}disconnect(e){this._closed=!0,this._last_message=null,this._websocket&&this._websocket.readyState!==WebSocket.CLOSED&&this._websocket.readyState!==WebSocket.CLOSING&&this._websocket.close(1e3,e),this._refresh_token_task&&clearInterval(this._refresh_token_task),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",r=e.workspace,n=e.expires_in,i=e.login_timeout||60,s=e.login_callback,o=e.profile,c=await connectToServer({name:"initial login client",server_url:e.server_url});try{const e=await c.getService(t);let a;return(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(e,`Failed to get the login service: ${t}`),a=r?await e.start({workspace:r,expires_in:n,_rkwargs:!0}):await e.start(),s?await s(a):console.log(`Please open your browser and login at ${a.login_url}`),await e.check(a.key,{timeout:i,profile:o,_rkwargs:!0})}catch(e){throw e}finally{await c.disconnect()}}async function webrtcGetService(e,t,r,n){const i=(n=n||{}).webrtc,s=n.webrtc_config;void 0!==n.webrtc&&delete n.webrtc,void 0!==n.webrtc_config&&delete n.webrtc_config,(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)([void 0,!0,!1,"auto"].includes(i),"webrtc must be true, false or 'auto'");const o=await e.getService(r,n);if(!0===i||"auto"===i){if(o.id.includes(":")&&o.id.includes("/"))try{const r=await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.b)(e,t,s),i=await r.getService(o.id.split(":")[1],n);return i._webrtc=!0,i._peer=r,i._service=o,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 o}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__WEBPACK_IMPORTED_MODULE_1__.bq)(),e.client_id=t);let r=normalizeServerUrl(e.server_url),n=new WebsocketRPCConnection(r,t,e.workspace,e.token,e.reconnection_token,e.method_timeout||60,e.WebSocketClass);const i=await n.open();if((0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(i,"Failed to connect to the server, no connection info obtained. This issue is most likely due to an outdated Hypha server version. Please use `imjoy-rpc` for compatibility, or upgrade the Hypha server to the latest version."),await new Promise((e=>setTimeout(e,100))),!n.manager_id){console.warn("Manager ID not set immediately, waiting...");const e=5e3,t=100,r=Date.now();for(;!n.manager_id&&Date.now()-r<e;)await new Promise((e=>setTimeout(e,t)));if(!n.manager_id)throw console.error("Manager ID still not set after waiting"),new Error("Failed to get manager ID from server");console.info(`Manager ID set after waiting: ${n.manager_id}`)}if(e.workspace&&i.workspace!==e.workspace)throw new Error(`Connected to the wrong workspace: ${i.workspace}, expected: ${e.workspace}`);const s=i.workspace,o=new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.y(n,{client_id:t,workspace:s,default_context:{connection_type:"websocket"},name:e.name,method_timeout:e.method_timeout,app_id:e.app_id,server_base_url:i.public_base_url,long_message_chunk_size:e.long_message_chunk_size}),c=await o.get_manager_service({timeout:e.method_timeout,case_conversion:"camel",kwargs_expansion:e.kwargs_expansion||!1});if(c.rpc=o,i&&(c.config=Object.assign(c.config,i)),c.export=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(t){t.id="default",t.name=t.name||e.name||t.id,t.description=t.description||e.description,await o.register_service(t,{overwrite:!0})}),{name:"export",description:"Export the api.",parameters:{properties:{api:{description:"The api to export",type:"object"}},required:["api"],type:"object"}}),c.getApp=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(e){return e=e||"*",(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(!e.includes(":"),"clientId should not contain ':'"),e.includes("/")||(e=i.workspace+"/"+e),(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(2===e.split("/").length,"clientId should match pattern workspace/clientId"),await c.getService(`${e}:default`)}),{name:"getApp",description:"Get the app.",parameters:{properties:{clientId:{default:"*",description:"The clientId",type:"string"}},type:"object"}}),c.listApps=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(e){e=e||s,(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(!e.includes(":"),"workspace should not contain ':'"),(0,_utils__WEBPACK_IMPORTED_MODULE_1__.vA)(!e.includes("/"),"workspace should not contain '/'");const t={workspace:e,service_id:"default"};return await c.listServices(t)}),{name:"listApps",description:"List the apps.",parameters:{properties:{workspace:{default:s,description:"The workspace",type:"string"}},type:"object"}}),c.disconnect=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.disconnect.bind(o),{name:"disconnect",description:"Disconnect from the server.",parameters:{type:"object",properties:{},required:[]}}),c.registerCodec=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.register_codec.bind(o),{name:"registerCodec",description:"Register a codec for the webrtc connection",parameters:{type:"object",properties:{codec:{type:"object",description:"Codec to register",properties:{name:{type:"string"},type:{},encoder:{type:"function"},decoder:{type:"function"}}}}}}),c.emit=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.emit.bind(o),{name:"emit",description:"Emit a message.",parameters:{properties:{data:{description:"The data to emit",type:"object"}},required:["data"],type:"object"}}),c.on=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.on.bind(o),{name:"on",description:"Register a message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.off=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.off.bind(o),{name:"off",description:"Remove a message handler.",parameters:{properties:{event:{description:"The event to remove",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.once=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.once.bind(o),{name:"once",description:"Register a one-time message handler.",parameters:{properties:{event:{description:"The event to listen to",type:"string"},handler:{description:"The handler function",type:"function"}},required:["event","handler"],type:"object"}}),c.getServiceSchema=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.get_service_schema,{name:"getServiceSchema",description:"Get the service schema.",parameters:{properties:{service:{description:"The service to extract schema",type:"object"}},required:["service"],type:"object"}}),c.registerService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.register_service.bind(o),{name:"registerService",description:"Register a service.",parameters:{properties:{service:{description:"The service to register",type:"object"},force:{default:!1,description:"Force to register the service",type:"boolean"}},required:["service"],type:"object"}}),c.unregisterService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(o.unregister_service.bind(o),{name:"unregisterService",description:"Unregister a service.",parameters:{properties:{service:{description:"The service id to unregister",type:"string"},notify:{default:!0,description:"Notify the workspace manager",type:"boolean"}},required:["service"],type:"object"}}),n.manager_id&&o.on("force-exit",(async e=>{e.from==="*/"+n.manager_id&&(console.log("Disconnecting from server, reason:",e.reason),await o.disconnect())})),e.webrtc){await(0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.e)(c,`${t}-rtc`,e.webrtc_config);const r=Object.assign({},c),n=r.getService.__schema__.description,i=r.getService.__schema__.parameters;c.getService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(webrtcGetService.bind(null,r,`${s}/${t}-rtc`),{name:"getService",description:n,parameters:i}),c.getRTCService=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.b.bind(null,c),{name:"getRTCService",description:"Get the webrtc connection, returns a peer connection.",parameters:{properties:{config:{description:"The config for the webrtc service",type:"object"}},required:["config"],type:"object"}})}else{const e=c.getService;c.getService=(t,r)=>e(t,r=r||{}),c.getService.__schema__=e.__schema__}return c.registerProbes=(0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.G)((async function(e){return e.id="probes",e.name="Probes",e.config={visibility:"public"},e.type="probes",e.description=`Probes Service, visit ${r}/${s}services/probes for the available probes.`,await c.registerService(e,{overwrite:!0})}),{name:"registerProbes",description:"Register probes service",parameters:{properties:{probes:{description:"The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",type:"object"}},required:["probes"],type:"object"}}),c}async function getRemoteService(e,t={}){const{serverUrl:r,workspace:n,clientId:i,serviceId:s,appId:o}=(0,_utils__WEBPACK_IMPORTED_MODULE_1__.iO)(e),c=`${n}/${i}:${s}@${o}`;if(t.serverUrl&&t.serverUrl!==r)throw new Error("server_url in config does not match the server_url in the url");t.serverUrl=r;const a=await connectToServer(t);return await a.getService(c)}class LocalWebSocket{constructor(e,t,r){this.url=e,this.onopen=()=>{},this.onmessage=()=>{},this.onclose=()=>{},this.onerror=()=>{},this.client_id=t,this.workspace=r;const n="undefined"!=typeof window?window:self,i="undefined"!=typeof window;if(this.postMessage=e=>{i?window.parent.postMessage(e,"*"):self.postMessage(e)},this.readyState=WebSocket.CONNECTING,n.addEventListener("message",(e=>{const{type:t,data:r,to:n}=e.data;if(n===this.client_id)switch(t){case"message":this.readyState===WebSocket.OPEN&&this.onmessage&&this.onmessage({data:r});break;case"connected":this.readyState=WebSocket.OPEN,this.onopen(e);break;case"closed":this.readyState=WebSocket.CLOSED,this.onclose(e)}}),!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:");class FixedLocalWebSocket extends LocalWebSocket{constructor(e){super(e,client_id,workspace)}}connectToServer({server_url,workspace,client_id,token,method_timeout,name,WebSocketClass:FixedLocalWebSocket}).then((async server=>{globalThis.api=server;try{if(isWindow&&enable_execution){function e(e){return new Promise(((t,r)=>{const n=document.createElement("script");n.innerHTML=e.content,n.lang=e.lang,n.onload=()=>t(),n.onerror=e=>r(e),document.head.appendChild(n)}))}if(config.styles&&config.styles.length>0)for(const t of config.styles){const r=document.createElement("style");r.innerHTML=t.content,r.lang=t.lang,document.head.appendChild(r)}if(config.links&&config.links.length>0)for(const n of config.links){const i=document.createElement("a");i.href=n.url,i.innerText=n.text,document.body.appendChild(i)}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(c){reject(c)}}))}}),!1),isWindow?window.parent.postMessage({type:"hyphaClientReady"},"*"):self.postMessage({type:"hyphaClientReady"})}))}return __webpack_exports__})()));
2
2
  //# sourceMappingURL=hypha-rpc-websocket.min.js.map