@inditextech/weave-store-azure-web-pubsub 5.2.1 → 5.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { AzureKeyCredential, WebPubSubServiceClient } from "@azure/web-pubsub";
2
2
  import { DefaultAzureCredential } from "@azure/identity";
3
- import * as Y$1 from "yjs";
4
3
  import * as Y from "yjs";
5
4
  import { URL } from "node:url";
6
5
  import crypto, { createHmac, timingSafeEqual } from "node:crypto";
@@ -10,12 +9,10 @@ import process from "node:process";
10
9
  import { WebSocket } from "ws";
11
10
  import { mergeExceptArrays } from "@inditextech/weave-sdk";
12
11
  import { defaultInitialState } from "@inditextech/weave-sdk/server";
13
-
14
12
  //#region ../../node_modules/emittery/maps.js
15
- const anyMap = new WeakMap();
16
- const eventsMap = new WeakMap();
17
- const producersMap = new WeakMap();
18
-
13
+ const anyMap = /* @__PURE__ */ new WeakMap();
14
+ const eventsMap = /* @__PURE__ */ new WeakMap();
15
+ const producersMap = /* @__PURE__ */ new WeakMap();
19
16
  //#endregion
20
17
  //#region ../../node_modules/emittery/index.js
21
18
  const anyProducer = Symbol("anyProducer");
@@ -68,9 +65,8 @@ function iterator(instance, eventNames) {
68
65
  for (const eventName of eventNames) {
69
66
  let set = getEventProducers(instance, eventName);
70
67
  if (!set) {
71
- set = new Set();
72
- const producers = producersMap.get(instance);
73
- producers.set(eventName, set);
68
+ set = /* @__PURE__ */ new Set();
69
+ producersMap.get(instance).set(eventName, set);
74
70
  }
75
71
  set.add(producer);
76
72
  }
@@ -98,10 +94,7 @@ function iterator(instance, eventNames) {
98
94
  const set = getEventProducers(instance, eventName);
99
95
  if (set) {
100
96
  set.delete(producer);
101
- if (set.size === 0) {
102
- const producers = producersMap.get(instance);
103
- producers.delete(eventName);
104
- }
97
+ if (set.size === 0) producersMap.get(instance).delete(eventName);
105
98
  }
106
99
  }
107
100
  flush();
@@ -170,10 +163,10 @@ var Emittery = class Emittery {
170
163
  isGlobalDebugEnabled = newValue;
171
164
  }
172
165
  constructor(options = {}) {
173
- anyMap.set(this, new Set());
174
- eventsMap.set(this, new Map());
175
- producersMap.set(this, new Map());
176
- producersMap.get(this).set(anyProducer, new Set());
166
+ anyMap.set(this, /* @__PURE__ */ new Set());
167
+ eventsMap.set(this, /* @__PURE__ */ new Map());
168
+ producersMap.set(this, /* @__PURE__ */ new Map());
169
+ producersMap.get(this).set(anyProducer, /* @__PURE__ */ new Set());
177
170
  this.debug = options.debug ?? {};
178
171
  if (this.debug.enabled === void 0) this.debug.enabled = false;
179
172
  if (!this.debug.logger) this.debug.logger = (type, debugName, eventName, eventData) => {
@@ -183,7 +176,7 @@ var Emittery = class Emittery {
183
176
  eventData = `Object with the following keys failed to stringify: ${Object.keys(eventData).join(",")}`;
184
177
  }
185
178
  if (typeof eventName === "symbol" || typeof eventName === "number") eventName = eventName.toString();
186
- const currentTime = new Date();
179
+ const currentTime = /* @__PURE__ */ new Date();
187
180
  const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;
188
181
  console.log(`[${logTime}][emittery:${type}][${debugName}] Event Name: ${eventName}\n\tdata: ${eventData}`);
189
182
  };
@@ -198,9 +191,8 @@ var Emittery = class Emittery {
198
191
  assertEventName(eventName);
199
192
  let set = getListeners(this, eventName);
200
193
  if (!set) {
201
- set = new Set();
202
- const events = eventsMap.get(this);
203
- events.set(eventName, set);
194
+ set = /* @__PURE__ */ new Set();
195
+ eventsMap.get(this).set(eventName, set);
204
196
  }
205
197
  set.add(listener);
206
198
  this.logIfDebugEnabled("subscribe", eventName, void 0);
@@ -225,10 +217,7 @@ var Emittery = class Emittery {
225
217
  const set = getListeners(this, eventName);
226
218
  if (set) {
227
219
  set.delete(listener);
228
- if (set.size === 0) {
229
- const events = eventsMap.get(this);
230
- events.delete(eventName);
231
- }
220
+ if (set.size === 0) eventsMap.get(this).delete(eventName);
232
221
  }
233
222
  this.logIfDebugEnabled("unsubscribe", eventName, void 0);
234
223
  if (!isMetaEvent(eventName)) emitMetaEvent(this, listenerRemoved, {
@@ -237,12 +226,10 @@ var Emittery = class Emittery {
237
226
  });
238
227
  }
239
228
  }
240
- once(eventNames, predicate) {
241
- if (predicate !== void 0 && typeof predicate !== "function") throw new TypeError("predicate must be a function");
229
+ once(eventNames) {
242
230
  let off_;
243
231
  const promise = new Promise((resolve) => {
244
232
  off_ = this.on(eventNames, (data) => {
245
- if (predicate && !predicate(data)) return;
246
233
  off_();
247
234
  resolve(data);
248
235
  });
@@ -260,7 +247,7 @@ var Emittery = class Emittery {
260
247
  if (isMetaEvent(eventName) && !canEmitMetaEvents) throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");
261
248
  this.logIfDebugEnabled("emit", eventName, eventData);
262
249
  enqueueProducers(this, eventName, eventData);
263
- const listeners = getListeners(this, eventName) ?? new Set();
250
+ const listeners = getListeners(this, eventName) ?? /* @__PURE__ */ new Set();
264
251
  const anyListeners = anyMap.get(this);
265
252
  const staticListeners = [...listeners];
266
253
  const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];
@@ -275,11 +262,10 @@ var Emittery = class Emittery {
275
262
  assertEventName(eventName);
276
263
  if (isMetaEvent(eventName) && !canEmitMetaEvents) throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");
277
264
  this.logIfDebugEnabled("emitSerial", eventName, eventData);
278
- enqueueProducers(this, eventName, eventData);
279
- const listeners = getListeners(this, eventName) ?? new Set();
265
+ const listeners = getListeners(this, eventName) ?? /* @__PURE__ */ new Set();
280
266
  const anyListeners = anyMap.get(this);
281
267
  const staticListeners = [...listeners];
282
- const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];
268
+ const staticAnyListeners = [...anyListeners];
283
269
  await resolvedPromise;
284
270
  for (const listener of staticListeners) if (listeners.has(listener)) await listener(eventData);
285
271
  for (const listener of staticAnyListeners) if (anyListeners.has(listener)) await listener(eventName, eventData);
@@ -320,14 +306,14 @@ var Emittery = class Emittery {
320
306
  }
321
307
  } else {
322
308
  anyMap.get(this).clear();
323
- for (const [eventName$1, listeners] of eventsMap.get(this).entries()) {
309
+ for (const [eventName, listeners] of eventsMap.get(this).entries()) {
324
310
  listeners.clear();
325
- eventsMap.get(this).delete(eventName$1);
311
+ eventsMap.get(this).delete(eventName);
326
312
  }
327
- for (const [eventName$1, producers] of producersMap.get(this).entries()) {
313
+ for (const [eventName, producers] of producersMap.get(this).entries()) {
328
314
  for (const producer of producers) producer.finish();
329
315
  producers.clear();
330
- producersMap.get(this).delete(eventName$1);
316
+ producersMap.get(this).delete(eventName);
331
317
  }
332
318
  }
333
319
  }
@@ -372,26 +358,23 @@ Object.defineProperty(Emittery, "listenerRemoved", {
372
358
  enumerable: true,
373
359
  configurable: false
374
360
  });
375
-
376
361
  //#endregion
377
362
  //#region src/types.ts
378
- let MessageType = /* @__PURE__ */ function(MessageType$1) {
379
- MessageType$1["System"] = "system";
380
- MessageType$1["JoinGroup"] = "joinGroup";
381
- MessageType$1["SendToGroup"] = "sendToGroup";
382
- return MessageType$1;
363
+ let MessageType = /* @__PURE__ */ function(MessageType) {
364
+ MessageType["System"] = "system";
365
+ MessageType["JoinGroup"] = "joinGroup";
366
+ MessageType["SendToGroup"] = "sendToGroup";
367
+ return MessageType;
383
368
  }({});
384
- let MessageDataType = /* @__PURE__ */ function(MessageDataType$1) {
385
- MessageDataType$1["Init"] = "init";
386
- MessageDataType$1["Sync"] = "sync";
387
- MessageDataType$1["Awareness"] = "awareness";
388
- return MessageDataType$1;
369
+ let MessageDataType = /* @__PURE__ */ function(MessageDataType) {
370
+ MessageDataType["Init"] = "init";
371
+ MessageDataType["Sync"] = "sync";
372
+ MessageDataType["Awareness"] = "awareness";
373
+ return MessageDataType;
389
374
  }({});
390
-
391
375
  //#endregion
392
376
  //#region src/yjs.ts
393
- var yjs_default = Y$1;
394
-
377
+ var yjs_default = Y;
395
378
  //#endregion
396
379
  //#region src/server/event-handler/utils.ts
397
380
  function isJsonObject(obj) {
@@ -414,7 +397,7 @@ function fromBase64JsonString(base64String) {
414
397
  function getHttpHeader(req, key) {
415
398
  if (!key) return void 0;
416
399
  const value = req.headers[key.toLowerCase()];
417
- if (value === void 0) return void 0;
400
+ if (value === void 0) return;
418
401
  if (typeof value === "string") return value;
419
402
  return value[0];
420
403
  }
@@ -425,21 +408,18 @@ function readRequestBody(req) {
425
408
  chunks.push(chunk);
426
409
  });
427
410
  req.on("end", function() {
428
- const buffer = Buffer.concat(chunks);
429
- resolve(buffer);
411
+ resolve(Buffer.concat(chunks));
430
412
  });
431
413
  req.on("error", function(err) {
432
414
  reject(err);
433
415
  });
434
416
  });
435
417
  }
436
-
437
418
  //#endregion
438
419
  //#region ../../node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js
439
420
  function log(message, ...args) {
440
421
  process.stderr.write(`${util.format(message, ...args)}${EOL}`);
441
422
  }
442
-
443
423
  //#endregion
444
424
  //#region ../../node_modules/@typespec/ts-http-runtime/dist/esm/env.js
445
425
  /**
@@ -450,15 +430,8 @@ function log(message, ...args) {
450
430
  function getEnvironmentVariable(name) {
451
431
  return process.env[name];
452
432
  }
453
- /**
454
- * A constant that indicates whether the environment the code is running is Deno.
455
- */
456
- const isDeno = typeof process.versions.deno === "string" && process.versions.deno.length > 0;
457
- /**
458
- * A constant that indicates whether the environment the code is running is Bun.sh.
459
- */
460
- const isBun = typeof process.versions.bun === "string" && process.versions.bun.length > 0;
461
-
433
+ typeof process.versions.deno === "string" && process.versions.deno.length;
434
+ typeof process.versions.bun === "string" && process.versions.bun.length;
462
435
  //#endregion
463
436
  //#region ../../node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js
464
437
  const debugEnvVariable = getEnvironmentVariable("DEBUG");
@@ -581,8 +554,6 @@ function extend(namespace) {
581
554
  newDebugger.log = this.log;
582
555
  return newDebugger;
583
556
  }
584
- var debug_default = debugObj;
585
-
586
557
  //#endregion
587
558
  //#region ../../node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js
588
559
  const TYPESPEC_RUNTIME_LOG_LEVELS = [
@@ -611,34 +582,36 @@ function isTypeSpecRuntimeLogLevel(level) {
611
582
  * @returns The logger context.
612
583
  */
613
584
  function createLoggerContext(options) {
614
- const registeredLoggers = new Set();
585
+ const registeredLoggers = /* @__PURE__ */ new Set();
615
586
  const logLevelFromEnv = getEnvironmentVariable(options.logLevelEnvVarName);
616
587
  let logLevel;
617
- const clientLogger = debug_default(options.namespace);
588
+ const clientLogger = debugObj(options.namespace);
618
589
  clientLogger.log = (...args) => {
619
- debug_default.log(...args);
590
+ debugObj.log(...args);
620
591
  };
621
592
  function contextSetLogLevel(level) {
622
593
  if (level && !isTypeSpecRuntimeLogLevel(level)) throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`);
623
594
  logLevel = level;
624
- const enabledNamespaces$1 = [];
625
- for (const logger$1 of registeredLoggers) if (shouldEnable(logger$1)) enabledNamespaces$1.push(logger$1.namespace);
626
- debug_default.enable(enabledNamespaces$1.join(","));
595
+ const enabledNamespaces = [];
596
+ for (const logger of registeredLoggers) if (shouldEnable(logger)) enabledNamespaces.push(logger.namespace);
597
+ debugObj.enable(enabledNamespaces.join(","));
627
598
  }
628
- if (logLevelFromEnv) if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) contextSetLogLevel(logLevelFromEnv);
629
- else console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`);
630
- function shouldEnable(logger$1) {
631
- return Boolean(logLevel && levelMap[logger$1.level] <= levelMap[logLevel]);
599
+ if (logLevelFromEnv) {
600
+ if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) contextSetLogLevel(logLevelFromEnv);
601
+ else console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`);
602
+ }
603
+ function shouldEnable(logger) {
604
+ return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]);
632
605
  }
633
606
  function createLogger(parent, level) {
634
- const logger$1 = Object.assign(parent.extend(level), { level });
635
- patchLogMethod(parent, logger$1);
636
- if (shouldEnable(logger$1)) {
637
- const enabledNamespaces$1 = debug_default.disable();
638
- debug_default.enable(enabledNamespaces$1 + "," + logger$1.namespace);
607
+ const logger = Object.assign(parent.extend(level), { level });
608
+ patchLogMethod(parent, logger);
609
+ if (shouldEnable(logger)) {
610
+ const enabledNamespaces = debugObj.disable();
611
+ debugObj.enable(enabledNamespaces + "," + logger.namespace);
639
612
  }
640
- registeredLoggers.add(logger$1);
641
- return logger$1;
613
+ registeredLoggers.add(logger);
614
+ return logger;
642
615
  }
643
616
  function contextGetLogLevel() {
644
617
  return logLevel;
@@ -660,33 +633,17 @@ function createLoggerContext(options) {
660
633
  logger: clientLogger
661
634
  };
662
635
  }
663
- const context$1 = createLoggerContext({
636
+ createLoggerContext({
664
637
  logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL",
665
638
  namespace: "typeSpecRuntime"
666
- });
667
- /**
668
- * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
669
- * @param level - The log level to enable for logging.
670
- * Options from most verbose to least verbose are:
671
- * - verbose
672
- * - info
673
- * - warning
674
- * - error
675
- */
676
- const TypeSpecRuntimeLogger = context$1.logger;
677
-
639
+ }).logger;
678
640
  //#endregion
679
641
  //#region ../../node_modules/@azure/logger/dist/esm/index.js
680
642
  const context = createLoggerContext({
681
643
  logLevelEnvVarName: "AZURE_LOG_LEVEL",
682
644
  namespace: "azure"
683
645
  });
684
- /**
685
- * The AzureLogger provides a mechanism for overriding where logs are output to.
686
- * By default, logs are sent to stderr.
687
- * Override the `log` method to redirect logs to another location.
688
- */
689
- const AzureLogger = context.logger;
646
+ context.logger;
690
647
  /**
691
648
  * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
692
649
  * @param namespace - The name of the SDK package.
@@ -695,173 +652,162 @@ const AzureLogger = context.logger;
695
652
  function createClientLogger(namespace) {
696
653
  return context.createClientLogger(namespace);
697
654
  }
698
-
699
655
  //#endregion
700
656
  //#region src/server/event-handler/logger.ts
701
657
  const logger = createClientLogger("store-azure-web-pubsub");
702
-
703
658
  //#endregion
704
659
  //#region src/server/event-handler/enum/mqtt-error-codes/mqtt-v311-connect-return-code.ts
705
660
  /**
706
661
  * MQTT 3.1.1 Connect Return Codes.
707
662
  */
708
- let MqttV311ConnectReturnCode = /* @__PURE__ */ function(MqttV311ConnectReturnCode$1) {
663
+ let MqttV311ConnectReturnCode = /* @__PURE__ */ function(MqttV311ConnectReturnCode) {
709
664
  /**
710
665
  * 0x01: Connection refused, unacceptable protocol version
711
666
  * The Server does not support the level of the MQTT protocol requested by the Client.
712
667
  */
713
- MqttV311ConnectReturnCode$1[MqttV311ConnectReturnCode$1["UnacceptableProtocolVersion"] = 1] = "UnacceptableProtocolVersion";
668
+ MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["UnacceptableProtocolVersion"] = 1] = "UnacceptableProtocolVersion";
714
669
  /**
715
670
  * 0x02: Connection refused, identifier rejected
716
671
  * The Client identifier is correct UTF-8 but not allowed by the Server.
717
672
  */
718
- MqttV311ConnectReturnCode$1[MqttV311ConnectReturnCode$1["IdentifierRejected"] = 2] = "IdentifierRejected";
673
+ MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["IdentifierRejected"] = 2] = "IdentifierRejected";
719
674
  /**
720
675
  * 0x03: Connection refused, server unavailable
721
676
  * The Network Connection has been made but the MQTT service is unavailable.
722
677
  */
723
- MqttV311ConnectReturnCode$1[MqttV311ConnectReturnCode$1["ServerUnavailable"] = 3] = "ServerUnavailable";
678
+ MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["ServerUnavailable"] = 3] = "ServerUnavailable";
724
679
  /**
725
680
  * 0x04: Connection refused, bad user name or password
726
681
  * The data in the user name or password is malformed.
727
682
  */
728
- MqttV311ConnectReturnCode$1[MqttV311ConnectReturnCode$1["BadUsernameOrPassword"] = 4] = "BadUsernameOrPassword";
683
+ MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["BadUsernameOrPassword"] = 4] = "BadUsernameOrPassword";
729
684
  /**
730
685
  * 0x05: Connection refused, not authorized
731
686
  * The Client is not authorized to connect.
732
687
  */
733
- MqttV311ConnectReturnCode$1[MqttV311ConnectReturnCode$1["NotAuthorized"] = 5] = "NotAuthorized";
734
- return MqttV311ConnectReturnCode$1;
688
+ MqttV311ConnectReturnCode[MqttV311ConnectReturnCode["NotAuthorized"] = 5] = "NotAuthorized";
689
+ return MqttV311ConnectReturnCode;
735
690
  }({});
736
-
737
691
  //#endregion
738
692
  //#region src/server/event-handler/enum/mqtt-error-codes/mqtt-v500-connect-reason-code.ts
739
693
  /**
740
694
  * MQTT Connect Reason Codes
741
695
  * These codes represent the reasons for the outcome of an MQTT CONNECT packet as per MQTT 5.0 specification.
742
696
  */
743
- let MqttV500ConnectReasonCode = /* @__PURE__ */ function(MqttV500ConnectReasonCode$1) {
697
+ let MqttV500ConnectReasonCode = /* @__PURE__ */ function(MqttV500ConnectReasonCode) {
744
698
  /**
745
699
  * 0x80 - Unspecified error
746
700
  * Description: The Server does not wish to reveal the reason for the failure, or none of the other Reason Codes apply.
747
701
  */
748
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["UnspecifiedError"] = 128] = "UnspecifiedError";
702
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["UnspecifiedError"] = 128] = "UnspecifiedError";
749
703
  /**
750
704
  * 0x81 - Malformed Packet
751
705
  * Description: Data within the CONNECT packet could not be correctly parsed.
752
706
  */
753
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["MalformedPacket"] = 129] = "MalformedPacket";
707
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["MalformedPacket"] = 129] = "MalformedPacket";
754
708
  /**
755
709
  * 0x82 - Protocol Error
756
710
  * Description: Data in the CONNECT packet does not conform to this specification.
757
711
  */
758
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["ProtocolError"] = 130] = "ProtocolError";
712
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ProtocolError"] = 130] = "ProtocolError";
759
713
  /**
760
714
  * 0x83 - Implementation specific error
761
715
  * Description: The CONNECT is valid but is not accepted by this Server.
762
716
  */
763
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["ImplementationSpecificError"] = 131] = "ImplementationSpecificError";
717
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ImplementationSpecificError"] = 131] = "ImplementationSpecificError";
764
718
  /**
765
719
  * 0x84 - Unsupported Protocol Version
766
720
  * Description: The Server does not support the version of the MQTT protocol requested by the Client.
767
721
  */
768
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["UnsupportedProtocolVersion"] = 132] = "UnsupportedProtocolVersion";
722
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["UnsupportedProtocolVersion"] = 132] = "UnsupportedProtocolVersion";
769
723
  /**
770
724
  * 0x85 - Client Identifier not valid
771
725
  * Description: The Client Identifier is a valid string but is not allowed by the Server.
772
726
  */
773
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["ClientIdentifierNotValid"] = 133] = "ClientIdentifierNotValid";
727
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ClientIdentifierNotValid"] = 133] = "ClientIdentifierNotValid";
774
728
  /**
775
729
  * 0x86 - Bad User Name or Password
776
730
  * Description: The Server does not accept the User Name or Password specified by the Client.
777
731
  */
778
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["BadUserNameOrPassword"] = 134] = "BadUserNameOrPassword";
732
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["BadUserNameOrPassword"] = 134] = "BadUserNameOrPassword";
779
733
  /**
780
734
  * 0x87 - Not authorized
781
735
  * Description: The Client is not authorized to connect.
782
736
  */
783
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["NotAuthorized"] = 135] = "NotAuthorized";
737
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["NotAuthorized"] = 135] = "NotAuthorized";
784
738
  /**
785
739
  * 0x88 - Server unavailable
786
740
  * Description: The MQTT Server is not available.
787
741
  */
788
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["ServerUnavailable"] = 136] = "ServerUnavailable";
742
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ServerUnavailable"] = 136] = "ServerUnavailable";
789
743
  /**
790
744
  * 0x89 - Server busy
791
745
  * Description: The Server is busy. Try again later.
792
746
  */
793
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["ServerBusy"] = 137] = "ServerBusy";
747
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ServerBusy"] = 137] = "ServerBusy";
794
748
  /**
795
749
  * 0x8A - Banned
796
750
  * Description: This Client has been banned by administrative action. Contact the server administrator.
797
751
  */
798
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["Banned"] = 138] = "Banned";
752
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["Banned"] = 138] = "Banned";
799
753
  /**
800
754
  * 0x8C - Bad authentication method
801
755
  * Description: The authentication method is not supported or does not match the authentication method currently in use.
802
756
  */
803
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["BadAuthenticationMethod"] = 140] = "BadAuthenticationMethod";
757
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["BadAuthenticationMethod"] = 140] = "BadAuthenticationMethod";
804
758
  /**
805
759
  * 0x90 - Topic Name invalid
806
760
  * Description: The Will Topic Name is not malformed, but is not accepted by this Server.
807
761
  */
808
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["TopicNameInvalid"] = 144] = "TopicNameInvalid";
762
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["TopicNameInvalid"] = 144] = "TopicNameInvalid";
809
763
  /**
810
764
  * 0x95 - Packet too large
811
765
  * Description: The CONNECT packet exceeded the maximum permissible size.
812
766
  */
813
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["PacketTooLarge"] = 149] = "PacketTooLarge";
767
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["PacketTooLarge"] = 149] = "PacketTooLarge";
814
768
  /**
815
769
  * 0x97 - Quota exceeded
816
770
  * Description: An implementation or administrative imposed limit has been exceeded.
817
771
  */
818
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["QuotaExceeded"] = 151] = "QuotaExceeded";
772
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["QuotaExceeded"] = 151] = "QuotaExceeded";
819
773
  /**
820
774
  * 0x99 - Payload format invalid
821
775
  * Description: The Will Payload does not match the specified Payload Format Indicator.
822
776
  */
823
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["PayloadFormatInvalid"] = 153] = "PayloadFormatInvalid";
777
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["PayloadFormatInvalid"] = 153] = "PayloadFormatInvalid";
824
778
  /**
825
779
  * 0x9A - Retain not supported
826
780
  * Description: The Server does not support retained messages, and Will Retain was set to 1.
827
781
  */
828
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["RetainNotSupported"] = 154] = "RetainNotSupported";
782
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["RetainNotSupported"] = 154] = "RetainNotSupported";
829
783
  /**
830
784
  * 0x9B - QoS not supported
831
785
  * Description: The Server does not support the QoS set in Will QoS.
832
786
  */
833
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["QosNotSupported"] = 155] = "QosNotSupported";
787
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["QosNotSupported"] = 155] = "QosNotSupported";
834
788
  /**
835
789
  * 0x9C - Use another server
836
790
  * Description: The Client should temporarily use another server.
837
791
  */
838
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["UseAnotherServer"] = 156] = "UseAnotherServer";
792
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["UseAnotherServer"] = 156] = "UseAnotherServer";
839
793
  /**
840
794
  * 0x9D - Server moved
841
795
  * Description: The Client should permanently use another server.
842
796
  */
843
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["ServerMoved"] = 157] = "ServerMoved";
797
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ServerMoved"] = 157] = "ServerMoved";
844
798
  /**
845
799
  * 0x9F - Connection rate exceeded
846
800
  * Description: The connection rate limit has been exceeded.
847
801
  */
848
- MqttV500ConnectReasonCode$1[MqttV500ConnectReasonCode$1["ConnectionRateExceeded"] = 159] = "ConnectionRateExceeded";
849
- return MqttV500ConnectReasonCode$1;
802
+ MqttV500ConnectReasonCode[MqttV500ConnectReasonCode["ConnectionRateExceeded"] = 159] = "ConnectionRateExceeded";
803
+ return MqttV500ConnectReasonCode;
850
804
  }({});
851
-
852
805
  //#endregion
853
806
  //#region src/server/event-handler/cloud-events-dispatcher.ts
854
- var EventType = /* @__PURE__ */ function(EventType$1) {
855
- EventType$1[EventType$1["Connect"] = 0] = "Connect";
856
- EventType$1[EventType$1["Connected"] = 1] = "Connected";
857
- EventType$1[EventType$1["Disconnected"] = 2] = "Disconnected";
858
- EventType$1[EventType$1["UserEvent"] = 3] = "UserEvent";
859
- return EventType$1;
860
- }(EventType || {});
861
807
  function getConnectResponseHandler(connectRequest, response) {
862
808
  const states = connectRequest.context.states;
863
809
  let modified = false;
864
- const handler = {
810
+ return {
865
811
  setState(name, value) {
866
812
  states[name] = value;
867
813
  modified = true;
@@ -888,12 +834,11 @@ function getConnectResponseHandler(connectRequest, response) {
888
834
  } else handleConnectErrorResponse(connectRequest, response, res.code, res.detail);
889
835
  }
890
836
  };
891
- return handler;
892
837
  }
893
838
  function getUserEventResponseHandler(userRequest, response) {
894
839
  const states = userRequest.context.states;
895
840
  let modified = false;
896
- const handler = {
841
+ return {
897
842
  setState(name, value) {
898
843
  modified = true;
899
844
  states[name] = value;
@@ -908,9 +853,7 @@ function getUserEventResponseHandler(userRequest, response) {
908
853
  case "text":
909
854
  response.setHeader("Content-Type", "text/plain; charset=utf-8");
910
855
  break;
911
- default:
912
- response.setHeader("Content-Type", "application/octet-stream");
913
- break;
856
+ default: response.setHeader("Content-Type", "application/octet-stream");
914
857
  }
915
858
  response.end(data ?? "");
916
859
  },
@@ -919,7 +862,6 @@ function getUserEventResponseHandler(userRequest, response) {
919
862
  response.end(detail ?? "");
920
863
  }
921
864
  };
922
- return handler;
923
865
  }
924
866
  function getContext(request, origin) {
925
867
  const baseContext = {
@@ -951,47 +893,47 @@ function tryGetWebPubSubEvent(req) {
951
893
  const disconnectd = "azure.webpubsub.sys.disconnected";
952
894
  const userPrefix = "azure.webpubsub.user.";
953
895
  const type = getHttpHeader(req, "ce-type");
954
- if (!type?.startsWith(prefix)) return void 0;
955
- if (type.startsWith(userPrefix)) return EventType.UserEvent;
896
+ if (!type?.startsWith(prefix)) return;
897
+ if (type.startsWith(userPrefix)) return 3;
956
898
  switch (type) {
957
- case connect: return EventType.Connect;
958
- case connected: return EventType.Connected;
959
- case disconnectd: return EventType.Disconnected;
960
- default: return void 0;
899
+ case connect: return 0;
900
+ case connected: return 1;
901
+ case disconnectd: return 2;
902
+ default: return;
961
903
  }
962
904
  }
963
905
  function getStatusCodeFromMqttConnectCode(mqttConnectCode) {
964
906
  if (mqttConnectCode < 128) switch (mqttConnectCode) {
965
- case MqttV311ConnectReturnCode.UnacceptableProtocolVersion:
966
- case MqttV311ConnectReturnCode.IdentifierRejected: return 400;
967
- case MqttV311ConnectReturnCode.ServerUnavailable: return 503;
968
- case MqttV311ConnectReturnCode.BadUsernameOrPassword:
969
- case MqttV311ConnectReturnCode.NotAuthorized: return 401;
907
+ case 1:
908
+ case 2: return 400;
909
+ case 3: return 503;
910
+ case 4:
911
+ case 5: return 401;
970
912
  default:
971
913
  logger.warning(`Invalid MQTT connect return code: ${mqttConnectCode}.`);
972
914
  return 500;
973
915
  }
974
916
  else switch (mqttConnectCode) {
975
- case MqttV500ConnectReasonCode.NotAuthorized:
976
- case MqttV500ConnectReasonCode.BadUserNameOrPassword: return 401;
977
- case MqttV500ConnectReasonCode.ClientIdentifierNotValid:
978
- case MqttV500ConnectReasonCode.MalformedPacket:
979
- case MqttV500ConnectReasonCode.UnsupportedProtocolVersion:
980
- case MqttV500ConnectReasonCode.BadAuthenticationMethod:
981
- case MqttV500ConnectReasonCode.TopicNameInvalid:
982
- case MqttV500ConnectReasonCode.PayloadFormatInvalid:
983
- case MqttV500ConnectReasonCode.ImplementationSpecificError:
984
- case MqttV500ConnectReasonCode.PacketTooLarge:
985
- case MqttV500ConnectReasonCode.RetainNotSupported:
986
- case MqttV500ConnectReasonCode.QosNotSupported: return 400;
987
- case MqttV500ConnectReasonCode.QuotaExceeded:
988
- case MqttV500ConnectReasonCode.ConnectionRateExceeded: return 429;
989
- case MqttV500ConnectReasonCode.Banned: return 403;
990
- case MqttV500ConnectReasonCode.UseAnotherServer:
991
- case MqttV500ConnectReasonCode.ServerMoved:
992
- case MqttV500ConnectReasonCode.ServerUnavailable:
993
- case MqttV500ConnectReasonCode.ServerBusy:
994
- case MqttV500ConnectReasonCode.UnspecifiedError: return 500;
917
+ case 135:
918
+ case 134: return 401;
919
+ case 133:
920
+ case 129:
921
+ case 132:
922
+ case 140:
923
+ case 144:
924
+ case 153:
925
+ case 131:
926
+ case 149:
927
+ case 154:
928
+ case 155: return 400;
929
+ case 151:
930
+ case 159: return 429;
931
+ case 138: return 403;
932
+ case 156:
933
+ case 157:
934
+ case 136:
935
+ case 137:
936
+ case 128: return 500;
995
937
  default:
996
938
  logger.warning(`Invalid MQTT connect return code: ${mqttConnectCode}.`);
997
939
  return 500;
@@ -999,29 +941,28 @@ function getStatusCodeFromMqttConnectCode(mqttConnectCode) {
999
941
  }
1000
942
  function getMqttConnectCodeFromStatusCode(statusCode, protocolVersion) {
1001
943
  if (protocolVersion === 4) switch (statusCode) {
1002
- case 400: return MqttV311ConnectReturnCode.BadUsernameOrPassword;
1003
- case 401: return MqttV311ConnectReturnCode.NotAuthorized;
1004
- case 500: return MqttV311ConnectReturnCode.ServerUnavailable;
944
+ case 400: return 4;
945
+ case 401: return 5;
946
+ case 500: return 3;
1005
947
  default:
1006
948
  logger.warning(`Unsupported HTTP Status Code: ${statusCode}.`);
1007
- return MqttV311ConnectReturnCode.ServerUnavailable;
949
+ return 3;
1008
950
  }
1009
951
  else if (protocolVersion === 5) switch (statusCode) {
1010
- case 400: return MqttV500ConnectReasonCode.BadUserNameOrPassword;
1011
- case 401: return MqttV500ConnectReasonCode.NotAuthorized;
1012
- case 500: return MqttV500ConnectReasonCode.UnspecifiedError;
952
+ case 400: return 134;
953
+ case 401: return 135;
954
+ case 500: return 128;
1013
955
  default:
1014
956
  logger.warning(`Unsupported HTTP Status Code: ${statusCode}.`);
1015
- return MqttV500ConnectReasonCode.UnspecifiedError;
957
+ return 128;
1016
958
  }
1017
959
  else {
1018
960
  logger.warning(`Invalid MQTT protocol version: ${protocolVersion}.`);
1019
- return MqttV311ConnectReturnCode.UnacceptableProtocolVersion;
961
+ return 1;
1020
962
  }
1021
963
  }
1022
964
  function handleConnectErrorResponse(connectRequest, response, code, detail) {
1023
- const isMqttReq = connectRequest.context.clientProtocol === "mqtt";
1024
- if (isMqttReq) {
965
+ if (connectRequest.context.clientProtocol === "mqtt") {
1025
966
  const protocolVersion = connectRequest.mqtt.protocolVersion;
1026
967
  const mqttErrorResponse = { mqtt: {
1027
968
  code: getMqttConnectCodeFromStatusCode(code, protocolVersion),
@@ -1045,9 +986,8 @@ function isMqttRequest(req) {
1045
986
  }
1046
987
  async function readUserEventRequest(request, origin) {
1047
988
  const contentTypeheader = getHttpHeader(request, "content-type");
1048
- if (contentTypeheader === void 0) return void 0;
1049
- const contentType = contentTypeheader.split(";")[0].trim();
1050
- switch (contentType) {
989
+ if (contentTypeheader === void 0) return;
990
+ switch (contentTypeheader.split(";")[0].trim()) {
1051
991
  case "application/octet-stream": return {
1052
992
  context: getContext(request, origin),
1053
993
  data: bufferToArrayBufferCopy(await readRequestBody(request)),
@@ -1063,7 +1003,7 @@ async function readUserEventRequest(request, origin) {
1063
1003
  data: (await readRequestBody(request)).toString(),
1064
1004
  dataType: "text"
1065
1005
  };
1066
- default: return void 0;
1006
+ default: return;
1067
1007
  }
1068
1008
  }
1069
1009
  async function readSystemEventRequest(request, origin) {
@@ -1076,6 +1016,8 @@ async function readSystemEventRequest(request, origin) {
1076
1016
  * @internal
1077
1017
  */
1078
1018
  var CloudEventsDispatcher = class {
1019
+ hub;
1020
+ eventHandler;
1079
1021
  _allowAll = true;
1080
1022
  _allowedOrigins = [];
1081
1023
  _accessKeys = [];
@@ -1112,8 +1054,7 @@ var CloudEventsDispatcher = class {
1112
1054
  }
1113
1055
  handlePreflight(req, res) {
1114
1056
  if (!isWebPubSubRequest(req)) return false;
1115
- const origin = getHttpHeader(req, "webhook-request-origin");
1116
- if (origin === void 0) {
1057
+ if (getHttpHeader(req, "webhook-request-origin") === void 0) {
1117
1058
  logger.warning("Expecting webhook-request-origin header.");
1118
1059
  res.statusCode = 400;
1119
1060
  } else if (this._allowAll) res.setHeader("WebHook-Allowed-Origin", "*");
@@ -1139,8 +1080,7 @@ var CloudEventsDispatcher = class {
1139
1080
  }
1140
1081
  const eventType = tryGetWebPubSubEvent(request);
1141
1082
  if (eventType === void 0) return false;
1142
- const hub = getHttpHeader(request, "ce-hub");
1143
- if (hub?.toUpperCase() !== this.hub.toUpperCase()) return false;
1083
+ if (getHttpHeader(request, "ce-hub")?.toUpperCase() !== this.hub.toUpperCase()) return false;
1144
1084
  const sigHeader = getHttpHeader(request, "ce-signature");
1145
1085
  const connectionId = getHttpHeader(request, "ce-connectionid");
1146
1086
  if (this._accessKeys.length > 0) {
@@ -1152,26 +1092,26 @@ var CloudEventsDispatcher = class {
1152
1092
  } else logger.warning("CloudEventsDispatcher: no accessKey configured — ce-signature is not verified. Restrict ingress to Azure Web PubSub IP ranges or provide an accessKey.");
1153
1093
  const isMqtt = isMqttRequest(request);
1154
1094
  switch (eventType) {
1155
- case EventType.Connect:
1095
+ case 0:
1156
1096
  if (!this.eventHandler?.handleConnect) {
1157
1097
  if (isMqtt) response.statusCode = 204;
1158
1098
  response.end();
1159
1099
  return true;
1160
1100
  }
1161
1101
  break;
1162
- case EventType.Connected:
1102
+ case 1:
1163
1103
  if (!this.eventHandler?.onConnected) {
1164
1104
  response.end();
1165
1105
  return true;
1166
1106
  }
1167
1107
  break;
1168
- case EventType.Disconnected:
1108
+ case 2:
1169
1109
  if (!this.eventHandler?.onDisconnected) {
1170
1110
  response.end();
1171
1111
  return true;
1172
1112
  }
1173
1113
  break;
1174
- case EventType.UserEvent:
1114
+ case 3:
1175
1115
  if (!this.eventHandler?.handleUserEvent) {
1176
1116
  response.end();
1177
1117
  return true;
@@ -1182,28 +1122,28 @@ var CloudEventsDispatcher = class {
1182
1122
  return false;
1183
1123
  }
1184
1124
  switch (eventType) {
1185
- case EventType.Connect: {
1125
+ case 0: {
1186
1126
  const connectRequest = isMqtt ? await readSystemEventRequest(request, origin) : await readSystemEventRequest(request, origin);
1187
1127
  connectRequest.queries = connectRequest.queries ?? {};
1188
1128
  logger.verbose(connectRequest);
1189
1129
  this.eventHandler.handleConnect(connectRequest, getConnectResponseHandler(connectRequest, response));
1190
1130
  return true;
1191
1131
  }
1192
- case EventType.Connected: {
1132
+ case 1: {
1193
1133
  response.end();
1194
1134
  const connectedRequest = await readSystemEventRequest(request, origin);
1195
1135
  logger.verbose(connectedRequest);
1196
1136
  this.eventHandler.onConnected(connectedRequest);
1197
1137
  return true;
1198
1138
  }
1199
- case EventType.Disconnected: {
1139
+ case 2: {
1200
1140
  response.end();
1201
1141
  const disconnectedRequest = isMqtt ? await readSystemEventRequest(request, origin) : await readSystemEventRequest(request, origin);
1202
1142
  logger.verbose(disconnectedRequest);
1203
1143
  this.eventHandler.onDisconnected(disconnectedRequest);
1204
1144
  return true;
1205
1145
  }
1206
- case EventType.UserEvent: {
1146
+ case 3: {
1207
1147
  const userRequest = await readUserEventRequest(request, origin);
1208
1148
  if (userRequest === void 0) {
1209
1149
  logger.warning(`Unsupported content type ${getHttpHeader(request, "content-type")}`);
@@ -1222,13 +1162,18 @@ var CloudEventsDispatcher = class {
1222
1162
  function bufferToArrayBufferCopy(buf) {
1223
1163
  return Uint8Array.from(buf).buffer;
1224
1164
  }
1225
-
1226
1165
  //#endregion
1227
1166
  //#region src/server/event-handler/web-pubsub-event-handler.ts
1228
1167
  /**
1229
1168
  * The handler to handle incoming CloudEvents messages
1230
1169
  */
1231
1170
  var WebPubSubEventHandler = class {
1171
+ hub;
1172
+ /**
1173
+ * The path this CloudEvents handler listens to
1174
+ */
1175
+ path;
1176
+ _cloudEventsHandler;
1232
1177
  /**
1233
1178
  * Creates an instance of a WebPubSubEventHandler for handling incoming CloudEvents messages.
1234
1179
  *
@@ -1302,232 +1247,188 @@ var WebPubSubEventHandler = class {
1302
1247
  };
1303
1248
  }
1304
1249
  };
1305
-
1306
1250
  //#endregion
1307
1251
  //#region src/server/event-handler/enum/mqtt-error-codes/mqtt-disconnect-reason-code.ts
1308
1252
  /**
1309
1253
  * MQTT 5.0 Disconnect Reason Codes.
1310
1254
  */
1311
- let MqttDisconnectReasonCode = /* @__PURE__ */ function(MqttDisconnectReasonCode$1) {
1255
+ let MqttDisconnectReasonCode = /* @__PURE__ */ function(MqttDisconnectReasonCode) {
1312
1256
  /**
1313
1257
  * 0x00 - Normal disconnection
1314
1258
  * Sent by: Client or Server
1315
1259
  * Description: Close the connection normally. Do not send the Will Message.
1316
1260
  */
1317
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["NormalDisconnection"] = 0] = "NormalDisconnection";
1261
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["NormalDisconnection"] = 0] = "NormalDisconnection";
1318
1262
  /**
1319
1263
  * 0x04 - Disconnect with Will Message
1320
1264
  * Sent by: Client
1321
1265
  * Description: The Client wishes to disconnect but requires that the Server also publishes its Will Message.
1322
1266
  */
1323
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["DisconnectWithWillMessage"] = 4] = "DisconnectWithWillMessage";
1267
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["DisconnectWithWillMessage"] = 4] = "DisconnectWithWillMessage";
1324
1268
  /**
1325
1269
  * 0x80 - Unspecified error
1326
1270
  * Sent by: Client or Server
1327
1271
  * Description: The Connection is closed but the sender either does not wish to reveal the reason, or none of the other Reason Codes apply.
1328
1272
  */
1329
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["UnspecifiedError"] = 128] = "UnspecifiedError";
1273
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["UnspecifiedError"] = 128] = "UnspecifiedError";
1330
1274
  /**
1331
1275
  * 0x81 - Malformed Packet
1332
1276
  * Sent by: Client or Server
1333
1277
  * Description: The received packet does not conform to this specification.
1334
1278
  */
1335
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["MalformedPacket"] = 129] = "MalformedPacket";
1279
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["MalformedPacket"] = 129] = "MalformedPacket";
1336
1280
  /**
1337
1281
  * 0x82 - Protocol Error
1338
1282
  * Sent by: Client or Server
1339
1283
  * Description: An unexpected or out of order packet was received.
1340
1284
  */
1341
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["ProtocolError"] = 130] = "ProtocolError";
1285
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["ProtocolError"] = 130] = "ProtocolError";
1342
1286
  /**
1343
1287
  * 0x83 - Implementation specific error
1344
1288
  * Sent by: Client or Server
1345
1289
  * Description: The packet received is valid but cannot be processed by this implementation.
1346
1290
  */
1347
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["ImplementationSpecificError"] = 131] = "ImplementationSpecificError";
1291
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["ImplementationSpecificError"] = 131] = "ImplementationSpecificError";
1348
1292
  /**
1349
1293
  * 0x87 - Not authorized
1350
1294
  * Sent by: Server
1351
1295
  * Description: The request is not authorized.
1352
1296
  */
1353
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["NotAuthorized"] = 135] = "NotAuthorized";
1297
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["NotAuthorized"] = 135] = "NotAuthorized";
1354
1298
  /**
1355
1299
  * 0x89 - Server busy
1356
1300
  * Sent by: Server
1357
1301
  * Description: The Server is busy and cannot continue processing requests from this Client.
1358
1302
  */
1359
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["ServerBusy"] = 137] = "ServerBusy";
1303
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["ServerBusy"] = 137] = "ServerBusy";
1360
1304
  /**
1361
1305
  * 0x8B - Server shutting down
1362
1306
  * Sent by: Server
1363
1307
  * Description: The Server is shutting down.
1364
1308
  */
1365
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["ServerShuttingDown"] = 139] = "ServerShuttingDown";
1309
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["ServerShuttingDown"] = 139] = "ServerShuttingDown";
1366
1310
  /**
1367
1311
  * 0x8D - Keep Alive timeout
1368
1312
  * Sent by: Server
1369
1313
  * Description: The Connection is closed because no packet has been received for 1.5 times the Keepalive time.
1370
1314
  */
1371
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["KeepAliveTimeout"] = 141] = "KeepAliveTimeout";
1315
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["KeepAliveTimeout"] = 141] = "KeepAliveTimeout";
1372
1316
  /**
1373
1317
  * 0x8E - Session taken over
1374
1318
  * Sent by: Server
1375
1319
  * Description: Another Connection using the same ClientID has connected causing this Connection to be closed.
1376
1320
  */
1377
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["SessionTakenOver"] = 142] = "SessionTakenOver";
1321
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["SessionTakenOver"] = 142] = "SessionTakenOver";
1378
1322
  /**
1379
1323
  * 0x8F - Topic Filter invalid
1380
1324
  * Sent by: Server
1381
1325
  * Description: The Topic Filter is correctly formed, but is not accepted by this Server.
1382
1326
  */
1383
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["TopicFilterInvalid"] = 143] = "TopicFilterInvalid";
1327
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["TopicFilterInvalid"] = 143] = "TopicFilterInvalid";
1384
1328
  /**
1385
1329
  * 0x90 - Topic Name invalid
1386
1330
  * Sent by: Client or Server
1387
1331
  * Description: The Topic Name is correctly formed, but is not accepted by this Client or Server.
1388
1332
  */
1389
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["TopicNameInvalid"] = 144] = "TopicNameInvalid";
1333
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["TopicNameInvalid"] = 144] = "TopicNameInvalid";
1390
1334
  /**
1391
1335
  * 0x93 - Receive Maximum exceeded
1392
1336
  * Sent by: Client or Server
1393
1337
  * Description: The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.
1394
1338
  */
1395
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["ReceiveMaximumExceeded"] = 147] = "ReceiveMaximumExceeded";
1339
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["ReceiveMaximumExceeded"] = 147] = "ReceiveMaximumExceeded";
1396
1340
  /**
1397
1341
  * 0x94 - Topic Alias invalid
1398
1342
  * Sent by: Client or Server
1399
1343
  * Description: The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.
1400
1344
  */
1401
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["TopicAliasInvalid"] = 148] = "TopicAliasInvalid";
1345
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["TopicAliasInvalid"] = 148] = "TopicAliasInvalid";
1402
1346
  /**
1403
1347
  * 0x95 - Packet too large
1404
1348
  * Sent by: Client or Server
1405
1349
  * Description: The packet size is greater than Maximum Packet Size for this Client or Server.
1406
1350
  */
1407
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["PacketTooLarge"] = 149] = "PacketTooLarge";
1351
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["PacketTooLarge"] = 149] = "PacketTooLarge";
1408
1352
  /**
1409
1353
  * 0x96 - Message rate too high
1410
1354
  * Sent by: Client or Server
1411
1355
  * Description: The received data rate is too high.
1412
1356
  */
1413
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["MessageRateTooHigh"] = 150] = "MessageRateTooHigh";
1357
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["MessageRateTooHigh"] = 150] = "MessageRateTooHigh";
1414
1358
  /**
1415
1359
  * 0x97 - Quota exceeded
1416
1360
  * Sent by: Client or Server
1417
1361
  * Description: An implementation or administrative imposed limit has been exceeded.
1418
1362
  */
1419
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["QuotaExceeded"] = 151] = "QuotaExceeded";
1363
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["QuotaExceeded"] = 151] = "QuotaExceeded";
1420
1364
  /**
1421
1365
  * 0x98 - Administrative action
1422
1366
  * Sent by: Client or Server
1423
1367
  * Description: The Connection is closed due to an administrative action.
1424
1368
  */
1425
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["AdministrativeAction"] = 152] = "AdministrativeAction";
1369
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["AdministrativeAction"] = 152] = "AdministrativeAction";
1426
1370
  /**
1427
1371
  * 0x99 - Payload format invalid
1428
1372
  * Sent by: Client or Server
1429
1373
  * Description: The payload format does not match the one specified by the Payload Format Indicator.
1430
1374
  */
1431
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["PayloadFormatInvalid"] = 153] = "PayloadFormatInvalid";
1375
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["PayloadFormatInvalid"] = 153] = "PayloadFormatInvalid";
1432
1376
  /**
1433
1377
  * 0x9A - Retain not supported
1434
1378
  * Sent by: Server
1435
1379
  * Description: The Server does not support retained messages.
1436
1380
  */
1437
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["RetainNotSupported"] = 154] = "RetainNotSupported";
1381
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["RetainNotSupported"] = 154] = "RetainNotSupported";
1438
1382
  /**
1439
1383
  * 0x9B - QoS not supported
1440
1384
  * Sent by: Server
1441
1385
  * Description: The Client specified a QoS greater than the QoS specified in a Maximum QoS in the CONNACK.
1442
1386
  */
1443
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["QosNotSupported"] = 155] = "QosNotSupported";
1387
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["QosNotSupported"] = 155] = "QosNotSupported";
1444
1388
  /**
1445
1389
  * 0x9C - Use another server
1446
1390
  * Sent by: Server
1447
1391
  * Description: The Client should temporarily change its Server.
1448
1392
  */
1449
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["UseAnotherServer"] = 156] = "UseAnotherServer";
1393
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["UseAnotherServer"] = 156] = "UseAnotherServer";
1450
1394
  /**
1451
1395
  * 0x9D - Server moved
1452
1396
  * Sent by: Server
1453
1397
  * Description: The Server is moved and the Client should permanently change its server location.
1454
1398
  */
1455
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["ServerMoved"] = 157] = "ServerMoved";
1399
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["ServerMoved"] = 157] = "ServerMoved";
1456
1400
  /**
1457
1401
  * 0x9E - Shared Subscriptions not supported
1458
1402
  * Sent by: Server
1459
1403
  * Description: The Server does not support Shared Subscriptions.
1460
1404
  */
1461
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["SharedSubscriptionsNotSupported"] = 158] = "SharedSubscriptionsNotSupported";
1405
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["SharedSubscriptionsNotSupported"] = 158] = "SharedSubscriptionsNotSupported";
1462
1406
  /**
1463
1407
  * 0x9F - Connection rate exceeded
1464
1408
  * Sent by: Server
1465
1409
  * Description: This connection is closed because the connection rate is too high.
1466
1410
  */
1467
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["ConnectionRateExceeded"] = 159] = "ConnectionRateExceeded";
1411
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["ConnectionRateExceeded"] = 159] = "ConnectionRateExceeded";
1468
1412
  /**
1469
1413
  * 0xA0 - Maximum connect time
1470
1414
  * Sent by: Server
1471
1415
  * Description: The maximum connection time authorized for this connection has been exceeded.
1472
1416
  */
1473
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["MaximumConnectTime"] = 160] = "MaximumConnectTime";
1417
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["MaximumConnectTime"] = 160] = "MaximumConnectTime";
1474
1418
  /**
1475
1419
  * 0xA1 - Subscription Identifiers not supported
1476
1420
  * Sent by: Server
1477
1421
  * Description: The Server does not support Subscription Identifiers; the subscription is not accepted.
1478
1422
  */
1479
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["SubscriptionIdentifiersNotSupported"] = 161] = "SubscriptionIdentifiersNotSupported";
1423
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["SubscriptionIdentifiersNotSupported"] = 161] = "SubscriptionIdentifiersNotSupported";
1480
1424
  /**
1481
1425
  * 0xA2 - Wildcard Subscriptions not supported
1482
1426
  * Sent by: Server
1483
1427
  * Description: The Server does not support Wildcard Subscriptions; the subscription is not accepted.
1484
1428
  */
1485
- MqttDisconnectReasonCode$1[MqttDisconnectReasonCode$1["WildcardSubscriptionsNotSupported"] = 162] = "WildcardSubscriptionsNotSupported";
1486
- return MqttDisconnectReasonCode$1;
1429
+ MqttDisconnectReasonCode[MqttDisconnectReasonCode["WildcardSubscriptionsNotSupported"] = 162] = "WildcardSubscriptionsNotSupported";
1430
+ return MqttDisconnectReasonCode;
1487
1431
  }({});
1488
-
1489
- //#endregion
1490
- //#region ../../node_modules/lib0/binary.js
1491
- const BIT8 = 128;
1492
- const BIT18 = 1 << 17;
1493
- const BIT19 = 1 << 18;
1494
- const BIT20 = 1 << 19;
1495
- const BIT21 = 1 << 20;
1496
- const BIT22 = 1 << 21;
1497
- const BIT23 = 1 << 22;
1498
- const BIT24 = 1 << 23;
1499
- const BIT25 = 1 << 24;
1500
- const BIT26 = 1 << 25;
1501
- const BIT27 = 1 << 26;
1502
- const BIT28 = 1 << 27;
1503
- const BIT29 = 1 << 28;
1504
- const BIT30 = 1 << 29;
1505
- const BIT31 = 1 << 30;
1506
- const BIT32 = 1 << 31;
1507
- const BITS7 = 127;
1508
- const BITS17 = BIT18 - 1;
1509
- const BITS18 = BIT19 - 1;
1510
- const BITS19 = BIT20 - 1;
1511
- const BITS20 = BIT21 - 1;
1512
- const BITS21 = BIT22 - 1;
1513
- const BITS22 = BIT23 - 1;
1514
- const BITS23 = BIT24 - 1;
1515
- const BITS24 = BIT25 - 1;
1516
- const BITS25 = BIT26 - 1;
1517
- const BITS26 = BIT27 - 1;
1518
- const BITS27 = BIT28 - 1;
1519
- const BITS28 = BIT29 - 1;
1520
- const BITS29 = BIT30 - 1;
1521
- const BITS30 = BIT31 - 1;
1522
- /**
1523
- * @type {number}
1524
- */
1525
- const BITS31 = 2147483647;
1526
- /**
1527
- * @type {number}
1528
- */
1529
- const BITS32 = 4294967295;
1530
-
1531
1432
  //#endregion
1532
1433
  //#region ../../node_modules/lib0/math.js
1533
1434
  /**
@@ -1550,20 +1451,19 @@ const min = (a, b) => a < b ? a : b;
1550
1451
  * @return {number} The bigger element of a and b
1551
1452
  */
1552
1453
  const max = (a, b) => a > b ? a : b;
1553
- const isNaN$1 = Number.isNaN;
1554
-
1454
+ Number.isNaN;
1555
1455
  //#endregion
1556
1456
  //#region ../../node_modules/lib0/number.js
1457
+ /**
1458
+ * Utility helpers for working with numbers.
1459
+ *
1460
+ * @module number
1461
+ */
1557
1462
  const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
1558
- const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
1559
- const LOWEST_INT32 = 1 << 31;
1560
- const HIGHEST_INT32 = BITS31;
1561
- const HIGHEST_UINT32 = BITS32;
1562
- /* c8 ignore next */
1563
- const isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num);
1564
- const isNaN = Number.isNaN;
1565
- const parseInt = Number.parseInt;
1566
-
1463
+ Number.MIN_SAFE_INTEGER;
1464
+ Number.isInteger;
1465
+ Number.isNaN;
1466
+ Number.parseInt;
1567
1467
  //#endregion
1568
1468
  //#region ../../node_modules/lib0/set.js
1569
1469
  /**
@@ -1571,8 +1471,7 @@ const parseInt = Number.parseInt;
1571
1471
  *
1572
1472
  * @module set
1573
1473
  */
1574
- const create$2 = () => new Set();
1575
-
1474
+ const create$2 = () => /* @__PURE__ */ new Set();
1576
1475
  //#endregion
1577
1476
  //#region ../../node_modules/lib0/array.js
1578
1477
  /**
@@ -1584,8 +1483,7 @@ const create$2 = () => new Set();
1584
1483
  * @return {T}
1585
1484
  */
1586
1485
  const from = Array.from;
1587
- const isArray$1 = Array.isArray;
1588
-
1486
+ Array.isArray;
1589
1487
  //#endregion
1590
1488
  //#region ../../node_modules/lib0/string.js
1591
1489
  /**
@@ -1594,12 +1492,8 @@ const isArray$1 = Array.isArray;
1594
1492
  * @module string
1595
1493
  */
1596
1494
  const fromCharCode = String.fromCharCode;
1597
- const fromCodePoint = String.fromCodePoint;
1598
- /**
1599
- * The largest utf16 character.
1600
- * Corresponds to Uint8Array([255, 255]) or charcodeof(2x2^8)
1601
- */
1602
- const MAX_UTF16_CHARACTER = fromCharCode(65535);
1495
+ String.fromCodePoint;
1496
+ fromCharCode(65535);
1603
1497
  /**
1604
1498
  * @param {string} str
1605
1499
  * @return {Uint8Array<ArrayBuffer>}
@@ -1630,10 +1524,9 @@ let utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecode
1630
1524
  ignoreBOM: true
1631
1525
  });
1632
1526
  /* c8 ignore start */
1633
- if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1)
1527
+ if (utf8TextDecoder && utf8TextDecoder.decode(/* @__PURE__ */ new Uint8Array()).length === 1)
1634
1528
  /* c8 ignore next */
1635
1529
  utf8TextDecoder = null;
1636
-
1637
1530
  //#endregion
1638
1531
  //#region ../../node_modules/lib0/error.js
1639
1532
  /**
@@ -1647,16 +1540,42 @@ utf8TextDecoder = null;
1647
1540
  */
1648
1541
  /* c8 ignore next */
1649
1542
  const create$1 = (s) => new Error(s);
1650
-
1651
1543
  //#endregion
1652
1544
  //#region ../../node_modules/lib0/encoding.js
1653
1545
  /**
1546
+ * Efficient schema-less binary encoding with support for variable length encoding.
1547
+ *
1548
+ * Use [lib0/encoding] with [lib0/decoding]. Every encoding function has a corresponding decoding function.
1549
+ *
1550
+ * Encodes numbers in little-endian order (least to most significant byte order)
1551
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
1552
+ * which is also used in Protocol Buffers.
1553
+ *
1554
+ * ```js
1555
+ * // encoding step
1556
+ * const encoder = encoding.createEncoder()
1557
+ * encoding.writeVarUint(encoder, 256)
1558
+ * encoding.writeVarString(encoder, 'Hello world!')
1559
+ * const buf = encoding.toUint8Array(encoder)
1560
+ * ```
1561
+ *
1562
+ * ```js
1563
+ * // decoding step
1564
+ * const decoder = decoding.createDecoder(buf)
1565
+ * decoding.readVarUint(decoder) // => 256
1566
+ * decoding.readVarString(decoder) // => 'Hello world!'
1567
+ * decoding.hasContent(decoder) // => false - all data is read
1568
+ * ```
1569
+ *
1570
+ * @module encoding
1571
+ */
1572
+ /**
1654
1573
  * A BinaryEncoder handles the encoding to an Uint8Array.
1655
1574
  */
1656
1575
  var Encoder = class {
1657
1576
  constructor() {
1658
1577
  this.cpos = 0;
1659
- this.cbuf = new Uint8Array(100);
1578
+ this.cbuf = /* @__PURE__ */ new Uint8Array(100);
1660
1579
  /**
1661
1580
  * @type {Array<Uint8Array>}
1662
1581
  */
@@ -1722,16 +1641,16 @@ const write = (encoder, num) => {
1722
1641
  * @param {number} num The number that is to be encoded.
1723
1642
  */
1724
1643
  const writeVarUint = (encoder, num) => {
1725
- while (num > BITS7) {
1726
- write(encoder, BIT8 | BITS7 & num);
1644
+ while (num > 127) {
1645
+ write(encoder, 128 | 127 & num);
1727
1646
  num = floor(num / 128);
1728
1647
  }
1729
- write(encoder, BITS7 & num);
1648
+ write(encoder, 127 & num);
1730
1649
  };
1731
1650
  /**
1732
1651
  * A cache to store strings temporarily
1733
1652
  */
1734
- const _strBuffer = new Uint8Array(3e4);
1653
+ const _strBuffer = /* @__PURE__ */ new Uint8Array(3e4);
1735
1654
  const _maxStrBSize = _strBuffer.length / 3;
1736
1655
  /**
1737
1656
  * Write a variable length string.
@@ -1759,11 +1678,7 @@ const _writeVarStringPolyfill = (encoder, str) => {
1759
1678
  const encodedString = unescape(encodeURIComponent(str));
1760
1679
  const len = encodedString.length;
1761
1680
  writeVarUint(encoder, len);
1762
- for (let i = 0; i < len; i++) write(
1763
- encoder,
1764
- /** @type {number} */
1765
- encodedString.codePointAt(i)
1766
- );
1681
+ for (let i = 0; i < len; i++) write(encoder, encodedString.codePointAt(i));
1767
1682
  };
1768
1683
  /**
1769
1684
  * Write a variable length string.
@@ -1806,10 +1721,35 @@ const writeVarUint8Array = (encoder, uint8Array) => {
1806
1721
  writeVarUint(encoder, uint8Array.byteLength);
1807
1722
  writeUint8Array(encoder, uint8Array);
1808
1723
  };
1809
- const floatTestBed = new DataView(new ArrayBuffer(4));
1810
-
1811
1724
  //#endregion
1812
1725
  //#region ../../node_modules/lib0/decoding.js
1726
+ /**
1727
+ * Efficient schema-less binary decoding with support for variable length encoding.
1728
+ *
1729
+ * Use [lib0/decoding] with [lib0/encoding]. Every encoding function has a corresponding decoding function.
1730
+ *
1731
+ * Encodes numbers in little-endian order (least to most significant byte order)
1732
+ * and is compatible with Golang's binary encoding (https://golang.org/pkg/encoding/binary/)
1733
+ * which is also used in Protocol Buffers.
1734
+ *
1735
+ * ```js
1736
+ * // encoding step
1737
+ * const encoder = encoding.createEncoder()
1738
+ * encoding.writeVarUint(encoder, 256)
1739
+ * encoding.writeVarString(encoder, 'Hello world!')
1740
+ * const buf = encoding.toUint8Array(encoder)
1741
+ * ```
1742
+ *
1743
+ * ```js
1744
+ * // decoding step
1745
+ * const decoder = decoding.createDecoder(buf)
1746
+ * decoding.readVarUint(decoder) // => 256
1747
+ * decoding.readVarString(decoder) // => 'Hello world!'
1748
+ * decoding.hasContent(decoder) // => false - all data is read
1749
+ * ```
1750
+ *
1751
+ * @module decoding
1752
+ */
1813
1753
  const errorUnexpectedEndOfArray = create$1("Unexpected end of array");
1814
1754
  const errorIntegerOutOfRange = create$1("Integer out of Range");
1815
1755
  /**
@@ -1894,9 +1834,9 @@ const readVarUint = (decoder) => {
1894
1834
  const len = decoder.arr.length;
1895
1835
  while (decoder.pos < len) {
1896
1836
  const r = decoder.arr[decoder.pos++];
1897
- num = num + (r & BITS7) * mult;
1837
+ num = num + (r & 127) * mult;
1898
1838
  mult *= 128;
1899
- if (r < BIT8) return num;
1839
+ if (r < 128) return num;
1900
1840
  /* c8 ignore start */
1901
1841
  if (num > MAX_SAFE_INTEGER) throw errorIntegerOutOfRange;
1902
1842
  }
@@ -1926,11 +1866,7 @@ const _readVarStringPolyfill = (decoder) => {
1926
1866
  const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
1927
1867
  const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
1928
1868
  decoder.pos += nextLen;
1929
- encodedString += String.fromCodePoint.apply(
1930
- null,
1931
- /** @type {any} */
1932
- bytes
1933
- );
1869
+ encodedString += String.fromCodePoint.apply(null, bytes);
1934
1870
  remainingLen -= nextLen;
1935
1871
  }
1936
1872
  return decodeURIComponent(escape(encodedString));
@@ -1954,39 +1890,6 @@ const _readVarStringNative = (decoder) => utf8TextDecoder.decode(readVarUint8Arr
1954
1890
  */
1955
1891
  /* c8 ignore next */
1956
1892
  const readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
1957
-
1958
- //#endregion
1959
- //#region ../../node_modules/y-protocols/sync.js
1960
- /**
1961
- * @typedef {Map<number, number>} StateMap
1962
- */
1963
- /**
1964
- * Core Yjs defines two message types:
1965
- * • YjsSyncStep1: Includes the State Set of the sending client. When received, the client should reply with YjsSyncStep2.
1966
- * • YjsSyncStep2: Includes all missing structs and the complete delete set. When received, the client is assured that it
1967
- * received all information from the remote client.
1968
- *
1969
- * In a peer-to-peer network, you may want to introduce a SyncDone message type. Both parties should initiate the connection
1970
- * with SyncStep1. When a client received SyncStep2, it should reply with SyncDone. When the local client received both
1971
- * SyncStep2 and SyncDone, it is assured that it is synced to the remote client.
1972
- *
1973
- * In a client-server model, you want to handle this differently: The client should initiate the connection with SyncStep1.
1974
- * When the server receives SyncStep1, it should reply with SyncStep2 immediately followed by SyncStep1. The client replies
1975
- * with SyncStep2 when it receives SyncStep1. Optionally the server may send a SyncDone after it received SyncStep2, so the
1976
- * client knows that the sync is finished. There are two reasons for this more elaborated sync model: 1. This protocol can
1977
- * easily be implemented on top of http and websockets. 2. The server should only reply to requests, and not initiate them.
1978
- * Therefore it is necessary that the client initiates the sync.
1979
- *
1980
- * Construction of a message:
1981
- * [messageType : varUint, message definition..]
1982
- *
1983
- * Note: A message does not include information about the room name. This must to be handled by the upper layer protocol!
1984
- *
1985
- * stringify[messageType] stringifies a message definition (messageType is already read from the bufffer)
1986
- */
1987
- const messageYjsSyncStep1 = 0;
1988
- const messageYjsSyncStep2 = 1;
1989
- const messageYjsUpdate = 2;
1990
1893
  /**
1991
1894
  * Create a sync step 1 message based on the state of the current shared document.
1992
1895
  *
@@ -1994,7 +1897,7 @@ const messageYjsUpdate = 2;
1994
1897
  * @param {Y.Doc} doc
1995
1898
  */
1996
1899
  const writeSyncStep1 = (encoder, doc) => {
1997
- writeVarUint(encoder, messageYjsSyncStep1);
1900
+ writeVarUint(encoder, 0);
1998
1901
  const sv = Y.encodeStateVector(doc);
1999
1902
  writeVarUint8Array(encoder, sv);
2000
1903
  };
@@ -2004,7 +1907,7 @@ const writeSyncStep1 = (encoder, doc) => {
2004
1907
  * @param {Uint8Array} [encodedStateVector]
2005
1908
  */
2006
1909
  const writeSyncStep2 = (encoder, doc, encodedStateVector) => {
2007
- writeVarUint(encoder, messageYjsSyncStep2);
1910
+ writeVarUint(encoder, 1);
2008
1911
  writeVarUint8Array(encoder, Y.encodeStateAsUpdate(doc, encodedStateVector));
2009
1912
  };
2010
1913
  /**
@@ -2027,10 +1930,7 @@ const readSyncStep2 = (decoder, doc, transactionOrigin, errorHandler) => {
2027
1930
  try {
2028
1931
  Y.applyUpdate(doc, readVarUint8Array(decoder), transactionOrigin);
2029
1932
  } catch (error) {
2030
- if (errorHandler != null) errorHandler(
2031
- /** @type {Error} */
2032
- error
2033
- );
1933
+ if (errorHandler != null) errorHandler(error);
2034
1934
  console.error("Caught error while handling a Yjs update", error);
2035
1935
  }
2036
1936
  };
@@ -2039,7 +1939,7 @@ const readSyncStep2 = (decoder, doc, transactionOrigin, errorHandler) => {
2039
1939
  * @param {Uint8Array} update
2040
1940
  */
2041
1941
  const writeUpdate = (encoder, update) => {
2042
- writeVarUint(encoder, messageYjsUpdate);
1942
+ writeVarUint(encoder, 2);
2043
1943
  writeVarUint8Array(encoder, update);
2044
1944
  };
2045
1945
  /**
@@ -2061,20 +1961,19 @@ const readUpdate = readSyncStep2;
2061
1961
  const readSyncMessage = (decoder, encoder, doc, transactionOrigin, errorHandler) => {
2062
1962
  const messageType = readVarUint(decoder);
2063
1963
  switch (messageType) {
2064
- case messageYjsSyncStep1:
1964
+ case 0:
2065
1965
  readSyncStep1(decoder, encoder, doc);
2066
1966
  break;
2067
- case messageYjsSyncStep2:
1967
+ case 1:
2068
1968
  readSyncStep2(decoder, doc, transactionOrigin, errorHandler);
2069
1969
  break;
2070
- case messageYjsUpdate:
1970
+ case 2:
2071
1971
  readUpdate(decoder, doc, transactionOrigin, errorHandler);
2072
1972
  break;
2073
1973
  default: throw new Error("Unknown message type");
2074
1974
  }
2075
1975
  return messageType;
2076
1976
  };
2077
-
2078
1977
  //#endregion
2079
1978
  //#region ../../node_modules/lib0/time.js
2080
1979
  /**
@@ -2083,7 +1982,6 @@ const readSyncMessage = (decoder, encoder, doc, transactionOrigin, errorHandler)
2083
1982
  * @return {number}
2084
1983
  */
2085
1984
  const getUnixTime = Date.now;
2086
-
2087
1985
  //#endregion
2088
1986
  //#region ../../node_modules/lib0/map.js
2089
1987
  /**
@@ -2104,7 +2002,7 @@ const getUnixTime = Date.now;
2104
2002
  *
2105
2003
  * @function
2106
2004
  */
2107
- const create = () => new Map();
2005
+ const create = () => /* @__PURE__ */ new Map();
2108
2006
  /**
2109
2007
  * Get map property. Create T if property is undefined and set T on map.
2110
2008
  *
@@ -2126,9 +2024,13 @@ const setIfUndefined = (map, key, createT) => {
2126
2024
  if (set === void 0) map.set(key, set = createT());
2127
2025
  return set;
2128
2026
  };
2129
-
2130
2027
  //#endregion
2131
2028
  //#region ../../node_modules/lib0/observable.js
2029
+ /**
2030
+ * Observable class prototype.
2031
+ *
2032
+ * @module observable
2033
+ */
2132
2034
  /* c8 ignore start */
2133
2035
  /**
2134
2036
  * Handles named events.
@@ -2193,11 +2095,9 @@ var Observable = class {
2193
2095
  }
2194
2096
  };
2195
2097
  /* c8 ignore end */
2196
-
2197
2098
  //#endregion
2198
2099
  //#region ../../node_modules/lib0/trait/equality.js
2199
2100
  const EqualityTraitSymbol = Symbol("Equality");
2200
-
2201
2101
  //#endregion
2202
2102
  //#region ../../node_modules/lib0/object.js
2203
2103
  /**
@@ -2217,7 +2117,6 @@ const size = (obj) => keys(obj).length;
2217
2117
  * @return {boolean}
2218
2118
  */
2219
2119
  const hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
2220
-
2221
2120
  //#endregion
2222
2121
  //#region ../../node_modules/lib0/function.js
2223
2122
  /* c8 ignore start */
@@ -2234,21 +2133,18 @@ const equalityDeep = (a, b) => {
2234
2133
  case ArrayBuffer:
2235
2134
  a = new Uint8Array(a);
2236
2135
  b = new Uint8Array(b);
2237
- case Uint8Array: {
2136
+ case Uint8Array:
2238
2137
  if (a.byteLength !== b.byteLength) return false;
2239
2138
  for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
2240
2139
  break;
2241
- }
2242
- case Set: {
2140
+ case Set:
2243
2141
  if (a.size !== b.size) return false;
2244
2142
  for (const value of a) if (!b.has(value)) return false;
2245
2143
  break;
2246
- }
2247
- case Map: {
2144
+ case Map:
2248
2145
  if (a.size !== b.size) return false;
2249
2146
  for (const key of a.keys()) if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) return false;
2250
2147
  break;
2251
- }
2252
2148
  case void 0:
2253
2149
  case Object:
2254
2150
  if (size(a) !== size(b)) return false;
@@ -2262,11 +2158,11 @@ const equalityDeep = (a, b) => {
2262
2158
  }
2263
2159
  return true;
2264
2160
  };
2265
- /* c8 ignore stop */
2266
- const isArray = isArray$1;
2267
-
2268
2161
  //#endregion
2269
2162
  //#region ../../node_modules/y-protocols/awareness.js
2163
+ /**
2164
+ * @module awareness-protocol
2165
+ */
2270
2166
  const outdatedTimeout = 3e4;
2271
2167
  /**
2272
2168
  * @typedef {Object} MetaClientState
@@ -2306,20 +2202,20 @@ var Awareness = class extends Observable {
2306
2202
  * Maps from client id to client state
2307
2203
  * @type {Map<number, Object<string, any>>}
2308
2204
  */
2309
- this.states = new Map();
2205
+ this.states = /* @__PURE__ */ new Map();
2310
2206
  /**
2311
2207
  * @type {Map<number, MetaClientState>}
2312
2208
  */
2313
- this.meta = new Map();
2209
+ this.meta = /* @__PURE__ */ new Map();
2314
2210
  this._checkInterval = setInterval(() => {
2315
2211
  const now = getUnixTime();
2316
- if (this.getLocalState() !== null && outdatedTimeout / 2 <= now - this.meta.get(this.clientID).lastUpdated) this.setLocalState(this.getLocalState());
2212
+ if (this.getLocalState() !== null && 15e3 <= now - this.meta.get(this.clientID).lastUpdated) this.setLocalState(this.getLocalState());
2317
2213
  /**
2318
2214
  * @type {Array<number>}
2319
2215
  */
2320
2216
  const remove = [];
2321
2217
  this.meta.forEach((meta, clientid) => {
2322
- if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) remove.push(clientid);
2218
+ if (clientid !== this.clientID && 3e4 <= now - meta.lastUpdated && this.states.has(clientid)) remove.push(clientid);
2323
2219
  });
2324
2220
  if (remove.length > 0) removeAwarenessStates(this, remove, "timeout");
2325
2221
  }, floor(outdatedTimeout / 10));
@@ -2471,9 +2367,10 @@ const applyAwarenessUpdate = (awareness, update, origin) => {
2471
2367
  const prevState = awareness.states.get(clientID);
2472
2368
  const currClock = clientMeta === void 0 ? 0 : clientMeta.clock;
2473
2369
  if (currClock < clock || currClock === clock && state === null && awareness.states.has(clientID)) {
2474
- if (state === null) if (clientID === awareness.clientID && awareness.getLocalState() != null) clock++;
2475
- else awareness.states.delete(clientID);
2476
- else awareness.states.set(clientID, state);
2370
+ if (state === null) {
2371
+ if (clientID === awareness.clientID && awareness.getLocalState() != null) clock++;
2372
+ else awareness.states.delete(clientID);
2373
+ } else awareness.states.set(clientID, state);
2477
2374
  awareness.meta.set(clientID, {
2478
2375
  clock,
2479
2376
  lastUpdated: timestamp
@@ -2497,7 +2394,6 @@ const applyAwarenessUpdate = (awareness, update, origin) => {
2497
2394
  removed
2498
2395
  }, origin]);
2499
2396
  };
2500
-
2501
2397
  //#endregion
2502
2398
  //#region src/utils.ts
2503
2399
  function handleChunkedMessage(chunkedMessagesMap, messageData) {
@@ -2514,7 +2410,6 @@ function handleChunkedMessage(chunkedMessagesMap, messageData) {
2514
2410
  }
2515
2411
  return joined;
2516
2412
  }
2517
-
2518
2413
  //#endregion
2519
2414
  //#region src/constants.ts
2520
2415
  const WEAVE_STORE_AZURE_WEB_PUBSUB = "store-azure-web-pubsub";
@@ -2547,7 +2442,6 @@ const WEAVE_STORE_AZURE_WEB_PUBSUB_SYNC_HOST_DEFAULT_OPTIONS = {
2547
2442
  attemptsLimit: 12
2548
2443
  }
2549
2444
  };
2550
-
2551
2445
  //#endregion
2552
2446
  //#region src/server/azure-web-pubsub-host.ts
2553
2447
  const expirationTimeInMinutes = 60;
@@ -2556,10 +2450,24 @@ const messageAwareness = 1;
2556
2450
  const AzureWebPubSubJsonProtocol = "json.webpubsub.azure.v1";
2557
2451
  const HostUserId = "host";
2558
2452
  var WeaveStoreAzureWebPubSubSyncHost = class {
2453
+ server;
2454
+ syncHandler;
2455
+ doc;
2456
+ topic;
2457
+ topicAwarenessChannel;
2458
+ _client;
2459
+ _conn;
2559
2460
  _reconnectAttempts = 0;
2560
2461
  _forceClose = false;
2462
+ _awareness;
2463
+ _chunkedMessages;
2464
+ _syncHostOptions;
2465
+ _heartbeatIntervalId;
2466
+ _reconnectionTimeoutId;
2561
2467
  _resyncAttempt = 0;
2562
2468
  _resyncIntervalId = null;
2469
+ _updateHandler;
2470
+ _awarenessUpdateHandler;
2563
2471
  constructor(server, syncHandler, client, topic, doc, syncHostOptions) {
2564
2472
  this._syncHostOptions = mergeExceptArrays(WEAVE_STORE_AZURE_WEB_PUBSUB_SYNC_HOST_DEFAULT_OPTIONS, syncHostOptions ?? {});
2565
2473
  this.server = server;
@@ -2568,7 +2476,7 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2568
2476
  this.topic = topic;
2569
2477
  this.topicAwarenessChannel = `${topic}-awareness`;
2570
2478
  this._client = client;
2571
- this._chunkedMessages = new Map();
2479
+ this._chunkedMessages = /* @__PURE__ */ new Map();
2572
2480
  this._heartbeatIntervalId = null;
2573
2481
  this._reconnectionTimeoutId = null;
2574
2482
  this._conn = null;
@@ -2616,7 +2524,7 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2616
2524
  setupHeartbeat() {
2617
2525
  this._heartbeatIntervalId = setInterval(() => {
2618
2526
  this._conn?.send?.(JSON.stringify({
2619
- type: MessageType.SendToGroup,
2527
+ type: "sendToGroup",
2620
2528
  group: this.topic,
2621
2529
  noEcho: true,
2622
2530
  data: { type: "heartbeat" }
@@ -2638,7 +2546,7 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2638
2546
  connectionAttempt
2639
2547
  });
2640
2548
  ws.send(JSON.stringify({
2641
- type: MessageType.JoinGroup,
2549
+ type: "joinGroup",
2642
2550
  group: `${group}.host`
2643
2551
  }));
2644
2552
  this.server.emitEvent("onWsJoinGroup", {
@@ -2647,7 +2555,7 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2647
2555
  });
2648
2556
  const handleResync = () => {
2649
2557
  ws.send(JSON.stringify({
2650
- type: MessageType.SendToGroup,
2558
+ type: "sendToGroup",
2651
2559
  group,
2652
2560
  noEcho: true,
2653
2561
  data: { type: "resync" }
@@ -2674,15 +2582,15 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2674
2582
  const joinedMessagePayload = handleChunkedMessage(this._chunkedMessages, event.data);
2675
2583
  if (event.data.type === "chunk") return;
2676
2584
  switch (event.data.t) {
2677
- case MessageDataType.Init:
2585
+ case "init":
2678
2586
  this.onClientInit(group, event.data);
2679
2587
  this.onClientSync(group, event.data.f, joinedMessagePayload ?? event.data.c);
2680
2588
  this.sendInitAwarenessInfo(event.data.f);
2681
2589
  return;
2682
- case MessageDataType.Sync:
2590
+ case "sync":
2683
2591
  this.onClientSync(group, event.data.f, joinedMessagePayload ?? event.data.c);
2684
2592
  return;
2685
- case MessageDataType.Awareness:
2593
+ case "awareness":
2686
2594
  this.onAwareness(group, event.data.c);
2687
2595
  return;
2688
2596
  }
@@ -2750,27 +2658,24 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2750
2658
  }
2751
2659
  }
2752
2660
  simulateWebsocketError() {
2753
- if (this._conn) this._conn.emit("error", new Error("Simulated connection failure"));
2661
+ if (this._conn) this._conn.emit("error", /* @__PURE__ */ new Error("Simulated connection failure"));
2754
2662
  }
2755
2663
  safeSend(data) {
2756
- const MAX_BYTES = 512 * 1024;
2757
- const bytes = new TextEncoder().encode(data);
2758
- if (bytes.byteLength > MAX_BYTES) return false;
2664
+ if (new TextEncoder().encode(data).byteLength > 524288) return false;
2759
2665
  return true;
2760
2666
  }
2761
- chunkString(str, size$1) {
2667
+ chunkString(str, size) {
2762
2668
  const chunks = [];
2763
- for (let i = 0; i < str.length; i += size$1) chunks.push(str.slice(i, i + size$1));
2669
+ for (let i = 0; i < str.length; i += size) chunks.push(str.slice(i, i + size));
2764
2670
  return chunks;
2765
2671
  }
2766
- chunkedBroadcast(group, from$1, u8) {
2672
+ chunkedBroadcast(group, from, u8) {
2767
2673
  const base64Data = Buffer.from(u8).toString("base64");
2768
- const CHUNK_SIZE = 512 * 1024;
2769
- const chunks = this.chunkString(base64Data, CHUNK_SIZE);
2674
+ const chunks = this.chunkString(base64Data, 524288);
2770
2675
  const payloadId = crypto.randomUUID();
2771
2676
  for (let i = 0; i < chunks.length; i++) {
2772
- const payload$1 = JSON.stringify({
2773
- type: MessageType.SendToGroup,
2677
+ const payload = JSON.stringify({
2678
+ type: "sendToGroup",
2774
2679
  group,
2775
2680
  noEcho: true,
2776
2681
  data: {
@@ -2778,37 +2683,37 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2778
2683
  type: "chunk",
2779
2684
  index: i,
2780
2685
  totalChunks: chunks.length,
2781
- f: from$1,
2686
+ f: from,
2782
2687
  c: chunks[i]
2783
2688
  }
2784
2689
  });
2785
- this._conn?.send?.(payload$1);
2690
+ this._conn?.send?.(payload);
2786
2691
  }
2787
2692
  const payload = JSON.stringify({
2788
- type: MessageType.SendToGroup,
2693
+ type: "sendToGroup",
2789
2694
  group,
2790
2695
  noEcho: true,
2791
2696
  data: {
2792
2697
  payloadId,
2793
2698
  type: "end",
2794
- f: from$1
2699
+ f: from
2795
2700
  }
2796
2701
  });
2797
2702
  this._conn?.send?.(payload);
2798
2703
  }
2799
- broadcast(group, from$1, u8) {
2704
+ broadcast(group, from, u8) {
2800
2705
  try {
2801
2706
  const payload = JSON.stringify({
2802
- type: MessageType.SendToGroup,
2707
+ type: "sendToGroup",
2803
2708
  group,
2804
2709
  noEcho: true,
2805
2710
  data: {
2806
- f: from$1,
2711
+ f: from,
2807
2712
  c: Buffer.from(u8).toString("base64")
2808
2713
  }
2809
2714
  });
2810
2715
  if (!this.safeSend(payload)) {
2811
- this.chunkedBroadcast(group, from$1, u8);
2716
+ this.chunkedBroadcast(group, from, u8);
2812
2717
  return;
2813
2718
  }
2814
2719
  this._conn?.send?.(payload);
@@ -2818,12 +2723,11 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2818
2723
  }
2819
2724
  chunkedSend(group, to, u8) {
2820
2725
  const base64Data = Buffer.from(u8).toString("base64");
2821
- const CHUNK_SIZE = 512 * 1024;
2822
- const chunks = this.chunkString(base64Data, CHUNK_SIZE);
2726
+ const chunks = this.chunkString(base64Data, 524288);
2823
2727
  const payloadId = crypto.randomUUID();
2824
2728
  for (let i = 0; i < chunks.length; i++) {
2825
- const payload$1 = JSON.stringify({
2826
- type: MessageType.SendToGroup,
2729
+ const payload = JSON.stringify({
2730
+ type: "sendToGroup",
2827
2731
  group,
2828
2732
  noEcho: true,
2829
2733
  data: {
@@ -2835,10 +2739,10 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2835
2739
  c: chunks[i]
2836
2740
  }
2837
2741
  });
2838
- this._conn?.send?.(payload$1);
2742
+ this._conn?.send?.(payload);
2839
2743
  }
2840
2744
  const payload = JSON.stringify({
2841
- type: MessageType.SendToGroup,
2745
+ type: "sendToGroup",
2842
2746
  group,
2843
2747
  noEcho: true,
2844
2748
  data: {
@@ -2852,7 +2756,7 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2852
2756
  send(group, to, u8) {
2853
2757
  try {
2854
2758
  const payload = JSON.stringify({
2855
- type: MessageType.SendToGroup,
2759
+ type: "sendToGroup",
2856
2760
  group,
2857
2761
  noEcho: true,
2858
2762
  data: {
@@ -2872,24 +2776,22 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2872
2776
  async onClientInit(group, data) {
2873
2777
  if (!this.doc) return;
2874
2778
  const encoder = createEncoder();
2875
- writeVarUint(encoder, messageYjsSyncStep1);
2779
+ writeVarUint(encoder, 0);
2876
2780
  writeSyncStep1(encoder, this.doc);
2877
2781
  const u8 = toUint8Array(encoder);
2878
2782
  this.send(group, data.f, u8);
2879
2783
  }
2880
- onClientSync(group, from$1, data) {
2784
+ onClientSync(group, from, data) {
2881
2785
  try {
2882
2786
  if (!this.doc) return;
2883
2787
  const buf = Buffer.from(data, "base64");
2884
2788
  const encoder = createEncoder();
2885
2789
  const decoder = createDecoder(buf);
2886
- const messageType = readVarUint(decoder);
2887
- switch (messageType) {
2888
- case messageYjsSyncStep1:
2889
- writeVarUint(encoder, messageYjsSyncStep1);
2890
- readSyncMessage(decoder, encoder, this.doc, from$1);
2891
- if (length(encoder) > 1) this.send(group, from$1, toUint8Array(encoder));
2892
- break;
2790
+ switch (readVarUint(decoder)) {
2791
+ case 0:
2792
+ writeVarUint(encoder, 0);
2793
+ readSyncMessage(decoder, encoder, this.doc, from);
2794
+ if (length(encoder) > 1) this.send(group, from, toUint8Array(encoder));
2893
2795
  }
2894
2796
  } catch (err) {
2895
2797
  this.doc.emit("error", [err]);
@@ -2913,36 +2815,37 @@ var WeaveStoreAzureWebPubSubSyncHost = class {
2913
2815
  `webpubsub.joinLeaveGroup.${group}`,
2914
2816
  `webpubsub.joinLeaveGroup.${group}.host`
2915
2817
  ];
2916
- const res = await this._client.getClientAccessToken({
2818
+ return await this._client.getClientAccessToken({
2917
2819
  expirationTimeInMinutes,
2918
2820
  userId: HostUserId,
2919
2821
  roles
2920
2822
  });
2921
- return res;
2922
2823
  }
2923
2824
  };
2924
-
2925
2825
  //#endregion
2926
2826
  //#region src/server/utils.ts
2927
2827
  function getStateAsJson(actualState) {
2928
2828
  const document = new yjs_default.Doc();
2929
2829
  yjs_default.applyUpdate(document, actualState);
2930
2830
  const actualStateString = JSON.stringify(document.getMap("weave").toJSON());
2931
- const actualStateJson = JSON.parse(actualStateString);
2932
- return actualStateJson;
2831
+ return JSON.parse(actualStateString);
2933
2832
  }
2934
2833
  function hashJson(obj) {
2935
2834
  const jsonString = JSON.stringify(obj);
2936
2835
  return crypto.createHash("sha256").update(jsonString).digest("hex");
2937
2836
  }
2938
-
2939
2837
  //#endregion
2940
2838
  //#region src/server/azure-web-pubsub-sync-handler.ts
2941
2839
  var WeaveAzureWebPubsubSyncHandler = class extends WebPubSubEventHandler {
2942
- _rooms = new Map();
2943
- _roomsSyncHost = new Map();
2944
- _store_persistence = new Map();
2945
- roomsLastState = new Map();
2840
+ _client;
2841
+ _rooms = /* @__PURE__ */ new Map();
2842
+ _roomsSyncHost = /* @__PURE__ */ new Map();
2843
+ _store_persistence = /* @__PURE__ */ new Map();
2844
+ syncHostOptions;
2845
+ syncOptions;
2846
+ initialState;
2847
+ server;
2848
+ roomsLastState = /* @__PURE__ */ new Map();
2946
2849
  constructor(hub, server, client, initialState, syncHandlerOptions, eventHandlerOptions, syncHostOptions) {
2947
2850
  super(hub, {
2948
2851
  ...eventHandlerOptions,
@@ -2980,8 +2883,7 @@ var WeaveAzureWebPubsubSyncHandler = class extends WebPubSubEventHandler {
2980
2883
  if (documentData) yjs_default.applyUpdate(doc, documentData);
2981
2884
  else this.initialState(doc);
2982
2885
  this._roomsSyncHost.set(roomId, new WeaveStoreAzureWebPubSubSyncHost(this.server, this, this._client, roomId, doc, this.syncHostOptions));
2983
- const connection = this._roomsSyncHost.get(roomId);
2984
- await connection.start();
2886
+ await this._roomsSyncHost.get(roomId).start();
2985
2887
  if (this.isPersistingOnInterval()) this.setupRoomInstancePersistence(roomId);
2986
2888
  this._rooms.set(roomId, doc);
2987
2889
  }
@@ -3004,12 +2906,7 @@ var WeaveAzureWebPubsubSyncHandler = class extends WebPubSubEventHandler {
3004
2906
  if (!this.isPersistingOnInterval()) {
3005
2907
  const savedRoomData = this.roomsLastState.get(roomId);
3006
2908
  if (savedRoomData) {
3007
- const savedStateJson = getStateAsJson(savedRoomData);
3008
- const savedHash = hashJson(savedStateJson);
3009
- const actualStateJson = getStateAsJson(actualState);
3010
- const actualHash = hashJson(actualStateJson);
3011
- const same = savedHash === actualHash;
3012
- if (same) return;
2909
+ if (hashJson(getStateAsJson(savedRoomData)) === hashJson(getStateAsJson(actualState))) return;
3013
2910
  this.roomsLastState.set(roomId, actualState);
3014
2911
  }
3015
2912
  }
@@ -3056,17 +2953,14 @@ var WeaveAzureWebPubsubSyncHandler = class extends WebPubSubEventHandler {
3056
2953
  }
3057
2954
  async clientConnect(roomId, connectionOptions) {
3058
2955
  await this.getHostConnection(roomId);
3059
- const token = await this._client.getClientAccessToken({
2956
+ return `${(await this._client.getClientAccessToken({
3060
2957
  groups: [roomId],
3061
2958
  roles: [`webpubsub.joinLeaveGroup.${roomId}`, `webpubsub.sendToGroup.${roomId}.host`],
3062
2959
  ...connectionOptions
3063
- });
3064
- const finalURL = `${token.url}&group=${roomId}`;
3065
- return finalURL;
2960
+ })).url}&group=${roomId}`;
3066
2961
  }
3067
2962
  async clientDisconnect(roomId) {
3068
- const roomSyncHost = this._roomsSyncHost.get(roomId);
3069
- if (roomSyncHost) await this.destroyRoomInstance(roomId);
2963
+ if (this._roomsSyncHost.get(roomId)) await this.destroyRoomInstance(roomId);
3070
2964
  }
3071
2965
  async clientTransportConnect(roomId) {
3072
2966
  const roomSyncHost = this._roomsSyncHost.get(roomId);
@@ -3077,10 +2971,11 @@ var WeaveAzureWebPubsubSyncHandler = class extends WebPubSubEventHandler {
3077
2971
  if (roomSyncHost) roomSyncHost.stop();
3078
2972
  }
3079
2973
  };
3080
-
3081
2974
  //#endregion
3082
2975
  //#region src/server/azure-web-pubsub-server.ts
3083
2976
  var WeaveAzureWebPubsubServer = class extends Emittery {
2977
+ syncClient;
2978
+ syncHandler;
3084
2979
  persistRoom = void 0;
3085
2980
  fetchRoom = void 0;
3086
2981
  constructor({ pubSubConfig, eventsHandlerConfig, initialState = defaultInitialState, persistRoom, fetchRoom, syncHostConfig }) {
@@ -3134,6 +3029,5 @@ var WeaveAzureWebPubsubServer = class extends Emittery {
3134
3029
  this.syncHandler.clientTransportDisconnect(roomId);
3135
3030
  }
3136
3031
  };
3137
-
3138
3032
  //#endregion
3139
- export { MessageDataType, MessageType, MqttDisconnectReasonCode, MqttV311ConnectReturnCode, MqttV500ConnectReasonCode, WEAVE_STORE_AZURE_WEB_PUBSUB, WEAVE_STORE_AZURE_WEB_PUBSUB_CONNECTION_STATUS, WEAVE_STORE_AZURE_WEB_PUBSUB_DESTROY_ROOM_STATUS, WEAVE_STORE_AZURE_WEB_PUBSUB_SYNC_CLIENT_DEFAULT_OPTIONS, WEAVE_STORE_AZURE_WEB_PUBSUB_SYNC_HOST_DEFAULT_OPTIONS, WEAVE_STORE_HORIZONTAL_SYNC_HANDLER_CLIENT_TYPE, WeaveAzureWebPubsubServer, WeaveStoreAzureWebPubSubSyncHost, WebPubSubEventHandler };
3033
+ export { MessageDataType, MessageType, MqttDisconnectReasonCode, MqttV311ConnectReturnCode, MqttV500ConnectReasonCode, WEAVE_STORE_AZURE_WEB_PUBSUB, WEAVE_STORE_AZURE_WEB_PUBSUB_CONNECTION_STATUS, WEAVE_STORE_AZURE_WEB_PUBSUB_DESTROY_ROOM_STATUS, WEAVE_STORE_AZURE_WEB_PUBSUB_SYNC_CLIENT_DEFAULT_OPTIONS, WEAVE_STORE_AZURE_WEB_PUBSUB_SYNC_HOST_DEFAULT_OPTIONS, WEAVE_STORE_HORIZONTAL_SYNC_HANDLER_CLIENT_TYPE, WeaveAzureWebPubsubServer, WeaveStoreAzureWebPubSubSyncHost, WebPubSubEventHandler };