人民医院前端

signalr.js 101KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790
  1. /* @license
  2. * Copyright (c) .NET Foundation. All rights reserved.
  3. * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  4. */
  5. (function (global, factory) {
  6. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  7. typeof define === 'function' && define.amd ? define(factory) :
  8. (global.signalR = factory());
  9. }(this, (function () { 'use strict';
  10. var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  11. function commonjsRequire () {
  12. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  13. }
  14. function unwrapExports (x) {
  15. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  16. }
  17. function createCommonjsModule(fn, module) {
  18. return module = { exports: {} }, fn(module, module.exports), module.exports;
  19. }
  20. var es6Promise_auto = createCommonjsModule(function (module, exports) {
  21. /*!
  22. * @overview es6-promise - a tiny implementation of Promises/A+.
  23. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  24. * @license Licensed under MIT license
  25. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  26. * @version v4.2.2+97478eb6
  27. */
  28. (function (global, factory) {
  29. module.exports = factory();
  30. }(commonjsGlobal, (function () { function objectOrFunction(x) {
  31. var type = typeof x;
  32. return x !== null && (type === 'object' || type === 'function');
  33. }
  34. function isFunction(x) {
  35. return typeof x === 'function';
  36. }
  37. var _isArray = void 0;
  38. if (Array.isArray) {
  39. _isArray = Array.isArray;
  40. } else {
  41. _isArray = function (x) {
  42. return Object.prototype.toString.call(x) === '[object Array]';
  43. };
  44. }
  45. var isArray = _isArray;
  46. var len = 0;
  47. var vertxNext = void 0;
  48. var customSchedulerFn = void 0;
  49. var asap = function asap(callback, arg) {
  50. queue[len] = callback;
  51. queue[len + 1] = arg;
  52. len += 2;
  53. if (len === 2) {
  54. // If len is 2, that means that we need to schedule an async flush.
  55. // If additional callbacks are queued before the queue is flushed, they
  56. // will be processed by this flush that we are scheduling.
  57. if (customSchedulerFn) {
  58. customSchedulerFn(flush);
  59. } else {
  60. scheduleFlush();
  61. }
  62. }
  63. };
  64. function setScheduler(scheduleFn) {
  65. customSchedulerFn = scheduleFn;
  66. }
  67. function setAsap(asapFn) {
  68. asap = asapFn;
  69. }
  70. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  71. var browserGlobal = browserWindow || {};
  72. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  73. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  74. // test for web worker but not in IE10
  75. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  76. // node
  77. function useNextTick() {
  78. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  79. // see https://github.com/cujojs/when/issues/410 for details
  80. return function () {
  81. return process.nextTick(flush);
  82. };
  83. }
  84. // vertx
  85. function useVertxTimer() {
  86. if (typeof vertxNext !== 'undefined') {
  87. return function () {
  88. vertxNext(flush);
  89. };
  90. }
  91. return useSetTimeout();
  92. }
  93. function useMutationObserver() {
  94. var iterations = 0;
  95. var observer = new BrowserMutationObserver(flush);
  96. var node = document.createTextNode('');
  97. observer.observe(node, { characterData: true });
  98. return function () {
  99. node.data = iterations = ++iterations % 2;
  100. };
  101. }
  102. // web worker
  103. function useMessageChannel() {
  104. var channel = new MessageChannel();
  105. channel.port1.onmessage = flush;
  106. return function () {
  107. return channel.port2.postMessage(0);
  108. };
  109. }
  110. function useSetTimeout() {
  111. // Store setTimeout reference so es6-promise will be unaffected by
  112. // other code modifying setTimeout (like sinon.useFakeTimers())
  113. var globalSetTimeout = setTimeout;
  114. return function () {
  115. return globalSetTimeout(flush, 1);
  116. };
  117. }
  118. var queue = new Array(1000);
  119. function flush() {
  120. for (var i = 0; i < len; i += 2) {
  121. var callback = queue[i];
  122. var arg = queue[i + 1];
  123. callback(arg);
  124. queue[i] = undefined;
  125. queue[i + 1] = undefined;
  126. }
  127. len = 0;
  128. }
  129. function attemptVertx() {
  130. try {
  131. var r = commonjsRequire;
  132. var vertx = r('vertx');
  133. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  134. return useVertxTimer();
  135. } catch (e) {
  136. return useSetTimeout();
  137. }
  138. }
  139. var scheduleFlush = void 0;
  140. // Decide what async method to use to triggering processing of queued callbacks:
  141. if (isNode) {
  142. scheduleFlush = useNextTick();
  143. } else if (BrowserMutationObserver) {
  144. scheduleFlush = useMutationObserver();
  145. } else if (isWorker) {
  146. scheduleFlush = useMessageChannel();
  147. } else if (browserWindow === undefined && typeof commonjsRequire === 'function') {
  148. scheduleFlush = attemptVertx();
  149. } else {
  150. scheduleFlush = useSetTimeout();
  151. }
  152. function then(onFulfillment, onRejection) {
  153. var parent = this;
  154. var child = new this.constructor(noop);
  155. if (child[PROMISE_ID] === undefined) {
  156. makePromise(child);
  157. }
  158. var _state = parent._state;
  159. if (_state) {
  160. var callback = arguments[_state - 1];
  161. asap(function () {
  162. return invokeCallback(_state, child, callback, parent._result);
  163. });
  164. } else {
  165. subscribe(parent, child, onFulfillment, onRejection);
  166. }
  167. return child;
  168. }
  169. /**
  170. `Promise.resolve` returns a promise that will become resolved with the
  171. passed `value`. It is shorthand for the following:
  172. ```javascript
  173. let promise = new Promise(function(resolve, reject){
  174. resolve(1);
  175. });
  176. promise.then(function(value){
  177. // value === 1
  178. });
  179. ```
  180. Instead of writing the above, your code now simply becomes the following:
  181. ```javascript
  182. let promise = Promise.resolve(1);
  183. promise.then(function(value){
  184. // value === 1
  185. });
  186. ```
  187. @method resolve
  188. @static
  189. @param {Any} value value that the returned promise will be resolved with
  190. Useful for tooling.
  191. @return {Promise} a promise that will become fulfilled with the given
  192. `value`
  193. */
  194. function resolve$1(object) {
  195. /*jshint validthis:true */
  196. var Constructor = this;
  197. if (object && typeof object === 'object' && object.constructor === Constructor) {
  198. return object;
  199. }
  200. var promise = new Constructor(noop);
  201. resolve(promise, object);
  202. return promise;
  203. }
  204. var PROMISE_ID = Math.random().toString(36).substring(16);
  205. function noop() {}
  206. var PENDING = void 0;
  207. var FULFILLED = 1;
  208. var REJECTED = 2;
  209. var GET_THEN_ERROR = new ErrorObject();
  210. function selfFulfillment() {
  211. return new TypeError("You cannot resolve a promise with itself");
  212. }
  213. function cannotReturnOwn() {
  214. return new TypeError('A promises callback cannot return that same promise.');
  215. }
  216. function getThen(promise) {
  217. try {
  218. return promise.then;
  219. } catch (error) {
  220. GET_THEN_ERROR.error = error;
  221. return GET_THEN_ERROR;
  222. }
  223. }
  224. function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
  225. try {
  226. then$$1.call(value, fulfillmentHandler, rejectionHandler);
  227. } catch (e) {
  228. return e;
  229. }
  230. }
  231. function handleForeignThenable(promise, thenable, then$$1) {
  232. asap(function (promise) {
  233. var sealed = false;
  234. var error = tryThen(then$$1, thenable, function (value) {
  235. if (sealed) {
  236. return;
  237. }
  238. sealed = true;
  239. if (thenable !== value) {
  240. resolve(promise, value);
  241. } else {
  242. fulfill(promise, value);
  243. }
  244. }, function (reason) {
  245. if (sealed) {
  246. return;
  247. }
  248. sealed = true;
  249. reject(promise, reason);
  250. }, 'Settle: ' + (promise._label || ' unknown promise'));
  251. if (!sealed && error) {
  252. sealed = true;
  253. reject(promise, error);
  254. }
  255. }, promise);
  256. }
  257. function handleOwnThenable(promise, thenable) {
  258. if (thenable._state === FULFILLED) {
  259. fulfill(promise, thenable._result);
  260. } else if (thenable._state === REJECTED) {
  261. reject(promise, thenable._result);
  262. } else {
  263. subscribe(thenable, undefined, function (value) {
  264. return resolve(promise, value);
  265. }, function (reason) {
  266. return reject(promise, reason);
  267. });
  268. }
  269. }
  270. function handleMaybeThenable(promise, maybeThenable, then$$1) {
  271. if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
  272. handleOwnThenable(promise, maybeThenable);
  273. } else {
  274. if (then$$1 === GET_THEN_ERROR) {
  275. reject(promise, GET_THEN_ERROR.error);
  276. GET_THEN_ERROR.error = null;
  277. } else if (then$$1 === undefined) {
  278. fulfill(promise, maybeThenable);
  279. } else if (isFunction(then$$1)) {
  280. handleForeignThenable(promise, maybeThenable, then$$1);
  281. } else {
  282. fulfill(promise, maybeThenable);
  283. }
  284. }
  285. }
  286. function resolve(promise, value) {
  287. if (promise === value) {
  288. reject(promise, selfFulfillment());
  289. } else if (objectOrFunction(value)) {
  290. handleMaybeThenable(promise, value, getThen(value));
  291. } else {
  292. fulfill(promise, value);
  293. }
  294. }
  295. function publishRejection(promise) {
  296. if (promise._onerror) {
  297. promise._onerror(promise._result);
  298. }
  299. publish(promise);
  300. }
  301. function fulfill(promise, value) {
  302. if (promise._state !== PENDING) {
  303. return;
  304. }
  305. promise._result = value;
  306. promise._state = FULFILLED;
  307. if (promise._subscribers.length !== 0) {
  308. asap(publish, promise);
  309. }
  310. }
  311. function reject(promise, reason) {
  312. if (promise._state !== PENDING) {
  313. return;
  314. }
  315. promise._state = REJECTED;
  316. promise._result = reason;
  317. asap(publishRejection, promise);
  318. }
  319. function subscribe(parent, child, onFulfillment, onRejection) {
  320. var _subscribers = parent._subscribers;
  321. var length = _subscribers.length;
  322. parent._onerror = null;
  323. _subscribers[length] = child;
  324. _subscribers[length + FULFILLED] = onFulfillment;
  325. _subscribers[length + REJECTED] = onRejection;
  326. if (length === 0 && parent._state) {
  327. asap(publish, parent);
  328. }
  329. }
  330. function publish(promise) {
  331. var subscribers = promise._subscribers;
  332. var settled = promise._state;
  333. if (subscribers.length === 0) {
  334. return;
  335. }
  336. var child = void 0,
  337. callback = void 0,
  338. detail = promise._result;
  339. for (var i = 0; i < subscribers.length; i += 3) {
  340. child = subscribers[i];
  341. callback = subscribers[i + settled];
  342. if (child) {
  343. invokeCallback(settled, child, callback, detail);
  344. } else {
  345. callback(detail);
  346. }
  347. }
  348. promise._subscribers.length = 0;
  349. }
  350. function ErrorObject() {
  351. this.error = null;
  352. }
  353. var TRY_CATCH_ERROR = new ErrorObject();
  354. function tryCatch(callback, detail) {
  355. try {
  356. return callback(detail);
  357. } catch (e) {
  358. TRY_CATCH_ERROR.error = e;
  359. return TRY_CATCH_ERROR;
  360. }
  361. }
  362. function invokeCallback(settled, promise, callback, detail) {
  363. var hasCallback = isFunction(callback),
  364. value = void 0,
  365. error = void 0,
  366. succeeded = void 0,
  367. failed = void 0;
  368. if (hasCallback) {
  369. value = tryCatch(callback, detail);
  370. if (value === TRY_CATCH_ERROR) {
  371. failed = true;
  372. error = value.error;
  373. value.error = null;
  374. } else {
  375. succeeded = true;
  376. }
  377. if (promise === value) {
  378. reject(promise, cannotReturnOwn());
  379. return;
  380. }
  381. } else {
  382. value = detail;
  383. succeeded = true;
  384. }
  385. if (promise._state !== PENDING) {
  386. // noop
  387. } else if (hasCallback && succeeded) {
  388. resolve(promise, value);
  389. } else if (failed) {
  390. reject(promise, error);
  391. } else if (settled === FULFILLED) {
  392. fulfill(promise, value);
  393. } else if (settled === REJECTED) {
  394. reject(promise, value);
  395. }
  396. }
  397. function initializePromise(promise, resolver) {
  398. try {
  399. resolver(function resolvePromise(value) {
  400. resolve(promise, value);
  401. }, function rejectPromise(reason) {
  402. reject(promise, reason);
  403. });
  404. } catch (e) {
  405. reject(promise, e);
  406. }
  407. }
  408. var id = 0;
  409. function nextId() {
  410. return id++;
  411. }
  412. function makePromise(promise) {
  413. promise[PROMISE_ID] = id++;
  414. promise._state = undefined;
  415. promise._result = undefined;
  416. promise._subscribers = [];
  417. }
  418. function validationError() {
  419. return new Error('Array Methods must be provided an Array');
  420. }
  421. function validationError() {
  422. return new Error('Array Methods must be provided an Array');
  423. }
  424. var Enumerator = function () {
  425. function Enumerator(Constructor, input) {
  426. this._instanceConstructor = Constructor;
  427. this.promise = new Constructor(noop);
  428. if (!this.promise[PROMISE_ID]) {
  429. makePromise(this.promise);
  430. }
  431. if (isArray(input)) {
  432. this.length = input.length;
  433. this._remaining = input.length;
  434. this._result = new Array(this.length);
  435. if (this.length === 0) {
  436. fulfill(this.promise, this._result);
  437. } else {
  438. this.length = this.length || 0;
  439. this._enumerate(input);
  440. if (this._remaining === 0) {
  441. fulfill(this.promise, this._result);
  442. }
  443. }
  444. } else {
  445. reject(this.promise, validationError());
  446. }
  447. }
  448. Enumerator.prototype._enumerate = function _enumerate(input) {
  449. for (var i = 0; this._state === PENDING && i < input.length; i++) {
  450. this._eachEntry(input[i], i);
  451. }
  452. };
  453. Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
  454. var c = this._instanceConstructor;
  455. var resolve$$1 = c.resolve;
  456. if (resolve$$1 === resolve$1) {
  457. var _then = getThen(entry);
  458. if (_then === then && entry._state !== PENDING) {
  459. this._settledAt(entry._state, i, entry._result);
  460. } else if (typeof _then !== 'function') {
  461. this._remaining--;
  462. this._result[i] = entry;
  463. } else if (c === Promise$2) {
  464. var promise = new c(noop);
  465. handleMaybeThenable(promise, entry, _then);
  466. this._willSettleAt(promise, i);
  467. } else {
  468. this._willSettleAt(new c(function (resolve$$1) {
  469. return resolve$$1(entry);
  470. }), i);
  471. }
  472. } else {
  473. this._willSettleAt(resolve$$1(entry), i);
  474. }
  475. };
  476. Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
  477. var promise = this.promise;
  478. if (promise._state === PENDING) {
  479. this._remaining--;
  480. if (state === REJECTED) {
  481. reject(promise, value);
  482. } else {
  483. this._result[i] = value;
  484. }
  485. }
  486. if (this._remaining === 0) {
  487. fulfill(promise, this._result);
  488. }
  489. };
  490. Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
  491. var enumerator = this;
  492. subscribe(promise, undefined, function (value) {
  493. return enumerator._settledAt(FULFILLED, i, value);
  494. }, function (reason) {
  495. return enumerator._settledAt(REJECTED, i, reason);
  496. });
  497. };
  498. return Enumerator;
  499. }();
  500. /**
  501. `Promise.all` accepts an array of promises, and returns a new promise which
  502. is fulfilled with an array of fulfillment values for the passed promises, or
  503. rejected with the reason of the first passed promise to be rejected. It casts all
  504. elements of the passed iterable to promises as it runs this algorithm.
  505. Example:
  506. ```javascript
  507. let promise1 = resolve(1);
  508. let promise2 = resolve(2);
  509. let promise3 = resolve(3);
  510. let promises = [ promise1, promise2, promise3 ];
  511. Promise.all(promises).then(function(array){
  512. // The array here would be [ 1, 2, 3 ];
  513. });
  514. ```
  515. If any of the `promises` given to `all` are rejected, the first promise
  516. that is rejected will be given as an argument to the returned promises's
  517. rejection handler. For example:
  518. Example:
  519. ```javascript
  520. let promise1 = resolve(1);
  521. let promise2 = reject(new Error("2"));
  522. let promise3 = reject(new Error("3"));
  523. let promises = [ promise1, promise2, promise3 ];
  524. Promise.all(promises).then(function(array){
  525. // Code here never runs because there are rejected promises!
  526. }, function(error) {
  527. // error.message === "2"
  528. });
  529. ```
  530. @method all
  531. @static
  532. @param {Array} entries array of promises
  533. @param {String} label optional string for labeling the promise.
  534. Useful for tooling.
  535. @return {Promise} promise that is fulfilled when all `promises` have been
  536. fulfilled, or rejected if any of them become rejected.
  537. @static
  538. */
  539. function all(entries) {
  540. return new Enumerator(this, entries).promise;
  541. }
  542. /**
  543. `Promise.race` returns a new promise which is settled in the same way as the
  544. first passed promise to settle.
  545. Example:
  546. ```javascript
  547. let promise1 = new Promise(function(resolve, reject){
  548. setTimeout(function(){
  549. resolve('promise 1');
  550. }, 200);
  551. });
  552. let promise2 = new Promise(function(resolve, reject){
  553. setTimeout(function(){
  554. resolve('promise 2');
  555. }, 100);
  556. });
  557. Promise.race([promise1, promise2]).then(function(result){
  558. // result === 'promise 2' because it was resolved before promise1
  559. // was resolved.
  560. });
  561. ```
  562. `Promise.race` is deterministic in that only the state of the first
  563. settled promise matters. For example, even if other promises given to the
  564. `promises` array argument are resolved, but the first settled promise has
  565. become rejected before the other promises became fulfilled, the returned
  566. promise will become rejected:
  567. ```javascript
  568. let promise1 = new Promise(function(resolve, reject){
  569. setTimeout(function(){
  570. resolve('promise 1');
  571. }, 200);
  572. });
  573. let promise2 = new Promise(function(resolve, reject){
  574. setTimeout(function(){
  575. reject(new Error('promise 2'));
  576. }, 100);
  577. });
  578. Promise.race([promise1, promise2]).then(function(result){
  579. // Code here never runs
  580. }, function(reason){
  581. // reason.message === 'promise 2' because promise 2 became rejected before
  582. // promise 1 became fulfilled
  583. });
  584. ```
  585. An example real-world use case is implementing timeouts:
  586. ```javascript
  587. Promise.race([ajax('foo.json'), timeout(5000)])
  588. ```
  589. @method race
  590. @static
  591. @param {Array} promises array of promises to observe
  592. Useful for tooling.
  593. @return {Promise} a promise which settles in the same way as the first passed
  594. promise to settle.
  595. */
  596. function race(entries) {
  597. /*jshint validthis:true */
  598. var Constructor = this;
  599. if (!isArray(entries)) {
  600. return new Constructor(function (_, reject) {
  601. return reject(new TypeError('You must pass an array to race.'));
  602. });
  603. } else {
  604. return new Constructor(function (resolve, reject) {
  605. var length = entries.length;
  606. for (var i = 0; i < length; i++) {
  607. Constructor.resolve(entries[i]).then(resolve, reject);
  608. }
  609. });
  610. }
  611. }
  612. /**
  613. `Promise.reject` returns a promise rejected with the passed `reason`.
  614. It is shorthand for the following:
  615. ```javascript
  616. let promise = new Promise(function(resolve, reject){
  617. reject(new Error('WHOOPS'));
  618. });
  619. promise.then(function(value){
  620. // Code here doesn't run because the promise is rejected!
  621. }, function(reason){
  622. // reason.message === 'WHOOPS'
  623. });
  624. ```
  625. Instead of writing the above, your code now simply becomes the following:
  626. ```javascript
  627. let promise = Promise.reject(new Error('WHOOPS'));
  628. promise.then(function(value){
  629. // Code here doesn't run because the promise is rejected!
  630. }, function(reason){
  631. // reason.message === 'WHOOPS'
  632. });
  633. ```
  634. @method reject
  635. @static
  636. @param {Any} reason value that the returned promise will be rejected with.
  637. Useful for tooling.
  638. @return {Promise} a promise rejected with the given `reason`.
  639. */
  640. function reject$1(reason) {
  641. /*jshint validthis:true */
  642. var Constructor = this;
  643. var promise = new Constructor(noop);
  644. reject(promise, reason);
  645. return promise;
  646. }
  647. function needsResolver() {
  648. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  649. }
  650. function needsNew() {
  651. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  652. }
  653. /**
  654. Promise objects represent the eventual result of an asynchronous operation. The
  655. primary way of interacting with a promise is through its `then` method, which
  656. registers callbacks to receive either a promise's eventual value or the reason
  657. why the promise cannot be fulfilled.
  658. Terminology
  659. -----------
  660. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  661. - `thenable` is an object or function that defines a `then` method.
  662. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  663. - `exception` is a value that is thrown using the throw statement.
  664. - `reason` is a value that indicates why a promise was rejected.
  665. - `settled` the final resting state of a promise, fulfilled or rejected.
  666. A promise can be in one of three states: pending, fulfilled, or rejected.
  667. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  668. state. Promises that are rejected have a rejection reason and are in the
  669. rejected state. A fulfillment value is never a thenable.
  670. Promises can also be said to *resolve* a value. If this value is also a
  671. promise, then the original promise's settled state will match the value's
  672. settled state. So a promise that *resolves* a promise that rejects will
  673. itself reject, and a promise that *resolves* a promise that fulfills will
  674. itself fulfill.
  675. Basic Usage:
  676. ------------
  677. ```js
  678. let promise = new Promise(function(resolve, reject) {
  679. // on success
  680. resolve(value);
  681. // on failure
  682. reject(reason);
  683. });
  684. promise.then(function(value) {
  685. // on fulfillment
  686. }, function(reason) {
  687. // on rejection
  688. });
  689. ```
  690. Advanced Usage:
  691. ---------------
  692. Promises shine when abstracting away asynchronous interactions such as
  693. `XMLHttpRequest`s.
  694. ```js
  695. function getJSON(url) {
  696. return new Promise(function(resolve, reject){
  697. let xhr = new XMLHttpRequest();
  698. xhr.open('GET', url);
  699. xhr.onreadystatechange = handler;
  700. xhr.responseType = 'json';
  701. xhr.setRequestHeader('Accept', 'application/json');
  702. xhr.send();
  703. function handler() {
  704. if (this.readyState === this.DONE) {
  705. if (this.status === 200) {
  706. resolve(this.response);
  707. } else {
  708. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  709. }
  710. }
  711. };
  712. });
  713. }
  714. getJSON('/posts.json').then(function(json) {
  715. // on fulfillment
  716. }, function(reason) {
  717. // on rejection
  718. });
  719. ```
  720. Unlike callbacks, promises are great composable primitives.
  721. ```js
  722. Promise.all([
  723. getJSON('/posts'),
  724. getJSON('/comments')
  725. ]).then(function(values){
  726. values[0] // => postsJSON
  727. values[1] // => commentsJSON
  728. return values;
  729. });
  730. ```
  731. @class Promise
  732. @param {Function} resolver
  733. Useful for tooling.
  734. @constructor
  735. */
  736. var Promise$2 = function () {
  737. function Promise(resolver) {
  738. this[PROMISE_ID] = nextId();
  739. this._result = this._state = undefined;
  740. this._subscribers = [];
  741. if (noop !== resolver) {
  742. typeof resolver !== 'function' && needsResolver();
  743. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  744. }
  745. }
  746. /**
  747. The primary way of interacting with a promise is through its `then` method,
  748. which registers callbacks to receive either a promise's eventual value or the
  749. reason why the promise cannot be fulfilled.
  750. ```js
  751. findUser().then(function(user){
  752. // user is available
  753. }, function(reason){
  754. // user is unavailable, and you are given the reason why
  755. });
  756. ```
  757. Chaining
  758. --------
  759. The return value of `then` is itself a promise. This second, 'downstream'
  760. promise is resolved with the return value of the first promise's fulfillment
  761. or rejection handler, or rejected if the handler throws an exception.
  762. ```js
  763. findUser().then(function (user) {
  764. return user.name;
  765. }, function (reason) {
  766. return 'default name';
  767. }).then(function (userName) {
  768. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  769. // will be `'default name'`
  770. });
  771. findUser().then(function (user) {
  772. throw new Error('Found user, but still unhappy');
  773. }, function (reason) {
  774. throw new Error('`findUser` rejected and we're unhappy');
  775. }).then(function (value) {
  776. // never reached
  777. }, function (reason) {
  778. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  779. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  780. });
  781. ```
  782. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  783. ```js
  784. findUser().then(function (user) {
  785. throw new PedagogicalException('Upstream error');
  786. }).then(function (value) {
  787. // never reached
  788. }).then(function (value) {
  789. // never reached
  790. }, function (reason) {
  791. // The `PedgagocialException` is propagated all the way down to here
  792. });
  793. ```
  794. Assimilation
  795. ------------
  796. Sometimes the value you want to propagate to a downstream promise can only be
  797. retrieved asynchronously. This can be achieved by returning a promise in the
  798. fulfillment or rejection handler. The downstream promise will then be pending
  799. until the returned promise is settled. This is called *assimilation*.
  800. ```js
  801. findUser().then(function (user) {
  802. return findCommentsByAuthor(user);
  803. }).then(function (comments) {
  804. // The user's comments are now available
  805. });
  806. ```
  807. If the assimliated promise rejects, then the downstream promise will also reject.
  808. ```js
  809. findUser().then(function (user) {
  810. return findCommentsByAuthor(user);
  811. }).then(function (comments) {
  812. // If `findCommentsByAuthor` fulfills, we'll have the value here
  813. }, function (reason) {
  814. // If `findCommentsByAuthor` rejects, we'll have the reason here
  815. });
  816. ```
  817. Simple Example
  818. --------------
  819. Synchronous Example
  820. ```javascript
  821. let result;
  822. try {
  823. result = findResult();
  824. // success
  825. } catch(reason) {
  826. // failure
  827. }
  828. ```
  829. Errback Example
  830. ```js
  831. findResult(function(result, err){
  832. if (err) {
  833. // failure
  834. } else {
  835. // success
  836. }
  837. });
  838. ```
  839. Promise Example;
  840. ```javascript
  841. findResult().then(function(result){
  842. // success
  843. }, function(reason){
  844. // failure
  845. });
  846. ```
  847. Advanced Example
  848. --------------
  849. Synchronous Example
  850. ```javascript
  851. let author, books;
  852. try {
  853. author = findAuthor();
  854. books = findBooksByAuthor(author);
  855. // success
  856. } catch(reason) {
  857. // failure
  858. }
  859. ```
  860. Errback Example
  861. ```js
  862. function foundBooks(books) {
  863. }
  864. function failure(reason) {
  865. }
  866. findAuthor(function(author, err){
  867. if (err) {
  868. failure(err);
  869. // failure
  870. } else {
  871. try {
  872. findBoooksByAuthor(author, function(books, err) {
  873. if (err) {
  874. failure(err);
  875. } else {
  876. try {
  877. foundBooks(books);
  878. } catch(reason) {
  879. failure(reason);
  880. }
  881. }
  882. });
  883. } catch(error) {
  884. failure(err);
  885. }
  886. // success
  887. }
  888. });
  889. ```
  890. Promise Example;
  891. ```javascript
  892. findAuthor().
  893. then(findBooksByAuthor).
  894. then(function(books){
  895. // found books
  896. }).catch(function(reason){
  897. // something went wrong
  898. });
  899. ```
  900. @method then
  901. @param {Function} onFulfilled
  902. @param {Function} onRejected
  903. Useful for tooling.
  904. @return {Promise}
  905. */
  906. /**
  907. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  908. as the catch block of a try/catch statement.
  909. ```js
  910. function findAuthor(){
  911. throw new Error('couldn't find that author');
  912. }
  913. // synchronous
  914. try {
  915. findAuthor();
  916. } catch(reason) {
  917. // something went wrong
  918. }
  919. // async with promises
  920. findAuthor().catch(function(reason){
  921. // something went wrong
  922. });
  923. ```
  924. @method catch
  925. @param {Function} onRejection
  926. Useful for tooling.
  927. @return {Promise}
  928. */
  929. Promise.prototype.catch = function _catch(onRejection) {
  930. return this.then(null, onRejection);
  931. };
  932. /**
  933. `finally` will be invoked regardless of the promise's fate just as native
  934. try/catch/finally behaves
  935. Synchronous example:
  936. ```js
  937. findAuthor() {
  938. if (Math.random() > 0.5) {
  939. throw new Error();
  940. }
  941. return new Author();
  942. }
  943. try {
  944. return findAuthor(); // succeed or fail
  945. } catch(error) {
  946. return findOtherAuther();
  947. } finally {
  948. // always runs
  949. // doesn't affect the return value
  950. }
  951. ```
  952. Asynchronous example:
  953. ```js
  954. findAuthor().catch(function(reason){
  955. return findOtherAuther();
  956. }).finally(function(){
  957. // author was either found, or not
  958. });
  959. ```
  960. @method finally
  961. @param {Function} callback
  962. @return {Promise}
  963. */
  964. Promise.prototype.finally = function _finally(callback) {
  965. var promise = this;
  966. var constructor = promise.constructor;
  967. return promise.then(function (value) {
  968. return constructor.resolve(callback()).then(function () {
  969. return value;
  970. });
  971. }, function (reason) {
  972. return constructor.resolve(callback()).then(function () {
  973. throw reason;
  974. });
  975. });
  976. };
  977. return Promise;
  978. }();
  979. Promise$2.prototype.then = then;
  980. Promise$2.all = all;
  981. Promise$2.race = race;
  982. Promise$2.resolve = resolve$1;
  983. Promise$2.reject = reject$1;
  984. Promise$2._setScheduler = setScheduler;
  985. Promise$2._setAsap = setAsap;
  986. Promise$2._asap = asap;
  987. /*global self*/
  988. function polyfill() {
  989. var local = void 0;
  990. if (typeof commonjsGlobal !== 'undefined') {
  991. local = commonjsGlobal;
  992. } else if (typeof self !== 'undefined') {
  993. local = self;
  994. } else {
  995. try {
  996. local = Function('return this')();
  997. } catch (e) {
  998. throw new Error('polyfill failed because global object is unavailable in this environment');
  999. }
  1000. }
  1001. var P = local.Promise;
  1002. if (P) {
  1003. var promiseToString = null;
  1004. try {
  1005. promiseToString = Object.prototype.toString.call(P.resolve());
  1006. } catch (e) {
  1007. // silently ignored
  1008. }
  1009. if (promiseToString === '[object Promise]' && !P.cast) {
  1010. return;
  1011. }
  1012. }
  1013. local.Promise = Promise$2;
  1014. }
  1015. // Strange compat..
  1016. Promise$2.polyfill = polyfill;
  1017. Promise$2.Promise = Promise$2;
  1018. Promise$2.polyfill();
  1019. return Promise$2;
  1020. })));
  1021. });
  1022. var Errors = createCommonjsModule(function (module, exports) {
  1023. var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
  1024. var extendStatics = Object.setPrototypeOf ||
  1025. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1026. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1027. return function (d, b) {
  1028. extendStatics(d, b);
  1029. function __() { this.constructor = d; }
  1030. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1031. };
  1032. })();
  1033. Object.defineProperty(exports, "__esModule", { value: true });
  1034. var HttpError = /** @class */ (function (_super) {
  1035. __extends(HttpError, _super);
  1036. function HttpError(errorMessage, statusCode) {
  1037. var _newTarget = this.constructor;
  1038. var _this = this;
  1039. var trueProto = _newTarget.prototype;
  1040. _this = _super.call(this, errorMessage) || this;
  1041. _this.statusCode = statusCode;
  1042. // Workaround issue in Typescript compiler
  1043. // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
  1044. _this.__proto__ = trueProto;
  1045. return _this;
  1046. }
  1047. return HttpError;
  1048. }(Error));
  1049. exports.HttpError = HttpError;
  1050. var TimeoutError = /** @class */ (function (_super) {
  1051. __extends(TimeoutError, _super);
  1052. function TimeoutError(errorMessage) {
  1053. var _newTarget = this.constructor;
  1054. if (errorMessage === void 0) { errorMessage = "A timeout occurred."; }
  1055. var _this = this;
  1056. var trueProto = _newTarget.prototype;
  1057. _this = _super.call(this, errorMessage) || this;
  1058. // Workaround issue in Typescript compiler
  1059. // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
  1060. _this.__proto__ = trueProto;
  1061. return _this;
  1062. }
  1063. return TimeoutError;
  1064. }(Error));
  1065. exports.TimeoutError = TimeoutError;
  1066. });
  1067. unwrapExports(Errors);
  1068. var Errors_1 = Errors.HttpError;
  1069. var Errors_2 = Errors.TimeoutError;
  1070. var ILogger = createCommonjsModule(function (module, exports) {
  1071. Object.defineProperty(exports, "__esModule", { value: true });
  1072. var LogLevel;
  1073. (function (LogLevel) {
  1074. LogLevel[LogLevel["Trace"] = 0] = "Trace";
  1075. LogLevel[LogLevel["Information"] = 1] = "Information";
  1076. LogLevel[LogLevel["Warning"] = 2] = "Warning";
  1077. LogLevel[LogLevel["Error"] = 3] = "Error";
  1078. LogLevel[LogLevel["None"] = 4] = "None";
  1079. })(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
  1080. });
  1081. unwrapExports(ILogger);
  1082. var ILogger_1 = ILogger.LogLevel;
  1083. var HttpClient_1 = createCommonjsModule(function (module, exports) {
  1084. var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
  1085. var extendStatics = Object.setPrototypeOf ||
  1086. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1087. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1088. return function (d, b) {
  1089. extendStatics(d, b);
  1090. function __() { this.constructor = d; }
  1091. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1092. };
  1093. })();
  1094. var __assign = (commonjsGlobal && commonjsGlobal.__assign) || Object.assign || function(t) {
  1095. for (var s, i = 1, n = arguments.length; i < n; i++) {
  1096. s = arguments[i];
  1097. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  1098. t[p] = s[p];
  1099. }
  1100. return t;
  1101. };
  1102. Object.defineProperty(exports, "__esModule", { value: true });
  1103. var HttpResponse = /** @class */ (function () {
  1104. function HttpResponse(statusCode, statusText, content) {
  1105. this.statusCode = statusCode;
  1106. this.statusText = statusText;
  1107. this.content = content;
  1108. }
  1109. return HttpResponse;
  1110. }());
  1111. exports.HttpResponse = HttpResponse;
  1112. var HttpClient = /** @class */ (function () {
  1113. function HttpClient() {
  1114. }
  1115. HttpClient.prototype.get = function (url, options) {
  1116. return this.send(__assign({}, options, { method: "GET", url: url }));
  1117. };
  1118. HttpClient.prototype.post = function (url, options) {
  1119. return this.send(__assign({}, options, { method: "POST", url: url }));
  1120. };
  1121. return HttpClient;
  1122. }());
  1123. exports.HttpClient = HttpClient;
  1124. var DefaultHttpClient = /** @class */ (function (_super) {
  1125. __extends(DefaultHttpClient, _super);
  1126. function DefaultHttpClient(logger) {
  1127. var _this = _super.call(this) || this;
  1128. _this.logger = logger;
  1129. return _this;
  1130. }
  1131. DefaultHttpClient.prototype.send = function (request) {
  1132. var _this = this;
  1133. return new Promise(function (resolve, reject) {
  1134. var xhr = new XMLHttpRequest();
  1135. xhr.open(request.method, request.url, true);
  1136. xhr.withCredentials = true;
  1137. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  1138. if (request.headers) {
  1139. Object.keys(request.headers)
  1140. .forEach(function (header) { return xhr.setRequestHeader(header, request.headers[header]); });
  1141. }
  1142. if (request.responseType) {
  1143. xhr.responseType = request.responseType;
  1144. }
  1145. if (request.abortSignal) {
  1146. request.abortSignal.onabort = function () {
  1147. xhr.abort();
  1148. };
  1149. }
  1150. if (request.timeout) {
  1151. xhr.timeout = request.timeout;
  1152. }
  1153. xhr.onload = function () {
  1154. if (request.abortSignal) {
  1155. request.abortSignal.onabort = null;
  1156. }
  1157. if (xhr.status >= 200 && xhr.status < 300) {
  1158. resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));
  1159. }
  1160. else {
  1161. reject(new Errors.HttpError(xhr.statusText, xhr.status));
  1162. }
  1163. };
  1164. xhr.onerror = function () {
  1165. _this.logger.log(ILogger.LogLevel.Warning, "Error from HTTP request. " + xhr.status + ": " + xhr.statusText);
  1166. reject(new Errors.HttpError(xhr.statusText, xhr.status));
  1167. };
  1168. xhr.ontimeout = function () {
  1169. _this.logger.log(ILogger.LogLevel.Warning, "Timeout from HTTP request.");
  1170. reject(new Errors.TimeoutError());
  1171. };
  1172. xhr.send(request.content || "");
  1173. });
  1174. };
  1175. return DefaultHttpClient;
  1176. }(HttpClient));
  1177. exports.DefaultHttpClient = DefaultHttpClient;
  1178. });
  1179. unwrapExports(HttpClient_1);
  1180. var HttpClient_2 = HttpClient_1.HttpResponse;
  1181. var HttpClient_3 = HttpClient_1.HttpClient;
  1182. var HttpClient_4 = HttpClient_1.DefaultHttpClient;
  1183. var Loggers = createCommonjsModule(function (module, exports) {
  1184. Object.defineProperty(exports, "__esModule", { value: true });
  1185. var NullLogger = /** @class */ (function () {
  1186. function NullLogger() {
  1187. }
  1188. NullLogger.prototype.log = function (logLevel, message) {
  1189. };
  1190. return NullLogger;
  1191. }());
  1192. exports.NullLogger = NullLogger;
  1193. var ConsoleLogger = /** @class */ (function () {
  1194. function ConsoleLogger(minimumLogLevel) {
  1195. this.minimumLogLevel = minimumLogLevel;
  1196. }
  1197. ConsoleLogger.prototype.log = function (logLevel, message) {
  1198. if (logLevel >= this.minimumLogLevel) {
  1199. switch (logLevel) {
  1200. case ILogger.LogLevel.Error:
  1201. console.error(ILogger.LogLevel[logLevel] + ": " + message);
  1202. break;
  1203. case ILogger.LogLevel.Warning:
  1204. console.warn(ILogger.LogLevel[logLevel] + ": " + message);
  1205. break;
  1206. case ILogger.LogLevel.Information:
  1207. console.info(ILogger.LogLevel[logLevel] + ": " + message);
  1208. break;
  1209. default:
  1210. console.log(ILogger.LogLevel[logLevel] + ": " + message);
  1211. break;
  1212. }
  1213. }
  1214. };
  1215. return ConsoleLogger;
  1216. }());
  1217. exports.ConsoleLogger = ConsoleLogger;
  1218. var LoggerFactory = /** @class */ (function () {
  1219. function LoggerFactory() {
  1220. }
  1221. LoggerFactory.createLogger = function (logging) {
  1222. if (logging === undefined) {
  1223. return new ConsoleLogger(ILogger.LogLevel.Information);
  1224. }
  1225. if (logging === null) {
  1226. return new NullLogger();
  1227. }
  1228. if (logging.log) {
  1229. return logging;
  1230. }
  1231. return new ConsoleLogger(logging);
  1232. };
  1233. return LoggerFactory;
  1234. }());
  1235. exports.LoggerFactory = LoggerFactory;
  1236. });
  1237. unwrapExports(Loggers);
  1238. var Loggers_1 = Loggers.NullLogger;
  1239. var Loggers_2 = Loggers.ConsoleLogger;
  1240. var Loggers_3 = Loggers.LoggerFactory;
  1241. var AbortController_1 = createCommonjsModule(function (module, exports) {
  1242. Object.defineProperty(exports, "__esModule", { value: true });
  1243. // Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController
  1244. // We don't actually ever use the API being polyfilled, we always use the polyfill because
  1245. // it's a very new API right now.
  1246. var AbortController = /** @class */ (function () {
  1247. function AbortController() {
  1248. this.isAborted = false;
  1249. }
  1250. AbortController.prototype.abort = function () {
  1251. if (!this.isAborted) {
  1252. this.isAborted = true;
  1253. if (this.onabort) {
  1254. this.onabort();
  1255. }
  1256. }
  1257. };
  1258. Object.defineProperty(AbortController.prototype, "signal", {
  1259. get: function () {
  1260. return this;
  1261. },
  1262. enumerable: true,
  1263. configurable: true
  1264. });
  1265. Object.defineProperty(AbortController.prototype, "aborted", {
  1266. get: function () {
  1267. return this.isAborted;
  1268. },
  1269. enumerable: true,
  1270. configurable: true
  1271. });
  1272. return AbortController;
  1273. }());
  1274. exports.AbortController = AbortController;
  1275. });
  1276. unwrapExports(AbortController_1);
  1277. var AbortController_2 = AbortController_1.AbortController;
  1278. var Utils = createCommonjsModule(function (module, exports) {
  1279. Object.defineProperty(exports, "__esModule", { value: true });
  1280. var Arg = /** @class */ (function () {
  1281. function Arg() {
  1282. }
  1283. Arg.isRequired = function (val, name) {
  1284. if (val === null || val === undefined) {
  1285. throw new Error("The '" + name + "' argument is required.");
  1286. }
  1287. };
  1288. Arg.isIn = function (val, values, name) {
  1289. // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.
  1290. if (!(val in values)) {
  1291. throw new Error("Unknown " + name + " value: " + val + ".");
  1292. }
  1293. };
  1294. return Arg;
  1295. }());
  1296. exports.Arg = Arg;
  1297. });
  1298. unwrapExports(Utils);
  1299. var Utils_1 = Utils.Arg;
  1300. var Transports = createCommonjsModule(function (module, exports) {
  1301. var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
  1302. return new (P || (P = Promise))(function (resolve, reject) {
  1303. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1304. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1305. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  1306. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1307. });
  1308. };
  1309. var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
  1310. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  1311. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  1312. function verb(n) { return function (v) { return step([n, v]); }; }
  1313. function step(op) {
  1314. if (f) throw new TypeError("Generator is already executing.");
  1315. while (_) try {
  1316. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  1317. if (y = 0, t) op = [0, t.value];
  1318. switch (op[0]) {
  1319. case 0: case 1: t = op; break;
  1320. case 4: _.label++; return { value: op[1], done: false };
  1321. case 5: _.label++; y = op[1]; op = [0]; continue;
  1322. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  1323. default:
  1324. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  1325. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  1326. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  1327. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  1328. if (t[2]) _.ops.pop();
  1329. _.trys.pop(); continue;
  1330. }
  1331. op = body.call(thisArg, _);
  1332. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  1333. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  1334. }
  1335. };
  1336. Object.defineProperty(exports, "__esModule", { value: true });
  1337. var TransportType;
  1338. (function (TransportType) {
  1339. TransportType[TransportType["WebSockets"] = 0] = "WebSockets";
  1340. TransportType[TransportType["ServerSentEvents"] = 1] = "ServerSentEvents";
  1341. TransportType[TransportType["LongPolling"] = 2] = "LongPolling";
  1342. })(TransportType = exports.TransportType || (exports.TransportType = {}));
  1343. var TransferFormat;
  1344. (function (TransferFormat) {
  1345. TransferFormat[TransferFormat["Text"] = 1] = "Text";
  1346. TransferFormat[TransferFormat["Binary"] = 2] = "Binary";
  1347. })(TransferFormat = exports.TransferFormat || (exports.TransferFormat = {}));
  1348. var WebSocketTransport = /** @class */ (function () {
  1349. function WebSocketTransport(accessTokenFactory, logger) {
  1350. this.logger = logger;
  1351. this.accessTokenFactory = accessTokenFactory || (function () { return null; });
  1352. }
  1353. WebSocketTransport.prototype.connect = function (url, transferFormat, connection) {
  1354. var _this = this;
  1355. Utils.Arg.isRequired(url, "url");
  1356. Utils.Arg.isRequired(transferFormat, "transferFormat");
  1357. Utils.Arg.isIn(transferFormat, TransferFormat, "transferFormat");
  1358. Utils.Arg.isRequired(connection, "connection");
  1359. if (typeof (WebSocket) === "undefined") {
  1360. throw new Error("'WebSocket' is not supported in your environment.");
  1361. }
  1362. this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) Connecting");
  1363. return new Promise(function (resolve, reject) {
  1364. url = url.replace(/^http/, "ws");
  1365. var token = _this.accessTokenFactory();
  1366. if (token) {
  1367. url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token));
  1368. }
  1369. var webSocket = new WebSocket(url);
  1370. if (transferFormat === TransferFormat.Binary) {
  1371. webSocket.binaryType = "arraybuffer";
  1372. }
  1373. webSocket.onopen = function (event) {
  1374. _this.logger.log(ILogger.LogLevel.Information, "WebSocket connected to " + url);
  1375. _this.webSocket = webSocket;
  1376. resolve();
  1377. };
  1378. webSocket.onerror = function (event) {
  1379. reject(event.error);
  1380. };
  1381. webSocket.onmessage = function (message) {
  1382. _this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) data received. " + getDataDetail(message.data) + ".");
  1383. if (_this.onreceive) {
  1384. _this.onreceive(message.data);
  1385. }
  1386. };
  1387. webSocket.onclose = function (event) {
  1388. // webSocket will be null if the transport did not start successfully
  1389. if (_this.onclose && _this.webSocket) {
  1390. if (event.wasClean === false || event.code !== 1000) {
  1391. _this.onclose(new Error("Websocket closed with status code: " + event.code + " (" + event.reason + ")"));
  1392. }
  1393. else {
  1394. _this.onclose();
  1395. }
  1396. }
  1397. };
  1398. });
  1399. };
  1400. WebSocketTransport.prototype.send = function (data) {
  1401. if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
  1402. this.logger.log(ILogger.LogLevel.Trace, "(WebSockets transport) sending data. " + getDataDetail(data) + ".");
  1403. this.webSocket.send(data);
  1404. return Promise.resolve();
  1405. }
  1406. return Promise.reject("WebSocket is not in the OPEN state");
  1407. };
  1408. WebSocketTransport.prototype.stop = function () {
  1409. if (this.webSocket) {
  1410. this.webSocket.close();
  1411. this.webSocket = null;
  1412. }
  1413. return Promise.resolve();
  1414. };
  1415. return WebSocketTransport;
  1416. }());
  1417. exports.WebSocketTransport = WebSocketTransport;
  1418. var ServerSentEventsTransport = /** @class */ (function () {
  1419. function ServerSentEventsTransport(httpClient, accessTokenFactory, logger) {
  1420. this.httpClient = httpClient;
  1421. this.accessTokenFactory = accessTokenFactory || (function () { return null; });
  1422. this.logger = logger;
  1423. }
  1424. ServerSentEventsTransport.prototype.connect = function (url, transferFormat, connection) {
  1425. var _this = this;
  1426. Utils.Arg.isRequired(url, "url");
  1427. Utils.Arg.isRequired(transferFormat, "transferFormat");
  1428. Utils.Arg.isIn(transferFormat, TransferFormat, "transferFormat");
  1429. Utils.Arg.isRequired(connection, "connection");
  1430. if (typeof (EventSource) === "undefined") {
  1431. throw new Error("'EventSource' is not supported in your environment.");
  1432. }
  1433. this.logger.log(ILogger.LogLevel.Trace, "(SSE transport) Connecting");
  1434. this.url = url;
  1435. return new Promise(function (resolve, reject) {
  1436. if (transferFormat !== TransferFormat.Text) {
  1437. reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));
  1438. }
  1439. var token = _this.accessTokenFactory();
  1440. if (token) {
  1441. url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token));
  1442. }
  1443. var eventSource = new EventSource(url, { withCredentials: true });
  1444. try {
  1445. eventSource.onmessage = function (e) {
  1446. if (_this.onreceive) {
  1447. try {
  1448. _this.logger.log(ILogger.LogLevel.Trace, "(SSE transport) data received. " + getDataDetail(e.data) + ".");
  1449. _this.onreceive(e.data);
  1450. }
  1451. catch (error) {
  1452. if (_this.onclose) {
  1453. _this.onclose(error);
  1454. }
  1455. return;
  1456. }
  1457. }
  1458. };
  1459. eventSource.onerror = function (e) {
  1460. reject(new Error(e.message || "Error occurred"));
  1461. // don't report an error if the transport did not start successfully
  1462. if (_this.eventSource && _this.onclose) {
  1463. _this.onclose(new Error(e.message || "Error occurred"));
  1464. }
  1465. };
  1466. eventSource.onopen = function () {
  1467. _this.logger.log(ILogger.LogLevel.Information, "SSE connected to " + _this.url);
  1468. _this.eventSource = eventSource;
  1469. // SSE is a text protocol
  1470. resolve();
  1471. };
  1472. }
  1473. catch (e) {
  1474. return Promise.reject(e);
  1475. }
  1476. });
  1477. };
  1478. ServerSentEventsTransport.prototype.send = function (data) {
  1479. return __awaiter(this, void 0, void 0, function () {
  1480. return __generator(this, function (_a) {
  1481. return [2 /*return*/, send(this.logger, "SSE", this.httpClient, this.url, this.accessTokenFactory, data)];
  1482. });
  1483. });
  1484. };
  1485. ServerSentEventsTransport.prototype.stop = function () {
  1486. if (this.eventSource) {
  1487. this.eventSource.close();
  1488. this.eventSource = null;
  1489. }
  1490. return Promise.resolve();
  1491. };
  1492. return ServerSentEventsTransport;
  1493. }());
  1494. exports.ServerSentEventsTransport = ServerSentEventsTransport;
  1495. var LongPollingTransport = /** @class */ (function () {
  1496. function LongPollingTransport(httpClient, accessTokenFactory, logger) {
  1497. this.httpClient = httpClient;
  1498. this.accessTokenFactory = accessTokenFactory || (function () { return null; });
  1499. this.logger = logger;
  1500. this.pollAbort = new AbortController_1.AbortController();
  1501. }
  1502. LongPollingTransport.prototype.connect = function (url, transferFormat, connection) {
  1503. Utils.Arg.isRequired(url, "url");
  1504. Utils.Arg.isRequired(transferFormat, "transferFormat");
  1505. Utils.Arg.isIn(transferFormat, TransferFormat, "transferFormat");
  1506. Utils.Arg.isRequired(connection, "connection");
  1507. this.url = url;
  1508. this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Connecting");
  1509. // Set a flag indicating we have inherent keep-alive in this transport.
  1510. connection.features.inherentKeepAlive = true;
  1511. if (transferFormat === TransferFormat.Binary && (typeof new XMLHttpRequest().responseType !== "string")) {
  1512. // This will work if we fix: https://github.com/aspnet/SignalR/issues/742
  1513. throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");
  1514. }
  1515. this.poll(this.url, transferFormat);
  1516. return Promise.resolve();
  1517. };
  1518. LongPollingTransport.prototype.poll = function (url, transferFormat) {
  1519. return __awaiter(this, void 0, void 0, function () {
  1520. var pollOptions, token, pollUrl, response, e_1;
  1521. return __generator(this, function (_a) {
  1522. switch (_a.label) {
  1523. case 0:
  1524. pollOptions = {
  1525. abortSignal: this.pollAbort.signal,
  1526. headers: {},
  1527. timeout: 90000,
  1528. };
  1529. if (transferFormat === TransferFormat.Binary) {
  1530. pollOptions.responseType = "arraybuffer";
  1531. }
  1532. token = this.accessTokenFactory();
  1533. if (token) {
  1534. // tslint:disable-next-line:no-string-literal
  1535. pollOptions.headers["Authorization"] = "Bearer " + token;
  1536. }
  1537. _a.label = 1;
  1538. case 1:
  1539. if (!!this.pollAbort.signal.aborted) return [3 /*break*/, 6];
  1540. _a.label = 2;
  1541. case 2:
  1542. _a.trys.push([2, 4, , 5]);
  1543. pollUrl = url + "&_=" + Date.now();
  1544. this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl);
  1545. return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)];
  1546. case 3:
  1547. response = _a.sent();
  1548. if (response.statusCode === 204) {
  1549. this.logger.log(ILogger.LogLevel.Information, "(LongPolling transport) Poll terminated by server");
  1550. // Poll terminated by server
  1551. if (this.onclose) {
  1552. this.onclose();
  1553. }
  1554. this.pollAbort.abort();
  1555. }
  1556. else if (response.statusCode !== 200) {
  1557. this.logger.log(ILogger.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode);
  1558. // Unexpected status code
  1559. if (this.onclose) {
  1560. this.onclose(new Errors.HttpError(response.statusText, response.statusCode));
  1561. }
  1562. this.pollAbort.abort();
  1563. }
  1564. else {
  1565. // Process the response
  1566. if (response.content) {
  1567. this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) data received. " + getDataDetail(response.content) + ".");
  1568. if (this.onreceive) {
  1569. this.onreceive(response.content);
  1570. }
  1571. }
  1572. else {
  1573. // This is another way timeout manifest.
  1574. this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
  1575. }
  1576. }
  1577. return [3 /*break*/, 5];
  1578. case 4:
  1579. e_1 = _a.sent();
  1580. if (e_1 instanceof Errors.TimeoutError) {
  1581. // Ignore timeouts and reissue the poll.
  1582. this.logger.log(ILogger.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
  1583. }
  1584. else {
  1585. // Close the connection with the error as the result.
  1586. if (this.onclose) {
  1587. this.onclose(e_1);
  1588. }
  1589. this.pollAbort.abort();
  1590. }
  1591. return [3 /*break*/, 5];
  1592. case 5: return [3 /*break*/, 1];
  1593. case 6: return [2 /*return*/];
  1594. }
  1595. });
  1596. });
  1597. };
  1598. LongPollingTransport.prototype.send = function (data) {
  1599. return __awaiter(this, void 0, void 0, function () {
  1600. return __generator(this, function (_a) {
  1601. return [2 /*return*/, send(this.logger, "LongPolling", this.httpClient, this.url, this.accessTokenFactory, data)];
  1602. });
  1603. });
  1604. };
  1605. LongPollingTransport.prototype.stop = function () {
  1606. this.pollAbort.abort();
  1607. return Promise.resolve();
  1608. };
  1609. return LongPollingTransport;
  1610. }());
  1611. exports.LongPollingTransport = LongPollingTransport;
  1612. function getDataDetail(data) {
  1613. var length = null;
  1614. if (data instanceof ArrayBuffer) {
  1615. length = "Binary data of length " + data.byteLength;
  1616. }
  1617. else if (typeof data === "string") {
  1618. length = "String data of length " + data.length;
  1619. }
  1620. return length;
  1621. }
  1622. function send(logger, transportName, httpClient, url, accessTokenFactory, content) {
  1623. return __awaiter(this, void 0, void 0, function () {
  1624. var headers, token, response, _a;
  1625. return __generator(this, function (_b) {
  1626. switch (_b.label) {
  1627. case 0:
  1628. token = accessTokenFactory();
  1629. if (token) {
  1630. headers = (_a = {}, _a["Authorization"] = "Bearer " + accessTokenFactory(), _a);
  1631. }
  1632. logger.log(ILogger.LogLevel.Trace, "(" + transportName + " transport) sending data. " + getDataDetail(content) + ".");
  1633. return [4 /*yield*/, httpClient.post(url, {
  1634. content: content,
  1635. headers: headers,
  1636. })];
  1637. case 1:
  1638. response = _b.sent();
  1639. logger.log(ILogger.LogLevel.Trace, "(" + transportName + " transport) request complete. Response status: " + response.statusCode + ".");
  1640. return [2 /*return*/];
  1641. }
  1642. });
  1643. });
  1644. }
  1645. });
  1646. unwrapExports(Transports);
  1647. var Transports_1 = Transports.TransportType;
  1648. var Transports_2 = Transports.TransferFormat;
  1649. var Transports_3 = Transports.WebSocketTransport;
  1650. var Transports_4 = Transports.ServerSentEventsTransport;
  1651. var Transports_5 = Transports.LongPollingTransport;
  1652. var HttpConnection_1 = createCommonjsModule(function (module, exports) {
  1653. var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
  1654. return new (P || (P = Promise))(function (resolve, reject) {
  1655. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  1656. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  1657. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  1658. step((generator = generator.apply(thisArg, _arguments || [])).next());
  1659. });
  1660. };
  1661. var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
  1662. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  1663. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  1664. function verb(n) { return function (v) { return step([n, v]); }; }
  1665. function step(op) {
  1666. if (f) throw new TypeError("Generator is already executing.");
  1667. while (_) try {
  1668. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  1669. if (y = 0, t) op = [0, t.value];
  1670. switch (op[0]) {
  1671. case 0: case 1: t = op; break;
  1672. case 4: _.label++; return { value: op[1], done: false };
  1673. case 5: _.label++; y = op[1]; op = [0]; continue;
  1674. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  1675. default:
  1676. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  1677. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  1678. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  1679. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  1680. if (t[2]) _.ops.pop();
  1681. _.trys.pop(); continue;
  1682. }
  1683. op = body.call(thisArg, _);
  1684. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  1685. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  1686. }
  1687. };
  1688. Object.defineProperty(exports, "__esModule", { value: true });
  1689. var HttpConnection = /** @class */ (function () {
  1690. function HttpConnection(url, options) {
  1691. if (options === void 0) { options = {}; }
  1692. this.features = {};
  1693. Utils.Arg.isRequired(url, "url");
  1694. this.logger = Loggers.LoggerFactory.createLogger(options.logger);
  1695. this.baseUrl = this.resolveUrl(url);
  1696. options = options || {};
  1697. options.accessTokenFactory = options.accessTokenFactory || (function () { return null; });
  1698. this.httpClient = options.httpClient || new HttpClient_1.DefaultHttpClient(this.logger);
  1699. this.connectionState = 2 /* Disconnected */;
  1700. this.options = options;
  1701. }
  1702. HttpConnection.prototype.start = function (transferFormat) {
  1703. Utils.Arg.isRequired(transferFormat, "transferFormat");
  1704. Utils.Arg.isIn(transferFormat, Transports.TransferFormat, "transferFormat");
  1705. this.logger.log(ILogger.LogLevel.Trace, "Starting connection with transfer format '" + Transports.TransferFormat[transferFormat] + "'.");
  1706. if (this.connectionState !== 2 /* Disconnected */) {
  1707. return Promise.reject(new Error("Cannot start a connection that is not in the 'Disconnected' state."));
  1708. }
  1709. this.connectionState = 0 /* Connecting */;
  1710. this.startPromise = this.startInternal(transferFormat);
  1711. return this.startPromise;
  1712. };
  1713. HttpConnection.prototype.startInternal = function (transferFormat) {
  1714. return __awaiter(this, void 0, void 0, function () {
  1715. var _this = this;
  1716. var token, headers, negotiateResponse, e_1, _a;
  1717. return __generator(this, function (_b) {
  1718. switch (_b.label) {
  1719. case 0:
  1720. _b.trys.push([0, 6, , 7]);
  1721. if (!(this.options.transport === Transports.TransportType.WebSockets)) return [3 /*break*/, 2];
  1722. // No need to add a connection ID in this case
  1723. this.url = this.baseUrl;
  1724. this.transport = this.constructTransport(Transports.TransportType.WebSockets);
  1725. // We should just call connect directly in this case.
  1726. // No fallback or negotiate in this case.
  1727. return [4 /*yield*/, this.transport.connect(this.url, transferFormat, this)];
  1728. case 1:
  1729. // We should just call connect directly in this case.
  1730. // No fallback or negotiate in this case.
  1731. _b.sent();
  1732. return [3 /*break*/, 5];
  1733. case 2:
  1734. token = this.options.accessTokenFactory();
  1735. headers = void 0;
  1736. if (token) {
  1737. headers = (_a = {}, _a["Authorization"] = "Bearer " + token, _a);
  1738. }
  1739. return [4 /*yield*/, this.getNegotiationResponse(headers)];
  1740. case 3:
  1741. negotiateResponse = _b.sent();
  1742. // the user tries to stop the the connection when it is being started
  1743. if (this.connectionState === 2 /* Disconnected */) {
  1744. return [2 /*return*/];
  1745. }
  1746. return [4 /*yield*/, this.createTransport(this.options.transport, negotiateResponse, transferFormat, headers)];
  1747. case 4:
  1748. _b.sent();
  1749. _b.label = 5;
  1750. case 5:
  1751. this.transport.onreceive = this.onreceive;
  1752. this.transport.onclose = function (e) { return _this.stopConnection(true, e); };
  1753. // only change the state if we were connecting to not overwrite
  1754. // the state if the connection is already marked as Disconnected
  1755. this.changeState(0 /* Connecting */, 1 /* Connected */);
  1756. return [3 /*break*/, 7];
  1757. case 6:
  1758. e_1 = _b.sent();
  1759. this.logger.log(ILogger.LogLevel.Error, "Failed to start the connection: " + e_1);
  1760. this.connectionState = 2 /* Disconnected */;
  1761. this.transport = null;
  1762. throw e_1;
  1763. case 7: return [2 /*return*/];
  1764. }
  1765. });
  1766. });
  1767. };
  1768. HttpConnection.prototype.getNegotiationResponse = function (headers) {
  1769. return __awaiter(this, void 0, void 0, function () {
  1770. var negotiateUrl, response, e_2;
  1771. return __generator(this, function (_a) {
  1772. switch (_a.label) {
  1773. case 0:
  1774. negotiateUrl = this.resolveNegotiateUrl(this.baseUrl);
  1775. this.logger.log(ILogger.LogLevel.Trace, "Sending negotiation request: " + negotiateUrl);
  1776. _a.label = 1;
  1777. case 1:
  1778. _a.trys.push([1, 3, , 4]);
  1779. return [4 /*yield*/, this.httpClient.post(negotiateUrl, {
  1780. content: "",
  1781. headers: headers,
  1782. })];
  1783. case 2:
  1784. response = _a.sent();
  1785. return [2 /*return*/, JSON.parse(response.content)];
  1786. case 3:
  1787. e_2 = _a.sent();
  1788. this.logger.log(ILogger.LogLevel.Error, "Failed to complete negotiation with the server: " + e_2);
  1789. throw e_2;
  1790. case 4: return [2 /*return*/];
  1791. }
  1792. });
  1793. });
  1794. };
  1795. HttpConnection.prototype.updateConnectionId = function (negotiateResponse) {
  1796. this.connectionId = negotiateResponse.connectionId;
  1797. this.url = this.baseUrl + (this.baseUrl.indexOf("?") === -1 ? "?" : "&") + ("id=" + this.connectionId);
  1798. };
  1799. HttpConnection.prototype.createTransport = function (requestedTransport, negotiateResponse, requestedTransferFormat, headers) {
  1800. return __awaiter(this, void 0, void 0, function () {
  1801. var transports, _i, transports_1, endpoint, transport, ex_1;
  1802. return __generator(this, function (_a) {
  1803. switch (_a.label) {
  1804. case 0:
  1805. this.updateConnectionId(negotiateResponse);
  1806. if (!this.isITransport(requestedTransport)) return [3 /*break*/, 2];
  1807. this.logger.log(ILogger.LogLevel.Trace, "Connection was provided an instance of ITransport, using that directly.");
  1808. this.transport = requestedTransport;
  1809. return [4 /*yield*/, this.transport.connect(this.url, requestedTransferFormat, this)];
  1810. case 1:
  1811. _a.sent();
  1812. // only change the state if we were connecting to not overwrite
  1813. // the state if the connection is already marked as Disconnected
  1814. this.changeState(0 /* Connecting */, 1 /* Connected */);
  1815. return [2 /*return*/];
  1816. case 2:
  1817. transports = negotiateResponse.availableTransports;
  1818. _i = 0, transports_1 = transports;
  1819. _a.label = 3;
  1820. case 3:
  1821. if (!(_i < transports_1.length)) return [3 /*break*/, 9];
  1822. endpoint = transports_1[_i];
  1823. this.connectionState = 0 /* Connecting */;
  1824. transport = this.resolveTransport(endpoint, requestedTransport, requestedTransferFormat);
  1825. if (!(typeof transport === "number")) return [3 /*break*/, 8];
  1826. this.transport = this.constructTransport(transport);
  1827. if (!(negotiateResponse.connectionId === null)) return [3 /*break*/, 5];
  1828. return [4 /*yield*/, this.getNegotiationResponse(headers)];
  1829. case 4:
  1830. negotiateResponse = _a.sent();
  1831. this.updateConnectionId(negotiateResponse);
  1832. _a.label = 5;
  1833. case 5:
  1834. _a.trys.push([5, 7, , 8]);
  1835. return [4 /*yield*/, this.transport.connect(this.url, requestedTransferFormat, this)];
  1836. case 6:
  1837. _a.sent();
  1838. this.changeState(0 /* Connecting */, 1 /* Connected */);
  1839. return [2 /*return*/];
  1840. case 7:
  1841. ex_1 = _a.sent();
  1842. this.logger.log(ILogger.LogLevel.Error, "Failed to start the transport '" + Transports.TransportType[transport] + "': " + ex_1);
  1843. this.connectionState = 2 /* Disconnected */;
  1844. negotiateResponse.connectionId = null;
  1845. return [3 /*break*/, 8];
  1846. case 8:
  1847. _i++;
  1848. return [3 /*break*/, 3];
  1849. case 9: throw new Error("Unable to initialize any of the available transports.");
  1850. }
  1851. });
  1852. });
  1853. };
  1854. HttpConnection.prototype.constructTransport = function (transport) {
  1855. switch (transport) {
  1856. case Transports.TransportType.WebSockets:
  1857. return new Transports.WebSocketTransport(this.options.accessTokenFactory, this.logger);
  1858. case Transports.TransportType.ServerSentEvents:
  1859. return new Transports.ServerSentEventsTransport(this.httpClient, this.options.accessTokenFactory, this.logger);
  1860. case Transports.TransportType.LongPolling:
  1861. return new Transports.LongPollingTransport(this.httpClient, this.options.accessTokenFactory, this.logger);
  1862. default:
  1863. throw new Error("Unknown transport: " + transport + ".");
  1864. }
  1865. };
  1866. HttpConnection.prototype.resolveTransport = function (endpoint, requestedTransport, requestedTransferFormat) {
  1867. var transport = Transports.TransportType[endpoint.transport];
  1868. if (transport === null || transport === undefined) {
  1869. this.logger.log(ILogger.LogLevel.Trace, "Skipping transport '" + endpoint.transport + "' because it is not supported by this client.");
  1870. }
  1871. else {
  1872. var transferFormats = endpoint.transferFormats.map(function (s) { return Transports.TransferFormat[s]; });
  1873. if (!requestedTransport || transport === requestedTransport) {
  1874. if (transferFormats.indexOf(requestedTransferFormat) >= 0) {
  1875. if ((transport === Transports.TransportType.WebSockets && typeof WebSocket === "undefined") ||
  1876. (transport === Transports.TransportType.ServerSentEvents && typeof EventSource === "undefined")) {
  1877. this.logger.log(ILogger.LogLevel.Trace, "Skipping transport '" + Transports.TransportType[transport] + "' because it is not supported in your environment.'");
  1878. }
  1879. else {
  1880. this.logger.log(ILogger.LogLevel.Trace, "Selecting transport '" + Transports.TransportType[transport] + "'");
  1881. return transport;
  1882. }
  1883. }
  1884. else {
  1885. this.logger.log(ILogger.LogLevel.Trace, "Skipping transport '" + Transports.TransportType[transport] + "' because it does not support the requested transfer format '" + Transports.TransferFormat[requestedTransferFormat] + "'.");
  1886. }
  1887. }
  1888. else {
  1889. this.logger.log(ILogger.LogLevel.Trace, "Skipping transport '" + Transports.TransportType[transport] + "' because it was disabled by the client.");
  1890. }
  1891. }
  1892. return null;
  1893. };
  1894. HttpConnection.prototype.isITransport = function (transport) {
  1895. return typeof (transport) === "object" && "connect" in transport;
  1896. };
  1897. HttpConnection.prototype.changeState = function (from, to) {
  1898. if (this.connectionState === from) {
  1899. this.connectionState = to;
  1900. return true;
  1901. }
  1902. return false;
  1903. };
  1904. HttpConnection.prototype.send = function (data) {
  1905. if (this.connectionState !== 1 /* Connected */) {
  1906. throw new Error("Cannot send data if the connection is not in the 'Connected' State.");
  1907. }
  1908. return this.transport.send(data);
  1909. };
  1910. HttpConnection.prototype.stop = function (error) {
  1911. return __awaiter(this, void 0, void 0, function () {
  1912. var previousState, e_3;
  1913. return __generator(this, function (_a) {
  1914. switch (_a.label) {
  1915. case 0:
  1916. previousState = this.connectionState;
  1917. this.connectionState = 2 /* Disconnected */;
  1918. _a.label = 1;
  1919. case 1:
  1920. _a.trys.push([1, 3, , 4]);
  1921. return [4 /*yield*/, this.startPromise];
  1922. case 2:
  1923. _a.sent();
  1924. return [3 /*break*/, 4];
  1925. case 3:
  1926. e_3 = _a.sent();
  1927. return [3 /*break*/, 4];
  1928. case 4:
  1929. this.stopConnection(/*raiseClosed*/ previousState === 1 /* Connected */, error);
  1930. return [2 /*return*/];
  1931. }
  1932. });
  1933. });
  1934. };
  1935. HttpConnection.prototype.stopConnection = function (raiseClosed, error) {
  1936. if (this.transport) {
  1937. this.transport.stop();
  1938. this.transport = null;
  1939. }
  1940. if (error) {
  1941. this.logger.log(ILogger.LogLevel.Error, "Connection disconnected with error '" + error + "'.");
  1942. }
  1943. else {
  1944. this.logger.log(ILogger.LogLevel.Information, "Connection disconnected.");
  1945. }
  1946. this.connectionState = 2 /* Disconnected */;
  1947. if (raiseClosed && this.onclose) {
  1948. this.onclose(error);
  1949. }
  1950. };
  1951. HttpConnection.prototype.resolveUrl = function (url) {
  1952. // startsWith is not supported in IE
  1953. if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
  1954. return url;
  1955. }
  1956. if (typeof window === "undefined" || !window || !window.document) {
  1957. throw new Error("Cannot resolve '" + url + "'.");
  1958. }
  1959. var parser = window.document.createElement("a");
  1960. parser.href = url;
  1961. var baseUrl = (!parser.protocol || parser.protocol === ":")
  1962. ? window.document.location.protocol + "//" + (parser.host || window.document.location.host)
  1963. : parser.protocol + "//" + parser.host;
  1964. if (!url || url[0] !== "/") {
  1965. url = "/" + url;
  1966. }
  1967. var normalizedUrl = baseUrl + url;
  1968. this.logger.log(ILogger.LogLevel.Information, "Normalizing '" + url + "' to '" + normalizedUrl + "'.");
  1969. return normalizedUrl;
  1970. };
  1971. HttpConnection.prototype.resolveNegotiateUrl = function (url) {
  1972. var index = url.indexOf("?");
  1973. var negotiateUrl = url.substring(0, index === -1 ? url.length : index);
  1974. if (negotiateUrl[negotiateUrl.length - 1] !== "/") {
  1975. negotiateUrl += "/";
  1976. }
  1977. negotiateUrl += "negotiate";
  1978. negotiateUrl += index === -1 ? "" : url.substring(index);
  1979. return negotiateUrl;
  1980. };
  1981. return HttpConnection;
  1982. }());
  1983. exports.HttpConnection = HttpConnection;
  1984. });
  1985. unwrapExports(HttpConnection_1);
  1986. var HttpConnection_2 = HttpConnection_1.HttpConnection;
  1987. var TextMessageFormat_1 = createCommonjsModule(function (module, exports) {
  1988. Object.defineProperty(exports, "__esModule", { value: true });
  1989. var TextMessageFormat = /** @class */ (function () {
  1990. function TextMessageFormat() {
  1991. }
  1992. TextMessageFormat.write = function (output) {
  1993. return "" + output + TextMessageFormat.RecordSeparator;
  1994. };
  1995. TextMessageFormat.parse = function (input) {
  1996. if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
  1997. throw new Error("Message is incomplete.");
  1998. }
  1999. var messages = input.split(TextMessageFormat.RecordSeparator);
  2000. messages.pop();
  2001. return messages;
  2002. };
  2003. TextMessageFormat.RecordSeparatorCode = 0x1e;
  2004. TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);
  2005. return TextMessageFormat;
  2006. }());
  2007. exports.TextMessageFormat = TextMessageFormat;
  2008. });
  2009. unwrapExports(TextMessageFormat_1);
  2010. var TextMessageFormat_2 = TextMessageFormat_1.TextMessageFormat;
  2011. var JsonHubProtocol_1 = createCommonjsModule(function (module, exports) {
  2012. Object.defineProperty(exports, "__esModule", { value: true });
  2013. exports.JSON_HUB_PROTOCOL_NAME = "json";
  2014. var JsonHubProtocol = /** @class */ (function () {
  2015. function JsonHubProtocol() {
  2016. this.name = exports.JSON_HUB_PROTOCOL_NAME;
  2017. this.version = 1;
  2018. this.transferFormat = Transports.TransferFormat.Text;
  2019. }
  2020. JsonHubProtocol.prototype.parseMessages = function (input, logger) {
  2021. if (!input) {
  2022. return [];
  2023. }
  2024. if (logger === null) {
  2025. logger = new Loggers.NullLogger();
  2026. }
  2027. // Parse the messages
  2028. var messages = TextMessageFormat_1.TextMessageFormat.parse(input);
  2029. var hubMessages = [];
  2030. for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
  2031. var message = messages_1[_i];
  2032. var parsedMessage = JSON.parse(message);
  2033. if (typeof parsedMessage.type !== "number") {
  2034. throw new Error("Invalid payload.");
  2035. }
  2036. switch (parsedMessage.type) {
  2037. case 1 /* Invocation */:
  2038. this.isInvocationMessage(parsedMessage);
  2039. break;
  2040. case 2 /* StreamItem */:
  2041. this.isStreamItemMessage(parsedMessage);
  2042. break;
  2043. case 3 /* Completion */:
  2044. this.isCompletionMessage(parsedMessage);
  2045. break;
  2046. case 6 /* Ping */:
  2047. // Single value, no need to validate
  2048. break;
  2049. case 7 /* Close */:
  2050. // All optional values, no need to validate
  2051. break;
  2052. default:
  2053. // Future protocol changes can add message types, old clients can ignore them
  2054. logger.log(ILogger.LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored.");
  2055. continue;
  2056. }
  2057. hubMessages.push(parsedMessage);
  2058. }
  2059. return hubMessages;
  2060. };
  2061. JsonHubProtocol.prototype.writeMessage = function (message) {
  2062. return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(message));
  2063. };
  2064. JsonHubProtocol.prototype.isInvocationMessage = function (message) {
  2065. this.assertNotEmptyString(message.target, "Invalid payload for Invocation message.");
  2066. if (message.invocationId !== undefined) {
  2067. this.assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message.");
  2068. }
  2069. };
  2070. JsonHubProtocol.prototype.isStreamItemMessage = function (message) {
  2071. this.assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message.");
  2072. if (message.item === undefined) {
  2073. throw new Error("Invalid payload for StreamItem message.");
  2074. }
  2075. };
  2076. JsonHubProtocol.prototype.isCompletionMessage = function (message) {
  2077. if (message.result && message.error) {
  2078. throw new Error("Invalid payload for Completion message.");
  2079. }
  2080. if (!message.result && message.error) {
  2081. this.assertNotEmptyString(message.error, "Invalid payload for Completion message.");
  2082. }
  2083. this.assertNotEmptyString(message.invocationId, "Invalid payload for Completion message.");
  2084. };
  2085. JsonHubProtocol.prototype.assertNotEmptyString = function (value, errorMessage) {
  2086. if (typeof value !== "string" || value === "") {
  2087. throw new Error(errorMessage);
  2088. }
  2089. };
  2090. return JsonHubProtocol;
  2091. }());
  2092. exports.JsonHubProtocol = JsonHubProtocol;
  2093. });
  2094. unwrapExports(JsonHubProtocol_1);
  2095. var JsonHubProtocol_2 = JsonHubProtocol_1.JSON_HUB_PROTOCOL_NAME;
  2096. var JsonHubProtocol_3 = JsonHubProtocol_1.JsonHubProtocol;
  2097. var Observable = createCommonjsModule(function (module, exports) {
  2098. Object.defineProperty(exports, "__esModule", { value: true });
  2099. var Subscription = /** @class */ (function () {
  2100. function Subscription(subject, observer) {
  2101. this.subject = subject;
  2102. this.observer = observer;
  2103. }
  2104. Subscription.prototype.dispose = function () {
  2105. var index = this.subject.observers.indexOf(this.observer);
  2106. if (index > -1) {
  2107. this.subject.observers.splice(index, 1);
  2108. }
  2109. if (this.subject.observers.length === 0) {
  2110. this.subject.cancelCallback().catch(function (_) { });
  2111. }
  2112. };
  2113. return Subscription;
  2114. }());
  2115. exports.Subscription = Subscription;
  2116. var Subject = /** @class */ (function () {
  2117. function Subject(cancelCallback) {
  2118. this.observers = [];
  2119. this.cancelCallback = cancelCallback;
  2120. }
  2121. Subject.prototype.next = function (item) {
  2122. for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
  2123. var observer = _a[_i];
  2124. observer.next(item);
  2125. }
  2126. };
  2127. Subject.prototype.error = function (err) {
  2128. for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
  2129. var observer = _a[_i];
  2130. if (observer.error) {
  2131. observer.error(err);
  2132. }
  2133. }
  2134. };
  2135. Subject.prototype.complete = function () {
  2136. for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
  2137. var observer = _a[_i];
  2138. if (observer.complete) {
  2139. observer.complete();
  2140. }
  2141. }
  2142. };
  2143. Subject.prototype.subscribe = function (observer) {
  2144. this.observers.push(observer);
  2145. return new Subscription(this, observer);
  2146. };
  2147. return Subject;
  2148. }());
  2149. exports.Subject = Subject;
  2150. });
  2151. unwrapExports(Observable);
  2152. var Observable_1 = Observable.Subscription;
  2153. var Observable_2 = Observable.Subject;
  2154. var HubConnection_1 = createCommonjsModule(function (module, exports) {
  2155. var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
  2156. return new (P || (P = Promise))(function (resolve, reject) {
  2157. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  2158. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  2159. function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
  2160. step((generator = generator.apply(thisArg, _arguments || [])).next());
  2161. });
  2162. };
  2163. var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
  2164. var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  2165. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  2166. function verb(n) { return function (v) { return step([n, v]); }; }
  2167. function step(op) {
  2168. if (f) throw new TypeError("Generator is already executing.");
  2169. while (_) try {
  2170. if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
  2171. if (y = 0, t) op = [0, t.value];
  2172. switch (op[0]) {
  2173. case 0: case 1: t = op; break;
  2174. case 4: _.label++; return { value: op[1], done: false };
  2175. case 5: _.label++; y = op[1]; op = [0]; continue;
  2176. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  2177. default:
  2178. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  2179. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  2180. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  2181. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  2182. if (t[2]) _.ops.pop();
  2183. _.trys.pop(); continue;
  2184. }
  2185. op = body.call(thisArg, _);
  2186. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
  2187. if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
  2188. }
  2189. };
  2190. Object.defineProperty(exports, "__esModule", { value: true });
  2191. exports.JsonHubProtocol = JsonHubProtocol_1.JsonHubProtocol;
  2192. var DEFAULT_TIMEOUT_IN_MS = 30 * 1000;
  2193. var HubConnection = /** @class */ (function () {
  2194. function HubConnection(urlOrConnection, options) {
  2195. if (options === void 0) { options = {}; }
  2196. var _this = this;
  2197. options = options || {};
  2198. this.timeoutInMilliseconds = options.timeoutInMilliseconds || DEFAULT_TIMEOUT_IN_MS;
  2199. this.protocol = options.protocol || new JsonHubProtocol_1.JsonHubProtocol();
  2200. if (typeof urlOrConnection === "string") {
  2201. this.connection = new HttpConnection_1.HttpConnection(urlOrConnection, options);
  2202. }
  2203. else {
  2204. this.connection = urlOrConnection;
  2205. }
  2206. this.logger = Loggers.LoggerFactory.createLogger(options.logger);
  2207. this.connection.onreceive = function (data) { return _this.processIncomingData(data); };
  2208. this.connection.onclose = function (error) { return _this.connectionClosed(error); };
  2209. this.callbacks = {};
  2210. this.methods = {};
  2211. this.closedCallbacks = [];
  2212. this.id = 0;
  2213. }
  2214. HubConnection.prototype.processIncomingData = function (data) {
  2215. this.cleanupTimeout();
  2216. if (!this.receivedHandshakeResponse) {
  2217. data = this.processHandshakeResponse(data);
  2218. this.receivedHandshakeResponse = true;
  2219. }
  2220. // Data may have all been read when processing handshake response
  2221. if (data) {
  2222. // Parse the messages
  2223. var messages = this.protocol.parseMessages(data, this.logger);
  2224. for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
  2225. var message = messages_1[_i];
  2226. switch (message.type) {
  2227. case 1 /* Invocation */:
  2228. this.invokeClientMethod(message);
  2229. break;
  2230. case 2 /* StreamItem */:
  2231. case 3 /* Completion */:
  2232. var callback = this.callbacks[message.invocationId];
  2233. if (callback != null) {
  2234. if (message.type === 3 /* Completion */) {
  2235. delete this.callbacks[message.invocationId];
  2236. }
  2237. callback(message);
  2238. }
  2239. break;
  2240. case 6 /* Ping */:
  2241. // Don't care about pings
  2242. break;
  2243. case 7 /* Close */:
  2244. this.logger.log(ILogger.LogLevel.Information, "Close message received from server.");
  2245. this.connection.stop(message.error ? new Error("Server returned an error on close: " + message.error) : null);
  2246. break;
  2247. default:
  2248. this.logger.log(ILogger.LogLevel.Warning, "Invalid message type: " + message.type);
  2249. break;
  2250. }
  2251. }
  2252. }
  2253. this.configureTimeout();
  2254. };
  2255. HubConnection.prototype.processHandshakeResponse = function (data) {
  2256. var responseMessage;
  2257. var messageData;
  2258. var remainingData;
  2259. try {
  2260. if (data instanceof ArrayBuffer) {
  2261. // Format is binary but still need to read JSON text from handshake response
  2262. var binaryData = new Uint8Array(data);
  2263. var separatorIndex = binaryData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparatorCode);
  2264. if (separatorIndex === -1) {
  2265. throw new Error("Message is incomplete.");
  2266. }
  2267. // content before separator is handshake response
  2268. // optional content after is additional messages
  2269. var responseLength = separatorIndex + 1;
  2270. messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength));
  2271. remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
  2272. }
  2273. else {
  2274. var textData = data;
  2275. var separatorIndex = textData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparator);
  2276. if (separatorIndex === -1) {
  2277. throw new Error("Message is incomplete.");
  2278. }
  2279. // content before separator is handshake response
  2280. // optional content after is additional messages
  2281. var responseLength = separatorIndex + 1;
  2282. messageData = textData.substring(0, responseLength);
  2283. remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
  2284. }
  2285. // At this point we should have just the single handshake message
  2286. var messages = TextMessageFormat_1.TextMessageFormat.parse(messageData);
  2287. responseMessage = JSON.parse(messages[0]);
  2288. }
  2289. catch (e) {
  2290. var message = "Error parsing handshake response: " + e;
  2291. this.logger.log(ILogger.LogLevel.Error, message);
  2292. var error = new Error(message);
  2293. this.connection.stop(error);
  2294. throw error;
  2295. }
  2296. if (responseMessage.error) {
  2297. var message = "Server returned handshake error: " + responseMessage.error;
  2298. this.logger.log(ILogger.LogLevel.Error, message);
  2299. this.connection.stop(new Error(message));
  2300. }
  2301. else {
  2302. this.logger.log(ILogger.LogLevel.Trace, "Server handshake complete.");
  2303. }
  2304. // multiple messages could have arrived with handshake
  2305. // return additional data to be parsed as usual, or null if all parsed
  2306. return remainingData;
  2307. };
  2308. HubConnection.prototype.configureTimeout = function () {
  2309. var _this = this;
  2310. if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
  2311. // Set the timeout timer
  2312. this.timeoutHandle = setTimeout(function () { return _this.serverTimeout(); }, this.timeoutInMilliseconds);
  2313. }
  2314. };
  2315. HubConnection.prototype.serverTimeout = function () {
  2316. // The server hasn't talked to us in a while. It doesn't like us anymore ... :(
  2317. // Terminate the connection
  2318. this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
  2319. };
  2320. HubConnection.prototype.invokeClientMethod = function (invocationMessage) {
  2321. var _this = this;
  2322. var methods = this.methods[invocationMessage.target.toLowerCase()];
  2323. if (methods) {
  2324. methods.forEach(function (m) { return m.apply(_this, invocationMessage.arguments); });
  2325. if (invocationMessage.invocationId) {
  2326. // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.
  2327. var message = "Server requested a response, which is not supported in this version of the client.";
  2328. this.logger.log(ILogger.LogLevel.Error, message);
  2329. this.connection.stop(new Error(message));
  2330. }
  2331. }
  2332. else {
  2333. this.logger.log(ILogger.LogLevel.Warning, "No client method with the name '" + invocationMessage.target + "' found.");
  2334. }
  2335. };
  2336. HubConnection.prototype.connectionClosed = function (error) {
  2337. var _this = this;
  2338. var callbacks = this.callbacks;
  2339. this.callbacks = {};
  2340. Object.keys(callbacks)
  2341. .forEach(function (key) {
  2342. var callback = callbacks[key];
  2343. callback(undefined, error ? error : new Error("Invocation canceled due to connection being closed."));
  2344. });
  2345. this.cleanupTimeout();
  2346. this.closedCallbacks.forEach(function (c) { return c.apply(_this, [error]); });
  2347. };
  2348. HubConnection.prototype.start = function () {
  2349. return __awaiter(this, void 0, void 0, function () {
  2350. return __generator(this, function (_a) {
  2351. switch (_a.label) {
  2352. case 0:
  2353. this.logger.log(ILogger.LogLevel.Trace, "Starting HubConnection.");
  2354. this.receivedHandshakeResponse = false;
  2355. return [4 /*yield*/, this.connection.start(this.protocol.transferFormat)];
  2356. case 1:
  2357. _a.sent();
  2358. this.logger.log(ILogger.LogLevel.Trace, "Sending handshake request.");
  2359. // Handshake request is always JSON
  2360. return [4 /*yield*/, this.connection.send(TextMessageFormat_1.TextMessageFormat.write(JSON.stringify({ protocol: this.protocol.name, version: this.protocol.version })))];
  2361. case 2:
  2362. // Handshake request is always JSON
  2363. _a.sent();
  2364. this.logger.log(ILogger.LogLevel.Information, "Using HubProtocol '" + this.protocol.name + "'.");
  2365. // defensively cleanup timeout in case we receive a message from the server before we finish start
  2366. this.cleanupTimeout();
  2367. this.configureTimeout();
  2368. return [2 /*return*/];
  2369. }
  2370. });
  2371. });
  2372. };
  2373. HubConnection.prototype.stop = function () {
  2374. this.logger.log(ILogger.LogLevel.Trace, "Stopping HubConnection.");
  2375. this.cleanupTimeout();
  2376. return this.connection.stop();
  2377. };
  2378. HubConnection.prototype.stream = function (methodName) {
  2379. var _this = this;
  2380. var args = [];
  2381. for (var _i = 1; _i < arguments.length; _i++) {
  2382. args[_i - 1] = arguments[_i];
  2383. }
  2384. var invocationDescriptor = this.createStreamInvocation(methodName, args);
  2385. var subject = new Observable.Subject(function () {
  2386. var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId);
  2387. var cancelMessage = _this.protocol.writeMessage(cancelInvocation);
  2388. delete _this.callbacks[invocationDescriptor.invocationId];
  2389. return _this.connection.send(cancelMessage);
  2390. });
  2391. this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
  2392. if (error) {
  2393. subject.error(error);
  2394. return;
  2395. }
  2396. if (invocationEvent.type === 3 /* Completion */) {
  2397. if (invocationEvent.error) {
  2398. subject.error(new Error(invocationEvent.error));
  2399. }
  2400. else {
  2401. subject.complete();
  2402. }
  2403. }
  2404. else {
  2405. subject.next((invocationEvent.item));
  2406. }
  2407. };
  2408. var message = this.protocol.writeMessage(invocationDescriptor);
  2409. this.connection.send(message)
  2410. .catch(function (e) {
  2411. subject.error(e);
  2412. delete _this.callbacks[invocationDescriptor.invocationId];
  2413. });
  2414. return subject;
  2415. };
  2416. HubConnection.prototype.send = function (methodName) {
  2417. var args = [];
  2418. for (var _i = 1; _i < arguments.length; _i++) {
  2419. args[_i - 1] = arguments[_i];
  2420. }
  2421. var invocationDescriptor = this.createInvocation(methodName, args, true);
  2422. var message = this.protocol.writeMessage(invocationDescriptor);
  2423. return this.connection.send(message);
  2424. };
  2425. HubConnection.prototype.invoke = function (methodName) {
  2426. var _this = this;
  2427. var args = [];
  2428. for (var _i = 1; _i < arguments.length; _i++) {
  2429. args[_i - 1] = arguments[_i];
  2430. }
  2431. var invocationDescriptor = this.createInvocation(methodName, args, false);
  2432. var p = new Promise(function (resolve, reject) {
  2433. _this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
  2434. if (error) {
  2435. reject(error);
  2436. return;
  2437. }
  2438. if (invocationEvent.type === 3 /* Completion */) {
  2439. var completionMessage = invocationEvent;
  2440. if (completionMessage.error) {
  2441. reject(new Error(completionMessage.error));
  2442. }
  2443. else {
  2444. resolve(completionMessage.result);
  2445. }
  2446. }
  2447. else {
  2448. reject(new Error("Unexpected message type: " + invocationEvent.type));
  2449. }
  2450. };
  2451. var message = _this.protocol.writeMessage(invocationDescriptor);
  2452. _this.connection.send(message)
  2453. .catch(function (e) {
  2454. reject(e);
  2455. delete _this.callbacks[invocationDescriptor.invocationId];
  2456. });
  2457. });
  2458. return p;
  2459. };
  2460. HubConnection.prototype.on = function (methodName, newMethod) {
  2461. if (!methodName || !newMethod) {
  2462. return;
  2463. }
  2464. methodName = methodName.toLowerCase();
  2465. if (!this.methods[methodName]) {
  2466. this.methods[methodName] = [];
  2467. }
  2468. // Preventing adding the same handler multiple times.
  2469. if (this.methods[methodName].indexOf(newMethod) !== -1) {
  2470. return;
  2471. }
  2472. this.methods[methodName].push(newMethod);
  2473. };
  2474. HubConnection.prototype.off = function (methodName, method) {
  2475. if (!methodName) {
  2476. return;
  2477. }
  2478. methodName = methodName.toLowerCase();
  2479. var handlers = this.methods[methodName];
  2480. if (!handlers) {
  2481. return;
  2482. }
  2483. if (method) {
  2484. var removeIdx = handlers.indexOf(method);
  2485. if (removeIdx !== -1) {
  2486. handlers.splice(removeIdx, 1);
  2487. if (handlers.length === 0) {
  2488. delete this.methods[methodName];
  2489. }
  2490. }
  2491. }
  2492. else {
  2493. delete this.methods[methodName];
  2494. }
  2495. };
  2496. HubConnection.prototype.onclose = function (callback) {
  2497. if (callback) {
  2498. this.closedCallbacks.push(callback);
  2499. }
  2500. };
  2501. HubConnection.prototype.cleanupTimeout = function () {
  2502. if (this.timeoutHandle) {
  2503. clearTimeout(this.timeoutHandle);
  2504. }
  2505. };
  2506. HubConnection.prototype.createInvocation = function (methodName, args, nonblocking) {
  2507. if (nonblocking) {
  2508. return {
  2509. arguments: args,
  2510. target: methodName,
  2511. type: 1 /* Invocation */,
  2512. };
  2513. }
  2514. else {
  2515. var id = this.id;
  2516. this.id++;
  2517. return {
  2518. arguments: args,
  2519. invocationId: id.toString(),
  2520. target: methodName,
  2521. type: 1 /* Invocation */,
  2522. };
  2523. }
  2524. };
  2525. HubConnection.prototype.createStreamInvocation = function (methodName, args) {
  2526. var id = this.id;
  2527. this.id++;
  2528. return {
  2529. arguments: args,
  2530. invocationId: id.toString(),
  2531. target: methodName,
  2532. type: 4 /* StreamInvocation */,
  2533. };
  2534. };
  2535. HubConnection.prototype.createCancelInvocation = function (id) {
  2536. return {
  2537. invocationId: id,
  2538. type: 5 /* CancelInvocation */,
  2539. };
  2540. };
  2541. return HubConnection;
  2542. }());
  2543. exports.HubConnection = HubConnection;
  2544. });
  2545. unwrapExports(HubConnection_1);
  2546. var HubConnection_2 = HubConnection_1.JsonHubProtocol;
  2547. var HubConnection_3 = HubConnection_1.HubConnection;
  2548. var IHubProtocol = createCommonjsModule(function (module, exports) {
  2549. Object.defineProperty(exports, "__esModule", { value: true });
  2550. });
  2551. unwrapExports(IHubProtocol);
  2552. var cjs = createCommonjsModule(function (module, exports) {
  2553. function __export(m) {
  2554. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  2555. }
  2556. Object.defineProperty(exports, "__esModule", { value: true });
  2557. __export(Errors);
  2558. __export(HttpClient_1);
  2559. __export(HttpConnection_1);
  2560. __export(HubConnection_1);
  2561. __export(IHubProtocol);
  2562. __export(ILogger);
  2563. __export(Loggers);
  2564. __export(Transports);
  2565. __export(Observable);
  2566. });
  2567. unwrapExports(cjs);
  2568. var browserIndex = createCommonjsModule(function (module, exports) {
  2569. function __export(m) {
  2570. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  2571. }
  2572. Object.defineProperty(exports, "__esModule", { value: true });
  2573. // This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds.
  2574. __export(cjs);
  2575. });
  2576. var browserIndex$1 = unwrapExports(browserIndex);
  2577. return browserIndex$1;
  2578. })));