signalr.js 176 KB

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