@bluecopa/core 0.1.30 → 0.1.32

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/index.es.js CHANGED
@@ -1522,7 +1522,7 @@ typeof SuppressedError === "function" ? SuppressedError : function(error, suppre
1522
1522
  var e = new Error(message);
1523
1523
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1524
1524
  };
1525
- function getDefaultExportFromCjs(x) {
1525
+ function getDefaultExportFromCjs$1(x) {
1526
1526
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
1527
1527
  }
1528
1528
  var events = { exports: {} };
@@ -1888,7 +1888,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
1888
1888
  }
1889
1889
  }
1890
1890
  var eventsExports = events.exports;
1891
- var EventEmitter$1 = /* @__PURE__ */ getDefaultExportFromCjs(eventsExports);
1891
+ var EventEmitter$1 = /* @__PURE__ */ getDefaultExportFromCjs$1(eventsExports);
1892
1892
  var errorCodes;
1893
1893
  (function(errorCodes2) {
1894
1894
  errorCodes2[errorCodes2["timeout"] = 1] = "timeout";
@@ -5049,13 +5049,4184 @@ class CentrifugoWebsocket {
5049
5049
  this.isConnected = false;
5050
5050
  }
5051
5051
  }
5052
- class WebsocketContextFactory {
5053
- static create(mechanism, args) {
5054
- let websocketProvider;
5055
- if (mechanism === "centrifugo") {
5056
- websocketProvider = new CentrifugoWebsocket(args.connectionUrl, args.token, args.userId);
5052
+ function getDefaultExportFromCjs(x) {
5053
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
5054
+ }
5055
+ var pusher = { exports: {} };
5056
+ /*!
5057
+ * Pusher JavaScript Library v8.4.0
5058
+ * https://pusher.com/
5059
+ *
5060
+ * Copyright 2020, Pusher
5061
+ * Released under the MIT licence.
5062
+ */
5063
+ (function(module, exports$1) {
5064
+ (function webpackUniversalModuleDefinition(root, factory) {
5065
+ module.exports = factory();
5066
+ })(window, function() {
5067
+ return (
5068
+ /******/
5069
+ function(modules) {
5070
+ var installedModules = {};
5071
+ function __webpack_require__(moduleId) {
5072
+ if (installedModules[moduleId]) {
5073
+ return installedModules[moduleId].exports;
5074
+ }
5075
+ var module2 = installedModules[moduleId] = {
5076
+ /******/
5077
+ i: moduleId,
5078
+ /******/
5079
+ l: false,
5080
+ /******/
5081
+ exports: {}
5082
+ /******/
5083
+ };
5084
+ modules[moduleId].call(module2.exports, module2, module2.exports, __webpack_require__);
5085
+ module2.l = true;
5086
+ return module2.exports;
5087
+ }
5088
+ __webpack_require__.m = modules;
5089
+ __webpack_require__.c = installedModules;
5090
+ __webpack_require__.d = function(exports$12, name, getter) {
5091
+ if (!__webpack_require__.o(exports$12, name)) {
5092
+ Object.defineProperty(exports$12, name, { enumerable: true, get: getter });
5093
+ }
5094
+ };
5095
+ __webpack_require__.r = function(exports$12) {
5096
+ if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
5097
+ Object.defineProperty(exports$12, Symbol.toStringTag, { value: "Module" });
5098
+ }
5099
+ Object.defineProperty(exports$12, "__esModule", { value: true });
5100
+ };
5101
+ __webpack_require__.t = function(value, mode) {
5102
+ if (mode & 1) value = __webpack_require__(value);
5103
+ if (mode & 8) return value;
5104
+ if (mode & 4 && typeof value === "object" && value && value.__esModule) return value;
5105
+ var ns = /* @__PURE__ */ Object.create(null);
5106
+ __webpack_require__.r(ns);
5107
+ Object.defineProperty(ns, "default", { enumerable: true, value });
5108
+ if (mode & 2 && typeof value != "string") for (var key in value) __webpack_require__.d(ns, key, (function(key2) {
5109
+ return value[key2];
5110
+ }).bind(null, key));
5111
+ return ns;
5112
+ };
5113
+ __webpack_require__.n = function(module2) {
5114
+ var getter = module2 && module2.__esModule ? (
5115
+ /******/
5116
+ function getDefault() {
5117
+ return module2["default"];
5118
+ }
5119
+ ) : (
5120
+ /******/
5121
+ function getModuleExports() {
5122
+ return module2;
5123
+ }
5124
+ );
5125
+ __webpack_require__.d(getter, "a", getter);
5126
+ return getter;
5127
+ };
5128
+ __webpack_require__.o = function(object, property) {
5129
+ return Object.prototype.hasOwnProperty.call(object, property);
5130
+ };
5131
+ __webpack_require__.p = "";
5132
+ return __webpack_require__(__webpack_require__.s = 2);
5133
+ }([
5134
+ /* 0 */
5135
+ /***/
5136
+ function(module2, exports$12, __webpack_require__) {
5137
+ var __extends = this && this.__extends || /* @__PURE__ */ function() {
5138
+ var extendStatics = function(d, b) {
5139
+ extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
5140
+ d2.__proto__ = b2;
5141
+ } || function(d2, b2) {
5142
+ for (var p in b2) if (b2.hasOwnProperty(p)) d2[p] = b2[p];
5143
+ };
5144
+ return extendStatics(d, b);
5145
+ };
5146
+ return function(d, b) {
5147
+ extendStatics(d, b);
5148
+ function __() {
5149
+ this.constructor = d;
5150
+ }
5151
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5152
+ };
5153
+ }();
5154
+ Object.defineProperty(exports$12, "__esModule", { value: true });
5155
+ var INVALID_BYTE = 256;
5156
+ var Coder = (
5157
+ /** @class */
5158
+ function() {
5159
+ function Coder2(_paddingCharacter) {
5160
+ if (_paddingCharacter === void 0) {
5161
+ _paddingCharacter = "=";
5162
+ }
5163
+ this._paddingCharacter = _paddingCharacter;
5164
+ }
5165
+ Coder2.prototype.encodedLength = function(length) {
5166
+ if (!this._paddingCharacter) {
5167
+ return (length * 8 + 5) / 6 | 0;
5168
+ }
5169
+ return (length + 2) / 3 * 4 | 0;
5170
+ };
5171
+ Coder2.prototype.encode = function(data) {
5172
+ var out = "";
5173
+ var i = 0;
5174
+ for (; i < data.length - 2; i += 3) {
5175
+ var c = data[i] << 16 | data[i + 1] << 8 | data[i + 2];
5176
+ out += this._encodeByte(c >>> 3 * 6 & 63);
5177
+ out += this._encodeByte(c >>> 2 * 6 & 63);
5178
+ out += this._encodeByte(c >>> 1 * 6 & 63);
5179
+ out += this._encodeByte(c >>> 0 * 6 & 63);
5180
+ }
5181
+ var left = data.length - i;
5182
+ if (left > 0) {
5183
+ var c = data[i] << 16 | (left === 2 ? data[i + 1] << 8 : 0);
5184
+ out += this._encodeByte(c >>> 3 * 6 & 63);
5185
+ out += this._encodeByte(c >>> 2 * 6 & 63);
5186
+ if (left === 2) {
5187
+ out += this._encodeByte(c >>> 1 * 6 & 63);
5188
+ } else {
5189
+ out += this._paddingCharacter || "";
5190
+ }
5191
+ out += this._paddingCharacter || "";
5192
+ }
5193
+ return out;
5194
+ };
5195
+ Coder2.prototype.maxDecodedLength = function(length) {
5196
+ if (!this._paddingCharacter) {
5197
+ return (length * 6 + 7) / 8 | 0;
5198
+ }
5199
+ return length / 4 * 3 | 0;
5200
+ };
5201
+ Coder2.prototype.decodedLength = function(s) {
5202
+ return this.maxDecodedLength(s.length - this._getPaddingLength(s));
5203
+ };
5204
+ Coder2.prototype.decode = function(s) {
5205
+ if (s.length === 0) {
5206
+ return new Uint8Array(0);
5207
+ }
5208
+ var paddingLength = this._getPaddingLength(s);
5209
+ var length = s.length - paddingLength;
5210
+ var out = new Uint8Array(this.maxDecodedLength(length));
5211
+ var op = 0;
5212
+ var i = 0;
5213
+ var haveBad = 0;
5214
+ var v0 = 0, v1 = 0, v2 = 0, v3 = 0;
5215
+ for (; i < length - 4; i += 4) {
5216
+ v0 = this._decodeChar(s.charCodeAt(i + 0));
5217
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5218
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5219
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5220
+ out[op++] = v0 << 2 | v1 >>> 4;
5221
+ out[op++] = v1 << 4 | v2 >>> 2;
5222
+ out[op++] = v2 << 6 | v3;
5223
+ haveBad |= v0 & INVALID_BYTE;
5224
+ haveBad |= v1 & INVALID_BYTE;
5225
+ haveBad |= v2 & INVALID_BYTE;
5226
+ haveBad |= v3 & INVALID_BYTE;
5227
+ }
5228
+ if (i < length - 1) {
5229
+ v0 = this._decodeChar(s.charCodeAt(i));
5230
+ v1 = this._decodeChar(s.charCodeAt(i + 1));
5231
+ out[op++] = v0 << 2 | v1 >>> 4;
5232
+ haveBad |= v0 & INVALID_BYTE;
5233
+ haveBad |= v1 & INVALID_BYTE;
5234
+ }
5235
+ if (i < length - 2) {
5236
+ v2 = this._decodeChar(s.charCodeAt(i + 2));
5237
+ out[op++] = v1 << 4 | v2 >>> 2;
5238
+ haveBad |= v2 & INVALID_BYTE;
5239
+ }
5240
+ if (i < length - 3) {
5241
+ v3 = this._decodeChar(s.charCodeAt(i + 3));
5242
+ out[op++] = v2 << 6 | v3;
5243
+ haveBad |= v3 & INVALID_BYTE;
5244
+ }
5245
+ if (haveBad !== 0) {
5246
+ throw new Error("Base64Coder: incorrect characters for decoding");
5247
+ }
5248
+ return out;
5249
+ };
5250
+ Coder2.prototype._encodeByte = function(b) {
5251
+ var result = b;
5252
+ result += 65;
5253
+ result += 25 - b >>> 8 & 0 - 65 - 26 + 97;
5254
+ result += 51 - b >>> 8 & 26 - 97 - 52 + 48;
5255
+ result += 61 - b >>> 8 & 52 - 48 - 62 + 43;
5256
+ result += 62 - b >>> 8 & 62 - 43 - 63 + 47;
5257
+ return String.fromCharCode(result);
5258
+ };
5259
+ Coder2.prototype._decodeChar = function(c) {
5260
+ var result = INVALID_BYTE;
5261
+ result += (42 - c & c - 44) >>> 8 & -INVALID_BYTE + c - 43 + 62;
5262
+ result += (46 - c & c - 48) >>> 8 & -INVALID_BYTE + c - 47 + 63;
5263
+ result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52;
5264
+ result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0;
5265
+ result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26;
5266
+ return result;
5267
+ };
5268
+ Coder2.prototype._getPaddingLength = function(s) {
5269
+ var paddingLength = 0;
5270
+ if (this._paddingCharacter) {
5271
+ for (var i = s.length - 1; i >= 0; i--) {
5272
+ if (s[i] !== this._paddingCharacter) {
5273
+ break;
5274
+ }
5275
+ paddingLength++;
5276
+ }
5277
+ if (s.length < 4 || paddingLength > 2) {
5278
+ throw new Error("Base64Coder: incorrect padding");
5279
+ }
5280
+ }
5281
+ return paddingLength;
5282
+ };
5283
+ return Coder2;
5284
+ }()
5285
+ );
5286
+ exports$12.Coder = Coder;
5287
+ var stdCoder = new Coder();
5288
+ function encode(data) {
5289
+ return stdCoder.encode(data);
5290
+ }
5291
+ exports$12.encode = encode;
5292
+ function decode(s) {
5293
+ return stdCoder.decode(s);
5294
+ }
5295
+ exports$12.decode = decode;
5296
+ var URLSafeCoder = (
5297
+ /** @class */
5298
+ function(_super) {
5299
+ __extends(URLSafeCoder2, _super);
5300
+ function URLSafeCoder2() {
5301
+ return _super !== null && _super.apply(this, arguments) || this;
5302
+ }
5303
+ URLSafeCoder2.prototype._encodeByte = function(b) {
5304
+ var result = b;
5305
+ result += 65;
5306
+ result += 25 - b >>> 8 & 0 - 65 - 26 + 97;
5307
+ result += 51 - b >>> 8 & 26 - 97 - 52 + 48;
5308
+ result += 61 - b >>> 8 & 52 - 48 - 62 + 45;
5309
+ result += 62 - b >>> 8 & 62 - 45 - 63 + 95;
5310
+ return String.fromCharCode(result);
5311
+ };
5312
+ URLSafeCoder2.prototype._decodeChar = function(c) {
5313
+ var result = INVALID_BYTE;
5314
+ result += (44 - c & c - 46) >>> 8 & -INVALID_BYTE + c - 45 + 62;
5315
+ result += (94 - c & c - 96) >>> 8 & -INVALID_BYTE + c - 95 + 63;
5316
+ result += (47 - c & c - 58) >>> 8 & -INVALID_BYTE + c - 48 + 52;
5317
+ result += (64 - c & c - 91) >>> 8 & -INVALID_BYTE + c - 65 + 0;
5318
+ result += (96 - c & c - 123) >>> 8 & -INVALID_BYTE + c - 97 + 26;
5319
+ return result;
5320
+ };
5321
+ return URLSafeCoder2;
5322
+ }(Coder)
5323
+ );
5324
+ exports$12.URLSafeCoder = URLSafeCoder;
5325
+ var urlSafeCoder = new URLSafeCoder();
5326
+ function encodeURLSafe(data) {
5327
+ return urlSafeCoder.encode(data);
5328
+ }
5329
+ exports$12.encodeURLSafe = encodeURLSafe;
5330
+ function decodeURLSafe(s) {
5331
+ return urlSafeCoder.decode(s);
5332
+ }
5333
+ exports$12.decodeURLSafe = decodeURLSafe;
5334
+ exports$12.encodedLength = function(length) {
5335
+ return stdCoder.encodedLength(length);
5336
+ };
5337
+ exports$12.maxDecodedLength = function(length) {
5338
+ return stdCoder.maxDecodedLength(length);
5339
+ };
5340
+ exports$12.decodedLength = function(s) {
5341
+ return stdCoder.decodedLength(s);
5342
+ };
5343
+ },
5344
+ /* 1 */
5345
+ /***/
5346
+ function(module2, exports$12, __webpack_require__) {
5347
+ Object.defineProperty(exports$12, "__esModule", { value: true });
5348
+ var INVALID_UTF16 = "utf8: invalid string";
5349
+ var INVALID_UTF8 = "utf8: invalid source encoding";
5350
+ function encode(s) {
5351
+ var arr = new Uint8Array(encodedLength(s));
5352
+ var pos = 0;
5353
+ for (var i = 0; i < s.length; i++) {
5354
+ var c = s.charCodeAt(i);
5355
+ if (c < 128) {
5356
+ arr[pos++] = c;
5357
+ } else if (c < 2048) {
5358
+ arr[pos++] = 192 | c >> 6;
5359
+ arr[pos++] = 128 | c & 63;
5360
+ } else if (c < 55296) {
5361
+ arr[pos++] = 224 | c >> 12;
5362
+ arr[pos++] = 128 | c >> 6 & 63;
5363
+ arr[pos++] = 128 | c & 63;
5364
+ } else {
5365
+ i++;
5366
+ c = (c & 1023) << 10;
5367
+ c |= s.charCodeAt(i) & 1023;
5368
+ c += 65536;
5369
+ arr[pos++] = 240 | c >> 18;
5370
+ arr[pos++] = 128 | c >> 12 & 63;
5371
+ arr[pos++] = 128 | c >> 6 & 63;
5372
+ arr[pos++] = 128 | c & 63;
5373
+ }
5374
+ }
5375
+ return arr;
5376
+ }
5377
+ exports$12.encode = encode;
5378
+ function encodedLength(s) {
5379
+ var result = 0;
5380
+ for (var i = 0; i < s.length; i++) {
5381
+ var c = s.charCodeAt(i);
5382
+ if (c < 128) {
5383
+ result += 1;
5384
+ } else if (c < 2048) {
5385
+ result += 2;
5386
+ } else if (c < 55296) {
5387
+ result += 3;
5388
+ } else if (c <= 57343) {
5389
+ if (i >= s.length - 1) {
5390
+ throw new Error(INVALID_UTF16);
5391
+ }
5392
+ i++;
5393
+ result += 4;
5394
+ } else {
5395
+ throw new Error(INVALID_UTF16);
5396
+ }
5397
+ }
5398
+ return result;
5399
+ }
5400
+ exports$12.encodedLength = encodedLength;
5401
+ function decode(arr) {
5402
+ var chars = [];
5403
+ for (var i = 0; i < arr.length; i++) {
5404
+ var b = arr[i];
5405
+ if (b & 128) {
5406
+ var min = void 0;
5407
+ if (b < 224) {
5408
+ if (i >= arr.length) {
5409
+ throw new Error(INVALID_UTF8);
5410
+ }
5411
+ var n1 = arr[++i];
5412
+ if ((n1 & 192) !== 128) {
5413
+ throw new Error(INVALID_UTF8);
5414
+ }
5415
+ b = (b & 31) << 6 | n1 & 63;
5416
+ min = 128;
5417
+ } else if (b < 240) {
5418
+ if (i >= arr.length - 1) {
5419
+ throw new Error(INVALID_UTF8);
5420
+ }
5421
+ var n1 = arr[++i];
5422
+ var n2 = arr[++i];
5423
+ if ((n1 & 192) !== 128 || (n2 & 192) !== 128) {
5424
+ throw new Error(INVALID_UTF8);
5425
+ }
5426
+ b = (b & 15) << 12 | (n1 & 63) << 6 | n2 & 63;
5427
+ min = 2048;
5428
+ } else if (b < 248) {
5429
+ if (i >= arr.length - 2) {
5430
+ throw new Error(INVALID_UTF8);
5431
+ }
5432
+ var n1 = arr[++i];
5433
+ var n2 = arr[++i];
5434
+ var n3 = arr[++i];
5435
+ if ((n1 & 192) !== 128 || (n2 & 192) !== 128 || (n3 & 192) !== 128) {
5436
+ throw new Error(INVALID_UTF8);
5437
+ }
5438
+ b = (b & 15) << 18 | (n1 & 63) << 12 | (n2 & 63) << 6 | n3 & 63;
5439
+ min = 65536;
5440
+ } else {
5441
+ throw new Error(INVALID_UTF8);
5442
+ }
5443
+ if (b < min || b >= 55296 && b <= 57343) {
5444
+ throw new Error(INVALID_UTF8);
5445
+ }
5446
+ if (b >= 65536) {
5447
+ if (b > 1114111) {
5448
+ throw new Error(INVALID_UTF8);
5449
+ }
5450
+ b -= 65536;
5451
+ chars.push(String.fromCharCode(55296 | b >> 10));
5452
+ b = 56320 | b & 1023;
5453
+ }
5454
+ }
5455
+ chars.push(String.fromCharCode(b));
5456
+ }
5457
+ return chars.join("");
5458
+ }
5459
+ exports$12.decode = decode;
5460
+ },
5461
+ /* 2 */
5462
+ /***/
5463
+ function(module2, exports$12, __webpack_require__) {
5464
+ module2.exports = __webpack_require__(3).default;
5465
+ },
5466
+ /* 3 */
5467
+ /***/
5468
+ function(module2, __webpack_exports__, __webpack_require__) {
5469
+ __webpack_require__.r(__webpack_exports__);
5470
+ class ScriptReceiverFactory {
5471
+ constructor(prefix2, name) {
5472
+ this.lastId = 0;
5473
+ this.prefix = prefix2;
5474
+ this.name = name;
5475
+ }
5476
+ create(callback) {
5477
+ this.lastId++;
5478
+ var number = this.lastId;
5479
+ var id = this.prefix + number;
5480
+ var name = this.name + "[" + number + "]";
5481
+ var called = false;
5482
+ var callbackWrapper = function() {
5483
+ if (!called) {
5484
+ callback.apply(null, arguments);
5485
+ called = true;
5486
+ }
5487
+ };
5488
+ this[number] = callbackWrapper;
5489
+ return { number, id, name, callback: callbackWrapper };
5490
+ }
5491
+ remove(receiver) {
5492
+ delete this[receiver.number];
5493
+ }
5494
+ }
5495
+ var ScriptReceivers = new ScriptReceiverFactory("_pusher_script_", "Pusher.ScriptReceivers");
5496
+ var Defaults = {
5497
+ VERSION: "8.4.0",
5498
+ PROTOCOL: 7,
5499
+ wsPort: 80,
5500
+ wssPort: 443,
5501
+ wsPath: "",
5502
+ httpHost: "sockjs.pusher.com",
5503
+ httpPort: 80,
5504
+ httpsPort: 443,
5505
+ httpPath: "/pusher",
5506
+ stats_host: "stats.pusher.com",
5507
+ authEndpoint: "/pusher/auth",
5508
+ authTransport: "ajax",
5509
+ activityTimeout: 12e4,
5510
+ pongTimeout: 3e4,
5511
+ unavailableTimeout: 1e4,
5512
+ userAuthentication: {
5513
+ endpoint: "/pusher/user-auth",
5514
+ transport: "ajax"
5515
+ },
5516
+ channelAuthorization: {
5517
+ endpoint: "/pusher/auth",
5518
+ transport: "ajax"
5519
+ },
5520
+ cdn_http: "http://js.pusher.com",
5521
+ cdn_https: "https://js.pusher.com",
5522
+ dependency_suffix: ""
5523
+ };
5524
+ var defaults2 = Defaults;
5525
+ class dependency_loader_DependencyLoader {
5526
+ constructor(options) {
5527
+ this.options = options;
5528
+ this.receivers = options.receivers || ScriptReceivers;
5529
+ this.loading = {};
5530
+ }
5531
+ load(name, options, callback) {
5532
+ var self = this;
5533
+ if (self.loading[name] && self.loading[name].length > 0) {
5534
+ self.loading[name].push(callback);
5535
+ } else {
5536
+ self.loading[name] = [callback];
5537
+ var request = runtime.createScriptRequest(self.getPath(name, options));
5538
+ var receiver = self.receivers.create(function(error) {
5539
+ self.receivers.remove(receiver);
5540
+ if (self.loading[name]) {
5541
+ var callbacks = self.loading[name];
5542
+ delete self.loading[name];
5543
+ var successCallback = function(wasSuccessful) {
5544
+ if (!wasSuccessful) {
5545
+ request.cleanup();
5546
+ }
5547
+ };
5548
+ for (var i = 0; i < callbacks.length; i++) {
5549
+ callbacks[i](error, successCallback);
5550
+ }
5551
+ }
5552
+ });
5553
+ request.send(receiver);
5554
+ }
5555
+ }
5556
+ getRoot(options) {
5557
+ var cdn;
5558
+ var protocol = runtime.getDocument().location.protocol;
5559
+ if (options && options.useTLS || protocol === "https:") {
5560
+ cdn = this.options.cdn_https;
5561
+ } else {
5562
+ cdn = this.options.cdn_http;
5563
+ }
5564
+ return cdn.replace(/\/*$/, "") + "/" + this.options.version;
5565
+ }
5566
+ getPath(name, options) {
5567
+ return this.getRoot(options) + "/" + name + this.options.suffix + ".js";
5568
+ }
5569
+ }
5570
+ var DependenciesReceivers = new ScriptReceiverFactory("_pusher_dependencies", "Pusher.DependenciesReceivers");
5571
+ var Dependencies = new dependency_loader_DependencyLoader({
5572
+ cdn_http: defaults2.cdn_http,
5573
+ cdn_https: defaults2.cdn_https,
5574
+ version: defaults2.VERSION,
5575
+ suffix: defaults2.dependency_suffix,
5576
+ receivers: DependenciesReceivers
5577
+ });
5578
+ const urlStore = {
5579
+ baseUrl: "https://pusher.com",
5580
+ urls: {
5581
+ authenticationEndpoint: {
5582
+ path: "/docs/channels/server_api/authenticating_users"
5583
+ },
5584
+ authorizationEndpoint: {
5585
+ path: "/docs/channels/server_api/authorizing-users/"
5586
+ },
5587
+ javascriptQuickStart: {
5588
+ path: "/docs/javascript_quick_start"
5589
+ },
5590
+ triggeringClientEvents: {
5591
+ path: "/docs/client_api_guide/client_events#trigger-events"
5592
+ },
5593
+ encryptedChannelSupport: {
5594
+ fullUrl: "https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support"
5595
+ }
5596
+ }
5597
+ };
5598
+ const buildLogSuffix = function(key) {
5599
+ const urlPrefix = "See:";
5600
+ const urlObj = urlStore.urls[key];
5601
+ if (!urlObj)
5602
+ return "";
5603
+ let url;
5604
+ if (urlObj.fullUrl) {
5605
+ url = urlObj.fullUrl;
5606
+ } else if (urlObj.path) {
5607
+ url = urlStore.baseUrl + urlObj.path;
5608
+ }
5609
+ if (!url)
5610
+ return "";
5611
+ return `${urlPrefix} ${url}`;
5612
+ };
5613
+ var url_store = { buildLogSuffix };
5614
+ var AuthRequestType;
5615
+ (function(AuthRequestType2) {
5616
+ AuthRequestType2["UserAuthentication"] = "user-authentication";
5617
+ AuthRequestType2["ChannelAuthorization"] = "channel-authorization";
5618
+ })(AuthRequestType || (AuthRequestType = {}));
5619
+ class BadEventName extends Error {
5620
+ constructor(msg) {
5621
+ super(msg);
5622
+ Object.setPrototypeOf(this, new.target.prototype);
5623
+ }
5624
+ }
5625
+ class BadChannelName extends Error {
5626
+ constructor(msg) {
5627
+ super(msg);
5628
+ Object.setPrototypeOf(this, new.target.prototype);
5629
+ }
5630
+ }
5631
+ class RequestTimedOut extends Error {
5632
+ constructor(msg) {
5633
+ super(msg);
5634
+ Object.setPrototypeOf(this, new.target.prototype);
5635
+ }
5636
+ }
5637
+ class TransportPriorityTooLow extends Error {
5638
+ constructor(msg) {
5639
+ super(msg);
5640
+ Object.setPrototypeOf(this, new.target.prototype);
5641
+ }
5642
+ }
5643
+ class TransportClosed extends Error {
5644
+ constructor(msg) {
5645
+ super(msg);
5646
+ Object.setPrototypeOf(this, new.target.prototype);
5647
+ }
5648
+ }
5649
+ class UnsupportedFeature extends Error {
5650
+ constructor(msg) {
5651
+ super(msg);
5652
+ Object.setPrototypeOf(this, new.target.prototype);
5653
+ }
5654
+ }
5655
+ class UnsupportedTransport extends Error {
5656
+ constructor(msg) {
5657
+ super(msg);
5658
+ Object.setPrototypeOf(this, new.target.prototype);
5659
+ }
5660
+ }
5661
+ class UnsupportedStrategy extends Error {
5662
+ constructor(msg) {
5663
+ super(msg);
5664
+ Object.setPrototypeOf(this, new.target.prototype);
5665
+ }
5666
+ }
5667
+ class HTTPAuthError extends Error {
5668
+ constructor(status, msg) {
5669
+ super(msg);
5670
+ this.status = status;
5671
+ Object.setPrototypeOf(this, new.target.prototype);
5672
+ }
5673
+ }
5674
+ const ajax = function(context, query, authOptions, authRequestType, callback) {
5675
+ const xhr = runtime.createXHR();
5676
+ xhr.open("POST", authOptions.endpoint, true);
5677
+ xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
5678
+ for (var headerName in authOptions.headers) {
5679
+ xhr.setRequestHeader(headerName, authOptions.headers[headerName]);
5680
+ }
5681
+ if (authOptions.headersProvider != null) {
5682
+ let dynamicHeaders = authOptions.headersProvider();
5683
+ for (var headerName in dynamicHeaders) {
5684
+ xhr.setRequestHeader(headerName, dynamicHeaders[headerName]);
5685
+ }
5686
+ }
5687
+ xhr.onreadystatechange = function() {
5688
+ if (xhr.readyState === 4) {
5689
+ if (xhr.status === 200) {
5690
+ let data;
5691
+ let parsed = false;
5692
+ try {
5693
+ data = JSON.parse(xhr.responseText);
5694
+ parsed = true;
5695
+ } catch (e) {
5696
+ callback(new HTTPAuthError(200, `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${xhr.responseText}`), null);
5697
+ }
5698
+ if (parsed) {
5699
+ callback(null, data);
5700
+ }
5701
+ } else {
5702
+ let suffix = "";
5703
+ switch (authRequestType) {
5704
+ case AuthRequestType.UserAuthentication:
5705
+ suffix = url_store.buildLogSuffix("authenticationEndpoint");
5706
+ break;
5707
+ case AuthRequestType.ChannelAuthorization:
5708
+ suffix = `Clients must be authorized to join private or presence channels. ${url_store.buildLogSuffix("authorizationEndpoint")}`;
5709
+ break;
5710
+ }
5711
+ callback(new HTTPAuthError(xhr.status, `Unable to retrieve auth string from ${authRequestType.toString()} endpoint - received status: ${xhr.status} from ${authOptions.endpoint}. ${suffix}`), null);
5712
+ }
5713
+ }
5714
+ };
5715
+ xhr.send(query);
5716
+ return xhr;
5717
+ };
5718
+ var xhr_auth = ajax;
5719
+ function encode(s) {
5720
+ return btoa(utob(s));
5721
+ }
5722
+ var fromCharCode = String.fromCharCode;
5723
+ var b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
5724
+ var cb_utob = function(c) {
5725
+ var cc = c.charCodeAt(0);
5726
+ return cc < 128 ? c : cc < 2048 ? fromCharCode(192 | cc >>> 6) + fromCharCode(128 | cc & 63) : fromCharCode(224 | cc >>> 12 & 15) + fromCharCode(128 | cc >>> 6 & 63) + fromCharCode(128 | cc & 63);
5727
+ };
5728
+ var utob = function(u) {
5729
+ return u.replace(/[^\x00-\x7F]/g, cb_utob);
5730
+ };
5731
+ var cb_encode = function(ccc) {
5732
+ var padlen = [0, 2, 1][ccc.length % 3];
5733
+ var ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0);
5734
+ var chars = [
5735
+ b64chars.charAt(ord >>> 18),
5736
+ b64chars.charAt(ord >>> 12 & 63),
5737
+ padlen >= 2 ? "=" : b64chars.charAt(ord >>> 6 & 63),
5738
+ padlen >= 1 ? "=" : b64chars.charAt(ord & 63)
5739
+ ];
5740
+ return chars.join("");
5741
+ };
5742
+ var btoa = window.btoa || function(b) {
5743
+ return b.replace(/[\s\S]{1,3}/g, cb_encode);
5744
+ };
5745
+ class Timer {
5746
+ constructor(set, clear, delay, callback) {
5747
+ this.clear = clear;
5748
+ this.timer = set(() => {
5749
+ if (this.timer) {
5750
+ this.timer = callback(this.timer);
5751
+ }
5752
+ }, delay);
5753
+ }
5754
+ isRunning() {
5755
+ return this.timer !== null;
5756
+ }
5757
+ ensureAborted() {
5758
+ if (this.timer) {
5759
+ this.clear(this.timer);
5760
+ this.timer = null;
5761
+ }
5762
+ }
5763
+ }
5764
+ var abstract_timer = Timer;
5765
+ function timers_clearTimeout(timer) {
5766
+ window.clearTimeout(timer);
5767
+ }
5768
+ function timers_clearInterval(timer) {
5769
+ window.clearInterval(timer);
5770
+ }
5771
+ class timers_OneOffTimer extends abstract_timer {
5772
+ constructor(delay, callback) {
5773
+ super(setTimeout, timers_clearTimeout, delay, function(timer) {
5774
+ callback();
5775
+ return null;
5776
+ });
5777
+ }
5778
+ }
5779
+ class timers_PeriodicTimer extends abstract_timer {
5780
+ constructor(delay, callback) {
5781
+ super(setInterval, timers_clearInterval, delay, function(timer) {
5782
+ callback();
5783
+ return timer;
5784
+ });
5785
+ }
5786
+ }
5787
+ var Util = {
5788
+ now() {
5789
+ if (Date.now) {
5790
+ return Date.now();
5791
+ } else {
5792
+ return (/* @__PURE__ */ new Date()).valueOf();
5793
+ }
5794
+ },
5795
+ defer(callback) {
5796
+ return new timers_OneOffTimer(0, callback);
5797
+ },
5798
+ method(name, ...args) {
5799
+ var boundArguments = Array.prototype.slice.call(arguments, 1);
5800
+ return function(object) {
5801
+ return object[name].apply(object, boundArguments.concat(arguments));
5802
+ };
5803
+ }
5804
+ };
5805
+ var util = Util;
5806
+ function extend(target, ...sources) {
5807
+ for (var i = 0; i < sources.length; i++) {
5808
+ var extensions = sources[i];
5809
+ for (var property in extensions) {
5810
+ if (extensions[property] && extensions[property].constructor && extensions[property].constructor === Object) {
5811
+ target[property] = extend(target[property] || {}, extensions[property]);
5812
+ } else {
5813
+ target[property] = extensions[property];
5814
+ }
5815
+ }
5816
+ }
5817
+ return target;
5818
+ }
5819
+ function stringify() {
5820
+ var m = ["Pusher"];
5821
+ for (var i = 0; i < arguments.length; i++) {
5822
+ if (typeof arguments[i] === "string") {
5823
+ m.push(arguments[i]);
5824
+ } else {
5825
+ m.push(safeJSONStringify(arguments[i]));
5826
+ }
5827
+ }
5828
+ return m.join(" : ");
5829
+ }
5830
+ function arrayIndexOf(array, item) {
5831
+ var nativeIndexOf = Array.prototype.indexOf;
5832
+ if (array === null) {
5833
+ return -1;
5834
+ }
5835
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) {
5836
+ return array.indexOf(item);
5837
+ }
5838
+ for (var i = 0, l = array.length; i < l; i++) {
5839
+ if (array[i] === item) {
5840
+ return i;
5841
+ }
5842
+ }
5843
+ return -1;
5844
+ }
5845
+ function objectApply(object, f) {
5846
+ for (var key in object) {
5847
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
5848
+ f(object[key], key, object);
5849
+ }
5850
+ }
5851
+ }
5852
+ function keys(object) {
5853
+ var keys2 = [];
5854
+ objectApply(object, function(_2, key) {
5855
+ keys2.push(key);
5856
+ });
5857
+ return keys2;
5858
+ }
5859
+ function values(object) {
5860
+ var values2 = [];
5861
+ objectApply(object, function(value) {
5862
+ values2.push(value);
5863
+ });
5864
+ return values2;
5865
+ }
5866
+ function apply(array, f, context) {
5867
+ for (var i = 0; i < array.length; i++) {
5868
+ f.call(context || window, array[i], i, array);
5869
+ }
5870
+ }
5871
+ function map(array, f) {
5872
+ var result = [];
5873
+ for (var i = 0; i < array.length; i++) {
5874
+ result.push(f(array[i], i, array, result));
5875
+ }
5876
+ return result;
5877
+ }
5878
+ function mapObject(object, f) {
5879
+ var result = {};
5880
+ objectApply(object, function(value, key) {
5881
+ result[key] = f(value);
5882
+ });
5883
+ return result;
5884
+ }
5885
+ function filter(array, test) {
5886
+ test = test || function(value) {
5887
+ return !!value;
5888
+ };
5889
+ var result = [];
5890
+ for (var i = 0; i < array.length; i++) {
5891
+ if (test(array[i], i, array, result)) {
5892
+ result.push(array[i]);
5893
+ }
5894
+ }
5895
+ return result;
5896
+ }
5897
+ function filterObject(object, test) {
5898
+ var result = {};
5899
+ objectApply(object, function(value, key) {
5900
+ if (test && test(value, key, object, result) || Boolean(value)) {
5901
+ result[key] = value;
5902
+ }
5903
+ });
5904
+ return result;
5905
+ }
5906
+ function flatten(object) {
5907
+ var result = [];
5908
+ objectApply(object, function(value, key) {
5909
+ result.push([key, value]);
5910
+ });
5911
+ return result;
5912
+ }
5913
+ function any(array, test) {
5914
+ for (var i = 0; i < array.length; i++) {
5915
+ if (test(array[i], i, array)) {
5916
+ return true;
5917
+ }
5918
+ }
5919
+ return false;
5920
+ }
5921
+ function collections_all(array, test) {
5922
+ for (var i = 0; i < array.length; i++) {
5923
+ if (!test(array[i], i, array)) {
5924
+ return false;
5925
+ }
5926
+ }
5927
+ return true;
5928
+ }
5929
+ function encodeParamsObject(data) {
5930
+ return mapObject(data, function(value) {
5931
+ if (typeof value === "object") {
5932
+ value = safeJSONStringify(value);
5933
+ }
5934
+ return encodeURIComponent(encode(value.toString()));
5935
+ });
5936
+ }
5937
+ function buildQueryString(data) {
5938
+ var params = filterObject(data, function(value) {
5939
+ return value !== void 0;
5940
+ });
5941
+ var query = map(flatten(encodeParamsObject(params)), util.method("join", "=")).join("&");
5942
+ return query;
5943
+ }
5944
+ function decycleObject(object) {
5945
+ var objects = [], paths = [];
5946
+ return function derez(value, path) {
5947
+ var i, name, nu;
5948
+ switch (typeof value) {
5949
+ case "object":
5950
+ if (!value) {
5951
+ return null;
5952
+ }
5953
+ for (i = 0; i < objects.length; i += 1) {
5954
+ if (objects[i] === value) {
5955
+ return { $ref: paths[i] };
5956
+ }
5957
+ }
5958
+ objects.push(value);
5959
+ paths.push(path);
5960
+ if (Object.prototype.toString.apply(value) === "[object Array]") {
5961
+ nu = [];
5962
+ for (i = 0; i < value.length; i += 1) {
5963
+ nu[i] = derez(value[i], path + "[" + i + "]");
5964
+ }
5965
+ } else {
5966
+ nu = {};
5967
+ for (name in value) {
5968
+ if (Object.prototype.hasOwnProperty.call(value, name)) {
5969
+ nu[name] = derez(value[name], path + "[" + JSON.stringify(name) + "]");
5970
+ }
5971
+ }
5972
+ }
5973
+ return nu;
5974
+ case "number":
5975
+ case "string":
5976
+ case "boolean":
5977
+ return value;
5978
+ }
5979
+ }(object, "$");
5980
+ }
5981
+ function safeJSONStringify(source) {
5982
+ try {
5983
+ return JSON.stringify(source);
5984
+ } catch (e) {
5985
+ return JSON.stringify(decycleObject(source));
5986
+ }
5987
+ }
5988
+ class logger_Logger {
5989
+ constructor() {
5990
+ this.globalLog = (message) => {
5991
+ if (window.console && window.console.log) {
5992
+ window.console.log(message);
5993
+ }
5994
+ };
5995
+ }
5996
+ debug(...args) {
5997
+ this.log(this.globalLog, args);
5998
+ }
5999
+ warn(...args) {
6000
+ this.log(this.globalLogWarn, args);
6001
+ }
6002
+ error(...args) {
6003
+ this.log(this.globalLogError, args);
6004
+ }
6005
+ globalLogWarn(message) {
6006
+ if (window.console && window.console.warn) {
6007
+ window.console.warn(message);
6008
+ } else {
6009
+ this.globalLog(message);
6010
+ }
6011
+ }
6012
+ globalLogError(message) {
6013
+ if (window.console && window.console.error) {
6014
+ window.console.error(message);
6015
+ } else {
6016
+ this.globalLogWarn(message);
6017
+ }
6018
+ }
6019
+ log(defaultLoggingFunction, ...args) {
6020
+ var message = stringify.apply(this, arguments);
6021
+ if (core_pusher.log) {
6022
+ core_pusher.log(message);
6023
+ } else if (core_pusher.logToConsole) {
6024
+ const log2 = defaultLoggingFunction.bind(this);
6025
+ log2(message);
6026
+ }
6027
+ }
6028
+ }
6029
+ var logger = new logger_Logger();
6030
+ var jsonp = function(context, query, authOptions, authRequestType, callback) {
6031
+ if (authOptions.headers !== void 0 || authOptions.headersProvider != null) {
6032
+ logger.warn(`To send headers with the ${authRequestType.toString()} request, you must use AJAX, rather than JSONP.`);
6033
+ }
6034
+ var callbackName = context.nextAuthCallbackID.toString();
6035
+ context.nextAuthCallbackID++;
6036
+ var document2 = context.getDocument();
6037
+ var script = document2.createElement("script");
6038
+ context.auth_callbacks[callbackName] = function(data) {
6039
+ callback(null, data);
6040
+ };
6041
+ var callback_name = "Pusher.auth_callbacks['" + callbackName + "']";
6042
+ script.src = authOptions.endpoint + "?callback=" + encodeURIComponent(callback_name) + "&" + query;
6043
+ var head = document2.getElementsByTagName("head")[0] || document2.documentElement;
6044
+ head.insertBefore(script, head.firstChild);
6045
+ };
6046
+ var jsonp_auth = jsonp;
6047
+ class ScriptRequest {
6048
+ constructor(src) {
6049
+ this.src = src;
6050
+ }
6051
+ send(receiver) {
6052
+ var self = this;
6053
+ var errorString = "Error loading " + self.src;
6054
+ self.script = document.createElement("script");
6055
+ self.script.id = receiver.id;
6056
+ self.script.src = self.src;
6057
+ self.script.type = "text/javascript";
6058
+ self.script.charset = "UTF-8";
6059
+ if (self.script.addEventListener) {
6060
+ self.script.onerror = function() {
6061
+ receiver.callback(errorString);
6062
+ };
6063
+ self.script.onload = function() {
6064
+ receiver.callback(null);
6065
+ };
6066
+ } else {
6067
+ self.script.onreadystatechange = function() {
6068
+ if (self.script.readyState === "loaded" || self.script.readyState === "complete") {
6069
+ receiver.callback(null);
6070
+ }
6071
+ };
6072
+ }
6073
+ if (self.script.async === void 0 && document.attachEvent && /opera/i.test(navigator.userAgent)) {
6074
+ self.errorScript = document.createElement("script");
6075
+ self.errorScript.id = receiver.id + "_error";
6076
+ self.errorScript.text = receiver.name + "('" + errorString + "');";
6077
+ self.script.async = self.errorScript.async = false;
6078
+ } else {
6079
+ self.script.async = true;
6080
+ }
6081
+ var head = document.getElementsByTagName("head")[0];
6082
+ head.insertBefore(self.script, head.firstChild);
6083
+ if (self.errorScript) {
6084
+ head.insertBefore(self.errorScript, self.script.nextSibling);
6085
+ }
6086
+ }
6087
+ cleanup() {
6088
+ if (this.script) {
6089
+ this.script.onload = this.script.onerror = null;
6090
+ this.script.onreadystatechange = null;
6091
+ }
6092
+ if (this.script && this.script.parentNode) {
6093
+ this.script.parentNode.removeChild(this.script);
6094
+ }
6095
+ if (this.errorScript && this.errorScript.parentNode) {
6096
+ this.errorScript.parentNode.removeChild(this.errorScript);
6097
+ }
6098
+ this.script = null;
6099
+ this.errorScript = null;
6100
+ }
6101
+ }
6102
+ class jsonp_request_JSONPRequest {
6103
+ constructor(url, data) {
6104
+ this.url = url;
6105
+ this.data = data;
6106
+ }
6107
+ send(receiver) {
6108
+ if (this.request) {
6109
+ return;
6110
+ }
6111
+ var query = buildQueryString(this.data);
6112
+ var url = this.url + "/" + receiver.number + "?" + query;
6113
+ this.request = runtime.createScriptRequest(url);
6114
+ this.request.send(receiver);
6115
+ }
6116
+ cleanup() {
6117
+ if (this.request) {
6118
+ this.request.cleanup();
6119
+ }
6120
+ }
6121
+ }
6122
+ var getAgent = function(sender, useTLS) {
6123
+ return function(data, callback) {
6124
+ var scheme = "http" + (useTLS ? "s" : "") + "://";
6125
+ var url = scheme + (sender.host || sender.options.host) + sender.options.path;
6126
+ var request = runtime.createJSONPRequest(url, data);
6127
+ var receiver = runtime.ScriptReceivers.create(function(error, result) {
6128
+ ScriptReceivers.remove(receiver);
6129
+ request.cleanup();
6130
+ if (result && result.host) {
6131
+ sender.host = result.host;
6132
+ }
6133
+ if (callback) {
6134
+ callback(error, result);
6135
+ }
6136
+ });
6137
+ request.send(receiver);
6138
+ };
6139
+ };
6140
+ var jsonp_timeline_jsonp = {
6141
+ name: "jsonp",
6142
+ getAgent
6143
+ };
6144
+ var jsonp_timeline = jsonp_timeline_jsonp;
6145
+ function getGenericURL(baseScheme, params, path) {
6146
+ var scheme = baseScheme + (params.useTLS ? "s" : "");
6147
+ var host = params.useTLS ? params.hostTLS : params.hostNonTLS;
6148
+ return scheme + "://" + host + path;
6149
+ }
6150
+ function getGenericPath(key, queryString) {
6151
+ var path = "/app/" + key;
6152
+ var query = "?protocol=" + defaults2.PROTOCOL + "&client=js&version=" + defaults2.VERSION + (queryString ? "&" + queryString : "");
6153
+ return path + query;
6154
+ }
6155
+ var ws = {
6156
+ getInitial: function(key, params) {
6157
+ var path = (params.httpPath || "") + getGenericPath(key, "flash=false");
6158
+ return getGenericURL("ws", params, path);
6159
+ }
6160
+ };
6161
+ var http = {
6162
+ getInitial: function(key, params) {
6163
+ var path = (params.httpPath || "/pusher") + getGenericPath(key);
6164
+ return getGenericURL("http", params, path);
6165
+ }
6166
+ };
6167
+ var sockjs = {
6168
+ getInitial: function(key, params) {
6169
+ return getGenericURL("http", params, params.httpPath || "/pusher");
6170
+ },
6171
+ getPath: function(key, params) {
6172
+ return getGenericPath(key);
6173
+ }
6174
+ };
6175
+ class callback_registry_CallbackRegistry {
6176
+ constructor() {
6177
+ this._callbacks = {};
6178
+ }
6179
+ get(name) {
6180
+ return this._callbacks[prefix(name)];
6181
+ }
6182
+ add(name, callback, context) {
6183
+ var prefixedEventName = prefix(name);
6184
+ this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || [];
6185
+ this._callbacks[prefixedEventName].push({
6186
+ fn: callback,
6187
+ context
6188
+ });
6189
+ }
6190
+ remove(name, callback, context) {
6191
+ if (!name && !callback && !context) {
6192
+ this._callbacks = {};
6193
+ return;
6194
+ }
6195
+ var names = name ? [prefix(name)] : keys(this._callbacks);
6196
+ if (callback || context) {
6197
+ this.removeCallback(names, callback, context);
6198
+ } else {
6199
+ this.removeAllCallbacks(names);
6200
+ }
6201
+ }
6202
+ removeCallback(names, callback, context) {
6203
+ apply(names, function(name) {
6204
+ this._callbacks[name] = filter(this._callbacks[name] || [], function(binding) {
6205
+ return callback && callback !== binding.fn || context && context !== binding.context;
6206
+ });
6207
+ if (this._callbacks[name].length === 0) {
6208
+ delete this._callbacks[name];
6209
+ }
6210
+ }, this);
6211
+ }
6212
+ removeAllCallbacks(names) {
6213
+ apply(names, function(name) {
6214
+ delete this._callbacks[name];
6215
+ }, this);
6216
+ }
6217
+ }
6218
+ function prefix(name) {
6219
+ return "_" + name;
6220
+ }
6221
+ class dispatcher_Dispatcher {
6222
+ constructor(failThrough) {
6223
+ this.callbacks = new callback_registry_CallbackRegistry();
6224
+ this.global_callbacks = [];
6225
+ this.failThrough = failThrough;
6226
+ }
6227
+ bind(eventName, callback, context) {
6228
+ this.callbacks.add(eventName, callback, context);
6229
+ return this;
6230
+ }
6231
+ bind_global(callback) {
6232
+ this.global_callbacks.push(callback);
6233
+ return this;
6234
+ }
6235
+ unbind(eventName, callback, context) {
6236
+ this.callbacks.remove(eventName, callback, context);
6237
+ return this;
6238
+ }
6239
+ unbind_global(callback) {
6240
+ if (!callback) {
6241
+ this.global_callbacks = [];
6242
+ return this;
6243
+ }
6244
+ this.global_callbacks = filter(this.global_callbacks || [], (c) => c !== callback);
6245
+ return this;
6246
+ }
6247
+ unbind_all() {
6248
+ this.unbind();
6249
+ this.unbind_global();
6250
+ return this;
6251
+ }
6252
+ emit(eventName, data, metadata) {
6253
+ for (var i = 0; i < this.global_callbacks.length; i++) {
6254
+ this.global_callbacks[i](eventName, data);
6255
+ }
6256
+ var callbacks = this.callbacks.get(eventName);
6257
+ var args = [];
6258
+ if (metadata) {
6259
+ args.push(data, metadata);
6260
+ } else if (data) {
6261
+ args.push(data);
6262
+ }
6263
+ if (callbacks && callbacks.length > 0) {
6264
+ for (var i = 0; i < callbacks.length; i++) {
6265
+ callbacks[i].fn.apply(callbacks[i].context || window, args);
6266
+ }
6267
+ } else if (this.failThrough) {
6268
+ this.failThrough(eventName, data);
6269
+ }
6270
+ return this;
6271
+ }
6272
+ }
6273
+ class transport_connection_TransportConnection extends dispatcher_Dispatcher {
6274
+ constructor(hooks, name, priority, key, options) {
6275
+ super();
6276
+ this.initialize = runtime.transportConnectionInitializer;
6277
+ this.hooks = hooks;
6278
+ this.name = name;
6279
+ this.priority = priority;
6280
+ this.key = key;
6281
+ this.options = options;
6282
+ this.state = "new";
6283
+ this.timeline = options.timeline;
6284
+ this.activityTimeout = options.activityTimeout;
6285
+ this.id = this.timeline.generateUniqueID();
6286
+ }
6287
+ handlesActivityChecks() {
6288
+ return Boolean(this.hooks.handlesActivityChecks);
6289
+ }
6290
+ supportsPing() {
6291
+ return Boolean(this.hooks.supportsPing);
6292
+ }
6293
+ connect() {
6294
+ if (this.socket || this.state !== "initialized") {
6295
+ return false;
6296
+ }
6297
+ var url = this.hooks.urls.getInitial(this.key, this.options);
6298
+ try {
6299
+ this.socket = this.hooks.getSocket(url, this.options);
6300
+ } catch (e) {
6301
+ util.defer(() => {
6302
+ this.onError(e);
6303
+ this.changeState("closed");
6304
+ });
6305
+ return false;
6306
+ }
6307
+ this.bindListeners();
6308
+ logger.debug("Connecting", { transport: this.name, url });
6309
+ this.changeState("connecting");
6310
+ return true;
6311
+ }
6312
+ close() {
6313
+ if (this.socket) {
6314
+ this.socket.close();
6315
+ return true;
6316
+ } else {
6317
+ return false;
6318
+ }
6319
+ }
6320
+ send(data) {
6321
+ if (this.state === "open") {
6322
+ util.defer(() => {
6323
+ if (this.socket) {
6324
+ this.socket.send(data);
6325
+ }
6326
+ });
6327
+ return true;
6328
+ } else {
6329
+ return false;
6330
+ }
6331
+ }
6332
+ ping() {
6333
+ if (this.state === "open" && this.supportsPing()) {
6334
+ this.socket.ping();
6335
+ }
6336
+ }
6337
+ onOpen() {
6338
+ if (this.hooks.beforeOpen) {
6339
+ this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options));
6340
+ }
6341
+ this.changeState("open");
6342
+ this.socket.onopen = void 0;
6343
+ }
6344
+ onError(error) {
6345
+ this.emit("error", { type: "WebSocketError", error });
6346
+ this.timeline.error(this.buildTimelineMessage({ error: error.toString() }));
6347
+ }
6348
+ onClose(closeEvent) {
6349
+ if (closeEvent) {
6350
+ this.changeState("closed", {
6351
+ code: closeEvent.code,
6352
+ reason: closeEvent.reason,
6353
+ wasClean: closeEvent.wasClean
6354
+ });
6355
+ } else {
6356
+ this.changeState("closed");
6357
+ }
6358
+ this.unbindListeners();
6359
+ this.socket = void 0;
6360
+ }
6361
+ onMessage(message) {
6362
+ this.emit("message", message);
6363
+ }
6364
+ onActivity() {
6365
+ this.emit("activity");
6366
+ }
6367
+ bindListeners() {
6368
+ this.socket.onopen = () => {
6369
+ this.onOpen();
6370
+ };
6371
+ this.socket.onerror = (error) => {
6372
+ this.onError(error);
6373
+ };
6374
+ this.socket.onclose = (closeEvent) => {
6375
+ this.onClose(closeEvent);
6376
+ };
6377
+ this.socket.onmessage = (message) => {
6378
+ this.onMessage(message);
6379
+ };
6380
+ if (this.supportsPing()) {
6381
+ this.socket.onactivity = () => {
6382
+ this.onActivity();
6383
+ };
6384
+ }
6385
+ }
6386
+ unbindListeners() {
6387
+ if (this.socket) {
6388
+ this.socket.onopen = void 0;
6389
+ this.socket.onerror = void 0;
6390
+ this.socket.onclose = void 0;
6391
+ this.socket.onmessage = void 0;
6392
+ if (this.supportsPing()) {
6393
+ this.socket.onactivity = void 0;
6394
+ }
6395
+ }
6396
+ }
6397
+ changeState(state2, params) {
6398
+ this.state = state2;
6399
+ this.timeline.info(this.buildTimelineMessage({
6400
+ state: state2,
6401
+ params
6402
+ }));
6403
+ this.emit(state2, params);
6404
+ }
6405
+ buildTimelineMessage(message) {
6406
+ return extend({ cid: this.id }, message);
6407
+ }
6408
+ }
6409
+ class transport_Transport {
6410
+ constructor(hooks) {
6411
+ this.hooks = hooks;
6412
+ }
6413
+ isSupported(environment) {
6414
+ return this.hooks.isSupported(environment);
6415
+ }
6416
+ createConnection(name, priority, key, options) {
6417
+ return new transport_connection_TransportConnection(this.hooks, name, priority, key, options);
6418
+ }
6419
+ }
6420
+ var WSTransport = new transport_Transport({
6421
+ urls: ws,
6422
+ handlesActivityChecks: false,
6423
+ supportsPing: false,
6424
+ isInitialized: function() {
6425
+ return Boolean(runtime.getWebSocketAPI());
6426
+ },
6427
+ isSupported: function() {
6428
+ return Boolean(runtime.getWebSocketAPI());
6429
+ },
6430
+ getSocket: function(url) {
6431
+ return runtime.createWebSocket(url);
6432
+ }
6433
+ });
6434
+ var httpConfiguration = {
6435
+ urls: http,
6436
+ handlesActivityChecks: false,
6437
+ supportsPing: true,
6438
+ isInitialized: function() {
6439
+ return true;
6440
+ }
6441
+ };
6442
+ var streamingConfiguration = extend({
6443
+ getSocket: function(url) {
6444
+ return runtime.HTTPFactory.createStreamingSocket(url);
6445
+ }
6446
+ }, httpConfiguration);
6447
+ var pollingConfiguration = extend({
6448
+ getSocket: function(url) {
6449
+ return runtime.HTTPFactory.createPollingSocket(url);
6450
+ }
6451
+ }, httpConfiguration);
6452
+ var xhrConfiguration = {
6453
+ isSupported: function() {
6454
+ return runtime.isXHRSupported();
6455
+ }
6456
+ };
6457
+ var XHRStreamingTransport = new transport_Transport(extend({}, streamingConfiguration, xhrConfiguration));
6458
+ var XHRPollingTransport = new transport_Transport(extend({}, pollingConfiguration, xhrConfiguration));
6459
+ var Transports = {
6460
+ ws: WSTransport,
6461
+ xhr_streaming: XHRStreamingTransport,
6462
+ xhr_polling: XHRPollingTransport
6463
+ };
6464
+ var transports = Transports;
6465
+ var SockJSTransport = new transport_Transport({
6466
+ file: "sockjs",
6467
+ urls: sockjs,
6468
+ handlesActivityChecks: true,
6469
+ supportsPing: false,
6470
+ isSupported: function() {
6471
+ return true;
6472
+ },
6473
+ isInitialized: function() {
6474
+ return window.SockJS !== void 0;
6475
+ },
6476
+ getSocket: function(url, options) {
6477
+ return new window.SockJS(url, null, {
6478
+ js_path: Dependencies.getPath("sockjs", {
6479
+ useTLS: options.useTLS
6480
+ }),
6481
+ ignore_null_origin: options.ignoreNullOrigin
6482
+ });
6483
+ },
6484
+ beforeOpen: function(socket, path) {
6485
+ socket.send(JSON.stringify({
6486
+ path
6487
+ }));
6488
+ }
6489
+ });
6490
+ var xdrConfiguration = {
6491
+ isSupported: function(environment) {
6492
+ var yes = runtime.isXDRSupported(environment.useTLS);
6493
+ return yes;
6494
+ }
6495
+ };
6496
+ var XDRStreamingTransport = new transport_Transport(extend({}, streamingConfiguration, xdrConfiguration));
6497
+ var XDRPollingTransport = new transport_Transport(extend({}, pollingConfiguration, xdrConfiguration));
6498
+ transports.xdr_streaming = XDRStreamingTransport;
6499
+ transports.xdr_polling = XDRPollingTransport;
6500
+ transports.sockjs = SockJSTransport;
6501
+ var transports_transports = transports;
6502
+ class net_info_NetInfo extends dispatcher_Dispatcher {
6503
+ constructor() {
6504
+ super();
6505
+ var self = this;
6506
+ if (window.addEventListener !== void 0) {
6507
+ window.addEventListener("online", function() {
6508
+ self.emit("online");
6509
+ }, false);
6510
+ window.addEventListener("offline", function() {
6511
+ self.emit("offline");
6512
+ }, false);
6513
+ }
6514
+ }
6515
+ isOnline() {
6516
+ if (window.navigator.onLine === void 0) {
6517
+ return true;
6518
+ } else {
6519
+ return window.navigator.onLine;
6520
+ }
6521
+ }
6522
+ }
6523
+ var net_info_Network = new net_info_NetInfo();
6524
+ class assistant_to_the_transport_manager_AssistantToTheTransportManager {
6525
+ constructor(manager, transport, options) {
6526
+ this.manager = manager;
6527
+ this.transport = transport;
6528
+ this.minPingDelay = options.minPingDelay;
6529
+ this.maxPingDelay = options.maxPingDelay;
6530
+ this.pingDelay = void 0;
6531
+ }
6532
+ createConnection(name, priority, key, options) {
6533
+ options = extend({}, options, {
6534
+ activityTimeout: this.pingDelay
6535
+ });
6536
+ var connection = this.transport.createConnection(name, priority, key, options);
6537
+ var openTimestamp = null;
6538
+ var onOpen = function() {
6539
+ connection.unbind("open", onOpen);
6540
+ connection.bind("closed", onClosed);
6541
+ openTimestamp = util.now();
6542
+ };
6543
+ var onClosed = (closeEvent) => {
6544
+ connection.unbind("closed", onClosed);
6545
+ if (closeEvent.code === 1002 || closeEvent.code === 1003) {
6546
+ this.manager.reportDeath();
6547
+ } else if (!closeEvent.wasClean && openTimestamp) {
6548
+ var lifespan = util.now() - openTimestamp;
6549
+ if (lifespan < 2 * this.maxPingDelay) {
6550
+ this.manager.reportDeath();
6551
+ this.pingDelay = Math.max(lifespan / 2, this.minPingDelay);
6552
+ }
6553
+ }
6554
+ };
6555
+ connection.bind("open", onOpen);
6556
+ return connection;
6557
+ }
6558
+ isSupported(environment) {
6559
+ return this.manager.isAlive() && this.transport.isSupported(environment);
6560
+ }
6561
+ }
6562
+ const Protocol = {
6563
+ decodeMessage: function(messageEvent) {
6564
+ try {
6565
+ var messageData = JSON.parse(messageEvent.data);
6566
+ var pusherEventData = messageData.data;
6567
+ if (typeof pusherEventData === "string") {
6568
+ try {
6569
+ pusherEventData = JSON.parse(messageData.data);
6570
+ } catch (e) {
6571
+ }
6572
+ }
6573
+ var pusherEvent = {
6574
+ event: messageData.event,
6575
+ channel: messageData.channel,
6576
+ data: pusherEventData
6577
+ };
6578
+ if (messageData.user_id) {
6579
+ pusherEvent.user_id = messageData.user_id;
6580
+ }
6581
+ return pusherEvent;
6582
+ } catch (e) {
6583
+ throw { type: "MessageParseError", error: e, data: messageEvent.data };
6584
+ }
6585
+ },
6586
+ encodeMessage: function(event) {
6587
+ return JSON.stringify(event);
6588
+ },
6589
+ processHandshake: function(messageEvent) {
6590
+ var message = Protocol.decodeMessage(messageEvent);
6591
+ if (message.event === "pusher:connection_established") {
6592
+ if (!message.data.activity_timeout) {
6593
+ throw "No activity timeout specified in handshake";
6594
+ }
6595
+ return {
6596
+ action: "connected",
6597
+ id: message.data.socket_id,
6598
+ activityTimeout: message.data.activity_timeout * 1e3
6599
+ };
6600
+ } else if (message.event === "pusher:error") {
6601
+ return {
6602
+ action: this.getCloseAction(message.data),
6603
+ error: this.getCloseError(message.data)
6604
+ };
6605
+ } else {
6606
+ throw "Invalid handshake";
6607
+ }
6608
+ },
6609
+ getCloseAction: function(closeEvent) {
6610
+ if (closeEvent.code < 4e3) {
6611
+ if (closeEvent.code >= 1002 && closeEvent.code <= 1004) {
6612
+ return "backoff";
6613
+ } else {
6614
+ return null;
6615
+ }
6616
+ } else if (closeEvent.code === 4e3) {
6617
+ return "tls_only";
6618
+ } else if (closeEvent.code < 4100) {
6619
+ return "refused";
6620
+ } else if (closeEvent.code < 4200) {
6621
+ return "backoff";
6622
+ } else if (closeEvent.code < 4300) {
6623
+ return "retry";
6624
+ } else {
6625
+ return "refused";
6626
+ }
6627
+ },
6628
+ getCloseError: function(closeEvent) {
6629
+ if (closeEvent.code !== 1e3 && closeEvent.code !== 1001) {
6630
+ return {
6631
+ type: "PusherError",
6632
+ data: {
6633
+ code: closeEvent.code,
6634
+ message: closeEvent.reason || closeEvent.message
6635
+ }
6636
+ };
6637
+ } else {
6638
+ return null;
6639
+ }
6640
+ }
6641
+ };
6642
+ var protocol_protocol = Protocol;
6643
+ class connection_Connection extends dispatcher_Dispatcher {
6644
+ constructor(id, transport) {
6645
+ super();
6646
+ this.id = id;
6647
+ this.transport = transport;
6648
+ this.activityTimeout = transport.activityTimeout;
6649
+ this.bindListeners();
6650
+ }
6651
+ handlesActivityChecks() {
6652
+ return this.transport.handlesActivityChecks();
6653
+ }
6654
+ send(data) {
6655
+ return this.transport.send(data);
6656
+ }
6657
+ send_event(name, data, channel) {
6658
+ var event = { event: name, data };
6659
+ if (channel) {
6660
+ event.channel = channel;
6661
+ }
6662
+ logger.debug("Event sent", event);
6663
+ return this.send(protocol_protocol.encodeMessage(event));
6664
+ }
6665
+ ping() {
6666
+ if (this.transport.supportsPing()) {
6667
+ this.transport.ping();
6668
+ } else {
6669
+ this.send_event("pusher:ping", {});
6670
+ }
6671
+ }
6672
+ close() {
6673
+ this.transport.close();
6674
+ }
6675
+ bindListeners() {
6676
+ var listeners2 = {
6677
+ message: (messageEvent) => {
6678
+ var pusherEvent;
6679
+ try {
6680
+ pusherEvent = protocol_protocol.decodeMessage(messageEvent);
6681
+ } catch (e) {
6682
+ this.emit("error", {
6683
+ type: "MessageParseError",
6684
+ error: e,
6685
+ data: messageEvent.data
6686
+ });
6687
+ }
6688
+ if (pusherEvent !== void 0) {
6689
+ logger.debug("Event recd", pusherEvent);
6690
+ switch (pusherEvent.event) {
6691
+ case "pusher:error":
6692
+ this.emit("error", {
6693
+ type: "PusherError",
6694
+ data: pusherEvent.data
6695
+ });
6696
+ break;
6697
+ case "pusher:ping":
6698
+ this.emit("ping");
6699
+ break;
6700
+ case "pusher:pong":
6701
+ this.emit("pong");
6702
+ break;
6703
+ }
6704
+ this.emit("message", pusherEvent);
6705
+ }
6706
+ },
6707
+ activity: () => {
6708
+ this.emit("activity");
6709
+ },
6710
+ error: (error) => {
6711
+ this.emit("error", error);
6712
+ },
6713
+ closed: (closeEvent) => {
6714
+ unbindListeners();
6715
+ if (closeEvent && closeEvent.code) {
6716
+ this.handleCloseEvent(closeEvent);
6717
+ }
6718
+ this.transport = null;
6719
+ this.emit("closed");
6720
+ }
6721
+ };
6722
+ var unbindListeners = () => {
6723
+ objectApply(listeners2, (listener, event) => {
6724
+ this.transport.unbind(event, listener);
6725
+ });
6726
+ };
6727
+ objectApply(listeners2, (listener, event) => {
6728
+ this.transport.bind(event, listener);
6729
+ });
6730
+ }
6731
+ handleCloseEvent(closeEvent) {
6732
+ var action = protocol_protocol.getCloseAction(closeEvent);
6733
+ var error = protocol_protocol.getCloseError(closeEvent);
6734
+ if (error) {
6735
+ this.emit("error", error);
6736
+ }
6737
+ if (action) {
6738
+ this.emit(action, { action, error });
6739
+ }
6740
+ }
6741
+ }
6742
+ class handshake_Handshake {
6743
+ constructor(transport, callback) {
6744
+ this.transport = transport;
6745
+ this.callback = callback;
6746
+ this.bindListeners();
6747
+ }
6748
+ close() {
6749
+ this.unbindListeners();
6750
+ this.transport.close();
6751
+ }
6752
+ bindListeners() {
6753
+ this.onMessage = (m) => {
6754
+ this.unbindListeners();
6755
+ var result;
6756
+ try {
6757
+ result = protocol_protocol.processHandshake(m);
6758
+ } catch (e) {
6759
+ this.finish("error", { error: e });
6760
+ this.transport.close();
6761
+ return;
6762
+ }
6763
+ if (result.action === "connected") {
6764
+ this.finish("connected", {
6765
+ connection: new connection_Connection(result.id, this.transport),
6766
+ activityTimeout: result.activityTimeout
6767
+ });
6768
+ } else {
6769
+ this.finish(result.action, { error: result.error });
6770
+ this.transport.close();
6771
+ }
6772
+ };
6773
+ this.onClosed = (closeEvent) => {
6774
+ this.unbindListeners();
6775
+ var action = protocol_protocol.getCloseAction(closeEvent) || "backoff";
6776
+ var error = protocol_protocol.getCloseError(closeEvent);
6777
+ this.finish(action, { error });
6778
+ };
6779
+ this.transport.bind("message", this.onMessage);
6780
+ this.transport.bind("closed", this.onClosed);
6781
+ }
6782
+ unbindListeners() {
6783
+ this.transport.unbind("message", this.onMessage);
6784
+ this.transport.unbind("closed", this.onClosed);
6785
+ }
6786
+ finish(action, params) {
6787
+ this.callback(extend({ transport: this.transport, action }, params));
6788
+ }
6789
+ }
6790
+ class timeline_sender_TimelineSender {
6791
+ constructor(timeline, options) {
6792
+ this.timeline = timeline;
6793
+ this.options = options || {};
6794
+ }
6795
+ send(useTLS, callback) {
6796
+ if (this.timeline.isEmpty()) {
6797
+ return;
6798
+ }
6799
+ this.timeline.send(runtime.TimelineTransport.getAgent(this, useTLS), callback);
6800
+ }
6801
+ }
6802
+ class channel_Channel extends dispatcher_Dispatcher {
6803
+ constructor(name, pusher2) {
6804
+ super(function(event, data) {
6805
+ logger.debug("No callbacks on " + name + " for " + event);
6806
+ });
6807
+ this.name = name;
6808
+ this.pusher = pusher2;
6809
+ this.subscribed = false;
6810
+ this.subscriptionPending = false;
6811
+ this.subscriptionCancelled = false;
6812
+ }
6813
+ authorize(socketId, callback) {
6814
+ return callback(null, { auth: "" });
6815
+ }
6816
+ trigger(event, data) {
6817
+ if (event.indexOf("client-") !== 0) {
6818
+ throw new BadEventName("Event '" + event + "' does not start with 'client-'");
6819
+ }
6820
+ if (!this.subscribed) {
6821
+ var suffix = url_store.buildLogSuffix("triggeringClientEvents");
6822
+ logger.warn(`Client event triggered before channel 'subscription_succeeded' event . ${suffix}`);
6823
+ }
6824
+ return this.pusher.send_event(event, data, this.name);
6825
+ }
6826
+ disconnect() {
6827
+ this.subscribed = false;
6828
+ this.subscriptionPending = false;
6829
+ }
6830
+ handleEvent(event) {
6831
+ var eventName = event.event;
6832
+ var data = event.data;
6833
+ if (eventName === "pusher_internal:subscription_succeeded") {
6834
+ this.handleSubscriptionSucceededEvent(event);
6835
+ } else if (eventName === "pusher_internal:subscription_count") {
6836
+ this.handleSubscriptionCountEvent(event);
6837
+ } else if (eventName.indexOf("pusher_internal:") !== 0) {
6838
+ var metadata = {};
6839
+ this.emit(eventName, data, metadata);
6840
+ }
6841
+ }
6842
+ handleSubscriptionSucceededEvent(event) {
6843
+ this.subscriptionPending = false;
6844
+ this.subscribed = true;
6845
+ if (this.subscriptionCancelled) {
6846
+ this.pusher.unsubscribe(this.name);
6847
+ } else {
6848
+ this.emit("pusher:subscription_succeeded", event.data);
6849
+ }
6850
+ }
6851
+ handleSubscriptionCountEvent(event) {
6852
+ if (event.data.subscription_count) {
6853
+ this.subscriptionCount = event.data.subscription_count;
6854
+ }
6855
+ this.emit("pusher:subscription_count", event.data);
6856
+ }
6857
+ subscribe() {
6858
+ if (this.subscribed) {
6859
+ return;
6860
+ }
6861
+ this.subscriptionPending = true;
6862
+ this.subscriptionCancelled = false;
6863
+ this.authorize(this.pusher.connection.socket_id, (error, data) => {
6864
+ if (error) {
6865
+ this.subscriptionPending = false;
6866
+ logger.error(error.toString());
6867
+ this.emit("pusher:subscription_error", Object.assign({}, {
6868
+ type: "AuthError",
6869
+ error: error.message
6870
+ }, error instanceof HTTPAuthError ? { status: error.status } : {}));
6871
+ } else {
6872
+ this.pusher.send_event("pusher:subscribe", {
6873
+ auth: data.auth,
6874
+ channel_data: data.channel_data,
6875
+ channel: this.name
6876
+ });
6877
+ }
6878
+ });
6879
+ }
6880
+ unsubscribe() {
6881
+ this.subscribed = false;
6882
+ this.pusher.send_event("pusher:unsubscribe", {
6883
+ channel: this.name
6884
+ });
6885
+ }
6886
+ cancelSubscription() {
6887
+ this.subscriptionCancelled = true;
6888
+ }
6889
+ reinstateSubscription() {
6890
+ this.subscriptionCancelled = false;
6891
+ }
6892
+ }
6893
+ class private_channel_PrivateChannel extends channel_Channel {
6894
+ authorize(socketId, callback) {
6895
+ return this.pusher.config.channelAuthorizer({
6896
+ channelName: this.name,
6897
+ socketId
6898
+ }, callback);
6899
+ }
6900
+ }
6901
+ class members_Members {
6902
+ constructor() {
6903
+ this.reset();
6904
+ }
6905
+ get(id) {
6906
+ if (Object.prototype.hasOwnProperty.call(this.members, id)) {
6907
+ return {
6908
+ id,
6909
+ info: this.members[id]
6910
+ };
6911
+ } else {
6912
+ return null;
6913
+ }
6914
+ }
6915
+ each(callback) {
6916
+ objectApply(this.members, (member, id) => {
6917
+ callback(this.get(id));
6918
+ });
6919
+ }
6920
+ setMyID(id) {
6921
+ this.myID = id;
6922
+ }
6923
+ onSubscription(subscriptionData) {
6924
+ this.members = subscriptionData.presence.hash;
6925
+ this.count = subscriptionData.presence.count;
6926
+ this.me = this.get(this.myID);
6927
+ }
6928
+ addMember(memberData) {
6929
+ if (this.get(memberData.user_id) === null) {
6930
+ this.count++;
6931
+ }
6932
+ this.members[memberData.user_id] = memberData.user_info;
6933
+ return this.get(memberData.user_id);
6934
+ }
6935
+ removeMember(memberData) {
6936
+ var member = this.get(memberData.user_id);
6937
+ if (member) {
6938
+ delete this.members[memberData.user_id];
6939
+ this.count--;
6940
+ }
6941
+ return member;
6942
+ }
6943
+ reset() {
6944
+ this.members = {};
6945
+ this.count = 0;
6946
+ this.myID = null;
6947
+ this.me = null;
6948
+ }
6949
+ }
6950
+ var __awaiter2 = function(thisArg, _arguments, P, generator) {
6951
+ function adopt(value) {
6952
+ return value instanceof P ? value : new P(function(resolve) {
6953
+ resolve(value);
6954
+ });
6955
+ }
6956
+ return new (P || (P = Promise))(function(resolve, reject) {
6957
+ function fulfilled(value) {
6958
+ try {
6959
+ step(generator.next(value));
6960
+ } catch (e) {
6961
+ reject(e);
6962
+ }
6963
+ }
6964
+ function rejected(value) {
6965
+ try {
6966
+ step(generator["throw"](value));
6967
+ } catch (e) {
6968
+ reject(e);
6969
+ }
6970
+ }
6971
+ function step(result) {
6972
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
6973
+ }
6974
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
6975
+ });
6976
+ };
6977
+ class presence_channel_PresenceChannel extends private_channel_PrivateChannel {
6978
+ constructor(name, pusher2) {
6979
+ super(name, pusher2);
6980
+ this.members = new members_Members();
6981
+ }
6982
+ authorize(socketId, callback) {
6983
+ super.authorize(socketId, (error, authData) => __awaiter2(this, void 0, void 0, function* () {
6984
+ if (!error) {
6985
+ authData = authData;
6986
+ if (authData.channel_data != null) {
6987
+ var channelData = JSON.parse(authData.channel_data);
6988
+ this.members.setMyID(channelData.user_id);
6989
+ } else {
6990
+ yield this.pusher.user.signinDonePromise;
6991
+ if (this.pusher.user.user_data != null) {
6992
+ this.members.setMyID(this.pusher.user.user_data.id);
6993
+ } else {
6994
+ let suffix = url_store.buildLogSuffix("authorizationEndpoint");
6995
+ logger.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${suffix}, or the user should be signed in.`);
6996
+ callback("Invalid auth response");
6997
+ return;
6998
+ }
6999
+ }
7000
+ }
7001
+ callback(error, authData);
7002
+ }));
7003
+ }
7004
+ handleEvent(event) {
7005
+ var eventName = event.event;
7006
+ if (eventName.indexOf("pusher_internal:") === 0) {
7007
+ this.handleInternalEvent(event);
7008
+ } else {
7009
+ var data = event.data;
7010
+ var metadata = {};
7011
+ if (event.user_id) {
7012
+ metadata.user_id = event.user_id;
7013
+ }
7014
+ this.emit(eventName, data, metadata);
7015
+ }
7016
+ }
7017
+ handleInternalEvent(event) {
7018
+ var eventName = event.event;
7019
+ var data = event.data;
7020
+ switch (eventName) {
7021
+ case "pusher_internal:subscription_succeeded":
7022
+ this.handleSubscriptionSucceededEvent(event);
7023
+ break;
7024
+ case "pusher_internal:subscription_count":
7025
+ this.handleSubscriptionCountEvent(event);
7026
+ break;
7027
+ case "pusher_internal:member_added":
7028
+ var addedMember = this.members.addMember(data);
7029
+ this.emit("pusher:member_added", addedMember);
7030
+ break;
7031
+ case "pusher_internal:member_removed":
7032
+ var removedMember = this.members.removeMember(data);
7033
+ if (removedMember) {
7034
+ this.emit("pusher:member_removed", removedMember);
7035
+ }
7036
+ break;
7037
+ }
7038
+ }
7039
+ handleSubscriptionSucceededEvent(event) {
7040
+ this.subscriptionPending = false;
7041
+ this.subscribed = true;
7042
+ if (this.subscriptionCancelled) {
7043
+ this.pusher.unsubscribe(this.name);
7044
+ } else {
7045
+ this.members.onSubscription(event.data);
7046
+ this.emit("pusher:subscription_succeeded", this.members);
7047
+ }
7048
+ }
7049
+ disconnect() {
7050
+ this.members.reset();
7051
+ super.disconnect();
7052
+ }
7053
+ }
7054
+ var utf8 = __webpack_require__(1);
7055
+ var base64 = __webpack_require__(0);
7056
+ class encrypted_channel_EncryptedChannel extends private_channel_PrivateChannel {
7057
+ constructor(name, pusher2, nacl) {
7058
+ super(name, pusher2);
7059
+ this.key = null;
7060
+ this.nacl = nacl;
7061
+ }
7062
+ authorize(socketId, callback) {
7063
+ super.authorize(socketId, (error, authData) => {
7064
+ if (error) {
7065
+ callback(error, authData);
7066
+ return;
7067
+ }
7068
+ let sharedSecret = authData["shared_secret"];
7069
+ if (!sharedSecret) {
7070
+ callback(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`), null);
7071
+ return;
7072
+ }
7073
+ this.key = Object(base64["decode"])(sharedSecret);
7074
+ delete authData["shared_secret"];
7075
+ callback(null, authData);
7076
+ });
7077
+ }
7078
+ trigger(event, data) {
7079
+ throw new UnsupportedFeature("Client events are not currently supported for encrypted channels");
7080
+ }
7081
+ handleEvent(event) {
7082
+ var eventName = event.event;
7083
+ var data = event.data;
7084
+ if (eventName.indexOf("pusher_internal:") === 0 || eventName.indexOf("pusher:") === 0) {
7085
+ super.handleEvent(event);
7086
+ return;
7087
+ }
7088
+ this.handleEncryptedEvent(eventName, data);
7089
+ }
7090
+ handleEncryptedEvent(event, data) {
7091
+ if (!this.key) {
7092
+ logger.debug("Received encrypted event before key has been retrieved from the authEndpoint");
7093
+ return;
7094
+ }
7095
+ if (!data.ciphertext || !data.nonce) {
7096
+ logger.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: " + data);
7097
+ return;
7098
+ }
7099
+ let cipherText = Object(base64["decode"])(data.ciphertext);
7100
+ if (cipherText.length < this.nacl.secretbox.overheadLength) {
7101
+ logger.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}`);
7102
+ return;
7103
+ }
7104
+ let nonce = Object(base64["decode"])(data.nonce);
7105
+ if (nonce.length < this.nacl.secretbox.nonceLength) {
7106
+ logger.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}`);
7107
+ return;
7108
+ }
7109
+ let bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);
7110
+ if (bytes === null) {
7111
+ logger.debug("Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint...");
7112
+ this.authorize(this.pusher.connection.socket_id, (error, authData) => {
7113
+ if (error) {
7114
+ logger.error(`Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event`);
7115
+ return;
7116
+ }
7117
+ bytes = this.nacl.secretbox.open(cipherText, nonce, this.key);
7118
+ if (bytes === null) {
7119
+ logger.error(`Failed to decrypt event with new key. Dropping encrypted event`);
7120
+ return;
7121
+ }
7122
+ this.emit(event, this.getDataToEmit(bytes));
7123
+ return;
7124
+ });
7125
+ return;
7126
+ }
7127
+ this.emit(event, this.getDataToEmit(bytes));
7128
+ }
7129
+ getDataToEmit(bytes) {
7130
+ let raw = Object(utf8["decode"])(bytes);
7131
+ try {
7132
+ return JSON.parse(raw);
7133
+ } catch (_a) {
7134
+ return raw;
7135
+ }
7136
+ }
7137
+ }
7138
+ class connection_manager_ConnectionManager extends dispatcher_Dispatcher {
7139
+ constructor(key, options) {
7140
+ super();
7141
+ this.state = "initialized";
7142
+ this.connection = null;
7143
+ this.key = key;
7144
+ this.options = options;
7145
+ this.timeline = this.options.timeline;
7146
+ this.usingTLS = this.options.useTLS;
7147
+ this.errorCallbacks = this.buildErrorCallbacks();
7148
+ this.connectionCallbacks = this.buildConnectionCallbacks(this.errorCallbacks);
7149
+ this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks);
7150
+ var Network = runtime.getNetwork();
7151
+ Network.bind("online", () => {
7152
+ this.timeline.info({ netinfo: "online" });
7153
+ if (this.state === "connecting" || this.state === "unavailable") {
7154
+ this.retryIn(0);
7155
+ }
7156
+ });
7157
+ Network.bind("offline", () => {
7158
+ this.timeline.info({ netinfo: "offline" });
7159
+ if (this.connection) {
7160
+ this.sendActivityCheck();
7161
+ }
7162
+ });
7163
+ this.updateStrategy();
7164
+ }
7165
+ connect() {
7166
+ if (this.connection || this.runner) {
7167
+ return;
7168
+ }
7169
+ if (!this.strategy.isSupported()) {
7170
+ this.updateState("failed");
7171
+ return;
7172
+ }
7173
+ this.updateState("connecting");
7174
+ this.startConnecting();
7175
+ this.setUnavailableTimer();
7176
+ }
7177
+ send(data) {
7178
+ if (this.connection) {
7179
+ return this.connection.send(data);
7180
+ } else {
7181
+ return false;
7182
+ }
7183
+ }
7184
+ send_event(name, data, channel) {
7185
+ if (this.connection) {
7186
+ return this.connection.send_event(name, data, channel);
7187
+ } else {
7188
+ return false;
7189
+ }
7190
+ }
7191
+ disconnect() {
7192
+ this.disconnectInternally();
7193
+ this.updateState("disconnected");
7194
+ }
7195
+ isUsingTLS() {
7196
+ return this.usingTLS;
7197
+ }
7198
+ startConnecting() {
7199
+ var callback = (error, handshake) => {
7200
+ if (error) {
7201
+ this.runner = this.strategy.connect(0, callback);
7202
+ } else {
7203
+ if (handshake.action === "error") {
7204
+ this.emit("error", {
7205
+ type: "HandshakeError",
7206
+ error: handshake.error
7207
+ });
7208
+ this.timeline.error({ handshakeError: handshake.error });
7209
+ } else {
7210
+ this.abortConnecting();
7211
+ this.handshakeCallbacks[handshake.action](handshake);
7212
+ }
7213
+ }
7214
+ };
7215
+ this.runner = this.strategy.connect(0, callback);
7216
+ }
7217
+ abortConnecting() {
7218
+ if (this.runner) {
7219
+ this.runner.abort();
7220
+ this.runner = null;
7221
+ }
7222
+ }
7223
+ disconnectInternally() {
7224
+ this.abortConnecting();
7225
+ this.clearRetryTimer();
7226
+ this.clearUnavailableTimer();
7227
+ if (this.connection) {
7228
+ var connection = this.abandonConnection();
7229
+ connection.close();
7230
+ }
7231
+ }
7232
+ updateStrategy() {
7233
+ this.strategy = this.options.getStrategy({
7234
+ key: this.key,
7235
+ timeline: this.timeline,
7236
+ useTLS: this.usingTLS
7237
+ });
7238
+ }
7239
+ retryIn(delay) {
7240
+ this.timeline.info({ action: "retry", delay });
7241
+ if (delay > 0) {
7242
+ this.emit("connecting_in", Math.round(delay / 1e3));
7243
+ }
7244
+ this.retryTimer = new timers_OneOffTimer(delay || 0, () => {
7245
+ this.disconnectInternally();
7246
+ this.connect();
7247
+ });
7248
+ }
7249
+ clearRetryTimer() {
7250
+ if (this.retryTimer) {
7251
+ this.retryTimer.ensureAborted();
7252
+ this.retryTimer = null;
7253
+ }
7254
+ }
7255
+ setUnavailableTimer() {
7256
+ this.unavailableTimer = new timers_OneOffTimer(this.options.unavailableTimeout, () => {
7257
+ this.updateState("unavailable");
7258
+ });
7259
+ }
7260
+ clearUnavailableTimer() {
7261
+ if (this.unavailableTimer) {
7262
+ this.unavailableTimer.ensureAborted();
7263
+ }
7264
+ }
7265
+ sendActivityCheck() {
7266
+ this.stopActivityCheck();
7267
+ this.connection.ping();
7268
+ this.activityTimer = new timers_OneOffTimer(this.options.pongTimeout, () => {
7269
+ this.timeline.error({ pong_timed_out: this.options.pongTimeout });
7270
+ this.retryIn(0);
7271
+ });
7272
+ }
7273
+ resetActivityCheck() {
7274
+ this.stopActivityCheck();
7275
+ if (this.connection && !this.connection.handlesActivityChecks()) {
7276
+ this.activityTimer = new timers_OneOffTimer(this.activityTimeout, () => {
7277
+ this.sendActivityCheck();
7278
+ });
7279
+ }
7280
+ }
7281
+ stopActivityCheck() {
7282
+ if (this.activityTimer) {
7283
+ this.activityTimer.ensureAborted();
7284
+ }
7285
+ }
7286
+ buildConnectionCallbacks(errorCallbacks) {
7287
+ return extend({}, errorCallbacks, {
7288
+ message: (message) => {
7289
+ this.resetActivityCheck();
7290
+ this.emit("message", message);
7291
+ },
7292
+ ping: () => {
7293
+ this.send_event("pusher:pong", {});
7294
+ },
7295
+ activity: () => {
7296
+ this.resetActivityCheck();
7297
+ },
7298
+ error: (error) => {
7299
+ this.emit("error", error);
7300
+ },
7301
+ closed: () => {
7302
+ this.abandonConnection();
7303
+ if (this.shouldRetry()) {
7304
+ this.retryIn(1e3);
7305
+ }
7306
+ }
7307
+ });
7308
+ }
7309
+ buildHandshakeCallbacks(errorCallbacks) {
7310
+ return extend({}, errorCallbacks, {
7311
+ connected: (handshake) => {
7312
+ this.activityTimeout = Math.min(this.options.activityTimeout, handshake.activityTimeout, handshake.connection.activityTimeout || Infinity);
7313
+ this.clearUnavailableTimer();
7314
+ this.setConnection(handshake.connection);
7315
+ this.socket_id = this.connection.id;
7316
+ this.updateState("connected", { socket_id: this.socket_id });
7317
+ }
7318
+ });
7319
+ }
7320
+ buildErrorCallbacks() {
7321
+ let withErrorEmitted = (callback) => {
7322
+ return (result) => {
7323
+ if (result.error) {
7324
+ this.emit("error", { type: "WebSocketError", error: result.error });
7325
+ }
7326
+ callback(result);
7327
+ };
7328
+ };
7329
+ return {
7330
+ tls_only: withErrorEmitted(() => {
7331
+ this.usingTLS = true;
7332
+ this.updateStrategy();
7333
+ this.retryIn(0);
7334
+ }),
7335
+ refused: withErrorEmitted(() => {
7336
+ this.disconnect();
7337
+ }),
7338
+ backoff: withErrorEmitted(() => {
7339
+ this.retryIn(1e3);
7340
+ }),
7341
+ retry: withErrorEmitted(() => {
7342
+ this.retryIn(0);
7343
+ })
7344
+ };
7345
+ }
7346
+ setConnection(connection) {
7347
+ this.connection = connection;
7348
+ for (var event in this.connectionCallbacks) {
7349
+ this.connection.bind(event, this.connectionCallbacks[event]);
7350
+ }
7351
+ this.resetActivityCheck();
7352
+ }
7353
+ abandonConnection() {
7354
+ if (!this.connection) {
7355
+ return;
7356
+ }
7357
+ this.stopActivityCheck();
7358
+ for (var event in this.connectionCallbacks) {
7359
+ this.connection.unbind(event, this.connectionCallbacks[event]);
7360
+ }
7361
+ var connection = this.connection;
7362
+ this.connection = null;
7363
+ return connection;
7364
+ }
7365
+ updateState(newState, data) {
7366
+ var previousState = this.state;
7367
+ this.state = newState;
7368
+ if (previousState !== newState) {
7369
+ var newStateDescription = newState;
7370
+ if (newStateDescription === "connected") {
7371
+ newStateDescription += " with new socket ID " + data.socket_id;
7372
+ }
7373
+ logger.debug("State changed", previousState + " -> " + newStateDescription);
7374
+ this.timeline.info({ state: newState, params: data });
7375
+ this.emit("state_change", { previous: previousState, current: newState });
7376
+ this.emit(newState, data);
7377
+ }
7378
+ }
7379
+ shouldRetry() {
7380
+ return this.state === "connecting" || this.state === "connected";
7381
+ }
7382
+ }
7383
+ class channels_Channels {
7384
+ constructor() {
7385
+ this.channels = {};
7386
+ }
7387
+ add(name, pusher2) {
7388
+ if (!this.channels[name]) {
7389
+ this.channels[name] = createChannel(name, pusher2);
7390
+ }
7391
+ return this.channels[name];
7392
+ }
7393
+ all() {
7394
+ return values(this.channels);
7395
+ }
7396
+ find(name) {
7397
+ return this.channels[name];
7398
+ }
7399
+ remove(name) {
7400
+ var channel = this.channels[name];
7401
+ delete this.channels[name];
7402
+ return channel;
7403
+ }
7404
+ disconnect() {
7405
+ objectApply(this.channels, function(channel) {
7406
+ channel.disconnect();
7407
+ });
7408
+ }
7409
+ }
7410
+ function createChannel(name, pusher2) {
7411
+ if (name.indexOf("private-encrypted-") === 0) {
7412
+ if (pusher2.config.nacl) {
7413
+ return factory.createEncryptedChannel(name, pusher2, pusher2.config.nacl);
7414
+ }
7415
+ let errMsg = "Tried to subscribe to a private-encrypted- channel but no nacl implementation available";
7416
+ let suffix = url_store.buildLogSuffix("encryptedChannelSupport");
7417
+ throw new UnsupportedFeature(`${errMsg}. ${suffix}`);
7418
+ } else if (name.indexOf("private-") === 0) {
7419
+ return factory.createPrivateChannel(name, pusher2);
7420
+ } else if (name.indexOf("presence-") === 0) {
7421
+ return factory.createPresenceChannel(name, pusher2);
7422
+ } else if (name.indexOf("#") === 0) {
7423
+ throw new BadChannelName('Cannot create a channel with name "' + name + '".');
7424
+ } else {
7425
+ return factory.createChannel(name, pusher2);
7426
+ }
7427
+ }
7428
+ var Factory = {
7429
+ createChannels() {
7430
+ return new channels_Channels();
7431
+ },
7432
+ createConnectionManager(key, options) {
7433
+ return new connection_manager_ConnectionManager(key, options);
7434
+ },
7435
+ createChannel(name, pusher2) {
7436
+ return new channel_Channel(name, pusher2);
7437
+ },
7438
+ createPrivateChannel(name, pusher2) {
7439
+ return new private_channel_PrivateChannel(name, pusher2);
7440
+ },
7441
+ createPresenceChannel(name, pusher2) {
7442
+ return new presence_channel_PresenceChannel(name, pusher2);
7443
+ },
7444
+ createEncryptedChannel(name, pusher2, nacl) {
7445
+ return new encrypted_channel_EncryptedChannel(name, pusher2, nacl);
7446
+ },
7447
+ createTimelineSender(timeline, options) {
7448
+ return new timeline_sender_TimelineSender(timeline, options);
7449
+ },
7450
+ createHandshake(transport, callback) {
7451
+ return new handshake_Handshake(transport, callback);
7452
+ },
7453
+ createAssistantToTheTransportManager(manager, transport, options) {
7454
+ return new assistant_to_the_transport_manager_AssistantToTheTransportManager(manager, transport, options);
7455
+ }
7456
+ };
7457
+ var factory = Factory;
7458
+ class transport_manager_TransportManager {
7459
+ constructor(options) {
7460
+ this.options = options || {};
7461
+ this.livesLeft = this.options.lives || Infinity;
7462
+ }
7463
+ getAssistant(transport) {
7464
+ return factory.createAssistantToTheTransportManager(this, transport, {
7465
+ minPingDelay: this.options.minPingDelay,
7466
+ maxPingDelay: this.options.maxPingDelay
7467
+ });
7468
+ }
7469
+ isAlive() {
7470
+ return this.livesLeft > 0;
7471
+ }
7472
+ reportDeath() {
7473
+ this.livesLeft -= 1;
7474
+ }
7475
+ }
7476
+ class sequential_strategy_SequentialStrategy {
7477
+ constructor(strategies, options) {
7478
+ this.strategies = strategies;
7479
+ this.loop = Boolean(options.loop);
7480
+ this.failFast = Boolean(options.failFast);
7481
+ this.timeout = options.timeout;
7482
+ this.timeoutLimit = options.timeoutLimit;
7483
+ }
7484
+ isSupported() {
7485
+ return any(this.strategies, util.method("isSupported"));
7486
+ }
7487
+ connect(minPriority, callback) {
7488
+ var strategies = this.strategies;
7489
+ var current = 0;
7490
+ var timeout = this.timeout;
7491
+ var runner = null;
7492
+ var tryNextStrategy = (error, handshake) => {
7493
+ if (handshake) {
7494
+ callback(null, handshake);
7495
+ } else {
7496
+ current = current + 1;
7497
+ if (this.loop) {
7498
+ current = current % strategies.length;
7499
+ }
7500
+ if (current < strategies.length) {
7501
+ if (timeout) {
7502
+ timeout = timeout * 2;
7503
+ if (this.timeoutLimit) {
7504
+ timeout = Math.min(timeout, this.timeoutLimit);
7505
+ }
7506
+ }
7507
+ runner = this.tryStrategy(strategies[current], minPriority, { timeout, failFast: this.failFast }, tryNextStrategy);
7508
+ } else {
7509
+ callback(true);
7510
+ }
7511
+ }
7512
+ };
7513
+ runner = this.tryStrategy(strategies[current], minPriority, { timeout, failFast: this.failFast }, tryNextStrategy);
7514
+ return {
7515
+ abort: function() {
7516
+ runner.abort();
7517
+ },
7518
+ forceMinPriority: function(p) {
7519
+ minPriority = p;
7520
+ if (runner) {
7521
+ runner.forceMinPriority(p);
7522
+ }
7523
+ }
7524
+ };
7525
+ }
7526
+ tryStrategy(strategy, minPriority, options, callback) {
7527
+ var timer = null;
7528
+ var runner = null;
7529
+ if (options.timeout > 0) {
7530
+ timer = new timers_OneOffTimer(options.timeout, function() {
7531
+ runner.abort();
7532
+ callback(true);
7533
+ });
7534
+ }
7535
+ runner = strategy.connect(minPriority, function(error, handshake) {
7536
+ if (error && timer && timer.isRunning() && !options.failFast) {
7537
+ return;
7538
+ }
7539
+ if (timer) {
7540
+ timer.ensureAborted();
7541
+ }
7542
+ callback(error, handshake);
7543
+ });
7544
+ return {
7545
+ abort: function() {
7546
+ if (timer) {
7547
+ timer.ensureAborted();
7548
+ }
7549
+ runner.abort();
7550
+ },
7551
+ forceMinPriority: function(p) {
7552
+ runner.forceMinPriority(p);
7553
+ }
7554
+ };
7555
+ }
7556
+ }
7557
+ class best_connected_ever_strategy_BestConnectedEverStrategy {
7558
+ constructor(strategies) {
7559
+ this.strategies = strategies;
7560
+ }
7561
+ isSupported() {
7562
+ return any(this.strategies, util.method("isSupported"));
7563
+ }
7564
+ connect(minPriority, callback) {
7565
+ return connect(this.strategies, minPriority, function(i, runners) {
7566
+ return function(error, handshake) {
7567
+ runners[i].error = error;
7568
+ if (error) {
7569
+ if (allRunnersFailed(runners)) {
7570
+ callback(true);
7571
+ }
7572
+ return;
7573
+ }
7574
+ apply(runners, function(runner) {
7575
+ runner.forceMinPriority(handshake.transport.priority);
7576
+ });
7577
+ callback(null, handshake);
7578
+ };
7579
+ });
7580
+ }
7581
+ }
7582
+ function connect(strategies, minPriority, callbackBuilder) {
7583
+ var runners = map(strategies, function(strategy, i, _2, rs) {
7584
+ return strategy.connect(minPriority, callbackBuilder(i, rs));
7585
+ });
7586
+ return {
7587
+ abort: function() {
7588
+ apply(runners, abortRunner);
7589
+ },
7590
+ forceMinPriority: function(p) {
7591
+ apply(runners, function(runner) {
7592
+ runner.forceMinPriority(p);
7593
+ });
7594
+ }
7595
+ };
7596
+ }
7597
+ function allRunnersFailed(runners) {
7598
+ return collections_all(runners, function(runner) {
7599
+ return Boolean(runner.error);
7600
+ });
7601
+ }
7602
+ function abortRunner(runner) {
7603
+ if (!runner.error && !runner.aborted) {
7604
+ runner.abort();
7605
+ runner.aborted = true;
7606
+ }
7607
+ }
7608
+ class websocket_prioritized_cached_strategy_WebSocketPrioritizedCachedStrategy {
7609
+ constructor(strategy, transports2, options) {
7610
+ this.strategy = strategy;
7611
+ this.transports = transports2;
7612
+ this.ttl = options.ttl || 1800 * 1e3;
7613
+ this.usingTLS = options.useTLS;
7614
+ this.timeline = options.timeline;
7615
+ }
7616
+ isSupported() {
7617
+ return this.strategy.isSupported();
7618
+ }
7619
+ connect(minPriority, callback) {
7620
+ var usingTLS = this.usingTLS;
7621
+ var info = fetchTransportCache(usingTLS);
7622
+ var cacheSkipCount = info && info.cacheSkipCount ? info.cacheSkipCount : 0;
7623
+ var strategies = [this.strategy];
7624
+ if (info && info.timestamp + this.ttl >= util.now()) {
7625
+ var transport = this.transports[info.transport];
7626
+ if (transport) {
7627
+ if (["ws", "wss"].includes(info.transport) || cacheSkipCount > 3) {
7628
+ this.timeline.info({
7629
+ cached: true,
7630
+ transport: info.transport,
7631
+ latency: info.latency
7632
+ });
7633
+ strategies.push(new sequential_strategy_SequentialStrategy([transport], {
7634
+ timeout: info.latency * 2 + 1e3,
7635
+ failFast: true
7636
+ }));
7637
+ } else {
7638
+ cacheSkipCount++;
7639
+ }
7640
+ }
7641
+ }
7642
+ var startTimestamp = util.now();
7643
+ var runner = strategies.pop().connect(minPriority, function cb(error, handshake) {
7644
+ if (error) {
7645
+ flushTransportCache(usingTLS);
7646
+ if (strategies.length > 0) {
7647
+ startTimestamp = util.now();
7648
+ runner = strategies.pop().connect(minPriority, cb);
7649
+ } else {
7650
+ callback(error);
7651
+ }
7652
+ } else {
7653
+ storeTransportCache(usingTLS, handshake.transport.name, util.now() - startTimestamp, cacheSkipCount);
7654
+ callback(null, handshake);
7655
+ }
7656
+ });
7657
+ return {
7658
+ abort: function() {
7659
+ runner.abort();
7660
+ },
7661
+ forceMinPriority: function(p) {
7662
+ minPriority = p;
7663
+ if (runner) {
7664
+ runner.forceMinPriority(p);
7665
+ }
7666
+ }
7667
+ };
7668
+ }
7669
+ }
7670
+ function getTransportCacheKey(usingTLS) {
7671
+ return "pusherTransport" + (usingTLS ? "TLS" : "NonTLS");
7672
+ }
7673
+ function fetchTransportCache(usingTLS) {
7674
+ var storage = runtime.getLocalStorage();
7675
+ if (storage) {
7676
+ try {
7677
+ var serializedCache = storage[getTransportCacheKey(usingTLS)];
7678
+ if (serializedCache) {
7679
+ return JSON.parse(serializedCache);
7680
+ }
7681
+ } catch (e) {
7682
+ flushTransportCache(usingTLS);
7683
+ }
7684
+ }
7685
+ return null;
7686
+ }
7687
+ function storeTransportCache(usingTLS, transport, latency, cacheSkipCount) {
7688
+ var storage = runtime.getLocalStorage();
7689
+ if (storage) {
7690
+ try {
7691
+ storage[getTransportCacheKey(usingTLS)] = safeJSONStringify({
7692
+ timestamp: util.now(),
7693
+ transport,
7694
+ latency,
7695
+ cacheSkipCount
7696
+ });
7697
+ } catch (e) {
7698
+ }
7699
+ }
7700
+ }
7701
+ function flushTransportCache(usingTLS) {
7702
+ var storage = runtime.getLocalStorage();
7703
+ if (storage) {
7704
+ try {
7705
+ delete storage[getTransportCacheKey(usingTLS)];
7706
+ } catch (e) {
7707
+ }
7708
+ }
7709
+ }
7710
+ class delayed_strategy_DelayedStrategy {
7711
+ constructor(strategy, { delay: number }) {
7712
+ this.strategy = strategy;
7713
+ this.options = { delay: number };
7714
+ }
7715
+ isSupported() {
7716
+ return this.strategy.isSupported();
7717
+ }
7718
+ connect(minPriority, callback) {
7719
+ var strategy = this.strategy;
7720
+ var runner;
7721
+ var timer = new timers_OneOffTimer(this.options.delay, function() {
7722
+ runner = strategy.connect(minPriority, callback);
7723
+ });
7724
+ return {
7725
+ abort: function() {
7726
+ timer.ensureAborted();
7727
+ if (runner) {
7728
+ runner.abort();
7729
+ }
7730
+ },
7731
+ forceMinPriority: function(p) {
7732
+ minPriority = p;
7733
+ if (runner) {
7734
+ runner.forceMinPriority(p);
7735
+ }
7736
+ }
7737
+ };
7738
+ }
7739
+ }
7740
+ class IfStrategy {
7741
+ constructor(test, trueBranch, falseBranch) {
7742
+ this.test = test;
7743
+ this.trueBranch = trueBranch;
7744
+ this.falseBranch = falseBranch;
7745
+ }
7746
+ isSupported() {
7747
+ var branch = this.test() ? this.trueBranch : this.falseBranch;
7748
+ return branch.isSupported();
7749
+ }
7750
+ connect(minPriority, callback) {
7751
+ var branch = this.test() ? this.trueBranch : this.falseBranch;
7752
+ return branch.connect(minPriority, callback);
7753
+ }
7754
+ }
7755
+ class FirstConnectedStrategy {
7756
+ constructor(strategy) {
7757
+ this.strategy = strategy;
7758
+ }
7759
+ isSupported() {
7760
+ return this.strategy.isSupported();
7761
+ }
7762
+ connect(minPriority, callback) {
7763
+ var runner = this.strategy.connect(minPriority, function(error, handshake) {
7764
+ if (handshake) {
7765
+ runner.abort();
7766
+ }
7767
+ callback(error, handshake);
7768
+ });
7769
+ return runner;
7770
+ }
7771
+ }
7772
+ function testSupportsStrategy(strategy) {
7773
+ return function() {
7774
+ return strategy.isSupported();
7775
+ };
7776
+ }
7777
+ var getDefaultStrategy = function(config, baseOptions, defineTransport) {
7778
+ var definedTransports = {};
7779
+ function defineTransportStrategy(name, type, priority, options, manager) {
7780
+ var transport = defineTransport(config, name, type, priority, options, manager);
7781
+ definedTransports[name] = transport;
7782
+ return transport;
7783
+ }
7784
+ var ws_options = Object.assign({}, baseOptions, {
7785
+ hostNonTLS: config.wsHost + ":" + config.wsPort,
7786
+ hostTLS: config.wsHost + ":" + config.wssPort,
7787
+ httpPath: config.wsPath
7788
+ });
7789
+ var wss_options = Object.assign({}, ws_options, {
7790
+ useTLS: true
7791
+ });
7792
+ var sockjs_options = Object.assign({}, baseOptions, {
7793
+ hostNonTLS: config.httpHost + ":" + config.httpPort,
7794
+ hostTLS: config.httpHost + ":" + config.httpsPort,
7795
+ httpPath: config.httpPath
7796
+ });
7797
+ var timeouts = {
7798
+ loop: true,
7799
+ timeout: 15e3,
7800
+ timeoutLimit: 6e4
7801
+ };
7802
+ var ws_manager = new transport_manager_TransportManager({
7803
+ minPingDelay: 1e4,
7804
+ maxPingDelay: config.activityTimeout
7805
+ });
7806
+ var streaming_manager = new transport_manager_TransportManager({
7807
+ lives: 2,
7808
+ minPingDelay: 1e4,
7809
+ maxPingDelay: config.activityTimeout
7810
+ });
7811
+ var ws_transport = defineTransportStrategy("ws", "ws", 3, ws_options, ws_manager);
7812
+ var wss_transport = defineTransportStrategy("wss", "ws", 3, wss_options, ws_manager);
7813
+ var sockjs_transport = defineTransportStrategy("sockjs", "sockjs", 1, sockjs_options);
7814
+ var xhr_streaming_transport = defineTransportStrategy("xhr_streaming", "xhr_streaming", 1, sockjs_options, streaming_manager);
7815
+ var xdr_streaming_transport = defineTransportStrategy("xdr_streaming", "xdr_streaming", 1, sockjs_options, streaming_manager);
7816
+ var xhr_polling_transport = defineTransportStrategy("xhr_polling", "xhr_polling", 1, sockjs_options);
7817
+ var xdr_polling_transport = defineTransportStrategy("xdr_polling", "xdr_polling", 1, sockjs_options);
7818
+ var ws_loop = new sequential_strategy_SequentialStrategy([ws_transport], timeouts);
7819
+ var wss_loop = new sequential_strategy_SequentialStrategy([wss_transport], timeouts);
7820
+ var sockjs_loop = new sequential_strategy_SequentialStrategy([sockjs_transport], timeouts);
7821
+ var streaming_loop = new sequential_strategy_SequentialStrategy([
7822
+ new IfStrategy(testSupportsStrategy(xhr_streaming_transport), xhr_streaming_transport, xdr_streaming_transport)
7823
+ ], timeouts);
7824
+ var polling_loop = new sequential_strategy_SequentialStrategy([
7825
+ new IfStrategy(testSupportsStrategy(xhr_polling_transport), xhr_polling_transport, xdr_polling_transport)
7826
+ ], timeouts);
7827
+ var http_loop = new sequential_strategy_SequentialStrategy([
7828
+ new IfStrategy(testSupportsStrategy(streaming_loop), new best_connected_ever_strategy_BestConnectedEverStrategy([
7829
+ streaming_loop,
7830
+ new delayed_strategy_DelayedStrategy(polling_loop, { delay: 4e3 })
7831
+ ]), polling_loop)
7832
+ ], timeouts);
7833
+ var http_fallback_loop = new IfStrategy(testSupportsStrategy(http_loop), http_loop, sockjs_loop);
7834
+ var wsStrategy;
7835
+ if (baseOptions.useTLS) {
7836
+ wsStrategy = new best_connected_ever_strategy_BestConnectedEverStrategy([
7837
+ ws_loop,
7838
+ new delayed_strategy_DelayedStrategy(http_fallback_loop, { delay: 2e3 })
7839
+ ]);
7840
+ } else {
7841
+ wsStrategy = new best_connected_ever_strategy_BestConnectedEverStrategy([
7842
+ ws_loop,
7843
+ new delayed_strategy_DelayedStrategy(wss_loop, { delay: 2e3 }),
7844
+ new delayed_strategy_DelayedStrategy(http_fallback_loop, { delay: 5e3 })
7845
+ ]);
7846
+ }
7847
+ return new websocket_prioritized_cached_strategy_WebSocketPrioritizedCachedStrategy(new FirstConnectedStrategy(new IfStrategy(testSupportsStrategy(ws_transport), wsStrategy, http_fallback_loop)), definedTransports, {
7848
+ ttl: 18e5,
7849
+ timeline: baseOptions.timeline,
7850
+ useTLS: baseOptions.useTLS
7851
+ });
7852
+ };
7853
+ var default_strategy = getDefaultStrategy;
7854
+ var transport_connection_initializer = function() {
7855
+ var self = this;
7856
+ self.timeline.info(self.buildTimelineMessage({
7857
+ transport: self.name + (self.options.useTLS ? "s" : "")
7858
+ }));
7859
+ if (self.hooks.isInitialized()) {
7860
+ self.changeState("initialized");
7861
+ } else if (self.hooks.file) {
7862
+ self.changeState("initializing");
7863
+ Dependencies.load(self.hooks.file, { useTLS: self.options.useTLS }, function(error, callback) {
7864
+ if (self.hooks.isInitialized()) {
7865
+ self.changeState("initialized");
7866
+ callback(true);
7867
+ } else {
7868
+ if (error) {
7869
+ self.onError(error);
7870
+ }
7871
+ self.onClose();
7872
+ callback(false);
7873
+ }
7874
+ });
7875
+ } else {
7876
+ self.onClose();
7877
+ }
7878
+ };
7879
+ var http_xdomain_request_hooks = {
7880
+ getRequest: function(socket) {
7881
+ var xdr = new window.XDomainRequest();
7882
+ xdr.ontimeout = function() {
7883
+ socket.emit("error", new RequestTimedOut());
7884
+ socket.close();
7885
+ };
7886
+ xdr.onerror = function(e) {
7887
+ socket.emit("error", e);
7888
+ socket.close();
7889
+ };
7890
+ xdr.onprogress = function() {
7891
+ if (xdr.responseText && xdr.responseText.length > 0) {
7892
+ socket.onChunk(200, xdr.responseText);
7893
+ }
7894
+ };
7895
+ xdr.onload = function() {
7896
+ if (xdr.responseText && xdr.responseText.length > 0) {
7897
+ socket.onChunk(200, xdr.responseText);
7898
+ }
7899
+ socket.emit("finished", 200);
7900
+ socket.close();
7901
+ };
7902
+ return xdr;
7903
+ },
7904
+ abortRequest: function(xdr) {
7905
+ xdr.ontimeout = xdr.onerror = xdr.onprogress = xdr.onload = null;
7906
+ xdr.abort();
7907
+ }
7908
+ };
7909
+ var http_xdomain_request = http_xdomain_request_hooks;
7910
+ const MAX_BUFFER_LENGTH = 256 * 1024;
7911
+ class http_request_HTTPRequest extends dispatcher_Dispatcher {
7912
+ constructor(hooks, method, url) {
7913
+ super();
7914
+ this.hooks = hooks;
7915
+ this.method = method;
7916
+ this.url = url;
7917
+ }
7918
+ start(payload) {
7919
+ this.position = 0;
7920
+ this.xhr = this.hooks.getRequest(this);
7921
+ this.unloader = () => {
7922
+ this.close();
7923
+ };
7924
+ runtime.addUnloadListener(this.unloader);
7925
+ this.xhr.open(this.method, this.url, true);
7926
+ if (this.xhr.setRequestHeader) {
7927
+ this.xhr.setRequestHeader("Content-Type", "application/json");
7928
+ }
7929
+ this.xhr.send(payload);
7930
+ }
7931
+ close() {
7932
+ if (this.unloader) {
7933
+ runtime.removeUnloadListener(this.unloader);
7934
+ this.unloader = null;
7935
+ }
7936
+ if (this.xhr) {
7937
+ this.hooks.abortRequest(this.xhr);
7938
+ this.xhr = null;
7939
+ }
7940
+ }
7941
+ onChunk(status, data) {
7942
+ while (true) {
7943
+ var chunk = this.advanceBuffer(data);
7944
+ if (chunk) {
7945
+ this.emit("chunk", { status, data: chunk });
7946
+ } else {
7947
+ break;
7948
+ }
7949
+ }
7950
+ if (this.isBufferTooLong(data)) {
7951
+ this.emit("buffer_too_long");
7952
+ }
7953
+ }
7954
+ advanceBuffer(buffer) {
7955
+ var unreadData = buffer.slice(this.position);
7956
+ var endOfLinePosition = unreadData.indexOf("\n");
7957
+ if (endOfLinePosition !== -1) {
7958
+ this.position += endOfLinePosition + 1;
7959
+ return unreadData.slice(0, endOfLinePosition);
7960
+ } else {
7961
+ return null;
7962
+ }
7963
+ }
7964
+ isBufferTooLong(buffer) {
7965
+ return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH;
7966
+ }
7967
+ }
7968
+ var State2;
7969
+ (function(State3) {
7970
+ State3[State3["CONNECTING"] = 0] = "CONNECTING";
7971
+ State3[State3["OPEN"] = 1] = "OPEN";
7972
+ State3[State3["CLOSED"] = 3] = "CLOSED";
7973
+ })(State2 || (State2 = {}));
7974
+ var state = State2;
7975
+ var autoIncrement = 1;
7976
+ class http_socket_HTTPSocket {
7977
+ constructor(hooks, url) {
7978
+ this.hooks = hooks;
7979
+ this.session = randomNumber(1e3) + "/" + randomString(8);
7980
+ this.location = getLocation(url);
7981
+ this.readyState = state.CONNECTING;
7982
+ this.openStream();
7983
+ }
7984
+ send(payload) {
7985
+ return this.sendRaw(JSON.stringify([payload]));
7986
+ }
7987
+ ping() {
7988
+ this.hooks.sendHeartbeat(this);
7989
+ }
7990
+ close(code, reason) {
7991
+ this.onClose(code, reason, true);
7992
+ }
7993
+ sendRaw(payload) {
7994
+ if (this.readyState === state.OPEN) {
7995
+ try {
7996
+ runtime.createSocketRequest("POST", getUniqueURL(getSendURL(this.location, this.session))).start(payload);
7997
+ return true;
7998
+ } catch (e) {
7999
+ return false;
8000
+ }
8001
+ } else {
8002
+ return false;
8003
+ }
8004
+ }
8005
+ reconnect() {
8006
+ this.closeStream();
8007
+ this.openStream();
8008
+ }
8009
+ onClose(code, reason, wasClean) {
8010
+ this.closeStream();
8011
+ this.readyState = state.CLOSED;
8012
+ if (this.onclose) {
8013
+ this.onclose({
8014
+ code,
8015
+ reason,
8016
+ wasClean
8017
+ });
8018
+ }
8019
+ }
8020
+ onChunk(chunk) {
8021
+ if (chunk.status !== 200) {
8022
+ return;
8023
+ }
8024
+ if (this.readyState === state.OPEN) {
8025
+ this.onActivity();
8026
+ }
8027
+ var payload;
8028
+ var type = chunk.data.slice(0, 1);
8029
+ switch (type) {
8030
+ case "o":
8031
+ payload = JSON.parse(chunk.data.slice(1) || "{}");
8032
+ this.onOpen(payload);
8033
+ break;
8034
+ case "a":
8035
+ payload = JSON.parse(chunk.data.slice(1) || "[]");
8036
+ for (var i = 0; i < payload.length; i++) {
8037
+ this.onEvent(payload[i]);
8038
+ }
8039
+ break;
8040
+ case "m":
8041
+ payload = JSON.parse(chunk.data.slice(1) || "null");
8042
+ this.onEvent(payload);
8043
+ break;
8044
+ case "h":
8045
+ this.hooks.onHeartbeat(this);
8046
+ break;
8047
+ case "c":
8048
+ payload = JSON.parse(chunk.data.slice(1) || "[]");
8049
+ this.onClose(payload[0], payload[1], true);
8050
+ break;
8051
+ }
8052
+ }
8053
+ onOpen(options) {
8054
+ if (this.readyState === state.CONNECTING) {
8055
+ if (options && options.hostname) {
8056
+ this.location.base = replaceHost(this.location.base, options.hostname);
8057
+ }
8058
+ this.readyState = state.OPEN;
8059
+ if (this.onopen) {
8060
+ this.onopen();
8061
+ }
8062
+ } else {
8063
+ this.onClose(1006, "Server lost session", true);
8064
+ }
8065
+ }
8066
+ onEvent(event) {
8067
+ if (this.readyState === state.OPEN && this.onmessage) {
8068
+ this.onmessage({ data: event });
8069
+ }
8070
+ }
8071
+ onActivity() {
8072
+ if (this.onactivity) {
8073
+ this.onactivity();
8074
+ }
8075
+ }
8076
+ onError(error) {
8077
+ if (this.onerror) {
8078
+ this.onerror(error);
8079
+ }
8080
+ }
8081
+ openStream() {
8082
+ this.stream = runtime.createSocketRequest("POST", getUniqueURL(this.hooks.getReceiveURL(this.location, this.session)));
8083
+ this.stream.bind("chunk", (chunk) => {
8084
+ this.onChunk(chunk);
8085
+ });
8086
+ this.stream.bind("finished", (status) => {
8087
+ this.hooks.onFinished(this, status);
8088
+ });
8089
+ this.stream.bind("buffer_too_long", () => {
8090
+ this.reconnect();
8091
+ });
8092
+ try {
8093
+ this.stream.start();
8094
+ } catch (error) {
8095
+ util.defer(() => {
8096
+ this.onError(error);
8097
+ this.onClose(1006, "Could not start streaming", false);
8098
+ });
8099
+ }
8100
+ }
8101
+ closeStream() {
8102
+ if (this.stream) {
8103
+ this.stream.unbind_all();
8104
+ this.stream.close();
8105
+ this.stream = null;
8106
+ }
8107
+ }
8108
+ }
8109
+ function getLocation(url) {
8110
+ var parts = /([^\?]*)\/*(\??.*)/.exec(url);
8111
+ return {
8112
+ base: parts[1],
8113
+ queryString: parts[2]
8114
+ };
8115
+ }
8116
+ function getSendURL(url, session) {
8117
+ return url.base + "/" + session + "/xhr_send";
8118
+ }
8119
+ function getUniqueURL(url) {
8120
+ var separator = url.indexOf("?") === -1 ? "?" : "&";
8121
+ return url + separator + "t=" + +/* @__PURE__ */ new Date() + "&n=" + autoIncrement++;
8122
+ }
8123
+ function replaceHost(url, hostname) {
8124
+ var urlParts = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(url);
8125
+ return urlParts[1] + hostname + urlParts[3];
8126
+ }
8127
+ function randomNumber(max) {
8128
+ return runtime.randomInt(max);
8129
+ }
8130
+ function randomString(length) {
8131
+ var result = [];
8132
+ for (var i = 0; i < length; i++) {
8133
+ result.push(randomNumber(32).toString(32));
8134
+ }
8135
+ return result.join("");
8136
+ }
8137
+ var http_socket = http_socket_HTTPSocket;
8138
+ var http_streaming_socket_hooks = {
8139
+ getReceiveURL: function(url, session) {
8140
+ return url.base + "/" + session + "/xhr_streaming" + url.queryString;
8141
+ },
8142
+ onHeartbeat: function(socket) {
8143
+ socket.sendRaw("[]");
8144
+ },
8145
+ sendHeartbeat: function(socket) {
8146
+ socket.sendRaw("[]");
8147
+ },
8148
+ onFinished: function(socket, status) {
8149
+ socket.onClose(1006, "Connection interrupted (" + status + ")", false);
8150
+ }
8151
+ };
8152
+ var http_streaming_socket = http_streaming_socket_hooks;
8153
+ var http_polling_socket_hooks = {
8154
+ getReceiveURL: function(url, session) {
8155
+ return url.base + "/" + session + "/xhr" + url.queryString;
8156
+ },
8157
+ onHeartbeat: function() {
8158
+ },
8159
+ sendHeartbeat: function(socket) {
8160
+ socket.sendRaw("[]");
8161
+ },
8162
+ onFinished: function(socket, status) {
8163
+ if (status === 200) {
8164
+ socket.reconnect();
8165
+ } else {
8166
+ socket.onClose(1006, "Connection interrupted (" + status + ")", false);
8167
+ }
8168
+ }
8169
+ };
8170
+ var http_polling_socket = http_polling_socket_hooks;
8171
+ var http_xhr_request_hooks = {
8172
+ getRequest: function(socket) {
8173
+ var Constructor = runtime.getXHRAPI();
8174
+ var xhr = new Constructor();
8175
+ xhr.onreadystatechange = xhr.onprogress = function() {
8176
+ switch (xhr.readyState) {
8177
+ case 3:
8178
+ if (xhr.responseText && xhr.responseText.length > 0) {
8179
+ socket.onChunk(xhr.status, xhr.responseText);
8180
+ }
8181
+ break;
8182
+ case 4:
8183
+ if (xhr.responseText && xhr.responseText.length > 0) {
8184
+ socket.onChunk(xhr.status, xhr.responseText);
8185
+ }
8186
+ socket.emit("finished", xhr.status);
8187
+ socket.close();
8188
+ break;
8189
+ }
8190
+ };
8191
+ return xhr;
8192
+ },
8193
+ abortRequest: function(xhr) {
8194
+ xhr.onreadystatechange = null;
8195
+ xhr.abort();
8196
+ }
8197
+ };
8198
+ var http_xhr_request = http_xhr_request_hooks;
8199
+ var HTTP = {
8200
+ createStreamingSocket(url) {
8201
+ return this.createSocket(http_streaming_socket, url);
8202
+ },
8203
+ createPollingSocket(url) {
8204
+ return this.createSocket(http_polling_socket, url);
8205
+ },
8206
+ createSocket(hooks, url) {
8207
+ return new http_socket(hooks, url);
8208
+ },
8209
+ createXHR(method, url) {
8210
+ return this.createRequest(http_xhr_request, method, url);
8211
+ },
8212
+ createRequest(hooks, method, url) {
8213
+ return new http_request_HTTPRequest(hooks, method, url);
8214
+ }
8215
+ };
8216
+ var http_http = HTTP;
8217
+ http_http.createXDR = function(method, url) {
8218
+ return this.createRequest(http_xdomain_request, method, url);
8219
+ };
8220
+ var web_http_http = http_http;
8221
+ var Runtime = {
8222
+ nextAuthCallbackID: 1,
8223
+ auth_callbacks: {},
8224
+ ScriptReceivers,
8225
+ DependenciesReceivers,
8226
+ getDefaultStrategy: default_strategy,
8227
+ Transports: transports_transports,
8228
+ transportConnectionInitializer: transport_connection_initializer,
8229
+ HTTPFactory: web_http_http,
8230
+ TimelineTransport: jsonp_timeline,
8231
+ getXHRAPI() {
8232
+ return window.XMLHttpRequest;
8233
+ },
8234
+ getWebSocketAPI() {
8235
+ return window.WebSocket || window.MozWebSocket;
8236
+ },
8237
+ setup(PusherClass) {
8238
+ window.Pusher = PusherClass;
8239
+ var initializeOnDocumentBody = () => {
8240
+ this.onDocumentBody(PusherClass.ready);
8241
+ };
8242
+ if (!window.JSON) {
8243
+ Dependencies.load("json2", {}, initializeOnDocumentBody);
8244
+ } else {
8245
+ initializeOnDocumentBody();
8246
+ }
8247
+ },
8248
+ getDocument() {
8249
+ return document;
8250
+ },
8251
+ getProtocol() {
8252
+ return this.getDocument().location.protocol;
8253
+ },
8254
+ getAuthorizers() {
8255
+ return { ajax: xhr_auth, jsonp: jsonp_auth };
8256
+ },
8257
+ onDocumentBody(callback) {
8258
+ if (document.body) {
8259
+ callback();
8260
+ } else {
8261
+ setTimeout(() => {
8262
+ this.onDocumentBody(callback);
8263
+ }, 0);
8264
+ }
8265
+ },
8266
+ createJSONPRequest(url, data) {
8267
+ return new jsonp_request_JSONPRequest(url, data);
8268
+ },
8269
+ createScriptRequest(src) {
8270
+ return new ScriptRequest(src);
8271
+ },
8272
+ getLocalStorage() {
8273
+ try {
8274
+ return window.localStorage;
8275
+ } catch (e) {
8276
+ return void 0;
8277
+ }
8278
+ },
8279
+ createXHR() {
8280
+ if (this.getXHRAPI()) {
8281
+ return this.createXMLHttpRequest();
8282
+ } else {
8283
+ return this.createMicrosoftXHR();
8284
+ }
8285
+ },
8286
+ createXMLHttpRequest() {
8287
+ var Constructor = this.getXHRAPI();
8288
+ return new Constructor();
8289
+ },
8290
+ createMicrosoftXHR() {
8291
+ return new ActiveXObject("Microsoft.XMLHTTP");
8292
+ },
8293
+ getNetwork() {
8294
+ return net_info_Network;
8295
+ },
8296
+ createWebSocket(url) {
8297
+ var Constructor = this.getWebSocketAPI();
8298
+ return new Constructor(url);
8299
+ },
8300
+ createSocketRequest(method, url) {
8301
+ if (this.isXHRSupported()) {
8302
+ return this.HTTPFactory.createXHR(method, url);
8303
+ } else if (this.isXDRSupported(url.indexOf("https:") === 0)) {
8304
+ return this.HTTPFactory.createXDR(method, url);
8305
+ } else {
8306
+ throw "Cross-origin HTTP requests are not supported";
8307
+ }
8308
+ },
8309
+ isXHRSupported() {
8310
+ var Constructor = this.getXHRAPI();
8311
+ return Boolean(Constructor) && new Constructor().withCredentials !== void 0;
8312
+ },
8313
+ isXDRSupported(useTLS) {
8314
+ var protocol = useTLS ? "https:" : "http:";
8315
+ var documentProtocol = this.getProtocol();
8316
+ return Boolean(window["XDomainRequest"]) && documentProtocol === protocol;
8317
+ },
8318
+ addUnloadListener(listener) {
8319
+ if (window.addEventListener !== void 0) {
8320
+ window.addEventListener("unload", listener, false);
8321
+ } else if (window.attachEvent !== void 0) {
8322
+ window.attachEvent("onunload", listener);
8323
+ }
8324
+ },
8325
+ removeUnloadListener(listener) {
8326
+ if (window.addEventListener !== void 0) {
8327
+ window.removeEventListener("unload", listener, false);
8328
+ } else if (window.detachEvent !== void 0) {
8329
+ window.detachEvent("onunload", listener);
8330
+ }
8331
+ },
8332
+ randomInt(max) {
8333
+ const random = function() {
8334
+ const crypto = window.crypto || window["msCrypto"];
8335
+ const random2 = crypto.getRandomValues(new Uint32Array(1))[0];
8336
+ return random2 / Math.pow(2, 32);
8337
+ };
8338
+ return Math.floor(random() * max);
8339
+ }
8340
+ };
8341
+ var runtime = Runtime;
8342
+ var TimelineLevel;
8343
+ (function(TimelineLevel2) {
8344
+ TimelineLevel2[TimelineLevel2["ERROR"] = 3] = "ERROR";
8345
+ TimelineLevel2[TimelineLevel2["INFO"] = 6] = "INFO";
8346
+ TimelineLevel2[TimelineLevel2["DEBUG"] = 7] = "DEBUG";
8347
+ })(TimelineLevel || (TimelineLevel = {}));
8348
+ var timeline_level = TimelineLevel;
8349
+ class timeline_Timeline {
8350
+ constructor(key, session, options) {
8351
+ this.key = key;
8352
+ this.session = session;
8353
+ this.events = [];
8354
+ this.options = options || {};
8355
+ this.sent = 0;
8356
+ this.uniqueID = 0;
8357
+ }
8358
+ log(level, event) {
8359
+ if (level <= this.options.level) {
8360
+ this.events.push(extend({}, event, { timestamp: util.now() }));
8361
+ if (this.options.limit && this.events.length > this.options.limit) {
8362
+ this.events.shift();
8363
+ }
8364
+ }
8365
+ }
8366
+ error(event) {
8367
+ this.log(timeline_level.ERROR, event);
8368
+ }
8369
+ info(event) {
8370
+ this.log(timeline_level.INFO, event);
8371
+ }
8372
+ debug(event) {
8373
+ this.log(timeline_level.DEBUG, event);
8374
+ }
8375
+ isEmpty() {
8376
+ return this.events.length === 0;
8377
+ }
8378
+ send(sendfn, callback) {
8379
+ var data = extend({
8380
+ session: this.session,
8381
+ bundle: this.sent + 1,
8382
+ key: this.key,
8383
+ lib: "js",
8384
+ version: this.options.version,
8385
+ cluster: this.options.cluster,
8386
+ features: this.options.features,
8387
+ timeline: this.events
8388
+ }, this.options.params);
8389
+ this.events = [];
8390
+ sendfn(data, (error, result) => {
8391
+ if (!error) {
8392
+ this.sent++;
8393
+ }
8394
+ if (callback) {
8395
+ callback(error, result);
8396
+ }
8397
+ });
8398
+ return true;
8399
+ }
8400
+ generateUniqueID() {
8401
+ this.uniqueID++;
8402
+ return this.uniqueID;
8403
+ }
8404
+ }
8405
+ class transport_strategy_TransportStrategy {
8406
+ constructor(name, priority, transport, options) {
8407
+ this.name = name;
8408
+ this.priority = priority;
8409
+ this.transport = transport;
8410
+ this.options = options || {};
8411
+ }
8412
+ isSupported() {
8413
+ return this.transport.isSupported({
8414
+ useTLS: this.options.useTLS
8415
+ });
8416
+ }
8417
+ connect(minPriority, callback) {
8418
+ if (!this.isSupported()) {
8419
+ return failAttempt(new UnsupportedStrategy(), callback);
8420
+ } else if (this.priority < minPriority) {
8421
+ return failAttempt(new TransportPriorityTooLow(), callback);
8422
+ }
8423
+ var connected = false;
8424
+ var transport = this.transport.createConnection(this.name, this.priority, this.options.key, this.options);
8425
+ var handshake = null;
8426
+ var onInitialized = function() {
8427
+ transport.unbind("initialized", onInitialized);
8428
+ transport.connect();
8429
+ };
8430
+ var onOpen = function() {
8431
+ handshake = factory.createHandshake(transport, function(result) {
8432
+ connected = true;
8433
+ unbindListeners();
8434
+ callback(null, result);
8435
+ });
8436
+ };
8437
+ var onError = function(error) {
8438
+ unbindListeners();
8439
+ callback(error);
8440
+ };
8441
+ var onClosed = function() {
8442
+ unbindListeners();
8443
+ var serializedTransport;
8444
+ serializedTransport = safeJSONStringify(transport);
8445
+ callback(new TransportClosed(serializedTransport));
8446
+ };
8447
+ var unbindListeners = function() {
8448
+ transport.unbind("initialized", onInitialized);
8449
+ transport.unbind("open", onOpen);
8450
+ transport.unbind("error", onError);
8451
+ transport.unbind("closed", onClosed);
8452
+ };
8453
+ transport.bind("initialized", onInitialized);
8454
+ transport.bind("open", onOpen);
8455
+ transport.bind("error", onError);
8456
+ transport.bind("closed", onClosed);
8457
+ transport.initialize();
8458
+ return {
8459
+ abort: () => {
8460
+ if (connected) {
8461
+ return;
8462
+ }
8463
+ unbindListeners();
8464
+ if (handshake) {
8465
+ handshake.close();
8466
+ } else {
8467
+ transport.close();
8468
+ }
8469
+ },
8470
+ forceMinPriority: (p) => {
8471
+ if (connected) {
8472
+ return;
8473
+ }
8474
+ if (this.priority < p) {
8475
+ if (handshake) {
8476
+ handshake.close();
8477
+ } else {
8478
+ transport.close();
8479
+ }
8480
+ }
8481
+ }
8482
+ };
8483
+ }
8484
+ }
8485
+ function failAttempt(error, callback) {
8486
+ util.defer(function() {
8487
+ callback(error);
8488
+ });
8489
+ return {
8490
+ abort: function() {
8491
+ },
8492
+ forceMinPriority: function() {
8493
+ }
8494
+ };
8495
+ }
8496
+ const { Transports: strategy_builder_Transports } = runtime;
8497
+ var strategy_builder_defineTransport = function(config, name, type, priority, options, manager) {
8498
+ var transportClass = strategy_builder_Transports[type];
8499
+ if (!transportClass) {
8500
+ throw new UnsupportedTransport(type);
8501
+ }
8502
+ var enabled = (!config.enabledTransports || arrayIndexOf(config.enabledTransports, name) !== -1) && (!config.disabledTransports || arrayIndexOf(config.disabledTransports, name) === -1);
8503
+ var transport;
8504
+ if (enabled) {
8505
+ options = Object.assign({ ignoreNullOrigin: config.ignoreNullOrigin }, options);
8506
+ transport = new transport_strategy_TransportStrategy(name, priority, manager ? manager.getAssistant(transportClass) : transportClass, options);
8507
+ } else {
8508
+ transport = strategy_builder_UnsupportedStrategy;
8509
+ }
8510
+ return transport;
8511
+ };
8512
+ var strategy_builder_UnsupportedStrategy = {
8513
+ isSupported: function() {
8514
+ return false;
8515
+ },
8516
+ connect: function(_2, callback) {
8517
+ var deferred = util.defer(function() {
8518
+ callback(new UnsupportedStrategy());
8519
+ });
8520
+ return {
8521
+ abort: function() {
8522
+ deferred.ensureAborted();
8523
+ },
8524
+ forceMinPriority: function() {
8525
+ }
8526
+ };
8527
+ }
8528
+ };
8529
+ function validateOptions(options) {
8530
+ if (options == null) {
8531
+ throw "You must pass an options object";
8532
+ }
8533
+ if (options.cluster == null) {
8534
+ throw "Options object must provide a cluster";
8535
+ }
8536
+ if ("disableStats" in options) {
8537
+ logger.warn("The disableStats option is deprecated in favor of enableStats");
8538
+ }
8539
+ }
8540
+ const composeChannelQuery = (params, authOptions) => {
8541
+ var query = "socket_id=" + encodeURIComponent(params.socketId);
8542
+ for (var key in authOptions.params) {
8543
+ query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(authOptions.params[key]);
8544
+ }
8545
+ if (authOptions.paramsProvider != null) {
8546
+ let dynamicParams = authOptions.paramsProvider();
8547
+ for (var key in dynamicParams) {
8548
+ query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dynamicParams[key]);
8549
+ }
8550
+ }
8551
+ return query;
8552
+ };
8553
+ const UserAuthenticator = (authOptions) => {
8554
+ if (typeof runtime.getAuthorizers()[authOptions.transport] === "undefined") {
8555
+ throw `'${authOptions.transport}' is not a recognized auth transport`;
8556
+ }
8557
+ return (params, callback) => {
8558
+ const query = composeChannelQuery(params, authOptions);
8559
+ runtime.getAuthorizers()[authOptions.transport](runtime, query, authOptions, AuthRequestType.UserAuthentication, callback);
8560
+ };
8561
+ };
8562
+ var user_authenticator = UserAuthenticator;
8563
+ const channel_authorizer_composeChannelQuery = (params, authOptions) => {
8564
+ var query = "socket_id=" + encodeURIComponent(params.socketId);
8565
+ query += "&channel_name=" + encodeURIComponent(params.channelName);
8566
+ for (var key in authOptions.params) {
8567
+ query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(authOptions.params[key]);
8568
+ }
8569
+ if (authOptions.paramsProvider != null) {
8570
+ let dynamicParams = authOptions.paramsProvider();
8571
+ for (var key in dynamicParams) {
8572
+ query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dynamicParams[key]);
8573
+ }
8574
+ }
8575
+ return query;
8576
+ };
8577
+ const ChannelAuthorizer = (authOptions) => {
8578
+ if (typeof runtime.getAuthorizers()[authOptions.transport] === "undefined") {
8579
+ throw `'${authOptions.transport}' is not a recognized auth transport`;
8580
+ }
8581
+ return (params, callback) => {
8582
+ const query = channel_authorizer_composeChannelQuery(params, authOptions);
8583
+ runtime.getAuthorizers()[authOptions.transport](runtime, query, authOptions, AuthRequestType.ChannelAuthorization, callback);
8584
+ };
8585
+ };
8586
+ var channel_authorizer = ChannelAuthorizer;
8587
+ const ChannelAuthorizerProxy = (pusher2, authOptions, channelAuthorizerGenerator) => {
8588
+ const deprecatedAuthorizerOptions = {
8589
+ authTransport: authOptions.transport,
8590
+ authEndpoint: authOptions.endpoint,
8591
+ auth: {
8592
+ params: authOptions.params,
8593
+ headers: authOptions.headers
8594
+ }
8595
+ };
8596
+ return (params, callback) => {
8597
+ const channel = pusher2.channel(params.channelName);
8598
+ const channelAuthorizer = channelAuthorizerGenerator(channel, deprecatedAuthorizerOptions);
8599
+ channelAuthorizer.authorize(params.socketId, callback);
8600
+ };
8601
+ };
8602
+ function getConfig2(opts, pusher2) {
8603
+ let config = {
8604
+ activityTimeout: opts.activityTimeout || defaults2.activityTimeout,
8605
+ cluster: opts.cluster,
8606
+ httpPath: opts.httpPath || defaults2.httpPath,
8607
+ httpPort: opts.httpPort || defaults2.httpPort,
8608
+ httpsPort: opts.httpsPort || defaults2.httpsPort,
8609
+ pongTimeout: opts.pongTimeout || defaults2.pongTimeout,
8610
+ statsHost: opts.statsHost || defaults2.stats_host,
8611
+ unavailableTimeout: opts.unavailableTimeout || defaults2.unavailableTimeout,
8612
+ wsPath: opts.wsPath || defaults2.wsPath,
8613
+ wsPort: opts.wsPort || defaults2.wsPort,
8614
+ wssPort: opts.wssPort || defaults2.wssPort,
8615
+ enableStats: getEnableStatsConfig(opts),
8616
+ httpHost: getHttpHost(opts),
8617
+ useTLS: shouldUseTLS(opts),
8618
+ wsHost: getWebsocketHost(opts),
8619
+ userAuthenticator: buildUserAuthenticator(opts),
8620
+ channelAuthorizer: buildChannelAuthorizer(opts, pusher2)
8621
+ };
8622
+ if ("disabledTransports" in opts)
8623
+ config.disabledTransports = opts.disabledTransports;
8624
+ if ("enabledTransports" in opts)
8625
+ config.enabledTransports = opts.enabledTransports;
8626
+ if ("ignoreNullOrigin" in opts)
8627
+ config.ignoreNullOrigin = opts.ignoreNullOrigin;
8628
+ if ("timelineParams" in opts)
8629
+ config.timelineParams = opts.timelineParams;
8630
+ if ("nacl" in opts) {
8631
+ config.nacl = opts.nacl;
8632
+ }
8633
+ return config;
8634
+ }
8635
+ function getHttpHost(opts) {
8636
+ if (opts.httpHost) {
8637
+ return opts.httpHost;
8638
+ }
8639
+ if (opts.cluster) {
8640
+ return `sockjs-${opts.cluster}.pusher.com`;
8641
+ }
8642
+ return defaults2.httpHost;
8643
+ }
8644
+ function getWebsocketHost(opts) {
8645
+ if (opts.wsHost) {
8646
+ return opts.wsHost;
8647
+ }
8648
+ return getWebsocketHostFromCluster(opts.cluster);
8649
+ }
8650
+ function getWebsocketHostFromCluster(cluster) {
8651
+ return `ws-${cluster}.pusher.com`;
8652
+ }
8653
+ function shouldUseTLS(opts) {
8654
+ if (runtime.getProtocol() === "https:") {
8655
+ return true;
8656
+ } else if (opts.forceTLS === false) {
8657
+ return false;
8658
+ }
8659
+ return true;
8660
+ }
8661
+ function getEnableStatsConfig(opts) {
8662
+ if ("enableStats" in opts) {
8663
+ return opts.enableStats;
8664
+ }
8665
+ if ("disableStats" in opts) {
8666
+ return !opts.disableStats;
8667
+ }
8668
+ return false;
8669
+ }
8670
+ function buildUserAuthenticator(opts) {
8671
+ const userAuthentication = Object.assign(Object.assign({}, defaults2.userAuthentication), opts.userAuthentication);
8672
+ if ("customHandler" in userAuthentication && userAuthentication["customHandler"] != null) {
8673
+ return userAuthentication["customHandler"];
8674
+ }
8675
+ return user_authenticator(userAuthentication);
8676
+ }
8677
+ function buildChannelAuth(opts, pusher2) {
8678
+ let channelAuthorization;
8679
+ if ("channelAuthorization" in opts) {
8680
+ channelAuthorization = Object.assign(Object.assign({}, defaults2.channelAuthorization), opts.channelAuthorization);
8681
+ } else {
8682
+ channelAuthorization = {
8683
+ transport: opts.authTransport || defaults2.authTransport,
8684
+ endpoint: opts.authEndpoint || defaults2.authEndpoint
8685
+ };
8686
+ if ("auth" in opts) {
8687
+ if ("params" in opts.auth)
8688
+ channelAuthorization.params = opts.auth.params;
8689
+ if ("headers" in opts.auth)
8690
+ channelAuthorization.headers = opts.auth.headers;
8691
+ }
8692
+ if ("authorizer" in opts)
8693
+ channelAuthorization.customHandler = ChannelAuthorizerProxy(pusher2, channelAuthorization, opts.authorizer);
8694
+ }
8695
+ return channelAuthorization;
8696
+ }
8697
+ function buildChannelAuthorizer(opts, pusher2) {
8698
+ const channelAuthorization = buildChannelAuth(opts, pusher2);
8699
+ if ("customHandler" in channelAuthorization && channelAuthorization["customHandler"] != null) {
8700
+ return channelAuthorization["customHandler"];
8701
+ }
8702
+ return channel_authorizer(channelAuthorization);
8703
+ }
8704
+ class watchlist_WatchlistFacade extends dispatcher_Dispatcher {
8705
+ constructor(pusher2) {
8706
+ super(function(eventName, data) {
8707
+ logger.debug(`No callbacks on watchlist events for ${eventName}`);
8708
+ });
8709
+ this.pusher = pusher2;
8710
+ this.bindWatchlistInternalEvent();
8711
+ }
8712
+ handleEvent(pusherEvent) {
8713
+ pusherEvent.data.events.forEach((watchlistEvent) => {
8714
+ this.emit(watchlistEvent.name, watchlistEvent);
8715
+ });
8716
+ }
8717
+ bindWatchlistInternalEvent() {
8718
+ this.pusher.connection.bind("message", (pusherEvent) => {
8719
+ var eventName = pusherEvent.event;
8720
+ if (eventName === "pusher_internal:watchlist_events") {
8721
+ this.handleEvent(pusherEvent);
8722
+ }
8723
+ });
8724
+ }
8725
+ }
8726
+ function flatPromise() {
8727
+ let resolve, reject;
8728
+ const promise = new Promise((res, rej) => {
8729
+ resolve = res;
8730
+ reject = rej;
8731
+ });
8732
+ return { promise, resolve, reject };
8733
+ }
8734
+ var flat_promise = flatPromise;
8735
+ class user_UserFacade extends dispatcher_Dispatcher {
8736
+ constructor(pusher2) {
8737
+ super(function(eventName, data) {
8738
+ logger.debug("No callbacks on user for " + eventName);
8739
+ });
8740
+ this.signin_requested = false;
8741
+ this.user_data = null;
8742
+ this.serverToUserChannel = null;
8743
+ this.signinDonePromise = null;
8744
+ this._signinDoneResolve = null;
8745
+ this._onAuthorize = (err, authData) => {
8746
+ if (err) {
8747
+ logger.warn(`Error during signin: ${err}`);
8748
+ this._cleanup();
8749
+ return;
8750
+ }
8751
+ this.pusher.send_event("pusher:signin", {
8752
+ auth: authData.auth,
8753
+ user_data: authData.user_data
8754
+ });
8755
+ };
8756
+ this.pusher = pusher2;
8757
+ this.pusher.connection.bind("state_change", ({ previous, current }) => {
8758
+ if (previous !== "connected" && current === "connected") {
8759
+ this._signin();
8760
+ }
8761
+ if (previous === "connected" && current !== "connected") {
8762
+ this._cleanup();
8763
+ this._newSigninPromiseIfNeeded();
8764
+ }
8765
+ });
8766
+ this.watchlist = new watchlist_WatchlistFacade(pusher2);
8767
+ this.pusher.connection.bind("message", (event) => {
8768
+ var eventName = event.event;
8769
+ if (eventName === "pusher:signin_success") {
8770
+ this._onSigninSuccess(event.data);
8771
+ }
8772
+ if (this.serverToUserChannel && this.serverToUserChannel.name === event.channel) {
8773
+ this.serverToUserChannel.handleEvent(event);
8774
+ }
8775
+ });
8776
+ }
8777
+ signin() {
8778
+ if (this.signin_requested) {
8779
+ return;
8780
+ }
8781
+ this.signin_requested = true;
8782
+ this._signin();
8783
+ }
8784
+ _signin() {
8785
+ if (!this.signin_requested) {
8786
+ return;
8787
+ }
8788
+ this._newSigninPromiseIfNeeded();
8789
+ if (this.pusher.connection.state !== "connected") {
8790
+ return;
8791
+ }
8792
+ this.pusher.config.userAuthenticator({
8793
+ socketId: this.pusher.connection.socket_id
8794
+ }, this._onAuthorize);
8795
+ }
8796
+ _onSigninSuccess(data) {
8797
+ try {
8798
+ this.user_data = JSON.parse(data.user_data);
8799
+ } catch (e) {
8800
+ logger.error(`Failed parsing user data after signin: ${data.user_data}`);
8801
+ this._cleanup();
8802
+ return;
8803
+ }
8804
+ if (typeof this.user_data.id !== "string" || this.user_data.id === "") {
8805
+ logger.error(`user_data doesn't contain an id. user_data: ${this.user_data}`);
8806
+ this._cleanup();
8807
+ return;
8808
+ }
8809
+ this._signinDoneResolve();
8810
+ this._subscribeChannels();
8811
+ }
8812
+ _subscribeChannels() {
8813
+ const ensure_subscribed = (channel) => {
8814
+ if (channel.subscriptionPending && channel.subscriptionCancelled) {
8815
+ channel.reinstateSubscription();
8816
+ } else if (!channel.subscriptionPending && this.pusher.connection.state === "connected") {
8817
+ channel.subscribe();
8818
+ }
8819
+ };
8820
+ this.serverToUserChannel = new channel_Channel(`#server-to-user-${this.user_data.id}`, this.pusher);
8821
+ this.serverToUserChannel.bind_global((eventName, data) => {
8822
+ if (eventName.indexOf("pusher_internal:") === 0 || eventName.indexOf("pusher:") === 0) {
8823
+ return;
8824
+ }
8825
+ this.emit(eventName, data);
8826
+ });
8827
+ ensure_subscribed(this.serverToUserChannel);
8828
+ }
8829
+ _cleanup() {
8830
+ this.user_data = null;
8831
+ if (this.serverToUserChannel) {
8832
+ this.serverToUserChannel.unbind_all();
8833
+ this.serverToUserChannel.disconnect();
8834
+ this.serverToUserChannel = null;
8835
+ }
8836
+ if (this.signin_requested) {
8837
+ this._signinDoneResolve();
8838
+ }
8839
+ }
8840
+ _newSigninPromiseIfNeeded() {
8841
+ if (!this.signin_requested) {
8842
+ return;
8843
+ }
8844
+ if (this.signinDonePromise && !this.signinDonePromise.done) {
8845
+ return;
8846
+ }
8847
+ const { promise, resolve } = flat_promise();
8848
+ promise.done = false;
8849
+ const setDone = () => {
8850
+ promise.done = true;
8851
+ };
8852
+ promise.then(setDone).catch(setDone);
8853
+ this.signinDonePromise = promise;
8854
+ this._signinDoneResolve = resolve;
8855
+ }
8856
+ }
8857
+ class pusher_Pusher {
8858
+ static ready() {
8859
+ pusher_Pusher.isReady = true;
8860
+ for (var i = 0, l = pusher_Pusher.instances.length; i < l; i++) {
8861
+ pusher_Pusher.instances[i].connect();
8862
+ }
8863
+ }
8864
+ static getClientFeatures() {
8865
+ return keys(filterObject({ ws: runtime.Transports.ws }, function(t) {
8866
+ return t.isSupported({});
8867
+ }));
8868
+ }
8869
+ constructor(app_key, options) {
8870
+ checkAppKey(app_key);
8871
+ validateOptions(options);
8872
+ this.key = app_key;
8873
+ this.config = getConfig2(options, this);
8874
+ this.channels = factory.createChannels();
8875
+ this.global_emitter = new dispatcher_Dispatcher();
8876
+ this.sessionID = runtime.randomInt(1e9);
8877
+ this.timeline = new timeline_Timeline(this.key, this.sessionID, {
8878
+ cluster: this.config.cluster,
8879
+ features: pusher_Pusher.getClientFeatures(),
8880
+ params: this.config.timelineParams || {},
8881
+ limit: 50,
8882
+ level: timeline_level.INFO,
8883
+ version: defaults2.VERSION
8884
+ });
8885
+ if (this.config.enableStats) {
8886
+ this.timelineSender = factory.createTimelineSender(this.timeline, {
8887
+ host: this.config.statsHost,
8888
+ path: "/timeline/v2/" + runtime.TimelineTransport.name
8889
+ });
8890
+ }
8891
+ var getStrategy = (options2) => {
8892
+ return runtime.getDefaultStrategy(this.config, options2, strategy_builder_defineTransport);
8893
+ };
8894
+ this.connection = factory.createConnectionManager(this.key, {
8895
+ getStrategy,
8896
+ timeline: this.timeline,
8897
+ activityTimeout: this.config.activityTimeout,
8898
+ pongTimeout: this.config.pongTimeout,
8899
+ unavailableTimeout: this.config.unavailableTimeout,
8900
+ useTLS: Boolean(this.config.useTLS)
8901
+ });
8902
+ this.connection.bind("connected", () => {
8903
+ this.subscribeAll();
8904
+ if (this.timelineSender) {
8905
+ this.timelineSender.send(this.connection.isUsingTLS());
8906
+ }
8907
+ });
8908
+ this.connection.bind("message", (event) => {
8909
+ var eventName = event.event;
8910
+ var internal = eventName.indexOf("pusher_internal:") === 0;
8911
+ if (event.channel) {
8912
+ var channel = this.channel(event.channel);
8913
+ if (channel) {
8914
+ channel.handleEvent(event);
8915
+ }
8916
+ }
8917
+ if (!internal) {
8918
+ this.global_emitter.emit(event.event, event.data);
8919
+ }
8920
+ });
8921
+ this.connection.bind("connecting", () => {
8922
+ this.channels.disconnect();
8923
+ });
8924
+ this.connection.bind("disconnected", () => {
8925
+ this.channels.disconnect();
8926
+ });
8927
+ this.connection.bind("error", (err) => {
8928
+ logger.warn(err);
8929
+ });
8930
+ pusher_Pusher.instances.push(this);
8931
+ this.timeline.info({ instances: pusher_Pusher.instances.length });
8932
+ this.user = new user_UserFacade(this);
8933
+ if (pusher_Pusher.isReady) {
8934
+ this.connect();
8935
+ }
8936
+ }
8937
+ channel(name) {
8938
+ return this.channels.find(name);
8939
+ }
8940
+ allChannels() {
8941
+ return this.channels.all();
8942
+ }
8943
+ connect() {
8944
+ this.connection.connect();
8945
+ if (this.timelineSender) {
8946
+ if (!this.timelineSenderTimer) {
8947
+ var usingTLS = this.connection.isUsingTLS();
8948
+ var timelineSender = this.timelineSender;
8949
+ this.timelineSenderTimer = new timers_PeriodicTimer(6e4, function() {
8950
+ timelineSender.send(usingTLS);
8951
+ });
8952
+ }
8953
+ }
8954
+ }
8955
+ disconnect() {
8956
+ this.connection.disconnect();
8957
+ if (this.timelineSenderTimer) {
8958
+ this.timelineSenderTimer.ensureAborted();
8959
+ this.timelineSenderTimer = null;
8960
+ }
8961
+ }
8962
+ bind(event_name, callback, context) {
8963
+ this.global_emitter.bind(event_name, callback, context);
8964
+ return this;
8965
+ }
8966
+ unbind(event_name, callback, context) {
8967
+ this.global_emitter.unbind(event_name, callback, context);
8968
+ return this;
8969
+ }
8970
+ bind_global(callback) {
8971
+ this.global_emitter.bind_global(callback);
8972
+ return this;
8973
+ }
8974
+ unbind_global(callback) {
8975
+ this.global_emitter.unbind_global(callback);
8976
+ return this;
8977
+ }
8978
+ unbind_all(callback) {
8979
+ this.global_emitter.unbind_all();
8980
+ return this;
8981
+ }
8982
+ subscribeAll() {
8983
+ var channelName;
8984
+ for (channelName in this.channels.channels) {
8985
+ if (this.channels.channels.hasOwnProperty(channelName)) {
8986
+ this.subscribe(channelName);
8987
+ }
8988
+ }
8989
+ }
8990
+ subscribe(channel_name) {
8991
+ var channel = this.channels.add(channel_name, this);
8992
+ if (channel.subscriptionPending && channel.subscriptionCancelled) {
8993
+ channel.reinstateSubscription();
8994
+ } else if (!channel.subscriptionPending && this.connection.state === "connected") {
8995
+ channel.subscribe();
8996
+ }
8997
+ return channel;
8998
+ }
8999
+ unsubscribe(channel_name) {
9000
+ var channel = this.channels.find(channel_name);
9001
+ if (channel && channel.subscriptionPending) {
9002
+ channel.cancelSubscription();
9003
+ } else {
9004
+ channel = this.channels.remove(channel_name);
9005
+ if (channel && channel.subscribed) {
9006
+ channel.unsubscribe();
9007
+ }
9008
+ }
9009
+ }
9010
+ send_event(event_name, data, channel) {
9011
+ return this.connection.send_event(event_name, data, channel);
9012
+ }
9013
+ shouldUseTLS() {
9014
+ return this.config.useTLS;
9015
+ }
9016
+ signin() {
9017
+ this.user.signin();
9018
+ }
9019
+ }
9020
+ pusher_Pusher.instances = [];
9021
+ pusher_Pusher.isReady = false;
9022
+ pusher_Pusher.logToConsole = false;
9023
+ pusher_Pusher.Runtime = runtime;
9024
+ pusher_Pusher.ScriptReceivers = runtime.ScriptReceivers;
9025
+ pusher_Pusher.DependenciesReceivers = runtime.DependenciesReceivers;
9026
+ pusher_Pusher.auth_callbacks = runtime.auth_callbacks;
9027
+ var core_pusher = __webpack_exports__["default"] = pusher_Pusher;
9028
+ function checkAppKey(key) {
9029
+ if (key === null || key === void 0) {
9030
+ throw "You must pass your app key when you instantiate Pusher.";
9031
+ }
9032
+ }
9033
+ runtime.setup(pusher_Pusher);
9034
+ }
9035
+ /******/
9036
+ ])
9037
+ );
9038
+ });
9039
+ })(pusher);
9040
+ var pusherExports = pusher.exports;
9041
+ const Pusher = /* @__PURE__ */ getDefaultExportFromCjs(pusherExports);
9042
+ const NotebookChannel = "notebook";
9043
+ const NotificationChannel = "user-notification";
9044
+ const StatementResultChannel = "report-result";
9045
+ const ReconResultChannel = "recon-result";
9046
+ class PusherWebsocket {
9047
+ constructor(userId, pusherKey, pusherCluster) {
9048
+ this.pusher = null;
9049
+ this.isConnected = false;
9050
+ this.notebookChannel = null;
9051
+ this.notificationChannel = null;
9052
+ this.reconResultChannel = null;
9053
+ this.statementResultChannel = null;
9054
+ this.otherChannels = {};
9055
+ this.userId = userId;
9056
+ this.pusherKey = pusherKey;
9057
+ this.pusherCluster = pusherCluster;
9058
+ }
9059
+ /**
9060
+ * Set user info for presence channels.
9061
+ * Note: For Pusher, presence info is set via the server-side auth endpoint.
9062
+ * This method is a no-op but provided for interface compatibility.
9063
+ */
9064
+ setPresenceInfo(_info) {
9065
+ }
9066
+ connect() {
9067
+ if (this.pusherKey) {
9068
+ this.pusher = new Pusher(this.pusherKey, {
9069
+ cluster: this.pusherCluster,
9070
+ userAuthentication: { endpoint: "/pusher/auth", transport: "ajax" }
9071
+ });
9072
+ this.notebookChannel = this.pusher.subscribe("private-notebook-" + this.userId);
9073
+ this.notificationChannel = this.pusher.subscribe(`user-notification-${this.userId}`);
9074
+ this.reconResultChannel = this.pusher.subscribe(`private-recon-result-${this.userId}`);
9075
+ this.statementResultChannel = this.pusher.subscribe("private-report-result-" + this.userId);
9076
+ this.pusher.connection.bind("error", (err) => {
9077
+ console.error("Pusher Error!", err);
9078
+ this.isConnected = false;
9079
+ });
9080
+ this.isConnected = true;
9081
+ }
9082
+ }
9083
+ bind(channel, event, callback) {
9084
+ var _a, _b, _c, _d, _e, _f;
9085
+ if (channel === NotebookChannel) {
9086
+ (_a = this.notebookChannel) == null ? void 0 : _a.bind(event, callback);
9087
+ } else if (channel === NotificationChannel) {
9088
+ (_b = this.notificationChannel) == null ? void 0 : _b.bind(event, callback);
9089
+ } else if (channel === ReconResultChannel) {
9090
+ (_c = this.reconResultChannel) == null ? void 0 : _c.bind(event, callback);
9091
+ } else if (channel === StatementResultChannel) {
9092
+ (_d = this.statementResultChannel) == null ? void 0 : _d.bind(event, callback);
9093
+ } else {
9094
+ if (!this.otherChannels[channel]) {
9095
+ this.otherChannels[channel] = (_e = this.pusher) == null ? void 0 : _e.subscribe(channel);
9096
+ }
9097
+ (_f = this.otherChannels[channel]) == null ? void 0 : _f.bind(event, callback);
9098
+ }
9099
+ }
9100
+ bindGlobal(channel, callback) {
9101
+ var _a, _b;
9102
+ if (!this.otherChannels[channel]) {
9103
+ this.otherChannels[channel] = (_a = this.pusher) == null ? void 0 : _a.subscribe(channel);
9104
+ }
9105
+ (_b = this.otherChannels[channel]) == null ? void 0 : _b.bind_global(callback);
9106
+ }
9107
+ unbind(channel, event) {
9108
+ var _a, _b, _c, _d, _e;
9109
+ if (channel === NotebookChannel) {
9110
+ (_a = this.notebookChannel) == null ? void 0 : _a.unbind(event);
9111
+ } else if (channel === NotificationChannel) {
9112
+ (_b = this.notificationChannel) == null ? void 0 : _b.unbind(event);
9113
+ } else if (channel === ReconResultChannel) {
9114
+ (_c = this.reconResultChannel) == null ? void 0 : _c.unbind(event);
9115
+ } else if (channel === StatementResultChannel) {
9116
+ (_d = this.statementResultChannel) == null ? void 0 : _d.unbind(event);
9117
+ } else {
9118
+ (_e = this.otherChannels[channel]) == null ? void 0 : _e.unbind(event);
9119
+ }
9120
+ }
9121
+ unbindAll(channel) {
9122
+ var _a, _b, _c, _d, _e;
9123
+ if (channel === NotebookChannel) {
9124
+ (_a = this.notebookChannel) == null ? void 0 : _a.unbind_all();
9125
+ } else if (channel === NotificationChannel) {
9126
+ (_b = this.notificationChannel) == null ? void 0 : _b.unbind_all();
9127
+ } else if (channel === ReconResultChannel) {
9128
+ (_c = this.reconResultChannel) == null ? void 0 : _c.unbind_all();
9129
+ } else if (channel === StatementResultChannel) {
9130
+ (_d = this.statementResultChannel) == null ? void 0 : _d.unbind_all();
9131
+ } else {
9132
+ (_e = this.otherChannels[channel]) == null ? void 0 : _e.unbind_all();
9133
+ }
9134
+ }
9135
+ trigger(channel, event, data) {
9136
+ var _a, _b, _c, _d, _e;
9137
+ if (channel === NotebookChannel) {
9138
+ (_a = this.notebookChannel) == null ? void 0 : _a.trigger(event, data);
9139
+ } else if (channel === NotificationChannel) {
9140
+ (_b = this.notificationChannel) == null ? void 0 : _b.trigger(event, data);
9141
+ } else if (channel === ReconResultChannel) {
9142
+ (_c = this.reconResultChannel) == null ? void 0 : _c.trigger(event, data);
9143
+ } else if (channel === StatementResultChannel) {
9144
+ (_d = this.statementResultChannel) == null ? void 0 : _d.trigger(event, data);
9145
+ } else {
9146
+ (_e = this.otherChannels[channel]) == null ? void 0 : _e.trigger(event, data);
9147
+ }
9148
+ }
9149
+ disconnect() {
9150
+ var _a, _b, _c, _d, _e;
9151
+ if (this.pusher) {
9152
+ (_a = this.notebookChannel) == null ? void 0 : _a.unsubscribe();
9153
+ (_b = this.notificationChannel) == null ? void 0 : _b.unsubscribe();
9154
+ (_c = this.reconResultChannel) == null ? void 0 : _c.unsubscribe();
9155
+ (_d = this.statementResultChannel) == null ? void 0 : _d.unsubscribe();
9156
+ for (const channel in this.otherChannels) {
9157
+ (_e = this.otherChannels[channel]) == null ? void 0 : _e.unsubscribe();
9158
+ }
9159
+ this.pusher.disconnect();
9160
+ this.pusher = null;
9161
+ this.notebookChannel = null;
9162
+ this.notificationChannel = null;
9163
+ this.reconResultChannel = null;
9164
+ this.statementResultChannel = null;
9165
+ }
9166
+ this.isConnected = false;
9167
+ }
9168
+ /**
9169
+ * Get members of a presence channel.
9170
+ * Returns PresenceMembers synchronously for Pusher.
9171
+ */
9172
+ getPresenceChannelMembers(channel) {
9173
+ if (!channel.startsWith("presence-")) {
9174
+ throw new Error("Channel is not a presence channel");
9175
+ }
9176
+ if (!this.pusher) {
9177
+ throw new Error("Pusher is not connected");
9178
+ }
9179
+ if (!this.otherChannels[channel]) {
9180
+ this.otherChannels[channel] = this.pusher.subscribe(channel);
9181
+ }
9182
+ const presenceChannel = this.otherChannels[channel];
9183
+ if (!presenceChannel) {
9184
+ throw new Error("Failed to subscribe to presence channel");
9185
+ }
9186
+ if (!presenceChannel.members) {
9187
+ throw new Error("Channel is not a presence channel or subscription not ready");
9188
+ }
9189
+ const membersMap = {};
9190
+ const membersList = [];
9191
+ presenceChannel.members.each((member) => {
9192
+ membersMap[member.id] = member.info;
9193
+ membersList.push({ id: member.id, info: member.info });
9194
+ });
9195
+ return {
9196
+ count: presenceChannel.members.count,
9197
+ members: membersMap,
9198
+ each: (callback) => {
9199
+ membersList.forEach(callback);
9200
+ }
9201
+ };
9202
+ }
9203
+ }
9204
+ class WebsocketContextFactory {
9205
+ static create(mechanism, args) {
9206
+ let websocketProvider;
9207
+ if (mechanism === "centrifugo") {
9208
+ if (!args.connectionUrl) {
9209
+ throw new Error("Connection url is required");
9210
+ }
9211
+ if (!args.token) {
9212
+ throw new Error("Token is required");
9213
+ }
9214
+ websocketProvider = new CentrifugoWebsocket(args.connectionUrl, args.token, args.userId);
9215
+ } else if (mechanism === "pusher") {
9216
+ if (!args.pusherKey) {
9217
+ throw new Error("Pusher key is required");
9218
+ }
9219
+ if (!args.pusherCluster) {
9220
+ throw new Error("Pusher cluster is required");
9221
+ }
9222
+ websocketProvider = new PusherWebsocket(args.userId, args.pusherKey, args.pusherCluster);
9223
+ } else {
9224
+ throw new Error(`Unsupported mechanism: ${mechanism}. Supported mechanisms are: pusher, centrifugo`);
9225
+ }
9226
+ if (!websocketProvider) {
9227
+ throw new Error(`Failed to create websocket provider for mechanism: ${mechanism}`);
5057
9228
  }
5058
- websocketProvider == null ? void 0 : websocketProvider.connect();
9229
+ websocketProvider.connect();
5059
9230
  return websocketProvider;
5060
9231
  }
5061
9232
  }