hypha-rpc 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4741 @@
1
+ (function webpackUniversalModuleDefinition(root, factory) {
2
+ if(typeof exports === 'object' && typeof module === 'object')
3
+ module.exports = factory();
4
+ else if(typeof define === 'function' && define.amd)
5
+ define("hyphaWebsocketClient", [], factory);
6
+ else if(typeof exports === 'object')
7
+ exports["hyphaWebsocketClient"] = factory();
8
+ else
9
+ root["hyphaWebsocketClient"] = factory();
10
+ })(this, () => {
11
+ return /******/ (() => { // webpackBootstrap
12
+ /******/ "use strict";
13
+ /******/ var __webpack_modules__ = ({
14
+
15
+ /***/ "./src/rpc.js":
16
+ /*!********************!*\
17
+ !*** ./src/rpc.js ***!
18
+ \********************/
19
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
20
+
21
+ __webpack_require__.r(__webpack_exports__);
22
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
23
+ /* harmony export */ API_VERSION: () => (/* binding */ API_VERSION),
24
+ /* harmony export */ RPC: () => (/* binding */ RPC)
25
+ /* harmony export */ });
26
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils.js */ "./src/utils.js");
27
+ /* harmony import */ var _msgpack_msgpack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @msgpack/msgpack */ "./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs");
28
+ /* harmony import */ var _msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @msgpack/msgpack */ "./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs");
29
+ /**
30
+ * Contains the RPC object used both by the application
31
+ * site, and by each plugin
32
+ */
33
+
34
+
35
+
36
+
37
+ const API_VERSION = "0.3.0";
38
+ const CHUNK_SIZE = 1024 * 500;
39
+
40
+ const ArrayBufferView = Object.getPrototypeOf(
41
+ Object.getPrototypeOf(new Uint8Array()),
42
+ ).constructor;
43
+
44
+ function _appendBuffer(buffer1, buffer2) {
45
+ const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
46
+ tmp.set(new Uint8Array(buffer1), 0);
47
+ tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
48
+ return tmp.buffer;
49
+ }
50
+
51
+ function indexObject(obj, is) {
52
+ if (!is) throw new Error("undefined index");
53
+ if (typeof is === "string") return indexObject(obj, is.split("."));
54
+ else if (is.length === 0) return obj;
55
+ else return indexObject(obj[is[0]], is.slice(1));
56
+ }
57
+ function getFunctionInfo(func) {
58
+ const funcString = func.toString();
59
+
60
+ // Extract function name
61
+ const nameMatch = funcString.match(/function\s*(\w*)/);
62
+ const name = (nameMatch && nameMatch[1]) || "";
63
+
64
+ // Extract function parameters, excluding comments
65
+ const paramsMatch = funcString.match(/\(([^)]*)\)/);
66
+ let params = "";
67
+ if (paramsMatch) {
68
+ params = paramsMatch[1]
69
+ .split(",")
70
+ .map((p) =>
71
+ p
72
+ .replace(/\/\*.*?\*\//g, "") // Remove block comments
73
+ .replace(/\/\/.*$/g, ""),
74
+ ) // Remove line comments
75
+ .filter((p) => p.trim().length > 0) // Remove empty strings after removing comments
76
+ .map((p) => p.trim()) // Trim remaining whitespace
77
+ .join(", ");
78
+ }
79
+
80
+ // Extract function docstring (block comment)
81
+ let docMatch = funcString.match(/\)\s*\{\s*\/\*([\s\S]*?)\*\//);
82
+ const docstringBlock = (docMatch && docMatch[1].trim()) || "";
83
+
84
+ // Extract function docstring (line comment)
85
+ docMatch = funcString.match(/\)\s*\{\s*(\/\/[\s\S]*?)\n\s*[^\s\/]/);
86
+ const docstringLine =
87
+ (docMatch &&
88
+ docMatch[1]
89
+ .split("\n")
90
+ .map((s) => s.replace(/^\/\/\s*/, "").trim())
91
+ .join("\n")) ||
92
+ "";
93
+
94
+ const docstring = docstringBlock || docstringLine;
95
+ return (
96
+ name &&
97
+ params.length > 0 && {
98
+ name: name,
99
+ sig: params,
100
+ doc: docstring,
101
+ }
102
+ );
103
+ }
104
+
105
+ function concatArrayBuffers(buffers) {
106
+ var buffersLengths = buffers.map(function (b) {
107
+ return b.byteLength;
108
+ }),
109
+ totalBufferlength = buffersLengths.reduce(function (p, c) {
110
+ return p + c;
111
+ }, 0),
112
+ unit8Arr = new Uint8Array(totalBufferlength);
113
+ buffersLengths.reduce(function (p, c, i) {
114
+ unit8Arr.set(new Uint8Array(buffers[i]), p);
115
+ return p + c;
116
+ }, 0);
117
+ return unit8Arr.buffer;
118
+ }
119
+
120
+ class Timer {
121
+ constructor(timeout, callback, args, label) {
122
+ this._timeout = timeout;
123
+ this._callback = callback;
124
+ this._args = args;
125
+ this._label = label || "timer";
126
+ this._task = null;
127
+ this.started = false;
128
+ }
129
+
130
+ start() {
131
+ if (this.started) {
132
+ this.reset();
133
+ } else {
134
+ this._task = setTimeout(() => {
135
+ this._callback.apply(this, this._args);
136
+ }, this._timeout * 1000);
137
+ this.started = true;
138
+ }
139
+ }
140
+
141
+ clear() {
142
+ if (this._task) {
143
+ clearTimeout(this._task);
144
+ this._task = null;
145
+ this.started = false;
146
+ } else {
147
+ console.warn(`Clearing a timer (${this._label}) which is not started`);
148
+ }
149
+ }
150
+
151
+ reset() {
152
+ if (this._task) {
153
+ clearTimeout(this._task);
154
+ }
155
+ this._task = setTimeout(() => {
156
+ this._callback.apply(this, this._args);
157
+ }, this._timeout * 1000);
158
+ this.started = true;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * RPC object represents a single site in the
164
+ * communication protocol between the application and the plugin
165
+ *
166
+ * @param {Object} connection a special object allowing to send
167
+ * and receive messages from the opposite site (basically it
168
+ * should only provide send() and onMessage() methods)
169
+ */
170
+ class RPC extends _utils_js__WEBPACK_IMPORTED_MODULE_0__.MessageEmitter {
171
+ constructor(
172
+ connection,
173
+ {
174
+ client_id = null,
175
+ manager_id = null,
176
+ default_context = null,
177
+ name = null,
178
+ codecs = null,
179
+ method_timeout = null,
180
+ max_message_buffer_size = 0,
181
+ debug = false,
182
+ workspace = null,
183
+ silent = false,
184
+ app_id = null,
185
+ },
186
+ ) {
187
+ super(debug);
188
+ this._codecs = codecs || {};
189
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(client_id && typeof client_id === "string");
190
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(client_id, "client_id is required");
191
+ this._client_id = client_id;
192
+ this._name = name;
193
+ this._app_id = app_id;
194
+ this._local_workspace = workspace;
195
+ this.manager_id = manager_id;
196
+ this._silent = silent;
197
+ this.default_context = default_context || {};
198
+ this._method_annotations = new WeakMap();
199
+ this._manager_service = null;
200
+ this._max_message_buffer_size = max_message_buffer_size;
201
+ this._chunk_store = {};
202
+ this._method_timeout = method_timeout || 30;
203
+
204
+ // make sure there is an execute function
205
+ this._services = {};
206
+ this._object_store = {
207
+ services: this._services,
208
+ };
209
+
210
+ if (connection) {
211
+ this.add_service({
212
+ id: "built-in",
213
+ type: "built-in",
214
+ name: `Built-in services for ${this._local_workspace}/${this._client_id}`,
215
+ config: { require_context: true, visibility: "public" },
216
+ ping: this._ping.bind(this),
217
+ get_service: this.get_local_service.bind(this),
218
+ register_service: this.register_service.bind(this),
219
+ message_cache: {
220
+ create: this._create_message.bind(this),
221
+ append: this._append_message.bind(this),
222
+ process: this._process_message.bind(this),
223
+ remove: this._remove_message.bind(this),
224
+ },
225
+ });
226
+ this.on("method", this._handle_method.bind(this));
227
+
228
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(connection.emit_message && connection.on_message);
229
+ this._emit_message = connection.emit_message.bind(connection);
230
+ connection.on_message(this._on_message.bind(this));
231
+ this._connection = connection;
232
+ connection.on_connect(async () => {
233
+ if (!this._silent && this.manager_id) {
234
+ console.log("Connection established, reporting services...");
235
+ for (let service of Object.values(this._services)) {
236
+ const serviceInfo = this._extract_service_info(service);
237
+ await this.emit({
238
+ type: "service-added",
239
+ to: this.manager_id,
240
+ service: serviceInfo,
241
+ });
242
+ }
243
+ }
244
+ });
245
+ } else {
246
+ this._emit_message = function () {
247
+ console.log("No connection to emit message");
248
+ };
249
+ }
250
+ }
251
+
252
+ register_codec(config) {
253
+ if (!config["name"] || (!config["encoder"] && !config["decoder"])) {
254
+ throw new Error(
255
+ "Invalid codec format, please make sure you provide a name, type, encoder and decoder.",
256
+ );
257
+ } else {
258
+ if (config.type) {
259
+ for (let k of Object.keys(this._codecs)) {
260
+ if (this._codecs[k].type === config.type || k === config.name) {
261
+ delete this._codecs[k];
262
+ console.warn("Remove duplicated codec: " + k);
263
+ }
264
+ }
265
+ }
266
+ this._codecs[config["name"]] = config;
267
+ }
268
+ }
269
+
270
+ async _ping(msg, context) {
271
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(msg == "ping");
272
+ return "pong";
273
+ }
274
+
275
+ async ping(client_id, timeout) {
276
+ let method = this._generate_remote_method({
277
+ _rtarget: client_id,
278
+ _rmethod: "services.built-in.ping",
279
+ _rpromise: true,
280
+ _rdoc: "Ping a remote client",
281
+ _rsig: "ping(msg)",
282
+ });
283
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)((await method("ping", timeout)) == "pong");
284
+ }
285
+
286
+ _create_message(key, heartbeat, overwrite, context) {
287
+ if (heartbeat) {
288
+ if (!this._object_store[key]) {
289
+ throw new Error(`session does not exist anymore: ${key}`);
290
+ }
291
+ this._object_store[key]["timer"].reset();
292
+ }
293
+
294
+ if (!this._object_store["message_cache"]) {
295
+ this._object_store["message_cache"] = {};
296
+ }
297
+ if (!overwrite && this._object_store["message_cache"][key]) {
298
+ throw new Error(
299
+ `Message with the same key (${key}) already exists in the cache store, please use overwrite=true or remove it first.`,
300
+ );
301
+ }
302
+
303
+ this._object_store["message_cache"][key] = [];
304
+ }
305
+
306
+ _append_message(key, data, heartbeat, context) {
307
+ if (heartbeat) {
308
+ if (!this._object_store[key]) {
309
+ throw new Error(`session does not exist anymore: ${key}`);
310
+ }
311
+ this._object_store[key]["timer"].reset();
312
+ }
313
+ const cache = this._object_store["message_cache"];
314
+ if (!cache[key]) {
315
+ throw new Error(`Message with key ${key} does not exists.`);
316
+ }
317
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(data instanceof ArrayBufferView);
318
+ cache[key].push(data);
319
+ }
320
+
321
+ _remove_message(key, context) {
322
+ const cache = this._object_store["message_cache"];
323
+ if (!cache[key]) {
324
+ throw new Error(`Message with key ${key} does not exists.`);
325
+ }
326
+ delete cache[key];
327
+ }
328
+
329
+ _process_message(key, heartbeat, context) {
330
+ if (heartbeat) {
331
+ if (!this._object_store[key]) {
332
+ throw new Error(`session does not exist anymore: ${key}`);
333
+ }
334
+ this._object_store[key]["timer"].reset();
335
+ }
336
+ const cache = this._object_store["message_cache"];
337
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(!!context, "Context is required");
338
+ if (!cache[key]) {
339
+ throw new Error(`Message with key ${key} does not exists.`);
340
+ }
341
+ cache[key] = concatArrayBuffers(cache[key]);
342
+ console.debug(`Processing message ${key} (bytes=${cache[key].byteLength})`);
343
+ let unpacker = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_1__.decodeMulti)(cache[key]);
344
+ const { done, value } = unpacker.next();
345
+ const main = value;
346
+ // Make sure the fields are from trusted source
347
+ Object.assign(main, {
348
+ from: context.from,
349
+ to: context.to,
350
+ user: context.user,
351
+ });
352
+ main["ctx"] = JSON.parse(JSON.stringify(main));
353
+ Object.assign(main["ctx"], this.default_context);
354
+ if (!done) {
355
+ let extra = unpacker.next();
356
+ Object.assign(main, extra.value);
357
+ }
358
+ this._fire(main["type"], main);
359
+ console.debug(
360
+ this._client_id,
361
+ `Processed message ${key} (bytes=${cache[key].byteLength})`,
362
+ );
363
+ delete cache[key];
364
+ }
365
+
366
+ _on_message(message) {
367
+ try {
368
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(message instanceof ArrayBuffer);
369
+ let unpacker = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_1__.decodeMulti)(message);
370
+ const { done, value } = unpacker.next();
371
+ const main = value;
372
+ // Add trusted context to the method call
373
+ main["ctx"] = JSON.parse(JSON.stringify(main));
374
+ Object.assign(main["ctx"], this.default_context);
375
+ if (!done) {
376
+ let extra = unpacker.next();
377
+ Object.assign(main, extra.value);
378
+ }
379
+ this._fire(main["type"], main);
380
+ } catch (error) {
381
+ console.error("Failed to process message", error);
382
+ }
383
+ }
384
+
385
+ reset() {
386
+ this._event_handlers = {};
387
+ this._services = {};
388
+ }
389
+
390
+ async disconnect() {
391
+ this._fire("disconnect");
392
+ await this._connection.disconnect();
393
+ }
394
+
395
+ async get_manager_service(timeout) {
396
+ if (this.manager_id && !this._manager_service) {
397
+ this._manager_service = await this.get_remote_service(
398
+ `${this.manager_id}:default`,
399
+ timeout,
400
+ );
401
+ }
402
+ }
403
+
404
+ get_all_local_services() {
405
+ return this._services;
406
+ }
407
+ get_local_service(service_id, context) {
408
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(service_id);
409
+ const [ws, client_id] = context["to"].split("/");
410
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
411
+ client_id === this._client_id,
412
+ "Services can only be accessed locally",
413
+ );
414
+
415
+ const service = this._services[service_id];
416
+ if (!service) {
417
+ throw new Error("Service not found: " + service_id);
418
+ }
419
+
420
+ service.config["workspace"] = ws;
421
+ // allow access for the same workspace
422
+ if (service.config.visibility == "public") {
423
+ return service;
424
+ }
425
+
426
+ // allow access for the same workspace
427
+ if (context["from"].startsWith(ws + "/")) {
428
+ return service;
429
+ }
430
+
431
+ throw new Error(
432
+ `Permission denied for protected service: ${service_id}, workspace mismatch: ${ws} != ${context["from"]}`,
433
+ );
434
+ }
435
+ async get_remote_service(service_uri, timeout) {
436
+ timeout = timeout === undefined ? this._method_timeout : timeout;
437
+ if (!service_uri && this.manager_id) {
438
+ service_uri = this.manager_id;
439
+ } else if (!service_uri.includes(":")) {
440
+ service_uri = this._client_id + ":" + service_uri;
441
+ }
442
+ const provider = service_uri.split(":")[0];
443
+ let service_id = service_uri.split(":")[1];
444
+ if (service_id.includes("@")) {
445
+ service_id = service_id.split("@")[0];
446
+ const app_id = service_uri.split("@")[1];
447
+ if (this._app_id)
448
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
449
+ app_id === this._app_id,
450
+ `Invalid app id: ${app_id} != ${this._app_id}`,
451
+ );
452
+ }
453
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(provider, `Invalid service uri: ${service_uri}`);
454
+
455
+ try {
456
+ const method = this._generate_remote_method({
457
+ _rtarget: provider,
458
+ _rmethod: "services.built-in.get_service",
459
+ _rpromise: true,
460
+ _rdoc: "Get a remote service",
461
+ _rsig: "get_service(service_id)",
462
+ });
463
+ const svc = await (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.waitFor)(
464
+ method(service_id),
465
+ timeout,
466
+ "Timeout Error: Failed to get remote service: " + service_uri,
467
+ );
468
+ svc.id = `${provider}:${service_id}`;
469
+ return svc;
470
+ } catch (e) {
471
+ console.error("Failed to get remote service: " + service_uri, e);
472
+ throw e;
473
+ }
474
+ }
475
+ _annotate_service_methods(
476
+ aObject,
477
+ object_id,
478
+ require_context,
479
+ run_in_executor,
480
+ visibility,
481
+ ) {
482
+ if (typeof aObject === "function") {
483
+ // mark the method as a remote method that requires context
484
+ let method_name = object_id.split(".")[1];
485
+ this._method_annotations.set(aObject, {
486
+ require_context: Array.isArray(require_context)
487
+ ? require_context.includes(method_name)
488
+ : !!require_context,
489
+ run_in_executor: run_in_executor,
490
+ method_id: "services." + object_id,
491
+ visibility: visibility,
492
+ });
493
+ } else if (aObject instanceof Array || aObject instanceof Object) {
494
+ for (let key of Object.keys(aObject)) {
495
+ let val = aObject[key];
496
+ if (typeof val === "function" && val.__rpc_object__) {
497
+ let client_id = val.__rpc_object__._rtarget;
498
+ if (client_id.includes("/")) {
499
+ client_id = client_id.split("/")[1];
500
+ }
501
+ if (this._client_id === client_id) {
502
+ if (aObject instanceof Array) {
503
+ aObject = aObject.slice();
504
+ }
505
+ // recover local method
506
+ aObject[key] = indexObject(
507
+ this._object_store,
508
+ val.__rpc_object__._rmethod,
509
+ );
510
+ val = aObject[key]; // make sure it's annotated later
511
+ } else {
512
+ throw new Error(
513
+ `Local method not found: ${val.__rpc_object__._rmethod}, client id mismatch ${this._client_id} != ${client_id}`,
514
+ );
515
+ }
516
+ }
517
+ this._annotate_service_methods(
518
+ val,
519
+ object_id + "." + key,
520
+ require_context,
521
+ run_in_executor,
522
+ visibility,
523
+ );
524
+ }
525
+ }
526
+ }
527
+ add_service(api, overwrite) {
528
+ if (!api || Array.isArray(api)) throw new Error("Invalid service object");
529
+ if (api.constructor === Object) {
530
+ api = Object.assign({}, api);
531
+ } else {
532
+ const normApi = {};
533
+ const props = Object.getOwnPropertyNames(api).concat(
534
+ Object.getOwnPropertyNames(Object.getPrototypeOf(api)),
535
+ );
536
+ for (let k of props) {
537
+ if (k !== "constructor") {
538
+ if (typeof api[k] === "function") normApi[k] = api[k].bind(api);
539
+ else normApi[k] = api[k];
540
+ }
541
+ }
542
+ // For class instance, we need set a default id
543
+ api.id = api.id || "default";
544
+ api = normApi;
545
+ }
546
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
547
+ api.id && typeof api.id === "string",
548
+ `Service id not found: ${api}`,
549
+ );
550
+ if (!api.name) {
551
+ api.name = api.id;
552
+ }
553
+ if (!api.config) {
554
+ api.config = {};
555
+ }
556
+ if (!api.type) {
557
+ api.type = "generic";
558
+ }
559
+ // require_context only applies to the top-level functions
560
+ let require_context = false,
561
+ run_in_executor = false;
562
+ if (api.config.require_context)
563
+ require_context = api.config.require_context;
564
+ if (api.config.run_in_executor) run_in_executor = true;
565
+ const visibility = api.config.visibility || "protected";
566
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(["protected", "public"].includes(visibility));
567
+ this._annotate_service_methods(
568
+ api,
569
+ api["id"],
570
+ require_context,
571
+ run_in_executor,
572
+ visibility,
573
+ );
574
+
575
+ if (this._services[api.id]) {
576
+ if (overwrite) {
577
+ delete this._services[api.id];
578
+ } else {
579
+ throw new Error(
580
+ `Service already exists: ${api.id}, please specify a different id (not ${api.id}) or overwrite=true`,
581
+ );
582
+ }
583
+ }
584
+ this._services[api.id] = api;
585
+ return api;
586
+ }
587
+
588
+ _extract_service_info(service) {
589
+ return {
590
+ id: `${this._client_id}:${service["id"]}`,
591
+ type: service["type"],
592
+ name: service["name"],
593
+ description: service["description"] || "",
594
+ config: service["config"],
595
+ app_id: this._app_id,
596
+ };
597
+ }
598
+
599
+ async register_service(api, overwrite, notify, context) {
600
+ if (notify === undefined) notify = true;
601
+ if (context) {
602
+ // If this function is called from remote, we need to make sure
603
+ const [workspace, client_id] = context["to"].split("/");
604
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(client_id === this._client_id);
605
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
606
+ workspace === context["from"].split("/")[0],
607
+ "Services can only be registered from the same workspace",
608
+ );
609
+ }
610
+ const service = this.add_service(api, overwrite);
611
+ const serviceInfo = this._extract_service_info(service);
612
+ if (notify) {
613
+ if (this.manager_id) {
614
+ this.emit({
615
+ type: "service-added",
616
+ to: this.manager_id,
617
+ service: serviceInfo,
618
+ });
619
+ } else {
620
+ this.emit({ type: "service-added", to: "*", service: serviceInfo });
621
+ }
622
+ }
623
+ return serviceInfo;
624
+ }
625
+ async unregister_service(service, notify) {
626
+ if (service instanceof Object) {
627
+ service = service.id;
628
+ }
629
+ if (!this._services[service]) {
630
+ throw new Error(`Service not found: ${service}`);
631
+ }
632
+ const api = this._services[service];
633
+ delete this._services[service];
634
+ if (notify) {
635
+ const serviceInfo = this._extract_service_info(api);
636
+ if (this.manager_id) {
637
+ this.emit({
638
+ type: "service-removed",
639
+ to: this.manager_id,
640
+ service: serviceInfo,
641
+ });
642
+ } else {
643
+ this.emit({ type: "service-removed", to: "*", service: serviceInfo });
644
+ }
645
+ }
646
+ }
647
+
648
+ _ndarray(typedArray, shape, dtype) {
649
+ const _dtype = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.typedArrayToDtype)(typedArray);
650
+ if (dtype && dtype !== _dtype) {
651
+ throw (
652
+ "dtype doesn't match the type of the array: " + _dtype + " != " + dtype
653
+ );
654
+ }
655
+ shape = shape || [typedArray.length];
656
+ return {
657
+ _rtype: "ndarray",
658
+ _rvalue: typedArray.buffer,
659
+ _rshape: shape,
660
+ _rdtype: _dtype,
661
+ };
662
+ }
663
+
664
+ _encode_callback(
665
+ name,
666
+ callback,
667
+ session_id,
668
+ clear_after_called,
669
+ timer,
670
+ local_workspace,
671
+ ) {
672
+ let method_id = `${session_id}.${name}`;
673
+ let encoded = {
674
+ _rtype: "method",
675
+ _rtarget: local_workspace
676
+ ? `${local_workspace}/${this._client_id}`
677
+ : this._client_id,
678
+ _rmethod: method_id,
679
+ _rpromise: false,
680
+ };
681
+
682
+ const self = this;
683
+ let wrapped_callback = function () {
684
+ try {
685
+ callback.apply(null, Array.prototype.slice.call(arguments));
686
+ } catch (error) {
687
+ console.error("Error in callback:", method_id, error);
688
+ } finally {
689
+ if (clear_after_called && self._object_store[session_id]) {
690
+ // console.log("Deleting session", session_id, "from", self._client_id);
691
+ delete self._object_store[session_id];
692
+ }
693
+ if (timer && timer.started) {
694
+ timer.clear();
695
+ }
696
+ }
697
+ };
698
+
699
+ return [encoded, wrapped_callback];
700
+ }
701
+
702
+ async _encode_promise(
703
+ resolve,
704
+ reject,
705
+ session_id,
706
+ clear_after_called,
707
+ timer,
708
+ local_workspace,
709
+ ) {
710
+ let store = this._get_session_store(session_id, true);
711
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
712
+ store,
713
+ `Failed to create session store ${session_id} due to invalid parent`,
714
+ );
715
+ let encoded = {};
716
+
717
+ if (timer && reject && this._method_timeout) {
718
+ encoded.heartbeat = await this._encode(
719
+ timer.reset.bind(timer),
720
+ session_id,
721
+ local_workspace,
722
+ );
723
+ encoded.interval = this._method_timeout / 2;
724
+ store.timer = timer;
725
+ } else {
726
+ timer = null;
727
+ }
728
+
729
+ [encoded.resolve, store.resolve] = this._encode_callback(
730
+ "resolve",
731
+ resolve,
732
+ session_id,
733
+ clear_after_called,
734
+ timer,
735
+ local_workspace,
736
+ );
737
+ [encoded.reject, store.reject] = this._encode_callback(
738
+ "reject",
739
+ reject,
740
+ session_id,
741
+ clear_after_called,
742
+ timer,
743
+ local_workspace,
744
+ );
745
+ return encoded;
746
+ }
747
+
748
+ async _send_chunks(data, target_id, session_id) {
749
+ let remote_services = await this.get_remote_service(
750
+ `${target_id}:built-in`,
751
+ );
752
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
753
+ remote_services.message_cache,
754
+ "Remote client does not support message caching for long message.",
755
+ );
756
+ let message_cache = remote_services.message_cache;
757
+ let message_id = session_id || (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)();
758
+ await message_cache.create(message_id, !!session_id);
759
+ let total_size = data.length;
760
+ let chunk_num = Math.ceil(total_size / CHUNK_SIZE);
761
+ for (let idx = 0; idx < chunk_num; idx++) {
762
+ let start_byte = idx * CHUNK_SIZE;
763
+ await message_cache.append(
764
+ message_id,
765
+ data.slice(start_byte, start_byte + CHUNK_SIZE),
766
+ !!session_id,
767
+ );
768
+ console.log(
769
+ `Sending chunk ${idx + 1}/${chunk_num} (${total_size} bytes)`,
770
+ );
771
+ }
772
+ // console.log(`All chunks sent (${chunk_num})`);
773
+ await message_cache.process(message_id, !!session_id);
774
+ }
775
+
776
+ emit(main_message, extra_data) {
777
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
778
+ typeof main_message === "object" && main_message.type,
779
+ "Invalid message, must be an object with a type field.",
780
+ );
781
+ let message_package = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(main_message);
782
+ if (extra_data) {
783
+ const extra = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(extra_data);
784
+ message_package = new Uint8Array([...message_package, ...extra]);
785
+ }
786
+ const total_size = message_package.length;
787
+ if (total_size <= CHUNK_SIZE + 1024) {
788
+ return this._emit_message(message_package);
789
+ } else {
790
+ throw new Error("Message is too large to send in one go.");
791
+ }
792
+ }
793
+
794
+ _generate_remote_method(
795
+ encoded_method,
796
+ remote_parent,
797
+ local_parent,
798
+ remote_workspace,
799
+ local_workspace,
800
+ ) {
801
+ let target_id = encoded_method._rtarget;
802
+ if (remote_workspace && !target_id.includes("/")) {
803
+ if (remote_workspace !== target_id) {
804
+ target_id = remote_workspace + "/" + target_id;
805
+ }
806
+ // Fix the target id to be an absolute id
807
+ encoded_method._rtarget = target_id;
808
+ }
809
+ let method_id = encoded_method._rmethod;
810
+ let with_promise = encoded_method._rpromise;
811
+ const self = this;
812
+
813
+ function remote_method() {
814
+ return new Promise(async (resolve, reject) => {
815
+ let local_session_id = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)();
816
+ if (local_parent) {
817
+ // Store the children session under the parent
818
+ local_session_id = local_parent + "." + local_session_id;
819
+ }
820
+ let store = self._get_session_store(local_session_id, true);
821
+ if (!store) {
822
+ reject(
823
+ new Error(
824
+ `Runtime Error: Failed to get session store ${local_session_id}`,
825
+ ),
826
+ );
827
+ return;
828
+ }
829
+ store["target_id"] = target_id;
830
+ const args = await self._encode(
831
+ Array.prototype.slice.call(arguments),
832
+ local_session_id,
833
+ local_workspace,
834
+ );
835
+ const argLength = args.length;
836
+ // if the last argument is an object, mark it as kwargs
837
+ const withKwargs =
838
+ argLength > 0 &&
839
+ typeof args[argLength - 1] === "object" &&
840
+ args[argLength - 1] !== null &&
841
+ args[argLength - 1]._rkwargs;
842
+ if (withKwargs) delete args[argLength - 1]._rkwargs;
843
+
844
+ let from_client;
845
+ if (!self._local_workspace) {
846
+ from_client = self._client_id;
847
+ } else if (self._local_workspace === "*") {
848
+ from_client = target_id.split("/")[0] + "/" + self._client_id;
849
+ } else {
850
+ from_client = self._local_workspace + "/" + self._client_id;
851
+ }
852
+
853
+ let main_message = {
854
+ type: "method",
855
+ from: from_client,
856
+ to: target_id,
857
+ method: method_id,
858
+ };
859
+ let extra_data = {};
860
+ if (args) {
861
+ extra_data["args"] = args;
862
+ }
863
+ if (withKwargs) {
864
+ extra_data["with_kwargs"] = withKwargs;
865
+ }
866
+
867
+ // console.log(
868
+ // `Calling remote method ${target_id}:${method_id}, session: ${local_session_id}`
869
+ // );
870
+ if (remote_parent) {
871
+ // Set the parent session
872
+ // Note: It's a session id for the remote, not the current client
873
+ main_message["parent"] = remote_parent;
874
+ }
875
+
876
+ let timer = null;
877
+ if (with_promise) {
878
+ // Only pass the current session id to the remote
879
+ // if we want to received the result
880
+ // I.e. the session id won't be passed for promises themselves
881
+ main_message["session"] = local_session_id;
882
+ let method_name = `${target_id}:${method_id}`;
883
+ timer = new Timer(
884
+ self._method_timeout,
885
+ reject,
886
+ [`Method call time out: ${method_name}`],
887
+ method_name,
888
+ );
889
+ // By default, hypha will clear the session after the method is called
890
+ // However, if the args contains _rintf === true, we will not clear the session
891
+ let clear_after_called = true;
892
+ for (let arg of args) {
893
+ if (typeof arg === "object" && arg._rintf === true) {
894
+ clear_after_called = false;
895
+ break;
896
+ }
897
+ }
898
+ extra_data["promise"] = await self._encode_promise(
899
+ resolve,
900
+ reject,
901
+ local_session_id,
902
+ clear_after_called,
903
+ timer,
904
+ local_workspace,
905
+ );
906
+ }
907
+ // The message consists of two segments, the main message and extra data
908
+ let message_package = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(main_message);
909
+ if (extra_data) {
910
+ const extra = (0,_msgpack_msgpack__WEBPACK_IMPORTED_MODULE_2__.encode)(extra_data);
911
+ message_package = new Uint8Array([...message_package, ...extra]);
912
+ }
913
+ const total_size = message_package.length;
914
+ if (total_size <= CHUNK_SIZE + 1024) {
915
+ self._emit_message(message_package).then(function () {
916
+ if (timer) {
917
+ // console.log(`Start watchdog timer.`);
918
+ // Only start the timer after we send the message successfully
919
+ timer.start();
920
+ }
921
+ });
922
+ } else {
923
+ // send chunk by chunk
924
+ self
925
+ ._send_chunks(message_package, target_id, remote_parent)
926
+ .then(function () {
927
+ if (timer) {
928
+ // console.log(`Start watchdog timer.`);
929
+ // Only start the timer after we send the message successfully
930
+ timer.start();
931
+ }
932
+ })
933
+ .catch(function (err) {
934
+ console.error("Failed to send message", err);
935
+ reject(err);
936
+ });
937
+ }
938
+ });
939
+ }
940
+
941
+ // Generate debugging information for the method
942
+ remote_method.__rpc_object__ = encoded_method;
943
+ const parts = method_id.split(".");
944
+ remote_method.__name__ = parts[parts.length - 1];
945
+ remote_method.__doc__ = encoded_method._rdoc;
946
+ remote_method.__sig__ = encoded_method._rsig;
947
+ return remote_method;
948
+ }
949
+
950
+ async _notify_service_update() {
951
+ if (this.manager_id) {
952
+ // try to get the root service
953
+ try {
954
+ await this.get_manager_service(30.0);
955
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(this._manager_service);
956
+ await this._manager_service.update_client_info(this.get_client_info());
957
+ } catch (exp) {
958
+ // pylint: disable=broad-except
959
+ console.warn(
960
+ "Failed to notify service update to",
961
+ this.manager_id,
962
+ exp,
963
+ );
964
+ }
965
+ } else {
966
+ console.warn("No manager id provided, cannot notify service update");
967
+ }
968
+ }
969
+
970
+ get_client_info() {
971
+ const services = [];
972
+ for (let service of Object.values(this._services)) {
973
+ services.push(this._extract_service_info(service));
974
+ }
975
+
976
+ return {
977
+ id: this._client_id,
978
+ services: services,
979
+ };
980
+ }
981
+
982
+ async _handle_method(data) {
983
+ let reject = null;
984
+ let heartbeat_task = null;
985
+ try {
986
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(data["method"] && data["ctx"] && data["from"]);
987
+ const method_name = data.from + ":" + data.method;
988
+ const remote_workspace = data.from.split("/")[0];
989
+ // Make sure the target id is an absolute id
990
+ data["to"] = data["to"].includes("/")
991
+ ? data["to"]
992
+ : remote_workspace + "/" + data["to"];
993
+ data["ctx"]["to"] = data["to"];
994
+ let local_workspace;
995
+ if (!this._local_workspace) {
996
+ local_workspace = data["to"].split("/")[0];
997
+ } else if (this._local_workspace === "*") {
998
+ local_workspace = remote_workspace;
999
+ } else {
1000
+ if (this._local_workspace) {
1001
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
1002
+ data["to"].split("/")[0] === this._local_workspace,
1003
+ "Workspace mismatch: " +
1004
+ data["to"].split("/")[0] +
1005
+ " != " +
1006
+ this._local_workspace,
1007
+ );
1008
+ }
1009
+ local_workspace = this._local_workspace;
1010
+ }
1011
+ const local_parent = data.parent;
1012
+
1013
+ let resolve, reject;
1014
+ if (data.promise) {
1015
+ // Decode the promise with the remote session id
1016
+ // Such that the session id will be passed to the remote as a parent session id
1017
+ const promise = await this._decode(
1018
+ data.promise,
1019
+ data.session,
1020
+ local_parent,
1021
+ remote_workspace,
1022
+ local_workspace,
1023
+ );
1024
+ resolve = promise.resolve;
1025
+ reject = promise.reject;
1026
+ if (promise.heartbeat && promise.interval) {
1027
+ async function heartbeat() {
1028
+ try {
1029
+ console.log("Reset heartbeat timer: " + data.method);
1030
+ await promise.heartbeat();
1031
+ } catch (err) {
1032
+ console.error(err);
1033
+ }
1034
+ }
1035
+ heartbeat_task = setInterval(heartbeat, promise.interval * 1000);
1036
+ }
1037
+ }
1038
+
1039
+ let method;
1040
+
1041
+ try {
1042
+ method = indexObject(this._object_store, data["method"]);
1043
+ } catch (e) {
1044
+ console.debug("Failed to find method", method_name, e);
1045
+ throw new Error(`Method not found: ${method_name}`);
1046
+ }
1047
+
1048
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
1049
+ method && typeof method === "function",
1050
+ "Invalid method: " + method_name,
1051
+ );
1052
+
1053
+ // Check permission
1054
+ if (this._method_annotations.has(method)) {
1055
+ // For services, it should not be protected
1056
+ if (this._method_annotations.get(method).visibility === "protected") {
1057
+ if (local_workspace !== remote_workspace) {
1058
+ throw new Error(
1059
+ "Permission denied for protected method " +
1060
+ method_name +
1061
+ ", workspace mismatch: " +
1062
+ local_workspace +
1063
+ " != " +
1064
+ remote_workspace,
1065
+ );
1066
+ }
1067
+ }
1068
+ } else {
1069
+ // For sessions, the target_id should match exactly
1070
+ let session_target_id =
1071
+ this._object_store[data.method.split(".")[0]].target_id;
1072
+ if (
1073
+ local_workspace === remote_workspace &&
1074
+ session_target_id &&
1075
+ session_target_id.indexOf("/") === -1
1076
+ ) {
1077
+ session_target_id = local_workspace + "/" + session_target_id;
1078
+ }
1079
+ if (this._local_workspace !== "*" && session_target_id !== data.from) {
1080
+ throw new Error(
1081
+ "Access denied for method call (" +
1082
+ method_name +
1083
+ ") from " +
1084
+ data.from +
1085
+ " to target " +
1086
+ session_target_id,
1087
+ );
1088
+ }
1089
+ }
1090
+
1091
+ // Make sure the parent session is still open
1092
+ if (local_parent) {
1093
+ // The parent session should be a session that generate the current method call
1094
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
1095
+ this._get_session_store(local_parent, true) !== null,
1096
+ "Parent session was closed: " + local_parent,
1097
+ );
1098
+ }
1099
+ let args;
1100
+ if (data.args) {
1101
+ args = await this._decode(
1102
+ data.args,
1103
+ data.session,
1104
+ null,
1105
+ remote_workspace,
1106
+ null,
1107
+ );
1108
+ } else {
1109
+ args = [];
1110
+ }
1111
+ if (
1112
+ this._method_annotations.has(method) &&
1113
+ this._method_annotations.get(method).require_context
1114
+ ) {
1115
+ args.push(data.ctx);
1116
+ }
1117
+ // console.log("Executing method: " + method_name);
1118
+ if (data.promise) {
1119
+ const result = method.apply(null, args);
1120
+ if (result instanceof Promise) {
1121
+ result
1122
+ .then((result) => {
1123
+ resolve(result);
1124
+ clearInterval(heartbeat_task);
1125
+ })
1126
+ .catch((err) => {
1127
+ reject(err);
1128
+ clearInterval(heartbeat_task);
1129
+ });
1130
+ } else {
1131
+ resolve(result);
1132
+ clearInterval(heartbeat_task);
1133
+ }
1134
+ } else {
1135
+ method.apply(null, args);
1136
+ clearInterval(heartbeat_task);
1137
+ }
1138
+ } catch (err) {
1139
+ if (reject) {
1140
+ reject(err);
1141
+ console.debug("Error during calling method: ", err);
1142
+ } else {
1143
+ console.error("Error during calling method: ", err);
1144
+ }
1145
+ // make sure we clear the heartbeat timer
1146
+ clearInterval(heartbeat_task);
1147
+ }
1148
+ }
1149
+
1150
+ encode(aObject, session_id) {
1151
+ return this._encode(aObject, session_id);
1152
+ }
1153
+
1154
+ _get_session_store(session_id, create) {
1155
+ let store = this._object_store;
1156
+ const levels = session_id.split(".");
1157
+ if (create) {
1158
+ const last_index = levels.length - 1;
1159
+ for (let level of levels.slice(0, last_index)) {
1160
+ if (!store[level]) {
1161
+ return null;
1162
+ }
1163
+ store = store[level];
1164
+ }
1165
+ // Create the last level
1166
+ if (!store[levels[last_index]]) {
1167
+ store[levels[last_index]] = {};
1168
+ }
1169
+ return store[levels[last_index]];
1170
+ } else {
1171
+ for (let level of levels) {
1172
+ if (!store[level]) {
1173
+ return null;
1174
+ }
1175
+ store = store[level];
1176
+ }
1177
+ return store;
1178
+ }
1179
+ }
1180
+
1181
+ /**
1182
+ * Prepares the provided set of remote method arguments for
1183
+ * sending to the remote site, replaces all the callbacks with
1184
+ * identifiers
1185
+ *
1186
+ * @param {Array} args to wrap
1187
+ *
1188
+ * @returns {Array} wrapped arguments
1189
+ */
1190
+ async _encode(aObject, session_id, local_workspace) {
1191
+ const aType = typeof aObject;
1192
+ if (
1193
+ aType === "number" ||
1194
+ aType === "string" ||
1195
+ aType === "boolean" ||
1196
+ aObject === null ||
1197
+ aObject === undefined ||
1198
+ aObject instanceof Uint8Array
1199
+ ) {
1200
+ return aObject;
1201
+ }
1202
+ if (aObject instanceof ArrayBuffer) {
1203
+ return {
1204
+ _rtype: "memoryview",
1205
+ _rvalue: new Uint8Array(aObject),
1206
+ };
1207
+ }
1208
+ // Reuse the remote object
1209
+ if (aObject.__rpc_object__) {
1210
+ return aObject.__rpc_object__;
1211
+ }
1212
+
1213
+ let bObject;
1214
+
1215
+ // skip if already encoded
1216
+ if (aObject.constructor instanceof Object && aObject._rtype) {
1217
+ // make sure the interface functions are encoded
1218
+ const temp = aObject._rtype;
1219
+ delete aObject._rtype;
1220
+ bObject = await this._encode(aObject, session_id, local_workspace);
1221
+ bObject._rtype = temp;
1222
+ return bObject;
1223
+ }
1224
+
1225
+ if (typeof aObject === "function") {
1226
+ if (this._method_annotations.has(aObject)) {
1227
+ let annotation = this._method_annotations.get(aObject);
1228
+ bObject = {
1229
+ _rtype: "method",
1230
+ _rtarget: this._client_id,
1231
+ _rmethod: annotation.method_id,
1232
+ _rpromise: true,
1233
+ };
1234
+ } else {
1235
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(typeof session_id === "string");
1236
+ let object_id;
1237
+ if (aObject.__name__) {
1238
+ object_id = `${(0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)()}-${aObject.__name__}`;
1239
+ } else {
1240
+ object_id = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.randId)();
1241
+ }
1242
+ bObject = {
1243
+ _rtype: "method",
1244
+ _rtarget: this._client_id,
1245
+ _rmethod: `${session_id}.${object_id}`,
1246
+ _rpromise: true,
1247
+ };
1248
+ let store = this._get_session_store(session_id, true);
1249
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.assert)(
1250
+ store !== null,
1251
+ `Failed to create session store ${session_id} due to invalid parent`,
1252
+ );
1253
+ store[object_id] = aObject;
1254
+ }
1255
+ bObject._rdoc = aObject.__doc__;
1256
+ bObject._rsig = aObject.__sig__;
1257
+ if (!bObject._rdoc || !bObject._rsig) {
1258
+ try {
1259
+ const funcInfo = getFunctionInfo(aObject);
1260
+ if (funcInfo && !bObject._rdoc) {
1261
+ bObject._rdoc = `${funcInfo.doc}`;
1262
+ }
1263
+ if (funcInfo && !bObject._rsig) {
1264
+ bObject._rsig = `${funcInfo.name}(${funcInfo.sig})`;
1265
+ }
1266
+ } catch (e) {
1267
+ console.error("Failed to extract function docstring:", aObject);
1268
+ }
1269
+ }
1270
+
1271
+ return bObject;
1272
+ }
1273
+ const isarray = Array.isArray(aObject);
1274
+
1275
+ for (let tp of Object.keys(this._codecs)) {
1276
+ const codec = this._codecs[tp];
1277
+ if (codec.encoder && aObject instanceof codec.type) {
1278
+ // TODO: what if multiple encoders found
1279
+ let encodedObj = await Promise.resolve(codec.encoder(aObject));
1280
+ if (encodedObj && !encodedObj._rtype) encodedObj._rtype = codec.name;
1281
+ // encode the functions in the interface object
1282
+ if (typeof encodedObj === "object") {
1283
+ const temp = encodedObj._rtype;
1284
+ delete encodedObj._rtype;
1285
+ encodedObj = await this._encode(
1286
+ encodedObj,
1287
+ session_id,
1288
+ local_workspace,
1289
+ );
1290
+ encodedObj._rtype = temp;
1291
+ }
1292
+ bObject = encodedObj;
1293
+ return bObject;
1294
+ }
1295
+ }
1296
+
1297
+ if (
1298
+ /*global tf*/
1299
+ typeof tf !== "undefined" &&
1300
+ tf.Tensor &&
1301
+ aObject instanceof tf.Tensor
1302
+ ) {
1303
+ const v_buffer = aObject.dataSync();
1304
+ bObject = {
1305
+ _rtype: "ndarray",
1306
+ _rvalue: new Uint8Array(v_buffer.buffer),
1307
+ _rshape: aObject.shape,
1308
+ _rdtype: aObject.dtype,
1309
+ };
1310
+ } else if (
1311
+ /*global nj*/
1312
+ typeof nj !== "undefined" &&
1313
+ nj.NdArray &&
1314
+ aObject instanceof nj.NdArray
1315
+ ) {
1316
+ const dtype = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.typedArrayToDtype)(aObject.selection.data);
1317
+ bObject = {
1318
+ _rtype: "ndarray",
1319
+ _rvalue: new Uint8Array(aObject.selection.data.buffer),
1320
+ _rshape: aObject.shape,
1321
+ _rdtype: dtype,
1322
+ };
1323
+ } else if (aObject instanceof Error) {
1324
+ console.error(aObject);
1325
+ bObject = {
1326
+ _rtype: "error",
1327
+ _rvalue: aObject.toString(),
1328
+ _rtrace: aObject.stack,
1329
+ };
1330
+ }
1331
+ // send objects supported by structure clone algorithm
1332
+ // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
1333
+ else if (
1334
+ aObject !== Object(aObject) ||
1335
+ aObject instanceof Boolean ||
1336
+ aObject instanceof String ||
1337
+ aObject instanceof Date ||
1338
+ aObject instanceof RegExp ||
1339
+ aObject instanceof ImageData ||
1340
+ (typeof FileList !== "undefined" && aObject instanceof FileList) ||
1341
+ (typeof FileSystemDirectoryHandle !== "undefined" &&
1342
+ aObject instanceof FileSystemDirectoryHandle) ||
1343
+ (typeof FileSystemFileHandle !== "undefined" &&
1344
+ aObject instanceof FileSystemFileHandle) ||
1345
+ (typeof FileSystemHandle !== "undefined" &&
1346
+ aObject instanceof FileSystemHandle) ||
1347
+ (typeof FileSystemWritableFileStream !== "undefined" &&
1348
+ aObject instanceof FileSystemWritableFileStream)
1349
+ ) {
1350
+ bObject = aObject;
1351
+ // TODO: avoid object such as DynamicPlugin instance.
1352
+ } else if (aObject instanceof Blob) {
1353
+ let _current_pos = 0;
1354
+ async function read(length) {
1355
+ let blob;
1356
+ if (length) {
1357
+ blob = aObject.slice(_current_pos, _current_pos + length);
1358
+ } else {
1359
+ blob = aObject.slice(_current_pos);
1360
+ }
1361
+ const ret = new Uint8Array(await blob.arrayBuffer());
1362
+ _current_pos = _current_pos + ret.byteLength;
1363
+ return ret;
1364
+ }
1365
+ function seek(pos) {
1366
+ _current_pos = pos;
1367
+ }
1368
+ bObject = {
1369
+ _rtype: "iostream",
1370
+ _rnative: "js:blob",
1371
+ type: aObject.type,
1372
+ name: aObject.name,
1373
+ size: aObject.size,
1374
+ path: aObject._path || aObject.webkitRelativePath,
1375
+ read: await this._encode(read, session_id, local_workspace),
1376
+ seek: await this._encode(seek, session_id, local_workspace),
1377
+ };
1378
+ } else if (aObject instanceof ArrayBufferView) {
1379
+ const dtype = (0,_utils_js__WEBPACK_IMPORTED_MODULE_0__.typedArrayToDtype)(aObject);
1380
+ bObject = {
1381
+ _rtype: "typedarray",
1382
+ _rvalue: new Uint8Array(aObject.buffer),
1383
+ _rdtype: dtype,
1384
+ };
1385
+ } else if (aObject instanceof DataView) {
1386
+ bObject = {
1387
+ _rtype: "memoryview",
1388
+ _rvalue: new Uint8Array(aObject.buffer),
1389
+ };
1390
+ } else if (aObject instanceof Set) {
1391
+ bObject = {
1392
+ _rtype: "set",
1393
+ _rvalue: await this._encode(
1394
+ Array.from(aObject),
1395
+ session_id,
1396
+ local_workspace,
1397
+ ),
1398
+ };
1399
+ } else if (aObject instanceof Map) {
1400
+ bObject = {
1401
+ _rtype: "orderedmap",
1402
+ _rvalue: await this._encode(
1403
+ Array.from(aObject),
1404
+ session_id,
1405
+ local_workspace,
1406
+ ),
1407
+ };
1408
+ } else if (
1409
+ aObject.constructor instanceof Object ||
1410
+ Array.isArray(aObject)
1411
+ ) {
1412
+ bObject = isarray ? [] : {};
1413
+ const keys = Object.keys(aObject);
1414
+ for (let k of keys) {
1415
+ bObject[k] = await this._encode(
1416
+ aObject[k],
1417
+ session_id,
1418
+ local_workspace,
1419
+ );
1420
+ }
1421
+ } else {
1422
+ throw `hypha-rpc: Unsupported data type: ${aObject}, you can register a custom codec to encode/decode the object.`;
1423
+ }
1424
+
1425
+ if (!bObject) {
1426
+ throw new Error("Failed to encode object");
1427
+ }
1428
+ return bObject;
1429
+ }
1430
+
1431
+ async decode(aObject) {
1432
+ return await this._decode(aObject);
1433
+ }
1434
+
1435
+ async _decode(
1436
+ aObject,
1437
+ remote_parent,
1438
+ local_parent,
1439
+ remote_workspace,
1440
+ local_workspace,
1441
+ ) {
1442
+ if (!aObject) {
1443
+ return aObject;
1444
+ }
1445
+ let bObject;
1446
+ if (aObject._rtype) {
1447
+ if (
1448
+ this._codecs[aObject._rtype] &&
1449
+ this._codecs[aObject._rtype].decoder
1450
+ ) {
1451
+ const temp = aObject._rtype;
1452
+ delete aObject._rtype;
1453
+ aObject = await this._decode(
1454
+ aObject,
1455
+ remote_parent,
1456
+ local_parent,
1457
+ remote_workspace,
1458
+ local_workspace,
1459
+ );
1460
+ aObject._rtype = temp;
1461
+
1462
+ bObject = await Promise.resolve(
1463
+ this._codecs[aObject._rtype].decoder(aObject),
1464
+ );
1465
+ } else if (aObject._rtype === "method") {
1466
+ bObject = this._generate_remote_method(
1467
+ aObject,
1468
+ remote_parent,
1469
+ local_parent,
1470
+ remote_workspace,
1471
+ local_workspace,
1472
+ );
1473
+ } else if (aObject._rtype === "ndarray") {
1474
+ /*global nj tf*/
1475
+ //create build array/tensor if used in the plugin
1476
+ if (typeof nj !== "undefined" && nj.array) {
1477
+ if (Array.isArray(aObject._rvalue)) {
1478
+ aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);
1479
+ }
1480
+ bObject = nj
1481
+ .array(new Uint8(aObject._rvalue), aObject._rdtype)
1482
+ .reshape(aObject._rshape);
1483
+ } else if (typeof tf !== "undefined" && tf.Tensor) {
1484
+ if (Array.isArray(aObject._rvalue)) {
1485
+ aObject._rvalue = aObject._rvalue.reduce(_appendBuffer);
1486
+ }
1487
+ const arraytype = _utils_js__WEBPACK_IMPORTED_MODULE_0__.dtypeToTypedArray[aObject._rdtype];
1488
+ bObject = tf.tensor(
1489
+ new arraytype(aObject._rvalue),
1490
+ aObject._rshape,
1491
+ aObject._rdtype,
1492
+ );
1493
+ } else {
1494
+ //keep it as regular if transfered to the main app
1495
+ bObject = aObject;
1496
+ }
1497
+ } else if (aObject._rtype === "error") {
1498
+ bObject = new Error(
1499
+ "RemoteError: " + aObject._rvalue + "\n" + (aObject._rtrace || ""),
1500
+ );
1501
+ } else if (aObject._rtype === "typedarray") {
1502
+ const arraytype = _utils_js__WEBPACK_IMPORTED_MODULE_0__.dtypeToTypedArray[aObject._rdtype];
1503
+ if (!arraytype)
1504
+ throw new Error("unsupported dtype: " + aObject._rdtype);
1505
+ const buffer = aObject._rvalue.buffer.slice(
1506
+ aObject._rvalue.byteOffset,
1507
+ aObject._rvalue.byteOffset + aObject._rvalue.byteLength,
1508
+ );
1509
+ bObject = new arraytype(buffer);
1510
+ } else if (aObject._rtype === "memoryview") {
1511
+ bObject = aObject._rvalue.buffer.slice(
1512
+ aObject._rvalue.byteOffset,
1513
+ aObject._rvalue.byteOffset + aObject._rvalue.byteLength,
1514
+ ); // ArrayBuffer
1515
+ } else if (aObject._rtype === "iostream") {
1516
+ if (aObject._rnative === "js:blob") {
1517
+ const read = await this._generate_remote_method(
1518
+ aObject.read,
1519
+ remote_parent,
1520
+ local_parent,
1521
+ remote_workspace,
1522
+ local_workspace,
1523
+ );
1524
+ const bytes = await read();
1525
+ bObject = new Blob([bytes], {
1526
+ type: aObject.type,
1527
+ name: aObject.name,
1528
+ });
1529
+ } else {
1530
+ bObject = {};
1531
+ for (let k of Object.keys(aObject)) {
1532
+ if (!k.startsWith("_")) {
1533
+ bObject[k] = await this._decode(
1534
+ aObject[k],
1535
+ remote_parent,
1536
+ local_parent,
1537
+ remote_workspace,
1538
+ local_workspace,
1539
+ );
1540
+ }
1541
+ }
1542
+ }
1543
+ bObject["__rpc_object__"] = aObject;
1544
+ } else if (aObject._rtype === "orderedmap") {
1545
+ bObject = new Map(
1546
+ await this._decode(
1547
+ aObject._rvalue,
1548
+ remote_parent,
1549
+ local_parent,
1550
+ remote_workspace,
1551
+ local_workspace,
1552
+ ),
1553
+ );
1554
+ } else if (aObject._rtype === "set") {
1555
+ bObject = new Set(
1556
+ await this._decode(
1557
+ aObject._rvalue,
1558
+ remote_parent,
1559
+ local_parent,
1560
+ remote_workspace,
1561
+ local_workspace,
1562
+ ),
1563
+ );
1564
+ } else {
1565
+ const temp = aObject._rtype;
1566
+ delete aObject._rtype;
1567
+ bObject = await this._decode(
1568
+ aObject,
1569
+ remote_parent,
1570
+ local_parent,
1571
+ remote_workspace,
1572
+ local_workspace,
1573
+ );
1574
+ bObject._rtype = temp;
1575
+ }
1576
+ } else if (aObject.constructor === Object || Array.isArray(aObject)) {
1577
+ const isarray = Array.isArray(aObject);
1578
+ bObject = isarray ? [] : {};
1579
+ for (let k of Object.keys(aObject)) {
1580
+ if (isarray || aObject.hasOwnProperty(k)) {
1581
+ const v = aObject[k];
1582
+ bObject[k] = await this._decode(
1583
+ v,
1584
+ remote_parent,
1585
+ local_parent,
1586
+ remote_workspace,
1587
+ local_workspace,
1588
+ );
1589
+ }
1590
+ }
1591
+ } else {
1592
+ bObject = aObject;
1593
+ }
1594
+ if (bObject === undefined) {
1595
+ throw new Error("Failed to decode object");
1596
+ }
1597
+ return bObject;
1598
+ }
1599
+ }
1600
+
1601
+
1602
+ /***/ }),
1603
+
1604
+ /***/ "./src/utils.js":
1605
+ /*!**********************!*\
1606
+ !*** ./src/utils.js ***!
1607
+ \**********************/
1608
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1609
+
1610
+ __webpack_require__.r(__webpack_exports__);
1611
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1612
+ /* harmony export */ MessageEmitter: () => (/* binding */ MessageEmitter),
1613
+ /* harmony export */ assert: () => (/* binding */ assert),
1614
+ /* harmony export */ cacheRequirements: () => (/* binding */ cacheRequirements),
1615
+ /* harmony export */ dtypeToTypedArray: () => (/* binding */ dtypeToTypedArray),
1616
+ /* harmony export */ loadRequirements: () => (/* binding */ loadRequirements),
1617
+ /* harmony export */ loadRequirementsInWebworker: () => (/* binding */ loadRequirementsInWebworker),
1618
+ /* harmony export */ loadRequirementsInWindow: () => (/* binding */ loadRequirementsInWindow),
1619
+ /* harmony export */ normalizeConfig: () => (/* binding */ normalizeConfig),
1620
+ /* harmony export */ randId: () => (/* binding */ randId),
1621
+ /* harmony export */ typedArrayToDtype: () => (/* binding */ typedArrayToDtype),
1622
+ /* harmony export */ typedArrayToDtypeMapping: () => (/* binding */ typedArrayToDtypeMapping),
1623
+ /* harmony export */ urlJoin: () => (/* binding */ urlJoin),
1624
+ /* harmony export */ waitFor: () => (/* binding */ waitFor)
1625
+ /* harmony export */ });
1626
+ function randId() {
1627
+ return Math.random().toString(36).substr(2, 10) + new Date().getTime();
1628
+ }
1629
+
1630
+ const dtypeToTypedArray = {
1631
+ int8: Int8Array,
1632
+ int16: Int16Array,
1633
+ int32: Int32Array,
1634
+ uint8: Uint8Array,
1635
+ uint16: Uint16Array,
1636
+ uint32: Uint32Array,
1637
+ float32: Float32Array,
1638
+ float64: Float64Array,
1639
+ array: Array,
1640
+ };
1641
+
1642
+ async function loadRequirementsInWindow(requirements) {
1643
+ function _importScript(url) {
1644
+ //url is URL of external file, implementationCode is the code
1645
+ //to be called from the file, location is the location to
1646
+ //insert the <script> element
1647
+ return new Promise((resolve, reject) => {
1648
+ var scriptTag = document.createElement("script");
1649
+ scriptTag.src = url;
1650
+ scriptTag.type = "text/javascript";
1651
+ scriptTag.onload = resolve;
1652
+ scriptTag.onreadystatechange = function () {
1653
+ if (this.readyState === "loaded" || this.readyState === "complete") {
1654
+ resolve();
1655
+ }
1656
+ };
1657
+ scriptTag.onerror = reject;
1658
+ document.head.appendChild(scriptTag);
1659
+ });
1660
+ }
1661
+
1662
+ // support importScripts outside web worker
1663
+ async function importScripts() {
1664
+ var args = Array.prototype.slice.call(arguments),
1665
+ len = args.length,
1666
+ i = 0;
1667
+ for (; i < len; i++) {
1668
+ await _importScript(args[i]);
1669
+ }
1670
+ }
1671
+
1672
+ if (
1673
+ requirements &&
1674
+ (Array.isArray(requirements) || typeof requirements === "string")
1675
+ ) {
1676
+ try {
1677
+ var link_node;
1678
+ requirements =
1679
+ typeof requirements === "string" ? [requirements] : requirements;
1680
+ if (Array.isArray(requirements)) {
1681
+ for (var i = 0; i < requirements.length; i++) {
1682
+ if (
1683
+ requirements[i].toLowerCase().endsWith(".css") ||
1684
+ requirements[i].startsWith("css:")
1685
+ ) {
1686
+ if (requirements[i].startsWith("css:")) {
1687
+ requirements[i] = requirements[i].slice(4);
1688
+ }
1689
+ link_node = document.createElement("link");
1690
+ link_node.rel = "stylesheet";
1691
+ link_node.href = requirements[i];
1692
+ document.head.appendChild(link_node);
1693
+ } else if (
1694
+ requirements[i].toLowerCase().endsWith(".mjs") ||
1695
+ requirements[i].startsWith("mjs:")
1696
+ ) {
1697
+ // import esmodule
1698
+ if (requirements[i].startsWith("mjs:")) {
1699
+ requirements[i] = requirements[i].slice(4);
1700
+ }
1701
+ await import(/* webpackIgnore: true */ requirements[i]);
1702
+ } else if (
1703
+ requirements[i].toLowerCase().endsWith(".js") ||
1704
+ requirements[i].startsWith("js:")
1705
+ ) {
1706
+ if (requirements[i].startsWith("js:")) {
1707
+ requirements[i] = requirements[i].slice(3);
1708
+ }
1709
+ await importScripts(requirements[i]);
1710
+ } else if (requirements[i].startsWith("http")) {
1711
+ await importScripts(requirements[i]);
1712
+ } else if (requirements[i].startsWith("cache:")) {
1713
+ //ignore cache
1714
+ } else {
1715
+ console.log("Unprocessed requirements url: " + requirements[i]);
1716
+ }
1717
+ }
1718
+ } else {
1719
+ throw "unsupported requirements definition";
1720
+ }
1721
+ } catch (e) {
1722
+ throw "failed to import required scripts: " + requirements.toString();
1723
+ }
1724
+ }
1725
+ }
1726
+
1727
+ async function loadRequirementsInWebworker(requirements) {
1728
+ if (
1729
+ requirements &&
1730
+ (Array.isArray(requirements) || typeof requirements === "string")
1731
+ ) {
1732
+ try {
1733
+ if (!Array.isArray(requirements)) {
1734
+ requirements = [requirements];
1735
+ }
1736
+ for (var i = 0; i < requirements.length; i++) {
1737
+ if (
1738
+ requirements[i].toLowerCase().endsWith(".css") ||
1739
+ requirements[i].startsWith("css:")
1740
+ ) {
1741
+ throw "unable to import css in a webworker";
1742
+ } else if (
1743
+ requirements[i].toLowerCase().endsWith(".js") ||
1744
+ requirements[i].startsWith("js:")
1745
+ ) {
1746
+ if (requirements[i].startsWith("js:")) {
1747
+ requirements[i] = requirements[i].slice(3);
1748
+ }
1749
+ importScripts(requirements[i]);
1750
+ } else if (requirements[i].startsWith("http")) {
1751
+ importScripts(requirements[i]);
1752
+ } else if (requirements[i].startsWith("cache:")) {
1753
+ //ignore cache
1754
+ } else {
1755
+ console.log("Unprocessed requirements url: " + requirements[i]);
1756
+ }
1757
+ }
1758
+ } catch (e) {
1759
+ throw "failed to import required scripts: " + requirements.toString();
1760
+ }
1761
+ }
1762
+ }
1763
+
1764
+ function loadRequirements(requirements) {
1765
+ if (
1766
+ typeof WorkerGlobalScope !== "undefined" &&
1767
+ self instanceof WorkerGlobalScope
1768
+ ) {
1769
+ return loadRequirementsInWebworker(requirements);
1770
+ } else {
1771
+ return loadRequirementsInWindow(requirements);
1772
+ }
1773
+ }
1774
+
1775
+ function normalizeConfig(config) {
1776
+ config.version = config.version || "0.1.0";
1777
+ config.description =
1778
+ config.description || `[TODO: add description for ${config.name} ]`;
1779
+ config.type = config.type || "rpc-window";
1780
+ config.id = config.id || randId();
1781
+ config.target_origin = config.target_origin || "*";
1782
+ config.allow_execution = config.allow_execution || false;
1783
+ // remove functions
1784
+ config = Object.keys(config).reduce((p, c) => {
1785
+ if (typeof config[c] !== "function") p[c] = config[c];
1786
+ return p;
1787
+ }, {});
1788
+ return config;
1789
+ }
1790
+ const typedArrayToDtypeMapping = {
1791
+ Int8Array: "int8",
1792
+ Int16Array: "int16",
1793
+ Int32Array: "int32",
1794
+ Uint8Array: "uint8",
1795
+ Uint16Array: "uint16",
1796
+ Uint32Array: "uint32",
1797
+ Float32Array: "float32",
1798
+ Float64Array: "float64",
1799
+ Array: "array",
1800
+ };
1801
+
1802
+ const typedArrayToDtypeKeys = [];
1803
+ for (const arrType of Object.keys(typedArrayToDtypeMapping)) {
1804
+ typedArrayToDtypeKeys.push(eval(arrType));
1805
+ }
1806
+
1807
+ function typedArrayToDtype(obj) {
1808
+ let dtype = typedArrayToDtypeMapping[obj.constructor.name];
1809
+ if (!dtype) {
1810
+ const pt = Object.getPrototypeOf(obj);
1811
+ for (const arrType of typedArrayToDtypeKeys) {
1812
+ if (pt instanceof arrType) {
1813
+ dtype = typedArrayToDtypeMapping[arrType.name];
1814
+ break;
1815
+ }
1816
+ }
1817
+ }
1818
+ return dtype;
1819
+ }
1820
+
1821
+ function cacheUrlInServiceWorker(url) {
1822
+ return new Promise(function (resolve, reject) {
1823
+ const message = {
1824
+ command: "add",
1825
+ url: url,
1826
+ };
1827
+ if (!navigator.serviceWorker || !navigator.serviceWorker.register) {
1828
+ reject("Service worker is not supported.");
1829
+ return;
1830
+ }
1831
+ const messageChannel = new MessageChannel();
1832
+ messageChannel.port1.onmessage = function (event) {
1833
+ if (event.data && event.data.error) {
1834
+ reject(event.data.error);
1835
+ } else {
1836
+ resolve(event.data && event.data.result);
1837
+ }
1838
+ };
1839
+
1840
+ if (navigator.serviceWorker && navigator.serviceWorker.controller) {
1841
+ navigator.serviceWorker.controller.postMessage(message, [
1842
+ messageChannel.port2,
1843
+ ]);
1844
+ } else {
1845
+ reject("Service worker controller is not available");
1846
+ }
1847
+ });
1848
+ }
1849
+
1850
+ async function cacheRequirements(requirements) {
1851
+ requirements = requirements || [];
1852
+ if (!Array.isArray(requirements)) {
1853
+ requirements = [requirements];
1854
+ }
1855
+ for (let req of requirements) {
1856
+ //remove prefix
1857
+ if (req.startsWith("js:")) req = req.slice(3);
1858
+ if (req.startsWith("css:")) req = req.slice(4);
1859
+ if (req.startsWith("cache:")) req = req.slice(6);
1860
+ if (!req.startsWith("http")) continue;
1861
+
1862
+ await cacheUrlInServiceWorker(req).catch((e) => {
1863
+ console.error(e);
1864
+ });
1865
+ }
1866
+ }
1867
+
1868
+ function assert(condition, message) {
1869
+ if (!condition) {
1870
+ throw new Error(message || "Assertion failed");
1871
+ }
1872
+ }
1873
+
1874
+ //#Source https://bit.ly/2neWfJ2
1875
+ function urlJoin(...args) {
1876
+ return args
1877
+ .join("/")
1878
+ .replace(/[\/]+/g, "/")
1879
+ .replace(/^(.+):\//, "$1://")
1880
+ .replace(/^file:/, "file:/")
1881
+ .replace(/\/(\?|&|#[^!])/g, "$1")
1882
+ .replace(/\?/g, "&")
1883
+ .replace("&", "?");
1884
+ }
1885
+
1886
+ function waitFor(prom, time, error) {
1887
+ let timer;
1888
+ return Promise.race([
1889
+ prom,
1890
+ new Promise(
1891
+ (_r, rej) =>
1892
+ (timer = setTimeout(() => {
1893
+ rej(error || "Timeout Error");
1894
+ }, time * 1000)),
1895
+ ),
1896
+ ]).finally(() => clearTimeout(timer));
1897
+ }
1898
+
1899
+ class MessageEmitter {
1900
+ constructor(debug) {
1901
+ this._event_handlers = {};
1902
+ this._once_handlers = {};
1903
+ this._debug = debug;
1904
+ }
1905
+ emit() {
1906
+ throw new Error("emit is not implemented");
1907
+ }
1908
+ on(event, handler) {
1909
+ if (!this._event_handlers[event]) {
1910
+ this._event_handlers[event] = [];
1911
+ }
1912
+ this._event_handlers[event].push(handler);
1913
+ }
1914
+ once(event, handler) {
1915
+ handler.___event_run_once = true;
1916
+ this.on(event, handler);
1917
+ }
1918
+ off(event, handler) {
1919
+ if (!event && !handler) {
1920
+ // remove all events handlers
1921
+ this._event_handlers = {};
1922
+ } else if (event && !handler) {
1923
+ // remove all hanlders for the event
1924
+ if (this._event_handlers[event]) this._event_handlers[event] = [];
1925
+ } else {
1926
+ // remove a specific handler
1927
+ if (this._event_handlers[event]) {
1928
+ const idx = this._event_handlers[event].indexOf(handler);
1929
+ if (idx >= 0) {
1930
+ this._event_handlers[event].splice(idx, 1);
1931
+ }
1932
+ }
1933
+ }
1934
+ }
1935
+ _fire(event, data) {
1936
+ if (this._event_handlers[event]) {
1937
+ var i = this._event_handlers[event].length;
1938
+ while (i--) {
1939
+ const handler = this._event_handlers[event][i];
1940
+ try {
1941
+ handler(data);
1942
+ } catch (e) {
1943
+ console.error(e);
1944
+ } finally {
1945
+ if (handler.___event_run_once) {
1946
+ this._event_handlers[event].splice(i, 1);
1947
+ }
1948
+ }
1949
+ }
1950
+ } else {
1951
+ if (this._debug) {
1952
+ console.warn("unhandled event", event, data);
1953
+ }
1954
+ }
1955
+ }
1956
+ }
1957
+
1958
+
1959
+ /***/ }),
1960
+
1961
+ /***/ "./src/webrtc-client.js":
1962
+ /*!******************************!*\
1963
+ !*** ./src/webrtc-client.js ***!
1964
+ \******************************/
1965
+ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
1966
+
1967
+ __webpack_require__.r(__webpack_exports__);
1968
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
1969
+ /* harmony export */ getRTCService: () => (/* binding */ getRTCService),
1970
+ /* harmony export */ registerRTCService: () => (/* binding */ registerRTCService)
1971
+ /* harmony export */ });
1972
+ /* harmony import */ var _rpc_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./rpc.js */ "./src/rpc.js");
1973
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./src/utils.js");
1974
+
1975
+
1976
+
1977
+ class WebRTCConnection {
1978
+ constructor(channel) {
1979
+ this._data_channel = channel;
1980
+ this._handle_message = null;
1981
+ this._reconnection_token = null;
1982
+ this._data_channel.onmessage = async (event) => {
1983
+ let data = event.data;
1984
+ if (data instanceof Blob) {
1985
+ data = await data.arrayBuffer();
1986
+ }
1987
+ this._handle_message(data);
1988
+ };
1989
+ const self = this;
1990
+ this._data_channel.onclose = function () {
1991
+ console.log("websocket closed");
1992
+ self._data_channel = null;
1993
+ };
1994
+ }
1995
+
1996
+ set_reconnection_token(token) {
1997
+ this._reconnection_token = token;
1998
+ }
1999
+
2000
+ on_message(handler) {
2001
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(handler, "handler is required");
2002
+ this._handle_message = handler;
2003
+ }
2004
+
2005
+ async emit_message(data) {
2006
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(this._handle_message, "No handler for message");
2007
+ try {
2008
+ this._data_channel.send(data);
2009
+ } catch (exp) {
2010
+ // data = msgpack_unpackb(data);
2011
+ console.error(`Failed to send data, error: ${exp}`);
2012
+ throw exp;
2013
+ }
2014
+ }
2015
+
2016
+ async disconnect(reason) {
2017
+ this._data_channel = null;
2018
+ console.info(`data channel connection disconnected (${reason})`);
2019
+ }
2020
+ }
2021
+
2022
+ async function _setupRPC(config) {
2023
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(config.channel, "No channel provided");
2024
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(config.workspace, "No workspace provided");
2025
+ const channel = config.channel;
2026
+ const clientId = config.client_id || (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
2027
+ const connection = new WebRTCConnection(channel);
2028
+ config.context = config.context || {};
2029
+ config.context.connection_type = "webrtc";
2030
+ const rpc = new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(connection, {
2031
+ client_id: clientId,
2032
+ manager_id: null,
2033
+ default_context: config.context,
2034
+ name: config.name,
2035
+ method_timeout: config.method_timeout || 10.0,
2036
+ workspace: config.workspace,
2037
+ });
2038
+ return rpc;
2039
+ }
2040
+
2041
+ async function _createOffer(params, server, config, onInit, context) {
2042
+ config = config || {};
2043
+ let offer = new RTCSessionDescription({
2044
+ sdp: params.sdp,
2045
+ type: params.type,
2046
+ });
2047
+
2048
+ let pc = new RTCPeerConnection({
2049
+ iceServers: config.ice_servers || [
2050
+ { urls: ["stun:stun.l.google.com:19302"] },
2051
+ ],
2052
+ sdpSemantics: "unified-plan",
2053
+ });
2054
+
2055
+ if (server) {
2056
+ pc.addEventListener("datachannel", async (event) => {
2057
+ const channel = event.channel;
2058
+ let ctx = null;
2059
+ if (context && context.user) ctx = { user: context.user };
2060
+ const rpc = await _setupRPC({
2061
+ channel: channel,
2062
+ client_id: channel.label,
2063
+ workspace: server.config.workspace,
2064
+ context: ctx,
2065
+ });
2066
+ // Map all the local services to the webrtc client
2067
+ rpc._services = server.rpc._services;
2068
+ });
2069
+ }
2070
+
2071
+ if (onInit) {
2072
+ await onInit(pc);
2073
+ }
2074
+
2075
+ await pc.setRemoteDescription(offer);
2076
+
2077
+ let answer = await pc.createAnswer();
2078
+ await pc.setLocalDescription(answer);
2079
+
2080
+ return {
2081
+ sdp: pc.localDescription.sdp,
2082
+ type: pc.localDescription.type,
2083
+ workspace: server.config.workspace,
2084
+ };
2085
+ }
2086
+
2087
+ async function getRTCService(server, service_id, config) {
2088
+ config = config || {};
2089
+ config.peer_id = config.peer_id || (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
2090
+
2091
+ const pc = new RTCPeerConnection({
2092
+ iceServers: config.ice_servers || [
2093
+ { urls: ["stun:stun.l.google.com:19302"] },
2094
+ ],
2095
+ sdpSemantics: "unified-plan",
2096
+ });
2097
+
2098
+ return new Promise(async (resolve, reject) => {
2099
+ try {
2100
+ pc.addEventListener(
2101
+ "connectionstatechange",
2102
+ () => {
2103
+ if (pc.connectionState === "failed") {
2104
+ pc.close();
2105
+ reject(new Error("Connection failed"));
2106
+ }
2107
+ },
2108
+ false,
2109
+ );
2110
+
2111
+ if (config.on_init) {
2112
+ await config.on_init(pc);
2113
+ delete config.on_init;
2114
+ }
2115
+ let channel = pc.createDataChannel(config.peer_id, { ordered: true });
2116
+ channel.binaryType = "arraybuffer";
2117
+ const offer = await pc.createOffer();
2118
+ await pc.setLocalDescription(offer);
2119
+ const svc = await server.getService(service_id);
2120
+ const answer = await svc.offer({
2121
+ sdp: pc.localDescription.sdp,
2122
+ type: pc.localDescription.type,
2123
+ });
2124
+
2125
+ channel.onopen = () => {
2126
+ config.channel = channel;
2127
+ config.workspace = answer.workspace;
2128
+ // Wait for the channel to be open before returning the rpc
2129
+ // This is needed for safari to work
2130
+ setTimeout(async () => {
2131
+ const rpc = await _setupRPC(config);
2132
+ pc.rpc = rpc;
2133
+ async function getService(name) {
2134
+ return await rpc.get_remote_service(config.peer_id + ":" + name);
2135
+ }
2136
+ async function disconnect() {
2137
+ await rpc.disconnect();
2138
+ pc.close();
2139
+ }
2140
+ pc.get_service = getService;
2141
+ pc.getService = getService;
2142
+ pc.disconnect = disconnect;
2143
+ pc.register_codec = rpc.register_codec;
2144
+ pc.registerCodec = rpc.register_codec;
2145
+ resolve(pc);
2146
+ }, 500);
2147
+ };
2148
+
2149
+ channel.onclose = () => reject(new Error("Data channel closed"));
2150
+
2151
+ await pc.setRemoteDescription(
2152
+ new RTCSessionDescription({
2153
+ sdp: answer.sdp,
2154
+ type: answer.type,
2155
+ }),
2156
+ );
2157
+ } catch (e) {
2158
+ reject(e);
2159
+ }
2160
+ });
2161
+ }
2162
+
2163
+ async function registerRTCService(server, service_id, config) {
2164
+ config = config || {
2165
+ visibility: "protected",
2166
+ require_context: true,
2167
+ };
2168
+ const onInit = config.on_init;
2169
+ delete config.on_init;
2170
+ await server.registerService({
2171
+ id: service_id,
2172
+ config,
2173
+ offer: (params, context) =>
2174
+ _createOffer(params, server, config, onInit, context),
2175
+ });
2176
+ }
2177
+
2178
+
2179
+
2180
+
2181
+ /***/ }),
2182
+
2183
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs":
2184
+ /*!*************************************************************************!*\
2185
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs ***!
2186
+ \*************************************************************************/
2187
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2188
+
2189
+ __webpack_require__.r(__webpack_exports__);
2190
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2191
+ /* harmony export */ CachedKeyDecoder: () => (/* binding */ CachedKeyDecoder)
2192
+ /* harmony export */ });
2193
+ /* 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");
2194
+
2195
+ var DEFAULT_MAX_KEY_LENGTH = 16;
2196
+ var DEFAULT_MAX_LENGTH_PER_KEY = 16;
2197
+ var CachedKeyDecoder = /** @class */ (function () {
2198
+ function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
2199
+ if (maxKeyLength === void 0) { maxKeyLength = DEFAULT_MAX_KEY_LENGTH; }
2200
+ if (maxLengthPerKey === void 0) { maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY; }
2201
+ this.maxKeyLength = maxKeyLength;
2202
+ this.maxLengthPerKey = maxLengthPerKey;
2203
+ this.hit = 0;
2204
+ this.miss = 0;
2205
+ // avoid `new Array(N)`, which makes a sparse array,
2206
+ // because a sparse array is typically slower than a non-sparse array.
2207
+ this.caches = [];
2208
+ for (var i = 0; i < this.maxKeyLength; i++) {
2209
+ this.caches.push([]);
2210
+ }
2211
+ }
2212
+ CachedKeyDecoder.prototype.canBeCached = function (byteLength) {
2213
+ return byteLength > 0 && byteLength <= this.maxKeyLength;
2214
+ };
2215
+ CachedKeyDecoder.prototype.find = function (bytes, inputOffset, byteLength) {
2216
+ var records = this.caches[byteLength - 1];
2217
+ FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
2218
+ var record = records_1[_i];
2219
+ var recordBytes = record.bytes;
2220
+ for (var j = 0; j < byteLength; j++) {
2221
+ if (recordBytes[j] !== bytes[inputOffset + j]) {
2222
+ continue FIND_CHUNK;
2223
+ }
2224
+ }
2225
+ return record.str;
2226
+ }
2227
+ return null;
2228
+ };
2229
+ CachedKeyDecoder.prototype.store = function (bytes, value) {
2230
+ var records = this.caches[bytes.length - 1];
2231
+ var record = { bytes: bytes, str: value };
2232
+ if (records.length >= this.maxLengthPerKey) {
2233
+ // `records` are full!
2234
+ // Set `record` to an arbitrary position.
2235
+ records[(Math.random() * records.length) | 0] = record;
2236
+ }
2237
+ else {
2238
+ records.push(record);
2239
+ }
2240
+ };
2241
+ CachedKeyDecoder.prototype.decode = function (bytes, inputOffset, byteLength) {
2242
+ var cachedValue = this.find(bytes, inputOffset, byteLength);
2243
+ if (cachedValue != null) {
2244
+ this.hit++;
2245
+ return cachedValue;
2246
+ }
2247
+ this.miss++;
2248
+ var str = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_0__.utf8DecodeJs)(bytes, inputOffset, byteLength);
2249
+ // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer.
2250
+ var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
2251
+ this.store(slicedCopyOfBytes, str);
2252
+ return str;
2253
+ };
2254
+ return CachedKeyDecoder;
2255
+ }());
2256
+
2257
+ //# sourceMappingURL=CachedKeyDecoder.mjs.map
2258
+
2259
+ /***/ }),
2260
+
2261
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs":
2262
+ /*!********************************************************************!*\
2263
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs ***!
2264
+ \********************************************************************/
2265
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2266
+
2267
+ __webpack_require__.r(__webpack_exports__);
2268
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2269
+ /* harmony export */ DecodeError: () => (/* binding */ DecodeError)
2270
+ /* harmony export */ });
2271
+ var __extends = (undefined && undefined.__extends) || (function () {
2272
+ var extendStatics = function (d, b) {
2273
+ extendStatics = Object.setPrototypeOf ||
2274
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
2275
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
2276
+ return extendStatics(d, b);
2277
+ };
2278
+ return function (d, b) {
2279
+ if (typeof b !== "function" && b !== null)
2280
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
2281
+ extendStatics(d, b);
2282
+ function __() { this.constructor = d; }
2283
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2284
+ };
2285
+ })();
2286
+ var DecodeError = /** @class */ (function (_super) {
2287
+ __extends(DecodeError, _super);
2288
+ function DecodeError(message) {
2289
+ var _this = _super.call(this, message) || this;
2290
+ // fix the prototype chain in a cross-platform way
2291
+ var proto = Object.create(DecodeError.prototype);
2292
+ Object.setPrototypeOf(_this, proto);
2293
+ Object.defineProperty(_this, "name", {
2294
+ configurable: true,
2295
+ enumerable: false,
2296
+ value: DecodeError.name,
2297
+ });
2298
+ return _this;
2299
+ }
2300
+ return DecodeError;
2301
+ }(Error));
2302
+
2303
+ //# sourceMappingURL=DecodeError.mjs.map
2304
+
2305
+ /***/ }),
2306
+
2307
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs":
2308
+ /*!****************************************************************!*\
2309
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs ***!
2310
+ \****************************************************************/
2311
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2312
+
2313
+ __webpack_require__.r(__webpack_exports__);
2314
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2315
+ /* harmony export */ DataViewIndexOutOfBoundsError: () => (/* binding */ DataViewIndexOutOfBoundsError),
2316
+ /* harmony export */ Decoder: () => (/* binding */ Decoder)
2317
+ /* harmony export */ });
2318
+ /* 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");
2319
+ /* harmony import */ var _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtensionCodec.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs");
2320
+ /* 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");
2321
+ /* 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");
2322
+ /* 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");
2323
+ /* harmony import */ var _CachedKeyDecoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./CachedKeyDecoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs");
2324
+ /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
2325
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2326
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2327
+ return new (P || (P = Promise))(function (resolve, reject) {
2328
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2329
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2330
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2331
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2332
+ });
2333
+ };
2334
+ var __generator = (undefined && undefined.__generator) || function (thisArg, body) {
2335
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
2336
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2337
+ function verb(n) { return function (v) { return step([n, v]); }; }
2338
+ function step(op) {
2339
+ if (f) throw new TypeError("Generator is already executing.");
2340
+ while (_) try {
2341
+ 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;
2342
+ if (y = 0, t) op = [op[0] & 2, t.value];
2343
+ switch (op[0]) {
2344
+ case 0: case 1: t = op; break;
2345
+ case 4: _.label++; return { value: op[1], done: false };
2346
+ case 5: _.label++; y = op[1]; op = [0]; continue;
2347
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
2348
+ default:
2349
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2350
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2351
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2352
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2353
+ if (t[2]) _.ops.pop();
2354
+ _.trys.pop(); continue;
2355
+ }
2356
+ op = body.call(thisArg, _);
2357
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2358
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2359
+ }
2360
+ };
2361
+ var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
2362
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2363
+ var m = o[Symbol.asyncIterator], i;
2364
+ 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);
2365
+ 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); }); }; }
2366
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
2367
+ };
2368
+ var __await = (undefined && undefined.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
2369
+ var __asyncGenerator = (undefined && undefined.__asyncGenerator) || function (thisArg, _arguments, generator) {
2370
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2371
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
2372
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
2373
+ 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); }); }; }
2374
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
2375
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
2376
+ function fulfill(value) { resume("next", value); }
2377
+ function reject(value) { resume("throw", value); }
2378
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
2379
+ };
2380
+
2381
+
2382
+
2383
+
2384
+
2385
+
2386
+
2387
+ var isValidMapKeyType = function (key) {
2388
+ var keyType = typeof key;
2389
+ return keyType === "string" || keyType === "number";
2390
+ };
2391
+ var HEAD_BYTE_REQUIRED = -1;
2392
+ var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
2393
+ var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
2394
+ // IE11: Hack to support IE11.
2395
+ // IE11: Drop this hack and just use RangeError when IE11 is obsolete.
2396
+ var DataViewIndexOutOfBoundsError = (function () {
2397
+ try {
2398
+ // IE11: The spec says it should throw RangeError,
2399
+ // IE11: but in IE11 it throws TypeError.
2400
+ EMPTY_VIEW.getInt8(0);
2401
+ }
2402
+ catch (e) {
2403
+ return e.constructor;
2404
+ }
2405
+ throw new Error("never reached");
2406
+ })();
2407
+ var MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data");
2408
+ var sharedCachedKeyDecoder = new _CachedKeyDecoder_mjs__WEBPACK_IMPORTED_MODULE_0__.CachedKeyDecoder();
2409
+ var Decoder = /** @class */ (function () {
2410
+ function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {
2411
+ if (extensionCodec === void 0) { extensionCodec = _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtensionCodec.defaultCodec; }
2412
+ if (context === void 0) { context = undefined; }
2413
+ if (maxStrLength === void 0) { maxStrLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2414
+ if (maxBinLength === void 0) { maxBinLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2415
+ if (maxArrayLength === void 0) { maxArrayLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2416
+ if (maxMapLength === void 0) { maxMapLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2417
+ if (maxExtLength === void 0) { maxExtLength = _utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.UINT32_MAX; }
2418
+ if (keyDecoder === void 0) { keyDecoder = sharedCachedKeyDecoder; }
2419
+ this.extensionCodec = extensionCodec;
2420
+ this.context = context;
2421
+ this.maxStrLength = maxStrLength;
2422
+ this.maxBinLength = maxBinLength;
2423
+ this.maxArrayLength = maxArrayLength;
2424
+ this.maxMapLength = maxMapLength;
2425
+ this.maxExtLength = maxExtLength;
2426
+ this.keyDecoder = keyDecoder;
2427
+ this.totalPos = 0;
2428
+ this.pos = 0;
2429
+ this.view = EMPTY_VIEW;
2430
+ this.bytes = EMPTY_BYTES;
2431
+ this.headByte = HEAD_BYTE_REQUIRED;
2432
+ this.stack = [];
2433
+ }
2434
+ Decoder.prototype.reinitializeState = function () {
2435
+ this.totalPos = 0;
2436
+ this.headByte = HEAD_BYTE_REQUIRED;
2437
+ this.stack.length = 0;
2438
+ // view, bytes, and pos will be re-initialized in setBuffer()
2439
+ };
2440
+ Decoder.prototype.setBuffer = function (buffer) {
2441
+ this.bytes = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__.ensureUint8Array)(buffer);
2442
+ this.view = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__.createDataView)(this.bytes);
2443
+ this.pos = 0;
2444
+ };
2445
+ Decoder.prototype.appendBuffer = function (buffer) {
2446
+ if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
2447
+ this.setBuffer(buffer);
2448
+ }
2449
+ else {
2450
+ var remainingData = this.bytes.subarray(this.pos);
2451
+ var newData = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_3__.ensureUint8Array)(buffer);
2452
+ // concat remainingData + newData
2453
+ var newBuffer = new Uint8Array(remainingData.length + newData.length);
2454
+ newBuffer.set(remainingData);
2455
+ newBuffer.set(newData, remainingData.length);
2456
+ this.setBuffer(newBuffer);
2457
+ }
2458
+ };
2459
+ Decoder.prototype.hasRemaining = function (size) {
2460
+ return this.view.byteLength - this.pos >= size;
2461
+ };
2462
+ Decoder.prototype.createExtraByteError = function (posToShow) {
2463
+ var _a = this, view = _a.view, pos = _a.pos;
2464
+ return new RangeError("Extra ".concat(view.byteLength - pos, " of ").concat(view.byteLength, " byte(s) found at buffer[").concat(posToShow, "]"));
2465
+ };
2466
+ /**
2467
+ * @throws {@link DecodeError}
2468
+ * @throws {@link RangeError}
2469
+ */
2470
+ Decoder.prototype.decode = function (buffer) {
2471
+ this.reinitializeState();
2472
+ this.setBuffer(buffer);
2473
+ var object = this.doDecodeSync();
2474
+ if (this.hasRemaining(1)) {
2475
+ throw this.createExtraByteError(this.pos);
2476
+ }
2477
+ return object;
2478
+ };
2479
+ Decoder.prototype.decodeMulti = function (buffer) {
2480
+ return __generator(this, function (_a) {
2481
+ switch (_a.label) {
2482
+ case 0:
2483
+ this.reinitializeState();
2484
+ this.setBuffer(buffer);
2485
+ _a.label = 1;
2486
+ case 1:
2487
+ if (!this.hasRemaining(1)) return [3 /*break*/, 3];
2488
+ return [4 /*yield*/, this.doDecodeSync()];
2489
+ case 2:
2490
+ _a.sent();
2491
+ return [3 /*break*/, 1];
2492
+ case 3: return [2 /*return*/];
2493
+ }
2494
+ });
2495
+ };
2496
+ Decoder.prototype.decodeAsync = function (stream) {
2497
+ var stream_1, stream_1_1;
2498
+ var e_1, _a;
2499
+ return __awaiter(this, void 0, void 0, function () {
2500
+ var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;
2501
+ return __generator(this, function (_c) {
2502
+ switch (_c.label) {
2503
+ case 0:
2504
+ decoded = false;
2505
+ _c.label = 1;
2506
+ case 1:
2507
+ _c.trys.push([1, 6, 7, 12]);
2508
+ stream_1 = __asyncValues(stream);
2509
+ _c.label = 2;
2510
+ case 2: return [4 /*yield*/, stream_1.next()];
2511
+ case 3:
2512
+ if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3 /*break*/, 5];
2513
+ buffer = stream_1_1.value;
2514
+ if (decoded) {
2515
+ throw this.createExtraByteError(this.totalPos);
2516
+ }
2517
+ this.appendBuffer(buffer);
2518
+ try {
2519
+ object = this.doDecodeSync();
2520
+ decoded = true;
2521
+ }
2522
+ catch (e) {
2523
+ if (!(e instanceof DataViewIndexOutOfBoundsError)) {
2524
+ throw e; // rethrow
2525
+ }
2526
+ // fallthrough
2527
+ }
2528
+ this.totalPos += this.pos;
2529
+ _c.label = 4;
2530
+ case 4: return [3 /*break*/, 2];
2531
+ case 5: return [3 /*break*/, 12];
2532
+ case 6:
2533
+ e_1_1 = _c.sent();
2534
+ e_1 = { error: e_1_1 };
2535
+ return [3 /*break*/, 12];
2536
+ case 7:
2537
+ _c.trys.push([7, , 10, 11]);
2538
+ if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3 /*break*/, 9];
2539
+ return [4 /*yield*/, _a.call(stream_1)];
2540
+ case 8:
2541
+ _c.sent();
2542
+ _c.label = 9;
2543
+ case 9: return [3 /*break*/, 11];
2544
+ case 10:
2545
+ if (e_1) throw e_1.error;
2546
+ return [7 /*endfinally*/];
2547
+ case 11: return [7 /*endfinally*/];
2548
+ case 12:
2549
+ if (decoded) {
2550
+ if (this.hasRemaining(1)) {
2551
+ throw this.createExtraByteError(this.totalPos);
2552
+ }
2553
+ return [2 /*return*/, object];
2554
+ }
2555
+ _b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;
2556
+ throw new RangeError("Insufficient data in parsing ".concat((0,_utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__.prettyByte)(headByte), " at ").concat(totalPos, " (").concat(pos, " in the current buffer)"));
2557
+ }
2558
+ });
2559
+ });
2560
+ };
2561
+ Decoder.prototype.decodeArrayStream = function (stream) {
2562
+ return this.decodeMultiAsync(stream, true);
2563
+ };
2564
+ Decoder.prototype.decodeStream = function (stream) {
2565
+ return this.decodeMultiAsync(stream, false);
2566
+ };
2567
+ Decoder.prototype.decodeMultiAsync = function (stream, isArray) {
2568
+ return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {
2569
+ var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;
2570
+ var e_3, _a;
2571
+ return __generator(this, function (_b) {
2572
+ switch (_b.label) {
2573
+ case 0:
2574
+ isArrayHeaderRequired = isArray;
2575
+ arrayItemsLeft = -1;
2576
+ _b.label = 1;
2577
+ case 1:
2578
+ _b.trys.push([1, 13, 14, 19]);
2579
+ stream_2 = __asyncValues(stream);
2580
+ _b.label = 2;
2581
+ case 2: return [4 /*yield*/, __await(stream_2.next())];
2582
+ case 3:
2583
+ if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3 /*break*/, 12];
2584
+ buffer = stream_2_1.value;
2585
+ if (isArray && arrayItemsLeft === 0) {
2586
+ throw this.createExtraByteError(this.totalPos);
2587
+ }
2588
+ this.appendBuffer(buffer);
2589
+ if (isArrayHeaderRequired) {
2590
+ arrayItemsLeft = this.readArraySize();
2591
+ isArrayHeaderRequired = false;
2592
+ this.complete();
2593
+ }
2594
+ _b.label = 4;
2595
+ case 4:
2596
+ _b.trys.push([4, 9, , 10]);
2597
+ _b.label = 5;
2598
+ case 5:
2599
+ if (false) {}
2600
+ return [4 /*yield*/, __await(this.doDecodeSync())];
2601
+ case 6: return [4 /*yield*/, _b.sent()];
2602
+ case 7:
2603
+ _b.sent();
2604
+ if (--arrayItemsLeft === 0) {
2605
+ return [3 /*break*/, 8];
2606
+ }
2607
+ return [3 /*break*/, 5];
2608
+ case 8: return [3 /*break*/, 10];
2609
+ case 9:
2610
+ e_2 = _b.sent();
2611
+ if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) {
2612
+ throw e_2; // rethrow
2613
+ }
2614
+ return [3 /*break*/, 10];
2615
+ case 10:
2616
+ this.totalPos += this.pos;
2617
+ _b.label = 11;
2618
+ case 11: return [3 /*break*/, 2];
2619
+ case 12: return [3 /*break*/, 19];
2620
+ case 13:
2621
+ e_3_1 = _b.sent();
2622
+ e_3 = { error: e_3_1 };
2623
+ return [3 /*break*/, 19];
2624
+ case 14:
2625
+ _b.trys.push([14, , 17, 18]);
2626
+ if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3 /*break*/, 16];
2627
+ return [4 /*yield*/, __await(_a.call(stream_2))];
2628
+ case 15:
2629
+ _b.sent();
2630
+ _b.label = 16;
2631
+ case 16: return [3 /*break*/, 18];
2632
+ case 17:
2633
+ if (e_3) throw e_3.error;
2634
+ return [7 /*endfinally*/];
2635
+ case 18: return [7 /*endfinally*/];
2636
+ case 19: return [2 /*return*/];
2637
+ }
2638
+ });
2639
+ });
2640
+ };
2641
+ Decoder.prototype.doDecodeSync = function () {
2642
+ DECODE: while (true) {
2643
+ var headByte = this.readHeadByte();
2644
+ var object = void 0;
2645
+ if (headByte >= 0xe0) {
2646
+ // negative fixint (111x xxxx) 0xe0 - 0xff
2647
+ object = headByte - 0x100;
2648
+ }
2649
+ else if (headByte < 0xc0) {
2650
+ if (headByte < 0x80) {
2651
+ // positive fixint (0xxx xxxx) 0x00 - 0x7f
2652
+ object = headByte;
2653
+ }
2654
+ else if (headByte < 0x90) {
2655
+ // fixmap (1000 xxxx) 0x80 - 0x8f
2656
+ var size = headByte - 0x80;
2657
+ if (size !== 0) {
2658
+ this.pushMapState(size);
2659
+ this.complete();
2660
+ continue DECODE;
2661
+ }
2662
+ else {
2663
+ object = {};
2664
+ }
2665
+ }
2666
+ else if (headByte < 0xa0) {
2667
+ // fixarray (1001 xxxx) 0x90 - 0x9f
2668
+ var size = headByte - 0x90;
2669
+ if (size !== 0) {
2670
+ this.pushArrayState(size);
2671
+ this.complete();
2672
+ continue DECODE;
2673
+ }
2674
+ else {
2675
+ object = [];
2676
+ }
2677
+ }
2678
+ else {
2679
+ // fixstr (101x xxxx) 0xa0 - 0xbf
2680
+ var byteLength = headByte - 0xa0;
2681
+ object = this.decodeUtf8String(byteLength, 0);
2682
+ }
2683
+ }
2684
+ else if (headByte === 0xc0) {
2685
+ // nil
2686
+ object = null;
2687
+ }
2688
+ else if (headByte === 0xc2) {
2689
+ // false
2690
+ object = false;
2691
+ }
2692
+ else if (headByte === 0xc3) {
2693
+ // true
2694
+ object = true;
2695
+ }
2696
+ else if (headByte === 0xca) {
2697
+ // float 32
2698
+ object = this.readF32();
2699
+ }
2700
+ else if (headByte === 0xcb) {
2701
+ // float 64
2702
+ object = this.readF64();
2703
+ }
2704
+ else if (headByte === 0xcc) {
2705
+ // uint 8
2706
+ object = this.readU8();
2707
+ }
2708
+ else if (headByte === 0xcd) {
2709
+ // uint 16
2710
+ object = this.readU16();
2711
+ }
2712
+ else if (headByte === 0xce) {
2713
+ // uint 32
2714
+ object = this.readU32();
2715
+ }
2716
+ else if (headByte === 0xcf) {
2717
+ // uint 64
2718
+ object = this.readU64();
2719
+ }
2720
+ else if (headByte === 0xd0) {
2721
+ // int 8
2722
+ object = this.readI8();
2723
+ }
2724
+ else if (headByte === 0xd1) {
2725
+ // int 16
2726
+ object = this.readI16();
2727
+ }
2728
+ else if (headByte === 0xd2) {
2729
+ // int 32
2730
+ object = this.readI32();
2731
+ }
2732
+ else if (headByte === 0xd3) {
2733
+ // int 64
2734
+ object = this.readI64();
2735
+ }
2736
+ else if (headByte === 0xd9) {
2737
+ // str 8
2738
+ var byteLength = this.lookU8();
2739
+ object = this.decodeUtf8String(byteLength, 1);
2740
+ }
2741
+ else if (headByte === 0xda) {
2742
+ // str 16
2743
+ var byteLength = this.lookU16();
2744
+ object = this.decodeUtf8String(byteLength, 2);
2745
+ }
2746
+ else if (headByte === 0xdb) {
2747
+ // str 32
2748
+ var byteLength = this.lookU32();
2749
+ object = this.decodeUtf8String(byteLength, 4);
2750
+ }
2751
+ else if (headByte === 0xdc) {
2752
+ // array 16
2753
+ var size = this.readU16();
2754
+ if (size !== 0) {
2755
+ this.pushArrayState(size);
2756
+ this.complete();
2757
+ continue DECODE;
2758
+ }
2759
+ else {
2760
+ object = [];
2761
+ }
2762
+ }
2763
+ else if (headByte === 0xdd) {
2764
+ // array 32
2765
+ var size = this.readU32();
2766
+ if (size !== 0) {
2767
+ this.pushArrayState(size);
2768
+ this.complete();
2769
+ continue DECODE;
2770
+ }
2771
+ else {
2772
+ object = [];
2773
+ }
2774
+ }
2775
+ else if (headByte === 0xde) {
2776
+ // map 16
2777
+ var size = this.readU16();
2778
+ if (size !== 0) {
2779
+ this.pushMapState(size);
2780
+ this.complete();
2781
+ continue DECODE;
2782
+ }
2783
+ else {
2784
+ object = {};
2785
+ }
2786
+ }
2787
+ else if (headByte === 0xdf) {
2788
+ // map 32
2789
+ var size = this.readU32();
2790
+ if (size !== 0) {
2791
+ this.pushMapState(size);
2792
+ this.complete();
2793
+ continue DECODE;
2794
+ }
2795
+ else {
2796
+ object = {};
2797
+ }
2798
+ }
2799
+ else if (headByte === 0xc4) {
2800
+ // bin 8
2801
+ var size = this.lookU8();
2802
+ object = this.decodeBinary(size, 1);
2803
+ }
2804
+ else if (headByte === 0xc5) {
2805
+ // bin 16
2806
+ var size = this.lookU16();
2807
+ object = this.decodeBinary(size, 2);
2808
+ }
2809
+ else if (headByte === 0xc6) {
2810
+ // bin 32
2811
+ var size = this.lookU32();
2812
+ object = this.decodeBinary(size, 4);
2813
+ }
2814
+ else if (headByte === 0xd4) {
2815
+ // fixext 1
2816
+ object = this.decodeExtension(1, 0);
2817
+ }
2818
+ else if (headByte === 0xd5) {
2819
+ // fixext 2
2820
+ object = this.decodeExtension(2, 0);
2821
+ }
2822
+ else if (headByte === 0xd6) {
2823
+ // fixext 4
2824
+ object = this.decodeExtension(4, 0);
2825
+ }
2826
+ else if (headByte === 0xd7) {
2827
+ // fixext 8
2828
+ object = this.decodeExtension(8, 0);
2829
+ }
2830
+ else if (headByte === 0xd8) {
2831
+ // fixext 16
2832
+ object = this.decodeExtension(16, 0);
2833
+ }
2834
+ else if (headByte === 0xc7) {
2835
+ // ext 8
2836
+ var size = this.lookU8();
2837
+ object = this.decodeExtension(size, 1);
2838
+ }
2839
+ else if (headByte === 0xc8) {
2840
+ // ext 16
2841
+ var size = this.lookU16();
2842
+ object = this.decodeExtension(size, 2);
2843
+ }
2844
+ else if (headByte === 0xc9) {
2845
+ // ext 32
2846
+ var size = this.lookU32();
2847
+ object = this.decodeExtension(size, 4);
2848
+ }
2849
+ else {
2850
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Unrecognized type byte: ".concat((0,_utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__.prettyByte)(headByte)));
2851
+ }
2852
+ this.complete();
2853
+ var stack = this.stack;
2854
+ while (stack.length > 0) {
2855
+ // arrays and maps
2856
+ var state = stack[stack.length - 1];
2857
+ if (state.type === 0 /* State.ARRAY */) {
2858
+ state.array[state.position] = object;
2859
+ state.position++;
2860
+ if (state.position === state.size) {
2861
+ stack.pop();
2862
+ object = state.array;
2863
+ }
2864
+ else {
2865
+ continue DECODE;
2866
+ }
2867
+ }
2868
+ else if (state.type === 1 /* State.MAP_KEY */) {
2869
+ if (!isValidMapKeyType(object)) {
2870
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("The type of key must be string or number but " + typeof object);
2871
+ }
2872
+ if (object === "__proto__") {
2873
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("The key __proto__ is not allowed");
2874
+ }
2875
+ state.key = object;
2876
+ state.type = 2 /* State.MAP_VALUE */;
2877
+ continue DECODE;
2878
+ }
2879
+ else {
2880
+ // it must be `state.type === State.MAP_VALUE` here
2881
+ state.map[state.key] = object;
2882
+ state.readCount++;
2883
+ if (state.readCount === state.size) {
2884
+ stack.pop();
2885
+ object = state.map;
2886
+ }
2887
+ else {
2888
+ state.key = null;
2889
+ state.type = 1 /* State.MAP_KEY */;
2890
+ continue DECODE;
2891
+ }
2892
+ }
2893
+ }
2894
+ return object;
2895
+ }
2896
+ };
2897
+ Decoder.prototype.readHeadByte = function () {
2898
+ if (this.headByte === HEAD_BYTE_REQUIRED) {
2899
+ this.headByte = this.readU8();
2900
+ // console.log("headByte", prettyByte(this.headByte));
2901
+ }
2902
+ return this.headByte;
2903
+ };
2904
+ Decoder.prototype.complete = function () {
2905
+ this.headByte = HEAD_BYTE_REQUIRED;
2906
+ };
2907
+ Decoder.prototype.readArraySize = function () {
2908
+ var headByte = this.readHeadByte();
2909
+ switch (headByte) {
2910
+ case 0xdc:
2911
+ return this.readU16();
2912
+ case 0xdd:
2913
+ return this.readU32();
2914
+ default: {
2915
+ if (headByte < 0xa0) {
2916
+ return headByte - 0x90;
2917
+ }
2918
+ else {
2919
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Unrecognized array type byte: ".concat((0,_utils_prettyByte_mjs__WEBPACK_IMPORTED_MODULE_4__.prettyByte)(headByte)));
2920
+ }
2921
+ }
2922
+ }
2923
+ };
2924
+ Decoder.prototype.pushMapState = function (size) {
2925
+ if (size > this.maxMapLength) {
2926
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: map length (".concat(size, ") > maxMapLengthLength (").concat(this.maxMapLength, ")"));
2927
+ }
2928
+ this.stack.push({
2929
+ type: 1 /* State.MAP_KEY */,
2930
+ size: size,
2931
+ key: null,
2932
+ readCount: 0,
2933
+ map: {},
2934
+ });
2935
+ };
2936
+ Decoder.prototype.pushArrayState = function (size) {
2937
+ if (size > this.maxArrayLength) {
2938
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: array length (".concat(size, ") > maxArrayLength (").concat(this.maxArrayLength, ")"));
2939
+ }
2940
+ this.stack.push({
2941
+ type: 0 /* State.ARRAY */,
2942
+ size: size,
2943
+ array: new Array(size),
2944
+ position: 0,
2945
+ });
2946
+ };
2947
+ Decoder.prototype.decodeUtf8String = function (byteLength, headerOffset) {
2948
+ var _a;
2949
+ if (byteLength > this.maxStrLength) {
2950
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: UTF-8 byte length (".concat(byteLength, ") > maxStrLength (").concat(this.maxStrLength, ")"));
2951
+ }
2952
+ if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
2953
+ throw MORE_DATA;
2954
+ }
2955
+ var offset = this.pos + headerOffset;
2956
+ var object;
2957
+ if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) {
2958
+ object = this.keyDecoder.decode(this.bytes, offset, byteLength);
2959
+ }
2960
+ else if (byteLength > _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__.TEXT_DECODER_THRESHOLD) {
2961
+ object = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__.utf8DecodeTD)(this.bytes, offset, byteLength);
2962
+ }
2963
+ else {
2964
+ object = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_6__.utf8DecodeJs)(this.bytes, offset, byteLength);
2965
+ }
2966
+ this.pos += headerOffset + byteLength;
2967
+ return object;
2968
+ };
2969
+ Decoder.prototype.stateIsMapKey = function () {
2970
+ if (this.stack.length > 0) {
2971
+ var state = this.stack[this.stack.length - 1];
2972
+ return state.type === 1 /* State.MAP_KEY */;
2973
+ }
2974
+ return false;
2975
+ };
2976
+ Decoder.prototype.decodeBinary = function (byteLength, headOffset) {
2977
+ if (byteLength > this.maxBinLength) {
2978
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: bin length (".concat(byteLength, ") > maxBinLength (").concat(this.maxBinLength, ")"));
2979
+ }
2980
+ if (!this.hasRemaining(byteLength + headOffset)) {
2981
+ throw MORE_DATA;
2982
+ }
2983
+ var offset = this.pos + headOffset;
2984
+ var object = this.bytes.subarray(offset, offset + byteLength);
2985
+ this.pos += headOffset + byteLength;
2986
+ return object;
2987
+ };
2988
+ Decoder.prototype.decodeExtension = function (size, headOffset) {
2989
+ if (size > this.maxExtLength) {
2990
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_5__.DecodeError("Max length exceeded: ext length (".concat(size, ") > maxExtLength (").concat(this.maxExtLength, ")"));
2991
+ }
2992
+ var extType = this.view.getInt8(this.pos + headOffset);
2993
+ var data = this.decodeBinary(size, headOffset + 1 /* extType */);
2994
+ return this.extensionCodec.decode(data, extType, this.context);
2995
+ };
2996
+ Decoder.prototype.lookU8 = function () {
2997
+ return this.view.getUint8(this.pos);
2998
+ };
2999
+ Decoder.prototype.lookU16 = function () {
3000
+ return this.view.getUint16(this.pos);
3001
+ };
3002
+ Decoder.prototype.lookU32 = function () {
3003
+ return this.view.getUint32(this.pos);
3004
+ };
3005
+ Decoder.prototype.readU8 = function () {
3006
+ var value = this.view.getUint8(this.pos);
3007
+ this.pos++;
3008
+ return value;
3009
+ };
3010
+ Decoder.prototype.readI8 = function () {
3011
+ var value = this.view.getInt8(this.pos);
3012
+ this.pos++;
3013
+ return value;
3014
+ };
3015
+ Decoder.prototype.readU16 = function () {
3016
+ var value = this.view.getUint16(this.pos);
3017
+ this.pos += 2;
3018
+ return value;
3019
+ };
3020
+ Decoder.prototype.readI16 = function () {
3021
+ var value = this.view.getInt16(this.pos);
3022
+ this.pos += 2;
3023
+ return value;
3024
+ };
3025
+ Decoder.prototype.readU32 = function () {
3026
+ var value = this.view.getUint32(this.pos);
3027
+ this.pos += 4;
3028
+ return value;
3029
+ };
3030
+ Decoder.prototype.readI32 = function () {
3031
+ var value = this.view.getInt32(this.pos);
3032
+ this.pos += 4;
3033
+ return value;
3034
+ };
3035
+ Decoder.prototype.readU64 = function () {
3036
+ var value = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.getUint64)(this.view, this.pos);
3037
+ this.pos += 8;
3038
+ return value;
3039
+ };
3040
+ Decoder.prototype.readI64 = function () {
3041
+ var value = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_2__.getInt64)(this.view, this.pos);
3042
+ this.pos += 8;
3043
+ return value;
3044
+ };
3045
+ Decoder.prototype.readF32 = function () {
3046
+ var value = this.view.getFloat32(this.pos);
3047
+ this.pos += 4;
3048
+ return value;
3049
+ };
3050
+ Decoder.prototype.readF64 = function () {
3051
+ var value = this.view.getFloat64(this.pos);
3052
+ this.pos += 8;
3053
+ return value;
3054
+ };
3055
+ return Decoder;
3056
+ }());
3057
+
3058
+ //# sourceMappingURL=Decoder.mjs.map
3059
+
3060
+ /***/ }),
3061
+
3062
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs":
3063
+ /*!****************************************************************!*\
3064
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs ***!
3065
+ \****************************************************************/
3066
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3067
+
3068
+ __webpack_require__.r(__webpack_exports__);
3069
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3070
+ /* harmony export */ DEFAULT_INITIAL_BUFFER_SIZE: () => (/* binding */ DEFAULT_INITIAL_BUFFER_SIZE),
3071
+ /* harmony export */ DEFAULT_MAX_DEPTH: () => (/* binding */ DEFAULT_MAX_DEPTH),
3072
+ /* harmony export */ Encoder: () => (/* binding */ Encoder)
3073
+ /* harmony export */ });
3074
+ /* harmony import */ var _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils/utf8.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs");
3075
+ /* harmony import */ var _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ExtensionCodec.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs");
3076
+ /* harmony import */ var _utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./utils/int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
3077
+ /* harmony import */ var _utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./utils/typedArrays.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs");
3078
+
3079
+
3080
+
3081
+
3082
+ var DEFAULT_MAX_DEPTH = 100;
3083
+ var DEFAULT_INITIAL_BUFFER_SIZE = 2048;
3084
+ var Encoder = /** @class */ (function () {
3085
+ function Encoder(extensionCodec, context, maxDepth, initialBufferSize, sortKeys, forceFloat32, ignoreUndefined, forceIntegerToFloat) {
3086
+ if (extensionCodec === void 0) { extensionCodec = _ExtensionCodec_mjs__WEBPACK_IMPORTED_MODULE_0__.ExtensionCodec.defaultCodec; }
3087
+ if (context === void 0) { context = undefined; }
3088
+ if (maxDepth === void 0) { maxDepth = DEFAULT_MAX_DEPTH; }
3089
+ if (initialBufferSize === void 0) { initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE; }
3090
+ if (sortKeys === void 0) { sortKeys = false; }
3091
+ if (forceFloat32 === void 0) { forceFloat32 = false; }
3092
+ if (ignoreUndefined === void 0) { ignoreUndefined = false; }
3093
+ if (forceIntegerToFloat === void 0) { forceIntegerToFloat = false; }
3094
+ this.extensionCodec = extensionCodec;
3095
+ this.context = context;
3096
+ this.maxDepth = maxDepth;
3097
+ this.initialBufferSize = initialBufferSize;
3098
+ this.sortKeys = sortKeys;
3099
+ this.forceFloat32 = forceFloat32;
3100
+ this.ignoreUndefined = ignoreUndefined;
3101
+ this.forceIntegerToFloat = forceIntegerToFloat;
3102
+ this.pos = 0;
3103
+ this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
3104
+ this.bytes = new Uint8Array(this.view.buffer);
3105
+ }
3106
+ Encoder.prototype.reinitializeState = function () {
3107
+ this.pos = 0;
3108
+ };
3109
+ /**
3110
+ * This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
3111
+ *
3112
+ * @returns Encodes the object and returns a shared reference the encoder's internal buffer.
3113
+ */
3114
+ Encoder.prototype.encodeSharedRef = function (object) {
3115
+ this.reinitializeState();
3116
+ this.doEncode(object, 1);
3117
+ return this.bytes.subarray(0, this.pos);
3118
+ };
3119
+ /**
3120
+ * @returns Encodes the object and returns a copy of the encoder's internal buffer.
3121
+ */
3122
+ Encoder.prototype.encode = function (object) {
3123
+ this.reinitializeState();
3124
+ this.doEncode(object, 1);
3125
+ return this.bytes.slice(0, this.pos);
3126
+ };
3127
+ Encoder.prototype.doEncode = function (object, depth) {
3128
+ if (depth > this.maxDepth) {
3129
+ throw new Error("Too deep objects in depth ".concat(depth));
3130
+ }
3131
+ if (object == null) {
3132
+ this.encodeNil();
3133
+ }
3134
+ else if (typeof object === "boolean") {
3135
+ this.encodeBoolean(object);
3136
+ }
3137
+ else if (typeof object === "number") {
3138
+ this.encodeNumber(object);
3139
+ }
3140
+ else if (typeof object === "string") {
3141
+ this.encodeString(object);
3142
+ }
3143
+ else {
3144
+ this.encodeObject(object, depth);
3145
+ }
3146
+ };
3147
+ Encoder.prototype.ensureBufferSizeToWrite = function (sizeToWrite) {
3148
+ var requiredSize = this.pos + sizeToWrite;
3149
+ if (this.view.byteLength < requiredSize) {
3150
+ this.resizeBuffer(requiredSize * 2);
3151
+ }
3152
+ };
3153
+ Encoder.prototype.resizeBuffer = function (newSize) {
3154
+ var newBuffer = new ArrayBuffer(newSize);
3155
+ var newBytes = new Uint8Array(newBuffer);
3156
+ var newView = new DataView(newBuffer);
3157
+ newBytes.set(this.bytes);
3158
+ this.view = newView;
3159
+ this.bytes = newBytes;
3160
+ };
3161
+ Encoder.prototype.encodeNil = function () {
3162
+ this.writeU8(0xc0);
3163
+ };
3164
+ Encoder.prototype.encodeBoolean = function (object) {
3165
+ if (object === false) {
3166
+ this.writeU8(0xc2);
3167
+ }
3168
+ else {
3169
+ this.writeU8(0xc3);
3170
+ }
3171
+ };
3172
+ Encoder.prototype.encodeNumber = function (object) {
3173
+ if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) {
3174
+ if (object >= 0) {
3175
+ if (object < 0x80) {
3176
+ // positive fixint
3177
+ this.writeU8(object);
3178
+ }
3179
+ else if (object < 0x100) {
3180
+ // uint 8
3181
+ this.writeU8(0xcc);
3182
+ this.writeU8(object);
3183
+ }
3184
+ else if (object < 0x10000) {
3185
+ // uint 16
3186
+ this.writeU8(0xcd);
3187
+ this.writeU16(object);
3188
+ }
3189
+ else if (object < 0x100000000) {
3190
+ // uint 32
3191
+ this.writeU8(0xce);
3192
+ this.writeU32(object);
3193
+ }
3194
+ else {
3195
+ // uint 64
3196
+ this.writeU8(0xcf);
3197
+ this.writeU64(object);
3198
+ }
3199
+ }
3200
+ else {
3201
+ if (object >= -0x20) {
3202
+ // negative fixint
3203
+ this.writeU8(0xe0 | (object + 0x20));
3204
+ }
3205
+ else if (object >= -0x80) {
3206
+ // int 8
3207
+ this.writeU8(0xd0);
3208
+ this.writeI8(object);
3209
+ }
3210
+ else if (object >= -0x8000) {
3211
+ // int 16
3212
+ this.writeU8(0xd1);
3213
+ this.writeI16(object);
3214
+ }
3215
+ else if (object >= -0x80000000) {
3216
+ // int 32
3217
+ this.writeU8(0xd2);
3218
+ this.writeI32(object);
3219
+ }
3220
+ else {
3221
+ // int 64
3222
+ this.writeU8(0xd3);
3223
+ this.writeI64(object);
3224
+ }
3225
+ }
3226
+ }
3227
+ else {
3228
+ // non-integer numbers
3229
+ if (this.forceFloat32) {
3230
+ // float 32
3231
+ this.writeU8(0xca);
3232
+ this.writeF32(object);
3233
+ }
3234
+ else {
3235
+ // float 64
3236
+ this.writeU8(0xcb);
3237
+ this.writeF64(object);
3238
+ }
3239
+ }
3240
+ };
3241
+ Encoder.prototype.writeStringHeader = function (byteLength) {
3242
+ if (byteLength < 32) {
3243
+ // fixstr
3244
+ this.writeU8(0xa0 + byteLength);
3245
+ }
3246
+ else if (byteLength < 0x100) {
3247
+ // str 8
3248
+ this.writeU8(0xd9);
3249
+ this.writeU8(byteLength);
3250
+ }
3251
+ else if (byteLength < 0x10000) {
3252
+ // str 16
3253
+ this.writeU8(0xda);
3254
+ this.writeU16(byteLength);
3255
+ }
3256
+ else if (byteLength < 0x100000000) {
3257
+ // str 32
3258
+ this.writeU8(0xdb);
3259
+ this.writeU32(byteLength);
3260
+ }
3261
+ else {
3262
+ throw new Error("Too long string: ".concat(byteLength, " bytes in UTF-8"));
3263
+ }
3264
+ };
3265
+ Encoder.prototype.encodeString = function (object) {
3266
+ var maxHeaderSize = 1 + 4;
3267
+ var strLength = object.length;
3268
+ if (strLength > _utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.TEXT_ENCODER_THRESHOLD) {
3269
+ var byteLength = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8Count)(object);
3270
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
3271
+ this.writeStringHeader(byteLength);
3272
+ (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8EncodeTE)(object, this.bytes, this.pos);
3273
+ this.pos += byteLength;
3274
+ }
3275
+ else {
3276
+ var byteLength = (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8Count)(object);
3277
+ this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
3278
+ this.writeStringHeader(byteLength);
3279
+ (0,_utils_utf8_mjs__WEBPACK_IMPORTED_MODULE_1__.utf8EncodeJs)(object, this.bytes, this.pos);
3280
+ this.pos += byteLength;
3281
+ }
3282
+ };
3283
+ Encoder.prototype.encodeObject = function (object, depth) {
3284
+ // try to encode objects with custom codec first of non-primitives
3285
+ var ext = this.extensionCodec.tryToEncode(object, this.context);
3286
+ if (ext != null) {
3287
+ this.encodeExtension(ext);
3288
+ }
3289
+ else if (Array.isArray(object)) {
3290
+ this.encodeArray(object, depth);
3291
+ }
3292
+ else if (ArrayBuffer.isView(object)) {
3293
+ this.encodeBinary(object);
3294
+ }
3295
+ else if (typeof object === "object") {
3296
+ this.encodeMap(object, depth);
3297
+ }
3298
+ else {
3299
+ // symbol, function and other special object come here unless extensionCodec handles them.
3300
+ throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(object)));
3301
+ }
3302
+ };
3303
+ Encoder.prototype.encodeBinary = function (object) {
3304
+ var size = object.byteLength;
3305
+ if (size < 0x100) {
3306
+ // bin 8
3307
+ this.writeU8(0xc4);
3308
+ this.writeU8(size);
3309
+ }
3310
+ else if (size < 0x10000) {
3311
+ // bin 16
3312
+ this.writeU8(0xc5);
3313
+ this.writeU16(size);
3314
+ }
3315
+ else if (size < 0x100000000) {
3316
+ // bin 32
3317
+ this.writeU8(0xc6);
3318
+ this.writeU32(size);
3319
+ }
3320
+ else {
3321
+ throw new Error("Too large binary: ".concat(size));
3322
+ }
3323
+ var bytes = (0,_utils_typedArrays_mjs__WEBPACK_IMPORTED_MODULE_2__.ensureUint8Array)(object);
3324
+ this.writeU8a(bytes);
3325
+ };
3326
+ Encoder.prototype.encodeArray = function (object, depth) {
3327
+ var size = object.length;
3328
+ if (size < 16) {
3329
+ // fixarray
3330
+ this.writeU8(0x90 + size);
3331
+ }
3332
+ else if (size < 0x10000) {
3333
+ // array 16
3334
+ this.writeU8(0xdc);
3335
+ this.writeU16(size);
3336
+ }
3337
+ else if (size < 0x100000000) {
3338
+ // array 32
3339
+ this.writeU8(0xdd);
3340
+ this.writeU32(size);
3341
+ }
3342
+ else {
3343
+ throw new Error("Too large array: ".concat(size));
3344
+ }
3345
+ for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {
3346
+ var item = object_1[_i];
3347
+ this.doEncode(item, depth + 1);
3348
+ }
3349
+ };
3350
+ Encoder.prototype.countWithoutUndefined = function (object, keys) {
3351
+ var count = 0;
3352
+ for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
3353
+ var key = keys_1[_i];
3354
+ if (object[key] !== undefined) {
3355
+ count++;
3356
+ }
3357
+ }
3358
+ return count;
3359
+ };
3360
+ Encoder.prototype.encodeMap = function (object, depth) {
3361
+ var keys = Object.keys(object);
3362
+ if (this.sortKeys) {
3363
+ keys.sort();
3364
+ }
3365
+ var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
3366
+ if (size < 16) {
3367
+ // fixmap
3368
+ this.writeU8(0x80 + size);
3369
+ }
3370
+ else if (size < 0x10000) {
3371
+ // map 16
3372
+ this.writeU8(0xde);
3373
+ this.writeU16(size);
3374
+ }
3375
+ else if (size < 0x100000000) {
3376
+ // map 32
3377
+ this.writeU8(0xdf);
3378
+ this.writeU32(size);
3379
+ }
3380
+ else {
3381
+ throw new Error("Too large map object: ".concat(size));
3382
+ }
3383
+ for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
3384
+ var key = keys_2[_i];
3385
+ var value = object[key];
3386
+ if (!(this.ignoreUndefined && value === undefined)) {
3387
+ this.encodeString(key);
3388
+ this.doEncode(value, depth + 1);
3389
+ }
3390
+ }
3391
+ };
3392
+ Encoder.prototype.encodeExtension = function (ext) {
3393
+ var size = ext.data.length;
3394
+ if (size === 1) {
3395
+ // fixext 1
3396
+ this.writeU8(0xd4);
3397
+ }
3398
+ else if (size === 2) {
3399
+ // fixext 2
3400
+ this.writeU8(0xd5);
3401
+ }
3402
+ else if (size === 4) {
3403
+ // fixext 4
3404
+ this.writeU8(0xd6);
3405
+ }
3406
+ else if (size === 8) {
3407
+ // fixext 8
3408
+ this.writeU8(0xd7);
3409
+ }
3410
+ else if (size === 16) {
3411
+ // fixext 16
3412
+ this.writeU8(0xd8);
3413
+ }
3414
+ else if (size < 0x100) {
3415
+ // ext 8
3416
+ this.writeU8(0xc7);
3417
+ this.writeU8(size);
3418
+ }
3419
+ else if (size < 0x10000) {
3420
+ // ext 16
3421
+ this.writeU8(0xc8);
3422
+ this.writeU16(size);
3423
+ }
3424
+ else if (size < 0x100000000) {
3425
+ // ext 32
3426
+ this.writeU8(0xc9);
3427
+ this.writeU32(size);
3428
+ }
3429
+ else {
3430
+ throw new Error("Too large extension object: ".concat(size));
3431
+ }
3432
+ this.writeI8(ext.type);
3433
+ this.writeU8a(ext.data);
3434
+ };
3435
+ Encoder.prototype.writeU8 = function (value) {
3436
+ this.ensureBufferSizeToWrite(1);
3437
+ this.view.setUint8(this.pos, value);
3438
+ this.pos++;
3439
+ };
3440
+ Encoder.prototype.writeU8a = function (values) {
3441
+ var size = values.length;
3442
+ this.ensureBufferSizeToWrite(size);
3443
+ this.bytes.set(values, this.pos);
3444
+ this.pos += size;
3445
+ };
3446
+ Encoder.prototype.writeI8 = function (value) {
3447
+ this.ensureBufferSizeToWrite(1);
3448
+ this.view.setInt8(this.pos, value);
3449
+ this.pos++;
3450
+ };
3451
+ Encoder.prototype.writeU16 = function (value) {
3452
+ this.ensureBufferSizeToWrite(2);
3453
+ this.view.setUint16(this.pos, value);
3454
+ this.pos += 2;
3455
+ };
3456
+ Encoder.prototype.writeI16 = function (value) {
3457
+ this.ensureBufferSizeToWrite(2);
3458
+ this.view.setInt16(this.pos, value);
3459
+ this.pos += 2;
3460
+ };
3461
+ Encoder.prototype.writeU32 = function (value) {
3462
+ this.ensureBufferSizeToWrite(4);
3463
+ this.view.setUint32(this.pos, value);
3464
+ this.pos += 4;
3465
+ };
3466
+ Encoder.prototype.writeI32 = function (value) {
3467
+ this.ensureBufferSizeToWrite(4);
3468
+ this.view.setInt32(this.pos, value);
3469
+ this.pos += 4;
3470
+ };
3471
+ Encoder.prototype.writeF32 = function (value) {
3472
+ this.ensureBufferSizeToWrite(4);
3473
+ this.view.setFloat32(this.pos, value);
3474
+ this.pos += 4;
3475
+ };
3476
+ Encoder.prototype.writeF64 = function (value) {
3477
+ this.ensureBufferSizeToWrite(8);
3478
+ this.view.setFloat64(this.pos, value);
3479
+ this.pos += 8;
3480
+ };
3481
+ Encoder.prototype.writeU64 = function (value) {
3482
+ this.ensureBufferSizeToWrite(8);
3483
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setUint64)(this.view, this.pos, value);
3484
+ this.pos += 8;
3485
+ };
3486
+ Encoder.prototype.writeI64 = function (value) {
3487
+ this.ensureBufferSizeToWrite(8);
3488
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_3__.setInt64)(this.view, this.pos, value);
3489
+ this.pos += 8;
3490
+ };
3491
+ return Encoder;
3492
+ }());
3493
+
3494
+ //# sourceMappingURL=Encoder.mjs.map
3495
+
3496
+ /***/ }),
3497
+
3498
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs":
3499
+ /*!****************************************************************!*\
3500
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs ***!
3501
+ \****************************************************************/
3502
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3503
+
3504
+ __webpack_require__.r(__webpack_exports__);
3505
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3506
+ /* harmony export */ ExtData: () => (/* binding */ ExtData)
3507
+ /* harmony export */ });
3508
+ /**
3509
+ * ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
3510
+ */
3511
+ var ExtData = /** @class */ (function () {
3512
+ function ExtData(type, data) {
3513
+ this.type = type;
3514
+ this.data = data;
3515
+ }
3516
+ return ExtData;
3517
+ }());
3518
+
3519
+ //# sourceMappingURL=ExtData.mjs.map
3520
+
3521
+ /***/ }),
3522
+
3523
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs":
3524
+ /*!***********************************************************************!*\
3525
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs ***!
3526
+ \***********************************************************************/
3527
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3528
+
3529
+ __webpack_require__.r(__webpack_exports__);
3530
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3531
+ /* harmony export */ ExtensionCodec: () => (/* binding */ ExtensionCodec)
3532
+ /* harmony export */ });
3533
+ /* harmony import */ var _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ExtData.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs");
3534
+ /* harmony import */ var _timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./timestamp.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs");
3535
+ // ExtensionCodec to handle MessagePack extensions
3536
+
3537
+
3538
+ var ExtensionCodec = /** @class */ (function () {
3539
+ function ExtensionCodec() {
3540
+ // built-in extensions
3541
+ this.builtInEncoders = [];
3542
+ this.builtInDecoders = [];
3543
+ // custom extensions
3544
+ this.encoders = [];
3545
+ this.decoders = [];
3546
+ this.register(_timestamp_mjs__WEBPACK_IMPORTED_MODULE_0__.timestampExtension);
3547
+ }
3548
+ ExtensionCodec.prototype.register = function (_a) {
3549
+ var type = _a.type, encode = _a.encode, decode = _a.decode;
3550
+ if (type >= 0) {
3551
+ // custom extensions
3552
+ this.encoders[type] = encode;
3553
+ this.decoders[type] = decode;
3554
+ }
3555
+ else {
3556
+ // built-in extensions
3557
+ var index = 1 + type;
3558
+ this.builtInEncoders[index] = encode;
3559
+ this.builtInDecoders[index] = decode;
3560
+ }
3561
+ };
3562
+ ExtensionCodec.prototype.tryToEncode = function (object, context) {
3563
+ // built-in extensions
3564
+ for (var i = 0; i < this.builtInEncoders.length; i++) {
3565
+ var encodeExt = this.builtInEncoders[i];
3566
+ if (encodeExt != null) {
3567
+ var data = encodeExt(object, context);
3568
+ if (data != null) {
3569
+ var type = -1 - i;
3570
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
3571
+ }
3572
+ }
3573
+ }
3574
+ // custom extensions
3575
+ for (var i = 0; i < this.encoders.length; i++) {
3576
+ var encodeExt = this.encoders[i];
3577
+ if (encodeExt != null) {
3578
+ var data = encodeExt(object, context);
3579
+ if (data != null) {
3580
+ var type = i;
3581
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
3582
+ }
3583
+ }
3584
+ }
3585
+ if (object instanceof _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData) {
3586
+ // to keep ExtData as is
3587
+ return object;
3588
+ }
3589
+ return null;
3590
+ };
3591
+ ExtensionCodec.prototype.decode = function (data, type, context) {
3592
+ var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
3593
+ if (decodeExt) {
3594
+ return decodeExt(data, type, context);
3595
+ }
3596
+ else {
3597
+ // decode() does not fail, returns ExtData instead.
3598
+ return new _ExtData_mjs__WEBPACK_IMPORTED_MODULE_1__.ExtData(type, data);
3599
+ }
3600
+ };
3601
+ ExtensionCodec.defaultCodec = new ExtensionCodec();
3602
+ return ExtensionCodec;
3603
+ }());
3604
+
3605
+ //# sourceMappingURL=ExtensionCodec.mjs.map
3606
+
3607
+ /***/ }),
3608
+
3609
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs":
3610
+ /*!***************************************************************!*\
3611
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/decode.mjs ***!
3612
+ \***************************************************************/
3613
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3614
+
3615
+ __webpack_require__.r(__webpack_exports__);
3616
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3617
+ /* harmony export */ decode: () => (/* binding */ decode),
3618
+ /* harmony export */ decodeMulti: () => (/* binding */ decodeMulti),
3619
+ /* harmony export */ defaultDecodeOptions: () => (/* binding */ defaultDecodeOptions)
3620
+ /* harmony export */ });
3621
+ /* harmony import */ var _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Decoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs");
3622
+
3623
+ var defaultDecodeOptions = {};
3624
+ /**
3625
+ * It decodes a single MessagePack object in a buffer.
3626
+ *
3627
+ * This is a synchronous decoding function.
3628
+ * See other variants for asynchronous decoding: {@link decodeAsync()}, {@link decodeStream()}, or {@link decodeArrayStream()}.
3629
+ *
3630
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
3631
+ * @throws {@link DecodeError} if the buffer contains invalid data.
3632
+ */
3633
+ function decode(buffer, options) {
3634
+ if (options === void 0) { options = defaultDecodeOptions; }
3635
+ var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
3636
+ return decoder.decode(buffer);
3637
+ }
3638
+ /**
3639
+ * It decodes multiple MessagePack objects in a buffer.
3640
+ * This is corresponding to {@link decodeMultiStream()}.
3641
+ *
3642
+ * @throws {@link RangeError} if the buffer is incomplete, including the case where the buffer is empty.
3643
+ * @throws {@link DecodeError} if the buffer contains invalid data.
3644
+ */
3645
+ function decodeMulti(buffer, options) {
3646
+ if (options === void 0) { options = defaultDecodeOptions; }
3647
+ var decoder = new _Decoder_mjs__WEBPACK_IMPORTED_MODULE_0__.Decoder(options.extensionCodec, options.context, options.maxStrLength, options.maxBinLength, options.maxArrayLength, options.maxMapLength, options.maxExtLength);
3648
+ return decoder.decodeMulti(buffer);
3649
+ }
3650
+ //# sourceMappingURL=decode.mjs.map
3651
+
3652
+ /***/ }),
3653
+
3654
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs":
3655
+ /*!***************************************************************!*\
3656
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/encode.mjs ***!
3657
+ \***************************************************************/
3658
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3659
+
3660
+ __webpack_require__.r(__webpack_exports__);
3661
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3662
+ /* harmony export */ encode: () => (/* binding */ encode)
3663
+ /* harmony export */ });
3664
+ /* harmony import */ var _Encoder_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Encoder.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/Encoder.mjs");
3665
+
3666
+ var defaultEncodeOptions = {};
3667
+ /**
3668
+ * It encodes `value` in the MessagePack format and
3669
+ * returns a byte buffer.
3670
+ *
3671
+ * 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`.
3672
+ */
3673
+ function encode(value, options) {
3674
+ if (options === void 0) { options = defaultEncodeOptions; }
3675
+ 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);
3676
+ return encoder.encodeSharedRef(value);
3677
+ }
3678
+ //# sourceMappingURL=encode.mjs.map
3679
+
3680
+ /***/ }),
3681
+
3682
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs":
3683
+ /*!******************************************************************!*\
3684
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/timestamp.mjs ***!
3685
+ \******************************************************************/
3686
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3687
+
3688
+ __webpack_require__.r(__webpack_exports__);
3689
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3690
+ /* harmony export */ EXT_TIMESTAMP: () => (/* binding */ EXT_TIMESTAMP),
3691
+ /* harmony export */ decodeTimestampExtension: () => (/* binding */ decodeTimestampExtension),
3692
+ /* harmony export */ decodeTimestampToTimeSpec: () => (/* binding */ decodeTimestampToTimeSpec),
3693
+ /* harmony export */ encodeDateToTimeSpec: () => (/* binding */ encodeDateToTimeSpec),
3694
+ /* harmony export */ encodeTimeSpecToTimestamp: () => (/* binding */ encodeTimeSpecToTimestamp),
3695
+ /* harmony export */ encodeTimestampExtension: () => (/* binding */ encodeTimestampExtension),
3696
+ /* harmony export */ timestampExtension: () => (/* binding */ timestampExtension)
3697
+ /* harmony export */ });
3698
+ /* harmony import */ var _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./DecodeError.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs");
3699
+ /* 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");
3700
+ // https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
3701
+
3702
+
3703
+ var EXT_TIMESTAMP = -1;
3704
+ var TIMESTAMP32_MAX_SEC = 0x100000000 - 1; // 32-bit unsigned int
3705
+ var TIMESTAMP64_MAX_SEC = 0x400000000 - 1; // 34-bit unsigned int
3706
+ function encodeTimeSpecToTimestamp(_a) {
3707
+ var sec = _a.sec, nsec = _a.nsec;
3708
+ if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
3709
+ // Here sec >= 0 && nsec >= 0
3710
+ if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
3711
+ // timestamp 32 = { sec32 (unsigned) }
3712
+ var rv = new Uint8Array(4);
3713
+ var view = new DataView(rv.buffer);
3714
+ view.setUint32(0, sec);
3715
+ return rv;
3716
+ }
3717
+ else {
3718
+ // timestamp 64 = { nsec30 (unsigned), sec34 (unsigned) }
3719
+ var secHigh = sec / 0x100000000;
3720
+ var secLow = sec & 0xffffffff;
3721
+ var rv = new Uint8Array(8);
3722
+ var view = new DataView(rv.buffer);
3723
+ // nsec30 | secHigh2
3724
+ view.setUint32(0, (nsec << 2) | (secHigh & 0x3));
3725
+ // secLow32
3726
+ view.setUint32(4, secLow);
3727
+ return rv;
3728
+ }
3729
+ }
3730
+ else {
3731
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
3732
+ var rv = new Uint8Array(12);
3733
+ var view = new DataView(rv.buffer);
3734
+ view.setUint32(0, nsec);
3735
+ (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.setInt64)(view, 4, sec);
3736
+ return rv;
3737
+ }
3738
+ }
3739
+ function encodeDateToTimeSpec(date) {
3740
+ var msec = date.getTime();
3741
+ var sec = Math.floor(msec / 1e3);
3742
+ var nsec = (msec - sec * 1e3) * 1e6;
3743
+ // Normalizes { sec, nsec } to ensure nsec is unsigned.
3744
+ var nsecInSec = Math.floor(nsec / 1e9);
3745
+ return {
3746
+ sec: sec + nsecInSec,
3747
+ nsec: nsec - nsecInSec * 1e9,
3748
+ };
3749
+ }
3750
+ function encodeTimestampExtension(object) {
3751
+ if (object instanceof Date) {
3752
+ var timeSpec = encodeDateToTimeSpec(object);
3753
+ return encodeTimeSpecToTimestamp(timeSpec);
3754
+ }
3755
+ else {
3756
+ return null;
3757
+ }
3758
+ }
3759
+ function decodeTimestampToTimeSpec(data) {
3760
+ var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
3761
+ // data may be 32, 64, or 96 bits
3762
+ switch (data.byteLength) {
3763
+ case 4: {
3764
+ // timestamp 32 = { sec32 }
3765
+ var sec = view.getUint32(0);
3766
+ var nsec = 0;
3767
+ return { sec: sec, nsec: nsec };
3768
+ }
3769
+ case 8: {
3770
+ // timestamp 64 = { nsec30, sec34 }
3771
+ var nsec30AndSecHigh2 = view.getUint32(0);
3772
+ var secLow32 = view.getUint32(4);
3773
+ var sec = (nsec30AndSecHigh2 & 0x3) * 0x100000000 + secLow32;
3774
+ var nsec = nsec30AndSecHigh2 >>> 2;
3775
+ return { sec: sec, nsec: nsec };
3776
+ }
3777
+ case 12: {
3778
+ // timestamp 96 = { nsec32 (unsigned), sec64 (signed) }
3779
+ var sec = (0,_utils_int_mjs__WEBPACK_IMPORTED_MODULE_0__.getInt64)(view, 4);
3780
+ var nsec = view.getUint32(0);
3781
+ return { sec: sec, nsec: nsec };
3782
+ }
3783
+ default:
3784
+ throw new _DecodeError_mjs__WEBPACK_IMPORTED_MODULE_1__.DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
3785
+ }
3786
+ }
3787
+ function decodeTimestampExtension(data) {
3788
+ var timeSpec = decodeTimestampToTimeSpec(data);
3789
+ return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
3790
+ }
3791
+ var timestampExtension = {
3792
+ type: EXT_TIMESTAMP,
3793
+ encode: encodeTimestampExtension,
3794
+ decode: decodeTimestampExtension,
3795
+ };
3796
+ //# sourceMappingURL=timestamp.mjs.map
3797
+
3798
+ /***/ }),
3799
+
3800
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs":
3801
+ /*!******************************************************************!*\
3802
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs ***!
3803
+ \******************************************************************/
3804
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3805
+
3806
+ __webpack_require__.r(__webpack_exports__);
3807
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3808
+ /* harmony export */ UINT32_MAX: () => (/* binding */ UINT32_MAX),
3809
+ /* harmony export */ getInt64: () => (/* binding */ getInt64),
3810
+ /* harmony export */ getUint64: () => (/* binding */ getUint64),
3811
+ /* harmony export */ setInt64: () => (/* binding */ setInt64),
3812
+ /* harmony export */ setUint64: () => (/* binding */ setUint64)
3813
+ /* harmony export */ });
3814
+ // Integer Utility
3815
+ var UINT32_MAX = 4294967295;
3816
+ // DataView extension to handle int64 / uint64,
3817
+ // where the actual range is 53-bits integer (a.k.a. safe integer)
3818
+ function setUint64(view, offset, value) {
3819
+ var high = value / 4294967296;
3820
+ var low = value; // high bits are truncated by DataView
3821
+ view.setUint32(offset, high);
3822
+ view.setUint32(offset + 4, low);
3823
+ }
3824
+ function setInt64(view, offset, value) {
3825
+ var high = Math.floor(value / 4294967296);
3826
+ var low = value; // high bits are truncated by DataView
3827
+ view.setUint32(offset, high);
3828
+ view.setUint32(offset + 4, low);
3829
+ }
3830
+ function getInt64(view, offset) {
3831
+ var high = view.getInt32(offset);
3832
+ var low = view.getUint32(offset + 4);
3833
+ return high * 4294967296 + low;
3834
+ }
3835
+ function getUint64(view, offset) {
3836
+ var high = view.getUint32(offset);
3837
+ var low = view.getUint32(offset + 4);
3838
+ return high * 4294967296 + low;
3839
+ }
3840
+ //# sourceMappingURL=int.mjs.map
3841
+
3842
+ /***/ }),
3843
+
3844
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs":
3845
+ /*!*************************************************************************!*\
3846
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs ***!
3847
+ \*************************************************************************/
3848
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3849
+
3850
+ __webpack_require__.r(__webpack_exports__);
3851
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3852
+ /* harmony export */ prettyByte: () => (/* binding */ prettyByte)
3853
+ /* harmony export */ });
3854
+ function prettyByte(byte) {
3855
+ return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0"));
3856
+ }
3857
+ //# sourceMappingURL=prettyByte.mjs.map
3858
+
3859
+ /***/ }),
3860
+
3861
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs":
3862
+ /*!**************************************************************************!*\
3863
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs ***!
3864
+ \**************************************************************************/
3865
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3866
+
3867
+ __webpack_require__.r(__webpack_exports__);
3868
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3869
+ /* harmony export */ createDataView: () => (/* binding */ createDataView),
3870
+ /* harmony export */ ensureUint8Array: () => (/* binding */ ensureUint8Array)
3871
+ /* harmony export */ });
3872
+ function ensureUint8Array(buffer) {
3873
+ if (buffer instanceof Uint8Array) {
3874
+ return buffer;
3875
+ }
3876
+ else if (ArrayBuffer.isView(buffer)) {
3877
+ return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
3878
+ }
3879
+ else if (buffer instanceof ArrayBuffer) {
3880
+ return new Uint8Array(buffer);
3881
+ }
3882
+ else {
3883
+ // ArrayLike<number>
3884
+ return Uint8Array.from(buffer);
3885
+ }
3886
+ }
3887
+ function createDataView(buffer) {
3888
+ if (buffer instanceof ArrayBuffer) {
3889
+ return new DataView(buffer);
3890
+ }
3891
+ var bufferView = ensureUint8Array(buffer);
3892
+ return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
3893
+ }
3894
+ //# sourceMappingURL=typedArrays.mjs.map
3895
+
3896
+ /***/ }),
3897
+
3898
+ /***/ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs":
3899
+ /*!*******************************************************************!*\
3900
+ !*** ./node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs ***!
3901
+ \*******************************************************************/
3902
+ /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
3903
+
3904
+ __webpack_require__.r(__webpack_exports__);
3905
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
3906
+ /* harmony export */ TEXT_DECODER_THRESHOLD: () => (/* binding */ TEXT_DECODER_THRESHOLD),
3907
+ /* harmony export */ TEXT_ENCODER_THRESHOLD: () => (/* binding */ TEXT_ENCODER_THRESHOLD),
3908
+ /* harmony export */ utf8Count: () => (/* binding */ utf8Count),
3909
+ /* harmony export */ utf8DecodeJs: () => (/* binding */ utf8DecodeJs),
3910
+ /* harmony export */ utf8DecodeTD: () => (/* binding */ utf8DecodeTD),
3911
+ /* harmony export */ utf8EncodeJs: () => (/* binding */ utf8EncodeJs),
3912
+ /* harmony export */ utf8EncodeTE: () => (/* binding */ utf8EncodeTE)
3913
+ /* harmony export */ });
3914
+ /* harmony import */ var _int_mjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./int.mjs */ "./node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs");
3915
+ var _a, _b, _c;
3916
+ /* eslint-disable @typescript-eslint/no-unnecessary-condition */
3917
+
3918
+ 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") &&
3919
+ typeof TextEncoder !== "undefined" &&
3920
+ typeof TextDecoder !== "undefined";
3921
+ function utf8Count(str) {
3922
+ var strLength = str.length;
3923
+ var byteLength = 0;
3924
+ var pos = 0;
3925
+ while (pos < strLength) {
3926
+ var value = str.charCodeAt(pos++);
3927
+ if ((value & 0xffffff80) === 0) {
3928
+ // 1-byte
3929
+ byteLength++;
3930
+ continue;
3931
+ }
3932
+ else if ((value & 0xfffff800) === 0) {
3933
+ // 2-bytes
3934
+ byteLength += 2;
3935
+ }
3936
+ else {
3937
+ // handle surrogate pair
3938
+ if (value >= 0xd800 && value <= 0xdbff) {
3939
+ // high surrogate
3940
+ if (pos < strLength) {
3941
+ var extra = str.charCodeAt(pos);
3942
+ if ((extra & 0xfc00) === 0xdc00) {
3943
+ ++pos;
3944
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
3945
+ }
3946
+ }
3947
+ }
3948
+ if ((value & 0xffff0000) === 0) {
3949
+ // 3-byte
3950
+ byteLength += 3;
3951
+ }
3952
+ else {
3953
+ // 4-byte
3954
+ byteLength += 4;
3955
+ }
3956
+ }
3957
+ }
3958
+ return byteLength;
3959
+ }
3960
+ function utf8EncodeJs(str, output, outputOffset) {
3961
+ var strLength = str.length;
3962
+ var offset = outputOffset;
3963
+ var pos = 0;
3964
+ while (pos < strLength) {
3965
+ var value = str.charCodeAt(pos++);
3966
+ if ((value & 0xffffff80) === 0) {
3967
+ // 1-byte
3968
+ output[offset++] = value;
3969
+ continue;
3970
+ }
3971
+ else if ((value & 0xfffff800) === 0) {
3972
+ // 2-bytes
3973
+ output[offset++] = ((value >> 6) & 0x1f) | 0xc0;
3974
+ }
3975
+ else {
3976
+ // handle surrogate pair
3977
+ if (value >= 0xd800 && value <= 0xdbff) {
3978
+ // high surrogate
3979
+ if (pos < strLength) {
3980
+ var extra = str.charCodeAt(pos);
3981
+ if ((extra & 0xfc00) === 0xdc00) {
3982
+ ++pos;
3983
+ value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;
3984
+ }
3985
+ }
3986
+ }
3987
+ if ((value & 0xffff0000) === 0) {
3988
+ // 3-byte
3989
+ output[offset++] = ((value >> 12) & 0x0f) | 0xe0;
3990
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
3991
+ }
3992
+ else {
3993
+ // 4-byte
3994
+ output[offset++] = ((value >> 18) & 0x07) | 0xf0;
3995
+ output[offset++] = ((value >> 12) & 0x3f) | 0x80;
3996
+ output[offset++] = ((value >> 6) & 0x3f) | 0x80;
3997
+ }
3998
+ }
3999
+ output[offset++] = (value & 0x3f) | 0x80;
4000
+ }
4001
+ }
4002
+ var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : undefined;
4003
+ var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
4004
+ ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
4005
+ : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force"
4006
+ ? 200
4007
+ : 0;
4008
+ function utf8EncodeTEencode(str, output, outputOffset) {
4009
+ output.set(sharedTextEncoder.encode(str), outputOffset);
4010
+ }
4011
+ function utf8EncodeTEencodeInto(str, output, outputOffset) {
4012
+ sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
4013
+ }
4014
+ var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
4015
+ var CHUNK_SIZE = 4096;
4016
+ function utf8DecodeJs(bytes, inputOffset, byteLength) {
4017
+ var offset = inputOffset;
4018
+ var end = offset + byteLength;
4019
+ var units = [];
4020
+ var result = "";
4021
+ while (offset < end) {
4022
+ var byte1 = bytes[offset++];
4023
+ if ((byte1 & 0x80) === 0) {
4024
+ // 1 byte
4025
+ units.push(byte1);
4026
+ }
4027
+ else if ((byte1 & 0xe0) === 0xc0) {
4028
+ // 2 bytes
4029
+ var byte2 = bytes[offset++] & 0x3f;
4030
+ units.push(((byte1 & 0x1f) << 6) | byte2);
4031
+ }
4032
+ else if ((byte1 & 0xf0) === 0xe0) {
4033
+ // 3 bytes
4034
+ var byte2 = bytes[offset++] & 0x3f;
4035
+ var byte3 = bytes[offset++] & 0x3f;
4036
+ units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);
4037
+ }
4038
+ else if ((byte1 & 0xf8) === 0xf0) {
4039
+ // 4 bytes
4040
+ var byte2 = bytes[offset++] & 0x3f;
4041
+ var byte3 = bytes[offset++] & 0x3f;
4042
+ var byte4 = bytes[offset++] & 0x3f;
4043
+ var unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;
4044
+ if (unit > 0xffff) {
4045
+ unit -= 0x10000;
4046
+ units.push(((unit >>> 10) & 0x3ff) | 0xd800);
4047
+ unit = 0xdc00 | (unit & 0x3ff);
4048
+ }
4049
+ units.push(unit);
4050
+ }
4051
+ else {
4052
+ units.push(byte1);
4053
+ }
4054
+ if (units.length >= CHUNK_SIZE) {
4055
+ result += String.fromCharCode.apply(String, units);
4056
+ units.length = 0;
4057
+ }
4058
+ }
4059
+ if (units.length > 0) {
4060
+ result += String.fromCharCode.apply(String, units);
4061
+ }
4062
+ return result;
4063
+ }
4064
+ var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
4065
+ var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE
4066
+ ? _int_mjs__WEBPACK_IMPORTED_MODULE_0__.UINT32_MAX
4067
+ : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force"
4068
+ ? 200
4069
+ : 0;
4070
+ function utf8DecodeTD(bytes, inputOffset, byteLength) {
4071
+ var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
4072
+ return sharedTextDecoder.decode(stringBytes);
4073
+ }
4074
+ //# sourceMappingURL=utf8.mjs.map
4075
+
4076
+ /***/ }),
4077
+
4078
+ /***/ "./package.json":
4079
+ /*!**********************!*\
4080
+ !*** ./package.json ***!
4081
+ \**********************/
4082
+ /***/ ((module) => {
4083
+
4084
+ module.exports = /*#__PURE__*/JSON.parse('{"name":"hypha-rpc","version":"0.1.0","description":"Hypha RPC client for connecting to Hypha server for data management and AI model serving.","main":"index.js","types":"index.d.ts","scripts":{"build":"rm -rf dist && npm run build-umd","build-umd":"webpack --config webpack.config.js --mode development && NODE_ENV=production webpack --config webpack.config.js --mode production --devtool source-map","watch":"NODE_ENV=production webpack --watch --progress --config webpack.config.js --mode production --devtool source-map","publish-npm":"npm install && npm run build && npm publish","serve":"webpack serve","stats":"webpack --profile --json > stats.json","stats-prod":"webpack --profile --json --mode production > stats-prod.json","clean":"rimraf dist/*","format":"prettier --write \\"{src,tests}/**/**\\"","check-format":"prettier --check \\"{src,tests}/**/**\\"","test":"karma start --single-run --browsers ChromeHeadless,FirefoxHeadless karma.conf.js","test-watch":"karma start --auto-watch --browsers ChromeDebugging karma.conf.js --debug"},"repository":{"type":"git","url":"git+https://github.com/oeway/hypha-rpc.git"},"keywords":["hypha","rpc"],"author":"Wei Ouyang","license":"MIT","bugs":{"url":"https://github.com/oeway/hypha-rpc/issues"},"homepage":"https://github.com/oeway/hypha-rpc","engines":{"node":">=19.0.0"},"dependencies":{"@msgpack/msgpack":"^2.7.1"},"devDependencies":{"@babel/core":"^7.24.9","@babel/plugin-syntax-dynamic-import":"^7.8.3","@babel/preset-env":"^7.24.8","babel-loader":"^9.1.3","chai":"^5.1.1","clean-webpack-plugin":"^4.0.0","copy-webpack-plugin":"^12.0.2","eslint":"^7.32.0","eslint-config-prettier":"^9.1.0","eslint-loader":"^4.0.2","karma":"^6.4.3","karma-chrome-launcher":"^3.2.0","karma-firefox-launcher":"^2.1.3","karma-mocha":"^2.0.1","karma-sourcemap-loader":"^0.4.0","karma-spec-reporter":"^0.0.36","karma-webpack":"^5.0.1","mocha":"^10.6.0","prettier":"^3.3.3","webpack":"^5.93.0","webpack-cli":"^5.1.4","webpack-dev-server":"^5.0.4"}}');
4085
+
4086
+ /***/ })
4087
+
4088
+ /******/ });
4089
+ /************************************************************************/
4090
+ /******/ // The module cache
4091
+ /******/ var __webpack_module_cache__ = {};
4092
+ /******/
4093
+ /******/ // The require function
4094
+ /******/ function __webpack_require__(moduleId) {
4095
+ /******/ // Check if module is in cache
4096
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
4097
+ /******/ if (cachedModule !== undefined) {
4098
+ /******/ return cachedModule.exports;
4099
+ /******/ }
4100
+ /******/ // Create a new module (and put it into the cache)
4101
+ /******/ var module = __webpack_module_cache__[moduleId] = {
4102
+ /******/ // no module.id needed
4103
+ /******/ // no module.loaded needed
4104
+ /******/ exports: {}
4105
+ /******/ };
4106
+ /******/
4107
+ /******/ // Execute the module function
4108
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
4109
+ /******/
4110
+ /******/ // Return the exports of the module
4111
+ /******/ return module.exports;
4112
+ /******/ }
4113
+ /******/
4114
+ /************************************************************************/
4115
+ /******/ /* webpack/runtime/define property getters */
4116
+ /******/ (() => {
4117
+ /******/ // define getter functions for harmony exports
4118
+ /******/ __webpack_require__.d = (exports, definition) => {
4119
+ /******/ for(var key in definition) {
4120
+ /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
4121
+ /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
4122
+ /******/ }
4123
+ /******/ }
4124
+ /******/ };
4125
+ /******/ })();
4126
+ /******/
4127
+ /******/ /* webpack/runtime/hasOwnProperty shorthand */
4128
+ /******/ (() => {
4129
+ /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
4130
+ /******/ })();
4131
+ /******/
4132
+ /******/ /* webpack/runtime/make namespace object */
4133
+ /******/ (() => {
4134
+ /******/ // define __esModule on exports
4135
+ /******/ __webpack_require__.r = (exports) => {
4136
+ /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
4137
+ /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4138
+ /******/ }
4139
+ /******/ Object.defineProperty(exports, '__esModule', { value: true });
4140
+ /******/ };
4141
+ /******/ })();
4142
+ /******/
4143
+ /************************************************************************/
4144
+ var __webpack_exports__ = {};
4145
+ /*!*********************************!*\
4146
+ !*** ./src/websocket-client.js ***!
4147
+ \*********************************/
4148
+ __webpack_require__.r(__webpack_exports__);
4149
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
4150
+ /* harmony export */ API_VERSION: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.API_VERSION),
4151
+ /* harmony export */ RPC: () => (/* reexport safe */ _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC),
4152
+ /* harmony export */ VERSION: () => (/* reexport safe */ _package_json__WEBPACK_IMPORTED_MODULE_3__.version),
4153
+ /* harmony export */ connectToServer: () => (/* binding */ connectToServer),
4154
+ /* harmony export */ getRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.getRTCService),
4155
+ /* harmony export */ loadRequirements: () => (/* reexport safe */ _utils_js__WEBPACK_IMPORTED_MODULE_1__.loadRequirements),
4156
+ /* harmony export */ login: () => (/* binding */ login),
4157
+ /* harmony export */ registerRTCService: () => (/* reexport safe */ _webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.registerRTCService),
4158
+ /* harmony export */ setupLocalClient: () => (/* binding */ setupLocalClient)
4159
+ /* harmony export */ });
4160
+ /* harmony import */ var _rpc_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./rpc.js */ "./src/rpc.js");
4161
+ /* harmony import */ var _utils_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./utils.js */ "./src/utils.js");
4162
+ /* harmony import */ var _webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webrtc-client.js */ "./src/webrtc-client.js");
4163
+ /* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../package.json */ "./package.json");
4164
+
4165
+
4166
+
4167
+
4168
+
4169
+
4170
+
4171
+
4172
+
4173
+ const MAX_RETRY = 10000;
4174
+
4175
+ class WebsocketRPCConnection {
4176
+ constructor(
4177
+ server_url,
4178
+ client_id,
4179
+ workspace,
4180
+ token,
4181
+ timeout = 60,
4182
+ WebSocketClass = null,
4183
+ ) {
4184
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(server_url && client_id, "server_url and client_id are required");
4185
+ this._server_url = server_url;
4186
+ this._client_id = client_id;
4187
+ this._workspace = workspace;
4188
+ this._token = token;
4189
+ this._reconnection_token = null;
4190
+ this._websocket = null;
4191
+ this._handle_message = null;
4192
+ this._handle_connect = null; // Connection open event handler
4193
+ this._disconnect_handler = null; // Disconnection event handler
4194
+ this._timeout = timeout * 1000; // Convert seconds to milliseconds
4195
+ this._WebSocketClass = WebSocketClass || WebSocket; // Allow overriding the WebSocket class
4196
+ this._opening = null;
4197
+ this._closing = false;
4198
+ this._legacy_auth = null;
4199
+ this.connection_info = null;
4200
+ }
4201
+
4202
+ on_message(handler) {
4203
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(handler, "handler is required");
4204
+ this._handle_message = handler;
4205
+ }
4206
+
4207
+ on_connect(handler) {
4208
+ this._handle_connect = handler;
4209
+ if (this._websocket && this._websocket.readyState === WebSocket.OPEN) {
4210
+ this._handle_connect(this);
4211
+ }
4212
+ }
4213
+
4214
+ on_disconnected(handler) {
4215
+ this._disconnect_handler = handler;
4216
+ }
4217
+
4218
+ set_reconnection_token(token) {
4219
+ this._reconnection_token = token;
4220
+ }
4221
+
4222
+ async _attempt_connection(server_url, attempt_fallback = true) {
4223
+ return new Promise((resolve, reject) => {
4224
+ this._legacy_auth = false;
4225
+ const websocket = new this._WebSocketClass(server_url);
4226
+ websocket.binaryType = "arraybuffer";
4227
+
4228
+ websocket.onopen = () => {
4229
+ console.info("WebSocket connection established");
4230
+ resolve(websocket);
4231
+ };
4232
+
4233
+ websocket.onerror = (event) => {
4234
+ console.error("WebSocket connection error:", event);
4235
+ reject(event);
4236
+ };
4237
+
4238
+ websocket.onclose = (event) => {
4239
+ if (event.code === 1003 && attempt_fallback) {
4240
+ console.info(
4241
+ "Received 1003 error, attempting connection with query parameters.",
4242
+ );
4243
+ this._attempt_connection_with_query_params(server_url)
4244
+ .then(resolve)
4245
+ .catch(reject);
4246
+ } else if (this._disconnect_handler) {
4247
+ this._disconnect_handler(this, event.reason);
4248
+ }
4249
+ };
4250
+ });
4251
+ }
4252
+
4253
+ async _attempt_connection_with_query_params(server_url) {
4254
+ // Initialize an array to hold parts of the query string
4255
+ const queryParamsParts = [];
4256
+
4257
+ // Conditionally add each parameter if it has a non-empty value
4258
+ if (this._client_id)
4259
+ queryParamsParts.push(`client_id=${encodeURIComponent(this._client_id)}`);
4260
+ if (this._workspace)
4261
+ queryParamsParts.push(`workspace=${encodeURIComponent(this._workspace)}`);
4262
+ if (this._token)
4263
+ queryParamsParts.push(`token=${encodeURIComponent(this._token)}`);
4264
+ if (this._reconnection_token)
4265
+ queryParamsParts.push(
4266
+ `reconnection_token=${encodeURIComponent(this._reconnection_token)}`,
4267
+ );
4268
+
4269
+ // Join the parts with '&' to form the final query string, prepend '?' if there are any parameters
4270
+ const queryString =
4271
+ queryParamsParts.length > 0 ? `?${queryParamsParts.join("&")}` : "";
4272
+
4273
+ // Construct the full URL by appending the query string if it exists
4274
+ const full_url = server_url + queryString;
4275
+
4276
+ this._legacy_auth = true; // Assuming this flag is needed for some other logic
4277
+ return await this._attempt_connection(full_url, false);
4278
+ }
4279
+
4280
+ async open() {
4281
+ if (this._closing || this._websocket) {
4282
+ return; // Avoid opening a new connection if closing or already open
4283
+ }
4284
+ try {
4285
+ this._opening = true;
4286
+ this._websocket = await this._attempt_connection(this._server_url);
4287
+ if (!this._legacy_auth) {
4288
+ // Send authentication info as the first message if connected without query params
4289
+ const authInfo = JSON.stringify({
4290
+ client_id: this._client_id,
4291
+ workspace: this._workspace,
4292
+ token: this._token,
4293
+ reconnection_token: this._reconnection_token,
4294
+ });
4295
+ this._websocket.send(authInfo);
4296
+ // Wait for the first message from the server
4297
+ await (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.waitFor)(
4298
+ new Promise((resolve, reject) => {
4299
+ this._websocket.onmessage = (event) => {
4300
+ const data = event.data;
4301
+ const first_message = JSON.parse(data);
4302
+ if (!first_message.success) {
4303
+ const error = first_message.error || "Unknown error";
4304
+ console.error("Failed to connect, " + error);
4305
+ this.connection_info = None;
4306
+ reject(new Error(error));
4307
+ } else if (first_message) {
4308
+ console.log(
4309
+ "Successfully connected: " + JSON.stringify(first_message),
4310
+ );
4311
+ this.connection_info = first_message;
4312
+ }
4313
+ resolve();
4314
+ };
4315
+ }),
4316
+ this._timeout / 1000.0,
4317
+ "Failed to receive the first message from the server",
4318
+ );
4319
+ }
4320
+
4321
+ this._websocket.onmessage = (event) => {
4322
+ const data = event.data;
4323
+ this._handle_message(data);
4324
+ };
4325
+
4326
+ if (this._handle_connect) {
4327
+ await this._handle_connect(this);
4328
+ }
4329
+ } catch (error) {
4330
+ console.error("Failed to connect to", this._server_url, error);
4331
+ } finally {
4332
+ this._opening = false;
4333
+ }
4334
+ }
4335
+
4336
+ async emit_message(data) {
4337
+ if (this._closing) {
4338
+ throw new Error("Connection is closing");
4339
+ }
4340
+ await this._opening;
4341
+ if (!this._websocket || this._websocket.readyState !== WebSocket.OPEN) {
4342
+ throw new Error("WebSocket connection is not open");
4343
+ }
4344
+ try {
4345
+ this._websocket.send(data);
4346
+ } catch (exp) {
4347
+ console.error(`Failed to send data, error: ${exp}`);
4348
+ throw exp;
4349
+ }
4350
+ }
4351
+
4352
+ disconnect(reason) {
4353
+ this._closing = true;
4354
+ if (this._websocket && this._websocket.readyState === WebSocket.OPEN) {
4355
+ this._websocket.close(1000, reason);
4356
+ console.info(`WebSocket connection disconnected (${reason})`);
4357
+ }
4358
+ }
4359
+ }
4360
+
4361
+ function normalizeServerUrl(server_url) {
4362
+ if (!server_url) throw new Error("server_url is required");
4363
+ if (server_url.startsWith("http://")) {
4364
+ server_url =
4365
+ server_url.replace("http://", "ws://").replace(/\/$/, "") + "/ws";
4366
+ } else if (server_url.startsWith("https://")) {
4367
+ server_url =
4368
+ server_url.replace("https://", "wss://").replace(/\/$/, "") + "/ws";
4369
+ }
4370
+ return server_url;
4371
+ }
4372
+
4373
+ async function login(config) {
4374
+ const service_id = config.login_service_id || "public/*:hypha-login";
4375
+ const timeout = config.login_timeout || 60;
4376
+ const callback = config.login_callback;
4377
+
4378
+ const server = await connectToServer({
4379
+ name: "initial login client",
4380
+ server_url: config.server_url,
4381
+ });
4382
+ try {
4383
+ const svc = await server.get_service(service_id);
4384
+ const context = await svc.start();
4385
+ if (callback) {
4386
+ await callback(context);
4387
+ } else {
4388
+ console.log(`Please open your browser and login at ${context.login_url}`);
4389
+ }
4390
+ return await svc.check(context.key, timeout);
4391
+ } catch (error) {
4392
+ throw error;
4393
+ } finally {
4394
+ await server.disconnect();
4395
+ }
4396
+ }
4397
+
4398
+ async function connectToServer(config) {
4399
+ if (config.server) {
4400
+ config.server_url = config.server_url || config.server.url;
4401
+ config.WebSocketClass =
4402
+ config.WebSocketClass || config.server.WebSocketClass;
4403
+ }
4404
+ let clientId = config.client_id;
4405
+ if (!clientId) {
4406
+ clientId = (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.randId)();
4407
+ config.client_id = clientId;
4408
+ }
4409
+
4410
+ let server_url = normalizeServerUrl(config.server_url);
4411
+
4412
+ let connection = new WebsocketRPCConnection(
4413
+ server_url,
4414
+ clientId,
4415
+ config.workspace,
4416
+ config.token,
4417
+ config.method_timeout || 60,
4418
+ config.WebSocketClass,
4419
+ );
4420
+ await connection.open();
4421
+ let workspace = config.workspace;
4422
+ if (connection.connection_info) {
4423
+ workspace = connection.connection_info.workspace;
4424
+ }
4425
+ const rpc = new _rpc_js__WEBPACK_IMPORTED_MODULE_0__.RPC(connection, {
4426
+ client_id: clientId,
4427
+ workspace,
4428
+ manager_id: "workspace-manager",
4429
+ default_context: { connection_type: "websocket" },
4430
+ name: config.name,
4431
+ method_timeout: config.method_timeout,
4432
+ app_id: config.app_id,
4433
+ });
4434
+ const wm = await rpc.get_remote_service("workspace-manager:default");
4435
+ wm.rpc = rpc;
4436
+
4437
+ async function _export(api) {
4438
+ api.id = "default";
4439
+ api.name = api.name || config.name || api.id;
4440
+ api.description = api.description || config.description;
4441
+ api.docs = api.docs || config.docs;
4442
+ await rpc.register_service(api, true);
4443
+ }
4444
+
4445
+ async function getPlugin(query) {
4446
+ return await wm.get_service(query + ":default");
4447
+ }
4448
+
4449
+ async function disconnect() {
4450
+ await rpc.disconnect();
4451
+ await connection.disconnect();
4452
+ }
4453
+
4454
+ wm.config["client_id"] = clientId;
4455
+ wm.export = _export;
4456
+ wm.getPlugin = getPlugin;
4457
+ wm.listPlugins = wm.listServices;
4458
+ wm.disconnect = disconnect;
4459
+ wm.registerCodec = rpc.register_codec.bind(rpc);
4460
+ wm.emit = rpc.emit;
4461
+ wm.on = rpc.on;
4462
+ if (rpc.manager_id) {
4463
+ rpc.on("force-exit", async (message) => {
4464
+ if (message.from.endsWith("/" + rpc.manager_id)) {
4465
+ console.log("Disconnecting from server, reason:", message.reason);
4466
+ await disconnect();
4467
+ }
4468
+ });
4469
+ }
4470
+ if (config.webrtc) {
4471
+ await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.registerRTCService)(wm, clientId + "-rtc", config.webrtc_config);
4472
+ }
4473
+ if (wm.get_service || wm.getService) {
4474
+ const _get_service = wm.get_service || wm.getService;
4475
+ wm.get_service = async function (query, webrtc, webrtc_config) {
4476
+ (0,_utils_js__WEBPACK_IMPORTED_MODULE_1__.assert)(
4477
+ [undefined, true, false, "auto"].includes(webrtc),
4478
+ "webrtc must be true, false or 'auto'",
4479
+ );
4480
+ const svc = await _get_service(query);
4481
+ if (webrtc === true || webrtc === "auto") {
4482
+ if (svc.id.includes(":") && svc.id.includes("/")) {
4483
+ const client = svc.id.split(":")[0];
4484
+ try {
4485
+ // Assuming that the client registered a webrtc service with the client_id + "-rtc"
4486
+ const peer = await (0,_webrtc_client_js__WEBPACK_IMPORTED_MODULE_2__.getRTCService)(
4487
+ wm,
4488
+ client + ":" + client.split("/")[1] + "-rtc",
4489
+ webrtc_config,
4490
+ );
4491
+ const rtcSvc = await peer.get_service(svc.id.split(":")[1]);
4492
+ rtcSvc._webrtc = true;
4493
+ rtcSvc._peer = peer;
4494
+ rtcSvc._service = svc;
4495
+ return rtcSvc;
4496
+ } catch (e) {
4497
+ console.warn(
4498
+ "Failed to get webrtc service, using websocket connection",
4499
+ e,
4500
+ );
4501
+ }
4502
+ }
4503
+ if (webrtc === true) {
4504
+ throw new Error("Failed to get the service via webrtc");
4505
+ }
4506
+ }
4507
+ return svc;
4508
+ };
4509
+ wm.getService = wm.get_service;
4510
+ }
4511
+ return wm;
4512
+ }
4513
+
4514
+ class LocalWebSocket {
4515
+ constructor(url, client_id, workspace) {
4516
+ this.url = url;
4517
+ this.onopen = () => {};
4518
+ this.onmessage = () => {};
4519
+ this.onclose = () => {};
4520
+ this.onerror = () => {};
4521
+ this.client_id = client_id;
4522
+ this.workspace = workspace;
4523
+ const context = typeof window !== "undefined" ? window : self;
4524
+ const isWindow = typeof window !== "undefined";
4525
+ this.postMessage = (message) => {
4526
+ if (isWindow) {
4527
+ window.parent.postMessage(message, "*");
4528
+ } else {
4529
+ self.postMessage(message);
4530
+ }
4531
+ };
4532
+
4533
+ this.readyState = WebSocket.CONNECTING;
4534
+ context.addEventListener(
4535
+ "message",
4536
+ (event) => {
4537
+ const { type, data, to } = event.data;
4538
+ if (to !== this.client_id) {
4539
+ console.debug("message not for me", to, this.client_id);
4540
+ return;
4541
+ }
4542
+ switch (type) {
4543
+ case "message":
4544
+ if (this.readyState === WebSocket.OPEN && this.onmessage) {
4545
+ this.onmessage({ data: data });
4546
+ }
4547
+ break;
4548
+ case "connected":
4549
+ this.readyState = WebSocket.OPEN;
4550
+ this.onopen(event);
4551
+ break;
4552
+ case "closed":
4553
+ this.readyState = WebSocket.CLOSED;
4554
+ this.onclose(event);
4555
+ break;
4556
+ default:
4557
+ break;
4558
+ }
4559
+ },
4560
+ false,
4561
+ );
4562
+
4563
+ if (!this.client_id) throw new Error("client_id is required");
4564
+ if (!this.workspace) throw new Error("workspace is required");
4565
+ this.postMessage({
4566
+ type: "connect",
4567
+ url: this.url,
4568
+ from: this.client_id,
4569
+ workspace: this.workspace,
4570
+ });
4571
+ }
4572
+
4573
+ send(data) {
4574
+ if (this.readyState === WebSocket.OPEN) {
4575
+ this.postMessage({
4576
+ type: "message",
4577
+ data: data,
4578
+ from: this.client_id,
4579
+ workspace: this.workspace,
4580
+ });
4581
+ }
4582
+ }
4583
+
4584
+ close() {
4585
+ this.readyState = WebSocket.CLOSING;
4586
+ this.postMessage({
4587
+ type: "close",
4588
+ from: this.client_id,
4589
+ workspace: this.workspace,
4590
+ });
4591
+ this.onclose();
4592
+ }
4593
+
4594
+ addEventListener(type, listener) {
4595
+ if (type === "message") {
4596
+ this.onmessage = listener;
4597
+ }
4598
+ if (type === "open") {
4599
+ this.onopen = listener;
4600
+ }
4601
+ if (type === "close") {
4602
+ this.onclose = listener;
4603
+ }
4604
+ if (type === "error") {
4605
+ this.onerror = listener;
4606
+ }
4607
+ }
4608
+ }
4609
+
4610
+ function setupLocalClient({
4611
+ enable_execution = false,
4612
+ on_ready = null,
4613
+ }) {
4614
+ return new Promise((resolve, reject) => {
4615
+ const context = typeof window !== "undefined" ? window : self;
4616
+ const isWindow = typeof window !== "undefined";
4617
+ context.addEventListener(
4618
+ "message",
4619
+ (event) => {
4620
+ const {
4621
+ type,
4622
+ server_url,
4623
+ workspace,
4624
+ client_id,
4625
+ token,
4626
+ method_timeout,
4627
+ name,
4628
+ config,
4629
+ } = event.data;
4630
+
4631
+ if (type === "initializeHyphaClient") {
4632
+ if (!server_url || !workspace || !client_id) {
4633
+ console.error("server_url, workspace, and client_id are required.");
4634
+ return;
4635
+ }
4636
+
4637
+ if (!server_url.startsWith("https://local-hypha-server:")) {
4638
+ console.error(
4639
+ "server_url should start with https://local-hypha-server:",
4640
+ );
4641
+ return;
4642
+ }
4643
+
4644
+ connectToServer({
4645
+ server_url,
4646
+ workspace,
4647
+ client_id,
4648
+ token,
4649
+ method_timeout,
4650
+ name,
4651
+ }).then(async (server) => {
4652
+ globalThis.api = server;
4653
+ try {
4654
+ // for iframe
4655
+ if (isWindow && enable_execution) {
4656
+ function loadScript(script) {
4657
+ return new Promise((resolve, reject) => {
4658
+ const scriptElement = document.createElement("script");
4659
+ scriptElement.innerHTML = script.content;
4660
+ scriptElement.lang = script.lang;
4661
+
4662
+ scriptElement.onload = () => resolve();
4663
+ scriptElement.onerror = (e) => reject(e);
4664
+
4665
+ document.head.appendChild(scriptElement);
4666
+ });
4667
+ }
4668
+ if (config.styles && config.styles.length > 0) {
4669
+ for (const style of config.styles) {
4670
+ const styleElement = document.createElement("style");
4671
+ styleElement.innerHTML = style.content;
4672
+ styleElement.lang = style.lang;
4673
+ document.head.appendChild(styleElement);
4674
+ }
4675
+ }
4676
+ if (config.links && config.links.length > 0) {
4677
+ for (const link of config.links) {
4678
+ const linkElement = document.createElement("a");
4679
+ linkElement.href = link.url;
4680
+ linkElement.innerText = link.text;
4681
+ document.body.appendChild(linkElement);
4682
+ }
4683
+ }
4684
+ if (config.windows && config.windows.length > 0) {
4685
+ for (const w of config.windows) {
4686
+ document.body.innerHTML = w.content;
4687
+ break;
4688
+ }
4689
+ }
4690
+ if (config.scripts && config.scripts.length > 0) {
4691
+ for (const script of config.scripts) {
4692
+ if (script.lang !== "javascript")
4693
+ throw new Error("Only javascript scripts are supported");
4694
+ await loadScript(script); // Await the loading of each script
4695
+ }
4696
+ }
4697
+ }
4698
+ // for web worker
4699
+ else if (
4700
+ !isWindow &&
4701
+ enable_execution &&
4702
+ config.scripts &&
4703
+ config.scripts.length > 0
4704
+ ) {
4705
+ for (const script of config.scripts) {
4706
+ if (script.lang !== "javascript")
4707
+ throw new Error("Only javascript scripts are supported");
4708
+ eval(script.content);
4709
+ }
4710
+ }
4711
+
4712
+ if (on_ready) {
4713
+ await on_ready(server, config);
4714
+ }
4715
+ resolve(server);
4716
+ } catch (e) {
4717
+ // If any script fails to load, send an error message
4718
+ await server.update_client_info({
4719
+ id: client_id,
4720
+ error: e.message,
4721
+ });
4722
+ reject(e);
4723
+ }
4724
+ });
4725
+ }
4726
+ },
4727
+ false,
4728
+ );
4729
+ if (isWindow) {
4730
+ window.parent.postMessage({ type: "hyphaClientReady" }, "*");
4731
+ } else {
4732
+ self.postMessage({ type: "hyphaClientReady" });
4733
+ }
4734
+ });
4735
+ }
4736
+
4737
+ /******/ return __webpack_exports__;
4738
+ /******/ })()
4739
+ ;
4740
+ });
4741
+ //# sourceMappingURL=hypha-rpc-websocket.js.map