hypha-rpc 0.20.91 → 0.20.92

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.
@@ -405,7 +405,9 @@ class HTTPStreamingRPCConnection {
405
405
 
406
406
  if (!response.ok) {
407
407
  const error_text = await response.text();
408
- throw new Error(`POST failed with status ${response.status}: ${error_text}`);
408
+ throw new Error(
409
+ `POST failed with status ${response.status}: ${error_text}`,
410
+ );
409
411
  }
410
412
 
411
413
  return true;
@@ -4599,1432 +4601,203 @@ async function registerRTCService(server, service_id, config) {
4599
4601
 
4600
4602
  /***/ }),
4601
4603
 
4602
- /***/ "./src/websocket-client.js":
4603
- /*!*********************************!*\
4604
- !*** ./src/websocket-client.js ***!
4605
- \*********************************/
4606
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
4604
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
4605
+ /*!*************************************************************************!*\
4606
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs ***!
4607
+ \*************************************************************************/
4608
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
4607
4609
 
4608
4610
  __webpack_require__.r(__webpack_exports__);
4609
4611
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
4610
- /* harmony export */ API_VERSION: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION),
4611
- /* harmony export */ LocalWebSocket: () => (/* binding */ LocalWebSocket),
4612
- /* harmony export */ RPC: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC),
4613
- /* harmony export */ _connectToServer: () => (/* binding */ connectToServer),
4614
- /* harmony export */ connectToServer: () => (/* binding */ connectToServer),
4615
- /* harmony export */ getRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService),
4616
- /* harmony export */ getRemoteService: () => (/* binding */ getRemoteService),
4617
- /* harmony export */ loadRequirements: () => (/* reexport safe */ _utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements),
4618
- /* harmony export */ login: () => (/* binding */ login),
4619
- /* harmony export */ logout: () => (/* binding */ logout),
4620
- /* harmony export */ registerRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService),
4621
- /* harmony export */ schemaFunction: () => (/* reexport safe */ _utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction),
4622
- /* harmony export */ setupLocalClient: () => (/* binding */ setupLocalClient)
4612
+ /* harmony export */ CachedKeyDecoder: () => (/* binding */ CachedKeyDecoder)
4623
4613
  /* harmony export */ });
4624
- /* harmony import */ var _rpc_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./rpc.js */ "./src/rpc.js");
4625
- /* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/index.js */ "./src/utils/index.js");
4626
- /* harmony import */ var _utils_schema_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/schema.js */ "./src/utils/schema.js");
4627
- /* harmony import */ var _webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webrtc-client.js */ "./src/webrtc-client.js");
4614
+ /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
4628
4615
 
4616
+ var DEFAULT_MAX_KEY_LENGTH = 16;
4617
+ var DEFAULT_MAX_LENGTH_PER_KEY = 16;
4618
+ var CachedKeyDecoder = /** @class */ (function () {
4619
+ function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
4620
+ if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
4621
+ if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
4622
+ this.maxKeyLength = maxKeyLength;
4623
+ this.maxLengthPerKey = maxLengthPerKey;
4624
+ this.hit = 0;
4625
+ this.miss = 0;
4626
+ // avoid `new Array(N)`, which makes a sparse array,
4627
+ // because a sparse array is typically slower than a non-sparse array.
4628
+ this.caches = [];
4629
+ for (var i = 0; i < this.maxKeyLength; i++) {
4630
+ this.caches.push([]);
4631
+ }
4632
+ }
4633
+ CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
4634
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
4635
+ };
4636
+ CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {
4637
+ var records = this.caches[byteLength - 1];
4638
+ FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
4639
+ var record = records_1[_i];
4640
+ var recordBytes = record.bytes;
4641
+ for (var j = 0; j < byteLength; j++) {
4642
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
4643
+ continue FIND_CHUNK;
4644
+ }
4645
+ }
4646
+ return record.str;
4647
+ }
4648
+ return null;
4649
+ };
4650
+ CachedKeyDecoder.prototype.store = function (bytes, value) {
4651
+ var records = this.caches[bytes.length - 1];
4652
+ var record = { bytes: bytes, str: value };
4653
+ if (records.length >= this.maxLengthPerKey) {
4654
+ // `records` are full!
4655
+ // Set `record` to an arbitrary position.
4656
+ records[(Math.random() * records.length) | 0] = record;
4657
+ }
4658
+ else {
4659
+ records.push(record);
4660
+ }
4661
+ };
4662
+ CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
4663
+ var cachedValue = this.find(bytes, inputOffset, byteLength);
4664
+ if (cachedValue != null) {
4665
+ this.hit++;
4666
+ return cachedValue;
4667
+ }
4668
+ this.miss++;
4669
+ var str = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_0__.utf8DecodeJs)(bytes, inputOffset, byteLength);
4670
+ // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
4671
+ var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
4672
+ this.store(slicedCopyOfBytes, str);
4673
+ return str;
4674
+ };
4675
+ return CachedKeyDecoder;
4676
+ }());
4629
4677
 
4678
+ //# sourceMappingURL=CachedKeyDecoder.mjs.map
4630
4679
 
4680
+ /***/ }),
4631
4681
 
4682
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
4683
+ /*!********************************************************************!*\
4684
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs ***!
4685
+ \********************************************************************/
4686
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
4632
4687
 
4688
+ __webpack_require__.r(__webpack_exports__);
4689
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
4690
+ /* harmony export */ DecodeError: () => (/* binding */ DecodeError)
4691
+ /* harmony export */ });
4692
+ var __extends = (undefined && undefined.__extends) || (function () {
4693
+ var extendStatics = function (d, b) {
4694
+ extendStatics = Object.setPrototypeOf ||
4695
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
4696
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
4697
+ return extendStatics(d, b);
4698
+ };
4699
+ return function (d, b) {
4700
+ if (typeof b !== "function" && b !== null)
4701
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
4702
+ extendStatics(d, b);
4703
+ function __() { this.constructor = d; }
4704
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4705
+ };
4706
+ })();
4707
+ var DecodeError = /** @class */ (function (_super) {
4708
+ __extends(DecodeError, _super);
4709
+ function DecodeError(message) {
4710
+ var _this = _super.call(this, message) || this;
4711
+ // fix the prototype chain in a cross-platform way
4712
+ var proto = Object.create(DecodeError.prototype);
4713
+ Object.setPrototypeOf(_this, proto);
4714
+ Object.defineProperty(_this, "name", {
4715
+ configurable: true,
4716
+ enumerable: false,
4717
+ value: DecodeError.name,
4718
+ });
4719
+ return _this;
4720
+ }
4721
+ return DecodeError;
4722
+ }(Error));
4633
4723
 
4724
+ //# sourceMappingURL=DecodeError.mjs.map
4634
4725
 
4726
+ /***/ }),
4635
4727
 
4728
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs":
4729
+ /*!****************************************************************!*\
4730
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs ***!
4731
+ \****************************************************************/
4732
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
4636
4733
 
4637
- const MAX_RETRY = 1000000;
4638
-
4639
- class WebsocketRPCConnection {
4640
- constructor(
4641
- server_url,
4642
- client_id,
4643
- workspace,
4644
- token,
4645
- reconnection_token = null,
4646
- timeout = 60,
4647
- WebSocketClass = null,
4648
- token_refresh_interval = 2 * 60 * 60,
4649
- additional_headers = null,
4650
- ) {
4651
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(server_url && client_id, "server_url and client_id are required");
4652
- this._server_url = server_url;
4653
- this._client_id = client_id;
4654
- this._workspace = workspace;
4655
- this._token = token;
4656
- this._reconnection_token = reconnection_token;
4657
- this._websocket = null;
4658
- this._handle_message = null;
4659
- this._handle_connected = null; // Connection open event handler
4660
- this._handle_disconnected = null; // Disconnection event handler
4661
- this._timeout = timeout;
4662
- this._WebSocketClass = WebSocketClass || WebSocket; // Allow overriding the WebSocket class
4663
- this._closed = false;
4664
- this._legacy_auth = null;
4665
- this.connection_info = null;
4666
- this._enable_reconnect = false;
4667
- this._token_refresh_interval = token_refresh_interval;
4668
- this.manager_id = null;
4669
- this._refresh_token_task = null;
4670
- this._last_message = null; // Store the last sent message
4671
- this._reconnect_timeouts = new Set(); // Track reconnection timeouts
4672
- this._additional_headers = additional_headers;
4673
- }
4674
-
4675
- /**
4676
- * Centralized cleanup method to clear all timers and prevent resource leaks
4677
- */
4678
- _cleanup() {
4679
- // Clear token refresh interval
4680
- if (this._refresh_token_task) {
4681
- clearInterval(this._refresh_token_task);
4682
- this._refresh_token_task = null;
4683
- }
4684
-
4685
- // Clear all reconnection timeouts
4686
- for (const timeoutId of this._reconnect_timeouts) {
4687
- clearTimeout(timeoutId);
4688
- }
4689
- this._reconnect_timeouts.clear();
4690
- }
4691
-
4692
- on_message(handler) {
4693
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(handler, "handler is required");
4694
- this._handle_message = handler;
4695
- }
4696
-
4697
- on_connected(handler) {
4698
- this._handle_connected = handler;
4699
- }
4700
-
4701
- on_disconnected(handler) {
4702
- this._handle_disconnected = handler;
4703
- }
4704
-
4705
- async _attempt_connection(server_url, attempt_fallback = true) {
4706
- return new Promise((resolve, reject) => {
4707
- this._legacy_auth = false;
4708
- const websocket = new this._WebSocketClass(server_url);
4709
- websocket.binaryType = "arraybuffer";
4710
-
4711
- websocket.onopen = () => {
4712
- console.info("WebSocket connection established");
4713
- resolve(websocket);
4714
- };
4715
-
4716
- websocket.onerror = (event) => {
4717
- console.error("WebSocket connection error:", event);
4718
- reject(new Error(`WebSocket connection error: ${event}`));
4719
- };
4720
-
4721
- websocket.onclose = (event) => {
4722
- if (event.code === 1003 && attempt_fallback) {
4723
- console.info(
4724
- "Received 1003 error, attempting connection with query parameters.",
4725
- );
4726
- this._legacy_auth = true;
4727
- this._attempt_connection_with_query_params(server_url)
4728
- .then(resolve)
4729
- .catch(reject);
4730
- } else if (this._handle_disconnected) {
4731
- this._handle_disconnected(event.reason);
4732
- }
4733
- };
4734
- });
4735
- }
4736
-
4737
- async _attempt_connection_with_query_params(server_url) {
4738
- // Initialize an array to hold parts of the query string
4739
- const queryParamsParts = [];
4740
-
4741
- // Conditionally add each parameter if it has a non-empty value
4742
- if (this._client_id)
4743
- queryParamsParts.push(`client_id=${encodeURIComponent(this._client_id)}`);
4744
- if (this._workspace)
4745
- queryParamsParts.push(`workspace=${encodeURIComponent(this._workspace)}`);
4746
- if (this._token)
4747
- queryParamsParts.push(`token=${encodeURIComponent(this._token)}`);
4748
- if (this._reconnection_token)
4749
- queryParamsParts.push(
4750
- `reconnection_token=${encodeURIComponent(this._reconnection_token)}`,
4751
- );
4752
-
4753
- // Join the parts with '&' to form the final query string, prepend '?' if there are any parameters
4754
- const queryString =
4755
- queryParamsParts.length > 0 ? `?${queryParamsParts.join("&")}` : "";
4756
-
4757
- // Construct the full URL by appending the query string if it exists
4758
- const full_url = server_url + queryString;
4759
-
4760
- return await this._attempt_connection(full_url, false);
4761
- }
4762
-
4763
- _establish_connection() {
4764
- return new Promise((resolve, reject) => {
4765
- this._websocket.onmessage = (event) => {
4766
- const data = event.data;
4767
- const first_message = JSON.parse(data);
4768
- if (first_message.type == "connection_info") {
4769
- this.connection_info = first_message;
4770
- if (this._workspace) {
4771
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
4772
- this.connection_info.workspace === this._workspace,
4773
- `Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`,
4774
- );
4775
- }
4776
- if (this.connection_info.reconnection_token) {
4777
- this._reconnection_token = this.connection_info.reconnection_token;
4778
- }
4779
- if (this.connection_info.reconnection_token_life_time) {
4780
- // make sure the token refresh interval is less than the token life time
4781
- if (
4782
- this.token_refresh_interval >
4783
- this.connection_info.reconnection_token_life_time / 1.5
4784
- ) {
4785
- console.warn(
4786
- `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}).`,
4787
- );
4788
- this.token_refresh_interval =
4789
- this.connection_info.reconnection_token_life_time / 1.5;
4790
- }
4791
- }
4792
- this.manager_id = this.connection_info.manager_id || null;
4793
- console.log(
4794
- `Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`,
4795
- );
4796
- if (this.connection_info.announcement) {
4797
- console.log(`${this.connection_info.announcement}`);
4798
- }
4799
- resolve(this.connection_info);
4800
- } else if (first_message.type == "error") {
4801
- const error = "ConnectionAbortedError: " + first_message.message;
4802
- console.error("Failed to connect, " + error);
4803
- reject(new Error(error));
4804
- return;
4805
- } else {
4806
- console.error(
4807
- "ConnectionAbortedError: Unexpected message received from the server:",
4808
- data,
4809
- );
4810
- reject(
4811
- new Error(
4812
- "ConnectionAbortedError: Unexpected message received from the server",
4813
- ),
4814
- );
4815
- return;
4816
- }
4817
- };
4818
- });
4819
- }
4820
-
4821
- async open() {
4822
- console.log(
4823
- "Creating a new websocket connection to",
4824
- this._server_url.split("?")[0],
4825
- );
4826
- try {
4827
- this._websocket = await this._attempt_connection(this._server_url);
4828
- if (this._legacy_auth) {
4829
- throw new Error(
4830
- "NotImplementedError: Legacy authentication is not supported",
4831
- );
4832
- }
4833
- // Send authentication info as the first message if connected without query params
4834
- const authInfo = JSON.stringify({
4835
- client_id: this._client_id,
4836
- workspace: this._workspace,
4837
- token: this._token,
4838
- reconnection_token: this._reconnection_token,
4839
- });
4840
- this._websocket.send(authInfo);
4841
- // Wait for the first message from the server
4842
- await (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.waitFor)(
4843
- this._establish_connection(),
4844
- this._timeout,
4845
- "Failed to receive the first message from the server",
4846
- );
4847
- if (this._token_refresh_interval > 0) {
4848
- setTimeout(() => {
4849
- this._send_refresh_token();
4850
- this._refresh_token_task = setInterval(() => {
4851
- this._send_refresh_token();
4852
- }, this._token_refresh_interval * 1000);
4853
- }, 2000);
4854
- }
4855
- // Listen to messages from the server
4856
- this._enable_reconnect = true;
4857
- this._closed = false;
4858
- this._websocket.onmessage = (event) => {
4859
- if (typeof event.data === "string") {
4860
- const parsedData = JSON.parse(event.data);
4861
- // Check if the message is a reconnection token
4862
- if (parsedData.type === "reconnection_token") {
4863
- this._reconnection_token = parsedData.reconnection_token;
4864
- // console.log("Reconnection token received");
4865
- } else {
4866
- console.log("Received message from the server:", parsedData);
4867
- }
4868
- } else {
4869
- this._handle_message(event.data);
4870
- }
4871
- };
4872
-
4873
- this._websocket.onerror = (event) => {
4874
- console.error("WebSocket connection error:", event);
4875
- // Clean up timers on error
4876
- this._cleanup();
4877
- };
4878
-
4879
- this._websocket.onclose = this._handle_close.bind(this);
4880
-
4881
- if (this._handle_connected) {
4882
- this._handle_connected(this.connection_info);
4883
- }
4884
- return this.connection_info;
4885
- } catch (error) {
4886
- // Clean up any timers that might have been set up before the error
4887
- this._cleanup();
4888
- console.error(
4889
- "Failed to connect to",
4890
- this._server_url.split("?")[0],
4891
- error,
4892
- );
4893
- throw error;
4894
- }
4895
- }
4896
-
4897
- _send_refresh_token() {
4898
- if (this._websocket && this._websocket.readyState === WebSocket.OPEN) {
4899
- const refreshMessage = JSON.stringify({ type: "refresh_token" });
4900
- this._websocket.send(refreshMessage);
4901
- // console.log("Requested refresh token");
4902
- }
4903
- }
4904
-
4905
- _handle_close(event) {
4906
- if (
4907
- !this._closed &&
4908
- this._websocket &&
4909
- this._websocket.readyState === WebSocket.CLOSED
4910
- ) {
4911
- // Clean up timers when connection closes
4912
- this._cleanup();
4913
-
4914
- // Even if it's a graceful closure (codes 1000, 1001), if it wasn't user-initiated,
4915
- // we should attempt to reconnect (e.g., server restart, k8s upgrade)
4916
- if (this._enable_reconnect) {
4917
- if ([1000, 1001].includes(event.code)) {
4918
- console.warn(
4919
- `Websocket connection closed gracefully by server (code: ${event.code}): ${event.reason} - attempting reconnect`,
4920
- );
4921
- } else {
4922
- console.warn(
4923
- "Websocket connection closed unexpectedly (code: %s): %s",
4924
- event.code,
4925
- event.reason,
4926
- );
4927
- }
4928
-
4929
- let retry = 0;
4930
- const baseDelay = 1000; // Start with 1 second
4931
- const maxDelay = 60000; // Maximum delay of 60 seconds
4932
- const maxJitter = 0.1; // Maximum jitter factor
4933
-
4934
- const reconnect = async () => {
4935
- // Check if we were explicitly closed
4936
- if (this._closed) {
4937
- console.info("Connection was closed, stopping reconnection");
4938
- return;
4939
- }
4940
-
4941
- try {
4942
- console.warn(
4943
- `Reconnecting to ${this._server_url.split("?")[0]} (attempt #${retry})`,
4944
- );
4945
- // Open the connection, this will trigger the on_connected callback
4946
- await this.open();
4947
-
4948
- // Wait a short time for services to be registered
4949
- // This gives time for the on_connected callback to complete
4950
- // which includes re-registering all services to the server
4951
- await new Promise((resolve) => setTimeout(resolve, 500));
4952
-
4953
- // Resend last message if there was one
4954
- if (this._last_message) {
4955
- console.info("Resending last message after reconnection");
4956
- this._websocket.send(this._last_message);
4957
- this._last_message = null;
4958
- }
4959
- console.warn(
4960
- `Successfully reconnected to server ${this._server_url} (services re-registered)`,
4961
- );
4962
- // Emit reconnection success event
4963
- if (this._handle_connected) {
4964
- this._handle_connected(this.connection_info);
4965
- }
4966
- } catch (e) {
4967
- if (`${e}`.includes("ConnectionAbortedError:")) {
4968
- console.warn("Server refused to reconnect:", e);
4969
- // Mark as closed and notify the application
4970
- this._closed = true;
4971
- if (this._handle_disconnected) {
4972
- this._handle_disconnected(`Server refused reconnection: ${e}`);
4973
- }
4974
- return;
4975
- } else if (`${e}`.includes("NotImplementedError:")) {
4976
- console.error(
4977
- `${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`,
4978
- );
4979
- // Mark as closed to prevent further reconnection attempts
4980
- this._closed = true;
4981
- if (this._handle_disconnected) {
4982
- this._handle_disconnected(`Server too old: ${e}`);
4983
- }
4984
- return;
4985
- }
4986
-
4987
- // Log specific error types for better debugging
4988
- if (e.name === "NetworkError" || e.message.includes("network")) {
4989
- console.error(`Network error during reconnection: ${e.message}`);
4990
- } else if (
4991
- e.name === "TimeoutError" ||
4992
- e.message.includes("timeout")
4993
- ) {
4994
- console.error(
4995
- `Connection timeout during reconnection: ${e.message}`,
4996
- );
4997
- } else {
4998
- console.error(
4999
- `Unexpected error during reconnection: ${e.message}`,
5000
- );
5001
- }
5002
-
5003
- // Calculate exponential backoff with jitter
5004
- const delay = Math.min(baseDelay * Math.pow(2, retry), maxDelay);
5005
- // Add jitter to prevent thundering herd
5006
- const jitter = (Math.random() * 2 - 1) * maxJitter * delay;
5007
- const finalDelay = Math.max(100, delay + jitter);
5008
-
5009
- console.debug(
5010
- `Waiting ${(finalDelay / 1000).toFixed(2)}s before next reconnection attempt`,
5011
- );
5012
-
5013
- // Track the reconnection timeout to prevent leaks
5014
- const timeoutId = setTimeout(async () => {
5015
- this._reconnect_timeouts.delete(timeoutId);
5016
-
5017
- // Check if connection was restored externally
5018
- if (
5019
- this._websocket &&
5020
- this._websocket.readyState === WebSocket.OPEN
5021
- ) {
5022
- console.info("Connection restored externally");
5023
- return;
5024
- }
5025
-
5026
- // Check if we were explicitly closed
5027
- if (this._closed) {
5028
- console.info("Connection was closed, stopping reconnection");
5029
- return;
5030
- }
5031
-
5032
- retry += 1;
5033
- if (retry < MAX_RETRY) {
5034
- await reconnect();
5035
- } else {
5036
- console.error(
5037
- `Failed to reconnect after ${MAX_RETRY} attempts, giving up.`,
5038
- );
5039
- // Mark as closed to prevent further reconnection attempts
5040
- this._closed = true;
5041
- // Notify about max retry exceeded
5042
- if (this._handle_disconnected) {
5043
- this._handle_disconnected(
5044
- "Max reconnection attempts exceeded",
5045
- );
5046
- }
5047
- // Note: We intentionally do NOT call process.exit() here.
5048
- // Instead, we mark the connection as closed and let the
5049
- // application handle the failure through the disconnected
5050
- // handler or by checking connection state.
5051
- }
5052
- }, finalDelay);
5053
- this._reconnect_timeouts.add(timeoutId);
5054
- }
5055
- };
5056
- reconnect();
5057
- }
5058
- } else {
5059
- // Clean up timers in all cases
5060
- this._cleanup();
5061
- if (this._handle_disconnected) {
5062
- this._handle_disconnected(event.reason);
5063
- }
5064
- }
5065
- }
5066
-
5067
- async emit_message(data) {
5068
- if (this._closed) {
5069
- throw new Error("Connection is closed");
5070
- }
5071
- if (!this._websocket || this._websocket.readyState !== WebSocket.OPEN) {
5072
- await this.open();
5073
- }
5074
- try {
5075
- this._last_message = data; // Store the message before sending
5076
- this._websocket.send(data);
5077
- this._last_message = null; // Clear after successful send
5078
- } catch (exp) {
5079
- console.error(`Failed to send data, error: ${exp}`);
5080
- throw exp;
5081
- }
5082
- }
5083
-
5084
- disconnect(reason) {
5085
- this._closed = true;
5086
- this._last_message = null; // Clear last message on disconnect
5087
- // Ensure websocket is closed if it exists and is not already closed or closing
5088
- if (
5089
- this._websocket &&
5090
- this._websocket.readyState !== WebSocket.CLOSED &&
5091
- this._websocket.readyState !== WebSocket.CLOSING
5092
- ) {
5093
- this._websocket.close(1000, reason);
5094
- }
5095
- // Use centralized cleanup to clear all timers
5096
- this._cleanup();
5097
- console.info(`WebSocket connection disconnected (${reason})`);
5098
- }
5099
- }
5100
-
5101
- function normalizeServerUrl(server_url) {
5102
- if (!server_url) throw new Error("server_url is required");
5103
- if (server_url.startsWith("http://")) {
5104
- server_url =
5105
- server_url.replace("http://", "ws://").replace(/\/$/, "") + "/ws";
5106
- } else if (server_url.startsWith("https://")) {
5107
- server_url =
5108
- server_url.replace("https://", "wss://").replace(/\/$/, "") + "/ws";
5109
- }
5110
- return server_url;
5111
- }
5112
-
5113
- async function login(config) {
5114
- const service_id = config.login_service_id || "public/hypha-login";
5115
- const workspace = config.workspace;
5116
- const expires_in = config.expires_in;
5117
- const timeout = config.login_timeout || 60;
5118
- const callback = config.login_callback;
5119
- const profile = config.profile;
5120
- const additional_headers = config.additional_headers;
5121
-
5122
- const server = await connectToServer({
5123
- name: "initial login client",
5124
- server_url: config.server_url,
5125
- additional_headers: additional_headers,
5126
- });
5127
- try {
5128
- const svc = await server.getService(service_id);
5129
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(svc, `Failed to get the login service: ${service_id}`);
5130
- let context;
5131
- if (workspace) {
5132
- context = await svc.start({ workspace, expires_in, _rkwargs: true });
5133
- } else {
5134
- context = await svc.start();
5135
- }
5136
- if (callback) {
5137
- await callback(context);
5138
- } else {
5139
- console.log(`Please open your browser and login at ${context.login_url}`);
5140
- }
5141
- return await svc.check(context.key, { timeout, profile, _rkwargs: true });
5142
- } catch (error) {
5143
- throw error;
5144
- } finally {
5145
- await server.disconnect();
5146
- }
5147
- }
5148
-
5149
- async function logout(config) {
5150
- const service_id = config.login_service_id || "public/hypha-login";
5151
- const callback = config.logout_callback;
5152
- const additional_headers = config.additional_headers;
5153
-
5154
- const server = await connectToServer({
5155
- name: "initial logout client",
5156
- server_url: config.server_url,
5157
- additional_headers: additional_headers,
5158
- });
5159
- try {
5160
- const svc = await server.getService(service_id);
5161
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(svc, `Failed to get the login service: ${service_id}`);
5162
-
5163
- // Check if logout function exists for backward compatibility
5164
- if (!svc.logout) {
5165
- throw new Error(
5166
- "Logout is not supported by this server. " +
5167
- "Please upgrade the Hypha server to a version that supports logout.",
5168
- );
5169
- }
5170
-
5171
- const context = await svc.logout({});
5172
- if (callback) {
5173
- await callback(context);
5174
- } else {
5175
- console.log(
5176
- `Please open your browser to logout at ${context.logout_url}`,
5177
- );
5178
- }
5179
- return context;
5180
- } catch (error) {
5181
- throw error;
5182
- } finally {
5183
- await server.disconnect();
5184
- }
5185
- }
5186
-
5187
- async function webrtcGetService(wm, rtc_service_id, query, config) {
5188
- config = config || {};
5189
- const webrtc = config.webrtc;
5190
- const webrtc_config = config.webrtc_config;
5191
- if (config.webrtc !== undefined) delete config.webrtc;
5192
- if (config.webrtc_config !== undefined) delete config.webrtc_config;
5193
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
5194
- [undefined, true, false, "auto"].includes(webrtc),
5195
- "webrtc must be true, false or 'auto'",
5196
- );
5197
-
5198
- const svc = await wm.getService(query, config);
5199
- if (webrtc === true || webrtc === "auto") {
5200
- if (svc.id.includes(":") && svc.id.includes("/")) {
5201
- try {
5202
- // Assuming that the client registered a webrtc service with the client_id + "-rtc"
5203
- const peer = await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService)(wm, rtc_service_id, webrtc_config);
5204
- const rtcSvc = await peer.getService(svc.id.split(":")[1], config);
5205
- rtcSvc._webrtc = true;
5206
- rtcSvc._peer = peer;
5207
- rtcSvc._service = svc;
5208
- return rtcSvc;
5209
- } catch (e) {
5210
- console.warn(
5211
- "Failed to get webrtc service, using websocket connection",
5212
- e,
5213
- );
5214
- }
5215
- }
5216
- if (webrtc === true) {
5217
- throw new Error("Failed to get the service via webrtc");
5218
- }
5219
- }
5220
- return svc;
5221
- }
5222
-
5223
- async function connectToServer(config) {
5224
- if (config.server) {
5225
- config.server_url = config.server_url || config.server.url;
5226
- config.WebSocketClass =
5227
- config.WebSocketClass || config.server.WebSocketClass;
5228
- }
5229
- let clientId = config.client_id;
5230
- if (!clientId) {
5231
- clientId = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
5232
- config.client_id = clientId;
5233
- }
5234
- if (Object.keys(config).length === 0) {
5235
- if (typeof process !== "undefined" && process.env) {
5236
- // Node.js
5237
- config.server_url = process.env.HYPHA_SERVER_URL;
5238
- config.token = process.env.HYPHA_TOKEN;
5239
- config.client_id = process.env.HYPHA_CLIENT_ID;
5240
- config.workspace = process.env.HYPHA_WORKSPACE;
5241
- } else if (typeof self !== "undefined" && self.env) {
5242
- // WebWorker (only if you inject self.env manually)
5243
- config.server_url = self.env.HYPHA_SERVER_URL;
5244
- config.token = self.env.HYPHA_TOKEN;
5245
- config.client_id = self.env.HYPHA_CLIENT_ID;
5246
- config.workspace = self.env.HYPHA_WORKSPACE;
5247
- } else if (typeof globalThis !== "undefined" && globalThis.env) {
5248
- // Browser (only if you define globalThis.env beforehand)
5249
- config.server_url = globalThis.env.HYPHA_SERVER_URL;
5250
- config.token = globalThis.env.HYPHA_TOKEN;
5251
- config.client_id = globalThis.env.HYPHA_CLIENT_ID;
5252
- config.workspace = globalThis.env.HYPHA_WORKSPACE;
5253
- }
5254
- }
5255
-
5256
- let server_url = normalizeServerUrl(config.server_url);
5257
-
5258
- let connection = new WebsocketRPCConnection(
5259
- server_url,
5260
- clientId,
5261
- config.workspace,
5262
- config.token,
5263
- config.reconnection_token,
5264
- config.method_timeout || 60,
5265
- config.WebSocketClass,
5266
- config.token_refresh_interval,
5267
- config.additional_headers,
5268
- );
5269
- const connection_info = await connection.open();
5270
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
5271
- connection_info,
5272
- "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.",
5273
- );
5274
- // wait for 0.5 seconds
5275
- await new Promise((resolve) => setTimeout(resolve, 100));
5276
- // Ensure manager_id is set before proceeding
5277
- if (!connection.manager_id) {
5278
- console.warn("Manager ID not set immediately, waiting...");
5279
-
5280
- // Wait for manager_id to be set with timeout
5281
- const maxWaitTime = 5000; // 5 seconds
5282
- const checkInterval = 100; // 100ms
5283
- const startTime = Date.now();
5284
-
5285
- while (!connection.manager_id && Date.now() - startTime < maxWaitTime) {
5286
- await new Promise((resolve) => setTimeout(resolve, checkInterval));
5287
- }
5288
-
5289
- if (!connection.manager_id) {
5290
- console.error("Manager ID still not set after waiting");
5291
- throw new Error("Failed to get manager ID from server");
5292
- } else {
5293
- console.info(`Manager ID set after waiting: ${connection.manager_id}`);
5294
- }
5295
- }
5296
- if (config.workspace && connection_info.workspace !== config.workspace) {
5297
- throw new Error(
5298
- `Connected to the wrong workspace: ${connection_info.workspace}, expected: ${config.workspace}`,
5299
- );
5300
- }
5301
-
5302
- const workspace = connection_info.workspace;
5303
- const rpc = new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(connection, {
5304
- client_id: clientId,
5305
- workspace,
5306
- default_context: { connection_type: "websocket" },
5307
- name: config.name,
5308
- method_timeout: config.method_timeout,
5309
- app_id: config.app_id,
5310
- server_base_url: connection_info.public_base_url,
5311
- long_message_chunk_size: config.long_message_chunk_size,
5312
- });
5313
- await rpc.waitFor("services_registered", config.method_timeout || 120);
5314
- const wm = await rpc.get_manager_service({
5315
- timeout: config.method_timeout,
5316
- case_conversion: "camel",
5317
- kwargs_expansion: config.kwargs_expansion || false,
5318
- });
5319
- wm.rpc = rpc;
5320
-
5321
- async function _export(api) {
5322
- api.id = "default";
5323
- api.name = api.name || config.name || api.id;
5324
- api.description = api.description || config.description;
5325
- await rpc.register_service(api, { overwrite: true });
5326
- }
5327
-
5328
- async function getApp(clientId) {
5329
- clientId = clientId || "*";
5330
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!clientId.includes(":"), "clientId should not contain ':'");
5331
- if (!clientId.includes("/")) {
5332
- clientId = connection_info.workspace + "/" + clientId;
5333
- }
5334
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
5335
- clientId.split("/").length === 2,
5336
- "clientId should match pattern workspace/clientId",
5337
- );
5338
- return await wm.getService(`${clientId}:default`);
5339
- }
5340
-
5341
- async function listApps(ws) {
5342
- ws = ws || workspace;
5343
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!ws.includes(":"), "workspace should not contain ':'");
5344
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!ws.includes("/"), "workspace should not contain '/'");
5345
- const query = { workspace: ws, service_id: "default" };
5346
- return await wm.listServices(query);
5347
- }
5348
-
5349
- if (connection_info) {
5350
- wm.config = Object.assign(wm.config, connection_info);
5351
- }
5352
- wm.export = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(_export, {
5353
- name: "export",
5354
- description: "Export the api.",
5355
- parameters: {
5356
- properties: { api: { description: "The api to export", type: "object" } },
5357
- required: ["api"],
5358
- type: "object",
5359
- },
5360
- });
5361
- wm.getApp = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(getApp, {
5362
- name: "getApp",
5363
- description: "Get the app.",
5364
- parameters: {
5365
- properties: {
5366
- clientId: { default: "*", description: "The clientId", type: "string" },
5367
- },
5368
- type: "object",
5369
- },
5370
- });
5371
- wm.listApps = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(listApps, {
5372
- name: "listApps",
5373
- description: "List the apps.",
5374
- parameters: {
5375
- properties: {
5376
- workspace: {
5377
- default: workspace,
5378
- description: "The workspace",
5379
- type: "string",
5380
- },
5381
- },
5382
- type: "object",
5383
- },
5384
- });
5385
- wm.disconnect = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.disconnect.bind(rpc), {
5386
- name: "disconnect",
5387
- description: "Disconnect from the server.",
5388
- parameters: { type: "object", properties: {}, required: [] },
5389
- });
5390
- wm.registerCodec = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.register_codec.bind(rpc), {
5391
- name: "registerCodec",
5392
- description: "Register a codec for the webrtc connection",
5393
- parameters: {
5394
- type: "object",
5395
- properties: {
5396
- codec: {
5397
- type: "object",
5398
- description: "Codec to register",
5399
- properties: {
5400
- name: { type: "string" },
5401
- type: {},
5402
- encoder: { type: "function" },
5403
- decoder: { type: "function" },
5404
- },
5405
- },
5406
- },
5407
- },
5408
- });
5409
-
5410
- wm.emit = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.emit.bind(rpc), {
5411
- name: "emit",
5412
- description: "Emit a message.",
5413
- parameters: {
5414
- properties: { data: { description: "The data to emit", type: "object" } },
5415
- required: ["data"],
5416
- type: "object",
5417
- },
5418
- });
5419
-
5420
- wm.on = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.on.bind(rpc), {
5421
- name: "on",
5422
- description: "Register a message handler.",
5423
- parameters: {
5424
- properties: {
5425
- event: { description: "The event to listen to", type: "string" },
5426
- handler: { description: "The handler function", type: "function" },
5427
- },
5428
- required: ["event", "handler"],
5429
- type: "object",
5430
- },
5431
- });
5432
-
5433
- wm.off = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.off.bind(rpc), {
5434
- name: "off",
5435
- description: "Remove a message handler.",
5436
- parameters: {
5437
- properties: {
5438
- event: { description: "The event to remove", type: "string" },
5439
- handler: { description: "The handler function", type: "function" },
5440
- },
5441
- required: ["event", "handler"],
5442
- type: "object",
5443
- },
5444
- });
5445
-
5446
- wm.once = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.once.bind(rpc), {
5447
- name: "once",
5448
- description: "Register a one-time message handler.",
5449
- parameters: {
5450
- properties: {
5451
- event: { description: "The event to listen to", type: "string" },
5452
- handler: { description: "The handler function", type: "function" },
5453
- },
5454
- required: ["event", "handler"],
5455
- type: "object",
5456
- },
5457
- });
5458
-
5459
- wm.getServiceSchema = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.get_service_schema, {
5460
- name: "getServiceSchema",
5461
- description: "Get the service schema.",
5462
- parameters: {
5463
- properties: {
5464
- service: {
5465
- description: "The service to extract schema",
5466
- type: "object",
5467
- },
5468
- },
5469
- required: ["service"],
5470
- type: "object",
5471
- },
5472
- });
5473
-
5474
- wm.registerService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.register_service.bind(rpc), {
5475
- name: "registerService",
5476
- description: "Register a service.",
5477
- parameters: {
5478
- properties: {
5479
- service: { description: "The service to register", type: "object" },
5480
- force: {
5481
- default: false,
5482
- description: "Force to register the service",
5483
- type: "boolean",
5484
- },
5485
- },
5486
- required: ["service"],
5487
- type: "object",
5488
- },
5489
- });
5490
- wm.unregisterService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.unregister_service.bind(rpc), {
5491
- name: "unregisterService",
5492
- description: "Unregister a service.",
5493
- parameters: {
5494
- properties: {
5495
- service: {
5496
- description: "The service id to unregister",
5497
- type: "string",
5498
- },
5499
- notify: {
5500
- default: true,
5501
- description: "Notify the workspace manager",
5502
- type: "boolean",
5503
- },
5504
- },
5505
- required: ["service"],
5506
- type: "object",
5507
- },
5508
- });
5509
- if (connection.manager_id) {
5510
- rpc.on("force-exit", async (message) => {
5511
- if (message.from === "*/" + connection.manager_id) {
5512
- console.log("Disconnecting from server, reason:", message.reason);
5513
- await rpc.disconnect();
5514
- }
5515
- });
5516
- }
5517
- if (config.webrtc) {
5518
- await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService)(wm, `${clientId}-rtc`, config.webrtc_config);
5519
- // make a copy of wm, so webrtc can use the original wm.getService
5520
- const _wm = Object.assign({}, wm);
5521
- const description = _wm.getService.__schema__.description;
5522
- // TODO: Fix the schema for adding options for webrtc
5523
- const parameters = _wm.getService.__schema__.parameters;
5524
- wm.getService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(
5525
- webrtcGetService.bind(null, _wm, `${workspace}/${clientId}-rtc`),
5526
- {
5527
- name: "getService",
5528
- description,
5529
- parameters,
5530
- },
5531
- );
5532
-
5533
- wm.getRTCService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService.bind(null, wm), {
5534
- name: "getRTCService",
5535
- description: "Get the webrtc connection, returns a peer connection.",
5536
- parameters: {
5537
- properties: {
5538
- config: {
5539
- description: "The config for the webrtc service",
5540
- type: "object",
5541
- },
5542
- },
5543
- required: ["config"],
5544
- type: "object",
5545
- },
5546
- });
5547
- } else {
5548
- const _getService = wm.getService;
5549
- wm.getService = (query, config) => {
5550
- config = config || {};
5551
- return _getService(query, config);
5552
- };
5553
- wm.getService.__schema__ = _getService.__schema__;
5554
- }
5555
-
5556
- async function registerProbes(probes) {
5557
- probes.id = "probes";
5558
- probes.name = "Probes";
5559
- probes.config = { visibility: "public" };
5560
- probes.type = "probes";
5561
- probes.description = `Probes Service, visit ${server_url}/${workspace}services/probes for the available probes.`;
5562
- return await wm.registerService(probes, { overwrite: true });
5563
- }
5564
-
5565
- wm.registerProbes = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(registerProbes, {
5566
- name: "registerProbes",
5567
- description: "Register probes service",
5568
- parameters: {
5569
- properties: {
5570
- probes: {
5571
- description:
5572
- "The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",
5573
- type: "object",
5574
- },
5575
- },
5576
- required: ["probes"],
5577
- type: "object",
5578
- },
5579
- });
5580
- return wm;
5581
- }
5582
-
5583
- // Export alias for use by client.js
5584
-
5585
-
5586
- async function getRemoteService(serviceUri, config = {}) {
5587
- const { serverUrl, workspace, clientId, serviceId, appId } =
5588
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.parseServiceUrl)(serviceUri);
5589
- const fullServiceId = `${workspace}/${clientId}:${serviceId}@${appId}`;
5590
-
5591
- if (config.serverUrl) {
5592
- if (config.serverUrl !== serverUrl) {
5593
- throw new Error(
5594
- "server_url in config does not match the server_url in the url",
5595
- );
5596
- }
5597
- }
5598
- config.serverUrl = serverUrl;
5599
- const server = await connectToServer(config);
5600
- return await server.getService(fullServiceId);
5601
- }
5602
-
5603
- class LocalWebSocket {
5604
- constructor(url, client_id, workspace) {
5605
- this.url = url;
5606
- this.onopen = () => {};
5607
- this.onmessage = () => {};
5608
- this.onclose = () => {};
5609
- this.onerror = () => {};
5610
- this.client_id = client_id;
5611
- this.workspace = workspace;
5612
- const context = typeof window !== "undefined" ? window : self;
5613
- const isWindow = typeof window !== "undefined";
5614
- this.postMessage = (message) => {
5615
- if (isWindow) {
5616
- window.parent.postMessage(message, "*");
5617
- } else {
5618
- self.postMessage(message);
5619
- }
5620
- };
5621
-
5622
- this.readyState = WebSocket.CONNECTING;
5623
- context.addEventListener(
5624
- "message",
5625
- (event) => {
5626
- const { type, data, to } = event.data;
5627
- if (to !== this.client_id) {
5628
- // console.debug("message not for me", to, this.client_id);
5629
- return;
5630
- }
5631
- switch (type) {
5632
- case "message":
5633
- if (this.readyState === WebSocket.OPEN && this.onmessage) {
5634
- this.onmessage({ data: data });
5635
- }
5636
- break;
5637
- case "connected":
5638
- this.readyState = WebSocket.OPEN;
5639
- this.onopen(event);
5640
- break;
5641
- case "closed":
5642
- this.readyState = WebSocket.CLOSED;
5643
- this.onclose(event);
5644
- break;
5645
- default:
5646
- break;
5647
- }
5648
- },
5649
- false,
5650
- );
5651
-
5652
- if (!this.client_id) throw new Error("client_id is required");
5653
- if (!this.workspace) throw new Error("workspace is required");
5654
- this.postMessage({
5655
- type: "connect",
5656
- url: this.url,
5657
- from: this.client_id,
5658
- workspace: this.workspace,
5659
- });
5660
- }
5661
-
5662
- send(data) {
5663
- if (this.readyState === WebSocket.OPEN) {
5664
- this.postMessage({
5665
- type: "message",
5666
- data: data,
5667
- from: this.client_id,
5668
- workspace: this.workspace,
5669
- });
5670
- }
5671
- }
5672
-
5673
- close() {
5674
- this.readyState = WebSocket.CLOSING;
5675
- this.postMessage({
5676
- type: "close",
5677
- from: this.client_id,
5678
- workspace: this.workspace,
5679
- });
5680
- this.onclose();
5681
- }
5682
-
5683
- addEventListener(type, listener) {
5684
- if (type === "message") {
5685
- this.onmessage = listener;
5686
- }
5687
- if (type === "open") {
5688
- this.onopen = listener;
5689
- }
5690
- if (type === "close") {
5691
- this.onclose = listener;
5692
- }
5693
- if (type === "error") {
5694
- this.onerror = listener;
5695
- }
5696
- }
5697
- }
5698
-
5699
- function setupLocalClient({
5700
- enable_execution = false,
5701
- on_ready = null,
5702
- }) {
5703
- return new Promise((resolve, reject) => {
5704
- const context = typeof window !== "undefined" ? window : self;
5705
- const isWindow = typeof window !== "undefined";
5706
- context.addEventListener(
5707
- "message",
5708
- (event) => {
5709
- const {
5710
- type,
5711
- server_url,
5712
- workspace,
5713
- client_id,
5714
- token,
5715
- method_timeout,
5716
- name,
5717
- config,
5718
- } = event.data;
5719
-
5720
- if (type === "initializeHyphaClient") {
5721
- if (!server_url || !workspace || !client_id) {
5722
- console.error("server_url, workspace, and client_id are required.");
5723
- return;
5724
- }
5725
-
5726
- if (!server_url.startsWith("https://local-hypha-server:")) {
5727
- console.error(
5728
- "server_url should start with https://local-hypha-server:",
5729
- );
5730
- return;
5731
- }
5732
-
5733
- class FixedLocalWebSocket extends LocalWebSocket {
5734
- constructor(url) {
5735
- // Call the parent class's constructor with fixed values
5736
- super(url, client_id, workspace);
5737
- }
5738
- }
5739
- connectToServer({
5740
- server_url,
5741
- workspace,
5742
- client_id,
5743
- token,
5744
- method_timeout,
5745
- name,
5746
- WebSocketClass: FixedLocalWebSocket,
5747
- }).then(async (server) => {
5748
- globalThis.api = server;
5749
- try {
5750
- // for iframe
5751
- if (isWindow && enable_execution) {
5752
- function loadScript(script) {
5753
- return new Promise((resolve, reject) => {
5754
- const scriptElement = document.createElement("script");
5755
- scriptElement.innerHTML = script.content;
5756
- scriptElement.lang = script.lang;
5757
-
5758
- scriptElement.onload = () => resolve();
5759
- scriptElement.onerror = (e) => reject(e);
5760
-
5761
- document.head.appendChild(scriptElement);
5762
- });
5763
- }
5764
- if (config.styles && config.styles.length > 0) {
5765
- for (const style of config.styles) {
5766
- const styleElement = document.createElement("style");
5767
- styleElement.innerHTML = style.content;
5768
- styleElement.lang = style.lang;
5769
- document.head.appendChild(styleElement);
5770
- }
5771
- }
5772
- if (config.links && config.links.length > 0) {
5773
- for (const link of config.links) {
5774
- const linkElement = document.createElement("a");
5775
- linkElement.href = link.url;
5776
- linkElement.innerText = link.text;
5777
- document.body.appendChild(linkElement);
5778
- }
5779
- }
5780
- if (config.windows && config.windows.length > 0) {
5781
- for (const w of config.windows) {
5782
- document.body.innerHTML = w.content;
5783
- break;
5784
- }
5785
- }
5786
- if (config.scripts && config.scripts.length > 0) {
5787
- for (const script of config.scripts) {
5788
- if (script.lang !== "javascript")
5789
- throw new Error("Only javascript scripts are supported");
5790
- await loadScript(script); // Await the loading of each script
5791
- }
5792
- }
5793
- }
5794
- // for web worker
5795
- else if (
5796
- !isWindow &&
5797
- enable_execution &&
5798
- config.scripts &&
5799
- config.scripts.length > 0
5800
- ) {
5801
- for (const script of config.scripts) {
5802
- if (script.lang !== "javascript")
5803
- throw new Error("Only javascript scripts are supported");
5804
- eval(script.content);
5805
- }
5806
- }
5807
-
5808
- if (on_ready) {
5809
- await on_ready(server, config);
5810
- }
5811
- resolve(server);
5812
- } catch (e) {
5813
- reject(e);
5814
- }
5815
- });
5816
- }
5817
- },
5818
- false,
5819
- );
5820
- if (isWindow) {
5821
- window.parent.postMessage({ type: "hyphaClientReady" }, "*");
5822
- } else {
5823
- self.postMessage({ type: "hyphaClientReady" });
5824
- }
5825
- });
5826
- }
5827
-
5828
-
5829
- /***/ }),
5830
-
5831
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
5832
- /*!*************************************************************************!*\
5833
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs ***!
5834
- \*************************************************************************/
5835
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5836
-
5837
- __webpack_require__.r(__webpack_exports__);
5838
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5839
- /* harmony export */ CachedKeyDecoder: () => (/* binding */ CachedKeyDecoder)
5840
- /* harmony export */ });
5841
- /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
5842
-
5843
- var DEFAULT_MAX_KEY_LENGTH = 16;
5844
- var DEFAULT_MAX_LENGTH_PER_KEY = 16;
5845
- var CachedKeyDecoder = /** @class */ (function () {
5846
- function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
5847
- if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
5848
- if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
5849
- this.maxKeyLength = maxKeyLength;
5850
- this.maxLengthPerKey = maxLengthPerKey;
5851
- this.hit = 0;
5852
- this.miss = 0;
5853
- // avoid `new Array(N)`, which makes a sparse array,
5854
- // because a sparse array is typically slower than a non-sparse array.
5855
- this.caches = [];
5856
- for (var i = 0; i < this.maxKeyLength; i++) {
5857
- this.caches.push([]);
5858
- }
5859
- }
5860
- CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
5861
- return byteLength > 0 && byteLength <= this.maxKeyLength;
5862
- };
5863
- CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {
5864
- var records = this.caches[byteLength - 1];
5865
- FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
5866
- var record = records_1[_i];
5867
- var recordBytes = record.bytes;
5868
- for (var j = 0; j < byteLength; j++) {
5869
- if (recordBytes[j] !== bytes[inputOffset + j]) {
5870
- continue FIND_CHUNK;
5871
- }
5872
- }
5873
- return record.str;
5874
- }
5875
- return null;
5876
- };
5877
- CachedKeyDecoder.prototype.store = function (bytes, value) {
5878
- var records = this.caches[bytes.length - 1];
5879
- var record = { bytes: bytes, str: value };
5880
- if (records.length >= this.maxLengthPerKey) {
5881
- // `records` are full!
5882
- // Set `record` to an arbitrary position.
5883
- records[(Math.random() * records.length) | 0] = record;
5884
- }
5885
- else {
5886
- records.push(record);
5887
- }
5888
- };
5889
- CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
5890
- var cachedValue = this.find(bytes, inputOffset, byteLength);
5891
- if (cachedValue != null) {
5892
- this.hit++;
5893
- return cachedValue;
5894
- }
5895
- this.miss++;
5896
- var str = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_0__.utf8DecodeJs)(bytes, inputOffset, byteLength);
5897
- // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
5898
- var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
5899
- this.store(slicedCopyOfBytes, str);
5900
- return str;
5901
- };
5902
- return CachedKeyDecoder;
5903
- }());
5904
-
5905
- //# sourceMappingURL=CachedKeyDecoder.mjs.map
5906
-
5907
- /***/ }),
5908
-
5909
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
5910
- /*!********************************************************************!*\
5911
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs ***!
5912
- \********************************************************************/
5913
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5914
-
5915
- __webpack_require__.r(__webpack_exports__);
5916
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5917
- /* harmony export */ DecodeError: () => (/* binding */ DecodeError)
5918
- /* harmony export */ });
5919
- var __extends = (undefined && undefined.__extends) || (function () {
5920
- var extendStatics = function (d, b) {
5921
- extendStatics = Object.setPrototypeOf ||
5922
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5923
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
5924
- return extendStatics(d, b);
5925
- };
5926
- return function (d, b) {
5927
- if (typeof b !== "function" && b !== null)
5928
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
5929
- extendStatics(d, b);
5930
- function __() { this.constructor = d; }
5931
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5932
- };
5933
- })();
5934
- var DecodeError = /** @class */ (function (_super) {
5935
- __extends(DecodeError, _super);
5936
- function DecodeError(message) {
5937
- var _this = _super.call(this, message) || this;
5938
- // fix the prototype chain in a cross-platform way
5939
- var proto = Object.create(DecodeError.prototype);
5940
- Object.setPrototypeOf(_this, proto);
5941
- Object.defineProperty(_this, "name", {
5942
- configurable: true,
5943
- enumerable: false,
5944
- value: DecodeError.name,
5945
- });
5946
- return _this;
5947
- }
5948
- return DecodeError;
5949
- }(Error));
5950
-
5951
- //# sourceMappingURL=DecodeError.mjs.map
5952
-
5953
- /***/ }),
5954
-
5955
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs":
5956
- /*!****************************************************************!*\
5957
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs ***!
5958
- \****************************************************************/
5959
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5960
-
5961
- __webpack_require__.r(__webpack_exports__);
5962
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5963
- /* harmony export */ DataViewIndexOutOfBoundsError: () => (/* binding */ DataViewIndexOutOfBoundsError),
5964
- /* harmony export */ Decoder: () => (/* binding */ Decoder)
5965
- /* harmony export */ });
5966
- /* harmony import */ var _utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/prettyByte.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs");
5967
- /* harmony import */ var _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtensionCodec.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs");
5968
- /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
5969
- /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
5970
- /* harmony import */ var _utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/typedArrays.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs");
5971
- /* harmony import */ var _CachedKeyDecoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CachedKeyDecoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs");
5972
- /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
5973
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
5974
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5975
- return new (P || (P = Promise))(function (resolve, reject) {
5976
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5977
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5978
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
5979
- step((generator = generator.apply(thisArg, _arguments || [])).next());
5980
- });
5981
- };
5982
- var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
5983
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
5984
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
5985
- function verb(n) { return function (v) { return step([n, v]); }; }
5986
- function step(op) {
5987
- if (f) throw new TypeError("Generator is already executing.");
5988
- while (_) try {
5989
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
5990
- if (y = 0, t) op = [op[0] & 2, t.value];
5991
- switch (op[0]) {
5992
- case 0: case 1: t = op; break;
5993
- case 4: _.label++; return { value: op[1], done: false };
5994
- case 5: _.label++; y = op[1]; op = [0]; continue;
5995
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
5996
- default:
5997
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
5998
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
5999
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
6000
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
6001
- if (t[2]) _.ops.pop();
6002
- _.trys.pop(); continue;
6003
- }
6004
- op = body.call(thisArg, _);
6005
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
6006
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
6007
- }
6008
- };
6009
- var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
6010
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
6011
- var m = o[Symbol.asyncIterator], i;
6012
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
6013
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
6014
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
6015
- };
6016
- var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
6017
- var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
6018
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
6019
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
6020
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
6021
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
6022
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
6023
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
6024
- function fulfill(value) { resume("next", value); }
6025
- function reject(value) { resume("throw", value); }
6026
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
6027
- };
4734
+ __webpack_require__.r(__webpack_exports__);
4735
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
4736
+ /* harmony export */ DataViewIndexOutOfBoundsError: () => (/* binding */ DataViewIndexOutOfBoundsError),
4737
+ /* harmony export */ Decoder: () => (/* binding */ Decoder)
4738
+ /* harmony export */ });
4739
+ /* harmony import */ var _utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./utils/prettyByte.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs");
4740
+ /* harmony import */ var _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtensionCodec.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs");
4741
+ /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
4742
+ /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
4743
+ /* harmony import */ var _utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/typedArrays.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs");
4744
+ /* harmony import */ var _CachedKeyDecoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CachedKeyDecoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs");
4745
+ /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
4746
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
4747
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4748
+ return new (P || (P = Promise))(function (resolve, reject) {
4749
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
4750
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
4751
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
4752
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
4753
+ });
4754
+ };
4755
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
4756
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
4757
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
4758
+ function verb(n) { return function (v) { return step([n, v]); }; }
4759
+ function step(op) {
4760
+ if (f) throw new TypeError("Generator is already executing.");
4761
+ while (_) try {
4762
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
4763
+ if (y = 0, t) op = [op[0] & 2, t.value];
4764
+ switch (op[0]) {
4765
+ case 0: case 1: t = op; break;
4766
+ case 4: _.label++; return { value: op[1], done: false };
4767
+ case 5: _.label++; y = op[1]; op = [0]; continue;
4768
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
4769
+ default:
4770
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
4771
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
4772
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
4773
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
4774
+ if (t[2]) _.ops.pop();
4775
+ _.trys.pop(); continue;
4776
+ }
4777
+ op = body.call(thisArg, _);
4778
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
4779
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
4780
+ }
4781
+ };
4782
+ var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
4783
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4784
+ var m = o[Symbol.asyncIterator], i;
4785
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
4786
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
4787
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
4788
+ };
4789
+ var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
4790
+ var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
4791
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4792
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
4793
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
4794
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
4795
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
4796
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
4797
+ function fulfill(value) { resume("next", value); }
4798
+ function reject(value) { resume("throw", value); }
4799
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
4800
+ };
6028
4801
 
6029
4802
 
6030
4803
 
@@ -6921,958 +5694,1862 @@ var Encoder = /** @class */ (function () {
6921
5694
  this.pos += byteLength;
6922
5695
  }
6923
5696
  else {
6924
- var byteLength = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8Count)(object);
6925
- this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
6926
- this.writeStringHeader(byteLength);
6927
- (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8EncodeJs)(object, this.bytes, this.pos);
6928
- this.pos += byteLength;
5697
+ var byteLength = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8Count)(object);
5698
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
5699
+ this.writeStringHeader(byteLength);
5700
+ (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8EncodeJs)(object, this.bytes, this.pos);
5701
+ this.pos += byteLength;
5702
+ }
5703
+ };
5704
+ Encoder.prototype.encodeObject = function (object, depth) {
5705
+ // try to encode objects with custom codec first of non-primitives
5706
+ var ext = this.extensionCodec.tryToEncode(object, this.context);
5707
+ if (ext != null) {
5708
+ this.encodeExtension(ext);
5709
+ }
5710
+ else if (Array.isArray(object)) {
5711
+ this.encodeArray(object, depth);
5712
+ }
5713
+ else if (ArrayBuffer.isView(object)) {
5714
+ this.encodeBinary(object);
5715
+ }
5716
+ else if (typeof object === "object") {
5717
+ this.encodeMap(object, depth);
5718
+ }
5719
+ else {
5720
+ // symbol, function and other special object come here unless extensionCodec handles them.
5721
+ throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(object)));
5722
+ }
5723
+ };
5724
+ Encoder.prototype.encodeBinary = function (object) {
5725
+ var size = object.byteLength;
5726
+ if (size < 0x100) {
5727
+ // bin 8
5728
+ this.writeU8(0xc4);
5729
+ this.writeU8(size);
5730
+ }
5731
+ else if (size < 0x10000) {
5732
+ // bin 16
5733
+ this.writeU8(0xc5);
5734
+ this.writeU16(size);
5735
+ }
5736
+ else if (size < 0x100000000) {
5737
+ // bin 32
5738
+ this.writeU8(0xc6);
5739
+ this.writeU32(size);
5740
+ }
5741
+ else {
5742
+ throw new Error("Too large binary: ".concat(size));
5743
+ }
5744
+ var bytes = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_2__.ensureUint8Array)(object);
5745
+ this.writeU8a(bytes);
5746
+ };
5747
+ Encoder.prototype.encodeArray = function (object, depth) {
5748
+ var size = object.length;
5749
+ if (size < 16) {
5750
+ // fixarray
5751
+ this.writeU8(0x90 + size);
5752
+ }
5753
+ else if (size < 0x10000) {
5754
+ // array 16
5755
+ this.writeU8(0xdc);
5756
+ this.writeU16(size);
5757
+ }
5758
+ else if (size < 0x100000000) {
5759
+ // array 32
5760
+ this.writeU8(0xdd);
5761
+ this.writeU32(size);
5762
+ }
5763
+ else {
5764
+ throw new Error("Too large array: ".concat(size));
5765
+ }
5766
+ for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {
5767
+ var item = object_1[_i];
5768
+ this.doEncode(item, depth + 1);
5769
+ }
5770
+ };
5771
+ Encoder.prototype.countWithoutUndefined = function (object, keys) {
5772
+ var count = 0;
5773
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
5774
+ var key = keys_1[_i];
5775
+ if (object[key] !== undefined) {
5776
+ count++;
5777
+ }
5778
+ }
5779
+ return count;
5780
+ };
5781
+ Encoder.prototype.encodeMap = function (object, depth) {
5782
+ var keys = Object.keys(object);
5783
+ if (this.sortKeys) {
5784
+ keys.sort();
5785
+ }
5786
+ var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
5787
+ if (size < 16) {
5788
+ // fixmap
5789
+ this.writeU8(0x80 + size);
5790
+ }
5791
+ else if (size < 0x10000) {
5792
+ // map 16
5793
+ this.writeU8(0xde);
5794
+ this.writeU16(size);
5795
+ }
5796
+ else if (size < 0x100000000) {
5797
+ // map 32
5798
+ this.writeU8(0xdf);
5799
+ this.writeU32(size);
5800
+ }
5801
+ else {
5802
+ throw new Error("Too large map object: ".concat(size));
5803
+ }
5804
+ for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
5805
+ var key = keys_2[_i];
5806
+ var value = object[key];
5807
+ if (!(this.ignoreUndefined && value === undefined)) {
5808
+ this.encodeString(key);
5809
+ this.doEncode(value, depth + 1);
5810
+ }
5811
+ }
5812
+ };
5813
+ Encoder.prototype.encodeExtension = function (ext) {
5814
+ var size = ext.data.length;
5815
+ if (size === 1) {
5816
+ // fixext 1
5817
+ this.writeU8(0xd4);
5818
+ }
5819
+ else if (size === 2) {
5820
+ // fixext 2
5821
+ this.writeU8(0xd5);
5822
+ }
5823
+ else if (size === 4) {
5824
+ // fixext 4
5825
+ this.writeU8(0xd6);
5826
+ }
5827
+ else if (size === 8) {
5828
+ // fixext 8
5829
+ this.writeU8(0xd7);
5830
+ }
5831
+ else if (size === 16) {
5832
+ // fixext 16
5833
+ this.writeU8(0xd8);
5834
+ }
5835
+ else if (size < 0x100) {
5836
+ // ext 8
5837
+ this.writeU8(0xc7);
5838
+ this.writeU8(size);
5839
+ }
5840
+ else if (size < 0x10000) {
5841
+ // ext 16
5842
+ this.writeU8(0xc8);
5843
+ this.writeU16(size);
5844
+ }
5845
+ else if (size < 0x100000000) {
5846
+ // ext 32
5847
+ this.writeU8(0xc9);
5848
+ this.writeU32(size);
5849
+ }
5850
+ else {
5851
+ throw new Error("Too large extension object: ".concat(size));
5852
+ }
5853
+ this.writeI8(ext.type);
5854
+ this.writeU8a(ext.data);
5855
+ };
5856
+ Encoder.prototype.writeU8 = function (value) {
5857
+ this.ensureBufferSizeToWrite(1);
5858
+ this.view.setUint8(this.pos, value);
5859
+ this.pos++;
5860
+ };
5861
+ Encoder.prototype.writeU8a = function (values) {
5862
+ var size = values.length;
5863
+ this.ensureBufferSizeToWrite(size);
5864
+ this.bytes.set(values, this.pos);
5865
+ this.pos += size;
5866
+ };
5867
+ Encoder.prototype.writeI8 = function (value) {
5868
+ this.ensureBufferSizeToWrite(1);
5869
+ this.view.setInt8(this.pos, value);
5870
+ this.pos++;
5871
+ };
5872
+ Encoder.prototype.writeU16 = function (value) {
5873
+ this.ensureBufferSizeToWrite(2);
5874
+ this.view.setUint16(this.pos, value);
5875
+ this.pos += 2;
5876
+ };
5877
+ Encoder.prototype.writeI16 = function (value) {
5878
+ this.ensureBufferSizeToWrite(2);
5879
+ this.view.setInt16(this.pos, value);
5880
+ this.pos += 2;
5881
+ };
5882
+ Encoder.prototype.writeU32 = function (value) {
5883
+ this.ensureBufferSizeToWrite(4);
5884
+ this.view.setUint32(this.pos, value);
5885
+ this.pos += 4;
5886
+ };
5887
+ Encoder.prototype.writeI32 = function (value) {
5888
+ this.ensureBufferSizeToWrite(4);
5889
+ this.view.setInt32(this.pos, value);
5890
+ this.pos += 4;
5891
+ };
5892
+ Encoder.prototype.writeF32 = function (value) {
5893
+ this.ensureBufferSizeToWrite(4);
5894
+ this.view.setFloat32(this.pos, value);
5895
+ this.pos += 4;
5896
+ };
5897
+ Encoder.prototype.writeF64 = function (value) {
5898
+ this.ensureBufferSizeToWrite(8);
5899
+ this.view.setFloat64(this.pos, value);
5900
+ this.pos += 8;
5901
+ };
5902
+ Encoder.prototype.writeU64 = function (value) {
5903
+ this.ensureBufferSizeToWrite(8);
5904
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setUint64)(this.view, this.pos, value);
5905
+ this.pos += 8;
5906
+ };
5907
+ Encoder.prototype.writeI64 = function (value) {
5908
+ this.ensureBufferSizeToWrite(8);
5909
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setInt64)(this.view, this.pos, value);
5910
+ this.pos += 8;
5911
+ };
5912
+ return Encoder;
5913
+ }());
5914
+
5915
+ //# sourceMappingURL=Encoder.mjs.map
5916
+
5917
+ /***/ }),
5918
+
5919
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
5920
+ /*!****************************************************************!*\
5921
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs ***!
5922
+ \****************************************************************/
5923
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5924
+
5925
+ __webpack_require__.r(__webpack_exports__);
5926
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5927
+ /* harmony export */ ExtData: () => (/* binding */ ExtData)
5928
+ /* harmony export */ });
5929
+ /**
5930
+ * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
5931
+ */
5932
+ var ExtData = /** @class */ (function () {
5933
+ function ExtData(type, data) {
5934
+ this.type = type;
5935
+ this.data = data;
5936
+ }
5937
+ return ExtData;
5938
+ }());
5939
+
5940
+ //# sourceMappingURL=ExtData.mjs.map
5941
+
5942
+ /***/ }),
5943
+
5944
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs":
5945
+ /*!***********************************************************************!*\
5946
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs ***!
5947
+ \***********************************************************************/
5948
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
5949
+
5950
+ __webpack_require__.r(__webpack_exports__);
5951
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
5952
+ /* harmony export */ ExtensionCodec: () => (/* binding */ ExtensionCodec)
5953
+ /* harmony export */ });
5954
+ /* harmony import */ var _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtData.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs");
5955
+ /* harmony import */ var _timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./timestamp.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs");
5956
+ // ExtensionCodec to handle MessagePack extensions
5957
+
5958
+
5959
+ var ExtensionCodec = /** @class */ (function () {
5960
+ function ExtensionCodec() {
5961
+ // built-in extensions
5962
+ this.builtInEncoders = [];
5963
+ this.builtInDecoders = [];
5964
+ // custom extensions
5965
+ this.encoders = [];
5966
+ this.decoders = [];
5967
+ this.register(_timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__.timestampExtension);
5968
+ }
5969
+ ExtensionCodec.prototype.register = function (_a) {
5970
+ var type = _a.type, encode = _a.encode, decode = _a.decode;
5971
+ if (type >= 0) {
5972
+ // custom extensions
5973
+ this.encoders[type] = encode;
5974
+ this.decoders[type] = decode;
5975
+ }
5976
+ else {
5977
+ // built-in extensions
5978
+ var index = 1 + type;
5979
+ this.builtInEncoders[index] = encode;
5980
+ this.builtInDecoders[index] = decode;
6929
5981
  }
6930
5982
  };
6931
- Encoder.prototype.encodeObject = function (object, depth) {
6932
- // try to encode objects with custom codec first of non-primitives
6933
- var ext = this.extensionCodec.tryToEncode(object, this.context);
6934
- if (ext != null) {
6935
- this.encodeExtension(ext);
6936
- }
6937
- else if (Array.isArray(object)) {
6938
- this.encodeArray(object, depth);
6939
- }
6940
- else if (ArrayBuffer.isView(object)) {
6941
- this.encodeBinary(object);
5983
+ ExtensionCodec.prototype.tryToEncode = function (object, context) {
5984
+ // built-in extensions
5985
+ for (var i = 0; i < this.builtInEncoders.length; i++) {
5986
+ var encodeExt = this.builtInEncoders[i];
5987
+ if (encodeExt != null) {
5988
+ var data = encodeExt(object, context);
5989
+ if (data != null) {
5990
+ var type = -1 - i;
5991
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
5992
+ }
5993
+ }
6942
5994
  }
6943
- else if (typeof object === "object") {
6944
- this.encodeMap(object, depth);
5995
+ // custom extensions
5996
+ for (var i = 0; i < this.encoders.length; i++) {
5997
+ var encodeExt = this.encoders[i];
5998
+ if (encodeExt != null) {
5999
+ var data = encodeExt(object, context);
6000
+ if (data != null) {
6001
+ var type = i;
6002
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
6003
+ }
6004
+ }
6945
6005
  }
6946
- else {
6947
- // symbol, function and other special object come here unless extensionCodec handles them.
6948
- throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(object)));
6006
+ if (object instanceof _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData) {
6007
+ // to keep ExtData as is
6008
+ return object;
6949
6009
  }
6010
+ return null;
6950
6011
  };
6951
- Encoder.prototype.encodeBinary = function (object) {
6952
- var size = object.byteLength;
6953
- if (size < 0x100) {
6954
- // bin 8
6955
- this.writeU8(0xc4);
6956
- this.writeU8(size);
6957
- }
6958
- else if (size < 0x10000) {
6959
- // bin 16
6960
- this.writeU8(0xc5);
6961
- this.writeU16(size);
6962
- }
6963
- else if (size < 0x100000000) {
6964
- // bin 32
6965
- this.writeU8(0xc6);
6966
- this.writeU32(size);
6012
+ ExtensionCodec.prototype.decode = function (data, type, context) {
6013
+ var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
6014
+ if (decodeExt) {
6015
+ return decodeExt(data, type, context);
6967
6016
  }
6968
6017
  else {
6969
- throw new Error("Too large binary: ".concat(size));
6018
+ // decode() does not fail, returns ExtData instead.
6019
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
6970
6020
  }
6971
- var bytes = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_2__.ensureUint8Array)(object);
6972
- this.writeU8a(bytes);
6973
6021
  };
6974
- Encoder.prototype.encodeArray = function (object, depth) {
6975
- var size = object.length;
6976
- if (size < 16) {
6977
- // fixarray
6978
- this.writeU8(0x90 + size);
6979
- }
6980
- else if (size < 0x10000) {
6981
- // array 16
6982
- this.writeU8(0xdc);
6983
- this.writeU16(size);
6984
- }
6985
- else if (size < 0x100000000) {
6986
- // array 32
6987
- this.writeU8(0xdd);
6988
- this.writeU32(size);
6022
+ ExtensionCodec.defaultCodec = new ExtensionCodec();
6023
+ return ExtensionCodec;
6024
+ }());
6025
+
6026
+ //# sourceMappingURL=ExtensionCodec.mjs.map
6027
+
6028
+ /***/ }),
6029
+
6030
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs":
6031
+ /*!***************************************************************!*\
6032
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs ***!
6033
+ \***************************************************************/
6034
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6035
+
6036
+ __webpack_require__.r(__webpack_exports__);
6037
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6038
+ /* harmony export */ decode: () => (/* binding */ decode),
6039
+ /* harmony export */ decodeMulti: () => (/* binding */ decodeMulti),
6040
+ /* harmony export */ defaultDecodeOptions: () => (/* binding */ defaultDecodeOptions)
6041
+ /* harmony export */ });
6042
+ /* harmony import */ var _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Decoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs");
6043
+
6044
+ var defaultDecodeOptions = {};
6045
+ /**
6046
+ * It decodes a single MessagePack object in a buffer.
6047
+ *
6048
+ * This is a synchronous decoding function.
6049
+ * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
6050
+ *
6051
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
6052
+ * @throws {@link DecodeError} if the buffer contains invalid data.
6053
+ */
6054
+ function decode(buffer, options) {
6055
+ if (options === void 0) { options = defaultDecodeOptions; }
6056
+ var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
6057
+ return decoder.decode(buffer);
6058
+ }
6059
+ /**
6060
+ * It decodes multiple MessagePack objects in a buffer.
6061
+ * This is corresponding to {@link decodeMultiStream()}.
6062
+ *
6063
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
6064
+ * @throws {@link DecodeError} if the buffer contains invalid data.
6065
+ */
6066
+ function decodeMulti(buffer, options) {
6067
+ if (options === void 0) { options = defaultDecodeOptions; }
6068
+ var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
6069
+ return decoder.decodeMulti(buffer);
6070
+ }
6071
+ //# sourceMappingURL=decode.mjs.map
6072
+
6073
+ /***/ }),
6074
+
6075
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs":
6076
+ /*!***************************************************************!*\
6077
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs ***!
6078
+ \***************************************************************/
6079
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6080
+
6081
+ __webpack_require__.r(__webpack_exports__);
6082
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6083
+ /* harmony export */ encode: () => (/* binding */ encode)
6084
+ /* harmony export */ });
6085
+ /* harmony import */ var _Encoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Encoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs");
6086
+
6087
+ var defaultEncodeOptions = {};
6088
+ /**
6089
+ * It encodes `value` in the MessagePack format and
6090
+ * returns a byte buffer.
6091
+ *
6092
+ * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.
6093
+ */
6094
+ function encode(value, options) {
6095
+ if (options === void 0) { options = defaultEncodeOptions; }
6096
+ var encoder = new _Encoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Encoder(options.extensionCodec, options.context, options.maxDepth, options.initialBufferSize, options.sortKeys, options.forceFloat32, options.ignoreUndefined, options.forceIntegerToFloat);
6097
+ return encoder.encodeSharedRef(value);
6098
+ }
6099
+ //# sourceMappingURL=encode.mjs.map
6100
+
6101
+ /***/ }),
6102
+
6103
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs":
6104
+ /*!******************************************************************!*\
6105
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs ***!
6106
+ \******************************************************************/
6107
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6108
+
6109
+ __webpack_require__.r(__webpack_exports__);
6110
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6111
+ /* harmony export */ EXT_TIMESTAMP: () => (/* binding */ EXT_TIMESTAMP),
6112
+ /* harmony export */ decodeTimestampExtension: () => (/* binding */ decodeTimestampExtension),
6113
+ /* harmony export */ decodeTimestampToTimeSpec: () => (/* binding */ decodeTimestampToTimeSpec),
6114
+ /* harmony export */ encodeDateToTimeSpec: () => (/* binding */ encodeDateToTimeSpec),
6115
+ /* harmony export */ encodeTimeSpecToTimestamp: () => (/* binding */ encodeTimeSpecToTimestamp),
6116
+ /* harmony export */ encodeTimestampExtension: () => (/* binding */ encodeTimestampExtension),
6117
+ /* harmony export */ timestampExtension: () => (/* binding */ timestampExtension)
6118
+ /* harmony export */ });
6119
+ /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
6120
+ /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
6121
+ // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
6122
+
6123
+
6124
+ var EXT_TIMESTAMP = -1;
6125
+ var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
6126
+ var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
6127
+ function encodeTimeSpecToTimestamp(_a) {
6128
+ var sec = _a.sec, nsec = _a.nsec;
6129
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
6130
+ // Here sec >= 0 && nsec >= 0
6131
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
6132
+ // timestamp 32 = { sec32 (unsigned) }
6133
+ var rv = new Uint8Array(4);
6134
+ var view = new DataView(rv.buffer);
6135
+ view.setUint32(0, sec);
6136
+ return rv;
6989
6137
  }
6990
6138
  else {
6991
- throw new Error("Too large array: ".concat(size));
6992
- }
6993
- for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {
6994
- var item = object_1[_i];
6995
- this.doEncode(item, depth + 1);
6139
+ // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
6140
+ var secHigh = sec / 0x100000000;
6141
+ var secLow = sec & 0xffffffff;
6142
+ var rv = new Uint8Array(8);
6143
+ var view = new DataView(rv.buffer);
6144
+ // nsec30 | secHigh2
6145
+ view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
6146
+ // secLow32
6147
+ view.setUint32(4, secLow);
6148
+ return rv;
6996
6149
  }
6150
+ }
6151
+ else {
6152
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
6153
+ var rv = new Uint8Array(12);
6154
+ var view = new DataView(rv.buffer);
6155
+ view.setUint32(0, nsec);
6156
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.setInt64)(view, 4, sec);
6157
+ return rv;
6158
+ }
6159
+ }
6160
+ function encodeDateToTimeSpec(date) {
6161
+ var msec = date.getTime();
6162
+ var sec = Math.floor(msec / 1e3);
6163
+ var nsec = (msec - sec * 1e3) * 1e6;
6164
+ // Normalizes { sec, nsec } to ensure nsec is unsigned.
6165
+ var nsecInSec = Math.floor(nsec / 1e9);
6166
+ return {
6167
+ sec: sec + nsecInSec,
6168
+ nsec: nsec - nsecInSec * 1e9,
6997
6169
  };
6998
- Encoder.prototype.countWithoutUndefined = function (object, keys) {
6999
- var count = 0;
7000
- for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
7001
- var key = keys_1[_i];
7002
- if (object[key] !== undefined) {
7003
- count++;
7004
- }
6170
+ }
6171
+ function encodeTimestampExtension(object) {
6172
+ if (object instanceof Date) {
6173
+ var timeSpec = encodeDateToTimeSpec(object);
6174
+ return encodeTimeSpecToTimestamp(timeSpec);
6175
+ }
6176
+ else {
6177
+ return null;
6178
+ }
6179
+ }
6180
+ function decodeTimestampToTimeSpec(data) {
6181
+ var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
6182
+ // data may be 32, 64, or 96 bits
6183
+ switch (data.byteLength) {
6184
+ case 4: {
6185
+ // timestamp 32 = { sec32 }
6186
+ var sec = view.getUint32(0);
6187
+ var nsec = 0;
6188
+ return { sec: sec, nsec: nsec };
7005
6189
  }
7006
- return count;
7007
- };
7008
- Encoder.prototype.encodeMap = function (object, depth) {
7009
- var keys = Object.keys(object);
7010
- if (this.sortKeys) {
7011
- keys.sort();
6190
+ case 8: {
6191
+ // timestamp 64 = { nsec30, sec34 }
6192
+ var nsec30AndSecHigh2 = view.getUint32(0);
6193
+ var secLow32 = view.getUint32(4);
6194
+ var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
6195
+ var nsec = nsec30AndSecHigh2 >>> 2;
6196
+ return { sec: sec, nsec: nsec };
7012
6197
  }
7013
- var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
7014
- if (size < 16) {
7015
- // fixmap
7016
- this.writeU8(0x80 + size);
6198
+ case 12: {
6199
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
6200
+ var sec = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.getInt64)(view, 4);
6201
+ var nsec = view.getUint32(0);
6202
+ return { sec: sec, nsec: nsec };
7017
6203
  }
7018
- else if (size < 0x10000) {
7019
- // map 16
7020
- this.writeU8(0xde);
7021
- this.writeU16(size);
6204
+ default:
6205
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
6206
+ }
6207
+ }
6208
+ function decodeTimestampExtension(data) {
6209
+ var timeSpec = decodeTimestampToTimeSpec(data);
6210
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
6211
+ }
6212
+ var timestampExtension = {
6213
+ type: EXT_TIMESTAMP,
6214
+ encode: encodeTimestampExtension,
6215
+ decode: decodeTimestampExtension,
6216
+ };
6217
+ //# sourceMappingURL=timestamp.mjs.map
6218
+
6219
+ /***/ }),
6220
+
6221
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
6222
+ /*!******************************************************************!*\
6223
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs ***!
6224
+ \******************************************************************/
6225
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6226
+
6227
+ __webpack_require__.r(__webpack_exports__);
6228
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6229
+ /* harmony export */ UINT32_MAX: () => (/* binding */ UINT32_MAX),
6230
+ /* harmony export */ getInt64: () => (/* binding */ getInt64),
6231
+ /* harmony export */ getUint64: () => (/* binding */ getUint64),
6232
+ /* harmony export */ setInt64: () => (/* binding */ setInt64),
6233
+ /* harmony export */ setUint64: () => (/* binding */ setUint64)
6234
+ /* harmony export */ });
6235
+ // Integer Utility
6236
+ var UINT32_MAX = 4294967295;
6237
+ // DataView extension to handle int64 / uint64,
6238
+ // where the actual range is 53-bits integer (a.k.a. safe integer)
6239
+ function setUint64(view, offset, value) {
6240
+ var high = value / 4294967296;
6241
+ var low = value; // high bits are truncated by DataView
6242
+ view.setUint32(offset, high);
6243
+ view.setUint32(offset + 4, low);
6244
+ }
6245
+ function setInt64(view, offset, value) {
6246
+ var high = Math.floor(value / 4294967296);
6247
+ var low = value; // high bits are truncated by DataView
6248
+ view.setUint32(offset, high);
6249
+ view.setUint32(offset + 4, low);
6250
+ }
6251
+ function getInt64(view, offset) {
6252
+ var high = view.getInt32(offset);
6253
+ var low = view.getUint32(offset + 4);
6254
+ return high * 4294967296 + low;
6255
+ }
6256
+ function getUint64(view, offset) {
6257
+ var high = view.getUint32(offset);
6258
+ var low = view.getUint32(offset + 4);
6259
+ return high * 4294967296 + low;
6260
+ }
6261
+ //# sourceMappingURL=int.mjs.map
6262
+
6263
+ /***/ }),
6264
+
6265
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
6266
+ /*!*************************************************************************!*\
6267
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs ***!
6268
+ \*************************************************************************/
6269
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6270
+
6271
+ __webpack_require__.r(__webpack_exports__);
6272
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6273
+ /* harmony export */ prettyByte: () => (/* binding */ prettyByte)
6274
+ /* harmony export */ });
6275
+ function prettyByte(byte) {
6276
+ return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0"));
6277
+ }
6278
+ //# sourceMappingURL=prettyByte.mjs.map
6279
+
6280
+ /***/ }),
6281
+
6282
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs":
6283
+ /*!**************************************************************************!*\
6284
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs ***!
6285
+ \**************************************************************************/
6286
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6287
+
6288
+ __webpack_require__.r(__webpack_exports__);
6289
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6290
+ /* harmony export */ createDataView: () => (/* binding */ createDataView),
6291
+ /* harmony export */ ensureUint8Array: () => (/* binding */ ensureUint8Array)
6292
+ /* harmony export */ });
6293
+ function ensureUint8Array(buffer) {
6294
+ if (buffer instanceof Uint8Array) {
6295
+ return buffer;
6296
+ }
6297
+ else if (ArrayBuffer.isView(buffer)) {
6298
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
6299
+ }
6300
+ else if (buffer instanceof ArrayBuffer) {
6301
+ return new Uint8Array(buffer);
6302
+ }
6303
+ else {
6304
+ // ArrayLike<number>
6305
+ return Uint8Array.from(buffer);
6306
+ }
6307
+ }
6308
+ function createDataView(buffer) {
6309
+ if (buffer instanceof ArrayBuffer) {
6310
+ return new DataView(buffer);
6311
+ }
6312
+ var bufferView = ensureUint8Array(buffer);
6313
+ return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
6314
+ }
6315
+ //# sourceMappingURL=typedArrays.mjs.map
6316
+
6317
+ /***/ }),
6318
+
6319
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs":
6320
+ /*!*******************************************************************!*\
6321
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs ***!
6322
+ \*******************************************************************/
6323
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6324
+
6325
+ __webpack_require__.r(__webpack_exports__);
6326
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6327
+ /* harmony export */ TEXT_DECODER_THRESHOLD: () => (/* binding */ TEXT_DECODER_THRESHOLD),
6328
+ /* harmony export */ TEXT_ENCODER_THRESHOLD: () => (/* binding */ TEXT_ENCODER_THRESHOLD),
6329
+ /* harmony export */ utf8Count: () => (/* binding */ utf8Count),
6330
+ /* harmony export */ utf8DecodeJs: () => (/* binding */ utf8DecodeJs),
6331
+ /* harmony export */ utf8DecodeTD: () => (/* binding */ utf8DecodeTD),
6332
+ /* harmony export */ utf8EncodeJs: () => (/* binding */ utf8EncodeJs),
6333
+ /* harmony export */ utf8EncodeTE: () => (/* binding */ utf8EncodeTE)
6334
+ /* harmony export */ });
6335
+ /* harmony import */ var _int_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
6336
+ var _a, _b, _c;
6337
+ /* eslint-disable @typescript-eslint/no-unnecessary-condition */
6338
+
6339
+ var TEXT_ENCODING_AVAILABLE = (typeof process === "undefined" || ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a["TEXT_ENCODING"]) !== "never") &&
6340
+ typeof TextEncoder !== "undefined" &&
6341
+ typeof TextDecoder !== "undefined";
6342
+ function utf8Count(str) {
6343
+ var strLength = str.length;
6344
+ var byteLength = 0;
6345
+ var pos = 0;
6346
+ while (pos < strLength) {
6347
+ var value = str.charCodeAt(pos++);
6348
+ if ((value & 0xffffff80) === 0) {
6349
+ // 1-byte
6350
+ byteLength++;
6351
+ continue;
7022
6352
  }
7023
- else if (size < 0x100000000) {
7024
- // map 32
7025
- this.writeU8(0xdf);
7026
- this.writeU32(size);
6353
+ else if ((value & 0xfffff800) === 0) {
6354
+ // 2-bytes
6355
+ byteLength += 2;
7027
6356
  }
7028
6357
  else {
7029
- throw new Error("Too large map object: ".concat(size));
7030
- }
7031
- for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
7032
- var key = keys_2[_i];
7033
- var value = object[key];
7034
- if (!(this.ignoreUndefined && value === undefined)) {
7035
- this.encodeString(key);
7036
- this.doEncode(value, depth + 1);
6358
+ // handle surrogate pair
6359
+ if (value >= 0xd800 && value <= 0xdbff) {
6360
+ // high surrogate
6361
+ if (pos < strLength) {
6362
+ var extra = str.charCodeAt(pos);
6363
+ if ((extra & 0xfc00) === 0xdc00) {
6364
+ ++pos;
6365
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
6366
+ }
6367
+ }
6368
+ }
6369
+ if ((value & 0xffff0000) === 0) {
6370
+ // 3-byte
6371
+ byteLength += 3;
6372
+ }
6373
+ else {
6374
+ // 4-byte
6375
+ byteLength += 4;
7037
6376
  }
7038
6377
  }
7039
- };
7040
- Encoder.prototype.encodeExtension = function (ext) {
7041
- var size = ext.data.length;
7042
- if (size === 1) {
7043
- // fixext 1
7044
- this.writeU8(0xd4);
7045
- }
7046
- else if (size === 2) {
7047
- // fixext 2
7048
- this.writeU8(0xd5);
6378
+ }
6379
+ return byteLength;
6380
+ }
6381
+ function utf8EncodeJs(str, output, outputOffset) {
6382
+ var strLength = str.length;
6383
+ var offset = outputOffset;
6384
+ var pos = 0;
6385
+ while (pos < strLength) {
6386
+ var value = str.charCodeAt(pos++);
6387
+ if ((value & 0xffffff80) === 0) {
6388
+ // 1-byte
6389
+ output[offset++] = value;
6390
+ continue;
7049
6391
  }
7050
- else if (size === 4) {
7051
- // fixext 4
7052
- this.writeU8(0xd6);
6392
+ else if ((value & 0xfffff800) === 0) {
6393
+ // 2-bytes
6394
+ output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
7053
6395
  }
7054
- else if (size === 8) {
7055
- // fixext 8
7056
- this.writeU8(0xd7);
6396
+ else {
6397
+ // handle surrogate pair
6398
+ if (value >= 0xd800 && value <= 0xdbff) {
6399
+ // high surrogate
6400
+ if (pos < strLength) {
6401
+ var extra = str.charCodeAt(pos);
6402
+ if ((extra & 0xfc00) === 0xdc00) {
6403
+ ++pos;
6404
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
6405
+ }
6406
+ }
6407
+ }
6408
+ if ((value & 0xffff0000) === 0) {
6409
+ // 3-byte
6410
+ output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
6411
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
6412
+ }
6413
+ else {
6414
+ // 4-byte
6415
+ output[offset++] = ((value >> 18) & 0x07) | 0xf0;
6416
+ output[offset++] = ((value >> 12) & 0x3f) | 0x80;
6417
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
6418
+ }
7057
6419
  }
7058
- else if (size === 16) {
7059
- // fixext 16
7060
- this.writeU8(0xd8);
6420
+ output[offset++] = (value & 0x3f) | 0x80;
6421
+ }
6422
+ }
6423
+ var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
6424
+ var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
6425
+ ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
6426
+ : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force"
6427
+ ? 200
6428
+ : 0;
6429
+ function utf8EncodeTEencode(str, output, outputOffset) {
6430
+ output.set(sharedTextEncoder.encode(str), outputOffset);
6431
+ }
6432
+ function utf8EncodeTEencodeInto(str, output, outputOffset) {
6433
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
6434
+ }
6435
+ var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
6436
+ var CHUNK_SIZE = 4096;
6437
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
6438
+ var offset = inputOffset;
6439
+ var end = offset + byteLength;
6440
+ var units = [];
6441
+ var result = "";
6442
+ while (offset < end) {
6443
+ var byte1 = bytes[offset++];
6444
+ if ((byte1 & 0x80) === 0) {
6445
+ // 1 byte
6446
+ units.push(byte1);
7061
6447
  }
7062
- else if (size < 0x100) {
7063
- // ext 8
7064
- this.writeU8(0xc7);
7065
- this.writeU8(size);
6448
+ else if ((byte1 & 0xe0) === 0xc0) {
6449
+ // 2 bytes
6450
+ var byte2 = bytes[offset++] & 0x3f;
6451
+ units.push(((byte1 & 0x1f) << 6) | byte2);
7066
6452
  }
7067
- else if (size < 0x10000) {
7068
- // ext 16
7069
- this.writeU8(0xc8);
7070
- this.writeU16(size);
6453
+ else if ((byte1 & 0xf0) === 0xe0) {
6454
+ // 3 bytes
6455
+ var byte2 = bytes[offset++] & 0x3f;
6456
+ var byte3 = bytes[offset++] & 0x3f;
6457
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
7071
6458
  }
7072
- else if (size < 0x100000000) {
7073
- // ext 32
7074
- this.writeU8(0xc9);
7075
- this.writeU32(size);
6459
+ else if ((byte1 & 0xf8) === 0xf0) {
6460
+ // 4 bytes
6461
+ var byte2 = bytes[offset++] & 0x3f;
6462
+ var byte3 = bytes[offset++] & 0x3f;
6463
+ var byte4 = bytes[offset++] & 0x3f;
6464
+ var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
6465
+ if (unit > 0xffff) {
6466
+ unit -= 0x10000;
6467
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
6468
+ unit = 0xdc00 | (unit & 0x3ff);
6469
+ }
6470
+ units.push(unit);
7076
6471
  }
7077
6472
  else {
7078
- throw new Error("Too large extension object: ".concat(size));
6473
+ units.push(byte1);
7079
6474
  }
7080
- this.writeI8(ext.type);
7081
- this.writeU8a(ext.data);
7082
- };
7083
- Encoder.prototype.writeU8 = function (value) {
7084
- this.ensureBufferSizeToWrite(1);
7085
- this.view.setUint8(this.pos, value);
7086
- this.pos++;
7087
- };
7088
- Encoder.prototype.writeU8a = function (values) {
7089
- var size = values.length;
7090
- this.ensureBufferSizeToWrite(size);
7091
- this.bytes.set(values, this.pos);
7092
- this.pos += size;
7093
- };
7094
- Encoder.prototype.writeI8 = function (value) {
7095
- this.ensureBufferSizeToWrite(1);
7096
- this.view.setInt8(this.pos, value);
7097
- this.pos++;
7098
- };
7099
- Encoder.prototype.writeU16 = function (value) {
7100
- this.ensureBufferSizeToWrite(2);
7101
- this.view.setUint16(this.pos, value);
7102
- this.pos += 2;
7103
- };
7104
- Encoder.prototype.writeI16 = function (value) {
7105
- this.ensureBufferSizeToWrite(2);
7106
- this.view.setInt16(this.pos, value);
7107
- this.pos += 2;
7108
- };
7109
- Encoder.prototype.writeU32 = function (value) {
7110
- this.ensureBufferSizeToWrite(4);
7111
- this.view.setUint32(this.pos, value);
7112
- this.pos += 4;
7113
- };
7114
- Encoder.prototype.writeI32 = function (value) {
7115
- this.ensureBufferSizeToWrite(4);
7116
- this.view.setInt32(this.pos, value);
7117
- this.pos += 4;
7118
- };
7119
- Encoder.prototype.writeF32 = function (value) {
7120
- this.ensureBufferSizeToWrite(4);
7121
- this.view.setFloat32(this.pos, value);
7122
- this.pos += 4;
7123
- };
7124
- Encoder.prototype.writeF64 = function (value) {
7125
- this.ensureBufferSizeToWrite(8);
7126
- this.view.setFloat64(this.pos, value);
7127
- this.pos += 8;
7128
- };
7129
- Encoder.prototype.writeU64 = function (value) {
7130
- this.ensureBufferSizeToWrite(8);
7131
- (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setUint64)(this.view, this.pos, value);
7132
- this.pos += 8;
7133
- };
7134
- Encoder.prototype.writeI64 = function (value) {
7135
- this.ensureBufferSizeToWrite(8);
7136
- (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setInt64)(this.view, this.pos, value);
7137
- this.pos += 8;
7138
- };
7139
- return Encoder;
7140
- }());
6475
+ if (units.length >= CHUNK_SIZE) {
6476
+ result += String.fromCharCode.apply(String, units);
6477
+ units.length = 0;
6478
+ }
6479
+ }
6480
+ if (units.length > 0) {
6481
+ result += String.fromCharCode.apply(String, units);
6482
+ }
6483
+ return result;
6484
+ }
6485
+ var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
6486
+ var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
6487
+ ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
6488
+ : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force"
6489
+ ? 200
6490
+ : 0;
6491
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
6492
+ var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
6493
+ return sharedTextDecoder.decode(stringBytes);
6494
+ }
6495
+ //# sourceMappingURL=utf8.mjs.map
6496
+
6497
+ /***/ })
6498
+
6499
+ /******/ });
6500
+ /************************************************************************/
6501
+ /******/ // The module cache
6502
+ /******/ var __webpack_module_cache__ = {};
6503
+ /******/
6504
+ /******/ // The require function
6505
+ /******/ function __webpack_require__(moduleId) {
6506
+ /******/ // Check if module is in cache
6507
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
6508
+ /******/ if (cachedModule !== undefined) {
6509
+ /******/ return cachedModule.exports;
6510
+ /******/ }
6511
+ /******/ // Create a new module (and put it into the cache)
6512
+ /******/ var module = __webpack_module_cache__[moduleId] = {
6513
+ /******/ // no module.id needed
6514
+ /******/ // no module.loaded needed
6515
+ /******/ exports: {}
6516
+ /******/ };
6517
+ /******/
6518
+ /******/ // Execute the module function
6519
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
6520
+ /******/
6521
+ /******/ // Return the exports of the module
6522
+ /******/ return module.exports;
6523
+ /******/ }
6524
+ /******/
6525
+ /************************************************************************/
6526
+ /******/ /* webpack/runtime/define property getters */
6527
+ /******/ (() => {
6528
+ /******/ // define getter functions for harmony exports
6529
+ /******/ __webpack_require__.d = (exports, definition) => {
6530
+ /******/ for(var key in definition) {
6531
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
6532
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
6533
+ /******/ }
6534
+ /******/ }
6535
+ /******/ };
6536
+ /******/ })();
6537
+ /******/
6538
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
6539
+ /******/ (() => {
6540
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
6541
+ /******/ })();
6542
+ /******/
6543
+ /******/ /* webpack/runtime/make namespace object */
6544
+ /******/ (() => {
6545
+ /******/ // define __esModule on exports
6546
+ /******/ __webpack_require__.r = (exports) => {
6547
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
6548
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
6549
+ /******/ }
6550
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
6551
+ /******/ };
6552
+ /******/ })();
6553
+ /******/
6554
+ /************************************************************************/
6555
+ var __webpack_exports__ = {};
6556
+ /*!*********************************!*\
6557
+ !*** ./src/websocket-client.js ***!
6558
+ \*********************************/
6559
+ __webpack_require__.r(__webpack_exports__);
6560
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
6561
+ /* harmony export */ API_VERSION: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION),
6562
+ /* harmony export */ HTTPStreamingRPCConnection: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_4__.HTTPStreamingRPCConnection),
6563
+ /* harmony export */ LocalWebSocket: () => (/* binding */ LocalWebSocket),
6564
+ /* harmony export */ RPC: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC),
6565
+ /* harmony export */ connectToServer: () => (/* binding */ connectToServer),
6566
+ /* harmony export */ connectToServerHTTP: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP),
6567
+ /* harmony export */ getRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService),
6568
+ /* harmony export */ getRemoteService: () => (/* binding */ getRemoteService),
6569
+ /* harmony export */ getRemoteServiceHTTP: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_4__.getRemoteServiceHTTP),
6570
+ /* harmony export */ loadRequirements: () => (/* reexport safe */ _utils_index_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements),
6571
+ /* harmony export */ login: () => (/* binding */ login),
6572
+ /* harmony export */ logout: () => (/* binding */ logout),
6573
+ /* harmony export */ normalizeServerUrlHTTP: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_4__.normalizeServerUrl),
6574
+ /* harmony export */ registerRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService),
6575
+ /* harmony export */ schemaFunction: () => (/* reexport safe */ _utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction),
6576
+ /* harmony export */ setupLocalClient: () => (/* binding */ setupLocalClient)
6577
+ /* harmony export */ });
6578
+ /* harmony import */ var _rpc_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./rpc.js */ "./src/rpc.js");
6579
+ /* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/index.js */ "./src/utils/index.js");
6580
+ /* harmony import */ var _utils_schema_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/schema.js */ "./src/utils/schema.js");
6581
+ /* harmony import */ var _webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webrtc-client.js */ "./src/webrtc-client.js");
6582
+ /* harmony import */ var _http_client_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./http-client.js */ "./src/http-client.js");
7141
6583
 
7142
- //# sourceMappingURL=Encoder.mjs.map
7143
6584
 
7144
- /***/ }),
7145
6585
 
7146
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
7147
- /*!****************************************************************!*\
7148
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs ***!
7149
- \****************************************************************/
7150
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7151
6586
 
7152
- __webpack_require__.r(__webpack_exports__);
7153
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7154
- /* harmony export */ ExtData: () => (/* binding */ ExtData)
7155
- /* harmony export */ });
7156
- /**
7157
- * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
7158
- */
7159
- var ExtData = /** @class */ (function () {
7160
- function ExtData(type, data) {
7161
- this.type = type;
7162
- this.data = data;
7163
- }
7164
- return ExtData;
7165
- }());
7166
6587
 
7167
- //# sourceMappingURL=ExtData.mjs.map
6588
+ // Import HTTP client for internal use and re-export
7168
6589
 
7169
- /***/ }),
7170
6590
 
7171
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs":
7172
- /*!***********************************************************************!*\
7173
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs ***!
7174
- \***********************************************************************/
7175
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6591
+ // Re-export HTTP client classes and functions
7176
6592
 
7177
- __webpack_require__.r(__webpack_exports__);
7178
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7179
- /* harmony export */ ExtensionCodec: () => (/* binding */ ExtensionCodec)
7180
- /* harmony export */ });
7181
- /* harmony import */ var _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtData.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs");
7182
- /* harmony import */ var _timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./timestamp.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs");
7183
- // ExtensionCodec to handle MessagePack extensions
7184
6593
 
7185
6594
 
7186
- var ExtensionCodec = /** @class */ (function () {
7187
- function ExtensionCodec() {
7188
- // built-in extensions
7189
- this.builtInEncoders = [];
7190
- this.builtInDecoders = [];
7191
- // custom extensions
7192
- this.encoders = [];
7193
- this.decoders = [];
7194
- this.register(_timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__.timestampExtension);
6595
+
6596
+
6597
+
6598
+ const MAX_RETRY = 1000000;
6599
+
6600
+ class WebsocketRPCConnection {
6601
+ constructor(
6602
+ server_url,
6603
+ client_id,
6604
+ workspace,
6605
+ token,
6606
+ reconnection_token = null,
6607
+ timeout = 60,
6608
+ WebSocketClass = null,
6609
+ token_refresh_interval = 2 * 60 * 60,
6610
+ additional_headers = null,
6611
+ ) {
6612
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(server_url && client_id, "server_url and client_id are required");
6613
+ this._server_url = server_url;
6614
+ this._client_id = client_id;
6615
+ this._workspace = workspace;
6616
+ this._token = token;
6617
+ this._reconnection_token = reconnection_token;
6618
+ this._websocket = null;
6619
+ this._handle_message = null;
6620
+ this._handle_connected = null; // Connection open event handler
6621
+ this._handle_disconnected = null; // Disconnection event handler
6622
+ this._timeout = timeout;
6623
+ this._WebSocketClass = WebSocketClass || WebSocket; // Allow overriding the WebSocket class
6624
+ this._closed = false;
6625
+ this._legacy_auth = null;
6626
+ this.connection_info = null;
6627
+ this._enable_reconnect = false;
6628
+ this._token_refresh_interval = token_refresh_interval;
6629
+ this.manager_id = null;
6630
+ this._refresh_token_task = null;
6631
+ this._last_message = null; // Store the last sent message
6632
+ this._reconnect_timeouts = new Set(); // Track reconnection timeouts
6633
+ this._additional_headers = additional_headers;
6634
+ }
6635
+
6636
+ /**
6637
+ * Centralized cleanup method to clear all timers and prevent resource leaks
6638
+ */
6639
+ _cleanup() {
6640
+ // Clear token refresh interval
6641
+ if (this._refresh_token_task) {
6642
+ clearInterval(this._refresh_token_task);
6643
+ this._refresh_token_task = null;
7195
6644
  }
7196
- ExtensionCodec.prototype.register = function (_a) {
7197
- var type = _a.type, encode = _a.encode, decode = _a.decode;
7198
- if (type >= 0) {
7199
- // custom extensions
7200
- this.encoders[type] = encode;
7201
- this.decoders[type] = decode;
7202
- }
7203
- else {
7204
- // built-in extensions
7205
- var index = 1 + type;
7206
- this.builtInEncoders[index] = encode;
7207
- this.builtInDecoders[index] = decode;
7208
- }
7209
- };
7210
- ExtensionCodec.prototype.tryToEncode = function (object, context) {
7211
- // built-in extensions
7212
- for (var i = 0; i < this.builtInEncoders.length; i++) {
7213
- var encodeExt = this.builtInEncoders[i];
7214
- if (encodeExt != null) {
7215
- var data = encodeExt(object, context);
7216
- if (data != null) {
7217
- var type = -1 - i;
7218
- return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
7219
- }
7220
- }
6645
+
6646
+ // Clear all reconnection timeouts
6647
+ for (const timeoutId of this._reconnect_timeouts) {
6648
+ clearTimeout(timeoutId);
6649
+ }
6650
+ this._reconnect_timeouts.clear();
6651
+ }
6652
+
6653
+ on_message(handler) {
6654
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(handler, "handler is required");
6655
+ this._handle_message = handler;
6656
+ }
6657
+
6658
+ on_connected(handler) {
6659
+ this._handle_connected = handler;
6660
+ }
6661
+
6662
+ on_disconnected(handler) {
6663
+ this._handle_disconnected = handler;
6664
+ }
6665
+
6666
+ async _attempt_connection(server_url, attempt_fallback = true) {
6667
+ return new Promise((resolve, reject) => {
6668
+ this._legacy_auth = false;
6669
+ const websocket = new this._WebSocketClass(server_url);
6670
+ websocket.binaryType = "arraybuffer";
6671
+
6672
+ websocket.onopen = () => {
6673
+ console.info("WebSocket connection established");
6674
+ resolve(websocket);
6675
+ };
6676
+
6677
+ websocket.onerror = (event) => {
6678
+ console.error("WebSocket connection error:", event);
6679
+ reject(new Error(`WebSocket connection error: ${event}`));
6680
+ };
6681
+
6682
+ websocket.onclose = (event) => {
6683
+ if (event.code === 1003 && attempt_fallback) {
6684
+ console.info(
6685
+ "Received 1003 error, attempting connection with query parameters.",
6686
+ );
6687
+ this._legacy_auth = true;
6688
+ this._attempt_connection_with_query_params(server_url)
6689
+ .then(resolve)
6690
+ .catch(reject);
6691
+ } else if (this._handle_disconnected) {
6692
+ this._handle_disconnected(event.reason);
7221
6693
  }
7222
- // custom extensions
7223
- for (var i = 0; i < this.encoders.length; i++) {
7224
- var encodeExt = this.encoders[i];
7225
- if (encodeExt != null) {
7226
- var data = encodeExt(object, context);
7227
- if (data != null) {
7228
- var type = i;
7229
- return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
7230
- }
6694
+ };
6695
+ });
6696
+ }
6697
+
6698
+ async _attempt_connection_with_query_params(server_url) {
6699
+ // Initialize an array to hold parts of the query string
6700
+ const queryParamsParts = [];
6701
+
6702
+ // Conditionally add each parameter if it has a non-empty value
6703
+ if (this._client_id)
6704
+ queryParamsParts.push(`client_id=${encodeURIComponent(this._client_id)}`);
6705
+ if (this._workspace)
6706
+ queryParamsParts.push(`workspace=${encodeURIComponent(this._workspace)}`);
6707
+ if (this._token)
6708
+ queryParamsParts.push(`token=${encodeURIComponent(this._token)}`);
6709
+ if (this._reconnection_token)
6710
+ queryParamsParts.push(
6711
+ `reconnection_token=${encodeURIComponent(this._reconnection_token)}`,
6712
+ );
6713
+
6714
+ // Join the parts with '&' to form the final query string, prepend '?' if there are any parameters
6715
+ const queryString =
6716
+ queryParamsParts.length > 0 ? `?${queryParamsParts.join("&")}` : "";
6717
+
6718
+ // Construct the full URL by appending the query string if it exists
6719
+ const full_url = server_url + queryString;
6720
+
6721
+ return await this._attempt_connection(full_url, false);
6722
+ }
6723
+
6724
+ _establish_connection() {
6725
+ return new Promise((resolve, reject) => {
6726
+ this._websocket.onmessage = (event) => {
6727
+ const data = event.data;
6728
+ const first_message = JSON.parse(data);
6729
+ if (first_message.type == "connection_info") {
6730
+ this.connection_info = first_message;
6731
+ if (this._workspace) {
6732
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
6733
+ this.connection_info.workspace === this._workspace,
6734
+ `Connected to the wrong workspace: ${this.connection_info.workspace}, expected: ${this._workspace}`,
6735
+ );
6736
+ }
6737
+ if (this.connection_info.reconnection_token) {
6738
+ this._reconnection_token = this.connection_info.reconnection_token;
6739
+ }
6740
+ if (this.connection_info.reconnection_token_life_time) {
6741
+ // make sure the token refresh interval is less than the token life time
6742
+ if (
6743
+ this.token_refresh_interval >
6744
+ this.connection_info.reconnection_token_life_time / 1.5
6745
+ ) {
6746
+ console.warn(
6747
+ `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}).`,
6748
+ );
6749
+ this.token_refresh_interval =
6750
+ this.connection_info.reconnection_token_life_time / 1.5;
7231
6751
  }
6752
+ }
6753
+ this.manager_id = this.connection_info.manager_id || null;
6754
+ console.log(
6755
+ `Successfully connected to the server, workspace: ${this.connection_info.workspace}, manager_id: ${this.manager_id}`,
6756
+ );
6757
+ if (this.connection_info.announcement) {
6758
+ console.log(`${this.connection_info.announcement}`);
6759
+ }
6760
+ resolve(this.connection_info);
6761
+ } else if (first_message.type == "error") {
6762
+ const error = "ConnectionAbortedError: " + first_message.message;
6763
+ console.error("Failed to connect, " + error);
6764
+ reject(new Error(error));
6765
+ return;
6766
+ } else {
6767
+ console.error(
6768
+ "ConnectionAbortedError: Unexpected message received from the server:",
6769
+ data,
6770
+ );
6771
+ reject(
6772
+ new Error(
6773
+ "ConnectionAbortedError: Unexpected message received from the server",
6774
+ ),
6775
+ );
6776
+ return;
7232
6777
  }
7233
- if (object instanceof _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData) {
7234
- // to keep ExtData as is
7235
- return object;
7236
- }
7237
- return null;
7238
- };
7239
- ExtensionCodec.prototype.decode = function (data, type, context) {
7240
- var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
7241
- if (decodeExt) {
7242
- return decodeExt(data, type, context);
7243
- }
7244
- else {
7245
- // decode() does not fail, returns ExtData instead.
7246
- return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
6778
+ };
6779
+ });
6780
+ }
6781
+
6782
+ async open() {
6783
+ console.log(
6784
+ "Creating a new websocket connection to",
6785
+ this._server_url.split("?")[0],
6786
+ );
6787
+ try {
6788
+ this._websocket = await this._attempt_connection(this._server_url);
6789
+ if (this._legacy_auth) {
6790
+ throw new Error(
6791
+ "NotImplementedError: Legacy authentication is not supported",
6792
+ );
6793
+ }
6794
+ // Send authentication info as the first message if connected without query params
6795
+ const authInfo = JSON.stringify({
6796
+ client_id: this._client_id,
6797
+ workspace: this._workspace,
6798
+ token: this._token,
6799
+ reconnection_token: this._reconnection_token,
6800
+ });
6801
+ this._websocket.send(authInfo);
6802
+ // Wait for the first message from the server
6803
+ await (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.waitFor)(
6804
+ this._establish_connection(),
6805
+ this._timeout,
6806
+ "Failed to receive the first message from the server",
6807
+ );
6808
+ if (this._token_refresh_interval > 0) {
6809
+ setTimeout(() => {
6810
+ this._send_refresh_token();
6811
+ this._refresh_token_task = setInterval(() => {
6812
+ this._send_refresh_token();
6813
+ }, this._token_refresh_interval * 1000);
6814
+ }, 2000);
6815
+ }
6816
+ // Listen to messages from the server
6817
+ this._enable_reconnect = true;
6818
+ this._closed = false;
6819
+ this._websocket.onmessage = (event) => {
6820
+ if (typeof event.data === "string") {
6821
+ const parsedData = JSON.parse(event.data);
6822
+ // Check if the message is a reconnection token
6823
+ if (parsedData.type === "reconnection_token") {
6824
+ this._reconnection_token = parsedData.reconnection_token;
6825
+ // console.log("Reconnection token received");
6826
+ } else {
6827
+ console.log("Received message from the server:", parsedData);
6828
+ }
6829
+ } else {
6830
+ this._handle_message(event.data);
7247
6831
  }
7248
- };
7249
- ExtensionCodec.defaultCodec = new ExtensionCodec();
7250
- return ExtensionCodec;
7251
- }());
6832
+ };
7252
6833
 
7253
- //# sourceMappingURL=ExtensionCodec.mjs.map
6834
+ this._websocket.onerror = (event) => {
6835
+ console.error("WebSocket connection error:", event);
6836
+ // Clean up timers on error
6837
+ this._cleanup();
6838
+ };
7254
6839
 
7255
- /***/ }),
6840
+ this._websocket.onclose = this._handle_close.bind(this);
7256
6841
 
7257
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs":
7258
- /*!***************************************************************!*\
7259
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs ***!
7260
- \***************************************************************/
7261
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6842
+ if (this._handle_connected) {
6843
+ this._handle_connected(this.connection_info);
6844
+ }
6845
+ return this.connection_info;
6846
+ } catch (error) {
6847
+ // Clean up any timers that might have been set up before the error
6848
+ this._cleanup();
6849
+ console.error(
6850
+ "Failed to connect to",
6851
+ this._server_url.split("?")[0],
6852
+ error,
6853
+ );
6854
+ throw error;
6855
+ }
6856
+ }
7262
6857
 
7263
- __webpack_require__.r(__webpack_exports__);
7264
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7265
- /* harmony export */ decode: () => (/* binding */ decode),
7266
- /* harmony export */ decodeMulti: () => (/* binding */ decodeMulti),
7267
- /* harmony export */ defaultDecodeOptions: () => (/* binding */ defaultDecodeOptions)
7268
- /* harmony export */ });
7269
- /* harmony import */ var _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Decoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs");
6858
+ _send_refresh_token() {
6859
+ if (this._websocket && this._websocket.readyState === WebSocket.OPEN) {
6860
+ const refreshMessage = JSON.stringify({ type: "refresh_token" });
6861
+ this._websocket.send(refreshMessage);
6862
+ // console.log("Requested refresh token");
6863
+ }
6864
+ }
7270
6865
 
7271
- var defaultDecodeOptions = {};
7272
- /**
7273
- * It decodes a single MessagePack object in a buffer.
7274
- *
7275
- * This is a synchronous decoding function.
7276
- * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
7277
- *
7278
- * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
7279
- * @throws {@link DecodeError} if the buffer contains invalid data.
7280
- */
7281
- function decode(buffer, options) {
7282
- if (options === void 0) { options = defaultDecodeOptions; }
7283
- var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
7284
- return decoder.decode(buffer);
7285
- }
7286
- /**
7287
- * It decodes multiple MessagePack objects in a buffer.
7288
- * This is corresponding to {@link decodeMultiStream()}.
7289
- *
7290
- * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
7291
- * @throws {@link DecodeError} if the buffer contains invalid data.
7292
- */
7293
- function decodeMulti(buffer, options) {
7294
- if (options === void 0) { options = defaultDecodeOptions; }
7295
- var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
7296
- return decoder.decodeMulti(buffer);
7297
- }
7298
- //# sourceMappingURL=decode.mjs.map
6866
+ _handle_close(event) {
6867
+ if (
6868
+ !this._closed &&
6869
+ this._websocket &&
6870
+ this._websocket.readyState === WebSocket.CLOSED
6871
+ ) {
6872
+ // Clean up timers when connection closes
6873
+ this._cleanup();
7299
6874
 
7300
- /***/ }),
6875
+ // Even if it's a graceful closure (codes 1000, 1001), if it wasn't user-initiated,
6876
+ // we should attempt to reconnect (e.g., server restart, k8s upgrade)
6877
+ if (this._enable_reconnect) {
6878
+ if ([1000, 1001].includes(event.code)) {
6879
+ console.warn(
6880
+ `Websocket connection closed gracefully by server (code: ${event.code}): ${event.reason} - attempting reconnect`,
6881
+ );
6882
+ } else {
6883
+ console.warn(
6884
+ "Websocket connection closed unexpectedly (code: %s): %s",
6885
+ event.code,
6886
+ event.reason,
6887
+ );
6888
+ }
7301
6889
 
7302
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs":
7303
- /*!***************************************************************!*\
7304
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs ***!
7305
- \***************************************************************/
7306
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6890
+ let retry = 0;
6891
+ const baseDelay = 1000; // Start with 1 second
6892
+ const maxDelay = 60000; // Maximum delay of 60 seconds
6893
+ const maxJitter = 0.1; // Maximum jitter factor
7307
6894
 
7308
- __webpack_require__.r(__webpack_exports__);
7309
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7310
- /* harmony export */ encode: () => (/* binding */ encode)
7311
- /* harmony export */ });
7312
- /* harmony import */ var _Encoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Encoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs");
6895
+ const reconnect = async () => {
6896
+ // Check if we were explicitly closed
6897
+ if (this._closed) {
6898
+ console.info("Connection was closed, stopping reconnection");
6899
+ return;
6900
+ }
7313
6901
 
7314
- var defaultEncodeOptions = {};
7315
- /**
7316
- * It encodes `value` in the MessagePack format and
7317
- * returns a byte buffer.
7318
- *
7319
- * The returned buffer is a slice of a larger `ArrayBuffer`, so you have to use its `#byteOffset` and `#byteLength` in order to convert it to another typed arrays including NodeJS `Buffer`.
7320
- */
7321
- function encode(value, options) {
7322
- if (options === void 0) { options = defaultEncodeOptions; }
7323
- var encoder = new _Encoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Encoder(options.extensionCodec, options.context, options.maxDepth, options.initialBufferSize, options.sortKeys, options.forceFloat32, options.ignoreUndefined, options.forceIntegerToFloat);
7324
- return encoder.encodeSharedRef(value);
7325
- }
7326
- //# sourceMappingURL=encode.mjs.map
6902
+ try {
6903
+ console.warn(
6904
+ `Reconnecting to ${this._server_url.split("?")[0]} (attempt #${retry})`,
6905
+ );
6906
+ // Open the connection, this will trigger the on_connected callback
6907
+ await this.open();
7327
6908
 
7328
- /***/ }),
6909
+ // Wait a short time for services to be registered
6910
+ // This gives time for the on_connected callback to complete
6911
+ // which includes re-registering all services to the server
6912
+ await new Promise((resolve) => setTimeout(resolve, 500));
7329
6913
 
7330
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs":
7331
- /*!******************************************************************!*\
7332
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs ***!
7333
- \******************************************************************/
7334
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6914
+ // Resend last message if there was one
6915
+ if (this._last_message) {
6916
+ console.info("Resending last message after reconnection");
6917
+ this._websocket.send(this._last_message);
6918
+ this._last_message = null;
6919
+ }
6920
+ console.warn(
6921
+ `Successfully reconnected to server ${this._server_url} (services re-registered)`,
6922
+ );
6923
+ // Emit reconnection success event
6924
+ if (this._handle_connected) {
6925
+ this._handle_connected(this.connection_info);
6926
+ }
6927
+ } catch (e) {
6928
+ if (`${e}`.includes("ConnectionAbortedError:")) {
6929
+ console.warn("Server refused to reconnect:", e);
6930
+ // Mark as closed and notify the application
6931
+ this._closed = true;
6932
+ if (this._handle_disconnected) {
6933
+ this._handle_disconnected(`Server refused reconnection: ${e}`);
6934
+ }
6935
+ return;
6936
+ } else if (`${e}`.includes("NotImplementedError:")) {
6937
+ console.error(
6938
+ `${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`,
6939
+ );
6940
+ // Mark as closed to prevent further reconnection attempts
6941
+ this._closed = true;
6942
+ if (this._handle_disconnected) {
6943
+ this._handle_disconnected(`Server too old: ${e}`);
6944
+ }
6945
+ return;
6946
+ }
7335
6947
 
7336
- __webpack_require__.r(__webpack_exports__);
7337
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7338
- /* harmony export */ EXT_TIMESTAMP: () => (/* binding */ EXT_TIMESTAMP),
7339
- /* harmony export */ decodeTimestampExtension: () => (/* binding */ decodeTimestampExtension),
7340
- /* harmony export */ decodeTimestampToTimeSpec: () => (/* binding */ decodeTimestampToTimeSpec),
7341
- /* harmony export */ encodeDateToTimeSpec: () => (/* binding */ encodeDateToTimeSpec),
7342
- /* harmony export */ encodeTimeSpecToTimestamp: () => (/* binding */ encodeTimeSpecToTimestamp),
7343
- /* harmony export */ encodeTimestampExtension: () => (/* binding */ encodeTimestampExtension),
7344
- /* harmony export */ timestampExtension: () => (/* binding */ timestampExtension)
7345
- /* harmony export */ });
7346
- /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
7347
- /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
7348
- // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
6948
+ // Log specific error types for better debugging
6949
+ if (e.name === "NetworkError" || e.message.includes("network")) {
6950
+ console.error(`Network error during reconnection: ${e.message}`);
6951
+ } else if (
6952
+ e.name === "TimeoutError" ||
6953
+ e.message.includes("timeout")
6954
+ ) {
6955
+ console.error(
6956
+ `Connection timeout during reconnection: ${e.message}`,
6957
+ );
6958
+ } else {
6959
+ console.error(
6960
+ `Unexpected error during reconnection: ${e.message}`,
6961
+ );
6962
+ }
7349
6963
 
6964
+ // Calculate exponential backoff with jitter
6965
+ const delay = Math.min(baseDelay * Math.pow(2, retry), maxDelay);
6966
+ // Add jitter to prevent thundering herd
6967
+ const jitter = (Math.random() * 2 - 1) * maxJitter * delay;
6968
+ const finalDelay = Math.max(100, delay + jitter);
7350
6969
 
7351
- var EXT_TIMESTAMP = -1;
7352
- var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
7353
- var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
7354
- function encodeTimeSpecToTimestamp(_a) {
7355
- var sec = _a.sec, nsec = _a.nsec;
7356
- if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
7357
- // Here sec >= 0 && nsec >= 0
7358
- if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
7359
- // timestamp 32 = { sec32 (unsigned) }
7360
- var rv = new Uint8Array(4);
7361
- var view = new DataView(rv.buffer);
7362
- view.setUint32(0, sec);
7363
- return rv;
7364
- }
7365
- else {
7366
- // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
7367
- var secHigh = sec / 0x100000000;
7368
- var secLow = sec & 0xffffffff;
7369
- var rv = new Uint8Array(8);
7370
- var view = new DataView(rv.buffer);
7371
- // nsec30 | secHigh2
7372
- view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
7373
- // secLow32
7374
- view.setUint32(4, secLow);
7375
- return rv;
7376
- }
7377
- }
7378
- else {
7379
- // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
7380
- var rv = new Uint8Array(12);
7381
- var view = new DataView(rv.buffer);
7382
- view.setUint32(0, nsec);
7383
- (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.setInt64)(view, 4, sec);
7384
- return rv;
7385
- }
7386
- }
7387
- function encodeDateToTimeSpec(date) {
7388
- var msec = date.getTime();
7389
- var sec = Math.floor(msec / 1e3);
7390
- var nsec = (msec - sec * 1e3) * 1e6;
7391
- // Normalizes { sec, nsec } to ensure nsec is unsigned.
7392
- var nsecInSec = Math.floor(nsec / 1e9);
7393
- return {
7394
- sec: sec + nsecInSec,
7395
- nsec: nsec - nsecInSec * 1e9,
7396
- };
7397
- }
7398
- function encodeTimestampExtension(object) {
7399
- if (object instanceof Date) {
7400
- var timeSpec = encodeDateToTimeSpec(object);
7401
- return encodeTimeSpecToTimestamp(timeSpec);
7402
- }
7403
- else {
7404
- return null;
7405
- }
7406
- }
7407
- function decodeTimestampToTimeSpec(data) {
7408
- var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
7409
- // data may be 32, 64, or 96 bits
7410
- switch (data.byteLength) {
7411
- case 4: {
7412
- // timestamp 32 = { sec32 }
7413
- var sec = view.getUint32(0);
7414
- var nsec = 0;
7415
- return { sec: sec, nsec: nsec };
7416
- }
7417
- case 8: {
7418
- // timestamp 64 = { nsec30, sec34 }
7419
- var nsec30AndSecHigh2 = view.getUint32(0);
7420
- var secLow32 = view.getUint32(4);
7421
- var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
7422
- var nsec = nsec30AndSecHigh2 >>> 2;
7423
- return { sec: sec, nsec: nsec };
7424
- }
7425
- case 12: {
7426
- // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
7427
- var sec = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.getInt64)(view, 4);
7428
- var nsec = view.getUint32(0);
7429
- return { sec: sec, nsec: nsec };
7430
- }
7431
- default:
7432
- throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
7433
- }
7434
- }
7435
- function decodeTimestampExtension(data) {
7436
- var timeSpec = decodeTimestampToTimeSpec(data);
7437
- return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
7438
- }
7439
- var timestampExtension = {
7440
- type: EXT_TIMESTAMP,
7441
- encode: encodeTimestampExtension,
7442
- decode: decodeTimestampExtension,
7443
- };
7444
- //# sourceMappingURL=timestamp.mjs.map
6970
+ console.debug(
6971
+ `Waiting ${(finalDelay / 1000).toFixed(2)}s before next reconnection attempt`,
6972
+ );
7445
6973
 
7446
- /***/ }),
6974
+ // Track the reconnection timeout to prevent leaks
6975
+ const timeoutId = setTimeout(async () => {
6976
+ this._reconnect_timeouts.delete(timeoutId);
7447
6977
 
7448
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
7449
- /*!******************************************************************!*\
7450
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs ***!
7451
- \******************************************************************/
7452
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6978
+ // Check if connection was restored externally
6979
+ if (
6980
+ this._websocket &&
6981
+ this._websocket.readyState === WebSocket.OPEN
6982
+ ) {
6983
+ console.info("Connection restored externally");
6984
+ return;
6985
+ }
7453
6986
 
7454
- __webpack_require__.r(__webpack_exports__);
7455
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7456
- /* harmony export */ UINT32_MAX: () => (/* binding */ UINT32_MAX),
7457
- /* harmony export */ getInt64: () => (/* binding */ getInt64),
7458
- /* harmony export */ getUint64: () => (/* binding */ getUint64),
7459
- /* harmony export */ setInt64: () => (/* binding */ setInt64),
7460
- /* harmony export */ setUint64: () => (/* binding */ setUint64)
7461
- /* harmony export */ });
7462
- // Integer Utility
7463
- var UINT32_MAX = 4294967295;
7464
- // DataView extension to handle int64 / uint64,
7465
- // where the actual range is 53-bits integer (a.k.a. safe integer)
7466
- function setUint64(view, offset, value) {
7467
- var high = value / 4294967296;
7468
- var low = value; // high bits are truncated by DataView
7469
- view.setUint32(offset, high);
7470
- view.setUint32(offset + 4, low);
7471
- }
7472
- function setInt64(view, offset, value) {
7473
- var high = Math.floor(value / 4294967296);
7474
- var low = value; // high bits are truncated by DataView
7475
- view.setUint32(offset, high);
7476
- view.setUint32(offset + 4, low);
7477
- }
7478
- function getInt64(view, offset) {
7479
- var high = view.getInt32(offset);
7480
- var low = view.getUint32(offset + 4);
7481
- return high * 4294967296 + low;
7482
- }
7483
- function getUint64(view, offset) {
7484
- var high = view.getUint32(offset);
7485
- var low = view.getUint32(offset + 4);
7486
- return high * 4294967296 + low;
7487
- }
7488
- //# sourceMappingURL=int.mjs.map
6987
+ // Check if we were explicitly closed
6988
+ if (this._closed) {
6989
+ console.info("Connection was closed, stopping reconnection");
6990
+ return;
6991
+ }
7489
6992
 
7490
- /***/ }),
6993
+ retry += 1;
6994
+ if (retry < MAX_RETRY) {
6995
+ await reconnect();
6996
+ } else {
6997
+ console.error(
6998
+ `Failed to reconnect after ${MAX_RETRY} attempts, giving up.`,
6999
+ );
7000
+ // Mark as closed to prevent further reconnection attempts
7001
+ this._closed = true;
7002
+ // Notify about max retry exceeded
7003
+ if (this._handle_disconnected) {
7004
+ this._handle_disconnected(
7005
+ "Max reconnection attempts exceeded",
7006
+ );
7007
+ }
7008
+ // Note: We intentionally do NOT call process.exit() here.
7009
+ // Instead, we mark the connection as closed and let the
7010
+ // application handle the failure through the disconnected
7011
+ // handler or by checking connection state.
7012
+ }
7013
+ }, finalDelay);
7014
+ this._reconnect_timeouts.add(timeoutId);
7015
+ }
7016
+ };
7017
+ reconnect();
7018
+ }
7019
+ } else {
7020
+ // Clean up timers in all cases
7021
+ this._cleanup();
7022
+ if (this._handle_disconnected) {
7023
+ this._handle_disconnected(event.reason);
7024
+ }
7025
+ }
7026
+ }
7491
7027
 
7492
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
7493
- /*!*************************************************************************!*\
7494
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs ***!
7495
- \*************************************************************************/
7496
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7028
+ async emit_message(data) {
7029
+ if (this._closed) {
7030
+ throw new Error("Connection is closed");
7031
+ }
7032
+ if (!this._websocket || this._websocket.readyState !== WebSocket.OPEN) {
7033
+ await this.open();
7034
+ }
7035
+ try {
7036
+ this._last_message = data; // Store the message before sending
7037
+ this._websocket.send(data);
7038
+ this._last_message = null; // Clear after successful send
7039
+ } catch (exp) {
7040
+ console.error(`Failed to send data, error: ${exp}`);
7041
+ throw exp;
7042
+ }
7043
+ }
7497
7044
 
7498
- __webpack_require__.r(__webpack_exports__);
7499
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7500
- /* harmony export */ prettyByte: () => (/* binding */ prettyByte)
7501
- /* harmony export */ });
7502
- function prettyByte(byte) {
7503
- return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0"));
7045
+ disconnect(reason) {
7046
+ this._closed = true;
7047
+ this._last_message = null; // Clear last message on disconnect
7048
+ // Ensure websocket is closed if it exists and is not already closed or closing
7049
+ if (
7050
+ this._websocket &&
7051
+ this._websocket.readyState !== WebSocket.CLOSED &&
7052
+ this._websocket.readyState !== WebSocket.CLOSING
7053
+ ) {
7054
+ this._websocket.close(1000, reason);
7055
+ }
7056
+ // Use centralized cleanup to clear all timers
7057
+ this._cleanup();
7058
+ console.info(`WebSocket connection disconnected (${reason})`);
7059
+ }
7504
7060
  }
7505
- //# sourceMappingURL=prettyByte.mjs.map
7506
7061
 
7507
- /***/ }),
7062
+ function normalizeServerUrl(server_url) {
7063
+ if (!server_url) throw new Error("server_url is required");
7064
+ if (server_url.startsWith("http://")) {
7065
+ server_url =
7066
+ server_url.replace("http://", "ws://").replace(/\/$/, "") + "/ws";
7067
+ } else if (server_url.startsWith("https://")) {
7068
+ server_url =
7069
+ server_url.replace("https://", "wss://").replace(/\/$/, "") + "/ws";
7070
+ }
7071
+ return server_url;
7072
+ }
7508
7073
 
7509
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs":
7510
- /*!**************************************************************************!*\
7511
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs ***!
7512
- \**************************************************************************/
7513
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7074
+ async function login(config) {
7075
+ const service_id = config.login_service_id || "public/hypha-login";
7076
+ const workspace = config.workspace;
7077
+ const expires_in = config.expires_in;
7078
+ const timeout = config.login_timeout || 60;
7079
+ const callback = config.login_callback;
7080
+ const profile = config.profile;
7081
+ const additional_headers = config.additional_headers;
7514
7082
 
7515
- __webpack_require__.r(__webpack_exports__);
7516
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7517
- /* harmony export */ createDataView: () => (/* binding */ createDataView),
7518
- /* harmony export */ ensureUint8Array: () => (/* binding */ ensureUint8Array)
7519
- /* harmony export */ });
7520
- function ensureUint8Array(buffer) {
7521
- if (buffer instanceof Uint8Array) {
7522
- return buffer;
7523
- }
7524
- else if (ArrayBuffer.isView(buffer)) {
7525
- return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
7526
- }
7527
- else if (buffer instanceof ArrayBuffer) {
7528
- return new Uint8Array(buffer);
7529
- }
7530
- else {
7531
- // ArrayLike<number>
7532
- return Uint8Array.from(buffer);
7083
+ const server = await connectToServer({
7084
+ name: "initial login client",
7085
+ server_url: config.server_url,
7086
+ additional_headers: additional_headers,
7087
+ });
7088
+ try {
7089
+ const svc = await server.getService(service_id);
7090
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(svc, `Failed to get the login service: ${service_id}`);
7091
+ let context;
7092
+ if (workspace) {
7093
+ context = await svc.start({ workspace, expires_in, _rkwargs: true });
7094
+ } else {
7095
+ context = await svc.start();
7533
7096
  }
7534
- }
7535
- function createDataView(buffer) {
7536
- if (buffer instanceof ArrayBuffer) {
7537
- return new DataView(buffer);
7097
+ if (callback) {
7098
+ await callback(context);
7099
+ } else {
7100
+ console.log(`Please open your browser and login at ${context.login_url}`);
7538
7101
  }
7539
- var bufferView = ensureUint8Array(buffer);
7540
- return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
7102
+ return await svc.check(context.key, { timeout, profile, _rkwargs: true });
7103
+ } catch (error) {
7104
+ throw error;
7105
+ } finally {
7106
+ await server.disconnect();
7107
+ }
7541
7108
  }
7542
- //# sourceMappingURL=typedArrays.mjs.map
7543
-
7544
- /***/ }),
7545
7109
 
7546
- /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs":
7547
- /*!*******************************************************************!*\
7548
- !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs ***!
7549
- \*******************************************************************/
7550
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
7110
+ async function logout(config) {
7111
+ const service_id = config.login_service_id || "public/hypha-login";
7112
+ const callback = config.logout_callback;
7113
+ const additional_headers = config.additional_headers;
7551
7114
 
7552
- __webpack_require__.r(__webpack_exports__);
7553
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7554
- /* harmony export */ TEXT_DECODER_THRESHOLD: () => (/* binding */ TEXT_DECODER_THRESHOLD),
7555
- /* harmony export */ TEXT_ENCODER_THRESHOLD: () => (/* binding */ TEXT_ENCODER_THRESHOLD),
7556
- /* harmony export */ utf8Count: () => (/* binding */ utf8Count),
7557
- /* harmony export */ utf8DecodeJs: () => (/* binding */ utf8DecodeJs),
7558
- /* harmony export */ utf8DecodeTD: () => (/* binding */ utf8DecodeTD),
7559
- /* harmony export */ utf8EncodeJs: () => (/* binding */ utf8EncodeJs),
7560
- /* harmony export */ utf8EncodeTE: () => (/* binding */ utf8EncodeTE)
7561
- /* harmony export */ });
7562
- /* harmony import */ var _int_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
7563
- var _a, _b, _c;
7564
- /* eslint-disable @typescript-eslint/no-unnecessary-condition */
7115
+ const server = await connectToServer({
7116
+ name: "initial logout client",
7117
+ server_url: config.server_url,
7118
+ additional_headers: additional_headers,
7119
+ });
7120
+ try {
7121
+ const svc = await server.getService(service_id);
7122
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(svc, `Failed to get the login service: ${service_id}`);
7565
7123
 
7566
- var TEXT_ENCODING_AVAILABLE = (typeof process === "undefined" || ((_a = process === null || process === void 0 ? void 0 : process.env) === null || _a === void 0 ? void 0 : _a["TEXT_ENCODING"]) !== "never") &&
7567
- typeof TextEncoder !== "undefined" &&
7568
- typeof TextDecoder !== "undefined";
7569
- function utf8Count(str) {
7570
- var strLength = str.length;
7571
- var byteLength = 0;
7572
- var pos = 0;
7573
- while (pos < strLength) {
7574
- var value = str.charCodeAt(pos++);
7575
- if ((value & 0xffffff80) === 0) {
7576
- // 1-byte
7577
- byteLength++;
7578
- continue;
7579
- }
7580
- else if ((value & 0xfffff800) === 0) {
7581
- // 2-bytes
7582
- byteLength += 2;
7583
- }
7584
- else {
7585
- // handle surrogate pair
7586
- if (value >= 0xd800 && value <= 0xdbff) {
7587
- // high surrogate
7588
- if (pos < strLength) {
7589
- var extra = str.charCodeAt(pos);
7590
- if ((extra & 0xfc00) === 0xdc00) {
7591
- ++pos;
7592
- value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
7593
- }
7594
- }
7595
- }
7596
- if ((value & 0xffff0000) === 0) {
7597
- // 3-byte
7598
- byteLength += 3;
7599
- }
7600
- else {
7601
- // 4-byte
7602
- byteLength += 4;
7603
- }
7604
- }
7124
+ // Check if logout function exists for backward compatibility
7125
+ if (!svc.logout) {
7126
+ throw new Error(
7127
+ "Logout is not supported by this server. " +
7128
+ "Please upgrade the Hypha server to a version that supports logout.",
7129
+ );
7605
7130
  }
7606
- return byteLength;
7607
- }
7608
- function utf8EncodeJs(str, output, outputOffset) {
7609
- var strLength = str.length;
7610
- var offset = outputOffset;
7611
- var pos = 0;
7612
- while (pos < strLength) {
7613
- var value = str.charCodeAt(pos++);
7614
- if ((value & 0xffffff80) === 0) {
7615
- // 1-byte
7616
- output[offset++] = value;
7617
- continue;
7618
- }
7619
- else if ((value & 0xfffff800) === 0) {
7620
- // 2-bytes
7621
- output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
7622
- }
7623
- else {
7624
- // handle surrogate pair
7625
- if (value >= 0xd800 && value <= 0xdbff) {
7626
- // high surrogate
7627
- if (pos < strLength) {
7628
- var extra = str.charCodeAt(pos);
7629
- if ((extra & 0xfc00) === 0xdc00) {
7630
- ++pos;
7631
- value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
7632
- }
7633
- }
7634
- }
7635
- if ((value & 0xffff0000) === 0) {
7636
- // 3-byte
7637
- output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
7638
- output[offset++] = ((value >> 6) & 0x3f) | 0x80;
7639
- }
7640
- else {
7641
- // 4-byte
7642
- output[offset++] = ((value >> 18) & 0x07) | 0xf0;
7643
- output[offset++] = ((value >> 12) & 0x3f) | 0x80;
7644
- output[offset++] = ((value >> 6) & 0x3f) | 0x80;
7645
- }
7646
- }
7647
- output[offset++] = (value & 0x3f) | 0x80;
7131
+
7132
+ const context = await svc.logout({});
7133
+ if (callback) {
7134
+ await callback(context);
7135
+ } else {
7136
+ console.log(
7137
+ `Please open your browser to logout at ${context.logout_url}`,
7138
+ );
7648
7139
  }
7140
+ return context;
7141
+ } catch (error) {
7142
+ throw error;
7143
+ } finally {
7144
+ await server.disconnect();
7145
+ }
7649
7146
  }
7650
- var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
7651
- var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
7652
- ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
7653
- : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force"
7654
- ? 200
7655
- : 0;
7656
- function utf8EncodeTEencode(str, output, outputOffset) {
7657
- output.set(sharedTextEncoder.encode(str), outputOffset);
7658
- }
7659
- function utf8EncodeTEencodeInto(str, output, outputOffset) {
7660
- sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
7661
- }
7662
- var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
7663
- var CHUNK_SIZE = 4096;
7664
- function utf8DecodeJs(bytes, inputOffset, byteLength) {
7665
- var offset = inputOffset;
7666
- var end = offset + byteLength;
7667
- var units = [];
7668
- var result = "";
7669
- while (offset < end) {
7670
- var byte1 = bytes[offset++];
7671
- if ((byte1 & 0x80) === 0) {
7672
- // 1 byte
7673
- units.push(byte1);
7674
- }
7675
- else if ((byte1 & 0xe0) === 0xc0) {
7676
- // 2 bytes
7677
- var byte2 = bytes[offset++] & 0x3f;
7678
- units.push(((byte1 & 0x1f) << 6) | byte2);
7679
- }
7680
- else if ((byte1 & 0xf0) === 0xe0) {
7681
- // 3 bytes
7682
- var byte2 = bytes[offset++] & 0x3f;
7683
- var byte3 = bytes[offset++] & 0x3f;
7684
- units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
7685
- }
7686
- else if ((byte1 & 0xf8) === 0xf0) {
7687
- // 4 bytes
7688
- var byte2 = bytes[offset++] & 0x3f;
7689
- var byte3 = bytes[offset++] & 0x3f;
7690
- var byte4 = bytes[offset++] & 0x3f;
7691
- var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
7692
- if (unit > 0xffff) {
7693
- unit -= 0x10000;
7694
- units.push(((unit >>> 10) & 0x3ff) | 0xd800);
7695
- unit = 0xdc00 | (unit & 0x3ff);
7696
- }
7697
- units.push(unit);
7698
- }
7699
- else {
7700
- units.push(byte1);
7701
- }
7702
- if (units.length >= CHUNK_SIZE) {
7703
- result += String.fromCharCode.apply(String, units);
7704
- units.length = 0;
7705
- }
7147
+
7148
+ async function webrtcGetService(wm, rtc_service_id, query, config) {
7149
+ config = config || {};
7150
+ const webrtc = config.webrtc;
7151
+ const webrtc_config = config.webrtc_config;
7152
+ if (config.webrtc !== undefined) delete config.webrtc;
7153
+ if (config.webrtc_config !== undefined) delete config.webrtc_config;
7154
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
7155
+ [undefined, true, false, "auto"].includes(webrtc),
7156
+ "webrtc must be true, false or 'auto'",
7157
+ );
7158
+
7159
+ const svc = await wm.getService(query, config);
7160
+ if (webrtc === true || webrtc === "auto") {
7161
+ if (svc.id.includes(":") && svc.id.includes("/")) {
7162
+ try {
7163
+ // Assuming that the client registered a webrtc service with the client_id + "-rtc"
7164
+ const peer = await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService)(wm, rtc_service_id, webrtc_config);
7165
+ const rtcSvc = await peer.getService(svc.id.split(":")[1], config);
7166
+ rtcSvc._webrtc = true;
7167
+ rtcSvc._peer = peer;
7168
+ rtcSvc._service = svc;
7169
+ return rtcSvc;
7170
+ } catch (e) {
7171
+ console.warn(
7172
+ "Failed to get webrtc service, using websocket connection",
7173
+ e,
7174
+ );
7175
+ }
7706
7176
  }
7707
- if (units.length > 0) {
7708
- result += String.fromCharCode.apply(String, units);
7177
+ if (webrtc === true) {
7178
+ throw new Error("Failed to get the service via webrtc");
7709
7179
  }
7710
- return result;
7711
- }
7712
- var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
7713
- var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
7714
- ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
7715
- : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force"
7716
- ? 200
7717
- : 0;
7718
- function utf8DecodeTD(bytes, inputOffset, byteLength) {
7719
- var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
7720
- return sharedTextDecoder.decode(stringBytes);
7180
+ }
7181
+ return svc;
7721
7182
  }
7722
- //# sourceMappingURL=utf8.mjs.map
7723
7183
 
7724
- /***/ })
7184
+ async function connectToServer(config) {
7185
+ // Support HTTP transport via transport option
7186
+ const transport = config.transport || "websocket";
7187
+ if (transport === "http") {
7188
+ return await (0,_http_client_js__WEBPACK_IMPORTED_MODULE_4__.connectToServerHTTP)(config);
7189
+ }
7725
7190
 
7726
- /******/ });
7727
- /************************************************************************/
7728
- /******/ // The module cache
7729
- /******/ var __webpack_module_cache__ = {};
7730
- /******/
7731
- /******/ // The require function
7732
- /******/ function __webpack_require__(moduleId) {
7733
- /******/ // Check if module is in cache
7734
- /******/ var cachedModule = __webpack_module_cache__[moduleId];
7735
- /******/ if (cachedModule !== undefined) {
7736
- /******/ return cachedModule.exports;
7737
- /******/ }
7738
- /******/ // Create a new module (and put it into the cache)
7739
- /******/ var module = __webpack_module_cache__[moduleId] = {
7740
- /******/ // no module.id needed
7741
- /******/ // no module.loaded needed
7742
- /******/ exports: {}
7743
- /******/ };
7744
- /******/
7745
- /******/ // Execute the module function
7746
- /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
7747
- /******/
7748
- /******/ // Return the exports of the module
7749
- /******/ return module.exports;
7750
- /******/ }
7751
- /******/
7752
- /************************************************************************/
7753
- /******/ /* webpack/runtime/define property getters */
7754
- /******/ (() => {
7755
- /******/ // define getter functions for harmony exports
7756
- /******/ __webpack_require__.d = (exports, definition) => {
7757
- /******/ for(var key in definition) {
7758
- /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
7759
- /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
7760
- /******/ }
7761
- /******/ }
7762
- /******/ };
7763
- /******/ })();
7764
- /******/
7765
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
7766
- /******/ (() => {
7767
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
7768
- /******/ })();
7769
- /******/
7770
- /******/ /* webpack/runtime/make namespace object */
7771
- /******/ (() => {
7772
- /******/ // define __esModule on exports
7773
- /******/ __webpack_require__.r = (exports) => {
7774
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
7775
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7776
- /******/ }
7777
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
7778
- /******/ };
7779
- /******/ })();
7780
- /******/
7781
- /************************************************************************/
7782
- var __webpack_exports__ = {};
7783
- /*!***********************!*\
7784
- !*** ./src/client.js ***!
7785
- \***********************/
7786
- __webpack_require__.r(__webpack_exports__);
7787
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
7788
- /* harmony export */ API_VERSION: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.API_VERSION),
7789
- /* harmony export */ HTTPStreamingRPCConnection: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_2__.HTTPStreamingRPCConnection),
7790
- /* harmony export */ LocalWebSocket: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.LocalWebSocket),
7791
- /* harmony export */ RPC: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.RPC),
7792
- /* harmony export */ connectToServer: () => (/* binding */ connectToServer),
7793
- /* harmony export */ connectToServerHTTP: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_2__.connectToServerHTTP),
7794
- /* harmony export */ connectToServerWebsocket: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.connectToServer),
7795
- /* harmony export */ getRTCService: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.getRTCService),
7796
- /* harmony export */ getRemoteService: () => (/* binding */ getRemoteService),
7797
- /* harmony export */ getRemoteServiceHTTP: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_2__.getRemoteServiceHTTP),
7798
- /* harmony export */ getRemoteServiceWebsocket: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.getRemoteService),
7799
- /* harmony export */ loadRequirements: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements),
7800
- /* harmony export */ login: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.login),
7801
- /* harmony export */ logout: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.logout),
7802
- /* harmony export */ normalizeServerUrlHTTP: () => (/* reexport safe */ _http_client_js__WEBPACK_IMPORTED_MODULE_2__.normalizeServerUrl),
7803
- /* harmony export */ registerRTCService: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.registerRTCService),
7804
- /* harmony export */ schemaFunction: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.schemaFunction),
7805
- /* harmony export */ setupLocalClient: () => (/* reexport safe */ _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__.setupLocalClient)
7806
- /* harmony export */ });
7807
- /* harmony import */ var _utils_index_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils/index.js */ "./src/utils/index.js");
7808
- /* harmony import */ var _websocket_client_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./websocket-client.js */ "./src/websocket-client.js");
7809
- /* harmony import */ var _http_client_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./http-client.js */ "./src/http-client.js");
7810
- /**
7811
- * Hypha RPC client - unified connection interface.
7812
- *
7813
- * This module provides the main entry point for connecting to Hypha servers.
7814
- * It supports multiple transport types:
7815
- * - "websocket" (default): Traditional WebSocket connection
7816
- * - "http": HTTP streaming connection (more resilient to network issues)
7817
- */
7191
+ if (config.server) {
7192
+ config.server_url = config.server_url || config.server.url;
7193
+ config.WebSocketClass =
7194
+ config.WebSocketClass || config.server.WebSocketClass;
7195
+ }
7196
+ let clientId = config.client_id;
7197
+ if (!clientId) {
7198
+ clientId = (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
7199
+ config.client_id = clientId;
7200
+ }
7201
+ if (Object.keys(config).length === 0) {
7202
+ if (typeof process !== "undefined" && process.env) {
7203
+ // Node.js
7204
+ config.server_url = process.env.HYPHA_SERVER_URL;
7205
+ config.token = process.env.HYPHA_TOKEN;
7206
+ config.client_id = process.env.HYPHA_CLIENT_ID;
7207
+ config.workspace = process.env.HYPHA_WORKSPACE;
7208
+ } else if (typeof self !== "undefined" && self.env) {
7209
+ // WebWorker (only if you inject self.env manually)
7210
+ config.server_url = self.env.HYPHA_SERVER_URL;
7211
+ config.token = self.env.HYPHA_TOKEN;
7212
+ config.client_id = self.env.HYPHA_CLIENT_ID;
7213
+ config.workspace = self.env.HYPHA_WORKSPACE;
7214
+ } else if (typeof globalThis !== "undefined" && globalThis.env) {
7215
+ // Browser (only if you define globalThis.env beforehand)
7216
+ config.server_url = globalThis.env.HYPHA_SERVER_URL;
7217
+ config.token = globalThis.env.HYPHA_TOKEN;
7218
+ config.client_id = globalThis.env.HYPHA_CLIENT_ID;
7219
+ config.workspace = globalThis.env.HYPHA_WORKSPACE;
7220
+ }
7221
+ }
7222
+
7223
+ let server_url = normalizeServerUrl(config.server_url);
7224
+
7225
+ let connection = new WebsocketRPCConnection(
7226
+ server_url,
7227
+ clientId,
7228
+ config.workspace,
7229
+ config.token,
7230
+ config.reconnection_token,
7231
+ config.method_timeout || 60,
7232
+ config.WebSocketClass,
7233
+ config.token_refresh_interval,
7234
+ config.additional_headers,
7235
+ );
7236
+ const connection_info = await connection.open();
7237
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
7238
+ connection_info,
7239
+ "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.",
7240
+ );
7241
+ // wait for 0.5 seconds
7242
+ await new Promise((resolve) => setTimeout(resolve, 100));
7243
+ // Ensure manager_id is set before proceeding
7244
+ if (!connection.manager_id) {
7245
+ console.warn("Manager ID not set immediately, waiting...");
7246
+
7247
+ // Wait for manager_id to be set with timeout
7248
+ const maxWaitTime = 5000; // 5 seconds
7249
+ const checkInterval = 100; // 100ms
7250
+ const startTime = Date.now();
7251
+
7252
+ while (!connection.manager_id && Date.now() - startTime < maxWaitTime) {
7253
+ await new Promise((resolve) => setTimeout(resolve, checkInterval));
7254
+ }
7255
+
7256
+ if (!connection.manager_id) {
7257
+ console.error("Manager ID still not set after waiting");
7258
+ throw new Error("Failed to get manager ID from server");
7259
+ } else {
7260
+ console.info(`Manager ID set after waiting: ${connection.manager_id}`);
7261
+ }
7262
+ }
7263
+ if (config.workspace && connection_info.workspace !== config.workspace) {
7264
+ throw new Error(
7265
+ `Connected to the wrong workspace: ${connection_info.workspace}, expected: ${config.workspace}`,
7266
+ );
7267
+ }
7818
7268
 
7269
+ const workspace = connection_info.workspace;
7270
+ const rpc = new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(connection, {
7271
+ client_id: clientId,
7272
+ workspace,
7273
+ default_context: { connection_type: "websocket" },
7274
+ name: config.name,
7275
+ method_timeout: config.method_timeout,
7276
+ app_id: config.app_id,
7277
+ server_base_url: connection_info.public_base_url,
7278
+ long_message_chunk_size: config.long_message_chunk_size,
7279
+ });
7280
+ await rpc.waitFor("services_registered", config.method_timeout || 120);
7281
+ const wm = await rpc.get_manager_service({
7282
+ timeout: config.method_timeout,
7283
+ case_conversion: "camel",
7284
+ kwargs_expansion: config.kwargs_expansion || false,
7285
+ });
7286
+ wm.rpc = rpc;
7819
7287
 
7288
+ async function _export(api) {
7289
+ api.id = "default";
7290
+ api.name = api.name || config.name || api.id;
7291
+ api.description = api.description || config.description;
7292
+ await rpc.register_service(api, { overwrite: true });
7293
+ }
7820
7294
 
7821
- // Re-export everything from websocket-client for backward compatibility
7822
- // (except _connectToServer which is internal)
7295
+ async function getApp(clientId) {
7296
+ clientId = clientId || "*";
7297
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!clientId.includes(":"), "clientId should not contain ':'");
7298
+ if (!clientId.includes("/")) {
7299
+ clientId = connection_info.workspace + "/" + clientId;
7300
+ }
7301
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
7302
+ clientId.split("/").length === 2,
7303
+ "clientId should match pattern workspace/clientId",
7304
+ );
7305
+ return await wm.getService(`${clientId}:default`);
7306
+ }
7823
7307
 
7308
+ async function listApps(ws) {
7309
+ ws = ws || workspace;
7310
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!ws.includes(":"), "workspace should not contain ':'");
7311
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.assert)(!ws.includes("/"), "workspace should not contain '/'");
7312
+ const query = { workspace: ws, service_id: "default" };
7313
+ return await wm.listServices(query);
7314
+ }
7824
7315
 
7825
- // Re-export HTTP client classes and functions
7316
+ if (connection_info) {
7317
+ wm.config = Object.assign(wm.config, connection_info);
7318
+ }
7319
+ wm.export = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(_export, {
7320
+ name: "export",
7321
+ description: "Export the api.",
7322
+ parameters: {
7323
+ properties: { api: { description: "The api to export", type: "object" } },
7324
+ required: ["api"],
7325
+ type: "object",
7326
+ },
7327
+ });
7328
+ wm.getApp = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(getApp, {
7329
+ name: "getApp",
7330
+ description: "Get the app.",
7331
+ parameters: {
7332
+ properties: {
7333
+ clientId: { default: "*", description: "The clientId", type: "string" },
7334
+ },
7335
+ type: "object",
7336
+ },
7337
+ });
7338
+ wm.listApps = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(listApps, {
7339
+ name: "listApps",
7340
+ description: "List the apps.",
7341
+ parameters: {
7342
+ properties: {
7343
+ workspace: {
7344
+ default: workspace,
7345
+ description: "The workspace",
7346
+ type: "string",
7347
+ },
7348
+ },
7349
+ type: "object",
7350
+ },
7351
+ });
7352
+ wm.disconnect = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.disconnect.bind(rpc), {
7353
+ name: "disconnect",
7354
+ description: "Disconnect from the server.",
7355
+ parameters: { type: "object", properties: {}, required: [] },
7356
+ });
7357
+ wm.registerCodec = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.register_codec.bind(rpc), {
7358
+ name: "registerCodec",
7359
+ description: "Register a codec for the webrtc connection",
7360
+ parameters: {
7361
+ type: "object",
7362
+ properties: {
7363
+ codec: {
7364
+ type: "object",
7365
+ description: "Codec to register",
7366
+ properties: {
7367
+ name: { type: "string" },
7368
+ type: {},
7369
+ encoder: { type: "function" },
7370
+ decoder: { type: "function" },
7371
+ },
7372
+ },
7373
+ },
7374
+ },
7375
+ });
7826
7376
 
7377
+ wm.emit = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.emit.bind(rpc), {
7378
+ name: "emit",
7379
+ description: "Emit a message.",
7380
+ parameters: {
7381
+ properties: { data: { description: "The data to emit", type: "object" } },
7382
+ required: ["data"],
7383
+ type: "object",
7384
+ },
7385
+ });
7827
7386
 
7828
- /**
7829
- * Connect to a Hypha server.
7830
- *
7831
- * @param {Object} config - Configuration object with connection options
7832
- * @param {string} config.serverUrl - The server URL (required, alias: server_url)
7833
- * @param {string} config.workspace - Target workspace (optional)
7834
- * @param {string} config.token - Authentication token (optional)
7835
- * @param {string} config.clientId - Unique client identifier (optional, alias: client_id)
7836
- * @param {string} config.transport - Transport type - "websocket" (default) or "http"
7837
- * @param {number} config.method_timeout - Timeout for RPC method calls
7838
- * @returns {Promise<Object>} Connected workspace manager
7839
- *
7840
- * @example
7841
- * const server = await connectToServer({
7842
- * serverUrl: "https://hypha.aicell.io",
7843
- * transport: "http" // or "websocket" (default)
7844
- * });
7845
- * await server.registerService({ id: "my-service", ... });
7846
- */
7847
- async function connectToServer(config = {}) {
7848
- const transport = config.transport || "websocket";
7387
+ wm.on = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.on.bind(rpc), {
7388
+ name: "on",
7389
+ description: "Register a message handler.",
7390
+ parameters: {
7391
+ properties: {
7392
+ event: { description: "The event to listen to", type: "string" },
7393
+ handler: { description: "The handler function", type: "function" },
7394
+ },
7395
+ required: ["event", "handler"],
7396
+ type: "object",
7397
+ },
7398
+ });
7849
7399
 
7850
- if (transport === "http") {
7851
- const { _connectToServerHTTP } = await Promise.resolve(/*! import() */).then(__webpack_require__.bind(__webpack_require__, /*! ./http-client.js */ "./src/http-client.js"));
7852
- return await _connectToServerHTTP(config);
7400
+ wm.off = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.off.bind(rpc), {
7401
+ name: "off",
7402
+ description: "Remove a message handler.",
7403
+ parameters: {
7404
+ properties: {
7405
+ event: { description: "The event to remove", type: "string" },
7406
+ handler: { description: "The handler function", type: "function" },
7407
+ },
7408
+ required: ["event", "handler"],
7409
+ type: "object",
7410
+ },
7411
+ });
7412
+
7413
+ wm.once = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.once.bind(rpc), {
7414
+ name: "once",
7415
+ description: "Register a one-time message handler.",
7416
+ parameters: {
7417
+ properties: {
7418
+ event: { description: "The event to listen to", type: "string" },
7419
+ handler: { description: "The handler function", type: "function" },
7420
+ },
7421
+ required: ["event", "handler"],
7422
+ type: "object",
7423
+ },
7424
+ });
7425
+
7426
+ wm.getServiceSchema = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.get_service_schema, {
7427
+ name: "getServiceSchema",
7428
+ description: "Get the service schema.",
7429
+ parameters: {
7430
+ properties: {
7431
+ service: {
7432
+ description: "The service to extract schema",
7433
+ type: "object",
7434
+ },
7435
+ },
7436
+ required: ["service"],
7437
+ type: "object",
7438
+ },
7439
+ });
7440
+
7441
+ wm.registerService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.register_service.bind(rpc), {
7442
+ name: "registerService",
7443
+ description: "Register a service.",
7444
+ parameters: {
7445
+ properties: {
7446
+ service: { description: "The service to register", type: "object" },
7447
+ force: {
7448
+ default: false,
7449
+ description: "Force to register the service",
7450
+ type: "boolean",
7451
+ },
7452
+ },
7453
+ required: ["service"],
7454
+ type: "object",
7455
+ },
7456
+ });
7457
+ wm.unregisterService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(rpc.unregister_service.bind(rpc), {
7458
+ name: "unregisterService",
7459
+ description: "Unregister a service.",
7460
+ parameters: {
7461
+ properties: {
7462
+ service: {
7463
+ description: "The service id to unregister",
7464
+ type: "string",
7465
+ },
7466
+ notify: {
7467
+ default: true,
7468
+ description: "Notify the workspace manager",
7469
+ type: "boolean",
7470
+ },
7471
+ },
7472
+ required: ["service"],
7473
+ type: "object",
7474
+ },
7475
+ });
7476
+ if (connection.manager_id) {
7477
+ rpc.on("force-exit", async (message) => {
7478
+ if (message.from === "*/" + connection.manager_id) {
7479
+ console.log("Disconnecting from server, reason:", message.reason);
7480
+ await rpc.disconnect();
7481
+ }
7482
+ });
7483
+ }
7484
+ if (config.webrtc) {
7485
+ await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.registerRTCService)(wm, `${clientId}-rtc`, config.webrtc_config);
7486
+ // make a copy of wm, so webrtc can use the original wm.getService
7487
+ const _wm = Object.assign({}, wm);
7488
+ const description = _wm.getService.__schema__.description;
7489
+ // TODO: Fix the schema for adding options for webrtc
7490
+ const parameters = _wm.getService.__schema__.parameters;
7491
+ wm.getService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(
7492
+ webrtcGetService.bind(null, _wm, `${workspace}/${clientId}-rtc`),
7493
+ {
7494
+ name: "getService",
7495
+ description,
7496
+ parameters,
7497
+ },
7498
+ );
7499
+
7500
+ wm.getRTCService = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(_webrtc_client_js__WEBPACK_IMPORTED_MODULE_3__.getRTCService.bind(null, wm), {
7501
+ name: "getRTCService",
7502
+ description: "Get the webrtc connection, returns a peer connection.",
7503
+ parameters: {
7504
+ properties: {
7505
+ config: {
7506
+ description: "The config for the webrtc service",
7507
+ type: "object",
7508
+ },
7509
+ },
7510
+ required: ["config"],
7511
+ type: "object",
7512
+ },
7513
+ });
7853
7514
  } else {
7854
- const { _connectToServer } = await Promise.resolve(/*! import() */).then(__webpack_require__.bind(__webpack_require__, /*! ./websocket-client.js */ "./src/websocket-client.js"));
7855
- return await _connectToServer(config);
7515
+ const _getService = wm.getService;
7516
+ wm.getService = (query, config) => {
7517
+ config = config || {};
7518
+ return _getService(query, config);
7519
+ };
7520
+ wm.getService.__schema__ = _getService.__schema__;
7521
+ }
7522
+
7523
+ async function registerProbes(probes) {
7524
+ probes.id = "probes";
7525
+ probes.name = "Probes";
7526
+ probes.config = { visibility: "public" };
7527
+ probes.type = "probes";
7528
+ probes.description = `Probes Service, visit ${server_url}/${workspace}services/probes for the available probes.`;
7529
+ return await wm.registerService(probes, { overwrite: true });
7856
7530
  }
7531
+
7532
+ wm.registerProbes = (0,_utils_schema_js__WEBPACK_IMPORTED_MODULE_2__.schemaFunction)(registerProbes, {
7533
+ name: "registerProbes",
7534
+ description: "Register probes service",
7535
+ parameters: {
7536
+ properties: {
7537
+ probes: {
7538
+ description:
7539
+ "The probes to register, e.g. {'liveness': {'type': 'function', 'description': 'Check the liveness of the service'}}",
7540
+ type: "object",
7541
+ },
7542
+ },
7543
+ required: ["probes"],
7544
+ type: "object",
7545
+ },
7546
+ });
7547
+ return wm;
7857
7548
  }
7858
7549
 
7859
- /**
7860
- * Get a remote service by URI.
7861
- *
7862
- * @param {string} serviceUri - Service URI in format "server_url/workspace/client_id:service_id"
7863
- * @param {Object} config - Additional configuration options
7864
- * @returns {Promise<Object>} The remote service
7865
- *
7866
- * @example
7867
- * const service = await getRemoteService(
7868
- * "https://hypha.aicell.io/public/client:service",
7869
- * { transport: "http" }
7870
- * );
7871
- * const result = await service.someMethod();
7872
- */
7873
7550
  async function getRemoteService(serviceUri, config = {}) {
7874
7551
  const { serverUrl, workspace, clientId, serviceId, appId } =
7875
- (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_0__.parseServiceUrl)(serviceUri);
7552
+ (0,_utils_index_js__WEBPACK_IMPORTED_MODULE_1__.parseServiceUrl)(serviceUri);
7876
7553
  const fullServiceId = `${workspace}/${clientId}:${serviceId}@${appId}`;
7877
7554
 
7878
7555
  if (config.serverUrl) {
@@ -7883,11 +7560,235 @@ async function getRemoteService(serviceUri, config = {}) {
7883
7560
  }
7884
7561
  }
7885
7562
  config.serverUrl = serverUrl;
7886
-
7887
7563
  const server = await connectToServer(config);
7888
7564
  return await server.getService(fullServiceId);
7889
7565
  }
7890
7566
 
7567
+ class LocalWebSocket {
7568
+ constructor(url, client_id, workspace) {
7569
+ this.url = url;
7570
+ this.onopen = () => {};
7571
+ this.onmessage = () => {};
7572
+ this.onclose = () => {};
7573
+ this.onerror = () => {};
7574
+ this.client_id = client_id;
7575
+ this.workspace = workspace;
7576
+ const context = typeof window !== "undefined" ? window : self;
7577
+ const isWindow = typeof window !== "undefined";
7578
+ this.postMessage = (message) => {
7579
+ if (isWindow) {
7580
+ window.parent.postMessage(message, "*");
7581
+ } else {
7582
+ self.postMessage(message);
7583
+ }
7584
+ };
7585
+
7586
+ this.readyState = WebSocket.CONNECTING;
7587
+ context.addEventListener(
7588
+ "message",
7589
+ (event) => {
7590
+ const { type, data, to } = event.data;
7591
+ if (to !== this.client_id) {
7592
+ // console.debug("message not for me", to, this.client_id);
7593
+ return;
7594
+ }
7595
+ switch (type) {
7596
+ case "message":
7597
+ if (this.readyState === WebSocket.OPEN && this.onmessage) {
7598
+ this.onmessage({ data: data });
7599
+ }
7600
+ break;
7601
+ case "connected":
7602
+ this.readyState = WebSocket.OPEN;
7603
+ this.onopen(event);
7604
+ break;
7605
+ case "closed":
7606
+ this.readyState = WebSocket.CLOSED;
7607
+ this.onclose(event);
7608
+ break;
7609
+ default:
7610
+ break;
7611
+ }
7612
+ },
7613
+ false,
7614
+ );
7615
+
7616
+ if (!this.client_id) throw new Error("client_id is required");
7617
+ if (!this.workspace) throw new Error("workspace is required");
7618
+ this.postMessage({
7619
+ type: "connect",
7620
+ url: this.url,
7621
+ from: this.client_id,
7622
+ workspace: this.workspace,
7623
+ });
7624
+ }
7625
+
7626
+ send(data) {
7627
+ if (this.readyState === WebSocket.OPEN) {
7628
+ this.postMessage({
7629
+ type: "message",
7630
+ data: data,
7631
+ from: this.client_id,
7632
+ workspace: this.workspace,
7633
+ });
7634
+ }
7635
+ }
7636
+
7637
+ close() {
7638
+ this.readyState = WebSocket.CLOSING;
7639
+ this.postMessage({
7640
+ type: "close",
7641
+ from: this.client_id,
7642
+ workspace: this.workspace,
7643
+ });
7644
+ this.onclose();
7645
+ }
7646
+
7647
+ addEventListener(type, listener) {
7648
+ if (type === "message") {
7649
+ this.onmessage = listener;
7650
+ }
7651
+ if (type === "open") {
7652
+ this.onopen = listener;
7653
+ }
7654
+ if (type === "close") {
7655
+ this.onclose = listener;
7656
+ }
7657
+ if (type === "error") {
7658
+ this.onerror = listener;
7659
+ }
7660
+ }
7661
+ }
7662
+
7663
+ function setupLocalClient({
7664
+ enable_execution = false,
7665
+ on_ready = null,
7666
+ }) {
7667
+ return new Promise((resolve, reject) => {
7668
+ const context = typeof window !== "undefined" ? window : self;
7669
+ const isWindow = typeof window !== "undefined";
7670
+ context.addEventListener(
7671
+ "message",
7672
+ (event) => {
7673
+ const {
7674
+ type,
7675
+ server_url,
7676
+ workspace,
7677
+ client_id,
7678
+ token,
7679
+ method_timeout,
7680
+ name,
7681
+ config,
7682
+ } = event.data;
7683
+
7684
+ if (type === "initializeHyphaClient") {
7685
+ if (!server_url || !workspace || !client_id) {
7686
+ console.error("server_url, workspace, and client_id are required.");
7687
+ return;
7688
+ }
7689
+
7690
+ if (!server_url.startsWith("https://local-hypha-server:")) {
7691
+ console.error(
7692
+ "server_url should start with https://local-hypha-server:",
7693
+ );
7694
+ return;
7695
+ }
7696
+
7697
+ class FixedLocalWebSocket extends LocalWebSocket {
7698
+ constructor(url) {
7699
+ // Call the parent class's constructor with fixed values
7700
+ super(url, client_id, workspace);
7701
+ }
7702
+ }
7703
+ connectToServer({
7704
+ server_url,
7705
+ workspace,
7706
+ client_id,
7707
+ token,
7708
+ method_timeout,
7709
+ name,
7710
+ WebSocketClass: FixedLocalWebSocket,
7711
+ }).then(async (server) => {
7712
+ globalThis.api = server;
7713
+ try {
7714
+ // for iframe
7715
+ if (isWindow && enable_execution) {
7716
+ function loadScript(script) {
7717
+ return new Promise((resolve, reject) => {
7718
+ const scriptElement = document.createElement("script");
7719
+ scriptElement.innerHTML = script.content;
7720
+ scriptElement.lang = script.lang;
7721
+
7722
+ scriptElement.onload = () => resolve();
7723
+ scriptElement.onerror = (e) => reject(e);
7724
+
7725
+ document.head.appendChild(scriptElement);
7726
+ });
7727
+ }
7728
+ if (config.styles && config.styles.length > 0) {
7729
+ for (const style of config.styles) {
7730
+ const styleElement = document.createElement("style");
7731
+ styleElement.innerHTML = style.content;
7732
+ styleElement.lang = style.lang;
7733
+ document.head.appendChild(styleElement);
7734
+ }
7735
+ }
7736
+ if (config.links && config.links.length > 0) {
7737
+ for (const link of config.links) {
7738
+ const linkElement = document.createElement("a");
7739
+ linkElement.href = link.url;
7740
+ linkElement.innerText = link.text;
7741
+ document.body.appendChild(linkElement);
7742
+ }
7743
+ }
7744
+ if (config.windows && config.windows.length > 0) {
7745
+ for (const w of config.windows) {
7746
+ document.body.innerHTML = w.content;
7747
+ break;
7748
+ }
7749
+ }
7750
+ if (config.scripts && config.scripts.length > 0) {
7751
+ for (const script of config.scripts) {
7752
+ if (script.lang !== "javascript")
7753
+ throw new Error("Only javascript scripts are supported");
7754
+ await loadScript(script); // Await the loading of each script
7755
+ }
7756
+ }
7757
+ }
7758
+ // for web worker
7759
+ else if (
7760
+ !isWindow &&
7761
+ enable_execution &&
7762
+ config.scripts &&
7763
+ config.scripts.length > 0
7764
+ ) {
7765
+ for (const script of config.scripts) {
7766
+ if (script.lang !== "javascript")
7767
+ throw new Error("Only javascript scripts are supported");
7768
+ eval(script.content);
7769
+ }
7770
+ }
7771
+
7772
+ if (on_ready) {
7773
+ await on_ready(server, config);
7774
+ }
7775
+ resolve(server);
7776
+ } catch (e) {
7777
+ reject(e);
7778
+ }
7779
+ });
7780
+ }
7781
+ },
7782
+ false,
7783
+ );
7784
+ if (isWindow) {
7785
+ window.parent.postMessage({ type: "hyphaClientReady" }, "*");
7786
+ } else {
7787
+ self.postMessage({ type: "hyphaClientReady" });
7788
+ }
7789
+ });
7790
+ }
7791
+
7891
7792
  /******/ return __webpack_exports__;
7892
7793
  /******/ })()
7893
7794
  ;