@hocuspocus/provider 3.0.8-rc.0 → 3.1.0-rc.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.
@@ -88,37 +88,6 @@ const create$2 = () => new Set();
88
88
  */
89
89
  const from = Array.from;
90
90
 
91
- /**
92
- * Utility module to work with strings.
93
- *
94
- * @module string
95
- */
96
-
97
- const fromCharCode = String.fromCharCode;
98
-
99
- /**
100
- * @param {string} s
101
- * @return {string}
102
- */
103
- const toLowerCase = s => s.toLowerCase();
104
-
105
- const trimLeftRegex = /^\s*/g;
106
-
107
- /**
108
- * @param {string} s
109
- * @return {string}
110
- */
111
- const trimLeft = s => s.replace(trimLeftRegex, '');
112
-
113
- const fromCamelCaseRegex = /([A-Z])/g;
114
-
115
- /**
116
- * @param {string} s
117
- * @param {string} separator
118
- * @return {string}
119
- */
120
- const fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, match => `${separator}${toLowerCase(match)}`));
121
-
122
91
  /**
123
92
  * @param {string} str
124
93
  * @return {Uint8Array}
@@ -770,22 +739,6 @@ class Observable {
770
739
  */
771
740
  const keys = Object.keys;
772
741
 
773
- /**
774
- * @todo implement mapToArray & map
775
- *
776
- * @template R
777
- * @param {Object<string,any>} obj
778
- * @param {function(any,string):R} f
779
- * @return {Array<R>}
780
- */
781
- const map = (obj, f) => {
782
- const results = [];
783
- for (const key in obj) {
784
- results.push(f(obj[key], key));
785
- }
786
- return results
787
- };
788
-
789
742
  /**
790
743
  * @deprecated use object.size instead
791
744
  * @param {Object<string,any>} obj
@@ -899,16 +852,6 @@ const equalityDeep = (a, b) => {
899
852
  return true
900
853
  };
901
854
 
902
- /**
903
- * @template V
904
- * @template {V} OPTS
905
- *
906
- * @param {V} value
907
- * @param {Array<OPTS>} options
908
- */
909
- // @ts-ignore
910
- const isOneOf = (value, options) => options.includes(value);
911
-
912
855
  /**
913
856
  * @module awareness-protocol
914
857
  */
@@ -1209,37 +1152,6 @@ class EventEmitter {
1209
1152
  }
1210
1153
  }
1211
1154
 
1212
- /**
1213
- * Utility module to work with urls.
1214
- *
1215
- * @module url
1216
- */
1217
-
1218
-
1219
- /**
1220
- * @param {Object<string,string>} params
1221
- * @return {string}
1222
- */
1223
- const encodeQueryParams = params =>
1224
- map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&');
1225
-
1226
- exports.MessageType = void 0;
1227
- (function (MessageType) {
1228
- MessageType[MessageType["Sync"] = 0] = "Sync";
1229
- MessageType[MessageType["Awareness"] = 1] = "Awareness";
1230
- MessageType[MessageType["Auth"] = 2] = "Auth";
1231
- MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness";
1232
- MessageType[MessageType["Stateless"] = 5] = "Stateless";
1233
- MessageType[MessageType["CLOSE"] = 7] = "CLOSE";
1234
- MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus";
1235
- })(exports.MessageType || (exports.MessageType = {}));
1236
- exports.WebSocketStatus = void 0;
1237
- (function (WebSocketStatus) {
1238
- WebSocketStatus["Connecting"] = "connecting";
1239
- WebSocketStatus["Connected"] = "connected";
1240
- WebSocketStatus["Disconnected"] = "disconnected";
1241
- })(exports.WebSocketStatus || (exports.WebSocketStatus = {}));
1242
-
1243
1155
  class IncomingMessage {
1244
1156
  constructor(data) {
1245
1157
  this.data = data;
@@ -1272,6 +1184,23 @@ class IncomingMessage {
1272
1184
  }
1273
1185
  }
1274
1186
 
1187
+ exports.MessageType = void 0;
1188
+ (function (MessageType) {
1189
+ MessageType[MessageType["Sync"] = 0] = "Sync";
1190
+ MessageType[MessageType["Awareness"] = 1] = "Awareness";
1191
+ MessageType[MessageType["Auth"] = 2] = "Auth";
1192
+ MessageType[MessageType["QueryAwareness"] = 3] = "QueryAwareness";
1193
+ MessageType[MessageType["Stateless"] = 5] = "Stateless";
1194
+ MessageType[MessageType["CLOSE"] = 7] = "CLOSE";
1195
+ MessageType[MessageType["SyncStatus"] = 8] = "SyncStatus";
1196
+ })(exports.MessageType || (exports.MessageType = {}));
1197
+ exports.WebSocketStatus = void 0;
1198
+ (function (WebSocketStatus) {
1199
+ WebSocketStatus["Connecting"] = "connecting";
1200
+ WebSocketStatus["Connected"] = "connected";
1201
+ WebSocketStatus["Disconnected"] = "disconnected";
1202
+ })(exports.WebSocketStatus || (exports.WebSocketStatus = {}));
1203
+
1275
1204
  class OutgoingMessage {
1276
1205
  constructor() {
1277
1206
  this.encoder = createEncoder();
@@ -1302,14 +1231,10 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1302
1231
  super();
1303
1232
  this.messageQueue = [];
1304
1233
  this.configuration = {
1305
- url: '',
1234
+ url: "",
1306
1235
  // @ts-ignore
1307
1236
  document: undefined,
1308
1237
  WebSocketPolyfill: undefined,
1309
- parameters: {},
1310
- connect: true,
1311
- broadcast: true,
1312
- forceSyncInterval: false,
1313
1238
  // TODO: this should depend on awareness.outdatedTime
1314
1239
  messageReconnectTimeout: 30000,
1315
1240
  // 1 second
@@ -1356,23 +1281,20 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1356
1281
  this.configuration.WebSocketPolyfill = configuration.WebSocketPolyfill
1357
1282
  ? configuration.WebSocketPolyfill
1358
1283
  : WebSocket;
1359
- this.on('open', this.configuration.onOpen);
1360
- this.on('open', this.onOpen.bind(this));
1361
- this.on('connect', this.configuration.onConnect);
1362
- this.on('message', this.configuration.onMessage);
1363
- this.on('outgoingMessage', this.configuration.onOutgoingMessage);
1364
- this.on('status', this.configuration.onStatus);
1365
- this.on('disconnect', this.configuration.onDisconnect);
1366
- this.on('close', this.configuration.onClose);
1367
- this.on('destroy', this.configuration.onDestroy);
1368
- this.on('awarenessUpdate', this.configuration.onAwarenessUpdate);
1369
- this.on('awarenessChange', this.configuration.onAwarenessChange);
1370
- this.on('close', this.onClose.bind(this));
1371
- this.on('message', this.onMessage.bind(this));
1284
+ this.on("open", this.configuration.onOpen);
1285
+ this.on("open", this.onOpen.bind(this));
1286
+ this.on("connect", this.configuration.onConnect);
1287
+ this.on("message", this.configuration.onMessage);
1288
+ this.on("outgoingMessage", this.configuration.onOutgoingMessage);
1289
+ this.on("status", this.configuration.onStatus);
1290
+ this.on("disconnect", this.configuration.onDisconnect);
1291
+ this.on("close", this.configuration.onClose);
1292
+ this.on("destroy", this.configuration.onDestroy);
1293
+ this.on("awarenessUpdate", this.configuration.onAwarenessUpdate);
1294
+ this.on("awarenessChange", this.configuration.onAwarenessChange);
1295
+ this.on("close", this.onClose.bind(this));
1296
+ this.on("message", this.onMessage.bind(this));
1372
1297
  this.intervals.connectionChecker = setInterval(this.checkConnection.bind(this), this.configuration.messageReconnectTimeout / 10);
1373
- if (typeof configuration.connect !== 'undefined') {
1374
- this.shouldConnect = configuration.connect;
1375
- }
1376
1298
  if (!this.shouldConnect) {
1377
1299
  return;
1378
1300
  }
@@ -1387,13 +1309,16 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1387
1309
  if (this.status === exports.WebSocketStatus.Disconnected && this.shouldConnect) {
1388
1310
  this.connect();
1389
1311
  }
1390
- if (this.receivedOnOpenPayload && this.status === exports.WebSocketStatus.Connected) {
1312
+ if (this.receivedOnOpenPayload &&
1313
+ this.status === exports.WebSocketStatus.Connected) {
1391
1314
  provider.onOpen(this.receivedOnOpenPayload);
1392
1315
  }
1393
1316
  }
1394
1317
  detach(provider) {
1395
1318
  if (this.configuration.providerMap.has(provider.configuration.name)) {
1396
- provider.send(CloseMessage, { documentName: provider.configuration.name });
1319
+ provider.send(CloseMessage, {
1320
+ documentName: provider.configuration.name,
1321
+ });
1397
1322
  this.configuration.providerMap.delete(provider.configuration.name);
1398
1323
  }
1399
1324
  }
@@ -1422,7 +1347,7 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1422
1347
  maxDelay: this.configuration.maxDelay,
1423
1348
  jitter: this.configuration.jitter,
1424
1349
  timeout: this.configuration.timeout,
1425
- beforeAttempt: context => {
1350
+ beforeAttempt: (context) => {
1426
1351
  if (!this.shouldConnect || cancelAttempt) {
1427
1352
  context.abort();
1428
1353
  }
@@ -1430,7 +1355,7 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1430
1355
  }).catch((error) => {
1431
1356
  // If we aborted the connection attempt then don’t throw an error
1432
1357
  // ref: https://github.com/lifeomic/attempt/blob/master/src/index.ts#L136
1433
- if (error && error.code !== 'ATTEMPT_ABORTED') {
1358
+ if (error && error.code !== "ATTEMPT_ABORTED") {
1434
1359
  throw error;
1435
1360
  }
1436
1361
  });
@@ -1448,9 +1373,9 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1448
1373
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
1449
1374
  attachWebSocketListeners(ws, reject) {
1450
1375
  const { identifier } = ws;
1451
- const onMessageHandler = (payload) => this.emit('message', payload);
1452
- const onCloseHandler = (payload) => this.emit('close', { event: payload });
1453
- const onOpenHandler = (payload) => this.emit('open', payload);
1376
+ const onMessageHandler = (payload) => this.emit("message", payload);
1377
+ const onCloseHandler = (payload) => this.emit("close", { event: payload });
1378
+ const onOpenHandler = (payload) => this.emit("open", payload);
1454
1379
  const onErrorHandler = (err) => {
1455
1380
  reject(err);
1456
1381
  };
@@ -1461,7 +1386,7 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1461
1386
  error: onErrorHandler,
1462
1387
  };
1463
1388
  const handlers = this.webSocketHandlers[ws.identifier];
1464
- Object.keys(handlers).forEach(name => {
1389
+ Object.keys(handlers).forEach((name) => {
1465
1390
  ws.addEventListener(name, handlers[name]);
1466
1391
  });
1467
1392
  }
@@ -1471,7 +1396,7 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1471
1396
  }
1472
1397
  const { identifier } = this.webSocket;
1473
1398
  const handlers = this.webSocketHandlers[identifier];
1474
- Object.keys(handlers).forEach(name => {
1399
+ Object.keys(handlers).forEach((name) => {
1475
1400
  var _a;
1476
1401
  (_a = this.webSocket) === null || _a === void 0 ? void 0 : _a.removeEventListener(name, handlers[name]);
1477
1402
  delete this.webSocketHandlers[identifier];
@@ -1489,13 +1414,13 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1489
1414
  this.identifier += 1;
1490
1415
  // Init the WebSocket connection
1491
1416
  const ws = new this.configuration.WebSocketPolyfill(this.url);
1492
- ws.binaryType = 'arraybuffer';
1417
+ ws.binaryType = "arraybuffer";
1493
1418
  ws.identifier = this.identifier;
1494
1419
  this.attachWebSocketListeners(ws, reject);
1495
1420
  this.webSocket = ws;
1496
1421
  // Reset the status
1497
1422
  this.status = exports.WebSocketStatus.Connecting;
1498
- this.emit('status', { status: exports.WebSocketStatus.Connecting });
1423
+ this.emit("status", { status: exports.WebSocketStatus.Connecting });
1499
1424
  // Store resolve/reject for later use
1500
1425
  this.connectionAttempt = {
1501
1426
  resolve,
@@ -1516,9 +1441,9 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1516
1441
  this.connectionAttempt.resolve();
1517
1442
  this.connectionAttempt = null;
1518
1443
  this.status = exports.WebSocketStatus.Connected;
1519
- this.emit('status', { status: exports.WebSocketStatus.Connected });
1520
- this.emit('connect');
1521
- this.messageQueue.forEach(message => this.send(message));
1444
+ this.emit("status", { status: exports.WebSocketStatus.Connected });
1445
+ this.emit("connect");
1446
+ this.messageQueue.forEach((message) => this.send(message));
1522
1447
  this.messageQueue = [];
1523
1448
  }
1524
1449
  }
@@ -1541,8 +1466,8 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1541
1466
  return;
1542
1467
  }
1543
1468
  // Don’t close the connection when a message was received recently
1544
- if (this.configuration.messageReconnectTimeout
1545
- >= getUnixTime() - this.lastMessageReceived) {
1469
+ if (this.configuration.messageReconnectTimeout >=
1470
+ getUnixTime() - this.lastMessageReceived) {
1546
1471
  return;
1547
1472
  }
1548
1473
  // No message received in a long time, not even your own
@@ -1554,7 +1479,7 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1554
1479
  this.onClose({
1555
1480
  event: {
1556
1481
  code: 4408,
1557
- reason: 'forced',
1482
+ reason: "forced",
1558
1483
  },
1559
1484
  });
1560
1485
  this.closeTries = 0;
@@ -1566,14 +1491,13 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1566
1491
  }
1567
1492
  // Ensure that the URL never ends with /
1568
1493
  get serverUrl() {
1569
- while (this.configuration.url[this.configuration.url.length - 1] === '/') {
1494
+ while (this.configuration.url[this.configuration.url.length - 1] === "/") {
1570
1495
  return this.configuration.url.slice(0, this.configuration.url.length - 1);
1571
1496
  }
1572
1497
  return this.configuration.url;
1573
1498
  }
1574
1499
  get url() {
1575
- const encodedParams = encodeQueryParams(this.configuration.parameters);
1576
- return `${this.serverUrl}${encodedParams.length === 0 ? '' : `?${encodedParams}`}`;
1500
+ return this.serverUrl;
1577
1501
  }
1578
1502
  disconnect() {
1579
1503
  this.shouldConnect = false;
@@ -1606,8 +1530,8 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1606
1530
  }
1607
1531
  // Let’s update the connection status.
1608
1532
  this.status = exports.WebSocketStatus.Disconnected;
1609
- this.emit('status', { status: exports.WebSocketStatus.Disconnected });
1610
- this.emit('disconnect', { event });
1533
+ this.emit("status", { status: exports.WebSocketStatus.Disconnected });
1534
+ this.emit("disconnect", { event });
1611
1535
  // trigger connect if no retry is running and we want to have a connection
1612
1536
  if (!this.cancelWebsocketRetry && this.shouldConnect) {
1613
1537
  setTimeout(() => {
@@ -1616,7 +1540,7 @@ class HocuspocusProviderWebsocket extends EventEmitter {
1616
1540
  }
1617
1541
  }
1618
1542
  destroy() {
1619
- this.emit('destroy');
1543
+ this.emit("destroy");
1620
1544
  clearInterval(this.intervals.connectionChecker);
1621
1545
  // If there is still a connection attempt outstanding then we should stop
1622
1546
  // it before calling disconnect, otherwise it will be rejected in the onClose
@@ -1839,366 +1763,6 @@ class MessageReceiver {
1839
1763
  }
1840
1764
  }
1841
1765
 
1842
- /**
1843
- * Often used conditions.
1844
- *
1845
- * @module conditions
1846
- */
1847
-
1848
- /**
1849
- * @template T
1850
- * @param {T|null|undefined} v
1851
- * @return {T|null}
1852
- */
1853
- /* c8 ignore next */
1854
- const undefinedToNull = v => v === undefined ? null : v;
1855
-
1856
- /* eslint-env browser */
1857
-
1858
- /**
1859
- * Isomorphic variable storage.
1860
- *
1861
- * Uses LocalStorage in the browser and falls back to in-memory storage.
1862
- *
1863
- * @module storage
1864
- */
1865
-
1866
- /* c8 ignore start */
1867
- class VarStoragePolyfill {
1868
- constructor () {
1869
- this.map = new Map();
1870
- }
1871
-
1872
- /**
1873
- * @param {string} key
1874
- * @param {any} newValue
1875
- */
1876
- setItem (key, newValue) {
1877
- this.map.set(key, newValue);
1878
- }
1879
-
1880
- /**
1881
- * @param {string} key
1882
- */
1883
- getItem (key) {
1884
- return this.map.get(key)
1885
- }
1886
- }
1887
- /* c8 ignore stop */
1888
-
1889
- /**
1890
- * @type {any}
1891
- */
1892
- let _localStorage = new VarStoragePolyfill();
1893
- let usePolyfill = true;
1894
-
1895
- /* c8 ignore start */
1896
- try {
1897
- // if the same-origin rule is violated, accessing localStorage might thrown an error
1898
- if (typeof localStorage !== 'undefined' && localStorage) {
1899
- _localStorage = localStorage;
1900
- usePolyfill = false;
1901
- }
1902
- } catch (e) { }
1903
- /* c8 ignore stop */
1904
-
1905
- /**
1906
- * This is basically localStorage in browser, or a polyfill in nodejs
1907
- */
1908
- /* c8 ignore next */
1909
- const varStorage = _localStorage;
1910
-
1911
- /**
1912
- * A polyfill for `addEventListener('storage', event => {..})` that does nothing if the polyfill is being used.
1913
- *
1914
- * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler
1915
- * @function
1916
- */
1917
- /* c8 ignore next */
1918
- const onChange = eventHandler => usePolyfill || addEventListener('storage', /** @type {any} */ (eventHandler));
1919
-
1920
- /**
1921
- * A polyfill for `removeEventListener('storage', event => {..})` that does nothing if the polyfill is being used.
1922
- *
1923
- * @param {function({ key: string, newValue: string, oldValue: string }): void} eventHandler
1924
- * @function
1925
- */
1926
- /* c8 ignore next */
1927
- const offChange = eventHandler => usePolyfill || removeEventListener('storage', /** @type {any} */ (eventHandler));
1928
-
1929
- /**
1930
- * Isomorphic module to work access the environment (query params, env variables).
1931
- *
1932
- * @module environment
1933
- */
1934
-
1935
-
1936
- /* c8 ignore next 2 */
1937
- // @ts-ignore
1938
- const isNode = typeof process !== 'undefined' && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
1939
-
1940
- /* c8 ignore next */
1941
- const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && !isNode;
1942
-
1943
- /**
1944
- * @type {Map<string,string>}
1945
- */
1946
- let params;
1947
-
1948
- /* c8 ignore start */
1949
- const computeParams = () => {
1950
- if (params === undefined) {
1951
- if (isNode) {
1952
- params = create();
1953
- const pargs = process.argv;
1954
- let currParamName = null;
1955
- for (let i = 0; i < pargs.length; i++) {
1956
- const parg = pargs[i];
1957
- if (parg[0] === '-') {
1958
- if (currParamName !== null) {
1959
- params.set(currParamName, '');
1960
- }
1961
- currParamName = parg;
1962
- } else {
1963
- if (currParamName !== null) {
1964
- params.set(currParamName, parg);
1965
- currParamName = null;
1966
- }
1967
- }
1968
- }
1969
- if (currParamName !== null) {
1970
- params.set(currParamName, '');
1971
- }
1972
- // in ReactNative for example this would not be true (unless connected to the Remote Debugger)
1973
- } else if (typeof location === 'object') {
1974
- params = create(); // eslint-disable-next-line no-undef
1975
- (location.search || '?').slice(1).split('&').forEach((kv) => {
1976
- if (kv.length !== 0) {
1977
- const [key, value] = kv.split('=');
1978
- params.set(`--${fromCamelCase(key, '-')}`, value);
1979
- params.set(`-${fromCamelCase(key, '-')}`, value);
1980
- }
1981
- });
1982
- } else {
1983
- params = create();
1984
- }
1985
- }
1986
- return params
1987
- };
1988
- /* c8 ignore stop */
1989
-
1990
- /**
1991
- * @param {string} name
1992
- * @return {boolean}
1993
- */
1994
- /* c8 ignore next */
1995
- const hasParam = (name) => computeParams().has(name);
1996
-
1997
- /**
1998
- * @param {string} name
1999
- * @return {string|null}
2000
- */
2001
- /* c8 ignore next 4 */
2002
- const getVariable = (name) =>
2003
- isNode
2004
- ? undefinedToNull(process.env[name.toUpperCase().replaceAll('-', '_')])
2005
- : undefinedToNull(varStorage.getItem(name));
2006
-
2007
- /**
2008
- * @param {string} name
2009
- * @return {boolean}
2010
- */
2011
- /* c8 ignore next 2 */
2012
- const hasConf = (name) =>
2013
- hasParam('--' + name) || getVariable(name) !== null;
2014
-
2015
- /* c8 ignore next */
2016
- hasConf('production');
2017
-
2018
- /* c8 ignore next 2 */
2019
- const forceColor = isNode &&
2020
- isOneOf(process.env.FORCE_COLOR, ['true', '1', '2']);
2021
-
2022
- /* c8 ignore start */
2023
- /**
2024
- * Color is enabled by default if the terminal supports it.
2025
- *
2026
- * Explicitly enable color using `--color` parameter
2027
- * Disable color using `--no-color` parameter or using `NO_COLOR=1` environment variable.
2028
- * `FORCE_COLOR=1` enables color and takes precedence over all.
2029
- */
2030
- forceColor || (
2031
- !hasParam('--no-colors') && // @todo deprecate --no-colors
2032
- !hasConf('no-color') &&
2033
- (!isNode || process.stdout.isTTY) && (
2034
- !isNode ||
2035
- hasParam('--color') ||
2036
- getVariable('COLORTERM') !== null ||
2037
- (getVariable('TERM') || '').includes('color')
2038
- )
2039
- );
2040
- /* c8 ignore stop */
2041
-
2042
- /**
2043
- * Utility functions to work with buffers (Uint8Array).
2044
- *
2045
- * @module buffer
2046
- */
2047
-
2048
-
2049
- /**
2050
- * @param {number} len
2051
- */
2052
- const createUint8ArrayFromLen = len => new Uint8Array(len);
2053
-
2054
- /**
2055
- * Create Uint8Array with initial content from buffer
2056
- *
2057
- * @param {ArrayBuffer} buffer
2058
- * @param {number} byteOffset
2059
- * @param {number} length
2060
- */
2061
- const createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length) => new Uint8Array(buffer, byteOffset, length);
2062
-
2063
- /**
2064
- * Create Uint8Array with initial content from buffer
2065
- *
2066
- * @param {ArrayBuffer} buffer
2067
- */
2068
- const createUint8ArrayFromArrayBuffer = buffer => new Uint8Array(buffer);
2069
-
2070
- /* c8 ignore start */
2071
- /**
2072
- * @param {Uint8Array} bytes
2073
- * @return {string}
2074
- */
2075
- const toBase64Browser = bytes => {
2076
- let s = '';
2077
- for (let i = 0; i < bytes.byteLength; i++) {
2078
- s += fromCharCode(bytes[i]);
2079
- }
2080
- // eslint-disable-next-line no-undef
2081
- return btoa(s)
2082
- };
2083
- /* c8 ignore stop */
2084
-
2085
- /**
2086
- * @param {Uint8Array} bytes
2087
- * @return {string}
2088
- */
2089
- const toBase64Node = bytes => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('base64');
2090
-
2091
- /* c8 ignore start */
2092
- /**
2093
- * @param {string} s
2094
- * @return {Uint8Array}
2095
- */
2096
- const fromBase64Browser = s => {
2097
- // eslint-disable-next-line no-undef
2098
- const a = atob(s);
2099
- const bytes = createUint8ArrayFromLen(a.length);
2100
- for (let i = 0; i < a.length; i++) {
2101
- bytes[i] = a.charCodeAt(i);
2102
- }
2103
- return bytes
2104
- };
2105
- /* c8 ignore stop */
2106
-
2107
- /**
2108
- * @param {string} s
2109
- */
2110
- const fromBase64Node = s => {
2111
- const buf = Buffer.from(s, 'base64');
2112
- return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength)
2113
- };
2114
-
2115
- /* c8 ignore next */
2116
- const toBase64 = isBrowser ? toBase64Browser : toBase64Node;
2117
-
2118
- /* c8 ignore next */
2119
- const fromBase64 = isBrowser ? fromBase64Browser : fromBase64Node;
2120
-
2121
- /* eslint-env browser */
2122
-
2123
-
2124
- /**
2125
- * @typedef {Object} Channel
2126
- * @property {Set<function(any, any):any>} Channel.subs
2127
- * @property {any} Channel.bc
2128
- */
2129
-
2130
- /**
2131
- * @type {Map<string, Channel>}
2132
- */
2133
- const channels = new Map();
2134
-
2135
- /* c8 ignore start */
2136
- class LocalStoragePolyfill {
2137
- /**
2138
- * @param {string} room
2139
- */
2140
- constructor (room) {
2141
- this.room = room;
2142
- /**
2143
- * @type {null|function({data:ArrayBuffer}):void}
2144
- */
2145
- this.onmessage = null;
2146
- /**
2147
- * @param {any} e
2148
- */
2149
- this._onChange = e => e.key === room && this.onmessage !== null && this.onmessage({ data: fromBase64(e.newValue || '') });
2150
- onChange(this._onChange);
2151
- }
2152
-
2153
- /**
2154
- * @param {ArrayBuffer} buf
2155
- */
2156
- postMessage (buf) {
2157
- varStorage.setItem(this.room, toBase64(createUint8ArrayFromArrayBuffer(buf)));
2158
- }
2159
-
2160
- close () {
2161
- offChange(this._onChange);
2162
- }
2163
- }
2164
- /* c8 ignore stop */
2165
-
2166
- // Use BroadcastChannel or Polyfill
2167
- /* c8 ignore next */
2168
- const BC = typeof BroadcastChannel === 'undefined' ? LocalStoragePolyfill : BroadcastChannel;
2169
-
2170
- /**
2171
- * @param {string} room
2172
- * @return {Channel}
2173
- */
2174
- const getChannel = room =>
2175
- setIfUndefined(channels, room, () => {
2176
- const subs = create$2();
2177
- const bc = new BC(room);
2178
- /**
2179
- * @param {{data:ArrayBuffer}} e
2180
- */
2181
- /* c8 ignore next */
2182
- bc.onmessage = e => subs.forEach(sub => sub(e.data, 'broadcastchannel'));
2183
- return {
2184
- bc, subs
2185
- }
2186
- });
2187
-
2188
- /**
2189
- * Publish data to all subscribers (including subscribers on this tab)
2190
- *
2191
- * @function
2192
- * @param {string} room
2193
- * @param {any} data
2194
- * @param {any} [origin]
2195
- */
2196
- const publish = (room, data, origin = null) => {
2197
- const c = getChannel(room);
2198
- c.bc.postMessage(data);
2199
- c.subs.forEach(sub => sub(data, origin));
2200
- };
2201
-
2202
1766
  class MessageSender {
2203
1767
  constructor(Message, args = {}) {
2204
1768
  this.message = new Message();
@@ -2210,9 +1774,6 @@ class MessageSender {
2210
1774
  send(webSocket) {
2211
1775
  webSocket === null || webSocket === void 0 ? void 0 : webSocket.send(this.create());
2212
1776
  }
2213
- broadcast(channel) {
2214
- publish(channel, this.create());
2215
- }
2216
1777
  }
2217
1778
 
2218
1779
  class AuthenticationMessage extends OutgoingMessage {