@microsoft_signalr.js 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561
  1. import {
  2. __require
  3. } from "./chunk-HM4MQYWN.js";
  4. // node_modules/@microsoft/signalr/dist/esm/Errors.js
  5. var HttpError = class extends Error {
  6. /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.
  7. *
  8. * @param {string} errorMessage A descriptive error message.
  9. * @param {number} statusCode The HTTP status code represented by this error.
  10. */
  11. constructor(errorMessage, statusCode) {
  12. const trueProto = new.target.prototype;
  13. super(`${errorMessage}: Status code '${statusCode}'`);
  14. this.statusCode = statusCode;
  15. this.__proto__ = trueProto;
  16. }
  17. };
  18. var TimeoutError = class extends Error {
  19. /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.
  20. *
  21. * @param {string} errorMessage A descriptive error message.
  22. */
  23. constructor(errorMessage = "A timeout occurred.") {
  24. const trueProto = new.target.prototype;
  25. super(errorMessage);
  26. this.__proto__ = trueProto;
  27. }
  28. };
  29. var AbortError = class extends Error {
  30. /** Constructs a new instance of {@link AbortError}.
  31. *
  32. * @param {string} errorMessage A descriptive error message.
  33. */
  34. constructor(errorMessage = "An abort occurred.") {
  35. const trueProto = new.target.prototype;
  36. super(errorMessage);
  37. this.__proto__ = trueProto;
  38. }
  39. };
  40. var UnsupportedTransportError = class extends Error {
  41. /** Constructs a new instance of {@link @microsoft/signalr.UnsupportedTransportError}.
  42. *
  43. * @param {string} message A descriptive error message.
  44. * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.
  45. */
  46. constructor(message, transport) {
  47. const trueProto = new.target.prototype;
  48. super(message);
  49. this.transport = transport;
  50. this.errorType = "UnsupportedTransportError";
  51. this.__proto__ = trueProto;
  52. }
  53. };
  54. var DisabledTransportError = class extends Error {
  55. /** Constructs a new instance of {@link @microsoft/signalr.DisabledTransportError}.
  56. *
  57. * @param {string} message A descriptive error message.
  58. * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.
  59. */
  60. constructor(message, transport) {
  61. const trueProto = new.target.prototype;
  62. super(message);
  63. this.transport = transport;
  64. this.errorType = "DisabledTransportError";
  65. this.__proto__ = trueProto;
  66. }
  67. };
  68. var FailedToStartTransportError = class extends Error {
  69. /** Constructs a new instance of {@link @microsoft/signalr.FailedToStartTransportError}.
  70. *
  71. * @param {string} message A descriptive error message.
  72. * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occurred on.
  73. */
  74. constructor(message, transport) {
  75. const trueProto = new.target.prototype;
  76. super(message);
  77. this.transport = transport;
  78. this.errorType = "FailedToStartTransportError";
  79. this.__proto__ = trueProto;
  80. }
  81. };
  82. var FailedToNegotiateWithServerError = class extends Error {
  83. /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}.
  84. *
  85. * @param {string} message A descriptive error message.
  86. */
  87. constructor(message) {
  88. const trueProto = new.target.prototype;
  89. super(message);
  90. this.errorType = "FailedToNegotiateWithServerError";
  91. this.__proto__ = trueProto;
  92. }
  93. };
  94. var AggregateErrors = class extends Error {
  95. /** Constructs a new instance of {@link @microsoft/signalr.AggregateErrors}.
  96. *
  97. * @param {string} message A descriptive error message.
  98. * @param {Error[]} innerErrors The collection of errors this error is aggregating.
  99. */
  100. constructor(message, innerErrors) {
  101. const trueProto = new.target.prototype;
  102. super(message);
  103. this.innerErrors = innerErrors;
  104. this.__proto__ = trueProto;
  105. }
  106. };
  107. // node_modules/@microsoft/signalr/dist/esm/HttpClient.js
  108. var HttpResponse = class {
  109. constructor(statusCode, statusText, content) {
  110. this.statusCode = statusCode;
  111. this.statusText = statusText;
  112. this.content = content;
  113. }
  114. };
  115. var HttpClient = class {
  116. get(url, options) {
  117. return this.send({
  118. ...options,
  119. method: "GET",
  120. url
  121. });
  122. }
  123. post(url, options) {
  124. return this.send({
  125. ...options,
  126. method: "POST",
  127. url
  128. });
  129. }
  130. delete(url, options) {
  131. return this.send({
  132. ...options,
  133. method: "DELETE",
  134. url
  135. });
  136. }
  137. /** Gets all cookies that apply to the specified URL.
  138. *
  139. * @param url The URL that the cookies are valid for.
  140. * @returns {string} A string containing all the key-value cookie pairs for the specified URL.
  141. */
  142. // @ts-ignore
  143. getCookieString(url) {
  144. return "";
  145. }
  146. };
  147. // node_modules/@microsoft/signalr/dist/esm/ILogger.js
  148. var LogLevel;
  149. (function(LogLevel2) {
  150. LogLevel2[LogLevel2["Trace"] = 0] = "Trace";
  151. LogLevel2[LogLevel2["Debug"] = 1] = "Debug";
  152. LogLevel2[LogLevel2["Information"] = 2] = "Information";
  153. LogLevel2[LogLevel2["Warning"] = 3] = "Warning";
  154. LogLevel2[LogLevel2["Error"] = 4] = "Error";
  155. LogLevel2[LogLevel2["Critical"] = 5] = "Critical";
  156. LogLevel2[LogLevel2["None"] = 6] = "None";
  157. })(LogLevel || (LogLevel = {}));
  158. // node_modules/@microsoft/signalr/dist/esm/Loggers.js
  159. var NullLogger = class {
  160. constructor() {
  161. }
  162. /** @inheritDoc */
  163. // eslint-disable-next-line
  164. log(_logLevel, _message) {
  165. }
  166. };
  167. NullLogger.instance = new NullLogger();
  168. // node_modules/@microsoft/signalr/dist/esm/Utils.js
  169. var VERSION = "7.0.14";
  170. var Arg = class {
  171. static isRequired(val, name) {
  172. if (val === null || val === void 0) {
  173. throw new Error(`The '${name}' argument is required.`);
  174. }
  175. }
  176. static isNotEmpty(val, name) {
  177. if (!val || val.match(/^\s*$/)) {
  178. throw new Error(`The '${name}' argument should not be empty.`);
  179. }
  180. }
  181. static isIn(val, values, name) {
  182. if (!(val in values)) {
  183. throw new Error(`Unknown ${name} value: ${val}.`);
  184. }
  185. }
  186. };
  187. var Platform = class {
  188. // react-native has a window but no document so we should check both
  189. static get isBrowser() {
  190. return typeof window === "object" && typeof window.document === "object";
  191. }
  192. // WebWorkers don't have a window object so the isBrowser check would fail
  193. static get isWebWorker() {
  194. return typeof self === "object" && "importScripts" in self;
  195. }
  196. // react-native has a window but no document
  197. static get isReactNative() {
  198. return typeof window === "object" && typeof window.document === "undefined";
  199. }
  200. // Node apps shouldn't have a window object, but WebWorkers don't either
  201. // so we need to check for both WebWorker and window
  202. static get isNode() {
  203. return !this.isBrowser && !this.isWebWorker && !this.isReactNative;
  204. }
  205. };
  206. function getDataDetail(data, includeContent) {
  207. let detail = "";
  208. if (isArrayBuffer(data)) {
  209. detail = `Binary data of length ${data.byteLength}`;
  210. if (includeContent) {
  211. detail += `. Content: '${formatArrayBuffer(data)}'`;
  212. }
  213. } else if (typeof data === "string") {
  214. detail = `String data of length ${data.length}`;
  215. if (includeContent) {
  216. detail += `. Content: '${data}'`;
  217. }
  218. }
  219. return detail;
  220. }
  221. function formatArrayBuffer(data) {
  222. const view = new Uint8Array(data);
  223. let str = "";
  224. view.forEach((num) => {
  225. const pad = num < 16 ? "0" : "";
  226. str += `0x${pad}${num.toString(16)} `;
  227. });
  228. return str.substr(0, str.length - 1);
  229. }
  230. function isArrayBuffer(val) {
  231. return val && typeof ArrayBuffer !== "undefined" && (val instanceof ArrayBuffer || // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
  232. val.constructor && val.constructor.name === "ArrayBuffer");
  233. }
  234. async function sendMessage(logger, transportName, httpClient, url, content, options) {
  235. const headers = {};
  236. const [name, value] = getUserAgentHeader();
  237. headers[name] = value;
  238. logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent)}.`);
  239. const responseType = isArrayBuffer(content) ? "arraybuffer" : "text";
  240. const response = await httpClient.post(url, {
  241. content,
  242. headers: { ...headers, ...options.headers },
  243. responseType,
  244. timeout: options.timeout,
  245. withCredentials: options.withCredentials
  246. });
  247. logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);
  248. }
  249. function createLogger(logger) {
  250. if (logger === void 0) {
  251. return new ConsoleLogger(LogLevel.Information);
  252. }
  253. if (logger === null) {
  254. return NullLogger.instance;
  255. }
  256. if (logger.log !== void 0) {
  257. return logger;
  258. }
  259. return new ConsoleLogger(logger);
  260. }
  261. var SubjectSubscription = class {
  262. constructor(subject, observer) {
  263. this._subject = subject;
  264. this._observer = observer;
  265. }
  266. dispose() {
  267. const index = this._subject.observers.indexOf(this._observer);
  268. if (index > -1) {
  269. this._subject.observers.splice(index, 1);
  270. }
  271. if (this._subject.observers.length === 0 && this._subject.cancelCallback) {
  272. this._subject.cancelCallback().catch((_) => {
  273. });
  274. }
  275. }
  276. };
  277. var ConsoleLogger = class {
  278. constructor(minimumLogLevel) {
  279. this._minLevel = minimumLogLevel;
  280. this.out = console;
  281. }
  282. log(logLevel, message) {
  283. if (logLevel >= this._minLevel) {
  284. const msg = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${LogLevel[logLevel]}: ${message}`;
  285. switch (logLevel) {
  286. case LogLevel.Critical:
  287. case LogLevel.Error:
  288. this.out.error(msg);
  289. break;
  290. case LogLevel.Warning:
  291. this.out.warn(msg);
  292. break;
  293. case LogLevel.Information:
  294. this.out.info(msg);
  295. break;
  296. default:
  297. this.out.log(msg);
  298. break;
  299. }
  300. }
  301. }
  302. };
  303. function getUserAgentHeader() {
  304. let userAgentHeaderName = "X-SignalR-User-Agent";
  305. if (Platform.isNode) {
  306. userAgentHeaderName = "User-Agent";
  307. }
  308. return [userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion())];
  309. }
  310. function constructUserAgent(version, os, runtime, runtimeVersion) {
  311. let userAgent = "Microsoft SignalR/";
  312. const majorAndMinor = version.split(".");
  313. userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;
  314. userAgent += ` (${version}; `;
  315. if (os && os !== "") {
  316. userAgent += `${os}; `;
  317. } else {
  318. userAgent += "Unknown OS; ";
  319. }
  320. userAgent += `${runtime}`;
  321. if (runtimeVersion) {
  322. userAgent += `; ${runtimeVersion}`;
  323. } else {
  324. userAgent += "; Unknown Runtime Version";
  325. }
  326. userAgent += ")";
  327. return userAgent;
  328. }
  329. function getOsName() {
  330. if (Platform.isNode) {
  331. switch (process.platform) {
  332. case "win32":
  333. return "Windows NT";
  334. case "darwin":
  335. return "macOS";
  336. case "linux":
  337. return "Linux";
  338. default:
  339. return process.platform;
  340. }
  341. } else {
  342. return "";
  343. }
  344. }
  345. function getRuntimeVersion() {
  346. if (Platform.isNode) {
  347. return process.versions.node;
  348. }
  349. return void 0;
  350. }
  351. function getRuntime() {
  352. if (Platform.isNode) {
  353. return "NodeJS";
  354. } else {
  355. return "Browser";
  356. }
  357. }
  358. function getErrorString(e) {
  359. if (e.stack) {
  360. return e.stack;
  361. } else if (e.message) {
  362. return e.message;
  363. }
  364. return `${e}`;
  365. }
  366. function getGlobalThis() {
  367. if (typeof globalThis !== "undefined") {
  368. return globalThis;
  369. }
  370. if (typeof self !== "undefined") {
  371. return self;
  372. }
  373. if (typeof window !== "undefined") {
  374. return window;
  375. }
  376. if (typeof global !== "undefined") {
  377. return global;
  378. }
  379. throw new Error("could not find global");
  380. }
  381. // node_modules/@microsoft/signalr/dist/esm/FetchHttpClient.js
  382. var FetchHttpClient = class extends HttpClient {
  383. constructor(logger) {
  384. super();
  385. this._logger = logger;
  386. if (typeof fetch === "undefined") {
  387. const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
  388. this._jar = new (requireFunc("tough-cookie")).CookieJar();
  389. this._fetchType = requireFunc("node-fetch");
  390. this._fetchType = requireFunc("fetch-cookie")(this._fetchType, this._jar);
  391. } else {
  392. this._fetchType = fetch.bind(getGlobalThis());
  393. }
  394. if (typeof AbortController === "undefined") {
  395. const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
  396. this._abortControllerType = requireFunc("abort-controller");
  397. } else {
  398. this._abortControllerType = AbortController;
  399. }
  400. }
  401. /** @inheritDoc */
  402. async send(request) {
  403. if (request.abortSignal && request.abortSignal.aborted) {
  404. throw new AbortError();
  405. }
  406. if (!request.method) {
  407. throw new Error("No method defined.");
  408. }
  409. if (!request.url) {
  410. throw new Error("No url defined.");
  411. }
  412. const abortController = new this._abortControllerType();
  413. let error;
  414. if (request.abortSignal) {
  415. request.abortSignal.onabort = () => {
  416. abortController.abort();
  417. error = new AbortError();
  418. };
  419. }
  420. let timeoutId = null;
  421. if (request.timeout) {
  422. const msTimeout = request.timeout;
  423. timeoutId = setTimeout(() => {
  424. abortController.abort();
  425. this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);
  426. error = new TimeoutError();
  427. }, msTimeout);
  428. }
  429. if (request.content === "") {
  430. request.content = void 0;
  431. }
  432. if (request.content) {
  433. request.headers = request.headers || {};
  434. if (isArrayBuffer(request.content)) {
  435. request.headers["Content-Type"] = "application/octet-stream";
  436. } else {
  437. request.headers["Content-Type"] = "text/plain;charset=UTF-8";
  438. }
  439. }
  440. let response;
  441. try {
  442. response = await this._fetchType(request.url, {
  443. body: request.content,
  444. cache: "no-cache",
  445. credentials: request.withCredentials === true ? "include" : "same-origin",
  446. headers: {
  447. "X-Requested-With": "XMLHttpRequest",
  448. ...request.headers
  449. },
  450. method: request.method,
  451. mode: "cors",
  452. redirect: "follow",
  453. signal: abortController.signal
  454. });
  455. } catch (e) {
  456. if (error) {
  457. throw error;
  458. }
  459. this._logger.log(LogLevel.Warning, `Error from HTTP request. ${e}.`);
  460. throw e;
  461. } finally {
  462. if (timeoutId) {
  463. clearTimeout(timeoutId);
  464. }
  465. if (request.abortSignal) {
  466. request.abortSignal.onabort = null;
  467. }
  468. }
  469. if (!response.ok) {
  470. const errorMessage = await deserializeContent(response, "text");
  471. throw new HttpError(errorMessage || response.statusText, response.status);
  472. }
  473. const content = deserializeContent(response, request.responseType);
  474. const payload = await content;
  475. return new HttpResponse(response.status, response.statusText, payload);
  476. }
  477. getCookieString(url) {
  478. let cookies = "";
  479. if (Platform.isNode && this._jar) {
  480. this._jar.getCookies(url, (e, c) => cookies = c.join("; "));
  481. }
  482. return cookies;
  483. }
  484. };
  485. function deserializeContent(response, responseType) {
  486. let content;
  487. switch (responseType) {
  488. case "arraybuffer":
  489. content = response.arrayBuffer();
  490. break;
  491. case "text":
  492. content = response.text();
  493. break;
  494. case "blob":
  495. case "document":
  496. case "json":
  497. throw new Error(`${responseType} is not supported.`);
  498. default:
  499. content = response.text();
  500. break;
  501. }
  502. return content;
  503. }
  504. // node_modules/@microsoft/signalr/dist/esm/XhrHttpClient.js
  505. var XhrHttpClient = class extends HttpClient {
  506. constructor(logger) {
  507. super();
  508. this._logger = logger;
  509. }
  510. /** @inheritDoc */
  511. send(request) {
  512. if (request.abortSignal && request.abortSignal.aborted) {
  513. return Promise.reject(new AbortError());
  514. }
  515. if (!request.method) {
  516. return Promise.reject(new Error("No method defined."));
  517. }
  518. if (!request.url) {
  519. return Promise.reject(new Error("No url defined."));
  520. }
  521. return new Promise((resolve, reject) => {
  522. const xhr = new XMLHttpRequest();
  523. xhr.open(request.method, request.url, true);
  524. xhr.withCredentials = request.withCredentials === void 0 ? true : request.withCredentials;
  525. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  526. if (request.content === "") {
  527. request.content = void 0;
  528. }
  529. if (request.content) {
  530. if (isArrayBuffer(request.content)) {
  531. xhr.setRequestHeader("Content-Type", "application/octet-stream");
  532. } else {
  533. xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  534. }
  535. }
  536. const headers = request.headers;
  537. if (headers) {
  538. Object.keys(headers).forEach((header) => {
  539. xhr.setRequestHeader(header, headers[header]);
  540. });
  541. }
  542. if (request.responseType) {
  543. xhr.responseType = request.responseType;
  544. }
  545. if (request.abortSignal) {
  546. request.abortSignal.onabort = () => {
  547. xhr.abort();
  548. reject(new AbortError());
  549. };
  550. }
  551. if (request.timeout) {
  552. xhr.timeout = request.timeout;
  553. }
  554. xhr.onload = () => {
  555. if (request.abortSignal) {
  556. request.abortSignal.onabort = null;
  557. }
  558. if (xhr.status >= 200 && xhr.status < 300) {
  559. resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));
  560. } else {
  561. reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status));
  562. }
  563. };
  564. xhr.onerror = () => {
  565. this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);
  566. reject(new HttpError(xhr.statusText, xhr.status));
  567. };
  568. xhr.ontimeout = () => {
  569. this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);
  570. reject(new TimeoutError());
  571. };
  572. xhr.send(request.content);
  573. });
  574. }
  575. };
  576. // node_modules/@microsoft/signalr/dist/esm/DefaultHttpClient.js
  577. var DefaultHttpClient = class extends HttpClient {
  578. /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
  579. constructor(logger) {
  580. super();
  581. if (typeof fetch !== "undefined" || Platform.isNode) {
  582. this._httpClient = new FetchHttpClient(logger);
  583. } else if (typeof XMLHttpRequest !== "undefined") {
  584. this._httpClient = new XhrHttpClient(logger);
  585. } else {
  586. throw new Error("No usable HttpClient found.");
  587. }
  588. }
  589. /** @inheritDoc */
  590. send(request) {
  591. if (request.abortSignal && request.abortSignal.aborted) {
  592. return Promise.reject(new AbortError());
  593. }
  594. if (!request.method) {
  595. return Promise.reject(new Error("No method defined."));
  596. }
  597. if (!request.url) {
  598. return Promise.reject(new Error("No url defined."));
  599. }
  600. return this._httpClient.send(request);
  601. }
  602. getCookieString(url) {
  603. return this._httpClient.getCookieString(url);
  604. }
  605. };
  606. // node_modules/@microsoft/signalr/dist/esm/TextMessageFormat.js
  607. var TextMessageFormat = class _TextMessageFormat {
  608. static write(output) {
  609. return `${output}${_TextMessageFormat.RecordSeparator}`;
  610. }
  611. static parse(input) {
  612. if (input[input.length - 1] !== _TextMessageFormat.RecordSeparator) {
  613. throw new Error("Message is incomplete.");
  614. }
  615. const messages = input.split(_TextMessageFormat.RecordSeparator);
  616. messages.pop();
  617. return messages;
  618. }
  619. };
  620. TextMessageFormat.RecordSeparatorCode = 30;
  621. TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);
  622. // node_modules/@microsoft/signalr/dist/esm/HandshakeProtocol.js
  623. var HandshakeProtocol = class {
  624. // Handshake request is always JSON
  625. writeHandshakeRequest(handshakeRequest) {
  626. return TextMessageFormat.write(JSON.stringify(handshakeRequest));
  627. }
  628. parseHandshakeResponse(data) {
  629. let messageData;
  630. let remainingData;
  631. if (isArrayBuffer(data)) {
  632. const binaryData = new Uint8Array(data);
  633. const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);
  634. if (separatorIndex === -1) {
  635. throw new Error("Message is incomplete.");
  636. }
  637. const responseLength = separatorIndex + 1;
  638. messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));
  639. remainingData = binaryData.byteLength > responseLength ? binaryData.slice(responseLength).buffer : null;
  640. } else {
  641. const textData = data;
  642. const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);
  643. if (separatorIndex === -1) {
  644. throw new Error("Message is incomplete.");
  645. }
  646. const responseLength = separatorIndex + 1;
  647. messageData = textData.substring(0, responseLength);
  648. remainingData = textData.length > responseLength ? textData.substring(responseLength) : null;
  649. }
  650. const messages = TextMessageFormat.parse(messageData);
  651. const response = JSON.parse(messages[0]);
  652. if (response.type) {
  653. throw new Error("Expected a handshake response from the server.");
  654. }
  655. const responseMessage = response;
  656. return [remainingData, responseMessage];
  657. }
  658. };
  659. // node_modules/@microsoft/signalr/dist/esm/IHubProtocol.js
  660. var MessageType;
  661. (function(MessageType2) {
  662. MessageType2[MessageType2["Invocation"] = 1] = "Invocation";
  663. MessageType2[MessageType2["StreamItem"] = 2] = "StreamItem";
  664. MessageType2[MessageType2["Completion"] = 3] = "Completion";
  665. MessageType2[MessageType2["StreamInvocation"] = 4] = "StreamInvocation";
  666. MessageType2[MessageType2["CancelInvocation"] = 5] = "CancelInvocation";
  667. MessageType2[MessageType2["Ping"] = 6] = "Ping";
  668. MessageType2[MessageType2["Close"] = 7] = "Close";
  669. })(MessageType || (MessageType = {}));
  670. // node_modules/@microsoft/signalr/dist/esm/Subject.js
  671. var Subject = class {
  672. constructor() {
  673. this.observers = [];
  674. }
  675. next(item) {
  676. for (const observer of this.observers) {
  677. observer.next(item);
  678. }
  679. }
  680. error(err) {
  681. for (const observer of this.observers) {
  682. if (observer.error) {
  683. observer.error(err);
  684. }
  685. }
  686. }
  687. complete() {
  688. for (const observer of this.observers) {
  689. if (observer.complete) {
  690. observer.complete();
  691. }
  692. }
  693. }
  694. subscribe(observer) {
  695. this.observers.push(observer);
  696. return new SubjectSubscription(this, observer);
  697. }
  698. };
  699. // node_modules/@microsoft/signalr/dist/esm/HubConnection.js
  700. var DEFAULT_TIMEOUT_IN_MS = 30 * 1e3;
  701. var DEFAULT_PING_INTERVAL_IN_MS = 15 * 1e3;
  702. var HubConnectionState;
  703. (function(HubConnectionState2) {
  704. HubConnectionState2["Disconnected"] = "Disconnected";
  705. HubConnectionState2["Connecting"] = "Connecting";
  706. HubConnectionState2["Connected"] = "Connected";
  707. HubConnectionState2["Disconnecting"] = "Disconnecting";
  708. HubConnectionState2["Reconnecting"] = "Reconnecting";
  709. })(HubConnectionState || (HubConnectionState = {}));
  710. var HubConnection = class _HubConnection {
  711. constructor(connection, logger, protocol, reconnectPolicy) {
  712. this._nextKeepAlive = 0;
  713. this._freezeEventListener = () => {
  714. this._logger.log(LogLevel.Warning, "The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://docs.microsoft.com/aspnet/core/signalr/javascript-client#bsleep");
  715. };
  716. Arg.isRequired(connection, "connection");
  717. Arg.isRequired(logger, "logger");
  718. Arg.isRequired(protocol, "protocol");
  719. this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;
  720. this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;
  721. this._logger = logger;
  722. this._protocol = protocol;
  723. this.connection = connection;
  724. this._reconnectPolicy = reconnectPolicy;
  725. this._handshakeProtocol = new HandshakeProtocol();
  726. this.connection.onreceive = (data) => this._processIncomingData(data);
  727. this.connection.onclose = (error) => this._connectionClosed(error);
  728. this._callbacks = {};
  729. this._methods = {};
  730. this._closedCallbacks = [];
  731. this._reconnectingCallbacks = [];
  732. this._reconnectedCallbacks = [];
  733. this._invocationId = 0;
  734. this._receivedHandshakeResponse = false;
  735. this._connectionState = HubConnectionState.Disconnected;
  736. this._connectionStarted = false;
  737. this._cachedPingMessage = this._protocol.writeMessage({ type: MessageType.Ping });
  738. }
  739. /** @internal */
  740. // Using a public static factory method means we can have a private constructor and an _internal_
  741. // create method that can be used by HubConnectionBuilder. An "internal" constructor would just
  742. // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
  743. // public parameter-less constructor.
  744. static create(connection, logger, protocol, reconnectPolicy) {
  745. return new _HubConnection(connection, logger, protocol, reconnectPolicy);
  746. }
  747. /** Indicates the state of the {@link HubConnection} to the server. */
  748. get state() {
  749. return this._connectionState;
  750. }
  751. /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
  752. * in the disconnected state or if the negotiation step was skipped.
  753. */
  754. get connectionId() {
  755. return this.connection ? this.connection.connectionId || null : null;
  756. }
  757. /** Indicates the url of the {@link HubConnection} to the server. */
  758. get baseUrl() {
  759. return this.connection.baseUrl || "";
  760. }
  761. /**
  762. * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
  763. * Reconnecting states.
  764. * @param {string} url The url to connect to.
  765. */
  766. set baseUrl(url) {
  767. if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) {
  768. throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
  769. }
  770. if (!url) {
  771. throw new Error("The HubConnection url must be a valid url.");
  772. }
  773. this.connection.baseUrl = url;
  774. }
  775. /** Starts the connection.
  776. *
  777. * @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
  778. */
  779. start() {
  780. this._startPromise = this._startWithStateTransitions();
  781. return this._startPromise;
  782. }
  783. async _startWithStateTransitions() {
  784. if (this._connectionState !== HubConnectionState.Disconnected) {
  785. return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));
  786. }
  787. this._connectionState = HubConnectionState.Connecting;
  788. this._logger.log(LogLevel.Debug, "Starting HubConnection.");
  789. try {
  790. await this._startInternal();
  791. if (Platform.isBrowser) {
  792. window.document.addEventListener("freeze", this._freezeEventListener);
  793. }
  794. this._connectionState = HubConnectionState.Connected;
  795. this._connectionStarted = true;
  796. this._logger.log(LogLevel.Debug, "HubConnection connected successfully.");
  797. } catch (e) {
  798. this._connectionState = HubConnectionState.Disconnected;
  799. this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);
  800. return Promise.reject(e);
  801. }
  802. }
  803. async _startInternal() {
  804. this._stopDuringStartError = void 0;
  805. this._receivedHandshakeResponse = false;
  806. const handshakePromise = new Promise((resolve, reject) => {
  807. this._handshakeResolver = resolve;
  808. this._handshakeRejecter = reject;
  809. });
  810. await this.connection.start(this._protocol.transferFormat);
  811. try {
  812. const handshakeRequest = {
  813. protocol: this._protocol.name,
  814. version: this._protocol.version
  815. };
  816. this._logger.log(LogLevel.Debug, "Sending handshake request.");
  817. await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));
  818. this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);
  819. this._cleanupTimeout();
  820. this._resetTimeoutPeriod();
  821. this._resetKeepAliveInterval();
  822. await handshakePromise;
  823. if (this._stopDuringStartError) {
  824. throw this._stopDuringStartError;
  825. }
  826. if (!this.connection.features.inherentKeepAlive) {
  827. await this._sendMessage(this._cachedPingMessage);
  828. }
  829. } catch (e) {
  830. this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);
  831. this._cleanupTimeout();
  832. this._cleanupPingTimer();
  833. await this.connection.stop(e);
  834. throw e;
  835. }
  836. }
  837. /** Stops the connection.
  838. *
  839. * @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
  840. */
  841. async stop() {
  842. const startPromise = this._startPromise;
  843. this._stopPromise = this._stopInternal();
  844. await this._stopPromise;
  845. try {
  846. await startPromise;
  847. } catch (e) {
  848. }
  849. }
  850. _stopInternal(error) {
  851. if (this._connectionState === HubConnectionState.Disconnected) {
  852. this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);
  853. return Promise.resolve();
  854. }
  855. if (this._connectionState === HubConnectionState.Disconnecting) {
  856. this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
  857. return this._stopPromise;
  858. }
  859. this._connectionState = HubConnectionState.Disconnecting;
  860. this._logger.log(LogLevel.Debug, "Stopping HubConnection.");
  861. if (this._reconnectDelayHandle) {
  862. this._logger.log(LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
  863. clearTimeout(this._reconnectDelayHandle);
  864. this._reconnectDelayHandle = void 0;
  865. this._completeClose();
  866. return Promise.resolve();
  867. }
  868. this._cleanupTimeout();
  869. this._cleanupPingTimer();
  870. this._stopDuringStartError = error || new AbortError("The connection was stopped before the hub handshake could complete.");
  871. return this.connection.stop(error);
  872. }
  873. /** Invokes a streaming hub method on the server using the specified name and arguments.
  874. *
  875. * @typeparam T The type of the items returned by the server.
  876. * @param {string} methodName The name of the server method to invoke.
  877. * @param {any[]} args The arguments used to invoke the server method.
  878. * @returns {IStreamResult<T>} An object that yields results from the server as they are received.
  879. */
  880. stream(methodName, ...args) {
  881. const [streams, streamIds] = this._replaceStreamingParams(args);
  882. const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);
  883. let promiseQueue;
  884. const subject = new Subject();
  885. subject.cancelCallback = () => {
  886. const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);
  887. delete this._callbacks[invocationDescriptor.invocationId];
  888. return promiseQueue.then(() => {
  889. return this._sendWithProtocol(cancelInvocation);
  890. });
  891. };
  892. this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
  893. if (error) {
  894. subject.error(error);
  895. return;
  896. } else if (invocationEvent) {
  897. if (invocationEvent.type === MessageType.Completion) {
  898. if (invocationEvent.error) {
  899. subject.error(new Error(invocationEvent.error));
  900. } else {
  901. subject.complete();
  902. }
  903. } else {
  904. subject.next(invocationEvent.item);
  905. }
  906. }
  907. };
  908. promiseQueue = this._sendWithProtocol(invocationDescriptor).catch((e) => {
  909. subject.error(e);
  910. delete this._callbacks[invocationDescriptor.invocationId];
  911. });
  912. this._launchStreams(streams, promiseQueue);
  913. return subject;
  914. }
  915. _sendMessage(message) {
  916. this._resetKeepAliveInterval();
  917. return this.connection.send(message);
  918. }
  919. /**
  920. * Sends a js object to the server.
  921. * @param message The js object to serialize and send.
  922. */
  923. _sendWithProtocol(message) {
  924. return this._sendMessage(this._protocol.writeMessage(message));
  925. }
  926. /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
  927. *
  928. * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
  929. * be processing the invocation.
  930. *
  931. * @param {string} methodName The name of the server method to invoke.
  932. * @param {any[]} args The arguments used to invoke the server method.
  933. * @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
  934. */
  935. send(methodName, ...args) {
  936. const [streams, streamIds] = this._replaceStreamingParams(args);
  937. const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));
  938. this._launchStreams(streams, sendPromise);
  939. return sendPromise;
  940. }
  941. /** Invokes a hub method on the server using the specified name and arguments.
  942. *
  943. * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
  944. * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
  945. * resolving the Promise.
  946. *
  947. * @typeparam T The expected return type.
  948. * @param {string} methodName The name of the server method to invoke.
  949. * @param {any[]} args The arguments used to invoke the server method.
  950. * @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
  951. */
  952. invoke(methodName, ...args) {
  953. const [streams, streamIds] = this._replaceStreamingParams(args);
  954. const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);
  955. const p = new Promise((resolve, reject) => {
  956. this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
  957. if (error) {
  958. reject(error);
  959. return;
  960. } else if (invocationEvent) {
  961. if (invocationEvent.type === MessageType.Completion) {
  962. if (invocationEvent.error) {
  963. reject(new Error(invocationEvent.error));
  964. } else {
  965. resolve(invocationEvent.result);
  966. }
  967. } else {
  968. reject(new Error(`Unexpected message type: ${invocationEvent.type}`));
  969. }
  970. }
  971. };
  972. const promiseQueue = this._sendWithProtocol(invocationDescriptor).catch((e) => {
  973. reject(e);
  974. delete this._callbacks[invocationDescriptor.invocationId];
  975. });
  976. this._launchStreams(streams, promiseQueue);
  977. });
  978. return p;
  979. }
  980. on(methodName, newMethod) {
  981. if (!methodName || !newMethod) {
  982. return;
  983. }
  984. methodName = methodName.toLowerCase();
  985. if (!this._methods[methodName]) {
  986. this._methods[methodName] = [];
  987. }
  988. if (this._methods[methodName].indexOf(newMethod) !== -1) {
  989. return;
  990. }
  991. this._methods[methodName].push(newMethod);
  992. }
  993. off(methodName, method) {
  994. if (!methodName) {
  995. return;
  996. }
  997. methodName = methodName.toLowerCase();
  998. const handlers = this._methods[methodName];
  999. if (!handlers) {
  1000. return;
  1001. }
  1002. if (method) {
  1003. const removeIdx = handlers.indexOf(method);
  1004. if (removeIdx !== -1) {
  1005. handlers.splice(removeIdx, 1);
  1006. if (handlers.length === 0) {
  1007. delete this._methods[methodName];
  1008. }
  1009. }
  1010. } else {
  1011. delete this._methods[methodName];
  1012. }
  1013. }
  1014. /** Registers a handler that will be invoked when the connection is closed.
  1015. *
  1016. * @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).
  1017. */
  1018. onclose(callback) {
  1019. if (callback) {
  1020. this._closedCallbacks.push(callback);
  1021. }
  1022. }
  1023. /** Registers a handler that will be invoked when the connection starts reconnecting.
  1024. *
  1025. * @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).
  1026. */
  1027. onreconnecting(callback) {
  1028. if (callback) {
  1029. this._reconnectingCallbacks.push(callback);
  1030. }
  1031. }
  1032. /** Registers a handler that will be invoked when the connection successfully reconnects.
  1033. *
  1034. * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
  1035. */
  1036. onreconnected(callback) {
  1037. if (callback) {
  1038. this._reconnectedCallbacks.push(callback);
  1039. }
  1040. }
  1041. _processIncomingData(data) {
  1042. this._cleanupTimeout();
  1043. if (!this._receivedHandshakeResponse) {
  1044. data = this._processHandshakeResponse(data);
  1045. this._receivedHandshakeResponse = true;
  1046. }
  1047. if (data) {
  1048. const messages = this._protocol.parseMessages(data, this._logger);
  1049. for (const message of messages) {
  1050. switch (message.type) {
  1051. case MessageType.Invocation:
  1052. this._invokeClientMethod(message);
  1053. break;
  1054. case MessageType.StreamItem:
  1055. case MessageType.Completion: {
  1056. const callback = this._callbacks[message.invocationId];
  1057. if (callback) {
  1058. if (message.type === MessageType.Completion) {
  1059. delete this._callbacks[message.invocationId];
  1060. }
  1061. try {
  1062. callback(message);
  1063. } catch (e) {
  1064. this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`);
  1065. }
  1066. }
  1067. break;
  1068. }
  1069. case MessageType.Ping:
  1070. break;
  1071. case MessageType.Close: {
  1072. this._logger.log(LogLevel.Information, "Close message received from server.");
  1073. const error = message.error ? new Error("Server returned an error on close: " + message.error) : void 0;
  1074. if (message.allowReconnect === true) {
  1075. this.connection.stop(error);
  1076. } else {
  1077. this._stopPromise = this._stopInternal(error);
  1078. }
  1079. break;
  1080. }
  1081. default:
  1082. this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);
  1083. break;
  1084. }
  1085. }
  1086. }
  1087. this._resetTimeoutPeriod();
  1088. }
  1089. _processHandshakeResponse(data) {
  1090. let responseMessage;
  1091. let remainingData;
  1092. try {
  1093. [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);
  1094. } catch (e) {
  1095. const message = "Error parsing handshake response: " + e;
  1096. this._logger.log(LogLevel.Error, message);
  1097. const error = new Error(message);
  1098. this._handshakeRejecter(error);
  1099. throw error;
  1100. }
  1101. if (responseMessage.error) {
  1102. const message = "Server returned handshake error: " + responseMessage.error;
  1103. this._logger.log(LogLevel.Error, message);
  1104. const error = new Error(message);
  1105. this._handshakeRejecter(error);
  1106. throw error;
  1107. } else {
  1108. this._logger.log(LogLevel.Debug, "Server handshake complete.");
  1109. }
  1110. this._handshakeResolver();
  1111. return remainingData;
  1112. }
  1113. _resetKeepAliveInterval() {
  1114. if (this.connection.features.inherentKeepAlive) {
  1115. return;
  1116. }
  1117. this._nextKeepAlive = (/* @__PURE__ */ new Date()).getTime() + this.keepAliveIntervalInMilliseconds;
  1118. this._cleanupPingTimer();
  1119. }
  1120. _resetTimeoutPeriod() {
  1121. if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
  1122. this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);
  1123. if (this._pingServerHandle === void 0) {
  1124. let nextPing = this._nextKeepAlive - (/* @__PURE__ */ new Date()).getTime();
  1125. if (nextPing < 0) {
  1126. nextPing = 0;
  1127. }
  1128. this._pingServerHandle = setTimeout(async () => {
  1129. if (this._connectionState === HubConnectionState.Connected) {
  1130. try {
  1131. await this._sendMessage(this._cachedPingMessage);
  1132. } catch {
  1133. this._cleanupPingTimer();
  1134. }
  1135. }
  1136. }, nextPing);
  1137. }
  1138. }
  1139. }
  1140. // eslint-disable-next-line @typescript-eslint/naming-convention
  1141. serverTimeout() {
  1142. this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
  1143. }
  1144. async _invokeClientMethod(invocationMessage) {
  1145. const methodName = invocationMessage.target.toLowerCase();
  1146. const methods = this._methods[methodName];
  1147. if (!methods) {
  1148. this._logger.log(LogLevel.Warning, `No client method with the name '${methodName}' found.`);
  1149. if (invocationMessage.invocationId) {
  1150. this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);
  1151. await this._sendWithProtocol(this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null));
  1152. }
  1153. return;
  1154. }
  1155. const methodsCopy = methods.slice();
  1156. const expectsResponse = invocationMessage.invocationId ? true : false;
  1157. let res;
  1158. let exception;
  1159. let completionMessage;
  1160. for (const m of methodsCopy) {
  1161. try {
  1162. const prevRes = res;
  1163. res = await m.apply(this, invocationMessage.arguments);
  1164. if (expectsResponse && res && prevRes) {
  1165. this._logger.log(LogLevel.Error, `Multiple results provided for '${methodName}'. Sending error to server.`);
  1166. completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `Client provided multiple results.`, null);
  1167. }
  1168. exception = void 0;
  1169. } catch (e) {
  1170. exception = e;
  1171. this._logger.log(LogLevel.Error, `A callback for the method '${methodName}' threw error '${e}'.`);
  1172. }
  1173. }
  1174. if (completionMessage) {
  1175. await this._sendWithProtocol(completionMessage);
  1176. } else if (expectsResponse) {
  1177. if (exception) {
  1178. completionMessage = this._createCompletionMessage(invocationMessage.invocationId, `${exception}`, null);
  1179. } else if (res !== void 0) {
  1180. completionMessage = this._createCompletionMessage(invocationMessage.invocationId, null, res);
  1181. } else {
  1182. this._logger.log(LogLevel.Warning, `No result given for '${methodName}' method and invocation ID '${invocationMessage.invocationId}'.`);
  1183. completionMessage = this._createCompletionMessage(invocationMessage.invocationId, "Client didn't provide a result.", null);
  1184. }
  1185. await this._sendWithProtocol(completionMessage);
  1186. } else {
  1187. if (res) {
  1188. this._logger.log(LogLevel.Error, `Result given for '${methodName}' method but server is not expecting a result.`);
  1189. }
  1190. }
  1191. }
  1192. _connectionClosed(error) {
  1193. this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);
  1194. this._stopDuringStartError = this._stopDuringStartError || error || new AbortError("The underlying connection was closed before the hub handshake could complete.");
  1195. if (this._handshakeResolver) {
  1196. this._handshakeResolver();
  1197. }
  1198. this._cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
  1199. this._cleanupTimeout();
  1200. this._cleanupPingTimer();
  1201. if (this._connectionState === HubConnectionState.Disconnecting) {
  1202. this._completeClose(error);
  1203. } else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) {
  1204. this._reconnect(error);
  1205. } else if (this._connectionState === HubConnectionState.Connected) {
  1206. this._completeClose(error);
  1207. }
  1208. }
  1209. _completeClose(error) {
  1210. if (this._connectionStarted) {
  1211. this._connectionState = HubConnectionState.Disconnected;
  1212. this._connectionStarted = false;
  1213. if (Platform.isBrowser) {
  1214. window.document.removeEventListener("freeze", this._freezeEventListener);
  1215. }
  1216. try {
  1217. this._closedCallbacks.forEach((c) => c.apply(this, [error]));
  1218. } catch (e) {
  1219. this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);
  1220. }
  1221. }
  1222. }
  1223. async _reconnect(error) {
  1224. const reconnectStartTime = Date.now();
  1225. let previousReconnectAttempts = 0;
  1226. let retryError = error !== void 0 ? error : new Error("Attempting to reconnect due to a unknown error.");
  1227. let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError);
  1228. if (nextRetryDelay === null) {
  1229. this._logger.log(LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
  1230. this._completeClose(error);
  1231. return;
  1232. }
  1233. this._connectionState = HubConnectionState.Reconnecting;
  1234. if (error) {
  1235. this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);
  1236. } else {
  1237. this._logger.log(LogLevel.Information, "Connection reconnecting.");
  1238. }
  1239. if (this._reconnectingCallbacks.length !== 0) {
  1240. try {
  1241. this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));
  1242. } catch (e) {
  1243. this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);
  1244. }
  1245. if (this._connectionState !== HubConnectionState.Reconnecting) {
  1246. this._logger.log(LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
  1247. return;
  1248. }
  1249. }
  1250. while (nextRetryDelay !== null) {
  1251. this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);
  1252. await new Promise((resolve) => {
  1253. this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
  1254. });
  1255. this._reconnectDelayHandle = void 0;
  1256. if (this._connectionState !== HubConnectionState.Reconnecting) {
  1257. this._logger.log(LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
  1258. return;
  1259. }
  1260. try {
  1261. await this._startInternal();
  1262. this._connectionState = HubConnectionState.Connected;
  1263. this._logger.log(LogLevel.Information, "HubConnection reconnected successfully.");
  1264. if (this._reconnectedCallbacks.length !== 0) {
  1265. try {
  1266. this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));
  1267. } catch (e) {
  1268. this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);
  1269. }
  1270. }
  1271. return;
  1272. } catch (e) {
  1273. this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);
  1274. if (this._connectionState !== HubConnectionState.Reconnecting) {
  1275. this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);
  1276. if (this._connectionState === HubConnectionState.Disconnecting) {
  1277. this._completeClose();
  1278. }
  1279. return;
  1280. }
  1281. retryError = e instanceof Error ? e : new Error(e.toString());
  1282. nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);
  1283. }
  1284. }
  1285. this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);
  1286. this._completeClose();
  1287. }
  1288. _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {
  1289. try {
  1290. return this._reconnectPolicy.nextRetryDelayInMilliseconds({
  1291. elapsedMilliseconds,
  1292. previousRetryCount,
  1293. retryReason
  1294. });
  1295. } catch (e) {
  1296. this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);
  1297. return null;
  1298. }
  1299. }
  1300. _cancelCallbacksWithError(error) {
  1301. const callbacks = this._callbacks;
  1302. this._callbacks = {};
  1303. Object.keys(callbacks).forEach((key) => {
  1304. const callback = callbacks[key];
  1305. try {
  1306. callback(null, error);
  1307. } catch (e) {
  1308. this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`);
  1309. }
  1310. });
  1311. }
  1312. _cleanupPingTimer() {
  1313. if (this._pingServerHandle) {
  1314. clearTimeout(this._pingServerHandle);
  1315. this._pingServerHandle = void 0;
  1316. }
  1317. }
  1318. _cleanupTimeout() {
  1319. if (this._timeoutHandle) {
  1320. clearTimeout(this._timeoutHandle);
  1321. }
  1322. }
  1323. _createInvocation(methodName, args, nonblocking, streamIds) {
  1324. if (nonblocking) {
  1325. if (streamIds.length !== 0) {
  1326. return {
  1327. arguments: args,
  1328. streamIds,
  1329. target: methodName,
  1330. type: MessageType.Invocation
  1331. };
  1332. } else {
  1333. return {
  1334. arguments: args,
  1335. target: methodName,
  1336. type: MessageType.Invocation
  1337. };
  1338. }
  1339. } else {
  1340. const invocationId = this._invocationId;
  1341. this._invocationId++;
  1342. if (streamIds.length !== 0) {
  1343. return {
  1344. arguments: args,
  1345. invocationId: invocationId.toString(),
  1346. streamIds,
  1347. target: methodName,
  1348. type: MessageType.Invocation
  1349. };
  1350. } else {
  1351. return {
  1352. arguments: args,
  1353. invocationId: invocationId.toString(),
  1354. target: methodName,
  1355. type: MessageType.Invocation
  1356. };
  1357. }
  1358. }
  1359. }
  1360. _launchStreams(streams, promiseQueue) {
  1361. if (streams.length === 0) {
  1362. return;
  1363. }
  1364. if (!promiseQueue) {
  1365. promiseQueue = Promise.resolve();
  1366. }
  1367. for (const streamId in streams) {
  1368. streams[streamId].subscribe({
  1369. complete: () => {
  1370. promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));
  1371. },
  1372. error: (err) => {
  1373. let message;
  1374. if (err instanceof Error) {
  1375. message = err.message;
  1376. } else if (err && err.toString) {
  1377. message = err.toString();
  1378. } else {
  1379. message = "Unknown error";
  1380. }
  1381. promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));
  1382. },
  1383. next: (item) => {
  1384. promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));
  1385. }
  1386. });
  1387. }
  1388. }
  1389. _replaceStreamingParams(args) {
  1390. const streams = [];
  1391. const streamIds = [];
  1392. for (let i = 0; i < args.length; i++) {
  1393. const argument = args[i];
  1394. if (this._isObservable(argument)) {
  1395. const streamId = this._invocationId;
  1396. this._invocationId++;
  1397. streams[streamId] = argument;
  1398. streamIds.push(streamId.toString());
  1399. args.splice(i, 1);
  1400. }
  1401. }
  1402. return [streams, streamIds];
  1403. }
  1404. _isObservable(arg) {
  1405. return arg && arg.subscribe && typeof arg.subscribe === "function";
  1406. }
  1407. _createStreamInvocation(methodName, args, streamIds) {
  1408. const invocationId = this._invocationId;
  1409. this._invocationId++;
  1410. if (streamIds.length !== 0) {
  1411. return {
  1412. arguments: args,
  1413. invocationId: invocationId.toString(),
  1414. streamIds,
  1415. target: methodName,
  1416. type: MessageType.StreamInvocation
  1417. };
  1418. } else {
  1419. return {
  1420. arguments: args,
  1421. invocationId: invocationId.toString(),
  1422. target: methodName,
  1423. type: MessageType.StreamInvocation
  1424. };
  1425. }
  1426. }
  1427. _createCancelInvocation(id) {
  1428. return {
  1429. invocationId: id,
  1430. type: MessageType.CancelInvocation
  1431. };
  1432. }
  1433. _createStreamItemMessage(id, item) {
  1434. return {
  1435. invocationId: id,
  1436. item,
  1437. type: MessageType.StreamItem
  1438. };
  1439. }
  1440. _createCompletionMessage(id, error, result) {
  1441. if (error) {
  1442. return {
  1443. error,
  1444. invocationId: id,
  1445. type: MessageType.Completion
  1446. };
  1447. }
  1448. return {
  1449. invocationId: id,
  1450. result,
  1451. type: MessageType.Completion
  1452. };
  1453. }
  1454. };
  1455. // node_modules/@microsoft/signalr/dist/esm/DefaultReconnectPolicy.js
  1456. var DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2e3, 1e4, 3e4, null];
  1457. var DefaultReconnectPolicy = class {
  1458. constructor(retryDelays) {
  1459. this._retryDelays = retryDelays !== void 0 ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;
  1460. }
  1461. nextRetryDelayInMilliseconds(retryContext) {
  1462. return this._retryDelays[retryContext.previousRetryCount];
  1463. }
  1464. };
  1465. // node_modules/@microsoft/signalr/dist/esm/HeaderNames.js
  1466. var HeaderNames = class {
  1467. };
  1468. HeaderNames.Authorization = "Authorization";
  1469. HeaderNames.Cookie = "Cookie";
  1470. // node_modules/@microsoft/signalr/dist/esm/AccessTokenHttpClient.js
  1471. var AccessTokenHttpClient = class extends HttpClient {
  1472. constructor(innerClient, accessTokenFactory) {
  1473. super();
  1474. this._innerClient = innerClient;
  1475. this._accessTokenFactory = accessTokenFactory;
  1476. }
  1477. async send(request) {
  1478. let allowRetry = true;
  1479. if (this._accessTokenFactory && (!this._accessToken || request.url && request.url.indexOf("/negotiate?") > 0)) {
  1480. allowRetry = false;
  1481. this._accessToken = await this._accessTokenFactory();
  1482. }
  1483. this._setAuthorizationHeader(request);
  1484. const response = await this._innerClient.send(request);
  1485. if (allowRetry && response.statusCode === 401 && this._accessTokenFactory) {
  1486. this._accessToken = await this._accessTokenFactory();
  1487. this._setAuthorizationHeader(request);
  1488. return await this._innerClient.send(request);
  1489. }
  1490. return response;
  1491. }
  1492. _setAuthorizationHeader(request) {
  1493. if (!request.headers) {
  1494. request.headers = {};
  1495. }
  1496. if (this._accessToken) {
  1497. request.headers[HeaderNames.Authorization] = `Bearer ${this._accessToken}`;
  1498. } else if (this._accessTokenFactory) {
  1499. if (request.headers[HeaderNames.Authorization]) {
  1500. delete request.headers[HeaderNames.Authorization];
  1501. }
  1502. }
  1503. }
  1504. getCookieString(url) {
  1505. return this._innerClient.getCookieString(url);
  1506. }
  1507. };
  1508. // node_modules/@microsoft/signalr/dist/esm/ITransport.js
  1509. var HttpTransportType;
  1510. (function(HttpTransportType2) {
  1511. HttpTransportType2[HttpTransportType2["None"] = 0] = "None";
  1512. HttpTransportType2[HttpTransportType2["WebSockets"] = 1] = "WebSockets";
  1513. HttpTransportType2[HttpTransportType2["ServerSentEvents"] = 2] = "ServerSentEvents";
  1514. HttpTransportType2[HttpTransportType2["LongPolling"] = 4] = "LongPolling";
  1515. })(HttpTransportType || (HttpTransportType = {}));
  1516. var TransferFormat;
  1517. (function(TransferFormat2) {
  1518. TransferFormat2[TransferFormat2["Text"] = 1] = "Text";
  1519. TransferFormat2[TransferFormat2["Binary"] = 2] = "Binary";
  1520. })(TransferFormat || (TransferFormat = {}));
  1521. // node_modules/@microsoft/signalr/dist/esm/AbortController.js
  1522. var AbortController2 = class {
  1523. constructor() {
  1524. this._isAborted = false;
  1525. this.onabort = null;
  1526. }
  1527. abort() {
  1528. if (!this._isAborted) {
  1529. this._isAborted = true;
  1530. if (this.onabort) {
  1531. this.onabort();
  1532. }
  1533. }
  1534. }
  1535. get signal() {
  1536. return this;
  1537. }
  1538. get aborted() {
  1539. return this._isAborted;
  1540. }
  1541. };
  1542. // node_modules/@microsoft/signalr/dist/esm/LongPollingTransport.js
  1543. var LongPollingTransport = class {
  1544. constructor(httpClient, logger, options) {
  1545. this._httpClient = httpClient;
  1546. this._logger = logger;
  1547. this._pollAbort = new AbortController2();
  1548. this._options = options;
  1549. this._running = false;
  1550. this.onreceive = null;
  1551. this.onclose = null;
  1552. }
  1553. // This is an internal type, not exported from 'index' so this is really just internal.
  1554. get pollAborted() {
  1555. return this._pollAbort.aborted;
  1556. }
  1557. async connect(url, transferFormat) {
  1558. Arg.isRequired(url, "url");
  1559. Arg.isRequired(transferFormat, "transferFormat");
  1560. Arg.isIn(transferFormat, TransferFormat, "transferFormat");
  1561. this._url = url;
  1562. this._logger.log(LogLevel.Trace, "(LongPolling transport) Connecting.");
  1563. if (transferFormat === TransferFormat.Binary && (typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) {
  1564. throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");
  1565. }
  1566. const [name, value] = getUserAgentHeader();
  1567. const headers = { [name]: value, ...this._options.headers };
  1568. const pollOptions = {
  1569. abortSignal: this._pollAbort.signal,
  1570. headers,
  1571. timeout: 1e5,
  1572. withCredentials: this._options.withCredentials
  1573. };
  1574. if (transferFormat === TransferFormat.Binary) {
  1575. pollOptions.responseType = "arraybuffer";
  1576. }
  1577. const pollUrl = `${url}&_=${Date.now()}`;
  1578. this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);
  1579. const response = await this._httpClient.get(pollUrl, pollOptions);
  1580. if (response.statusCode !== 200) {
  1581. this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);
  1582. this._closeError = new HttpError(response.statusText || "", response.statusCode);
  1583. this._running = false;
  1584. } else {
  1585. this._running = true;
  1586. }
  1587. this._receiving = this._poll(this._url, pollOptions);
  1588. }
  1589. async _poll(url, pollOptions) {
  1590. try {
  1591. while (this._running) {
  1592. try {
  1593. const pollUrl = `${url}&_=${Date.now()}`;
  1594. this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);
  1595. const response = await this._httpClient.get(pollUrl, pollOptions);
  1596. if (response.statusCode === 204) {
  1597. this._logger.log(LogLevel.Information, "(LongPolling transport) Poll terminated by server.");
  1598. this._running = false;
  1599. } else if (response.statusCode !== 200) {
  1600. this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);
  1601. this._closeError = new HttpError(response.statusText || "", response.statusCode);
  1602. this._running = false;
  1603. } else {
  1604. if (response.content) {
  1605. this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent)}.`);
  1606. if (this.onreceive) {
  1607. this.onreceive(response.content);
  1608. }
  1609. } else {
  1610. this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
  1611. }
  1612. }
  1613. } catch (e) {
  1614. if (!this._running) {
  1615. this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`);
  1616. } else {
  1617. if (e instanceof TimeoutError) {
  1618. this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
  1619. } else {
  1620. this._closeError = e;
  1621. this._running = false;
  1622. }
  1623. }
  1624. }
  1625. }
  1626. } finally {
  1627. this._logger.log(LogLevel.Trace, "(LongPolling transport) Polling complete.");
  1628. if (!this.pollAborted) {
  1629. this._raiseOnClose();
  1630. }
  1631. }
  1632. }
  1633. async send(data) {
  1634. if (!this._running) {
  1635. return Promise.reject(new Error("Cannot send until the transport is connected"));
  1636. }
  1637. return sendMessage(this._logger, "LongPolling", this._httpClient, this._url, data, this._options);
  1638. }
  1639. async stop() {
  1640. this._logger.log(LogLevel.Trace, "(LongPolling transport) Stopping polling.");
  1641. this._running = false;
  1642. this._pollAbort.abort();
  1643. try {
  1644. await this._receiving;
  1645. this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`);
  1646. const headers = {};
  1647. const [name, value] = getUserAgentHeader();
  1648. headers[name] = value;
  1649. const deleteOptions = {
  1650. headers: { ...headers, ...this._options.headers },
  1651. timeout: this._options.timeout,
  1652. withCredentials: this._options.withCredentials
  1653. };
  1654. await this._httpClient.delete(this._url, deleteOptions);
  1655. this._logger.log(LogLevel.Trace, "(LongPolling transport) DELETE request sent.");
  1656. } finally {
  1657. this._logger.log(LogLevel.Trace, "(LongPolling transport) Stop finished.");
  1658. this._raiseOnClose();
  1659. }
  1660. }
  1661. _raiseOnClose() {
  1662. if (this.onclose) {
  1663. let logMessage = "(LongPolling transport) Firing onclose event.";
  1664. if (this._closeError) {
  1665. logMessage += " Error: " + this._closeError;
  1666. }
  1667. this._logger.log(LogLevel.Trace, logMessage);
  1668. this.onclose(this._closeError);
  1669. }
  1670. }
  1671. };
  1672. // node_modules/@microsoft/signalr/dist/esm/ServerSentEventsTransport.js
  1673. var ServerSentEventsTransport = class {
  1674. constructor(httpClient, accessToken, logger, options) {
  1675. this._httpClient = httpClient;
  1676. this._accessToken = accessToken;
  1677. this._logger = logger;
  1678. this._options = options;
  1679. this.onreceive = null;
  1680. this.onclose = null;
  1681. }
  1682. async connect(url, transferFormat) {
  1683. Arg.isRequired(url, "url");
  1684. Arg.isRequired(transferFormat, "transferFormat");
  1685. Arg.isIn(transferFormat, TransferFormat, "transferFormat");
  1686. this._logger.log(LogLevel.Trace, "(SSE transport) Connecting.");
  1687. this._url = url;
  1688. if (this._accessToken) {
  1689. url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(this._accessToken)}`;
  1690. }
  1691. return new Promise((resolve, reject) => {
  1692. let opened = false;
  1693. if (transferFormat !== TransferFormat.Text) {
  1694. reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));
  1695. return;
  1696. }
  1697. let eventSource;
  1698. if (Platform.isBrowser || Platform.isWebWorker) {
  1699. eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials });
  1700. } else {
  1701. const cookies = this._httpClient.getCookieString(url);
  1702. const headers = {};
  1703. headers.Cookie = cookies;
  1704. const [name, value] = getUserAgentHeader();
  1705. headers[name] = value;
  1706. eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials, headers: { ...headers, ...this._options.headers } });
  1707. }
  1708. try {
  1709. eventSource.onmessage = (e) => {
  1710. if (this.onreceive) {
  1711. try {
  1712. this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent)}.`);
  1713. this.onreceive(e.data);
  1714. } catch (error) {
  1715. this._close(error);
  1716. return;
  1717. }
  1718. }
  1719. };
  1720. eventSource.onerror = (e) => {
  1721. if (opened) {
  1722. this._close();
  1723. } else {
  1724. reject(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."));
  1725. }
  1726. };
  1727. eventSource.onopen = () => {
  1728. this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`);
  1729. this._eventSource = eventSource;
  1730. opened = true;
  1731. resolve();
  1732. };
  1733. } catch (e) {
  1734. reject(e);
  1735. return;
  1736. }
  1737. });
  1738. }
  1739. async send(data) {
  1740. if (!this._eventSource) {
  1741. return Promise.reject(new Error("Cannot send until the transport is connected"));
  1742. }
  1743. return sendMessage(this._logger, "SSE", this._httpClient, this._url, data, this._options);
  1744. }
  1745. stop() {
  1746. this._close();
  1747. return Promise.resolve();
  1748. }
  1749. _close(e) {
  1750. if (this._eventSource) {
  1751. this._eventSource.close();
  1752. this._eventSource = void 0;
  1753. if (this.onclose) {
  1754. this.onclose(e);
  1755. }
  1756. }
  1757. }
  1758. };
  1759. // node_modules/@microsoft/signalr/dist/esm/WebSocketTransport.js
  1760. var WebSocketTransport = class {
  1761. constructor(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) {
  1762. this._logger = logger;
  1763. this._accessTokenFactory = accessTokenFactory;
  1764. this._logMessageContent = logMessageContent;
  1765. this._webSocketConstructor = webSocketConstructor;
  1766. this._httpClient = httpClient;
  1767. this.onreceive = null;
  1768. this.onclose = null;
  1769. this._headers = headers;
  1770. }
  1771. async connect(url, transferFormat) {
  1772. Arg.isRequired(url, "url");
  1773. Arg.isRequired(transferFormat, "transferFormat");
  1774. Arg.isIn(transferFormat, TransferFormat, "transferFormat");
  1775. this._logger.log(LogLevel.Trace, "(WebSockets transport) Connecting.");
  1776. let token;
  1777. if (this._accessTokenFactory) {
  1778. token = await this._accessTokenFactory();
  1779. }
  1780. return new Promise((resolve, reject) => {
  1781. url = url.replace(/^http/, "ws");
  1782. let webSocket;
  1783. const cookies = this._httpClient.getCookieString(url);
  1784. let opened = false;
  1785. if (Platform.isNode || Platform.isReactNative) {
  1786. const headers = {};
  1787. const [name, value] = getUserAgentHeader();
  1788. headers[name] = value;
  1789. if (token) {
  1790. headers[HeaderNames.Authorization] = `Bearer ${token}`;
  1791. }
  1792. if (cookies) {
  1793. headers[HeaderNames.Cookie] = cookies;
  1794. }
  1795. webSocket = new this._webSocketConstructor(url, void 0, {
  1796. headers: { ...headers, ...this._headers }
  1797. });
  1798. } else {
  1799. if (token) {
  1800. url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(token)}`;
  1801. }
  1802. }
  1803. if (!webSocket) {
  1804. webSocket = new this._webSocketConstructor(url);
  1805. }
  1806. if (transferFormat === TransferFormat.Binary) {
  1807. webSocket.binaryType = "arraybuffer";
  1808. }
  1809. webSocket.onopen = (_event) => {
  1810. this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);
  1811. this._webSocket = webSocket;
  1812. opened = true;
  1813. resolve();
  1814. };
  1815. webSocket.onerror = (event) => {
  1816. let error = null;
  1817. if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
  1818. error = event.error;
  1819. } else {
  1820. error = "There was an error with the transport";
  1821. }
  1822. this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`);
  1823. };
  1824. webSocket.onmessage = (message) => {
  1825. this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`);
  1826. if (this.onreceive) {
  1827. try {
  1828. this.onreceive(message.data);
  1829. } catch (error) {
  1830. this._close(error);
  1831. return;
  1832. }
  1833. }
  1834. };
  1835. webSocket.onclose = (event) => {
  1836. if (opened) {
  1837. this._close(event);
  1838. } else {
  1839. let error = null;
  1840. if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
  1841. error = event.error;
  1842. } else {
  1843. error = "WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.";
  1844. }
  1845. reject(new Error(error));
  1846. }
  1847. };
  1848. });
  1849. }
  1850. send(data) {
  1851. if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) {
  1852. this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`);
  1853. this._webSocket.send(data);
  1854. return Promise.resolve();
  1855. }
  1856. return Promise.reject("WebSocket is not in the OPEN state");
  1857. }
  1858. stop() {
  1859. if (this._webSocket) {
  1860. this._close(void 0);
  1861. }
  1862. return Promise.resolve();
  1863. }
  1864. _close(event) {
  1865. if (this._webSocket) {
  1866. this._webSocket.onclose = () => {
  1867. };
  1868. this._webSocket.onmessage = () => {
  1869. };
  1870. this._webSocket.onerror = () => {
  1871. };
  1872. this._webSocket.close();
  1873. this._webSocket = void 0;
  1874. }
  1875. this._logger.log(LogLevel.Trace, "(WebSockets transport) socket closed.");
  1876. if (this.onclose) {
  1877. if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1e3)) {
  1878. this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || "no reason given"}).`));
  1879. } else if (event instanceof Error) {
  1880. this.onclose(event);
  1881. } else {
  1882. this.onclose();
  1883. }
  1884. }
  1885. }
  1886. _isCloseEvent(event) {
  1887. return event && typeof event.wasClean === "boolean" && typeof event.code === "number";
  1888. }
  1889. };
  1890. // node_modules/@microsoft/signalr/dist/esm/HttpConnection.js
  1891. var MAX_REDIRECTS = 100;
  1892. var HttpConnection = class {
  1893. constructor(url, options = {}) {
  1894. this._stopPromiseResolver = () => {
  1895. };
  1896. this.features = {};
  1897. this._negotiateVersion = 1;
  1898. Arg.isRequired(url, "url");
  1899. this._logger = createLogger(options.logger);
  1900. this.baseUrl = this._resolveUrl(url);
  1901. options = options || {};
  1902. options.logMessageContent = options.logMessageContent === void 0 ? false : options.logMessageContent;
  1903. if (typeof options.withCredentials === "boolean" || options.withCredentials === void 0) {
  1904. options.withCredentials = options.withCredentials === void 0 ? true : options.withCredentials;
  1905. } else {
  1906. throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");
  1907. }
  1908. options.timeout = options.timeout === void 0 ? 100 * 1e3 : options.timeout;
  1909. let webSocketModule = null;
  1910. let eventSourceModule = null;
  1911. if (Platform.isNode && typeof __require !== "undefined") {
  1912. const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
  1913. webSocketModule = requireFunc("ws");
  1914. eventSourceModule = requireFunc("eventsource");
  1915. }
  1916. if (!Platform.isNode && typeof WebSocket !== "undefined" && !options.WebSocket) {
  1917. options.WebSocket = WebSocket;
  1918. } else if (Platform.isNode && !options.WebSocket) {
  1919. if (webSocketModule) {
  1920. options.WebSocket = webSocketModule;
  1921. }
  1922. }
  1923. if (!Platform.isNode && typeof EventSource !== "undefined" && !options.EventSource) {
  1924. options.EventSource = EventSource;
  1925. } else if (Platform.isNode && !options.EventSource) {
  1926. if (typeof eventSourceModule !== "undefined") {
  1927. options.EventSource = eventSourceModule;
  1928. }
  1929. }
  1930. this._httpClient = new AccessTokenHttpClient(options.httpClient || new DefaultHttpClient(this._logger), options.accessTokenFactory);
  1931. this._connectionState = "Disconnected";
  1932. this._connectionStarted = false;
  1933. this._options = options;
  1934. this.onreceive = null;
  1935. this.onclose = null;
  1936. }
  1937. async start(transferFormat) {
  1938. transferFormat = transferFormat || TransferFormat.Binary;
  1939. Arg.isIn(transferFormat, TransferFormat, "transferFormat");
  1940. this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);
  1941. if (this._connectionState !== "Disconnected") {
  1942. return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));
  1943. }
  1944. this._connectionState = "Connecting";
  1945. this._startInternalPromise = this._startInternal(transferFormat);
  1946. await this._startInternalPromise;
  1947. if (this._connectionState === "Disconnecting") {
  1948. const message = "Failed to start the HttpConnection before stop() was called.";
  1949. this._logger.log(LogLevel.Error, message);
  1950. await this._stopPromise;
  1951. return Promise.reject(new AbortError(message));
  1952. } else if (this._connectionState !== "Connected") {
  1953. const message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";
  1954. this._logger.log(LogLevel.Error, message);
  1955. return Promise.reject(new AbortError(message));
  1956. }
  1957. this._connectionStarted = true;
  1958. }
  1959. send(data) {
  1960. if (this._connectionState !== "Connected") {
  1961. return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State."));
  1962. }
  1963. if (!this._sendQueue) {
  1964. this._sendQueue = new TransportSendQueue(this.transport);
  1965. }
  1966. return this._sendQueue.send(data);
  1967. }
  1968. async stop(error) {
  1969. if (this._connectionState === "Disconnected") {
  1970. this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);
  1971. return Promise.resolve();
  1972. }
  1973. if (this._connectionState === "Disconnecting") {
  1974. this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
  1975. return this._stopPromise;
  1976. }
  1977. this._connectionState = "Disconnecting";
  1978. this._stopPromise = new Promise((resolve) => {
  1979. this._stopPromiseResolver = resolve;
  1980. });
  1981. await this._stopInternal(error);
  1982. await this._stopPromise;
  1983. }
  1984. async _stopInternal(error) {
  1985. this._stopError = error;
  1986. try {
  1987. await this._startInternalPromise;
  1988. } catch (e) {
  1989. }
  1990. if (this.transport) {
  1991. try {
  1992. await this.transport.stop();
  1993. } catch (e) {
  1994. this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);
  1995. this._stopConnection();
  1996. }
  1997. this.transport = void 0;
  1998. } else {
  1999. this._logger.log(LogLevel.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.");
  2000. }
  2001. }
  2002. async _startInternal(transferFormat) {
  2003. let url = this.baseUrl;
  2004. this._accessTokenFactory = this._options.accessTokenFactory;
  2005. this._httpClient._accessTokenFactory = this._accessTokenFactory;
  2006. try {
  2007. if (this._options.skipNegotiation) {
  2008. if (this._options.transport === HttpTransportType.WebSockets) {
  2009. this.transport = this._constructTransport(HttpTransportType.WebSockets);
  2010. await this._startTransport(url, transferFormat);
  2011. } else {
  2012. throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");
  2013. }
  2014. } else {
  2015. let negotiateResponse = null;
  2016. let redirects = 0;
  2017. do {
  2018. negotiateResponse = await this._getNegotiationResponse(url);
  2019. if (this._connectionState === "Disconnecting" || this._connectionState === "Disconnected") {
  2020. throw new AbortError("The connection was stopped during negotiation.");
  2021. }
  2022. if (negotiateResponse.error) {
  2023. throw new Error(negotiateResponse.error);
  2024. }
  2025. if (negotiateResponse.ProtocolVersion) {
  2026. throw new 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.");
  2027. }
  2028. if (negotiateResponse.url) {
  2029. url = negotiateResponse.url;
  2030. }
  2031. if (negotiateResponse.accessToken) {
  2032. const accessToken = negotiateResponse.accessToken;
  2033. this._accessTokenFactory = () => accessToken;
  2034. this._httpClient._accessToken = accessToken;
  2035. this._httpClient._accessTokenFactory = void 0;
  2036. }
  2037. redirects++;
  2038. } while (negotiateResponse.url && redirects < MAX_REDIRECTS);
  2039. if (redirects === MAX_REDIRECTS && negotiateResponse.url) {
  2040. throw new Error("Negotiate redirection limit exceeded.");
  2041. }
  2042. await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat);
  2043. }
  2044. if (this.transport instanceof LongPollingTransport) {
  2045. this.features.inherentKeepAlive = true;
  2046. }
  2047. if (this._connectionState === "Connecting") {
  2048. this._logger.log(LogLevel.Debug, "The HttpConnection connected successfully.");
  2049. this._connectionState = "Connected";
  2050. }
  2051. } catch (e) {
  2052. this._logger.log(LogLevel.Error, "Failed to start the connection: " + e);
  2053. this._connectionState = "Disconnected";
  2054. this.transport = void 0;
  2055. this._stopPromiseResolver();
  2056. return Promise.reject(e);
  2057. }
  2058. }
  2059. async _getNegotiationResponse(url) {
  2060. const headers = {};
  2061. const [name, value] = getUserAgentHeader();
  2062. headers[name] = value;
  2063. const negotiateUrl = this._resolveNegotiateUrl(url);
  2064. this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);
  2065. try {
  2066. const response = await this._httpClient.post(negotiateUrl, {
  2067. content: "",
  2068. headers: { ...headers, ...this._options.headers },
  2069. timeout: this._options.timeout,
  2070. withCredentials: this._options.withCredentials
  2071. });
  2072. if (response.statusCode !== 200) {
  2073. return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));
  2074. }
  2075. const negotiateResponse = JSON.parse(response.content);
  2076. if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {
  2077. negotiateResponse.connectionToken = negotiateResponse.connectionId;
  2078. }
  2079. return negotiateResponse;
  2080. } catch (e) {
  2081. let errorMessage = "Failed to complete negotiation with the server: " + e;
  2082. if (e instanceof HttpError) {
  2083. if (e.statusCode === 404) {
  2084. errorMessage = errorMessage + " Either this is not a SignalR endpoint or there is a proxy blocking the connection.";
  2085. }
  2086. }
  2087. this._logger.log(LogLevel.Error, errorMessage);
  2088. return Promise.reject(new FailedToNegotiateWithServerError(errorMessage));
  2089. }
  2090. }
  2091. _createConnectUrl(url, connectionToken) {
  2092. if (!connectionToken) {
  2093. return url;
  2094. }
  2095. return url + (url.indexOf("?") === -1 ? "?" : "&") + `id=${connectionToken}`;
  2096. }
  2097. async _createTransport(url, requestedTransport, negotiateResponse, requestedTransferFormat) {
  2098. let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken);
  2099. if (this._isITransport(requestedTransport)) {
  2100. this._logger.log(LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly.");
  2101. this.transport = requestedTransport;
  2102. await this._startTransport(connectUrl, requestedTransferFormat);
  2103. this.connectionId = negotiateResponse.connectionId;
  2104. return;
  2105. }
  2106. const transportExceptions = [];
  2107. const transports = negotiateResponse.availableTransports || [];
  2108. let negotiate = negotiateResponse;
  2109. for (const endpoint of transports) {
  2110. const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);
  2111. if (transportOrError instanceof Error) {
  2112. transportExceptions.push(`${endpoint.transport} failed:`);
  2113. transportExceptions.push(transportOrError);
  2114. } else if (this._isITransport(transportOrError)) {
  2115. this.transport = transportOrError;
  2116. if (!negotiate) {
  2117. try {
  2118. negotiate = await this._getNegotiationResponse(url);
  2119. } catch (ex) {
  2120. return Promise.reject(ex);
  2121. }
  2122. connectUrl = this._createConnectUrl(url, negotiate.connectionToken);
  2123. }
  2124. try {
  2125. await this._startTransport(connectUrl, requestedTransferFormat);
  2126. this.connectionId = negotiate.connectionId;
  2127. return;
  2128. } catch (ex) {
  2129. this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);
  2130. negotiate = void 0;
  2131. transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport]));
  2132. if (this._connectionState !== "Connecting") {
  2133. const message = "Failed to select transport before stop() was called.";
  2134. this._logger.log(LogLevel.Debug, message);
  2135. return Promise.reject(new AbortError(message));
  2136. }
  2137. }
  2138. }
  2139. }
  2140. if (transportExceptions.length > 0) {
  2141. return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(" ")}`, transportExceptions));
  2142. }
  2143. return Promise.reject(new Error("None of the transports supported by the client are supported by the server."));
  2144. }
  2145. _constructTransport(transport) {
  2146. switch (transport) {
  2147. case HttpTransportType.WebSockets:
  2148. if (!this._options.WebSocket) {
  2149. throw new Error("'WebSocket' is not supported in your environment.");
  2150. }
  2151. return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent, this._options.WebSocket, this._options.headers || {});
  2152. case HttpTransportType.ServerSentEvents:
  2153. if (!this._options.EventSource) {
  2154. throw new Error("'EventSource' is not supported in your environment.");
  2155. }
  2156. return new ServerSentEventsTransport(this._httpClient, this._httpClient._accessToken, this._logger, this._options);
  2157. case HttpTransportType.LongPolling:
  2158. return new LongPollingTransport(this._httpClient, this._logger, this._options);
  2159. default:
  2160. throw new Error(`Unknown transport: ${transport}.`);
  2161. }
  2162. }
  2163. _startTransport(url, transferFormat) {
  2164. this.transport.onreceive = this.onreceive;
  2165. this.transport.onclose = (e) => this._stopConnection(e);
  2166. return this.transport.connect(url, transferFormat);
  2167. }
  2168. _resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat) {
  2169. const transport = HttpTransportType[endpoint.transport];
  2170. if (transport === null || transport === void 0) {
  2171. this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);
  2172. return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);
  2173. } else {
  2174. if (transportMatches(requestedTransport, transport)) {
  2175. const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);
  2176. if (transferFormats.indexOf(requestedTransferFormat) >= 0) {
  2177. if (transport === HttpTransportType.WebSockets && !this._options.WebSocket || transport === HttpTransportType.ServerSentEvents && !this._options.EventSource) {
  2178. this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);
  2179. return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport);
  2180. } else {
  2181. this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);
  2182. try {
  2183. return this._constructTransport(transport);
  2184. } catch (ex) {
  2185. return ex;
  2186. }
  2187. }
  2188. } else {
  2189. this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);
  2190. return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);
  2191. }
  2192. } else {
  2193. this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);
  2194. return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport);
  2195. }
  2196. }
  2197. }
  2198. _isITransport(transport) {
  2199. return transport && typeof transport === "object" && "connect" in transport;
  2200. }
  2201. _stopConnection(error) {
  2202. this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`);
  2203. this.transport = void 0;
  2204. error = this._stopError || error;
  2205. this._stopError = void 0;
  2206. if (this._connectionState === "Disconnected") {
  2207. this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);
  2208. return;
  2209. }
  2210. if (this._connectionState === "Connecting") {
  2211. this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);
  2212. throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);
  2213. }
  2214. if (this._connectionState === "Disconnecting") {
  2215. this._stopPromiseResolver();
  2216. }
  2217. if (error) {
  2218. this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);
  2219. } else {
  2220. this._logger.log(LogLevel.Information, "Connection disconnected.");
  2221. }
  2222. if (this._sendQueue) {
  2223. this._sendQueue.stop().catch((e) => {
  2224. this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);
  2225. });
  2226. this._sendQueue = void 0;
  2227. }
  2228. this.connectionId = void 0;
  2229. this._connectionState = "Disconnected";
  2230. if (this._connectionStarted) {
  2231. this._connectionStarted = false;
  2232. try {
  2233. if (this.onclose) {
  2234. this.onclose(error);
  2235. }
  2236. } catch (e) {
  2237. this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);
  2238. }
  2239. }
  2240. }
  2241. _resolveUrl(url) {
  2242. if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
  2243. return url;
  2244. }
  2245. if (!Platform.isBrowser) {
  2246. throw new Error(`Cannot resolve '${url}'.`);
  2247. }
  2248. const aTag = window.document.createElement("a");
  2249. aTag.href = url;
  2250. this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);
  2251. return aTag.href;
  2252. }
  2253. _resolveNegotiateUrl(url) {
  2254. const index = url.indexOf("?");
  2255. let negotiateUrl = url.substring(0, index === -1 ? url.length : index);
  2256. if (negotiateUrl[negotiateUrl.length - 1] !== "/") {
  2257. negotiateUrl += "/";
  2258. }
  2259. negotiateUrl += "negotiate";
  2260. negotiateUrl += index === -1 ? "" : url.substring(index);
  2261. if (negotiateUrl.indexOf("negotiateVersion") === -1) {
  2262. negotiateUrl += index === -1 ? "?" : "&";
  2263. negotiateUrl += "negotiateVersion=" + this._negotiateVersion;
  2264. }
  2265. return negotiateUrl;
  2266. }
  2267. };
  2268. function transportMatches(requestedTransport, actualTransport) {
  2269. return !requestedTransport || (actualTransport & requestedTransport) !== 0;
  2270. }
  2271. var TransportSendQueue = class _TransportSendQueue {
  2272. constructor(_transport) {
  2273. this._transport = _transport;
  2274. this._buffer = [];
  2275. this._executing = true;
  2276. this._sendBufferedData = new PromiseSource();
  2277. this._transportResult = new PromiseSource();
  2278. this._sendLoopPromise = this._sendLoop();
  2279. }
  2280. send(data) {
  2281. this._bufferData(data);
  2282. if (!this._transportResult) {
  2283. this._transportResult = new PromiseSource();
  2284. }
  2285. return this._transportResult.promise;
  2286. }
  2287. stop() {
  2288. this._executing = false;
  2289. this._sendBufferedData.resolve();
  2290. return this._sendLoopPromise;
  2291. }
  2292. _bufferData(data) {
  2293. if (this._buffer.length && typeof this._buffer[0] !== typeof data) {
  2294. throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof data}`);
  2295. }
  2296. this._buffer.push(data);
  2297. this._sendBufferedData.resolve();
  2298. }
  2299. async _sendLoop() {
  2300. while (true) {
  2301. await this._sendBufferedData.promise;
  2302. if (!this._executing) {
  2303. if (this._transportResult) {
  2304. this._transportResult.reject("Connection stopped.");
  2305. }
  2306. break;
  2307. }
  2308. this._sendBufferedData = new PromiseSource();
  2309. const transportResult = this._transportResult;
  2310. this._transportResult = void 0;
  2311. const data = typeof this._buffer[0] === "string" ? this._buffer.join("") : _TransportSendQueue._concatBuffers(this._buffer);
  2312. this._buffer.length = 0;
  2313. try {
  2314. await this._transport.send(data);
  2315. transportResult.resolve();
  2316. } catch (error) {
  2317. transportResult.reject(error);
  2318. }
  2319. }
  2320. }
  2321. static _concatBuffers(arrayBuffers) {
  2322. const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b);
  2323. const result = new Uint8Array(totalLength);
  2324. let offset = 0;
  2325. for (const item of arrayBuffers) {
  2326. result.set(new Uint8Array(item), offset);
  2327. offset += item.byteLength;
  2328. }
  2329. return result.buffer;
  2330. }
  2331. };
  2332. var PromiseSource = class {
  2333. constructor() {
  2334. this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]);
  2335. }
  2336. resolve() {
  2337. this._resolver();
  2338. }
  2339. reject(reason) {
  2340. this._rejecter(reason);
  2341. }
  2342. };
  2343. // node_modules/@microsoft/signalr/dist/esm/JsonHubProtocol.js
  2344. var JSON_HUB_PROTOCOL_NAME = "json";
  2345. var JsonHubProtocol = class {
  2346. constructor() {
  2347. this.name = JSON_HUB_PROTOCOL_NAME;
  2348. this.version = 1;
  2349. this.transferFormat = TransferFormat.Text;
  2350. }
  2351. /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
  2352. *
  2353. * @param {string} input A string containing the serialized representation.
  2354. * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.
  2355. */
  2356. parseMessages(input, logger) {
  2357. if (typeof input !== "string") {
  2358. throw new Error("Invalid input for JSON hub protocol. Expected a string.");
  2359. }
  2360. if (!input) {
  2361. return [];
  2362. }
  2363. if (logger === null) {
  2364. logger = NullLogger.instance;
  2365. }
  2366. const messages = TextMessageFormat.parse(input);
  2367. const hubMessages = [];
  2368. for (const message of messages) {
  2369. const parsedMessage = JSON.parse(message);
  2370. if (typeof parsedMessage.type !== "number") {
  2371. throw new Error("Invalid payload.");
  2372. }
  2373. switch (parsedMessage.type) {
  2374. case MessageType.Invocation:
  2375. this._isInvocationMessage(parsedMessage);
  2376. break;
  2377. case MessageType.StreamItem:
  2378. this._isStreamItemMessage(parsedMessage);
  2379. break;
  2380. case MessageType.Completion:
  2381. this._isCompletionMessage(parsedMessage);
  2382. break;
  2383. case MessageType.Ping:
  2384. break;
  2385. case MessageType.Close:
  2386. break;
  2387. default:
  2388. logger.log(LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored.");
  2389. continue;
  2390. }
  2391. hubMessages.push(parsedMessage);
  2392. }
  2393. return hubMessages;
  2394. }
  2395. /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
  2396. *
  2397. * @param {HubMessage} message The message to write.
  2398. * @returns {string} A string containing the serialized representation of the message.
  2399. */
  2400. writeMessage(message) {
  2401. return TextMessageFormat.write(JSON.stringify(message));
  2402. }
  2403. _isInvocationMessage(message) {
  2404. this._assertNotEmptyString(message.target, "Invalid payload for Invocation message.");
  2405. if (message.invocationId !== void 0) {
  2406. this._assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message.");
  2407. }
  2408. }
  2409. _isStreamItemMessage(message) {
  2410. this._assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message.");
  2411. if (message.item === void 0) {
  2412. throw new Error("Invalid payload for StreamItem message.");
  2413. }
  2414. }
  2415. _isCompletionMessage(message) {
  2416. if (message.result && message.error) {
  2417. throw new Error("Invalid payload for Completion message.");
  2418. }
  2419. if (!message.result && message.error) {
  2420. this._assertNotEmptyString(message.error, "Invalid payload for Completion message.");
  2421. }
  2422. this._assertNotEmptyString(message.invocationId, "Invalid payload for Completion message.");
  2423. }
  2424. _assertNotEmptyString(value, errorMessage) {
  2425. if (typeof value !== "string" || value === "") {
  2426. throw new Error(errorMessage);
  2427. }
  2428. }
  2429. };
  2430. // node_modules/@microsoft/signalr/dist/esm/HubConnectionBuilder.js
  2431. var LogLevelNameMapping = {
  2432. trace: LogLevel.Trace,
  2433. debug: LogLevel.Debug,
  2434. info: LogLevel.Information,
  2435. information: LogLevel.Information,
  2436. warn: LogLevel.Warning,
  2437. warning: LogLevel.Warning,
  2438. error: LogLevel.Error,
  2439. critical: LogLevel.Critical,
  2440. none: LogLevel.None
  2441. };
  2442. function parseLogLevel(name) {
  2443. const mapping = LogLevelNameMapping[name.toLowerCase()];
  2444. if (typeof mapping !== "undefined") {
  2445. return mapping;
  2446. } else {
  2447. throw new Error(`Unknown log level: ${name}`);
  2448. }
  2449. }
  2450. var HubConnectionBuilder = class {
  2451. configureLogging(logging) {
  2452. Arg.isRequired(logging, "logging");
  2453. if (isLogger(logging)) {
  2454. this.logger = logging;
  2455. } else if (typeof logging === "string") {
  2456. const logLevel = parseLogLevel(logging);
  2457. this.logger = new ConsoleLogger(logLevel);
  2458. } else {
  2459. this.logger = new ConsoleLogger(logging);
  2460. }
  2461. return this;
  2462. }
  2463. withUrl(url, transportTypeOrOptions) {
  2464. Arg.isRequired(url, "url");
  2465. Arg.isNotEmpty(url, "url");
  2466. this.url = url;
  2467. if (typeof transportTypeOrOptions === "object") {
  2468. this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions };
  2469. } else {
  2470. this.httpConnectionOptions = {
  2471. ...this.httpConnectionOptions,
  2472. transport: transportTypeOrOptions
  2473. };
  2474. }
  2475. return this;
  2476. }
  2477. /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.
  2478. *
  2479. * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.
  2480. */
  2481. withHubProtocol(protocol) {
  2482. Arg.isRequired(protocol, "protocol");
  2483. this.protocol = protocol;
  2484. return this;
  2485. }
  2486. withAutomaticReconnect(retryDelaysOrReconnectPolicy) {
  2487. if (this.reconnectPolicy) {
  2488. throw new Error("A reconnectPolicy has already been set.");
  2489. }
  2490. if (!retryDelaysOrReconnectPolicy) {
  2491. this.reconnectPolicy = new DefaultReconnectPolicy();
  2492. } else if (Array.isArray(retryDelaysOrReconnectPolicy)) {
  2493. this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);
  2494. } else {
  2495. this.reconnectPolicy = retryDelaysOrReconnectPolicy;
  2496. }
  2497. return this;
  2498. }
  2499. /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.
  2500. *
  2501. * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.
  2502. */
  2503. build() {
  2504. const httpConnectionOptions = this.httpConnectionOptions || {};
  2505. if (httpConnectionOptions.logger === void 0) {
  2506. httpConnectionOptions.logger = this.logger;
  2507. }
  2508. if (!this.url) {
  2509. throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");
  2510. }
  2511. const connection = new HttpConnection(this.url, httpConnectionOptions);
  2512. return HubConnection.create(connection, this.logger || NullLogger.instance, this.protocol || new JsonHubProtocol(), this.reconnectPolicy);
  2513. }
  2514. };
  2515. function isLogger(logger) {
  2516. return logger.log !== void 0;
  2517. }
  2518. export {
  2519. AbortError,
  2520. DefaultHttpClient,
  2521. HttpClient,
  2522. HttpError,
  2523. HttpResponse,
  2524. HttpTransportType,
  2525. HubConnection,
  2526. HubConnectionBuilder,
  2527. HubConnectionState,
  2528. JsonHubProtocol,
  2529. LogLevel,
  2530. MessageType,
  2531. NullLogger,
  2532. Subject,
  2533. TimeoutError,
  2534. TransferFormat,
  2535. VERSION
  2536. };
  2537. //# sourceMappingURL=@microsoft_signalr.js.map