Advertisement
Guest User

Zuop

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