├── .vs └── slnx.sqlite ├── img ├── webSocket小程序化.png ├── xmlRequest方式改变.png └── 固定通讯方式为webSocket.png ├── README.md └── signalr.js /.vs/slnx.sqlite: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LcFireRabbit/SignalR-ClientForMiniProgram-js/HEAD/.vs/slnx.sqlite -------------------------------------------------------------------------------- /img/webSocket小程序化.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LcFireRabbit/SignalR-ClientForMiniProgram-js/HEAD/img/webSocket小程序化.png -------------------------------------------------------------------------------- /img/xmlRequest方式改变.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LcFireRabbit/SignalR-ClientForMiniProgram-js/HEAD/img/xmlRequest方式改变.png -------------------------------------------------------------------------------- /img/固定通讯方式为webSocket.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LcFireRabbit/SignalR-ClientForMiniProgram-js/HEAD/img/固定通讯方式为webSocket.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SignalR-ClientForMiniProgram-js 2 | ASP.NET SignalR依赖JQ,故小程序不能直接使用。但是在ASP.NET Core SignalR中,官方去除了对JQ的依赖,所以存在可以被小程序直接使用的可能,但是客户端js中连接服务端的方法和实现WebSoket方式,跟小程序中的用法不同,也不能直接用。但是通过修改这两处的实现方式,可以让小程序使用。 3 | --- 4 | 此版为老版本的signalR,新版本目前是TS编译版本,还未修改成功。 5 | # 修改处说明 6 | ### 将原来的XMLRequest请求方式,改为小程序字节的wx.requst. 7 | ![](/img/xmlRequest方式改变.png) 8 | ### 将原来的WebSocket,改为小程序的WebSocket 9 | ![](/img/webSocket小程序化.png) 10 | ### 因为小程序只支持signalR三种通讯方式中的WebSocket,所以将通讯方式固定位WebSocket即可 11 | ![](/img/固定通讯方式为webSocket.png) 12 | -------------------------------------------------------------------------------- /signalr.js: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * @overview ASP.NET Core SignalR JavaScript Client. 4 | * @version 1.0.0. 5 | * @license 6 | * Copyright (c) .NET Foundation. All rights reserved. 7 | * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 8 | */ 9 | (function(global, factory) { 10 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 11 | typeof define === 'function' && define.amd ? define(factory) : 12 | (global.signalR = factory()); 13 | }(this, (function() { 14 | 'use strict'; 15 | 16 | var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; 17 | 18 | function commonjsRequire() { 19 | throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); 20 | } 21 | 22 | function unwrapExports(x) { 23 | return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; 24 | } 25 | 26 | function createCommonjsModule(fn, module) { 27 | return module = { 28 | exports: {} 29 | }, fn(module, module.exports), module.exports; 30 | } 31 | 32 | /*! ***************************************************************************** 33 | Copyright (c) Microsoft Corporation. All rights reserved. 34 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use 35 | this file except in compliance with the License. You may obtain a copy of the 36 | License at http://www.apache.org/licenses/LICENSE-2.0 37 | 38 | THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 39 | KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 40 | WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 41 | MERCHANTABLITY OR NON-INFRINGEMENT. 42 | 43 | See the Apache Version 2.0 License for specific language governing permissions 44 | and limitations under the License. 45 | ***************************************************************************** */ 46 | /* global Reflect, Promise */ 47 | 48 | var extendStatics = Object.setPrototypeOf || 49 | ({ 50 | __proto__: [] 51 | } 52 | instanceof Array && function(d, b) { 53 | d.__proto__ = b; 54 | }) || 55 | function(d, b) { 56 | for (var p in b) 57 | if (b.hasOwnProperty(p)) d[p] = b[p]; 58 | }; 59 | 60 | function __extends(d, b) { 61 | extendStatics(d, b); 62 | 63 | function __() { 64 | this.constructor = d; 65 | } 66 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 67 | } 68 | 69 | var __assign = Object.assign || function __assign(t) { 70 | for (var s, i = 1, n = arguments.length; i < n; i++) { 71 | s = arguments[i]; 72 | for (var p in s) 73 | if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; 74 | } 75 | return t; 76 | }; 77 | 78 | function __rest(s, e) { 79 | var t = {}; 80 | for (var p in s) 81 | if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) 82 | t[p] = s[p]; 83 | if (s != null && typeof Object.getOwnPropertySymbols === "function") 84 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) 85 | if (e.indexOf(p[i]) < 0) 86 | t[p[i]] = s[p[i]]; 87 | return t; 88 | } 89 | 90 | function __decorate(decorators, target, key, desc) { 91 | var c = arguments.length, 92 | r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, 93 | d; 94 | if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); 95 | else 96 | for (var i = decorators.length - 1; i >= 0; i--) 97 | if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; 98 | return c > 3 && r && Object.defineProperty(target, key, r), r; 99 | } 100 | 101 | function __param(paramIndex, decorator) { 102 | return function(target, key) { 103 | decorator(target, key, paramIndex); 104 | } 105 | } 106 | 107 | function __metadata(metadataKey, metadataValue) { 108 | if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); 109 | } 110 | 111 | function __awaiter(thisArg, _arguments, P, generator) { 112 | return new(P || (P = Promise))(function(resolve, reject) { 113 | function fulfilled(value) { 114 | try { 115 | step(generator.next(value)); 116 | } catch (e) { 117 | reject(e); 118 | } 119 | } 120 | 121 | function rejected(value) { 122 | try { 123 | step(generator["throw"](value)); 124 | } catch (e) { 125 | reject(e); 126 | } 127 | } 128 | 129 | function step(result) { 130 | result.done ? resolve(result.value) : new P(function(resolve) { 131 | resolve(result.value); 132 | }).then(fulfilled, rejected); 133 | } 134 | step((generator = generator.apply(thisArg, _arguments || [])).next()); 135 | }); 136 | } 137 | 138 | function __generator(thisArg, body) { 139 | var _ = { 140 | label: 0, 141 | sent: function() { 142 | if (t[0] & 1) throw t[1]; 143 | return t[1]; 144 | }, 145 | trys: [], 146 | ops: [] 147 | }, 148 | f, y, t, g; 149 | return g = { 150 | next: verb(0), 151 | "throw": verb(1), 152 | "return": verb(2) 153 | }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { 154 | return this; 155 | }), g; 156 | 157 | function verb(n) { 158 | return function(v) { 159 | return step([n, v]); 160 | }; 161 | } 162 | 163 | function step(op) { 164 | if (f) throw new TypeError("Generator is already executing."); 165 | while (_) try { 166 | if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t; 167 | if (y = 0, t) op = [0, t.value]; 168 | switch (op[0]) { 169 | case 0: 170 | case 1: 171 | t = op; 172 | break; 173 | case 4: 174 | _.label++; 175 | return { 176 | value: op[1], 177 | done: false 178 | }; 179 | case 5: 180 | _.label++; 181 | y = op[1]; 182 | op = [0]; 183 | continue; 184 | case 7: 185 | op = _.ops.pop(); 186 | _.trys.pop(); 187 | continue; 188 | default: 189 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { 190 | _ = 0; 191 | continue; 192 | } 193 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { 194 | _.label = op[1]; 195 | break; 196 | } 197 | if (op[0] === 6 && _.label < t[1]) { 198 | _.label = t[1]; 199 | t = op; 200 | break; 201 | } 202 | if (t && _.label < t[2]) { 203 | _.label = t[2]; 204 | _.ops.push(op); 205 | break; 206 | } 207 | if (t[2]) _.ops.pop(); 208 | _.trys.pop(); 209 | continue; 210 | } 211 | op = body.call(thisArg, _); 212 | } catch (e) { 213 | op = [6, e]; 214 | y = 0; 215 | } finally { 216 | f = t = 0; 217 | } 218 | if (op[0] & 5) throw op[1]; 219 | return { 220 | value: op[0] ? op[1] : void 0, 221 | done: true 222 | }; 223 | } 224 | } 225 | 226 | function __exportStar(m, exports) { 227 | for (var p in m) 228 | if (!exports.hasOwnProperty(p)) exports[p] = m[p]; 229 | } 230 | 231 | function __values(o) { 232 | var m = typeof Symbol === "function" && o[Symbol.iterator], 233 | i = 0; 234 | if (m) return m.call(o); 235 | return { 236 | next: function() { 237 | if (o && i >= o.length) o = void 0; 238 | return { 239 | value: o && o[i++], 240 | done: !o 241 | }; 242 | } 243 | }; 244 | } 245 | 246 | function __read(o, n) { 247 | var m = typeof Symbol === "function" && o[Symbol.iterator]; 248 | if (!m) return o; 249 | var i = m.call(o), 250 | r, ar = [], 251 | e; 252 | try { 253 | while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); 254 | } catch (error) { 255 | e = { 256 | error: error 257 | }; 258 | } finally { 259 | try { 260 | if (r && !r.done && (m = i["return"])) m.call(i); 261 | } finally { 262 | if (e) throw e.error; 263 | } 264 | } 265 | return ar; 266 | } 267 | 268 | function __spread() { 269 | for (var ar = [], i = 0; i < arguments.length; i++) 270 | ar = ar.concat(__read(arguments[i])); 271 | return ar; 272 | } 273 | 274 | function __await(v) { 275 | return this instanceof __await ? (this.v = v, this) : new __await(v); 276 | } 277 | 278 | function __asyncGenerator(thisArg, _arguments, generator) { 279 | if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); 280 | var g = generator.apply(thisArg, _arguments || []), 281 | i, q = []; 282 | return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { 283 | return this; 284 | }, i; 285 | 286 | function verb(n) { 287 | if (g[n]) i[n] = function(v) { 288 | return new Promise(function(a, b) { 289 | q.push([n, v, a, b]) > 1 || resume(n, v); 290 | }); 291 | }; 292 | } 293 | 294 | function resume(n, v) { 295 | try { 296 | step(g[n](v)); 297 | } catch (e) { 298 | settle(q[0][3], e); 299 | } 300 | } 301 | 302 | function step(r) { 303 | r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); 304 | } 305 | 306 | function fulfill(value) { 307 | resume("next", value); 308 | } 309 | 310 | function reject(value) { 311 | resume("throw", value); 312 | } 313 | 314 | function settle(f, v) { 315 | if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); 316 | } 317 | } 318 | 319 | function __asyncDelegator(o) { 320 | var i, p; 321 | return i = {}, verb("next"), verb("throw", function(e) { 322 | throw e; 323 | }), verb("return"), i[Symbol.iterator] = function() { 324 | return this; 325 | }, i; 326 | 327 | function verb(n, f) { 328 | if (o[n]) i[n] = function(v) { 329 | return (p = !p) ? { 330 | value: __await(o[n](v)), 331 | done: n === "return" 332 | } : f ? f(v) : v; 333 | }; 334 | } 335 | } 336 | 337 | function __asyncValues(o) { 338 | if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); 339 | var m = o[Symbol.asyncIterator]; 340 | return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); 341 | } 342 | 343 | function __makeTemplateObject(cooked, raw) { 344 | if (Object.defineProperty) { 345 | Object.defineProperty(cooked, "raw", { 346 | value: raw 347 | }); 348 | } else { 349 | cooked.raw = raw; 350 | } 351 | return cooked; 352 | } 353 | 354 | function __importStar(mod) { 355 | if (mod && mod.__esModule) return mod; 356 | var result = {}; 357 | if (mod != null) 358 | for (var k in mod) 359 | if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; 360 | result.default = mod; 361 | return result; 362 | } 363 | 364 | function __importDefault(mod) { 365 | return (mod && mod.__esModule) ? mod : { 366 | default: mod 367 | }; 368 | } 369 | 370 | 371 | var tslib_1 = Object.freeze({ 372 | __extends: __extends, 373 | __assign: __assign, 374 | __rest: __rest, 375 | __decorate: __decorate, 376 | __param: __param, 377 | __metadata: __metadata, 378 | __awaiter: __awaiter, 379 | __generator: __generator, 380 | __exportStar: __exportStar, 381 | __values: __values, 382 | __read: __read, 383 | __spread: __spread, 384 | __await: __await, 385 | __asyncGenerator: __asyncGenerator, 386 | __asyncDelegator: __asyncDelegator, 387 | __asyncValues: __asyncValues, 388 | __makeTemplateObject: __makeTemplateObject, 389 | __importStar: __importStar, 390 | __importDefault: __importDefault 391 | }); 392 | 393 | var es6Promise_auto = createCommonjsModule(function(module, exports) { 394 | /*! 395 | * @overview es6-promise - a tiny implementation of Promises/A+. 396 | * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) 397 | * @license Licensed under MIT license 398 | * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE 399 | * @version v4.2.2+97478eb6 400 | */ 401 | 402 | (function(global, factory) { 403 | module.exports = factory(); 404 | }(commonjsGlobal, (function() { 405 | function objectOrFunction(x) { 406 | var type = typeof x; 407 | return x !== null && (type === 'object' || type === 'function'); 408 | } 409 | 410 | function isFunction(x) { 411 | return typeof x === 'function'; 412 | } 413 | 414 | 415 | 416 | var _isArray = void 0; 417 | if (Array.isArray) { 418 | _isArray = Array.isArray; 419 | } else { 420 | _isArray = function(x) { 421 | return Object.prototype.toString.call(x) === '[object Array]'; 422 | }; 423 | } 424 | 425 | var isArray = _isArray; 426 | 427 | var len = 0; 428 | var vertxNext = void 0; 429 | var customSchedulerFn = void 0; 430 | 431 | var asap = function asap(callback, arg) { 432 | queue[len] = callback; 433 | queue[len + 1] = arg; 434 | len += 2; 435 | if (len === 2) { 436 | // If len is 2, that means that we need to schedule an async flush. 437 | // If additional callbacks are queued before the queue is flushed, they 438 | // will be processed by this flush that we are scheduling. 439 | if (customSchedulerFn) { 440 | customSchedulerFn(flush); 441 | } else { 442 | scheduleFlush(); 443 | } 444 | } 445 | }; 446 | 447 | function setScheduler(scheduleFn) { 448 | customSchedulerFn = scheduleFn; 449 | } 450 | 451 | function setAsap(asapFn) { 452 | asap = asapFn; 453 | } 454 | 455 | var browserWindow = typeof window !== 'undefined' ? window : undefined; 456 | var browserGlobal = browserWindow || {}; 457 | var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; 458 | var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; 459 | 460 | // test for web worker but not in IE10 461 | var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; 462 | 463 | // node 464 | function useNextTick() { 465 | // node version 0.10.x displays a deprecation warning when nextTick is used recursively 466 | // see https://github.com/cujojs/when/issues/410 for details 467 | return function() { 468 | return process.nextTick(flush); 469 | }; 470 | } 471 | 472 | // vertx 473 | function useVertxTimer() { 474 | if (typeof vertxNext !== 'undefined') { 475 | return function() { 476 | vertxNext(flush); 477 | }; 478 | } 479 | 480 | return useSetTimeout(); 481 | } 482 | 483 | function useMutationObserver() { 484 | var iterations = 0; 485 | var observer = new BrowserMutationObserver(flush); 486 | var node = document.createTextNode(''); 487 | observer.observe(node, { 488 | characterData: true 489 | }); 490 | 491 | return function() { 492 | node.data = iterations = ++iterations % 2; 493 | }; 494 | } 495 | 496 | // web worker 497 | function useMessageChannel() { 498 | var channel = new MessageChannel(); 499 | channel.port1.onmessage = flush; 500 | return function() { 501 | return channel.port2.postMessage(0); 502 | }; 503 | } 504 | 505 | function useSetTimeout() { 506 | // Store setTimeout reference so es6-promise will be unaffected by 507 | // other code modifying setTimeout (like sinon.useFakeTimers()) 508 | var globalSetTimeout = setTimeout; 509 | return function() { 510 | return globalSetTimeout(flush, 1); 511 | }; 512 | } 513 | 514 | var queue = new Array(1000); 515 | 516 | function flush() { 517 | for (var i = 0; i < len; i += 2) { 518 | var callback = queue[i]; 519 | var arg = queue[i + 1]; 520 | 521 | callback(arg); 522 | 523 | queue[i] = undefined; 524 | queue[i + 1] = undefined; 525 | } 526 | 527 | len = 0; 528 | } 529 | 530 | function attemptVertx() { 531 | try { 532 | var r = commonjsRequire; 533 | var vertx = r('vertx'); 534 | vertxNext = vertx.runOnLoop || vertx.runOnContext; 535 | return useVertxTimer(); 536 | } catch (e) { 537 | return useSetTimeout(); 538 | } 539 | } 540 | 541 | var scheduleFlush = void 0; 542 | // Decide what async method to use to triggering processing of queued callbacks: 543 | if (isNode) { 544 | scheduleFlush = useNextTick(); 545 | } else if (BrowserMutationObserver) { 546 | scheduleFlush = useMutationObserver(); 547 | } else if (isWorker) { 548 | scheduleFlush = useMessageChannel(); 549 | } else if (browserWindow === undefined && typeof commonjsRequire === 'function') { 550 | scheduleFlush = attemptVertx(); 551 | } else { 552 | scheduleFlush = useSetTimeout(); 553 | } 554 | 555 | function then(onFulfillment, onRejection) { 556 | var parent = this; 557 | 558 | var child = new this.constructor(noop); 559 | 560 | if (child[PROMISE_ID] === undefined) { 561 | makePromise(child); 562 | } 563 | 564 | var _state = parent._state; 565 | 566 | 567 | if (_state) { 568 | var callback = arguments[_state - 1]; 569 | asap(function() { 570 | return invokeCallback(_state, child, callback, parent._result); 571 | }); 572 | } else { 573 | subscribe(parent, child, onFulfillment, onRejection); 574 | } 575 | 576 | return child; 577 | } 578 | 579 | /** 580 | `Promise.resolve` returns a promise that will become resolved with the 581 | passed `value`. It is shorthand for the following: 582 | 583 | ```javascript 584 | let promise = new Promise(function(resolve, reject){ 585 | resolve(1); 586 | }); 587 | 588 | promise.then(function(value){ 589 | // value === 1 590 | }); 591 | ``` 592 | 593 | Instead of writing the above, your code now simply becomes the following: 594 | 595 | ```javascript 596 | let promise = Promise.resolve(1); 597 | 598 | promise.then(function(value){ 599 | // value === 1 600 | }); 601 | ``` 602 | 603 | @method resolve 604 | @static 605 | @param {Any} value value that the returned promise will be resolved with 606 | Useful for tooling. 607 | @return {Promise} a promise that will become fulfilled with the given 608 | `value` 609 | */ 610 | function resolve$1(object) { 611 | /*jshint validthis:true */ 612 | var Constructor = this; 613 | 614 | if (object && typeof object === 'object' && object.constructor === Constructor) { 615 | return object; 616 | } 617 | 618 | var promise = new Constructor(noop); 619 | resolve(promise, object); 620 | return promise; 621 | } 622 | 623 | var PROMISE_ID = Math.random().toString(36).substring(16); 624 | 625 | function noop() {} 626 | 627 | var PENDING = void 0; 628 | var FULFILLED = 1; 629 | var REJECTED = 2; 630 | 631 | var GET_THEN_ERROR = new ErrorObject(); 632 | 633 | function selfFulfillment() { 634 | return new TypeError("You cannot resolve a promise with itself"); 635 | } 636 | 637 | function cannotReturnOwn() { 638 | return new TypeError('A promises callback cannot return that same promise.'); 639 | } 640 | 641 | function getThen(promise) { 642 | try { 643 | return promise.then; 644 | } catch (error) { 645 | GET_THEN_ERROR.error = error; 646 | return GET_THEN_ERROR; 647 | } 648 | } 649 | 650 | function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { 651 | try { 652 | then$$1.call(value, fulfillmentHandler, rejectionHandler); 653 | } catch (e) { 654 | return e; 655 | } 656 | } 657 | 658 | function handleForeignThenable(promise, thenable, then$$1) { 659 | asap(function(promise) { 660 | var sealed = false; 661 | var error = tryThen(then$$1, thenable, function(value) { 662 | if (sealed) { 663 | return; 664 | } 665 | sealed = true; 666 | if (thenable !== value) { 667 | resolve(promise, value); 668 | } else { 669 | fulfill(promise, value); 670 | } 671 | }, function(reason) { 672 | if (sealed) { 673 | return; 674 | } 675 | sealed = true; 676 | 677 | reject(promise, reason); 678 | }, 'Settle: ' + (promise._label || ' unknown promise')); 679 | 680 | if (!sealed && error) { 681 | sealed = true; 682 | reject(promise, error); 683 | } 684 | }, promise); 685 | } 686 | 687 | function handleOwnThenable(promise, thenable) { 688 | if (thenable._state === FULFILLED) { 689 | fulfill(promise, thenable._result); 690 | } else if (thenable._state === REJECTED) { 691 | reject(promise, thenable._result); 692 | } else { 693 | subscribe(thenable, undefined, function(value) { 694 | return resolve(promise, value); 695 | }, function(reason) { 696 | return reject(promise, reason); 697 | }); 698 | } 699 | } 700 | 701 | function handleMaybeThenable(promise, maybeThenable, then$$1) { 702 | if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { 703 | handleOwnThenable(promise, maybeThenable); 704 | } else { 705 | if (then$$1 === GET_THEN_ERROR) { 706 | reject(promise, GET_THEN_ERROR.error); 707 | GET_THEN_ERROR.error = null; 708 | } else if (then$$1 === undefined) { 709 | fulfill(promise, maybeThenable); 710 | } else if (isFunction(then$$1)) { 711 | handleForeignThenable(promise, maybeThenable, then$$1); 712 | } else { 713 | fulfill(promise, maybeThenable); 714 | } 715 | } 716 | } 717 | 718 | function resolve(promise, value) { 719 | if (promise === value) { 720 | reject(promise, selfFulfillment()); 721 | } else if (objectOrFunction(value)) { 722 | handleMaybeThenable(promise, value, getThen(value)); 723 | } else { 724 | fulfill(promise, value); 725 | } 726 | } 727 | 728 | function publishRejection(promise) { 729 | if (promise._onerror) { 730 | promise._onerror(promise._result); 731 | } 732 | 733 | publish(promise); 734 | } 735 | 736 | function fulfill(promise, value) { 737 | if (promise._state !== PENDING) { 738 | return; 739 | } 740 | 741 | promise._result = value; 742 | promise._state = FULFILLED; 743 | 744 | if (promise._subscribers.length !== 0) { 745 | asap(publish, promise); 746 | } 747 | } 748 | 749 | function reject(promise, reason) { 750 | if (promise._state !== PENDING) { 751 | return; 752 | } 753 | promise._state = REJECTED; 754 | promise._result = reason; 755 | 756 | asap(publishRejection, promise); 757 | } 758 | 759 | function subscribe(parent, child, onFulfillment, onRejection) { 760 | var _subscribers = parent._subscribers; 761 | var length = _subscribers.length; 762 | 763 | 764 | parent._onerror = null; 765 | 766 | _subscribers[length] = child; 767 | _subscribers[length + FULFILLED] = onFulfillment; 768 | _subscribers[length + REJECTED] = onRejection; 769 | 770 | if (length === 0 && parent._state) { 771 | asap(publish, parent); 772 | } 773 | } 774 | 775 | function publish(promise) { 776 | var subscribers = promise._subscribers; 777 | var settled = promise._state; 778 | 779 | if (subscribers.length === 0) { 780 | return; 781 | } 782 | 783 | var child = void 0, 784 | callback = void 0, 785 | detail = promise._result; 786 | 787 | for (var i = 0; i < subscribers.length; i += 3) { 788 | child = subscribers[i]; 789 | callback = subscribers[i + settled]; 790 | 791 | if (child) { 792 | invokeCallback(settled, child, callback, detail); 793 | } else { 794 | callback(detail); 795 | } 796 | } 797 | 798 | promise._subscribers.length = 0; 799 | } 800 | 801 | function ErrorObject() { 802 | this.error = null; 803 | } 804 | 805 | var TRY_CATCH_ERROR = new ErrorObject(); 806 | 807 | function tryCatch(callback, detail) { 808 | try { 809 | return callback(detail); 810 | } catch (e) { 811 | TRY_CATCH_ERROR.error = e; 812 | return TRY_CATCH_ERROR; 813 | } 814 | } 815 | 816 | function invokeCallback(settled, promise, callback, detail) { 817 | var hasCallback = isFunction(callback), 818 | value = void 0, 819 | error = void 0, 820 | succeeded = void 0, 821 | failed = void 0; 822 | 823 | if (hasCallback) { 824 | value = tryCatch(callback, detail); 825 | 826 | if (value === TRY_CATCH_ERROR) { 827 | failed = true; 828 | error = value.error; 829 | value.error = null; 830 | } else { 831 | succeeded = true; 832 | } 833 | 834 | if (promise === value) { 835 | reject(promise, cannotReturnOwn()); 836 | return; 837 | } 838 | } else { 839 | value = detail; 840 | succeeded = true; 841 | } 842 | 843 | if (promise._state !== PENDING) { 844 | // noop 845 | } else if (hasCallback && succeeded) { 846 | resolve(promise, value); 847 | } else if (failed) { 848 | reject(promise, error); 849 | } else if (settled === FULFILLED) { 850 | fulfill(promise, value); 851 | } else if (settled === REJECTED) { 852 | reject(promise, value); 853 | } 854 | } 855 | 856 | function initializePromise(promise, resolver) { 857 | try { 858 | resolver(function resolvePromise(value) { 859 | resolve(promise, value); 860 | }, function rejectPromise(reason) { 861 | reject(promise, reason); 862 | }); 863 | } catch (e) { 864 | reject(promise, e); 865 | } 866 | } 867 | 868 | var id = 0; 869 | 870 | function nextId() { 871 | return id++; 872 | } 873 | 874 | function makePromise(promise) { 875 | promise[PROMISE_ID] = id++; 876 | promise._state = undefined; 877 | promise._result = undefined; 878 | promise._subscribers = []; 879 | } 880 | 881 | function validationError() { 882 | return new Error('Array Methods must be provided an Array'); 883 | } 884 | 885 | function validationError() { 886 | return new Error('Array Methods must be provided an Array'); 887 | } 888 | 889 | var Enumerator = function() { 890 | function Enumerator(Constructor, input) { 891 | this._instanceConstructor = Constructor; 892 | this.promise = new Constructor(noop); 893 | 894 | if (!this.promise[PROMISE_ID]) { 895 | makePromise(this.promise); 896 | } 897 | 898 | if (isArray(input)) { 899 | this.length = input.length; 900 | this._remaining = input.length; 901 | 902 | this._result = new Array(this.length); 903 | 904 | if (this.length === 0) { 905 | fulfill(this.promise, this._result); 906 | } else { 907 | this.length = this.length || 0; 908 | this._enumerate(input); 909 | if (this._remaining === 0) { 910 | fulfill(this.promise, this._result); 911 | } 912 | } 913 | } else { 914 | reject(this.promise, validationError()); 915 | } 916 | } 917 | 918 | Enumerator.prototype._enumerate = function _enumerate(input) { 919 | for (var i = 0; this._state === PENDING && i < input.length; i++) { 920 | this._eachEntry(input[i], i); 921 | } 922 | }; 923 | 924 | Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { 925 | var c = this._instanceConstructor; 926 | var resolve$$1 = c.resolve; 927 | 928 | 929 | if (resolve$$1 === resolve$1) { 930 | var _then = getThen(entry); 931 | 932 | if (_then === then && entry._state !== PENDING) { 933 | this._settledAt(entry._state, i, entry._result); 934 | } else if (typeof _then !== 'function') { 935 | this._remaining--; 936 | this._result[i] = entry; 937 | } else if (c === Promise$2) { 938 | var promise = new c(noop); 939 | handleMaybeThenable(promise, entry, _then); 940 | this._willSettleAt(promise, i); 941 | } else { 942 | this._willSettleAt(new c(function(resolve$$1) { 943 | return resolve$$1(entry); 944 | }), i); 945 | } 946 | } else { 947 | this._willSettleAt(resolve$$1(entry), i); 948 | } 949 | }; 950 | 951 | Enumerator.prototype._settledAt = function _settledAt(state, i, value) { 952 | var promise = this.promise; 953 | 954 | 955 | if (promise._state === PENDING) { 956 | this._remaining--; 957 | 958 | if (state === REJECTED) { 959 | reject(promise, value); 960 | } else { 961 | this._result[i] = value; 962 | } 963 | } 964 | 965 | if (this._remaining === 0) { 966 | fulfill(promise, this._result); 967 | } 968 | }; 969 | 970 | Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { 971 | var enumerator = this; 972 | 973 | subscribe(promise, undefined, function(value) { 974 | return enumerator._settledAt(FULFILLED, i, value); 975 | }, function(reason) { 976 | return enumerator._settledAt(REJECTED, i, reason); 977 | }); 978 | }; 979 | 980 | return Enumerator; 981 | }(); 982 | 983 | function all(entries) { 984 | return new Enumerator(this, entries).promise; 985 | } 986 | 987 | function race(entries) { 988 | /*jshint validthis:true */ 989 | var Constructor = this; 990 | 991 | if (!isArray(entries)) { 992 | return new Constructor(function(_, reject) { 993 | return reject(new TypeError('You must pass an array to race.')); 994 | }); 995 | } else { 996 | return new Constructor(function(resolve, reject) { 997 | var length = entries.length; 998 | for (var i = 0; i < length; i++) { 999 | Constructor.resolve(entries[i]).then(resolve, reject); 1000 | } 1001 | }); 1002 | } 1003 | } 1004 | 1005 | /** 1006 | `Promise.reject` returns a promise rejected with the passed `reason`. 1007 | It is shorthand for the following: 1008 | 1009 | ```javascript 1010 | let promise = new Promise(function(resolve, reject){ 1011 | reject(new Error('WHOOPS')); 1012 | }); 1013 | 1014 | promise.then(function(value){ 1015 | // Code here doesn't run because the promise is rejected! 1016 | }, function(reason){ 1017 | // reason.message === 'WHOOPS' 1018 | }); 1019 | ``` 1020 | 1021 | Instead of writing the above, your code now simply becomes the following: 1022 | 1023 | ```javascript 1024 | let promise = Promise.reject(new Error('WHOOPS')); 1025 | 1026 | promise.then(function(value){ 1027 | // Code here doesn't run because the promise is rejected! 1028 | }, function(reason){ 1029 | // reason.message === 'WHOOPS' 1030 | }); 1031 | ``` 1032 | 1033 | @method reject 1034 | @static 1035 | @param {Any} reason value that the returned promise will be rejected with. 1036 | Useful for tooling. 1037 | @return {Promise} a promise rejected with the given `reason`. 1038 | */ 1039 | function reject$1(reason) { 1040 | /*jshint validthis:true */ 1041 | var Constructor = this; 1042 | var promise = new Constructor(noop); 1043 | reject(promise, reason); 1044 | return promise; 1045 | } 1046 | 1047 | function needsResolver() { 1048 | throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); 1049 | } 1050 | 1051 | function needsNew() { 1052 | throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); 1053 | } 1054 | 1055 | var Promise$2 = function() { 1056 | function Promise(resolver) { 1057 | this[PROMISE_ID] = nextId(); 1058 | this._result = this._state = undefined; 1059 | this._subscribers = []; 1060 | 1061 | if (noop !== resolver) { 1062 | typeof resolver !== 'function' && needsResolver(); 1063 | this instanceof Promise ? initializePromise(this, resolver) : needsNew(); 1064 | } 1065 | } 1066 | 1067 | 1068 | 1069 | Promise.prototype.catch = function _catch(onRejection) { 1070 | return this.then(null, onRejection); 1071 | }; 1072 | 1073 | Promise.prototype.finally = function _finally(callback) { 1074 | var promise = this; 1075 | var constructor = promise.constructor; 1076 | 1077 | return promise.then(function(value) { 1078 | return constructor.resolve(callback()).then(function() { 1079 | return value; 1080 | }); 1081 | }, function(reason) { 1082 | return constructor.resolve(callback()).then(function() { 1083 | throw reason; 1084 | }); 1085 | }); 1086 | }; 1087 | 1088 | return Promise; 1089 | }(); 1090 | 1091 | Promise$2.prototype.then = then; 1092 | Promise$2.all = all; 1093 | Promise$2.race = race; 1094 | Promise$2.resolve = resolve$1; 1095 | Promise$2.reject = reject$1; 1096 | Promise$2._setScheduler = setScheduler; 1097 | Promise$2._setAsap = setAsap; 1098 | Promise$2._asap = asap; 1099 | 1100 | /*global self*/ 1101 | function polyfill() { 1102 | var local = void 0; 1103 | 1104 | if (typeof commonjsGlobal !== 'undefined') { 1105 | local = commonjsGlobal; 1106 | } else if (typeof self !== 'undefined') { 1107 | local = self; 1108 | } else { 1109 | try { 1110 | local = Function('return this')(); 1111 | } catch (e) { 1112 | throw new Error('polyfill failed because global object is unavailable in this environment'); 1113 | } 1114 | } 1115 | 1116 | var P = local.Promise; 1117 | 1118 | if (P) { 1119 | var promiseToString = null; 1120 | try { 1121 | promiseToString = Object.prototype.toString.call(P.resolve()); 1122 | } catch (e) { 1123 | // silently ignored 1124 | } 1125 | 1126 | if (promiseToString === '[object Promise]' && !P.cast) { 1127 | return; 1128 | } 1129 | } 1130 | 1131 | local.Promise = Promise$2; 1132 | } 1133 | 1134 | // Strange compat.. 1135 | Promise$2.polyfill = polyfill; 1136 | Promise$2.Promise = Promise$2; 1137 | 1138 | Promise$2.polyfill(); 1139 | 1140 | return Promise$2; 1141 | 1142 | }))); 1143 | 1144 | 1145 | 1146 | 1147 | }); 1148 | 1149 | var Errors = createCommonjsModule(function(module, exports) { 1150 | Object.defineProperty(exports, "__esModule", { 1151 | value: true 1152 | }); 1153 | 1154 | /** Error thrown when an HTTP request fails. */ 1155 | var HttpError = /** @class */ (function(_super) { 1156 | tslib_1.__extends(HttpError, _super); 1157 | /** Constructs a new instance of {@link HttpError}. 1158 | * 1159 | * @param {string} errorMessage A descriptive error message. 1160 | * @param {number} statusCode The HTTP status code represented by this error. 1161 | */ 1162 | function HttpError(errorMessage, statusCode) { 1163 | var _newTarget = this.constructor; 1164 | var _this = this; 1165 | var trueProto = _newTarget.prototype; 1166 | _this = _super.call(this, errorMessage) || this; 1167 | _this.statusCode = statusCode; 1168 | // Workaround issue in Typescript compiler 1169 | // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 1170 | _this.__proto__ = trueProto; 1171 | return _this; 1172 | } 1173 | return HttpError; 1174 | }(Error)); 1175 | exports.HttpError = HttpError; 1176 | /** Error thrown when a timeout elapses. */ 1177 | var TimeoutError = /** @class */ (function(_super) { 1178 | tslib_1.__extends(TimeoutError, _super); 1179 | /** Constructs a new instance of {@link TimeoutError}. 1180 | * 1181 | * @param {string} errorMessage A descriptive error message. 1182 | */ 1183 | function TimeoutError(errorMessage) { 1184 | var _newTarget = this.constructor; 1185 | if (errorMessage === void 0) { 1186 | errorMessage = "A timeout occurred."; 1187 | } 1188 | var _this = this; 1189 | var trueProto = _newTarget.prototype; 1190 | _this = _super.call(this, errorMessage) || this; 1191 | // Workaround issue in Typescript compiler 1192 | // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200 1193 | _this.__proto__ = trueProto; 1194 | return _this; 1195 | } 1196 | return TimeoutError; 1197 | }(Error)); 1198 | exports.TimeoutError = TimeoutError; 1199 | 1200 | }); 1201 | 1202 | unwrapExports(Errors); 1203 | var Errors_1 = Errors.HttpError; 1204 | var Errors_2 = Errors.TimeoutError; 1205 | 1206 | var ILogger = createCommonjsModule(function(module, exports) { 1207 | Object.defineProperty(exports, "__esModule", { 1208 | value: true 1209 | }); 1210 | // These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here. 1211 | /** Indicates the severity of a log message. 1212 | * 1213 | * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc. 1214 | */ 1215 | var LogLevel; 1216 | (function(LogLevel) { 1217 | /** Log level for very low severity diagnostic messages. */ 1218 | LogLevel[LogLevel["Trace"] = 0] = "Trace"; 1219 | /** Log level for low severity diagnostic messages. */ 1220 | LogLevel[LogLevel["Debug"] = 1] = "Debug"; 1221 | /** Log level for informational diagnostic messages. */ 1222 | LogLevel[LogLevel["Information"] = 2] = "Information"; 1223 | /** Log level for diagnostic messages that indicate a non-fatal problem. */ 1224 | LogLevel[LogLevel["Warning"] = 3] = "Warning"; 1225 | /** Log level for diagnostic messages that indicate a failure in the current operation. */ 1226 | LogLevel[LogLevel["Error"] = 4] = "Error"; 1227 | /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */ 1228 | LogLevel[LogLevel["Critical"] = 5] = "Critical"; 1229 | /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */ 1230 | LogLevel[LogLevel["None"] = 6] = "None"; 1231 | })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); 1232 | 1233 | }); 1234 | 1235 | unwrapExports(ILogger); 1236 | var ILogger_1 = ILogger.LogLevel; 1237 | 1238 | var HttpClient_1 = createCommonjsModule(function(module, exports) { 1239 | Object.defineProperty(exports, "__esModule", { 1240 | value: true 1241 | }); 1242 | 1243 | 1244 | 1245 | /** Represents an HTTP response. */ 1246 | var HttpResponse = /** @class */ (function() { 1247 | function HttpResponse(statusCode, statusText, content) { 1248 | this.statusCode = statusCode; 1249 | this.statusText = statusText; 1250 | this.content = content; 1251 | } 1252 | return HttpResponse; 1253 | }()); 1254 | exports.HttpResponse = HttpResponse; 1255 | /** Abstraction over an HTTP client. 1256 | * 1257 | * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms. 1258 | */ 1259 | var HttpClient = /** @class */ (function() { 1260 | function HttpClient() {} 1261 | HttpClient.prototype.get = function(url, options) { 1262 | return this.send(tslib_1.__assign({}, options, { 1263 | method: "GET", 1264 | url: url 1265 | })); 1266 | }; 1267 | HttpClient.prototype.post = function(url, options) { 1268 | return this.send(tslib_1.__assign({}, options, { 1269 | method: "POST", 1270 | url: url 1271 | })); 1272 | }; 1273 | HttpClient.prototype.delete = function(url, options) { 1274 | return this.send(tslib_1.__assign({}, options, { 1275 | method: "DELETE", 1276 | url: url 1277 | })); 1278 | }; 1279 | return HttpClient; 1280 | }()); 1281 | exports.HttpClient = HttpClient; 1282 | /** Default implementation of {@link HttpClient}. */ 1283 | var DefaultHttpClient = /** @class */ (function(_super) { 1284 | tslib_1.__extends(DefaultHttpClient, _super); 1285 | /** Creates a new instance of the {@link DefaultHttpClient}, using the provided {@link ILogger} to log messages. */ 1286 | function DefaultHttpClient(logger) { 1287 | var _this = _super.call(this) || this; 1288 | _this.logger = logger; 1289 | return _this; 1290 | } 1291 | /** @inheritDoc */ 1292 | var num = 1 1293 | DefaultHttpClient.prototype.send = function(request) { 1294 | var _this = this; 1295 | 1296 | return new Promise(function(resolve, reject) { 1297 | var header = { 1298 | "X-Requested-With": "XMLHttpRequest" 1299 | } 1300 | var responseType = 'text' 1301 | if (request.headers != null) { 1302 | Object.keys(request.headers) 1303 | .forEach(function(header) { 1304 | return header = { 1305 | header: request.headers[header] 1306 | }; 1307 | }); 1308 | } 1309 | if (request.responseType) { 1310 | responseType = request.responseType; 1311 | } 1312 | const xmlrequest = wx.request({ 1313 | url: request.url, 1314 | data: request.content || "", 1315 | header: header, 1316 | method: request.method, 1317 | responseType: responseType, 1318 | withCredentials: true, 1319 | success: function(res) { 1320 | if (request.abortSignal) { 1321 | request.abortSignal.onabort = null; 1322 | } 1323 | const statusText = res.errMsg.split(':')[1] 1324 | let responseText = JSON.stringify(res.data) 1325 | if (typeof res.data == "object") { 1326 | responseText = JSON.stringify(res.data) 1327 | } else { 1328 | responseText = res.data 1329 | } 1330 | if (res.statusCode >= 200 && res.statusCode < 300) { 1331 | resolve(new HttpResponse(res.statusCode, statusText, responseText)); 1332 | } else { 1333 | reject(new Errors.HttpError(responseText, res.statusCode)); 1334 | } 1335 | }, 1336 | fail: function(res) { 1337 | if (res.errMsg.includes('timeout')) { 1338 | _this.logger.log(ILogger.LogLevel.Warning, "Timeout from HTTP request."); 1339 | reject(new Errors.TimeoutError()); 1340 | } else { 1341 | _this.logger.log(ILogger.LogLevel.Warning, "Error from HTTP request. " + res.statusCode + ": " + res.errMsg); 1342 | reject(new Errors.HttpError(res.errMsg, res.statusCode)); 1343 | } 1344 | }, 1345 | complete: function(res) {}, 1346 | }) 1347 | if (request.abortSignal) { 1348 | request.abortSignal.onabort = function() { 1349 | xmlrequest.abort(); 1350 | }; 1351 | } 1352 | }); 1353 | }; 1354 | return DefaultHttpClient; 1355 | }(HttpClient)); 1356 | exports.DefaultHttpClient = DefaultHttpClient; 1357 | 1358 | }); 1359 | unwrapExports(HttpClient_1); 1360 | var HttpClient_2 = HttpClient_1.HttpResponse; 1361 | var HttpClient_3 = HttpClient_1.HttpClient; 1362 | var HttpClient_4 = HttpClient_1.DefaultHttpClient; 1363 | 1364 | var TextMessageFormat_1 = createCommonjsModule(function(module, exports) { 1365 | Object.defineProperty(exports, "__esModule", { 1366 | value: true 1367 | }); 1368 | // Not exported from index 1369 | var TextMessageFormat = /** @class */ (function() { 1370 | function TextMessageFormat() {} 1371 | TextMessageFormat.write = function(output) { 1372 | return "" + output + TextMessageFormat.RecordSeparator; 1373 | }; 1374 | TextMessageFormat.parse = function(input) { 1375 | if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) { 1376 | throw new Error("Message is incomplete."); 1377 | } 1378 | var messages = input.split(TextMessageFormat.RecordSeparator); 1379 | messages.pop(); 1380 | return messages; 1381 | }; 1382 | TextMessageFormat.RecordSeparatorCode = 0x1e; 1383 | TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode); 1384 | return TextMessageFormat; 1385 | }()); 1386 | exports.TextMessageFormat = TextMessageFormat; 1387 | 1388 | }); 1389 | 1390 | unwrapExports(TextMessageFormat_1); 1391 | var TextMessageFormat_2 = TextMessageFormat_1.TextMessageFormat; 1392 | 1393 | var HandshakeProtocol_1 = createCommonjsModule(function(module, exports) { 1394 | Object.defineProperty(exports, "__esModule", { 1395 | value: true 1396 | }); 1397 | 1398 | var HandshakeProtocol = /** @class */ (function() { 1399 | function HandshakeProtocol() {} 1400 | // Handshake request is always JSON 1401 | HandshakeProtocol.prototype.writeHandshakeRequest = function(handshakeRequest) { 1402 | return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(handshakeRequest)); 1403 | }; 1404 | HandshakeProtocol.prototype.parseHandshakeResponse = function(data) { 1405 | var responseMessage; 1406 | var messageData; 1407 | var remainingData; 1408 | if (data instanceof ArrayBuffer) { 1409 | // Format is binary but still need to read JSON text from handshake response 1410 | var binaryData = new Uint8Array(data); 1411 | var separatorIndex = binaryData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparatorCode); 1412 | if (separatorIndex === -1) { 1413 | throw new Error("Message is incomplete."); 1414 | } 1415 | // content before separator is handshake response 1416 | // optional content after is additional messages 1417 | var responseLength = separatorIndex + 1; 1418 | messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength)); 1419 | remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null; 1420 | } else { 1421 | var textData = data; 1422 | var separatorIndex = textData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparator); 1423 | if (separatorIndex === -1) { 1424 | throw new Error("Message is incomplete."); 1425 | } 1426 | // content before separator is handshake response 1427 | // optional content after is additional messages 1428 | var responseLength = separatorIndex + 1; 1429 | messageData = textData.substring(0, responseLength); 1430 | remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null; 1431 | } 1432 | // At this point we should have just the single handshake message 1433 | var messages = TextMessageFormat_1.TextMessageFormat.parse(messageData); 1434 | responseMessage = JSON.parse(messages[0]); 1435 | // multiple messages could have arrived with handshake 1436 | // return additional data to be parsed as usual, or null if all parsed 1437 | return [remainingData, responseMessage]; 1438 | }; 1439 | return HandshakeProtocol; 1440 | }()); 1441 | exports.HandshakeProtocol = HandshakeProtocol; 1442 | 1443 | }); 1444 | 1445 | unwrapExports(HandshakeProtocol_1); 1446 | var HandshakeProtocol_2 = HandshakeProtocol_1.HandshakeProtocol; 1447 | 1448 | var IHubProtocol = createCommonjsModule(function(module, exports) { 1449 | Object.defineProperty(exports, "__esModule", { 1450 | value: true 1451 | }); 1452 | /** Defines the type of a Hub Message. */ 1453 | var MessageType; 1454 | (function(MessageType) { 1455 | /** Indicates the message is an Invocation message and implements the {@link InvocationMessage} interface. */ 1456 | MessageType[MessageType["Invocation"] = 1] = "Invocation"; 1457 | /** Indicates the message is a StreamItem message and implements the {@link StreamItemMessage} interface. */ 1458 | MessageType[MessageType["StreamItem"] = 2] = "StreamItem"; 1459 | /** Indicates the message is a Completion message and implements the {@link CompletionMessage} interface. */ 1460 | MessageType[MessageType["Completion"] = 3] = "Completion"; 1461 | /** Indicates the message is a Stream Invocation message and implements the {@link StreamInvocationMessage} interface. */ 1462 | MessageType[MessageType["StreamInvocation"] = 4] = "StreamInvocation"; 1463 | /** Indicates the message is a Cancel Invocation message and implements the {@link CancelInvocationMessage} interface. */ 1464 | MessageType[MessageType["CancelInvocation"] = 5] = "CancelInvocation"; 1465 | /** Indicates the message is a Ping message and implements the {@link PingMessage} interface. */ 1466 | MessageType[MessageType["Ping"] = 6] = "Ping"; 1467 | /** Indicates the message is a Close message and implements the {@link CloseMessage} interface. */ 1468 | MessageType[MessageType["Close"] = 7] = "Close"; 1469 | })(MessageType = exports.MessageType || (exports.MessageType = {})); 1470 | 1471 | }); 1472 | 1473 | unwrapExports(IHubProtocol); 1474 | var IHubProtocol_1 = IHubProtocol.MessageType; 1475 | 1476 | var Loggers = createCommonjsModule(function(module, exports) { 1477 | Object.defineProperty(exports, "__esModule", { 1478 | value: true 1479 | }); 1480 | /** A logger that does nothing when log messages are sent to it. */ 1481 | var NullLogger = /** @class */ (function() { 1482 | function NullLogger() {} 1483 | /** @inheritDoc */ 1484 | NullLogger.prototype.log = function(logLevel, message) {}; 1485 | /** The singleton instance of the {@link NullLogger}. */ 1486 | NullLogger.instance = new NullLogger(); 1487 | return NullLogger; 1488 | }()); 1489 | exports.NullLogger = NullLogger; 1490 | 1491 | }); 1492 | 1493 | unwrapExports(Loggers); 1494 | var Loggers_1 = Loggers.NullLogger; 1495 | 1496 | var Utils = createCommonjsModule(function(module, exports) { 1497 | Object.defineProperty(exports, "__esModule", { 1498 | value: true 1499 | }); 1500 | 1501 | 1502 | 1503 | var Arg = /** @class */ (function() { 1504 | function Arg() {} 1505 | Arg.isRequired = function(val, name) { 1506 | if (val === null || val === undefined) { 1507 | throw new Error("The '" + name + "' argument is required."); 1508 | } 1509 | }; 1510 | Arg.isIn = function(val, values, name) { 1511 | // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself. 1512 | if (!(val in values)) { 1513 | throw new Error("Unknown " + name + " value: " + val + "."); 1514 | } 1515 | }; 1516 | return Arg; 1517 | }()); 1518 | exports.Arg = Arg; 1519 | 1520 | function getDataDetail(data, includeContent) { 1521 | var length = null; 1522 | if (data instanceof ArrayBuffer) { 1523 | length = "Binary data of length " + data.byteLength; 1524 | if (includeContent) { 1525 | length += ". Content: '" + formatArrayBuffer(data) + "'"; 1526 | } 1527 | } else if (typeof data === "string") { 1528 | length = "String data of length " + data.length; 1529 | if (includeContent) { 1530 | length += ". Content: '" + data + "'."; 1531 | } 1532 | } 1533 | return length; 1534 | } 1535 | exports.getDataDetail = getDataDetail; 1536 | 1537 | function formatArrayBuffer(data) { 1538 | var view = new Uint8Array(data); 1539 | // Uint8Array.map only supports returning another Uint8Array? 1540 | var str = ""; 1541 | view.forEach(function(num) { 1542 | var pad = num < 16 ? "0" : ""; 1543 | str += "0x" + pad + num.toString(16) + " "; 1544 | }); 1545 | // Trim of trailing space. 1546 | return str.substr(0, str.length - 1); 1547 | } 1548 | exports.formatArrayBuffer = formatArrayBuffer; 1549 | 1550 | function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, logMessageContent) { 1551 | return tslib_1.__awaiter(this, void 0, void 0, function() { 1552 | var headers, token, response, _a; 1553 | return tslib_1.__generator(this, function(_b) { 1554 | switch (_b.label) { 1555 | case 0: 1556 | return [4 /*yield*/ , accessTokenFactory()]; 1557 | case 1: 1558 | token = _b.sent(); 1559 | if (token) { 1560 | headers = (_a = {}, _a["Authorization"] = "Bearer " + token, _a); 1561 | } 1562 | logger.log(ILogger.LogLevel.Trace, "(" + transportName + " transport) sending data. " + getDataDetail(content, logMessageContent) + "."); 1563 | return [4 /*yield*/ , httpClient.post(url, { 1564 | content: content, 1565 | headers: headers, 1566 | })]; 1567 | case 2: 1568 | response = _b.sent(); 1569 | logger.log(ILogger.LogLevel.Trace, "(" + transportName + " transport) request complete. Response status: " + response.statusCode + "."); 1570 | return [2 /*return*/ ]; 1571 | } 1572 | }); 1573 | }); 1574 | } 1575 | exports.sendMessage = sendMessage; 1576 | 1577 | function createLogger(logger) { 1578 | if (logger === undefined) { 1579 | return new ConsoleLogger(ILogger.LogLevel.Information); 1580 | } 1581 | if (logger === null) { 1582 | return Loggers.NullLogger.instance; 1583 | } 1584 | if (logger.log) { 1585 | return logger; 1586 | } 1587 | return new ConsoleLogger(logger); 1588 | } 1589 | exports.createLogger = createLogger; 1590 | var Subject = /** @class */ (function() { 1591 | function Subject(cancelCallback) { 1592 | this.observers = []; 1593 | this.cancelCallback = cancelCallback; 1594 | } 1595 | Subject.prototype.next = function(item) { 1596 | for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { 1597 | var observer = _a[_i]; 1598 | observer.next(item); 1599 | } 1600 | }; 1601 | Subject.prototype.error = function(err) { 1602 | for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { 1603 | var observer = _a[_i]; 1604 | if (observer.error) { 1605 | observer.error(err); 1606 | } 1607 | } 1608 | }; 1609 | Subject.prototype.complete = function() { 1610 | for (var _i = 0, _a = this.observers; _i < _a.length; _i++) { 1611 | var observer = _a[_i]; 1612 | if (observer.complete) { 1613 | observer.complete(); 1614 | } 1615 | } 1616 | }; 1617 | Subject.prototype.subscribe = function(observer) { 1618 | this.observers.push(observer); 1619 | return new SubjectSubscription(this, observer); 1620 | }; 1621 | return Subject; 1622 | }()); 1623 | exports.Subject = Subject; 1624 | var SubjectSubscription = /** @class */ (function() { 1625 | function SubjectSubscription(subject, observer) { 1626 | this.subject = subject; 1627 | this.observer = observer; 1628 | } 1629 | SubjectSubscription.prototype.dispose = function() { 1630 | var index = this.subject.observers.indexOf(this.observer); 1631 | if (index > -1) { 1632 | this.subject.observers.splice(index, 1); 1633 | } 1634 | if (this.subject.observers.length === 0) { 1635 | this.subject.cancelCallback().catch(function(_) {}); 1636 | } 1637 | }; 1638 | return SubjectSubscription; 1639 | }()); 1640 | exports.SubjectSubscription = SubjectSubscription; 1641 | var ConsoleLogger = /** @class */ (function() { 1642 | function ConsoleLogger(minimumLogLevel) { 1643 | this.minimumLogLevel = minimumLogLevel; 1644 | } 1645 | ConsoleLogger.prototype.log = function(logLevel, message) { 1646 | if (logLevel >= this.minimumLogLevel) { 1647 | switch (logLevel) { 1648 | case ILogger.LogLevel.Critical: 1649 | case ILogger.LogLevel.Error: 1650 | console.error(ILogger.LogLevel[logLevel] + ": " + message); 1651 | break; 1652 | case ILogger.LogLevel.Warning: 1653 | console.warn(ILogger.LogLevel[logLevel] + ": " + message); 1654 | break; 1655 | case ILogger.LogLevel.Information: 1656 | console.info(ILogger.LogLevel[logLevel] + ": " + message); 1657 | break; 1658 | default: 1659 | // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug 1660 | console.log(ILogger.LogLevel[logLevel] + ": " + message); 1661 | break; 1662 | } 1663 | } 1664 | }; 1665 | return ConsoleLogger; 1666 | }()); 1667 | exports.ConsoleLogger = ConsoleLogger; 1668 | 1669 | }); 1670 | 1671 | unwrapExports(Utils); 1672 | var Utils_1 = Utils.Arg; 1673 | var Utils_2 = Utils.getDataDetail; 1674 | var Utils_3 = Utils.formatArrayBuffer; 1675 | var Utils_4 = Utils.sendMessage; 1676 | var Utils_5 = Utils.createLogger; 1677 | var Utils_6 = Utils.Subject; 1678 | var Utils_7 = Utils.SubjectSubscription; 1679 | var Utils_8 = Utils.ConsoleLogger; 1680 | 1681 | var HubConnection_1 = createCommonjsModule(function(module, exports) { 1682 | Object.defineProperty(exports, "__esModule", { 1683 | value: true 1684 | }); 1685 | 1686 | 1687 | 1688 | 1689 | 1690 | var DEFAULT_TIMEOUT_IN_MS = 30 * 1000; 1691 | /** Represents a connection to a SignalR Hub. */ 1692 | var HubConnection = /** @class */ (function() { 1693 | function HubConnection(connection, logger, protocol) { 1694 | var _this = this; 1695 | Utils.Arg.isRequired(connection, "connection"); 1696 | Utils.Arg.isRequired(logger, "logger"); 1697 | Utils.Arg.isRequired(protocol, "protocol"); 1698 | this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS; 1699 | this.logger = logger; 1700 | this.protocol = protocol; 1701 | this.connection = connection; 1702 | this.handshakeProtocol = new HandshakeProtocol_1.HandshakeProtocol(); 1703 | this.connection.onreceive = function(data) { 1704 | return _this.processIncomingData(data); 1705 | }; 1706 | this.connection.onclose = function(error) { 1707 | return _this.connectionClosed(error); 1708 | }; 1709 | this.callbacks = {}; 1710 | this.methods = {}; 1711 | this.closedCallbacks = []; 1712 | this.id = 0; 1713 | } 1714 | /** @internal */ 1715 | // Using a public static factory method means we can have a private constructor and an _internal_ 1716 | // create method that can be used by HubConnectionBuilder. An "internal" constructor would just 1717 | // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a 1718 | // public parameter-less constructor. 1719 | HubConnection.create = function(connection, logger, protocol) { 1720 | return new HubConnection(connection, logger, protocol); 1721 | }; 1722 | /** Starts the connection. 1723 | * 1724 | * @returns {Promise} A Promise that resolves when the connection has been successfully established, or rejects with an error. 1725 | */ 1726 | HubConnection.prototype.start = function() { 1727 | return tslib_1.__awaiter(this, void 0, void 0, function() { 1728 | var handshakeRequest; 1729 | return tslib_1.__generator(this, function(_a) { 1730 | switch (_a.label) { 1731 | case 0: 1732 | handshakeRequest = { 1733 | protocol: this.protocol.name, 1734 | version: this.protocol.version, 1735 | }; 1736 | this.logger.log(ILogger.LogLevel.Debug, "Starting HubConnection."); 1737 | this.receivedHandshakeResponse = false; 1738 | return [4 /*yield*/ , this.connection.start(this.protocol.transferFormat)]; 1739 | case 1: 1740 | _a.sent(); 1741 | this.logger.log(ILogger.LogLevel.Debug, "Sending handshake request."); 1742 | return [4 /*yield*/ , this.connection.send(this.handshakeProtocol.writeHandshakeRequest(handshakeRequest))]; 1743 | case 2: 1744 | _a.sent(); 1745 | this.logger.log(ILogger.LogLevel.Information, "Using HubProtocol '" + this.protocol.name + "'."); 1746 | // defensively cleanup timeout in case we receive a message from the server before we finish start 1747 | this.cleanupTimeout(); 1748 | this.configureTimeout(); 1749 | return [2 /*return*/ ]; 1750 | } 1751 | }); 1752 | }); 1753 | }; 1754 | /** Stops the connection. 1755 | * 1756 | * @returns {Promise} A Promise that resolves when the connection has been successfully terminated, or rejects with an error. 1757 | */ 1758 | HubConnection.prototype.stop = function() { 1759 | this.logger.log(ILogger.LogLevel.Debug, "Stopping HubConnection."); 1760 | this.cleanupTimeout(); 1761 | return this.connection.stop(); 1762 | }; 1763 | /** Invokes a streaming hub method on the server using the specified name and arguments. 1764 | * 1765 | * @typeparam T The type of the items returned by the server. 1766 | * @param {string} methodName The name of the server method to invoke. 1767 | * @param {any[]} args The arguments used to invoke the server method. 1768 | * @returns {IStreamResult} An object that yields results from the server as they are received. 1769 | */ 1770 | HubConnection.prototype.stream = function(methodName) { 1771 | var _this = this; 1772 | var args = []; 1773 | for (var _i = 1; _i < arguments.length; _i++) { 1774 | args[_i - 1] = arguments[_i]; 1775 | } 1776 | var invocationDescriptor = this.createStreamInvocation(methodName, args); 1777 | var subject = new Utils.Subject(function() { 1778 | var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId); 1779 | var cancelMessage = _this.protocol.writeMessage(cancelInvocation); 1780 | delete _this.callbacks[invocationDescriptor.invocationId]; 1781 | return _this.connection.send(cancelMessage); 1782 | }); 1783 | this.callbacks[invocationDescriptor.invocationId] = function(invocationEvent, error) { 1784 | if (error) { 1785 | subject.error(error); 1786 | return; 1787 | } 1788 | if (invocationEvent.type === IHubProtocol.MessageType.Completion) { 1789 | if (invocationEvent.error) { 1790 | subject.error(new Error(invocationEvent.error)); 1791 | } else { 1792 | subject.complete(); 1793 | } 1794 | } else { 1795 | subject.next((invocationEvent.item)); 1796 | } 1797 | }; 1798 | var message = this.protocol.writeMessage(invocationDescriptor); 1799 | this.connection.send(message) 1800 | .catch(function(e) { 1801 | subject.error(e); 1802 | delete _this.callbacks[invocationDescriptor.invocationId]; 1803 | }); 1804 | return subject; 1805 | }; 1806 | /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver. 1807 | * 1808 | * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still 1809 | * be processing the invocation. 1810 | * 1811 | * @param {string} methodName The name of the server method to invoke. 1812 | * @param {any[]} args The arguments used to invoke the server method. 1813 | * @returns {Promise} A Promise that resolves when the invocation has been successfully sent, or rejects with an error. 1814 | */ 1815 | HubConnection.prototype.send = function(methodName) { 1816 | var args = []; 1817 | for (var _i = 1; _i < arguments.length; _i++) { 1818 | args[_i - 1] = arguments[_i]; 1819 | } 1820 | var invocationDescriptor = this.createInvocation(methodName, args, true); 1821 | var message = this.protocol.writeMessage(invocationDescriptor); 1822 | return this.connection.send(message); 1823 | }; 1824 | /** Invokes a hub method on the server using the specified name and arguments. 1825 | * 1826 | * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise 1827 | * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of 1828 | * resolving the Promise. 1829 | * 1830 | * @typeparam T The expected return type. 1831 | * @param {string} methodName The name of the server method to invoke. 1832 | * @param {any[]} args The arguments used to invoke the server method. 1833 | * @returns {Promise} A Promise that resolves with the result of the server method (if any), or rejects with an error. 1834 | */ 1835 | HubConnection.prototype.invoke = function(methodName) { 1836 | var _this = this; 1837 | var args = []; 1838 | for (var _i = 1; _i < arguments.length; _i++) { 1839 | args[_i - 1] = arguments[_i]; 1840 | } 1841 | var invocationDescriptor = this.createInvocation(methodName, args, false); 1842 | var p = new Promise(function(resolve, reject) { 1843 | _this.callbacks[invocationDescriptor.invocationId] = function(invocationEvent, error) { 1844 | if (error) { 1845 | reject(error); 1846 | return; 1847 | } 1848 | if (invocationEvent.type === IHubProtocol.MessageType.Completion) { 1849 | var completionMessage = invocationEvent; 1850 | if (completionMessage.error) { 1851 | reject(new Error(completionMessage.error)); 1852 | } else { 1853 | resolve(completionMessage.result); 1854 | } 1855 | } else { 1856 | reject(new Error("Unexpected message type: " + invocationEvent.type)); 1857 | } 1858 | }; 1859 | var message = _this.protocol.writeMessage(invocationDescriptor); 1860 | _this.connection.send(message) 1861 | .catch(function(e) { 1862 | reject(e); 1863 | delete _this.callbacks[invocationDescriptor.invocationId]; 1864 | }); 1865 | }); 1866 | return p; 1867 | }; 1868 | /** Registers a handler that will be invoked when the hub method with the specified method name is invoked. 1869 | * 1870 | * @param {string} methodName The name of the hub method to define. 1871 | * @param {Function} newMethod The handler that will be raised when the hub method is invoked. 1872 | */ 1873 | HubConnection.prototype.on = function(methodName, newMethod) { 1874 | if (!methodName || !newMethod) { 1875 | return; 1876 | } 1877 | methodName = methodName.toLowerCase(); 1878 | if (!this.methods[methodName]) { 1879 | this.methods[methodName] = []; 1880 | } 1881 | // Preventing adding the same handler multiple times. 1882 | if (this.methods[methodName].indexOf(newMethod) !== -1) { 1883 | return; 1884 | } 1885 | this.methods[methodName].push(newMethod); 1886 | }; 1887 | HubConnection.prototype.off = function(methodName, method) { 1888 | if (!methodName) { 1889 | return; 1890 | } 1891 | methodName = methodName.toLowerCase(); 1892 | var handlers = this.methods[methodName]; 1893 | if (!handlers) { 1894 | return; 1895 | } 1896 | if (method) { 1897 | var removeIdx = handlers.indexOf(method); 1898 | if (removeIdx !== -1) { 1899 | handlers.splice(removeIdx, 1); 1900 | if (handlers.length === 0) { 1901 | delete this.methods[methodName]; 1902 | } 1903 | } 1904 | } else { 1905 | delete this.methods[methodName]; 1906 | } 1907 | }; 1908 | /** Registers a handler that will be invoked when the connection is closed. 1909 | * 1910 | * @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any). 1911 | */ 1912 | HubConnection.prototype.onclose = function(callback) { 1913 | if (callback) { 1914 | this.closedCallbacks.push(callback); 1915 | } 1916 | }; 1917 | HubConnection.prototype.processIncomingData = function(data) { 1918 | this.cleanupTimeout(); 1919 | if (!this.receivedHandshakeResponse) { 1920 | data = this.processHandshakeResponse(data); 1921 | this.receivedHandshakeResponse = true; 1922 | } 1923 | // Data may have all been read when processing handshake response 1924 | if (data) { 1925 | // Parse the messages 1926 | var messages = this.protocol.parseMessages(data, this.logger); 1927 | for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) { 1928 | var message = messages_1[_i]; 1929 | switch (message.type) { 1930 | case IHubProtocol.MessageType.Invocation: 1931 | this.invokeClientMethod(message); 1932 | break; 1933 | case IHubProtocol.MessageType.StreamItem: 1934 | case IHubProtocol.MessageType.Completion: 1935 | var callback = this.callbacks[message.invocationId]; 1936 | if (callback != null) { 1937 | if (message.type === IHubProtocol.MessageType.Completion) { 1938 | delete this.callbacks[message.invocationId]; 1939 | } 1940 | callback(message); 1941 | } 1942 | break; 1943 | case IHubProtocol.MessageType.Ping: 1944 | // Don't care about pings 1945 | break; 1946 | case IHubProtocol.MessageType.Close: 1947 | this.logger.log(ILogger.LogLevel.Information, "Close message received from server."); 1948 | this.connection.stop(message.error ? new Error("Server returned an error on close: " + message.error) : null); 1949 | break; 1950 | default: 1951 | this.logger.log(ILogger.LogLevel.Warning, "Invalid message type: " + message.type); 1952 | break; 1953 | } 1954 | } 1955 | } 1956 | this.configureTimeout(); 1957 | }; 1958 | HubConnection.prototype.processHandshakeResponse = function(data) { 1959 | var responseMessage; 1960 | var remainingData; 1961 | try { 1962 | _a = this.handshakeProtocol.parseHandshakeResponse(data), remainingData = _a[0], responseMessage = _a[1]; 1963 | } catch (e) { 1964 | var message = "Error parsing handshake response: " + e; 1965 | this.logger.log(ILogger.LogLevel.Error, message); 1966 | var error = new Error(message); 1967 | this.connection.stop(error); 1968 | throw error; 1969 | } 1970 | if (responseMessage.error) { 1971 | var message = "Server returned handshake error: " + responseMessage.error; 1972 | this.logger.log(ILogger.LogLevel.Error, message); 1973 | this.connection.stop(new Error(message)); 1974 | } else { 1975 | this.logger.log(ILogger.LogLevel.Debug, "Server handshake complete."); 1976 | } 1977 | return remainingData; 1978 | var _a; 1979 | }; 1980 | HubConnection.prototype.configureTimeout = function() { 1981 | var _this = this; 1982 | if (!this.connection.features || !this.connection.features.inherentKeepAlive) { 1983 | // Set the timeout timer 1984 | this.timeoutHandle = setTimeout(function() { 1985 | return _this.serverTimeout(); 1986 | }, this.serverTimeoutInMilliseconds); 1987 | } 1988 | }; 1989 | HubConnection.prototype.serverTimeout = function() { 1990 | // The server hasn't talked to us in a while. It doesn't like us anymore ... :( 1991 | // Terminate the connection 1992 | this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server.")); 1993 | }; 1994 | HubConnection.prototype.invokeClientMethod = function(invocationMessage) { 1995 | var _this = this; 1996 | var methods = this.methods[invocationMessage.target.toLowerCase()]; 1997 | if (methods) { 1998 | methods.forEach(function(m) { 1999 | return m.apply(_this, invocationMessage.arguments); 2000 | }); 2001 | if (invocationMessage.invocationId) { 2002 | // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response. 2003 | var message = "Server requested a response, which is not supported in this version of the client."; 2004 | this.logger.log(ILogger.LogLevel.Error, message); 2005 | this.connection.stop(new Error(message)); 2006 | } 2007 | } else { 2008 | this.logger.log(ILogger.LogLevel.Warning, "No client method with the name '" + invocationMessage.target + "' found."); 2009 | } 2010 | }; 2011 | HubConnection.prototype.connectionClosed = function(error) { 2012 | var _this = this; 2013 | var callbacks = this.callbacks; 2014 | this.callbacks = {}; 2015 | Object.keys(callbacks) 2016 | .forEach(function(key) { 2017 | var callback = callbacks[key]; 2018 | callback(undefined, error ? error : new Error("Invocation canceled due to connection being closed.")); 2019 | }); 2020 | this.cleanupTimeout(); 2021 | this.closedCallbacks.forEach(function(c) { 2022 | return c.apply(_this, [error]); 2023 | }); 2024 | }; 2025 | HubConnection.prototype.cleanupTimeout = function() { 2026 | if (this.timeoutHandle) { 2027 | clearTimeout(this.timeoutHandle); 2028 | } 2029 | }; 2030 | HubConnection.prototype.createInvocation = function(methodName, args, nonblocking) { 2031 | if (nonblocking) { 2032 | return { 2033 | arguments: args, 2034 | target: methodName, 2035 | type: IHubProtocol.MessageType.Invocation, 2036 | }; 2037 | } else { 2038 | var id = this.id; 2039 | this.id++; 2040 | return { 2041 | arguments: args, 2042 | invocationId: id.toString(), 2043 | target: methodName, 2044 | type: IHubProtocol.MessageType.Invocation, 2045 | }; 2046 | } 2047 | }; 2048 | HubConnection.prototype.createStreamInvocation = function(methodName, args) { 2049 | var id = this.id; 2050 | this.id++; 2051 | return { 2052 | arguments: args, 2053 | invocationId: id.toString(), 2054 | target: methodName, 2055 | type: IHubProtocol.MessageType.StreamInvocation, 2056 | }; 2057 | }; 2058 | HubConnection.prototype.createCancelInvocation = function(id) { 2059 | return { 2060 | invocationId: id, 2061 | type: IHubProtocol.MessageType.CancelInvocation, 2062 | }; 2063 | }; 2064 | return HubConnection; 2065 | }()); 2066 | exports.HubConnection = HubConnection; 2067 | 2068 | }); 2069 | 2070 | unwrapExports(HubConnection_1); 2071 | var HubConnection_2 = HubConnection_1.HubConnection; 2072 | 2073 | var ITransport = createCommonjsModule(function(module, exports) { 2074 | Object.defineProperty(exports, "__esModule", { 2075 | value: true 2076 | }); 2077 | // This will be treated as a bit flag in the future, so we keep it using power-of-two values. 2078 | /** Specifies a specific HTTP transport type. */ 2079 | var HttpTransportType; 2080 | (function(HttpTransportType) { 2081 | /** Specifies no transport preference. */ 2082 | HttpTransportType[HttpTransportType["None"] = 0] = "None"; 2083 | /** Specifies the WebSockets transport. */ 2084 | HttpTransportType[HttpTransportType["WebSockets"] = 1] = "WebSockets"; 2085 | /** Specifies the Server-Sent Events transport. */ 2086 | HttpTransportType[HttpTransportType["ServerSentEvents"] = 2] = "ServerSentEvents"; 2087 | /** Specifies the Long Polling transport. */ 2088 | HttpTransportType[HttpTransportType["LongPolling"] = 4] = "LongPolling"; 2089 | })(HttpTransportType = exports.HttpTransportType || (exports.HttpTransportType = {})); 2090 | /** Specifies the transfer format for a connection. */ 2091 | var TransferFormat; 2092 | (function(TransferFormat) { 2093 | /** Specifies that only text data will be transmitted over the connection. */ 2094 | TransferFormat[TransferFormat["Text"] = 1] = "Text"; 2095 | /** Specifies that binary data will be transmitted over the connection. */ 2096 | TransferFormat[TransferFormat["Binary"] = 2] = "Binary"; 2097 | })(TransferFormat = exports.TransferFormat || (exports.TransferFormat = {})); 2098 | 2099 | }); 2100 | 2101 | unwrapExports(ITransport); 2102 | var ITransport_1 = ITransport.HttpTransportType; 2103 | var ITransport_2 = ITransport.TransferFormat; 2104 | 2105 | var AbortController_1 = createCommonjsModule(function(module, exports) { 2106 | Object.defineProperty(exports, "__esModule", { 2107 | value: true 2108 | }); 2109 | // Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController 2110 | // We don't actually ever use the API being polyfilled, we always use the polyfill because 2111 | // it's a very new API right now. 2112 | // Not exported from index. 2113 | var AbortController = /** @class */ (function() { 2114 | function AbortController() { 2115 | this.isAborted = false; 2116 | } 2117 | AbortController.prototype.abort = function() { 2118 | if (!this.isAborted) { 2119 | this.isAborted = true; 2120 | if (this.onabort) { 2121 | this.onabort(); 2122 | } 2123 | } 2124 | }; 2125 | Object.defineProperty(AbortController.prototype, "signal", { 2126 | get: function() { 2127 | return this; 2128 | }, 2129 | enumerable: true, 2130 | configurable: true 2131 | }); 2132 | Object.defineProperty(AbortController.prototype, "aborted", { 2133 | get: function() { 2134 | return this.isAborted; 2135 | }, 2136 | enumerable: true, 2137 | configurable: true 2138 | }); 2139 | return AbortController; 2140 | }()); 2141 | exports.AbortController = AbortController; 2142 | 2143 | }); 2144 | 2145 | unwrapExports(AbortController_1); 2146 | var AbortController_2 = AbortController_1.AbortController; 2147 | 2148 | var LongPollingTransport_1 = createCommonjsModule(function(module, exports) { 2149 | Object.defineProperty(exports, "__esModule", { 2150 | value: true 2151 | }); 2152 | 2153 | 2154 | 2155 | 2156 | 2157 | 2158 | var SHUTDOWN_TIMEOUT = 5 * 1000; 2159 | // Not exported from 'index', this type is internal. 2160 | var LongPollingTransport = /** @class */ (function() { 2161 | function LongPollingTransport(httpClient, accessTokenFactory, logger, logMessageContent, shutdownTimeout) { 2162 | this.httpClient = httpClient; 2163 | this.accessTokenFactory = accessTokenFactory || (function() { 2164 | return null; 2165 | }); 2166 | this.logger = logger; 2167 | this.pollAbort = new AbortController_1.AbortController(); 2168 | this.logMessageContent = logMessageContent; 2169 | this.shutdownTimeout = shutdownTimeout || SHUTDOWN_TIMEOUT; 2170 | } 2171 | Object.defineProperty(LongPollingTransport.prototype, "pollAborted", { 2172 | // This is an internal type, not exported from 'index' so this is really just internal. 2173 | get: function() { 2174 | return this.pollAbort.aborted; 2175 | }, 2176 | enumerable: true, 2177 | configurable: true 2178 | }); 2179 | LongPollingTransport.prototype.connect = function(url, transferFormat) { 2180 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2181 | var pollOptions, token, closeError, pollUrl, response; 2182 | return tslib_1.__generator(this, function(_a) { 2183 | switch (_a.label) { 2184 | case 0: 2185 | Utils.Arg.isRequired(url, "url"); 2186 | Utils.Arg.isRequired(transferFormat, "transferFormat"); 2187 | Utils.Arg.isIn(transferFormat, ITransport.TransferFormat, "transferFormat"); 2188 | this.url = url; 2189 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Connecting"); 2190 | if (transferFormat === ITransport.TransferFormat.Binary) { 2191 | 2192 | // This will work if we fix: https://github.com/aspnet/SignalR/issues/742 2193 | throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported."); 2194 | } 2195 | pollOptions = { 2196 | abortSignal: this.pollAbort.signal, 2197 | headers: {}, 2198 | timeout: 90000, 2199 | }; 2200 | if (transferFormat === ITransport.TransferFormat.Binary) { 2201 | pollOptions.responseType = "arraybuffer"; 2202 | } 2203 | return [4 /*yield*/ , this.accessTokenFactory()]; 2204 | case 1: 2205 | token = _a.sent(); 2206 | this.updateHeaderToken(pollOptions, token); 2207 | pollUrl = url + "&_=" + Date.now(); 2208 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl); 2209 | return [4 /*yield*/ , this.httpClient.get(pollUrl, pollOptions)]; 2210 | case 2: 2211 | response = _a.sent(); 2212 | if (response.statusCode !== 200) { 2213 | this.logger.log(ILogger.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode); 2214 | // Mark running as false so that the poll immediately ends and runs the close logic 2215 | closeError = new Errors.HttpError(response.statusText, response.statusCode); 2216 | this.running = false; 2217 | } else { 2218 | this.running = true; 2219 | } 2220 | this.poll(this.url, pollOptions, closeError); 2221 | return [2 /*return*/ , Promise.resolve()]; 2222 | } 2223 | }); 2224 | }); 2225 | }; 2226 | LongPollingTransport.prototype.updateHeaderToken = function(request, token) { 2227 | if (token) { 2228 | // tslint:disable-next-line:no-string-literal 2229 | request.headers["Authorization"] = "Bearer " + token; 2230 | return; 2231 | } 2232 | // tslint:disable-next-line:no-string-literal 2233 | if (request.headers["Authorization"]) { 2234 | // tslint:disable-next-line:no-string-literal 2235 | delete request.headers["Authorization"]; 2236 | } 2237 | }; 2238 | LongPollingTransport.prototype.poll = function(url, pollOptions, closeError) { 2239 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2240 | var token, pollUrl, response, e_1; 2241 | return tslib_1.__generator(this, function(_a) { 2242 | switch (_a.label) { 2243 | case 0: 2244 | _a.trys.push([0, , 8, 9]); 2245 | _a.label = 1; 2246 | case 1: 2247 | if (!this.running) return [3 /*break*/ , 7]; 2248 | return [4 /*yield*/ , this.accessTokenFactory()]; 2249 | case 2: 2250 | token = _a.sent(); 2251 | this.updateHeaderToken(pollOptions, token); 2252 | _a.label = 3; 2253 | case 3: 2254 | _a.trys.push([3, 5, , 6]); 2255 | pollUrl = url + "&_=" + Date.now(); 2256 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl); 2257 | return [4 /*yield*/ , this.httpClient.get(pollUrl, pollOptions)]; 2258 | case 4: 2259 | response = _a.sent(); 2260 | if (response.statusCode === 204) { 2261 | this.logger.log(ILogger.LogLevel.Information, "(LongPolling transport) Poll terminated by server"); 2262 | this.running = false; 2263 | } else if (response.statusCode !== 200) { 2264 | this.logger.log(ILogger.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode); 2265 | // Unexpected status code 2266 | closeError = new Errors.HttpError(response.statusText, response.statusCode); 2267 | this.running = false; 2268 | } else { 2269 | // Process the response 2270 | if (response.content) { 2271 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) data received. " + Utils.getDataDetail(response.content, this.logMessageContent)); 2272 | if (this.onreceive) { 2273 | this.onreceive(response.content); 2274 | } 2275 | } else { 2276 | // This is another way timeout manifest. 2277 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing."); 2278 | } 2279 | } 2280 | return [3 /*break*/ , 6]; 2281 | case 5: 2282 | e_1 = _a.sent(); 2283 | if (!this.running) { 2284 | // Log but disregard errors that occur after we were stopped by DELETE 2285 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Poll errored after shutdown: " + e_1.message); 2286 | } else { 2287 | if (e_1 instanceof Errors.TimeoutError) { 2288 | // Ignore timeouts and reissue the poll. 2289 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing."); 2290 | } else { 2291 | // Close the connection with the error as the result. 2292 | closeError = e_1; 2293 | this.running = false; 2294 | } 2295 | } 2296 | return [3 /*break*/ , 6]; 2297 | case 6: 2298 | return [3 /*break*/ , 1]; 2299 | case 7: 2300 | return [3 /*break*/ , 9]; 2301 | case 8: 2302 | // Indicate that we've stopped so the shutdown timer doesn't get registered. 2303 | this.stopped = true; 2304 | // Clean up the shutdown timer if it was registered 2305 | if (this.shutdownTimer) { 2306 | clearTimeout(this.shutdownTimer); 2307 | } 2308 | // Fire our onclosed event 2309 | if (this.onclose) { 2310 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Firing onclose event. Error: " + (closeError || "")); 2311 | this.onclose(closeError); 2312 | } 2313 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Transport finished."); 2314 | return [7 /*endfinally*/ ]; 2315 | case 9: 2316 | return [2 /*return*/ ]; 2317 | } 2318 | }); 2319 | }); 2320 | }; 2321 | LongPollingTransport.prototype.send = function(data) { 2322 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2323 | return tslib_1.__generator(this, function(_a) { 2324 | if (!this.running) { 2325 | return [2 /*return*/ , Promise.reject(new Error("Cannot send until the transport is connected"))]; 2326 | } 2327 | return [2 /*return*/ , Utils.sendMessage(this.logger, "LongPolling", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent)]; 2328 | }); 2329 | }); 2330 | }; 2331 | LongPollingTransport.prototype.stop = function() { 2332 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2333 | var _this = this; 2334 | var deleteOptions, token, response; 2335 | return tslib_1.__generator(this, function(_a) { 2336 | switch (_a.label) { 2337 | case 0: 2338 | _a.trys.push([0, , 3, 4]); 2339 | this.running = false; 2340 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) sending DELETE request to " + this.url + "."); 2341 | deleteOptions = { 2342 | headers: {}, 2343 | }; 2344 | return [4 /*yield*/ , this.accessTokenFactory()]; 2345 | case 1: 2346 | token = _a.sent(); 2347 | this.updateHeaderToken(deleteOptions, token); 2348 | return [4 /*yield*/ , this.httpClient.delete(this.url, deleteOptions)]; 2349 | case 2: 2350 | response = _a.sent(); 2351 | this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) DELETE request accepted."); 2352 | return [3 /*break*/ , 4]; 2353 | case 3: 2354 | // Abort the poll after the shutdown timeout if the server doesn't stop the poll. 2355 | if (!this.stopped) { 2356 | this.shutdownTimer = setTimeout(function() { 2357 | _this.logger.log(ILogger.LogLevel.Warning, "(LongPolling transport) server did not terminate after DELETE request, canceling poll."); 2358 | // Abort any outstanding poll 2359 | _this.pollAbort.abort(); 2360 | }, this.shutdownTimeout); 2361 | } 2362 | return [7 /*endfinally*/ ]; 2363 | case 4: 2364 | return [2 /*return*/ ]; 2365 | } 2366 | }); 2367 | }); 2368 | }; 2369 | return LongPollingTransport; 2370 | }()); 2371 | exports.LongPollingTransport = LongPollingTransport; 2372 | 2373 | }); 2374 | 2375 | unwrapExports(LongPollingTransport_1); 2376 | var LongPollingTransport_2 = LongPollingTransport_1.LongPollingTransport; 2377 | 2378 | var ServerSentEventsTransport_1 = createCommonjsModule(function(module, exports) { 2379 | Object.defineProperty(exports, "__esModule", { 2380 | value: true 2381 | }); 2382 | 2383 | 2384 | 2385 | 2386 | var ServerSentEventsTransport = /** @class */ (function() { 2387 | function ServerSentEventsTransport(httpClient, accessTokenFactory, logger, logMessageContent) { 2388 | this.httpClient = httpClient; 2389 | this.accessTokenFactory = accessTokenFactory || (function() { 2390 | return null; 2391 | }); 2392 | this.logger = logger; 2393 | this.logMessageContent = logMessageContent; 2394 | } 2395 | ServerSentEventsTransport.prototype.connect = function(url, transferFormat) { 2396 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2397 | var _this = this; 2398 | var token; 2399 | return tslib_1.__generator(this, function(_a) { 2400 | switch (_a.label) { 2401 | case 0: 2402 | Utils.Arg.isRequired(url, "url"); 2403 | Utils.Arg.isRequired(transferFormat, "transferFormat"); 2404 | Utils.Arg.isIn(transferFormat, ITransport.TransferFormat, "transferFormat"); 2405 | if (typeof(EventSource) === "undefined") { 2406 | throw new Error("'EventSource' is not supported in your environment."); 2407 | } 2408 | this.logger.log(ILogger.LogLevel.Trace, "(SSE transport) Connecting"); 2409 | return [4 /*yield*/ , this.accessTokenFactory()]; 2410 | case 1: 2411 | token = _a.sent(); 2412 | if (token) { 2413 | url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); 2414 | } 2415 | this.url = url; 2416 | return [2 /*return*/ , new Promise(function(resolve, reject) { 2417 | var opened = false; 2418 | if (transferFormat !== ITransport.TransferFormat.Text) { 2419 | reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format")); 2420 | } 2421 | var eventSource = new EventSource(url, { 2422 | withCredentials: true 2423 | }); 2424 | try { 2425 | eventSource.onmessage = function(e) { 2426 | if (_this.onreceive) { 2427 | try { 2428 | _this.logger.log(ILogger.LogLevel.Trace, "(SSE transport) data received. " + Utils.getDataDetail(e.data, _this.logMessageContent) + "."); 2429 | _this.onreceive(e.data); 2430 | } catch (error) { 2431 | if (_this.onclose) { 2432 | _this.onclose(error); 2433 | } 2434 | return; 2435 | } 2436 | } 2437 | }; 2438 | eventSource.onerror = function(e) { 2439 | var error = new Error(e.message || "Error occurred"); 2440 | if (opened) { 2441 | _this.close(error); 2442 | } else { 2443 | reject(error); 2444 | } 2445 | }; 2446 | eventSource.onopen = function() { 2447 | _this.logger.log(ILogger.LogLevel.Information, "SSE connected to " + _this.url); 2448 | _this.eventSource = eventSource; 2449 | opened = true; 2450 | resolve(); 2451 | }; 2452 | } catch (e) { 2453 | return Promise.reject(e); 2454 | } 2455 | })]; 2456 | } 2457 | }); 2458 | }); 2459 | }; 2460 | ServerSentEventsTransport.prototype.send = function(data) { 2461 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2462 | return tslib_1.__generator(this, function(_a) { 2463 | if (!this.eventSource) { 2464 | return [2 /*return*/ , Promise.reject(new Error("Cannot send until the transport is connected"))]; 2465 | } 2466 | return [2 /*return*/ , Utils.sendMessage(this.logger, "SSE", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent)]; 2467 | }); 2468 | }); 2469 | }; 2470 | ServerSentEventsTransport.prototype.stop = function() { 2471 | this.close(); 2472 | return Promise.resolve(); 2473 | }; 2474 | ServerSentEventsTransport.prototype.close = function(e) { 2475 | if (this.eventSource) { 2476 | this.eventSource.close(); 2477 | this.eventSource = null; 2478 | if (this.onclose) { 2479 | this.onclose(e); 2480 | } 2481 | } 2482 | }; 2483 | return ServerSentEventsTransport; 2484 | }()); 2485 | exports.ServerSentEventsTransport = ServerSentEventsTransport; 2486 | 2487 | }); 2488 | 2489 | unwrapExports(ServerSentEventsTransport_1); 2490 | var ServerSentEventsTransport_2 = ServerSentEventsTransport_1.ServerSentEventsTransport; 2491 | 2492 | var WebSocketTransport_1 = createCommonjsModule(function(module, exports) { 2493 | Object.defineProperty(exports, "__esModule", { 2494 | value: true 2495 | }); 2496 | 2497 | 2498 | 2499 | 2500 | var WebSocketTransport = /** @class */ (function() { 2501 | function WebSocketTransport(accessTokenFactory, logger, logMessageContent) { 2502 | this.logger = logger; 2503 | this.accessTokenFactory = accessTokenFactory || (function() { 2504 | return null; 2505 | }); 2506 | this.logMessageContent = logMessageContent; 2507 | } 2508 | WebSocketTransport.prototype.connect = function(url, transferFormat) { 2509 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2510 | var _this = this; 2511 | var token; 2512 | return tslib_1.__generator(this, function(_a) { 2513 | switch (_a.label) { 2514 | case 0: 2515 | Utils.Arg.isRequired(url, "url"); 2516 | Utils.Arg.isRequired(transferFormat, "transferFormat"); 2517 | Utils.Arg.isIn(transferFormat, ITransport.TransferFormat, "transferFormat"); 2518 | // if (typeof(WebSocket) === "undefined") { 2519 | // throw new Error("'WebSocket' is not supported in your environment."); 2520 | // } 2521 | this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) Connecting"); 2522 | return [4 /*yield*/ , this.accessTokenFactory()]; 2523 | case 1: 2524 | token = _a.sent(); 2525 | if (token) { 2526 | url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token)); 2527 | } 2528 | return [2 /*return*/ , new Promise(function(resolve, reject) { 2529 | url = url.replace(/^http/, "ws"); 2530 | var webSocket=wx.connectSocket({ 2531 | url: url, 2532 | }) 2533 | 2534 | if (transferFormat === ITransport.TransferFormat.Binary) { 2535 | webSocket.binaryType = "arraybuffer"; 2536 | } 2537 | webSocket.onOpen(function(event) { 2538 | _this.logger.log(ILogger.LogLevel.Information, "WebSocket connected to " + url); 2539 | _this.webSocket = webSocket; 2540 | resolve(); 2541 | }); 2542 | webSocket.onError(function(event) { 2543 | reject(event.error); 2544 | }); 2545 | webSocket.onMessage ( function(message) { 2546 | _this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) data received. " + Utils.getDataDetail(message.data, _this.logMessageContent) + "."); 2547 | if (_this.onreceive) { 2548 | _this.onreceive(message.data); 2549 | } 2550 | }); 2551 | webSocket.onClose ( function(event) { 2552 | // webSocket will be null if the transport did not start successfully 2553 | _this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) socket closed."); 2554 | if (_this.onclose) { 2555 | if (event.wasClean === false || event.code !== 1000) { 2556 | _this.onclose(new Error("Websocket closed with status code: " + event.code + " (" + event.reason + ")")); 2557 | } else { 2558 | _this.onclose(); 2559 | } 2560 | } 2561 | }); 2562 | })]; 2563 | } 2564 | }); 2565 | }); 2566 | }; 2567 | WebSocketTransport.prototype.send = function(data) { 2568 | 2569 | if (this.webSocket && this.webSocket.readyState === 1) { 2570 | this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) sending data. " + Utils.getDataDetail(data, this.logMessageContent) + "."); 2571 | this.webSocket.send({ 2572 | data:data, 2573 | }); 2574 | return Promise.resolve(); 2575 | } 2576 | return Promise.reject("WebSocket is not in the OPEN state"); 2577 | }; 2578 | WebSocketTransport.prototype.stop = function() { 2579 | if (this.webSocket) { 2580 | this.webSocket.close(); 2581 | this.webSocket = null; 2582 | } 2583 | return Promise.resolve(); 2584 | }; 2585 | return WebSocketTransport; 2586 | }()); 2587 | exports.WebSocketTransport = WebSocketTransport; 2588 | 2589 | }); 2590 | 2591 | unwrapExports(WebSocketTransport_1); 2592 | var WebSocketTransport_2 = WebSocketTransport_1.WebSocketTransport; 2593 | 2594 | var HttpConnection_1 = createCommonjsModule(function(module, exports) { 2595 | Object.defineProperty(exports, "__esModule", { 2596 | value: true 2597 | }); 2598 | 2599 | 2600 | 2601 | 2602 | 2603 | 2604 | 2605 | 2606 | var MAX_REDIRECTS = 100; 2607 | var HttpConnection = /** @class */ (function() { 2608 | function HttpConnection(url, options) { 2609 | if (options === void 0) { 2610 | options = {}; 2611 | } 2612 | this.features = {}; 2613 | Utils.Arg.isRequired(url, "url"); 2614 | this.logger = Utils.createLogger(options.logger); 2615 | this.baseUrl = this.resolveUrl(url); 2616 | options = options || {}; 2617 | options.accessTokenFactory = options.accessTokenFactory || (function() { 2618 | return null; 2619 | }); 2620 | options.logMessageContent = options.logMessageContent || false; 2621 | this.httpClient = options.httpClient || new HttpClient_1.DefaultHttpClient(this.logger); 2622 | this.connectionState = 2 /* Disconnected */ ; 2623 | this.options = options; 2624 | } 2625 | HttpConnection.prototype.start = function(transferFormat) { 2626 | transferFormat = transferFormat || ITransport.TransferFormat.Binary; 2627 | Utils.Arg.isIn(transferFormat, ITransport.TransferFormat, "transferFormat"); 2628 | this.logger.log(ILogger.LogLevel.Debug, "Starting connection with transfer format '" + ITransport.TransferFormat[transferFormat] + "'."); 2629 | if (this.connectionState !== 2 /* Disconnected */ ) { 2630 | return Promise.reject(new Error("Cannot start a connection that is not in the 'Disconnected' state.")); 2631 | } 2632 | this.connectionState = 0 /* Connecting */ ; 2633 | this.startPromise = this.startInternal(transferFormat); 2634 | return this.startPromise; 2635 | }; 2636 | HttpConnection.prototype.send = function(data) { 2637 | if (this.connectionState !== 1 /* Connected */ ) { 2638 | throw new Error("Cannot send data if the connection is not in the 'Connected' State."); 2639 | } 2640 | return this.transport.send(data); 2641 | }; 2642 | HttpConnection.prototype.stop = function(error) { 2643 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2644 | var e_1; 2645 | return tslib_1.__generator(this, function(_a) { 2646 | switch (_a.label) { 2647 | case 0: 2648 | this.connectionState = 2 /* Disconnected */ ; 2649 | _a.label = 1; 2650 | case 1: 2651 | _a.trys.push([1, 3, , 4]); 2652 | return [4 /*yield*/ , this.startPromise]; 2653 | case 2: 2654 | _a.sent(); 2655 | return [3 /*break*/ , 4]; 2656 | case 3: 2657 | e_1 = _a.sent(); 2658 | return [3 /*break*/ , 4]; 2659 | case 4: 2660 | if (!this.transport) return [3 /*break*/ , 6]; 2661 | this.stopError = error; 2662 | return [4 /*yield*/ , this.transport.stop()]; 2663 | case 5: 2664 | _a.sent(); 2665 | this.transport = null; 2666 | _a.label = 6; 2667 | case 6: 2668 | return [2 /*return*/ ]; 2669 | } 2670 | }); 2671 | }); 2672 | }; 2673 | HttpConnection.prototype.startInternal = function(transferFormat) { 2674 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2675 | var _this = this; 2676 | var url, negotiateResponse, redirects, _loop_1, this_1, state_1, e_2; 2677 | return tslib_1.__generator(this, function(_a) { 2678 | switch (_a.label) { 2679 | case 0: 2680 | url = this.baseUrl; 2681 | this.accessTokenFactory = this.options.accessTokenFactory; 2682 | _a.label = 1; 2683 | case 1: 2684 | _a.trys.push([1, 12, , 13]); 2685 | if (!this.options.skipNegotiation) return [3 /*break*/ , 5]; 2686 | if (!(this.options.transport === ITransport.HttpTransportType.WebSockets)) return [3 /*break*/ , 3]; 2687 | // No need to add a connection ID in this case 2688 | this.transport = this.constructTransport(ITransport.HttpTransportType.WebSockets); 2689 | // We should just call connect directly in this case. 2690 | // No fallback or negotiate in this case. 2691 | return [4 /*yield*/ , this.transport.connect(url, transferFormat)]; 2692 | case 2: 2693 | // We should just call connect directly in this case. 2694 | // No fallback or negotiate in this case. 2695 | _a.sent(); 2696 | return [3 /*break*/ , 4]; 2697 | case 3: 2698 | throw Error("Negotiation can only be skipped when using the WebSocket transport directly."); 2699 | case 4: 2700 | return [3 /*break*/ , 11]; 2701 | case 5: 2702 | negotiateResponse = null; 2703 | redirects = 0; 2704 | _loop_1 = function() { 2705 | var accessToken_1; 2706 | return tslib_1.__generator(this, function(_a) { 2707 | switch (_a.label) { 2708 | case 0: 2709 | return [4 /*yield*/ , this_1.getNegotiationResponse(url)]; 2710 | case 1: 2711 | negotiateResponse = _a.sent(); 2712 | // the user tries to stop the connection when it is being started 2713 | if (this_1.connectionState === 2 /* Disconnected */ ) { 2714 | return [2 /*return*/ , { 2715 | value: void 0 2716 | }]; 2717 | } 2718 | if (negotiateResponse.url) { 2719 | url = negotiateResponse.url; 2720 | } 2721 | if (negotiateResponse.accessToken) { 2722 | accessToken_1 = negotiateResponse.accessToken; 2723 | this_1.accessTokenFactory = function() { 2724 | return accessToken_1; 2725 | }; 2726 | } 2727 | redirects++; 2728 | return [2 /*return*/ ]; 2729 | } 2730 | }); 2731 | }; 2732 | this_1 = this; 2733 | _a.label = 6; 2734 | case 6: 2735 | return [5 /*yield**/ , _loop_1()]; 2736 | case 7: 2737 | state_1 = _a.sent(); 2738 | if (typeof state_1 === "object") 2739 | return [2 /*return*/ , state_1.value]; 2740 | _a.label = 8; 2741 | case 8: 2742 | if (negotiateResponse.url && redirects < MAX_REDIRECTS) return [3 /*break*/ , 6]; 2743 | _a.label = 9; 2744 | case 9: 2745 | if (redirects === MAX_REDIRECTS && negotiateResponse.url) { 2746 | throw Error("Negotiate redirection limit exceeded."); 2747 | } 2748 | return [4 /*yield*/ , this.createTransport(url, this.options.r, negotiateResponse, transferFormat)]; 2749 | case 10: 2750 | _a.sent(); 2751 | _a.label = 11; 2752 | case 11: 2753 | if (this.transport instanceof LongPollingTransport_1.LongPollingTransport) { 2754 | this.features.inherentKeepAlive = true; 2755 | } 2756 | this.transport.onreceive = this.onreceive; 2757 | this.transport.onclose = function(e) { 2758 | return _this.stopConnection(e); 2759 | }; 2760 | // only change the state if we were connecting to not overwrite 2761 | // the state if the connection is already marked as Disconnected 2762 | this.changeState(0 /* Connecting */ , 1 /* Connected */ ); 2763 | return [3 /*break*/ , 13]; 2764 | case 12: 2765 | e_2 = _a.sent(); 2766 | this.logger.log(ILogger.LogLevel.Error, "Failed to start the connection: " + e_2); 2767 | this.connectionState = 2 /* Disconnected */ ; 2768 | this.transport = null; 2769 | throw e_2; 2770 | case 13: 2771 | return [2 /*return*/ ]; 2772 | } 2773 | }); 2774 | }); 2775 | }; 2776 | HttpConnection.prototype.getNegotiationResponse = function(url) { 2777 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2778 | var token, headers, negotiateUrl, response, e_3, _a; 2779 | return tslib_1.__generator(this, function(_b) { 2780 | switch (_b.label) { 2781 | case 0: 2782 | return [4 /*yield*/ , this.accessTokenFactory()]; 2783 | case 1: 2784 | token = _b.sent(); 2785 | if (token) { 2786 | headers = (_a = {}, _a["Authorization"] = "Bearer " + token, _a); 2787 | } 2788 | negotiateUrl = this.resolveNegotiateUrl(url); 2789 | this.logger.log(ILogger.LogLevel.Debug, "Sending negotiation request: " + negotiateUrl); 2790 | _b.label = 2; 2791 | case 2: 2792 | _b.trys.push([2, 4, , 5]); 2793 | return [4 /*yield*/ , this.httpClient.post(negotiateUrl, { 2794 | content: "", 2795 | headers: headers, 2796 | })]; 2797 | case 3: 2798 | response = _b.sent(); 2799 | if (response.statusCode !== 200) { 2800 | throw Error("Unexpected status code returned from negotiate " + response.statusCode); 2801 | } 2802 | return [2 /*return*/ , JSON.parse(response.content)]; 2803 | case 4: 2804 | e_3 = _b.sent(); 2805 | this.logger.log(ILogger.LogLevel.Error, "Failed to complete negotiation with the server: " + e_3); 2806 | throw e_3; 2807 | case 5: 2808 | return [2 /*return*/ ]; 2809 | } 2810 | }); 2811 | }); 2812 | }; 2813 | HttpConnection.prototype.createConnectUrl = function(url, connectionId) { 2814 | return url + (url.indexOf("?") === -1 ? "?" : "&") + ("id=" + connectionId); 2815 | }; 2816 | HttpConnection.prototype.createTransport = function(url, requestedTransport, negotiateResponse, requestedTransferFormat) { 2817 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2818 | var connectUrl, transports, _i, transports_1, endpoint, transport, ex_1; 2819 | return tslib_1.__generator(this, function(_a) { 2820 | switch (_a.label) { 2821 | case 0: 2822 | connectUrl = this.createConnectUrl(url, negotiateResponse.connectionId); 2823 | if (!this.isITransport(requestedTransport)) return [3 /*break*/ , 2]; 2824 | this.logger.log(ILogger.LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly."); 2825 | this.transport = requestedTransport; 2826 | return [4 /*yield*/ , this.transport.connect(connectUrl, requestedTransferFormat)]; 2827 | case 1: 2828 | _a.sent(); 2829 | // only change the state if we were connecting to not overwrite 2830 | // the state if the connection is already marked as Disconnected 2831 | this.changeState(0 /* Connecting */ , 1 /* Connected */ ); 2832 | return [2 /*return*/ ]; 2833 | case 2: 2834 | transports = negotiateResponse.availableTransports; 2835 | _i = 0, transports_1 = transports; 2836 | _a.label = 3; 2837 | case 3: 2838 | if (!(_i < transports_1.length)) return [3 /*break*/ , 9]; 2839 | endpoint = transports_1[_i]; 2840 | this.connectionState = 0 /* Connecting */ ; 2841 | // transport = this.resolveTransport(endpoint, requestedTransport, requestedTransferFormat); 2842 | transport=1; 2843 | if (!(typeof transport === "number")) return [3 /*break*/ , 8]; 2844 | this.transport = this.constructTransport(transport);//////////////////////////////// 2845 | if (!(negotiateResponse.connectionId === null)) return [3 /*break*/ , 5]; 2846 | return [4 /*yield*/ , this.getNegotiationResponse(url)]; 2847 | case 4: 2848 | negotiateResponse = _a.sent(); 2849 | connectUrl = this.createConnectUrl(url, negotiateResponse.connectionId); 2850 | _a.label = 5; 2851 | case 5: 2852 | _a.trys.push([5, 7, , 8]); 2853 | return [4 /*yield*/ , this.transport.connect(connectUrl, requestedTransferFormat)]; 2854 | case 6: 2855 | _a.sent(); 2856 | this.changeState(0 /* Connecting */ , 1 /* Connected */ ); 2857 | return [2 /*return*/ ]; 2858 | case 7: 2859 | ex_1 = _a.sent(); 2860 | this.logger.log(ILogger.LogLevel.Error, "Failed to start the transport '" + ITransport.HttpTransportType[transport] + "': " + ex_1); 2861 | this.connectionState = 2 /* Disconnected */ ; 2862 | negotiateResponse.connectionId = null; 2863 | return [3 /*break*/ , 8]; 2864 | case 8: 2865 | _i++; 2866 | return [3 /*break*/ , 3]; 2867 | case 9: 2868 | throw new Error("Unable to initialize any of the available transports."); 2869 | } 2870 | }); 2871 | }); 2872 | }; 2873 | HttpConnection.prototype.constructTransport = function(transport) { 2874 | switch (transport) { 2875 | case ITransport.HttpTransportType.WebSockets: 2876 | return new WebSocketTransport_1.WebSocketTransport(this.accessTokenFactory, this.logger, this.options.logMessageContent); 2877 | case ITransport.HttpTransportType.ServerSentEvents: 2878 | return new ServerSentEventsTransport_1.ServerSentEventsTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent); 2879 | case ITransport.HttpTransportType.LongPolling: 2880 | return new LongPollingTransport_1.LongPollingTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent); 2881 | default: 2882 | throw new Error("Unknown transport: " + transport + "."); 2883 | } 2884 | }; 2885 | HttpConnection.prototype.resolveTransport = function(endpoint, requestedTransport, requestedTransferFormat) { 2886 | var transport = ITransport.HttpTransportType[endpoint.transport]; 2887 | if (transport === null || transport === undefined) { 2888 | this.logger.log(ILogger.LogLevel.Debug, "Skipping transport '" + endpoint.transport + "' because it is not supported by this client."); 2889 | } else { 2890 | var transferFormats = endpoint.transferFormats.map(function(s) { 2891 | return ITransport.TransferFormat[s]; 2892 | }); 2893 | if (transportMatches(requestedTransport, transport)) { 2894 | if (transferFormats.indexOf(requestedTransferFormat) >= 0) { 2895 | if ((transport === ITransport.HttpTransportType.WebSockets && typeof WebSocket === "undefined") || 2896 | (transport === ITransport.HttpTransportType.ServerSentEvents && typeof EventSource === "undefined")) { 2897 | this.logger.log(ILogger.LogLevel.Debug, "Skipping transport '" + ITransport.HttpTransportType[transport] + "' because it is not supported in your environment.'"); 2898 | } else { 2899 | this.logger.log(ILogger.LogLevel.Debug, "Selecting transport '" + ITransport.HttpTransportType[transport] + "'"); 2900 | return transport; 2901 | } 2902 | } else { 2903 | this.logger.log(ILogger.LogLevel.Debug, "Skipping transport '" + ITransport.HttpTransportType[transport] + "' because it does not support the requested transfer format '" + ITransport.TransferFormat[requestedTransferFormat] + "'."); 2904 | } 2905 | } else { 2906 | this.logger.log(ILogger.LogLevel.Debug, "Skipping transport '" + ITransport.HttpTransportType[transport] + "' because it was disabled by the client."); 2907 | } 2908 | } 2909 | return null; 2910 | }; 2911 | HttpConnection.prototype.isITransport = function(transport) { 2912 | return transport && typeof(transport) === "object" && "connect" in transport; 2913 | }; 2914 | HttpConnection.prototype.changeState = function(from, to) { 2915 | if (this.connectionState === from) { 2916 | this.connectionState = to; 2917 | return true; 2918 | } 2919 | return false; 2920 | }; 2921 | HttpConnection.prototype.stopConnection = function(error) { 2922 | return tslib_1.__awaiter(this, void 0, void 0, function() { 2923 | return tslib_1.__generator(this, function(_a) { 2924 | this.transport = null; 2925 | // If we have a stopError, it takes precedence over the error from the transport 2926 | error = this.stopError || error; 2927 | if (error) { 2928 | this.logger.log(ILogger.LogLevel.Error, "Connection disconnected with error '" + error + "'."); 2929 | } else { 2930 | this.logger.log(ILogger.LogLevel.Information, "Connection disconnected."); 2931 | } 2932 | this.connectionState = 2 /* Disconnected */ ; 2933 | if (this.onclose) { 2934 | this.onclose(error); 2935 | } 2936 | return [2 /*return*/ ]; 2937 | }); 2938 | }); 2939 | }; 2940 | HttpConnection.prototype.resolveUrl = function(url) { 2941 | // startsWith is not supported in IE 2942 | if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) { 2943 | return url; 2944 | } 2945 | if (typeof window === "undefined" || !window || !window.document) { 2946 | throw new Error("Cannot resolve '" + url + "'."); 2947 | } 2948 | // Setting the url to the href propery of an anchor tag handles normalization 2949 | // for us. There are 3 main cases. 2950 | // 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b" 2951 | // 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b" 2952 | // 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b" 2953 | var aTag = window.document.createElement("a"); 2954 | aTag.href = url; 2955 | this.logger.log(ILogger.LogLevel.Information, "Normalizing '" + url + "' to '" + aTag.href + "'."); 2956 | return aTag.href; 2957 | }; 2958 | HttpConnection.prototype.resolveNegotiateUrl = function(url) { 2959 | var index = url.indexOf("?"); 2960 | var negotiateUrl = url.substring(0, index === -1 ? url.length : index); 2961 | if (negotiateUrl[negotiateUrl.length - 1] !== "/") { 2962 | negotiateUrl += "/"; 2963 | } 2964 | negotiateUrl += "negotiate"; 2965 | negotiateUrl += index === -1 ? "" : url.substring(index); 2966 | return negotiateUrl; 2967 | }; 2968 | return HttpConnection; 2969 | }()); 2970 | exports.HttpConnection = HttpConnection; 2971 | 2972 | function transportMatches(requestedTransport, actualTransport) { 2973 | return !requestedTransport || ((actualTransport & requestedTransport) !== 0); 2974 | } 2975 | 2976 | }); 2977 | 2978 | unwrapExports(HttpConnection_1); 2979 | var HttpConnection_2 = HttpConnection_1.HttpConnection; 2980 | 2981 | var JsonHubProtocol_1 = createCommonjsModule(function(module, exports) { 2982 | Object.defineProperty(exports, "__esModule", { 2983 | value: true 2984 | }); 2985 | 2986 | 2987 | 2988 | 2989 | 2990 | var JSON_HUB_PROTOCOL_NAME = "json"; 2991 | /** Implements the JSON Hub Protocol. */ 2992 | var JsonHubProtocol = /** @class */ (function() { 2993 | function JsonHubProtocol() { 2994 | /** @inheritDoc */ 2995 | this.name = JSON_HUB_PROTOCOL_NAME; 2996 | /** @inheritDoc */ 2997 | this.version = 1; 2998 | /** @inheritDoc */ 2999 | this.transferFormat = ITransport.TransferFormat.Text; 3000 | } 3001 | /** Creates an array of {@link HubMessage} objects from the specified serialized representation. 3002 | * 3003 | * @param {string} input A string containing the serialized representation. 3004 | * @param {ILogger} logger A logger that will be used to log messages that occur during parsing. 3005 | */ 3006 | JsonHubProtocol.prototype.parseMessages = function(input, logger) { 3007 | // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error. 3008 | if (typeof input !== "string") { 3009 | throw new Error("Invalid input for JSON hub protocol. Expected a string."); 3010 | } 3011 | if (!input) { 3012 | return []; 3013 | } 3014 | if (logger === null) { 3015 | logger = Loggers.NullLogger.instance; 3016 | } 3017 | // Parse the messages 3018 | var messages = TextMessageFormat_1.TextMessageFormat.parse(input); 3019 | var hubMessages = []; 3020 | for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) { 3021 | var message = messages_1[_i]; 3022 | var parsedMessage = JSON.parse(message); 3023 | if (typeof parsedMessage.type !== "number") { 3024 | throw new Error("Invalid payload."); 3025 | } 3026 | switch (parsedMessage.type) { 3027 | case IHubProtocol.MessageType.Invocation: 3028 | this.isInvocationMessage(parsedMessage); 3029 | break; 3030 | case IHubProtocol.MessageType.StreamItem: 3031 | this.isStreamItemMessage(parsedMessage); 3032 | break; 3033 | case IHubProtocol.MessageType.Completion: 3034 | this.isCompletionMessage(parsedMessage); 3035 | break; 3036 | case IHubProtocol.MessageType.Ping: 3037 | // Single value, no need to validate 3038 | break; 3039 | case IHubProtocol.MessageType.Close: 3040 | // All optional values, no need to validate 3041 | break; 3042 | default: 3043 | // Future protocol changes can add message types, old clients can ignore them 3044 | logger.log(ILogger.LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored."); 3045 | continue; 3046 | } 3047 | hubMessages.push(parsedMessage); 3048 | } 3049 | return hubMessages; 3050 | }; 3051 | /** Writes the specified {@link HubMessage} to a string and returns it. 3052 | * 3053 | * @param {HubMessage} message The message to write. 3054 | * @returns {string} A string containing the serialized representation of the message. 3055 | */ 3056 | JsonHubProtocol.prototype.writeMessage = function(message) { 3057 | return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(message)); 3058 | }; 3059 | JsonHubProtocol.prototype.isInvocationMessage = function(message) { 3060 | this.assertNotEmptyString(message.target, "Invalid payload for Invocation message."); 3061 | if (message.invocationId !== undefined) { 3062 | this.assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message."); 3063 | } 3064 | }; 3065 | JsonHubProtocol.prototype.isStreamItemMessage = function(message) { 3066 | this.assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message."); 3067 | if (message.item === undefined) { 3068 | throw new Error("Invalid payload for StreamItem message."); 3069 | } 3070 | }; 3071 | JsonHubProtocol.prototype.isCompletionMessage = function(message) { 3072 | if (message.result && message.error) { 3073 | throw new Error("Invalid payload for Completion message."); 3074 | } 3075 | if (!message.result && message.error) { 3076 | this.assertNotEmptyString(message.error, "Invalid payload for Completion message."); 3077 | } 3078 | this.assertNotEmptyString(message.invocationId, "Invalid payload for Completion message."); 3079 | }; 3080 | JsonHubProtocol.prototype.assertNotEmptyString = function(value, errorMessage) { 3081 | if (typeof value !== "string" || value === "") { 3082 | throw new Error(errorMessage); 3083 | } 3084 | }; 3085 | return JsonHubProtocol; 3086 | }()); 3087 | exports.JsonHubProtocol = JsonHubProtocol; 3088 | 3089 | }); 3090 | 3091 | unwrapExports(JsonHubProtocol_1); 3092 | var JsonHubProtocol_2 = JsonHubProtocol_1.JsonHubProtocol; 3093 | 3094 | var HubConnectionBuilder_1 = createCommonjsModule(function(module, exports) { 3095 | Object.defineProperty(exports, "__esModule", { 3096 | value: true 3097 | }); 3098 | 3099 | 3100 | 3101 | 3102 | 3103 | /** A builder for configuring {@link HubConnection} instances. */ 3104 | var HubConnectionBuilder = /** @class */ (function() { 3105 | function HubConnectionBuilder() {} 3106 | HubConnectionBuilder.prototype.configureLogging = function(logging) { 3107 | Utils.Arg.isRequired(logging, "logging"); 3108 | if (isLogger(logging)) { 3109 | this.logger = logging; 3110 | } else { 3111 | this.logger = new Utils.ConsoleLogger(logging); 3112 | } 3113 | return this; 3114 | }; 3115 | HubConnectionBuilder.prototype.withUrl = function(url, transportTypeOrOptions) { 3116 | Utils.Arg.isRequired(url, "url"); 3117 | this.url = url; 3118 | // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed 3119 | // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called. 3120 | if (typeof transportTypeOrOptions === "object") { 3121 | this.httpConnectionOptions = transportTypeOrOptions; 3122 | } else { 3123 | this.httpConnectionOptions = { 3124 | transport: transportTypeOrOptions, 3125 | }; 3126 | } 3127 | return this; 3128 | }; 3129 | /** Configures the {@link HubConnection} to use the specified Hub Protocol. 3130 | * 3131 | * @param {IHubProtocol} protocol The {@link IHubProtocol} implementation to use. 3132 | */ 3133 | HubConnectionBuilder.prototype.withHubProtocol = function(protocol) { 3134 | Utils.Arg.isRequired(protocol, "protocol"); 3135 | this.protocol = protocol; 3136 | return this; 3137 | }; 3138 | /** Creates a {@link HubConnection} from the configuration options specified in this builder. 3139 | * 3140 | * @returns {HubConnection} The configured {@link HubConnection}. 3141 | */ 3142 | HubConnectionBuilder.prototype.build = function() { 3143 | // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one 3144 | // provided to configureLogger 3145 | var httpConnectionOptions = this.httpConnectionOptions || {}; 3146 | // If it's 'null', the user **explicitly** asked for null, don't mess with it. 3147 | if (httpConnectionOptions.logger === undefined) { 3148 | // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it. 3149 | httpConnectionOptions.logger = this.logger; 3150 | } 3151 | // Now create the connection 3152 | if (!this.url) { 3153 | throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection."); 3154 | } 3155 | var connection = new HttpConnection_1.HttpConnection(this.url, httpConnectionOptions); 3156 | return HubConnection_1.HubConnection.create(connection, this.logger || Loggers.NullLogger.instance, this.protocol || new JsonHubProtocol_1.JsonHubProtocol()); 3157 | }; 3158 | return HubConnectionBuilder; 3159 | }()); 3160 | exports.HubConnectionBuilder = HubConnectionBuilder; 3161 | 3162 | function isLogger(logger) { 3163 | return logger.log !== undefined; 3164 | } 3165 | 3166 | }); 3167 | 3168 | unwrapExports(HubConnectionBuilder_1); 3169 | var HubConnectionBuilder_2 = HubConnectionBuilder_1.HubConnectionBuilder; 3170 | 3171 | var cjs = createCommonjsModule(function(module, exports) { 3172 | Object.defineProperty(exports, "__esModule", { 3173 | value: true 3174 | }); 3175 | // Version token that will be replaced by the prepack command 3176 | /** The version of the SignalR client. */ 3177 | exports.VERSION = "0.0.0-DEV_BUILD"; 3178 | 3179 | exports.HttpError = Errors.HttpError; 3180 | exports.TimeoutError = Errors.TimeoutError; 3181 | 3182 | exports.DefaultHttpClient = HttpClient_1.DefaultHttpClient; 3183 | exports.HttpClient = HttpClient_1.HttpClient; 3184 | exports.HttpResponse = HttpClient_1.HttpResponse; 3185 | 3186 | exports.HubConnection = HubConnection_1.HubConnection; 3187 | 3188 | exports.HubConnectionBuilder = HubConnectionBuilder_1.HubConnectionBuilder; 3189 | 3190 | exports.MessageType = IHubProtocol.MessageType; 3191 | 3192 | exports.LogLevel = ILogger.LogLevel; 3193 | 3194 | exports.HttpTransportType = ITransport.HttpTransportType; 3195 | exports.TransferFormat = ITransport.TransferFormat; 3196 | 3197 | exports.NullLogger = Loggers.NullLogger; 3198 | 3199 | exports.JsonHubProtocol = JsonHubProtocol_1.JsonHubProtocol; 3200 | 3201 | }); 3202 | 3203 | unwrapExports(cjs); 3204 | var cjs_1 = cjs.VERSION; 3205 | var cjs_2 = cjs.HttpError; 3206 | var cjs_3 = cjs.TimeoutError; 3207 | var cjs_4 = cjs.DefaultHttpClient; 3208 | var cjs_5 = cjs.HttpClient; 3209 | var cjs_6 = cjs.HttpResponse; 3210 | var cjs_7 = cjs.HubConnection; 3211 | var cjs_8 = cjs.HubConnectionBuilder; 3212 | var cjs_9 = cjs.MessageType; 3213 | var cjs_10 = cjs.LogLevel; 3214 | var cjs_11 = cjs.HttpTransportType; 3215 | var cjs_12 = cjs.TransferFormat; 3216 | var cjs_13 = cjs.NullLogger; 3217 | var cjs_14 = cjs.JsonHubProtocol; 3218 | 3219 | var browserIndex = createCommonjsModule(function(module, exports) { 3220 | Object.defineProperty(exports, "__esModule", { 3221 | value: true 3222 | }); 3223 | 3224 | // This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds. 3225 | 3226 | // Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties 3227 | // that exist on Uint8Array with the same name, and JavaScript is magic. 3228 | // We make them 'writable' because the Buffer polyfill messes with it as well. 3229 | if (!Uint8Array.prototype.indexOf) { 3230 | Object.defineProperty(Uint8Array.prototype, "indexOf", { 3231 | value: Array.prototype.indexOf, 3232 | writable: true, 3233 | }); 3234 | } 3235 | if (!Uint8Array.prototype.slice) { 3236 | Object.defineProperty(Uint8Array.prototype, "slice", { 3237 | value: Array.prototype.slice, 3238 | writable: true, 3239 | }); 3240 | } 3241 | if (!Uint8Array.prototype.forEach) { 3242 | Object.defineProperty(Uint8Array.prototype, "forEach", { 3243 | value: Array.prototype.forEach, 3244 | writable: true, 3245 | }); 3246 | } 3247 | tslib_1.__exportStar(cjs, exports); 3248 | 3249 | }); 3250 | 3251 | var browserIndex$1 = unwrapExports(browserIndex); 3252 | 3253 | return browserIndex$1; 3254 | 3255 | }))); 3256 | //# sourceMappingURL=signalr.js.map --------------------------------------------------------------------------------