@sparkle-learning/core 0.0.52 → 0.0.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/cjs/header-mobile-collapse_61.cjs.entry.js +15 -2994
  2. package/dist/cjs/{ion-select_2.cjs.entry.js → ion-select_3.cjs.entry.js} +118 -0
  3. package/dist/cjs/loader.cjs.js +1 -1
  4. package/dist/cjs/signalR.service-5672eebc.js +2987 -0
  5. package/dist/cjs/sparkle-animation-player.cjs.entry.js +1 -0
  6. package/dist/cjs/sparkle-core.cjs.js +1 -1
  7. package/dist/cjs/sparkle-discussion-questions_2.cjs.entry.js +272 -0
  8. package/dist/cjs/sparkle-discussion.cjs.entry.js +40 -0
  9. package/dist/collection/collection-manifest.json +3 -0
  10. package/dist/collection/components/sparkle-animation-player/sparkle-animation-player.js +1 -0
  11. package/dist/collection/components/sparkle-course-root/sparkle-course-root.js +1 -1
  12. package/dist/collection/components/sparkle-discussion/sparkle-discussion-questions/sparkle-discussion-questions.css +157 -0
  13. package/dist/collection/components/sparkle-discussion/sparkle-discussion-questions/sparkle-discussion-questions.js +230 -0
  14. package/dist/collection/components/sparkle-discussion/sparkle-discussion-results/sparkle-discussion-results.css +158 -0
  15. package/dist/collection/components/sparkle-discussion/sparkle-discussion-results/sparkle-discussion-results.js +268 -0
  16. package/dist/collection/components/sparkle-discussion/sparkle-discussion.css +0 -0
  17. package/dist/collection/components/sparkle-discussion/sparkle-discussion.js +110 -0
  18. package/dist/esm/header-mobile-collapse_61.entry.js +3 -2982
  19. package/dist/esm/{ion-select_2.entry.js → ion-select_3.entry.js} +118 -1
  20. package/dist/esm/loader.js +1 -1
  21. package/dist/esm/signalR.service-9d5b9f36.js +2984 -0
  22. package/dist/esm/sparkle-animation-player.entry.js +1 -0
  23. package/dist/esm/sparkle-core.js +1 -1
  24. package/dist/esm/sparkle-discussion-questions_2.entry.js +267 -0
  25. package/dist/esm/sparkle-discussion.entry.js +36 -0
  26. package/dist/sparkle-core/{p-0335c863.entry.js → p-0a5d7c4f.entry.js} +26 -26
  27. package/dist/sparkle-core/p-18cdd458.entry.js +1 -0
  28. package/dist/sparkle-core/p-30767c1c.entry.js +1 -0
  29. package/dist/sparkle-core/p-3265ed87.entry.js +1 -0
  30. package/dist/sparkle-core/{p-564e64fc.entry.js → p-44334ef3.entry.js} +2 -2
  31. package/dist/sparkle-core/p-4c9f994f.js +1 -0
  32. package/dist/sparkle-core/sparkle-core.esm.js +1 -1
  33. package/dist/types/components/sparkle-discussion/sparkle-discussion-questions/sparkle-discussion-questions.d.ts +28 -0
  34. package/dist/types/components/sparkle-discussion/sparkle-discussion-results/sparkle-discussion-results.d.ts +45 -0
  35. package/dist/types/components/sparkle-discussion/sparkle-discussion.d.ts +11 -0
  36. package/dist/types/components.d.ts +66 -1
  37. package/package.json +1 -1
  38. package/dist/cjs/sparkle-feed-post.cjs.entry.js +0 -124
  39. package/dist/esm/sparkle-feed-post.entry.js +0 -120
  40. package/dist/sparkle-core/p-15403881.entry.js +0 -1
  41. package/dist/sparkle-core/p-41a9ece7.entry.js +0 -1
  42. package/dist/types/components/sparkle-quiz/sparkle-quiz.d.ts +0 -41
@@ -0,0 +1,2984 @@
1
+ import { E as EnvironmentConfigService } from './environment-config.service-2b5d692b.js';
2
+ import { d as createStore } from './auth.store-dba2c2da.js';
3
+
4
+ // Licensed to the .NET Foundation under one or more agreements.
5
+ // The .NET Foundation licenses this file to you under the MIT license.
6
+ /** Error thrown when an HTTP request fails. */
7
+ class HttpError extends Error {
8
+ /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.
9
+ *
10
+ * @param {string} errorMessage A descriptive error message.
11
+ * @param {number} statusCode The HTTP status code represented by this error.
12
+ */
13
+ constructor(errorMessage, statusCode) {
14
+ const trueProto = new.target.prototype;
15
+ super(`${errorMessage}: Status code '${statusCode}'`);
16
+ this.statusCode = statusCode;
17
+ // Workaround issue in Typescript compiler
18
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
19
+ this.__proto__ = trueProto;
20
+ }
21
+ }
22
+ /** Error thrown when a timeout elapses. */
23
+ class TimeoutError extends Error {
24
+ /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.
25
+ *
26
+ * @param {string} errorMessage A descriptive error message.
27
+ */
28
+ constructor(errorMessage = "A timeout occurred.") {
29
+ const trueProto = new.target.prototype;
30
+ super(errorMessage);
31
+ // Workaround issue in Typescript compiler
32
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
33
+ this.__proto__ = trueProto;
34
+ }
35
+ }
36
+ /** Error thrown when an action is aborted. */
37
+ class AbortError extends Error {
38
+ /** Constructs a new instance of {@link AbortError}.
39
+ *
40
+ * @param {string} errorMessage A descriptive error message.
41
+ */
42
+ constructor(errorMessage = "An abort occurred.") {
43
+ const trueProto = new.target.prototype;
44
+ super(errorMessage);
45
+ // Workaround issue in Typescript compiler
46
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
47
+ this.__proto__ = trueProto;
48
+ }
49
+ }
50
+ /** Error thrown when the selected transport is unsupported by the browser. */
51
+ /** @private */
52
+ class UnsupportedTransportError extends Error {
53
+ /** Constructs a new instance of {@link @microsoft/signalr.UnsupportedTransportError}.
54
+ *
55
+ * @param {string} message A descriptive error message.
56
+ * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.
57
+ */
58
+ constructor(message, transport) {
59
+ const trueProto = new.target.prototype;
60
+ super(message);
61
+ this.transport = transport;
62
+ this.errorType = 'UnsupportedTransportError';
63
+ // Workaround issue in Typescript compiler
64
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
65
+ this.__proto__ = trueProto;
66
+ }
67
+ }
68
+ /** Error thrown when the selected transport is disabled by the browser. */
69
+ /** @private */
70
+ class DisabledTransportError extends Error {
71
+ /** Constructs a new instance of {@link @microsoft/signalr.DisabledTransportError}.
72
+ *
73
+ * @param {string} message A descriptive error message.
74
+ * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.
75
+ */
76
+ constructor(message, transport) {
77
+ const trueProto = new.target.prototype;
78
+ super(message);
79
+ this.transport = transport;
80
+ this.errorType = 'DisabledTransportError';
81
+ // Workaround issue in Typescript compiler
82
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
83
+ this.__proto__ = trueProto;
84
+ }
85
+ }
86
+ /** Error thrown when the selected transport cannot be started. */
87
+ /** @private */
88
+ class FailedToStartTransportError extends Error {
89
+ /** Constructs a new instance of {@link @microsoft/signalr.FailedToStartTransportError}.
90
+ *
91
+ * @param {string} message A descriptive error message.
92
+ * @param {HttpTransportType} transport The {@link @microsoft/signalr.HttpTransportType} this error occured on.
93
+ */
94
+ constructor(message, transport) {
95
+ const trueProto = new.target.prototype;
96
+ super(message);
97
+ this.transport = transport;
98
+ this.errorType = 'FailedToStartTransportError';
99
+ // Workaround issue in Typescript compiler
100
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
101
+ this.__proto__ = trueProto;
102
+ }
103
+ }
104
+ /** Error thrown when the negotiation with the server failed to complete. */
105
+ /** @private */
106
+ class FailedToNegotiateWithServerError extends Error {
107
+ /** Constructs a new instance of {@link @microsoft/signalr.FailedToNegotiateWithServerError}.
108
+ *
109
+ * @param {string} message A descriptive error message.
110
+ */
111
+ constructor(message) {
112
+ const trueProto = new.target.prototype;
113
+ super(message);
114
+ this.errorType = 'FailedToNegotiateWithServerError';
115
+ // Workaround issue in Typescript compiler
116
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
117
+ this.__proto__ = trueProto;
118
+ }
119
+ }
120
+ /** Error thrown when multiple errors have occured. */
121
+ /** @private */
122
+ class AggregateErrors extends Error {
123
+ /** Constructs a new instance of {@link @microsoft/signalr.AggregateErrors}.
124
+ *
125
+ * @param {string} message A descriptive error message.
126
+ * @param {Error[]} innerErrors The collection of errors this error is aggregating.
127
+ */
128
+ constructor(message, innerErrors) {
129
+ const trueProto = new.target.prototype;
130
+ super(message);
131
+ this.innerErrors = innerErrors;
132
+ // Workaround issue in Typescript compiler
133
+ // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
134
+ this.__proto__ = trueProto;
135
+ }
136
+ }
137
+
138
+ // Licensed to the .NET Foundation under one or more agreements.
139
+ // The .NET Foundation licenses this file to you under the MIT license.
140
+ /** Represents an HTTP response. */
141
+ class HttpResponse {
142
+ constructor(statusCode, statusText, content) {
143
+ this.statusCode = statusCode;
144
+ this.statusText = statusText;
145
+ this.content = content;
146
+ }
147
+ }
148
+ /** Abstraction over an HTTP client.
149
+ *
150
+ * This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.
151
+ */
152
+ class HttpClient {
153
+ get(url, options) {
154
+ return this.send({
155
+ ...options,
156
+ method: "GET",
157
+ url,
158
+ });
159
+ }
160
+ post(url, options) {
161
+ return this.send({
162
+ ...options,
163
+ method: "POST",
164
+ url,
165
+ });
166
+ }
167
+ delete(url, options) {
168
+ return this.send({
169
+ ...options,
170
+ method: "DELETE",
171
+ url,
172
+ });
173
+ }
174
+ /** Gets all cookies that apply to the specified URL.
175
+ *
176
+ * @param url The URL that the cookies are valid for.
177
+ * @returns {string} A string containing all the key-value cookie pairs for the specified URL.
178
+ */
179
+ // @ts-ignore
180
+ getCookieString(url) {
181
+ return "";
182
+ }
183
+ }
184
+
185
+ // Licensed to the .NET Foundation under one or more agreements.
186
+ // The .NET Foundation licenses this file to you under the MIT license.
187
+ // These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.
188
+ /** Indicates the severity of a log message.
189
+ *
190
+ * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.
191
+ */
192
+ var LogLevel;
193
+ (function (LogLevel) {
194
+ /** Log level for very low severity diagnostic messages. */
195
+ LogLevel[LogLevel["Trace"] = 0] = "Trace";
196
+ /** Log level for low severity diagnostic messages. */
197
+ LogLevel[LogLevel["Debug"] = 1] = "Debug";
198
+ /** Log level for informational diagnostic messages. */
199
+ LogLevel[LogLevel["Information"] = 2] = "Information";
200
+ /** Log level for diagnostic messages that indicate a non-fatal problem. */
201
+ LogLevel[LogLevel["Warning"] = 3] = "Warning";
202
+ /** Log level for diagnostic messages that indicate a failure in the current operation. */
203
+ LogLevel[LogLevel["Error"] = 4] = "Error";
204
+ /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */
205
+ LogLevel[LogLevel["Critical"] = 5] = "Critical";
206
+ /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */
207
+ LogLevel[LogLevel["None"] = 6] = "None";
208
+ })(LogLevel || (LogLevel = {}));
209
+
210
+ // Licensed to the .NET Foundation under one or more agreements.
211
+ // The .NET Foundation licenses this file to you under the MIT license.
212
+ /** A logger that does nothing when log messages are sent to it. */
213
+ class NullLogger {
214
+ constructor() { }
215
+ /** @inheritDoc */
216
+ // eslint-disable-next-line
217
+ log(_logLevel, _message) {
218
+ }
219
+ }
220
+ /** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */
221
+ NullLogger.instance = new NullLogger();
222
+
223
+ // Licensed to the .NET Foundation under one or more agreements.
224
+ // Version token that will be replaced by the prepack command
225
+ /** The version of the SignalR client. */
226
+ const VERSION = "6.0.3";
227
+ /** @private */
228
+ class Arg {
229
+ static isRequired(val, name) {
230
+ if (val === null || val === undefined) {
231
+ throw new Error(`The '${name}' argument is required.`);
232
+ }
233
+ }
234
+ static isNotEmpty(val, name) {
235
+ if (!val || val.match(/^\s*$/)) {
236
+ throw new Error(`The '${name}' argument should not be empty.`);
237
+ }
238
+ }
239
+ static isIn(val, values, name) {
240
+ // TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.
241
+ if (!(val in values)) {
242
+ throw new Error(`Unknown ${name} value: ${val}.`);
243
+ }
244
+ }
245
+ }
246
+ /** @private */
247
+ class Platform {
248
+ // react-native has a window but no document so we should check both
249
+ static get isBrowser() {
250
+ return typeof window === "object" && typeof window.document === "object";
251
+ }
252
+ // WebWorkers don't have a window object so the isBrowser check would fail
253
+ static get isWebWorker() {
254
+ return typeof self === "object" && "importScripts" in self;
255
+ }
256
+ // react-native has a window but no document
257
+ static get isReactNative() {
258
+ return typeof window === "object" && typeof window.document === "undefined";
259
+ }
260
+ // Node apps shouldn't have a window object, but WebWorkers don't either
261
+ // so we need to check for both WebWorker and window
262
+ static get isNode() {
263
+ return !this.isBrowser && !this.isWebWorker && !this.isReactNative;
264
+ }
265
+ }
266
+ /** @private */
267
+ function getDataDetail(data, includeContent) {
268
+ let detail = "";
269
+ if (isArrayBuffer(data)) {
270
+ detail = `Binary data of length ${data.byteLength}`;
271
+ if (includeContent) {
272
+ detail += `. Content: '${formatArrayBuffer(data)}'`;
273
+ }
274
+ }
275
+ else if (typeof data === "string") {
276
+ detail = `String data of length ${data.length}`;
277
+ if (includeContent) {
278
+ detail += `. Content: '${data}'`;
279
+ }
280
+ }
281
+ return detail;
282
+ }
283
+ /** @private */
284
+ function formatArrayBuffer(data) {
285
+ const view = new Uint8Array(data);
286
+ // Uint8Array.map only supports returning another Uint8Array?
287
+ let str = "";
288
+ view.forEach((num) => {
289
+ const pad = num < 16 ? "0" : "";
290
+ str += `0x${pad}${num.toString(16)} `;
291
+ });
292
+ // Trim of trailing space.
293
+ return str.substr(0, str.length - 1);
294
+ }
295
+ // Also in signalr-protocol-msgpack/Utils.ts
296
+ /** @private */
297
+ function isArrayBuffer(val) {
298
+ return val && typeof ArrayBuffer !== "undefined" &&
299
+ (val instanceof ArrayBuffer ||
300
+ // Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
301
+ (val.constructor && val.constructor.name === "ArrayBuffer"));
302
+ }
303
+ /** @private */
304
+ async function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, options) {
305
+ let headers = {};
306
+ if (accessTokenFactory) {
307
+ const token = await accessTokenFactory();
308
+ if (token) {
309
+ headers = {
310
+ ["Authorization"]: `Bearer ${token}`,
311
+ };
312
+ }
313
+ }
314
+ const [name, value] = getUserAgentHeader();
315
+ headers[name] = value;
316
+ logger.log(LogLevel.Trace, `(${transportName} transport) sending data. ${getDataDetail(content, options.logMessageContent)}.`);
317
+ const responseType = isArrayBuffer(content) ? "arraybuffer" : "text";
318
+ const response = await httpClient.post(url, {
319
+ content,
320
+ headers: { ...headers, ...options.headers },
321
+ responseType,
322
+ timeout: options.timeout,
323
+ withCredentials: options.withCredentials,
324
+ });
325
+ logger.log(LogLevel.Trace, `(${transportName} transport) request complete. Response status: ${response.statusCode}.`);
326
+ }
327
+ /** @private */
328
+ function createLogger(logger) {
329
+ if (logger === undefined) {
330
+ return new ConsoleLogger(LogLevel.Information);
331
+ }
332
+ if (logger === null) {
333
+ return NullLogger.instance;
334
+ }
335
+ if (logger.log !== undefined) {
336
+ return logger;
337
+ }
338
+ return new ConsoleLogger(logger);
339
+ }
340
+ /** @private */
341
+ class SubjectSubscription {
342
+ constructor(subject, observer) {
343
+ this._subject = subject;
344
+ this._observer = observer;
345
+ }
346
+ dispose() {
347
+ const index = this._subject.observers.indexOf(this._observer);
348
+ if (index > -1) {
349
+ this._subject.observers.splice(index, 1);
350
+ }
351
+ if (this._subject.observers.length === 0 && this._subject.cancelCallback) {
352
+ this._subject.cancelCallback().catch((_) => { });
353
+ }
354
+ }
355
+ }
356
+ /** @private */
357
+ class ConsoleLogger {
358
+ constructor(minimumLogLevel) {
359
+ this._minLevel = minimumLogLevel;
360
+ this.out = console;
361
+ }
362
+ log(logLevel, message) {
363
+ if (logLevel >= this._minLevel) {
364
+ const msg = `[${new Date().toISOString()}] ${LogLevel[logLevel]}: ${message}`;
365
+ switch (logLevel) {
366
+ case LogLevel.Critical:
367
+ case LogLevel.Error:
368
+ this.out.error(msg);
369
+ break;
370
+ case LogLevel.Warning:
371
+ this.out.warn(msg);
372
+ break;
373
+ case LogLevel.Information:
374
+ this.out.info(msg);
375
+ break;
376
+ default:
377
+ // console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug
378
+ this.out.log(msg);
379
+ break;
380
+ }
381
+ }
382
+ }
383
+ }
384
+ /** @private */
385
+ function getUserAgentHeader() {
386
+ let userAgentHeaderName = "X-SignalR-User-Agent";
387
+ if (Platform.isNode) {
388
+ userAgentHeaderName = "User-Agent";
389
+ }
390
+ return [userAgentHeaderName, constructUserAgent(VERSION, getOsName(), getRuntime(), getRuntimeVersion())];
391
+ }
392
+ /** @private */
393
+ function constructUserAgent(version, os, runtime, runtimeVersion) {
394
+ // Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])
395
+ let userAgent = "Microsoft SignalR/";
396
+ const majorAndMinor = version.split(".");
397
+ userAgent += `${majorAndMinor[0]}.${majorAndMinor[1]}`;
398
+ userAgent += ` (${version}; `;
399
+ if (os && os !== "") {
400
+ userAgent += `${os}; `;
401
+ }
402
+ else {
403
+ userAgent += "Unknown OS; ";
404
+ }
405
+ userAgent += `${runtime}`;
406
+ if (runtimeVersion) {
407
+ userAgent += `; ${runtimeVersion}`;
408
+ }
409
+ else {
410
+ userAgent += "; Unknown Runtime Version";
411
+ }
412
+ userAgent += ")";
413
+ return userAgent;
414
+ }
415
+ // eslint-disable-next-line spaced-comment
416
+ /*#__PURE__*/ function getOsName() {
417
+ if (Platform.isNode) {
418
+ switch (process.platform) {
419
+ case "win32":
420
+ return "Windows NT";
421
+ case "darwin":
422
+ return "macOS";
423
+ case "linux":
424
+ return "Linux";
425
+ default:
426
+ return process.platform;
427
+ }
428
+ }
429
+ else {
430
+ return "";
431
+ }
432
+ }
433
+ // eslint-disable-next-line spaced-comment
434
+ /*#__PURE__*/ function getRuntimeVersion() {
435
+ if (Platform.isNode) {
436
+ return process.versions.node;
437
+ }
438
+ return undefined;
439
+ }
440
+ function getRuntime() {
441
+ if (Platform.isNode) {
442
+ return "NodeJS";
443
+ }
444
+ else {
445
+ return "Browser";
446
+ }
447
+ }
448
+ /** @private */
449
+ function getErrorString(e) {
450
+ if (e.stack) {
451
+ return e.stack;
452
+ }
453
+ else if (e.message) {
454
+ return e.message;
455
+ }
456
+ return `${e}`;
457
+ }
458
+ /** @private */
459
+ function getGlobalThis() {
460
+ // globalThis is semi-new and not available in Node until v12
461
+ if (typeof globalThis !== "undefined") {
462
+ return globalThis;
463
+ }
464
+ if (typeof self !== "undefined") {
465
+ return self;
466
+ }
467
+ if (typeof window !== "undefined") {
468
+ return window;
469
+ }
470
+ if (typeof global !== "undefined") {
471
+ return global;
472
+ }
473
+ throw new Error("could not find global");
474
+ }
475
+
476
+ // Licensed to the .NET Foundation under one or more agreements.
477
+ class FetchHttpClient extends HttpClient {
478
+ constructor(logger) {
479
+ super();
480
+ this._logger = logger;
481
+ if (typeof fetch === "undefined") {
482
+ // In order to ignore the dynamic require in webpack builds we need to do this magic
483
+ // @ts-ignore: TS doesn't know about these names
484
+ const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
485
+ // Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests
486
+ this._jar = new (requireFunc("tough-cookie")).CookieJar();
487
+ this._fetchType = requireFunc("node-fetch");
488
+ // node-fetch doesn't have a nice API for getting and setting cookies
489
+ // fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one
490
+ this._fetchType = requireFunc("fetch-cookie")(this._fetchType, this._jar);
491
+ }
492
+ else {
493
+ this._fetchType = fetch.bind(getGlobalThis());
494
+ }
495
+ if (typeof AbortController === "undefined") {
496
+ // In order to ignore the dynamic require in webpack builds we need to do this magic
497
+ // @ts-ignore: TS doesn't know about these names
498
+ const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
499
+ // Node needs EventListener methods on AbortController which our custom polyfill doesn't provide
500
+ this._abortControllerType = requireFunc("abort-controller");
501
+ }
502
+ else {
503
+ this._abortControllerType = AbortController;
504
+ }
505
+ }
506
+ /** @inheritDoc */
507
+ async send(request) {
508
+ // Check that abort was not signaled before calling send
509
+ if (request.abortSignal && request.abortSignal.aborted) {
510
+ throw new AbortError();
511
+ }
512
+ if (!request.method) {
513
+ throw new Error("No method defined.");
514
+ }
515
+ if (!request.url) {
516
+ throw new Error("No url defined.");
517
+ }
518
+ const abortController = new this._abortControllerType();
519
+ let error;
520
+ // Hook our abortSignal into the abort controller
521
+ if (request.abortSignal) {
522
+ request.abortSignal.onabort = () => {
523
+ abortController.abort();
524
+ error = new AbortError();
525
+ };
526
+ }
527
+ // If a timeout has been passed in, setup a timeout to call abort
528
+ // Type needs to be any to fit window.setTimeout and NodeJS.setTimeout
529
+ let timeoutId = null;
530
+ if (request.timeout) {
531
+ const msTimeout = request.timeout;
532
+ timeoutId = setTimeout(() => {
533
+ abortController.abort();
534
+ this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);
535
+ error = new TimeoutError();
536
+ }, msTimeout);
537
+ }
538
+ let response;
539
+ try {
540
+ response = await this._fetchType(request.url, {
541
+ body: request.content,
542
+ cache: "no-cache",
543
+ credentials: request.withCredentials === true ? "include" : "same-origin",
544
+ headers: {
545
+ "Content-Type": "text/plain;charset=UTF-8",
546
+ "X-Requested-With": "XMLHttpRequest",
547
+ ...request.headers,
548
+ },
549
+ method: request.method,
550
+ mode: "cors",
551
+ redirect: "follow",
552
+ signal: abortController.signal,
553
+ });
554
+ }
555
+ catch (e) {
556
+ if (error) {
557
+ throw error;
558
+ }
559
+ this._logger.log(LogLevel.Warning, `Error from HTTP request. ${e}.`);
560
+ throw e;
561
+ }
562
+ finally {
563
+ if (timeoutId) {
564
+ clearTimeout(timeoutId);
565
+ }
566
+ if (request.abortSignal) {
567
+ request.abortSignal.onabort = null;
568
+ }
569
+ }
570
+ if (!response.ok) {
571
+ const errorMessage = await deserializeContent(response, "text");
572
+ throw new HttpError(errorMessage || response.statusText, response.status);
573
+ }
574
+ const content = deserializeContent(response, request.responseType);
575
+ const payload = await content;
576
+ return new HttpResponse(response.status, response.statusText, payload);
577
+ }
578
+ getCookieString(url) {
579
+ let cookies = "";
580
+ if (Platform.isNode && this._jar) {
581
+ // @ts-ignore: unused variable
582
+ this._jar.getCookies(url, (e, c) => cookies = c.join("; "));
583
+ }
584
+ return cookies;
585
+ }
586
+ }
587
+ function deserializeContent(response, responseType) {
588
+ let content;
589
+ switch (responseType) {
590
+ case "arraybuffer":
591
+ content = response.arrayBuffer();
592
+ break;
593
+ case "text":
594
+ content = response.text();
595
+ break;
596
+ case "blob":
597
+ case "document":
598
+ case "json":
599
+ throw new Error(`${responseType} is not supported.`);
600
+ default:
601
+ content = response.text();
602
+ break;
603
+ }
604
+ return content;
605
+ }
606
+
607
+ // Licensed to the .NET Foundation under one or more agreements.
608
+ class XhrHttpClient extends HttpClient {
609
+ constructor(logger) {
610
+ super();
611
+ this._logger = logger;
612
+ }
613
+ /** @inheritDoc */
614
+ send(request) {
615
+ // Check that abort was not signaled before calling send
616
+ if (request.abortSignal && request.abortSignal.aborted) {
617
+ return Promise.reject(new AbortError());
618
+ }
619
+ if (!request.method) {
620
+ return Promise.reject(new Error("No method defined."));
621
+ }
622
+ if (!request.url) {
623
+ return Promise.reject(new Error("No url defined."));
624
+ }
625
+ return new Promise((resolve, reject) => {
626
+ const xhr = new XMLHttpRequest();
627
+ xhr.open(request.method, request.url, true);
628
+ xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;
629
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
630
+ // Explicitly setting the Content-Type header for React Native on Android platform.
631
+ xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
632
+ const headers = request.headers;
633
+ if (headers) {
634
+ Object.keys(headers)
635
+ .forEach((header) => {
636
+ xhr.setRequestHeader(header, headers[header]);
637
+ });
638
+ }
639
+ if (request.responseType) {
640
+ xhr.responseType = request.responseType;
641
+ }
642
+ if (request.abortSignal) {
643
+ request.abortSignal.onabort = () => {
644
+ xhr.abort();
645
+ reject(new AbortError());
646
+ };
647
+ }
648
+ if (request.timeout) {
649
+ xhr.timeout = request.timeout;
650
+ }
651
+ xhr.onload = () => {
652
+ if (request.abortSignal) {
653
+ request.abortSignal.onabort = null;
654
+ }
655
+ if (xhr.status >= 200 && xhr.status < 300) {
656
+ resolve(new HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));
657
+ }
658
+ else {
659
+ reject(new HttpError(xhr.response || xhr.responseText || xhr.statusText, xhr.status));
660
+ }
661
+ };
662
+ xhr.onerror = () => {
663
+ this._logger.log(LogLevel.Warning, `Error from HTTP request. ${xhr.status}: ${xhr.statusText}.`);
664
+ reject(new HttpError(xhr.statusText, xhr.status));
665
+ };
666
+ xhr.ontimeout = () => {
667
+ this._logger.log(LogLevel.Warning, `Timeout from HTTP request.`);
668
+ reject(new TimeoutError());
669
+ };
670
+ xhr.send(request.content || "");
671
+ });
672
+ }
673
+ }
674
+
675
+ // Licensed to the .NET Foundation under one or more agreements.
676
+ /** Default implementation of {@link @microsoft/signalr.HttpClient}. */
677
+ class DefaultHttpClient extends HttpClient {
678
+ /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
679
+ constructor(logger) {
680
+ super();
681
+ if (typeof fetch !== "undefined" || Platform.isNode) {
682
+ this._httpClient = new FetchHttpClient(logger);
683
+ }
684
+ else if (typeof XMLHttpRequest !== "undefined") {
685
+ this._httpClient = new XhrHttpClient(logger);
686
+ }
687
+ else {
688
+ throw new Error("No usable HttpClient found.");
689
+ }
690
+ }
691
+ /** @inheritDoc */
692
+ send(request) {
693
+ // Check that abort was not signaled before calling send
694
+ if (request.abortSignal && request.abortSignal.aborted) {
695
+ return Promise.reject(new AbortError());
696
+ }
697
+ if (!request.method) {
698
+ return Promise.reject(new Error("No method defined."));
699
+ }
700
+ if (!request.url) {
701
+ return Promise.reject(new Error("No url defined."));
702
+ }
703
+ return this._httpClient.send(request);
704
+ }
705
+ getCookieString(url) {
706
+ return this._httpClient.getCookieString(url);
707
+ }
708
+ }
709
+
710
+ // Licensed to the .NET Foundation under one or more agreements.
711
+ // The .NET Foundation licenses this file to you under the MIT license.
712
+ // Not exported from index
713
+ /** @private */
714
+ class TextMessageFormat {
715
+ static write(output) {
716
+ return `${output}${TextMessageFormat.RecordSeparator}`;
717
+ }
718
+ static parse(input) {
719
+ if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
720
+ throw new Error("Message is incomplete.");
721
+ }
722
+ const messages = input.split(TextMessageFormat.RecordSeparator);
723
+ messages.pop();
724
+ return messages;
725
+ }
726
+ }
727
+ TextMessageFormat.RecordSeparatorCode = 0x1e;
728
+ TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);
729
+
730
+ // Licensed to the .NET Foundation under one or more agreements.
731
+ /** @private */
732
+ class HandshakeProtocol {
733
+ // Handshake request is always JSON
734
+ writeHandshakeRequest(handshakeRequest) {
735
+ return TextMessageFormat.write(JSON.stringify(handshakeRequest));
736
+ }
737
+ parseHandshakeResponse(data) {
738
+ let messageData;
739
+ let remainingData;
740
+ if (isArrayBuffer(data)) {
741
+ // Format is binary but still need to read JSON text from handshake response
742
+ const binaryData = new Uint8Array(data);
743
+ const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);
744
+ if (separatorIndex === -1) {
745
+ throw new Error("Message is incomplete.");
746
+ }
747
+ // content before separator is handshake response
748
+ // optional content after is additional messages
749
+ const responseLength = separatorIndex + 1;
750
+ messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));
751
+ remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
752
+ }
753
+ else {
754
+ const textData = data;
755
+ const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);
756
+ if (separatorIndex === -1) {
757
+ throw new Error("Message is incomplete.");
758
+ }
759
+ // content before separator is handshake response
760
+ // optional content after is additional messages
761
+ const responseLength = separatorIndex + 1;
762
+ messageData = textData.substring(0, responseLength);
763
+ remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
764
+ }
765
+ // At this point we should have just the single handshake message
766
+ const messages = TextMessageFormat.parse(messageData);
767
+ const response = JSON.parse(messages[0]);
768
+ if (response.type) {
769
+ throw new Error("Expected a handshake response from the server.");
770
+ }
771
+ const responseMessage = response;
772
+ // multiple messages could have arrived with handshake
773
+ // return additional data to be parsed as usual, or null if all parsed
774
+ return [remainingData, responseMessage];
775
+ }
776
+ }
777
+
778
+ // Licensed to the .NET Foundation under one or more agreements.
779
+ // The .NET Foundation licenses this file to you under the MIT license.
780
+ /** Defines the type of a Hub Message. */
781
+ var MessageType;
782
+ (function (MessageType) {
783
+ /** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */
784
+ MessageType[MessageType["Invocation"] = 1] = "Invocation";
785
+ /** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */
786
+ MessageType[MessageType["StreamItem"] = 2] = "StreamItem";
787
+ /** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */
788
+ MessageType[MessageType["Completion"] = 3] = "Completion";
789
+ /** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */
790
+ MessageType[MessageType["StreamInvocation"] = 4] = "StreamInvocation";
791
+ /** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */
792
+ MessageType[MessageType["CancelInvocation"] = 5] = "CancelInvocation";
793
+ /** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */
794
+ MessageType[MessageType["Ping"] = 6] = "Ping";
795
+ /** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */
796
+ MessageType[MessageType["Close"] = 7] = "Close";
797
+ })(MessageType || (MessageType = {}));
798
+
799
+ // Licensed to the .NET Foundation under one or more agreements.
800
+ /** Stream implementation to stream items to the server. */
801
+ class Subject {
802
+ constructor() {
803
+ this.observers = [];
804
+ }
805
+ next(item) {
806
+ for (const observer of this.observers) {
807
+ observer.next(item);
808
+ }
809
+ }
810
+ error(err) {
811
+ for (const observer of this.observers) {
812
+ if (observer.error) {
813
+ observer.error(err);
814
+ }
815
+ }
816
+ }
817
+ complete() {
818
+ for (const observer of this.observers) {
819
+ if (observer.complete) {
820
+ observer.complete();
821
+ }
822
+ }
823
+ }
824
+ subscribe(observer) {
825
+ this.observers.push(observer);
826
+ return new SubjectSubscription(this, observer);
827
+ }
828
+ }
829
+
830
+ // Licensed to the .NET Foundation under one or more agreements.
831
+ const DEFAULT_TIMEOUT_IN_MS = 30 * 1000;
832
+ const DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;
833
+ /** Describes the current state of the {@link HubConnection} to the server. */
834
+ var HubConnectionState;
835
+ (function (HubConnectionState) {
836
+ /** The hub connection is disconnected. */
837
+ HubConnectionState["Disconnected"] = "Disconnected";
838
+ /** The hub connection is connecting. */
839
+ HubConnectionState["Connecting"] = "Connecting";
840
+ /** The hub connection is connected. */
841
+ HubConnectionState["Connected"] = "Connected";
842
+ /** The hub connection is disconnecting. */
843
+ HubConnectionState["Disconnecting"] = "Disconnecting";
844
+ /** The hub connection is reconnecting. */
845
+ HubConnectionState["Reconnecting"] = "Reconnecting";
846
+ })(HubConnectionState || (HubConnectionState = {}));
847
+ /** Represents a connection to a SignalR Hub. */
848
+ class HubConnection {
849
+ constructor(connection, logger, protocol, reconnectPolicy) {
850
+ this._nextKeepAlive = 0;
851
+ this._freezeEventListener = () => {
852
+ 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");
853
+ };
854
+ Arg.isRequired(connection, "connection");
855
+ Arg.isRequired(logger, "logger");
856
+ Arg.isRequired(protocol, "protocol");
857
+ this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;
858
+ this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;
859
+ this._logger = logger;
860
+ this._protocol = protocol;
861
+ this.connection = connection;
862
+ this._reconnectPolicy = reconnectPolicy;
863
+ this._handshakeProtocol = new HandshakeProtocol();
864
+ this.connection.onreceive = (data) => this._processIncomingData(data);
865
+ this.connection.onclose = (error) => this._connectionClosed(error);
866
+ this._callbacks = {};
867
+ this._methods = {};
868
+ this._closedCallbacks = [];
869
+ this._reconnectingCallbacks = [];
870
+ this._reconnectedCallbacks = [];
871
+ this._invocationId = 0;
872
+ this._receivedHandshakeResponse = false;
873
+ this._connectionState = HubConnectionState.Disconnected;
874
+ this._connectionStarted = false;
875
+ this._cachedPingMessage = this._protocol.writeMessage({ type: MessageType.Ping });
876
+ }
877
+ /** @internal */
878
+ // Using a public static factory method means we can have a private constructor and an _internal_
879
+ // create method that can be used by HubConnectionBuilder. An "internal" constructor would just
880
+ // be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
881
+ // public parameter-less constructor.
882
+ static create(connection, logger, protocol, reconnectPolicy) {
883
+ return new HubConnection(connection, logger, protocol, reconnectPolicy);
884
+ }
885
+ /** Indicates the state of the {@link HubConnection} to the server. */
886
+ get state() {
887
+ return this._connectionState;
888
+ }
889
+ /** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
890
+ * in the disconnected state or if the negotiation step was skipped.
891
+ */
892
+ get connectionId() {
893
+ return this.connection ? (this.connection.connectionId || null) : null;
894
+ }
895
+ /** Indicates the url of the {@link HubConnection} to the server. */
896
+ get baseUrl() {
897
+ return this.connection.baseUrl || "";
898
+ }
899
+ /**
900
+ * Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
901
+ * Reconnecting states.
902
+ * @param {string} url The url to connect to.
903
+ */
904
+ set baseUrl(url) {
905
+ if (this._connectionState !== HubConnectionState.Disconnected && this._connectionState !== HubConnectionState.Reconnecting) {
906
+ throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
907
+ }
908
+ if (!url) {
909
+ throw new Error("The HubConnection url must be a valid url.");
910
+ }
911
+ this.connection.baseUrl = url;
912
+ }
913
+ /** Starts the connection.
914
+ *
915
+ * @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
916
+ */
917
+ start() {
918
+ this._startPromise = this._startWithStateTransitions();
919
+ return this._startPromise;
920
+ }
921
+ async _startWithStateTransitions() {
922
+ if (this._connectionState !== HubConnectionState.Disconnected) {
923
+ return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));
924
+ }
925
+ this._connectionState = HubConnectionState.Connecting;
926
+ this._logger.log(LogLevel.Debug, "Starting HubConnection.");
927
+ try {
928
+ await this._startInternal();
929
+ if (Platform.isBrowser) {
930
+ // Log when the browser freezes the tab so users know why their connection unexpectedly stopped working
931
+ window.document.addEventListener("freeze", this._freezeEventListener);
932
+ }
933
+ this._connectionState = HubConnectionState.Connected;
934
+ this._connectionStarted = true;
935
+ this._logger.log(LogLevel.Debug, "HubConnection connected successfully.");
936
+ }
937
+ catch (e) {
938
+ this._connectionState = HubConnectionState.Disconnected;
939
+ this._logger.log(LogLevel.Debug, `HubConnection failed to start successfully because of error '${e}'.`);
940
+ return Promise.reject(e);
941
+ }
942
+ }
943
+ async _startInternal() {
944
+ this._stopDuringStartError = undefined;
945
+ this._receivedHandshakeResponse = false;
946
+ // Set up the promise before any connection is (re)started otherwise it could race with received messages
947
+ const handshakePromise = new Promise((resolve, reject) => {
948
+ this._handshakeResolver = resolve;
949
+ this._handshakeRejecter = reject;
950
+ });
951
+ await this.connection.start(this._protocol.transferFormat);
952
+ try {
953
+ const handshakeRequest = {
954
+ protocol: this._protocol.name,
955
+ version: this._protocol.version,
956
+ };
957
+ this._logger.log(LogLevel.Debug, "Sending handshake request.");
958
+ await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(handshakeRequest));
959
+ this._logger.log(LogLevel.Information, `Using HubProtocol '${this._protocol.name}'.`);
960
+ // defensively cleanup timeout in case we receive a message from the server before we finish start
961
+ this._cleanupTimeout();
962
+ this._resetTimeoutPeriod();
963
+ this._resetKeepAliveInterval();
964
+ await handshakePromise;
965
+ // It's important to check the stopDuringStartError instead of just relying on the handshakePromise
966
+ // being rejected on close, because this continuation can run after both the handshake completed successfully
967
+ // and the connection was closed.
968
+ if (this._stopDuringStartError) {
969
+ // It's important to throw instead of returning a rejected promise, because we don't want to allow any state
970
+ // transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise
971
+ // will cause the calling continuation to get scheduled to run later.
972
+ // eslint-disable-next-line @typescript-eslint/no-throw-literal
973
+ throw this._stopDuringStartError;
974
+ }
975
+ }
976
+ catch (e) {
977
+ this._logger.log(LogLevel.Debug, `Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`);
978
+ this._cleanupTimeout();
979
+ this._cleanupPingTimer();
980
+ // HttpConnection.stop() should not complete until after the onclose callback is invoked.
981
+ // This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
982
+ await this.connection.stop(e);
983
+ throw e;
984
+ }
985
+ }
986
+ /** Stops the connection.
987
+ *
988
+ * @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
989
+ */
990
+ async stop() {
991
+ // Capture the start promise before the connection might be restarted in an onclose callback.
992
+ const startPromise = this._startPromise;
993
+ this._stopPromise = this._stopInternal();
994
+ await this._stopPromise;
995
+ try {
996
+ // Awaiting undefined continues immediately
997
+ await startPromise;
998
+ }
999
+ catch (e) {
1000
+ // This exception is returned to the user as a rejected Promise from the start method.
1001
+ }
1002
+ }
1003
+ _stopInternal(error) {
1004
+ if (this._connectionState === HubConnectionState.Disconnected) {
1005
+ this._logger.log(LogLevel.Debug, `Call to HubConnection.stop(${error}) ignored because it is already in the disconnected state.`);
1006
+ return Promise.resolve();
1007
+ }
1008
+ if (this._connectionState === HubConnectionState.Disconnecting) {
1009
+ this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
1010
+ return this._stopPromise;
1011
+ }
1012
+ this._connectionState = HubConnectionState.Disconnecting;
1013
+ this._logger.log(LogLevel.Debug, "Stopping HubConnection.");
1014
+ if (this._reconnectDelayHandle) {
1015
+ // We're in a reconnect delay which means the underlying connection is currently already stopped.
1016
+ // Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and
1017
+ // fire the onclose callbacks.
1018
+ this._logger.log(LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
1019
+ clearTimeout(this._reconnectDelayHandle);
1020
+ this._reconnectDelayHandle = undefined;
1021
+ this._completeClose();
1022
+ return Promise.resolve();
1023
+ }
1024
+ this._cleanupTimeout();
1025
+ this._cleanupPingTimer();
1026
+ this._stopDuringStartError = error || new Error("The connection was stopped before the hub handshake could complete.");
1027
+ // HttpConnection.stop() should not complete until after either HttpConnection.start() fails
1028
+ // or the onclose callback is invoked. The onclose callback will transition the HubConnection
1029
+ // to the disconnected state if need be before HttpConnection.stop() completes.
1030
+ return this.connection.stop(error);
1031
+ }
1032
+ /** Invokes a streaming hub method on the server using the specified name and arguments.
1033
+ *
1034
+ * @typeparam T The type of the items returned by the server.
1035
+ * @param {string} methodName The name of the server method to invoke.
1036
+ * @param {any[]} args The arguments used to invoke the server method.
1037
+ * @returns {IStreamResult<T>} An object that yields results from the server as they are received.
1038
+ */
1039
+ stream(methodName, ...args) {
1040
+ const [streams, streamIds] = this._replaceStreamingParams(args);
1041
+ const invocationDescriptor = this._createStreamInvocation(methodName, args, streamIds);
1042
+ // eslint-disable-next-line prefer-const
1043
+ let promiseQueue;
1044
+ const subject = new Subject();
1045
+ subject.cancelCallback = () => {
1046
+ const cancelInvocation = this._createCancelInvocation(invocationDescriptor.invocationId);
1047
+ delete this._callbacks[invocationDescriptor.invocationId];
1048
+ return promiseQueue.then(() => {
1049
+ return this._sendWithProtocol(cancelInvocation);
1050
+ });
1051
+ };
1052
+ this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
1053
+ if (error) {
1054
+ subject.error(error);
1055
+ return;
1056
+ }
1057
+ else if (invocationEvent) {
1058
+ // invocationEvent will not be null when an error is not passed to the callback
1059
+ if (invocationEvent.type === MessageType.Completion) {
1060
+ if (invocationEvent.error) {
1061
+ subject.error(new Error(invocationEvent.error));
1062
+ }
1063
+ else {
1064
+ subject.complete();
1065
+ }
1066
+ }
1067
+ else {
1068
+ subject.next((invocationEvent.item));
1069
+ }
1070
+ }
1071
+ };
1072
+ promiseQueue = this._sendWithProtocol(invocationDescriptor)
1073
+ .catch((e) => {
1074
+ subject.error(e);
1075
+ delete this._callbacks[invocationDescriptor.invocationId];
1076
+ });
1077
+ this._launchStreams(streams, promiseQueue);
1078
+ return subject;
1079
+ }
1080
+ _sendMessage(message) {
1081
+ this._resetKeepAliveInterval();
1082
+ return this.connection.send(message);
1083
+ }
1084
+ /**
1085
+ * Sends a js object to the server.
1086
+ * @param message The js object to serialize and send.
1087
+ */
1088
+ _sendWithProtocol(message) {
1089
+ return this._sendMessage(this._protocol.writeMessage(message));
1090
+ }
1091
+ /** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
1092
+ *
1093
+ * The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
1094
+ * be processing the invocation.
1095
+ *
1096
+ * @param {string} methodName The name of the server method to invoke.
1097
+ * @param {any[]} args The arguments used to invoke the server method.
1098
+ * @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
1099
+ */
1100
+ send(methodName, ...args) {
1101
+ const [streams, streamIds] = this._replaceStreamingParams(args);
1102
+ const sendPromise = this._sendWithProtocol(this._createInvocation(methodName, args, true, streamIds));
1103
+ this._launchStreams(streams, sendPromise);
1104
+ return sendPromise;
1105
+ }
1106
+ /** Invokes a hub method on the server using the specified name and arguments.
1107
+ *
1108
+ * The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
1109
+ * resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
1110
+ * resolving the Promise.
1111
+ *
1112
+ * @typeparam T The expected return type.
1113
+ * @param {string} methodName The name of the server method to invoke.
1114
+ * @param {any[]} args The arguments used to invoke the server method.
1115
+ * @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
1116
+ */
1117
+ invoke(methodName, ...args) {
1118
+ const [streams, streamIds] = this._replaceStreamingParams(args);
1119
+ const invocationDescriptor = this._createInvocation(methodName, args, false, streamIds);
1120
+ const p = new Promise((resolve, reject) => {
1121
+ // invocationId will always have a value for a non-blocking invocation
1122
+ this._callbacks[invocationDescriptor.invocationId] = (invocationEvent, error) => {
1123
+ if (error) {
1124
+ reject(error);
1125
+ return;
1126
+ }
1127
+ else if (invocationEvent) {
1128
+ // invocationEvent will not be null when an error is not passed to the callback
1129
+ if (invocationEvent.type === MessageType.Completion) {
1130
+ if (invocationEvent.error) {
1131
+ reject(new Error(invocationEvent.error));
1132
+ }
1133
+ else {
1134
+ resolve(invocationEvent.result);
1135
+ }
1136
+ }
1137
+ else {
1138
+ reject(new Error(`Unexpected message type: ${invocationEvent.type}`));
1139
+ }
1140
+ }
1141
+ };
1142
+ const promiseQueue = this._sendWithProtocol(invocationDescriptor)
1143
+ .catch((e) => {
1144
+ reject(e);
1145
+ // invocationId will always have a value for a non-blocking invocation
1146
+ delete this._callbacks[invocationDescriptor.invocationId];
1147
+ });
1148
+ this._launchStreams(streams, promiseQueue);
1149
+ });
1150
+ return p;
1151
+ }
1152
+ /** Registers a handler that will be invoked when the hub method with the specified method name is invoked.
1153
+ *
1154
+ * @param {string} methodName The name of the hub method to define.
1155
+ * @param {Function} newMethod The handler that will be raised when the hub method is invoked.
1156
+ */
1157
+ on(methodName, newMethod) {
1158
+ if (!methodName || !newMethod) {
1159
+ return;
1160
+ }
1161
+ methodName = methodName.toLowerCase();
1162
+ if (!this._methods[methodName]) {
1163
+ this._methods[methodName] = [];
1164
+ }
1165
+ // Preventing adding the same handler multiple times.
1166
+ if (this._methods[methodName].indexOf(newMethod) !== -1) {
1167
+ return;
1168
+ }
1169
+ this._methods[methodName].push(newMethod);
1170
+ }
1171
+ off(methodName, method) {
1172
+ if (!methodName) {
1173
+ return;
1174
+ }
1175
+ methodName = methodName.toLowerCase();
1176
+ const handlers = this._methods[methodName];
1177
+ if (!handlers) {
1178
+ return;
1179
+ }
1180
+ if (method) {
1181
+ const removeIdx = handlers.indexOf(method);
1182
+ if (removeIdx !== -1) {
1183
+ handlers.splice(removeIdx, 1);
1184
+ if (handlers.length === 0) {
1185
+ delete this._methods[methodName];
1186
+ }
1187
+ }
1188
+ }
1189
+ else {
1190
+ delete this._methods[methodName];
1191
+ }
1192
+ }
1193
+ /** Registers a handler that will be invoked when the connection is closed.
1194
+ *
1195
+ * @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).
1196
+ */
1197
+ onclose(callback) {
1198
+ if (callback) {
1199
+ this._closedCallbacks.push(callback);
1200
+ }
1201
+ }
1202
+ /** Registers a handler that will be invoked when the connection starts reconnecting.
1203
+ *
1204
+ * @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).
1205
+ */
1206
+ onreconnecting(callback) {
1207
+ if (callback) {
1208
+ this._reconnectingCallbacks.push(callback);
1209
+ }
1210
+ }
1211
+ /** Registers a handler that will be invoked when the connection successfully reconnects.
1212
+ *
1213
+ * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
1214
+ */
1215
+ onreconnected(callback) {
1216
+ if (callback) {
1217
+ this._reconnectedCallbacks.push(callback);
1218
+ }
1219
+ }
1220
+ _processIncomingData(data) {
1221
+ this._cleanupTimeout();
1222
+ if (!this._receivedHandshakeResponse) {
1223
+ data = this._processHandshakeResponse(data);
1224
+ this._receivedHandshakeResponse = true;
1225
+ }
1226
+ // Data may have all been read when processing handshake response
1227
+ if (data) {
1228
+ // Parse the messages
1229
+ const messages = this._protocol.parseMessages(data, this._logger);
1230
+ for (const message of messages) {
1231
+ switch (message.type) {
1232
+ case MessageType.Invocation:
1233
+ this._invokeClientMethod(message);
1234
+ break;
1235
+ case MessageType.StreamItem:
1236
+ case MessageType.Completion: {
1237
+ const callback = this._callbacks[message.invocationId];
1238
+ if (callback) {
1239
+ if (message.type === MessageType.Completion) {
1240
+ delete this._callbacks[message.invocationId];
1241
+ }
1242
+ try {
1243
+ callback(message);
1244
+ }
1245
+ catch (e) {
1246
+ this._logger.log(LogLevel.Error, `Stream callback threw error: ${getErrorString(e)}`);
1247
+ }
1248
+ }
1249
+ break;
1250
+ }
1251
+ case MessageType.Ping:
1252
+ // Don't care about pings
1253
+ break;
1254
+ case MessageType.Close: {
1255
+ this._logger.log(LogLevel.Information, "Close message received from server.");
1256
+ const error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined;
1257
+ if (message.allowReconnect === true) {
1258
+ // It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,
1259
+ // this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.
1260
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1261
+ this.connection.stop(error);
1262
+ }
1263
+ else {
1264
+ // We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.
1265
+ this._stopPromise = this._stopInternal(error);
1266
+ }
1267
+ break;
1268
+ }
1269
+ default:
1270
+ this._logger.log(LogLevel.Warning, `Invalid message type: ${message.type}.`);
1271
+ break;
1272
+ }
1273
+ }
1274
+ }
1275
+ this._resetTimeoutPeriod();
1276
+ }
1277
+ _processHandshakeResponse(data) {
1278
+ let responseMessage;
1279
+ let remainingData;
1280
+ try {
1281
+ [remainingData, responseMessage] = this._handshakeProtocol.parseHandshakeResponse(data);
1282
+ }
1283
+ catch (e) {
1284
+ const message = "Error parsing handshake response: " + e;
1285
+ this._logger.log(LogLevel.Error, message);
1286
+ const error = new Error(message);
1287
+ this._handshakeRejecter(error);
1288
+ throw error;
1289
+ }
1290
+ if (responseMessage.error) {
1291
+ const message = "Server returned handshake error: " + responseMessage.error;
1292
+ this._logger.log(LogLevel.Error, message);
1293
+ const error = new Error(message);
1294
+ this._handshakeRejecter(error);
1295
+ throw error;
1296
+ }
1297
+ else {
1298
+ this._logger.log(LogLevel.Debug, "Server handshake complete.");
1299
+ }
1300
+ this._handshakeResolver();
1301
+ return remainingData;
1302
+ }
1303
+ _resetKeepAliveInterval() {
1304
+ if (this.connection.features.inherentKeepAlive) {
1305
+ return;
1306
+ }
1307
+ // Set the time we want the next keep alive to be sent
1308
+ // Timer will be setup on next message receive
1309
+ this._nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;
1310
+ this._cleanupPingTimer();
1311
+ }
1312
+ _resetTimeoutPeriod() {
1313
+ if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
1314
+ // Set the timeout timer
1315
+ this._timeoutHandle = setTimeout(() => this.serverTimeout(), this.serverTimeoutInMilliseconds);
1316
+ // Set keepAlive timer if there isn't one
1317
+ if (this._pingServerHandle === undefined) {
1318
+ let nextPing = this._nextKeepAlive - new Date().getTime();
1319
+ if (nextPing < 0) {
1320
+ nextPing = 0;
1321
+ }
1322
+ // The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute
1323
+ this._pingServerHandle = setTimeout(async () => {
1324
+ if (this._connectionState === HubConnectionState.Connected) {
1325
+ try {
1326
+ await this._sendMessage(this._cachedPingMessage);
1327
+ }
1328
+ catch {
1329
+ // We don't care about the error. It should be seen elsewhere in the client.
1330
+ // The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
1331
+ this._cleanupPingTimer();
1332
+ }
1333
+ }
1334
+ }, nextPing);
1335
+ }
1336
+ }
1337
+ }
1338
+ // eslint-disable-next-line @typescript-eslint/naming-convention
1339
+ serverTimeout() {
1340
+ // The server hasn't talked to us in a while. It doesn't like us anymore ... :(
1341
+ // Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.
1342
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1343
+ this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
1344
+ }
1345
+ _invokeClientMethod(invocationMessage) {
1346
+ const methods = this._methods[invocationMessage.target.toLowerCase()];
1347
+ if (methods) {
1348
+ try {
1349
+ methods.forEach((m) => m.apply(this, invocationMessage.arguments));
1350
+ }
1351
+ catch (e) {
1352
+ this._logger.log(LogLevel.Error, `A callback for the method ${invocationMessage.target.toLowerCase()} threw error '${e}'.`);
1353
+ }
1354
+ if (invocationMessage.invocationId) {
1355
+ // This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.
1356
+ const message = "Server requested a response, which is not supported in this version of the client.";
1357
+ this._logger.log(LogLevel.Error, message);
1358
+ // We don't want to wait on the stop itself.
1359
+ this._stopPromise = this._stopInternal(new Error(message));
1360
+ }
1361
+ }
1362
+ else {
1363
+ this._logger.log(LogLevel.Warning, `No client method with the name '${invocationMessage.target}' found.`);
1364
+ }
1365
+ }
1366
+ _connectionClosed(error) {
1367
+ this._logger.log(LogLevel.Debug, `HubConnection.connectionClosed(${error}) called while in state ${this._connectionState}.`);
1368
+ // Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.
1369
+ this._stopDuringStartError = this._stopDuringStartError || error || new Error("The underlying connection was closed before the hub handshake could complete.");
1370
+ // If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.
1371
+ // If it has already completed, this should just noop.
1372
+ if (this._handshakeResolver) {
1373
+ this._handshakeResolver();
1374
+ }
1375
+ this._cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
1376
+ this._cleanupTimeout();
1377
+ this._cleanupPingTimer();
1378
+ if (this._connectionState === HubConnectionState.Disconnecting) {
1379
+ this._completeClose(error);
1380
+ }
1381
+ else if (this._connectionState === HubConnectionState.Connected && this._reconnectPolicy) {
1382
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
1383
+ this._reconnect(error);
1384
+ }
1385
+ else if (this._connectionState === HubConnectionState.Connected) {
1386
+ this._completeClose(error);
1387
+ }
1388
+ // If none of the above if conditions were true were called the HubConnection must be in either:
1389
+ // 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.
1390
+ // 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt
1391
+ // and potentially continue the reconnect() loop.
1392
+ // 3. The Disconnected state in which case we're already done.
1393
+ }
1394
+ _completeClose(error) {
1395
+ if (this._connectionStarted) {
1396
+ this._connectionState = HubConnectionState.Disconnected;
1397
+ this._connectionStarted = false;
1398
+ if (Platform.isBrowser) {
1399
+ window.document.removeEventListener("freeze", this._freezeEventListener);
1400
+ }
1401
+ try {
1402
+ this._closedCallbacks.forEach((c) => c.apply(this, [error]));
1403
+ }
1404
+ catch (e) {
1405
+ this._logger.log(LogLevel.Error, `An onclose callback called with error '${error}' threw error '${e}'.`);
1406
+ }
1407
+ }
1408
+ }
1409
+ async _reconnect(error) {
1410
+ const reconnectStartTime = Date.now();
1411
+ let previousReconnectAttempts = 0;
1412
+ let retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error.");
1413
+ let nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, 0, retryError);
1414
+ if (nextRetryDelay === null) {
1415
+ this._logger.log(LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
1416
+ this._completeClose(error);
1417
+ return;
1418
+ }
1419
+ this._connectionState = HubConnectionState.Reconnecting;
1420
+ if (error) {
1421
+ this._logger.log(LogLevel.Information, `Connection reconnecting because of error '${error}'.`);
1422
+ }
1423
+ else {
1424
+ this._logger.log(LogLevel.Information, "Connection reconnecting.");
1425
+ }
1426
+ if (this._reconnectingCallbacks.length !== 0) {
1427
+ try {
1428
+ this._reconnectingCallbacks.forEach((c) => c.apply(this, [error]));
1429
+ }
1430
+ catch (e) {
1431
+ this._logger.log(LogLevel.Error, `An onreconnecting callback called with error '${error}' threw error '${e}'.`);
1432
+ }
1433
+ // Exit early if an onreconnecting callback called connection.stop().
1434
+ if (this._connectionState !== HubConnectionState.Reconnecting) {
1435
+ this._logger.log(LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
1436
+ return;
1437
+ }
1438
+ }
1439
+ while (nextRetryDelay !== null) {
1440
+ this._logger.log(LogLevel.Information, `Reconnect attempt number ${previousReconnectAttempts} will start in ${nextRetryDelay} ms.`);
1441
+ await new Promise((resolve) => {
1442
+ this._reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
1443
+ });
1444
+ this._reconnectDelayHandle = undefined;
1445
+ if (this._connectionState !== HubConnectionState.Reconnecting) {
1446
+ this._logger.log(LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
1447
+ return;
1448
+ }
1449
+ try {
1450
+ await this._startInternal();
1451
+ this._connectionState = HubConnectionState.Connected;
1452
+ this._logger.log(LogLevel.Information, "HubConnection reconnected successfully.");
1453
+ if (this._reconnectedCallbacks.length !== 0) {
1454
+ try {
1455
+ this._reconnectedCallbacks.forEach((c) => c.apply(this, [this.connection.connectionId]));
1456
+ }
1457
+ catch (e) {
1458
+ this._logger.log(LogLevel.Error, `An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`);
1459
+ }
1460
+ }
1461
+ return;
1462
+ }
1463
+ catch (e) {
1464
+ this._logger.log(LogLevel.Information, `Reconnect attempt failed because of error '${e}'.`);
1465
+ if (this._connectionState !== HubConnectionState.Reconnecting) {
1466
+ this._logger.log(LogLevel.Debug, `Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`);
1467
+ // The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.
1468
+ if (this._connectionState === HubConnectionState.Disconnecting) {
1469
+ this._completeClose();
1470
+ }
1471
+ return;
1472
+ }
1473
+ retryError = e instanceof Error ? e : new Error(e.toString());
1474
+ nextRetryDelay = this._getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);
1475
+ }
1476
+ }
1477
+ this._logger.log(LogLevel.Information, `Reconnect retries have been exhausted after ${Date.now() - reconnectStartTime} ms and ${previousReconnectAttempts} failed attempts. Connection disconnecting.`);
1478
+ this._completeClose();
1479
+ }
1480
+ _getNextRetryDelay(previousRetryCount, elapsedMilliseconds, retryReason) {
1481
+ try {
1482
+ return this._reconnectPolicy.nextRetryDelayInMilliseconds({
1483
+ elapsedMilliseconds,
1484
+ previousRetryCount,
1485
+ retryReason,
1486
+ });
1487
+ }
1488
+ catch (e) {
1489
+ this._logger.log(LogLevel.Error, `IRetryPolicy.nextRetryDelayInMilliseconds(${previousRetryCount}, ${elapsedMilliseconds}) threw error '${e}'.`);
1490
+ return null;
1491
+ }
1492
+ }
1493
+ _cancelCallbacksWithError(error) {
1494
+ const callbacks = this._callbacks;
1495
+ this._callbacks = {};
1496
+ Object.keys(callbacks)
1497
+ .forEach((key) => {
1498
+ const callback = callbacks[key];
1499
+ try {
1500
+ callback(null, error);
1501
+ }
1502
+ catch (e) {
1503
+ this._logger.log(LogLevel.Error, `Stream 'error' callback called with '${error}' threw error: ${getErrorString(e)}`);
1504
+ }
1505
+ });
1506
+ }
1507
+ _cleanupPingTimer() {
1508
+ if (this._pingServerHandle) {
1509
+ clearTimeout(this._pingServerHandle);
1510
+ this._pingServerHandle = undefined;
1511
+ }
1512
+ }
1513
+ _cleanupTimeout() {
1514
+ if (this._timeoutHandle) {
1515
+ clearTimeout(this._timeoutHandle);
1516
+ }
1517
+ }
1518
+ _createInvocation(methodName, args, nonblocking, streamIds) {
1519
+ if (nonblocking) {
1520
+ if (streamIds.length !== 0) {
1521
+ return {
1522
+ arguments: args,
1523
+ streamIds,
1524
+ target: methodName,
1525
+ type: MessageType.Invocation,
1526
+ };
1527
+ }
1528
+ else {
1529
+ return {
1530
+ arguments: args,
1531
+ target: methodName,
1532
+ type: MessageType.Invocation,
1533
+ };
1534
+ }
1535
+ }
1536
+ else {
1537
+ const invocationId = this._invocationId;
1538
+ this._invocationId++;
1539
+ if (streamIds.length !== 0) {
1540
+ return {
1541
+ arguments: args,
1542
+ invocationId: invocationId.toString(),
1543
+ streamIds,
1544
+ target: methodName,
1545
+ type: MessageType.Invocation,
1546
+ };
1547
+ }
1548
+ else {
1549
+ return {
1550
+ arguments: args,
1551
+ invocationId: invocationId.toString(),
1552
+ target: methodName,
1553
+ type: MessageType.Invocation,
1554
+ };
1555
+ }
1556
+ }
1557
+ }
1558
+ _launchStreams(streams, promiseQueue) {
1559
+ if (streams.length === 0) {
1560
+ return;
1561
+ }
1562
+ // Synchronize stream data so they arrive in-order on the server
1563
+ if (!promiseQueue) {
1564
+ promiseQueue = Promise.resolve();
1565
+ }
1566
+ // We want to iterate over the keys, since the keys are the stream ids
1567
+ // eslint-disable-next-line guard-for-in
1568
+ for (const streamId in streams) {
1569
+ streams[streamId].subscribe({
1570
+ complete: () => {
1571
+ promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId)));
1572
+ },
1573
+ error: (err) => {
1574
+ let message;
1575
+ if (err instanceof Error) {
1576
+ message = err.message;
1577
+ }
1578
+ else if (err && err.toString) {
1579
+ message = err.toString();
1580
+ }
1581
+ else {
1582
+ message = "Unknown error";
1583
+ }
1584
+ promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createCompletionMessage(streamId, message)));
1585
+ },
1586
+ next: (item) => {
1587
+ promiseQueue = promiseQueue.then(() => this._sendWithProtocol(this._createStreamItemMessage(streamId, item)));
1588
+ },
1589
+ });
1590
+ }
1591
+ }
1592
+ _replaceStreamingParams(args) {
1593
+ const streams = [];
1594
+ const streamIds = [];
1595
+ for (let i = 0; i < args.length; i++) {
1596
+ const argument = args[i];
1597
+ if (this._isObservable(argument)) {
1598
+ const streamId = this._invocationId;
1599
+ this._invocationId++;
1600
+ // Store the stream for later use
1601
+ streams[streamId] = argument;
1602
+ streamIds.push(streamId.toString());
1603
+ // remove stream from args
1604
+ args.splice(i, 1);
1605
+ }
1606
+ }
1607
+ return [streams, streamIds];
1608
+ }
1609
+ _isObservable(arg) {
1610
+ // This allows other stream implementations to just work (like rxjs)
1611
+ return arg && arg.subscribe && typeof arg.subscribe === "function";
1612
+ }
1613
+ _createStreamInvocation(methodName, args, streamIds) {
1614
+ const invocationId = this._invocationId;
1615
+ this._invocationId++;
1616
+ if (streamIds.length !== 0) {
1617
+ return {
1618
+ arguments: args,
1619
+ invocationId: invocationId.toString(),
1620
+ streamIds,
1621
+ target: methodName,
1622
+ type: MessageType.StreamInvocation,
1623
+ };
1624
+ }
1625
+ else {
1626
+ return {
1627
+ arguments: args,
1628
+ invocationId: invocationId.toString(),
1629
+ target: methodName,
1630
+ type: MessageType.StreamInvocation,
1631
+ };
1632
+ }
1633
+ }
1634
+ _createCancelInvocation(id) {
1635
+ return {
1636
+ invocationId: id,
1637
+ type: MessageType.CancelInvocation,
1638
+ };
1639
+ }
1640
+ _createStreamItemMessage(id, item) {
1641
+ return {
1642
+ invocationId: id,
1643
+ item,
1644
+ type: MessageType.StreamItem,
1645
+ };
1646
+ }
1647
+ _createCompletionMessage(id, error, result) {
1648
+ if (error) {
1649
+ return {
1650
+ error,
1651
+ invocationId: id,
1652
+ type: MessageType.Completion,
1653
+ };
1654
+ }
1655
+ return {
1656
+ invocationId: id,
1657
+ result,
1658
+ type: MessageType.Completion,
1659
+ };
1660
+ }
1661
+ }
1662
+
1663
+ // Licensed to the .NET Foundation under one or more agreements.
1664
+ // The .NET Foundation licenses this file to you under the MIT license.
1665
+ // 0, 2, 10, 30 second delays before reconnect attempts.
1666
+ const DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];
1667
+ /** @private */
1668
+ class DefaultReconnectPolicy {
1669
+ constructor(retryDelays) {
1670
+ this._retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;
1671
+ }
1672
+ nextRetryDelayInMilliseconds(retryContext) {
1673
+ return this._retryDelays[retryContext.previousRetryCount];
1674
+ }
1675
+ }
1676
+
1677
+ // Licensed to the .NET Foundation under one or more agreements.
1678
+ // The .NET Foundation licenses this file to you under the MIT license.
1679
+ class HeaderNames {
1680
+ }
1681
+ HeaderNames.Authorization = "Authorization";
1682
+ HeaderNames.Cookie = "Cookie";
1683
+
1684
+ // Licensed to the .NET Foundation under one or more agreements.
1685
+ // The .NET Foundation licenses this file to you under the MIT license.
1686
+ // This will be treated as a bit flag in the future, so we keep it using power-of-two values.
1687
+ /** Specifies a specific HTTP transport type. */
1688
+ var HttpTransportType;
1689
+ (function (HttpTransportType) {
1690
+ /** Specifies no transport preference. */
1691
+ HttpTransportType[HttpTransportType["None"] = 0] = "None";
1692
+ /** Specifies the WebSockets transport. */
1693
+ HttpTransportType[HttpTransportType["WebSockets"] = 1] = "WebSockets";
1694
+ /** Specifies the Server-Sent Events transport. */
1695
+ HttpTransportType[HttpTransportType["ServerSentEvents"] = 2] = "ServerSentEvents";
1696
+ /** Specifies the Long Polling transport. */
1697
+ HttpTransportType[HttpTransportType["LongPolling"] = 4] = "LongPolling";
1698
+ })(HttpTransportType || (HttpTransportType = {}));
1699
+ /** Specifies the transfer format for a connection. */
1700
+ var TransferFormat;
1701
+ (function (TransferFormat) {
1702
+ /** Specifies that only text data will be transmitted over the connection. */
1703
+ TransferFormat[TransferFormat["Text"] = 1] = "Text";
1704
+ /** Specifies that binary data will be transmitted over the connection. */
1705
+ TransferFormat[TransferFormat["Binary"] = 2] = "Binary";
1706
+ })(TransferFormat || (TransferFormat = {}));
1707
+
1708
+ // Licensed to the .NET Foundation under one or more agreements.
1709
+ // The .NET Foundation licenses this file to you under the MIT license.
1710
+ // Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController
1711
+ // We don't actually ever use the API being polyfilled, we always use the polyfill because
1712
+ // it's a very new API right now.
1713
+ // Not exported from index.
1714
+ /** @private */
1715
+ class AbortController$1 {
1716
+ constructor() {
1717
+ this._isAborted = false;
1718
+ this.onabort = null;
1719
+ }
1720
+ abort() {
1721
+ if (!this._isAborted) {
1722
+ this._isAborted = true;
1723
+ if (this.onabort) {
1724
+ this.onabort();
1725
+ }
1726
+ }
1727
+ }
1728
+ get signal() {
1729
+ return this;
1730
+ }
1731
+ get aborted() {
1732
+ return this._isAborted;
1733
+ }
1734
+ }
1735
+
1736
+ // Licensed to the .NET Foundation under one or more agreements.
1737
+ // Not exported from 'index', this type is internal.
1738
+ /** @private */
1739
+ class LongPollingTransport {
1740
+ constructor(httpClient, accessTokenFactory, logger, options) {
1741
+ this._httpClient = httpClient;
1742
+ this._accessTokenFactory = accessTokenFactory;
1743
+ this._logger = logger;
1744
+ this._pollAbort = new AbortController$1();
1745
+ this._options = options;
1746
+ this._running = false;
1747
+ this.onreceive = null;
1748
+ this.onclose = null;
1749
+ }
1750
+ // This is an internal type, not exported from 'index' so this is really just internal.
1751
+ get pollAborted() {
1752
+ return this._pollAbort.aborted;
1753
+ }
1754
+ async connect(url, transferFormat) {
1755
+ Arg.isRequired(url, "url");
1756
+ Arg.isRequired(transferFormat, "transferFormat");
1757
+ Arg.isIn(transferFormat, TransferFormat, "transferFormat");
1758
+ this._url = url;
1759
+ this._logger.log(LogLevel.Trace, "(LongPolling transport) Connecting.");
1760
+ // Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)
1761
+ if (transferFormat === TransferFormat.Binary &&
1762
+ (typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) {
1763
+ throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");
1764
+ }
1765
+ const [name, value] = getUserAgentHeader();
1766
+ const headers = { [name]: value, ...this._options.headers };
1767
+ const pollOptions = {
1768
+ abortSignal: this._pollAbort.signal,
1769
+ headers,
1770
+ timeout: 100000,
1771
+ withCredentials: this._options.withCredentials,
1772
+ };
1773
+ if (transferFormat === TransferFormat.Binary) {
1774
+ pollOptions.responseType = "arraybuffer";
1775
+ }
1776
+ const token = await this._getAccessToken();
1777
+ this._updateHeaderToken(pollOptions, token);
1778
+ // Make initial long polling request
1779
+ // Server uses first long polling request to finish initializing connection and it returns without data
1780
+ const pollUrl = `${url}&_=${Date.now()}`;
1781
+ this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);
1782
+ const response = await this._httpClient.get(pollUrl, pollOptions);
1783
+ if (response.statusCode !== 200) {
1784
+ this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);
1785
+ // Mark running as false so that the poll immediately ends and runs the close logic
1786
+ this._closeError = new HttpError(response.statusText || "", response.statusCode);
1787
+ this._running = false;
1788
+ }
1789
+ else {
1790
+ this._running = true;
1791
+ }
1792
+ this._receiving = this._poll(this._url, pollOptions);
1793
+ }
1794
+ async _getAccessToken() {
1795
+ if (this._accessTokenFactory) {
1796
+ return await this._accessTokenFactory();
1797
+ }
1798
+ return null;
1799
+ }
1800
+ _updateHeaderToken(request, token) {
1801
+ if (!request.headers) {
1802
+ request.headers = {};
1803
+ }
1804
+ if (token) {
1805
+ request.headers[HeaderNames.Authorization] = `Bearer ${token}`;
1806
+ return;
1807
+ }
1808
+ if (request.headers[HeaderNames.Authorization]) {
1809
+ delete request.headers[HeaderNames.Authorization];
1810
+ }
1811
+ }
1812
+ async _poll(url, pollOptions) {
1813
+ try {
1814
+ while (this._running) {
1815
+ // We have to get the access token on each poll, in case it changes
1816
+ const token = await this._getAccessToken();
1817
+ this._updateHeaderToken(pollOptions, token);
1818
+ try {
1819
+ const pollUrl = `${url}&_=${Date.now()}`;
1820
+ this._logger.log(LogLevel.Trace, `(LongPolling transport) polling: ${pollUrl}.`);
1821
+ const response = await this._httpClient.get(pollUrl, pollOptions);
1822
+ if (response.statusCode === 204) {
1823
+ this._logger.log(LogLevel.Information, "(LongPolling transport) Poll terminated by server.");
1824
+ this._running = false;
1825
+ }
1826
+ else if (response.statusCode !== 200) {
1827
+ this._logger.log(LogLevel.Error, `(LongPolling transport) Unexpected response code: ${response.statusCode}.`);
1828
+ // Unexpected status code
1829
+ this._closeError = new HttpError(response.statusText || "", response.statusCode);
1830
+ this._running = false;
1831
+ }
1832
+ else {
1833
+ // Process the response
1834
+ if (response.content) {
1835
+ this._logger.log(LogLevel.Trace, `(LongPolling transport) data received. ${getDataDetail(response.content, this._options.logMessageContent)}.`);
1836
+ if (this.onreceive) {
1837
+ this.onreceive(response.content);
1838
+ }
1839
+ }
1840
+ else {
1841
+ // This is another way timeout manifest.
1842
+ this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
1843
+ }
1844
+ }
1845
+ }
1846
+ catch (e) {
1847
+ if (!this._running) {
1848
+ // Log but disregard errors that occur after stopping
1849
+ this._logger.log(LogLevel.Trace, `(LongPolling transport) Poll errored after shutdown: ${e.message}`);
1850
+ }
1851
+ else {
1852
+ if (e instanceof TimeoutError) {
1853
+ // Ignore timeouts and reissue the poll.
1854
+ this._logger.log(LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
1855
+ }
1856
+ else {
1857
+ // Close the connection with the error as the result.
1858
+ this._closeError = e;
1859
+ this._running = false;
1860
+ }
1861
+ }
1862
+ }
1863
+ }
1864
+ }
1865
+ finally {
1866
+ this._logger.log(LogLevel.Trace, "(LongPolling transport) Polling complete.");
1867
+ // We will reach here with pollAborted==false when the server returned a response causing the transport to stop.
1868
+ // If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.
1869
+ if (!this.pollAborted) {
1870
+ this._raiseOnClose();
1871
+ }
1872
+ }
1873
+ }
1874
+ async send(data) {
1875
+ if (!this._running) {
1876
+ return Promise.reject(new Error("Cannot send until the transport is connected"));
1877
+ }
1878
+ return sendMessage(this._logger, "LongPolling", this._httpClient, this._url, this._accessTokenFactory, data, this._options);
1879
+ }
1880
+ async stop() {
1881
+ this._logger.log(LogLevel.Trace, "(LongPolling transport) Stopping polling.");
1882
+ // Tell receiving loop to stop, abort any current request, and then wait for it to finish
1883
+ this._running = false;
1884
+ this._pollAbort.abort();
1885
+ try {
1886
+ await this._receiving;
1887
+ // Send DELETE to clean up long polling on the server
1888
+ this._logger.log(LogLevel.Trace, `(LongPolling transport) sending DELETE request to ${this._url}.`);
1889
+ const headers = {};
1890
+ const [name, value] = getUserAgentHeader();
1891
+ headers[name] = value;
1892
+ const deleteOptions = {
1893
+ headers: { ...headers, ...this._options.headers },
1894
+ timeout: this._options.timeout,
1895
+ withCredentials: this._options.withCredentials,
1896
+ };
1897
+ const token = await this._getAccessToken();
1898
+ this._updateHeaderToken(deleteOptions, token);
1899
+ await this._httpClient.delete(this._url, deleteOptions);
1900
+ this._logger.log(LogLevel.Trace, "(LongPolling transport) DELETE request sent.");
1901
+ }
1902
+ finally {
1903
+ this._logger.log(LogLevel.Trace, "(LongPolling transport) Stop finished.");
1904
+ // Raise close event here instead of in polling
1905
+ // It needs to happen after the DELETE request is sent
1906
+ this._raiseOnClose();
1907
+ }
1908
+ }
1909
+ _raiseOnClose() {
1910
+ if (this.onclose) {
1911
+ let logMessage = "(LongPolling transport) Firing onclose event.";
1912
+ if (this._closeError) {
1913
+ logMessage += " Error: " + this._closeError;
1914
+ }
1915
+ this._logger.log(LogLevel.Trace, logMessage);
1916
+ this.onclose(this._closeError);
1917
+ }
1918
+ }
1919
+ }
1920
+
1921
+ // Licensed to the .NET Foundation under one or more agreements.
1922
+ /** @private */
1923
+ class ServerSentEventsTransport {
1924
+ constructor(httpClient, accessTokenFactory, logger, options) {
1925
+ this._httpClient = httpClient;
1926
+ this._accessTokenFactory = accessTokenFactory;
1927
+ this._logger = logger;
1928
+ this._options = options;
1929
+ this.onreceive = null;
1930
+ this.onclose = null;
1931
+ }
1932
+ async connect(url, transferFormat) {
1933
+ Arg.isRequired(url, "url");
1934
+ Arg.isRequired(transferFormat, "transferFormat");
1935
+ Arg.isIn(transferFormat, TransferFormat, "transferFormat");
1936
+ this._logger.log(LogLevel.Trace, "(SSE transport) Connecting.");
1937
+ // set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send
1938
+ this._url = url;
1939
+ if (this._accessTokenFactory) {
1940
+ const token = await this._accessTokenFactory();
1941
+ if (token) {
1942
+ url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(token)}`;
1943
+ }
1944
+ }
1945
+ return new Promise((resolve, reject) => {
1946
+ let opened = false;
1947
+ if (transferFormat !== TransferFormat.Text) {
1948
+ reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));
1949
+ return;
1950
+ }
1951
+ let eventSource;
1952
+ if (Platform.isBrowser || Platform.isWebWorker) {
1953
+ eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials });
1954
+ }
1955
+ else {
1956
+ // Non-browser passes cookies via the dictionary
1957
+ const cookies = this._httpClient.getCookieString(url);
1958
+ const headers = {};
1959
+ headers.Cookie = cookies;
1960
+ const [name, value] = getUserAgentHeader();
1961
+ headers[name] = value;
1962
+ eventSource = new this._options.EventSource(url, { withCredentials: this._options.withCredentials, headers: { ...headers, ...this._options.headers } });
1963
+ }
1964
+ try {
1965
+ eventSource.onmessage = (e) => {
1966
+ if (this.onreceive) {
1967
+ try {
1968
+ this._logger.log(LogLevel.Trace, `(SSE transport) data received. ${getDataDetail(e.data, this._options.logMessageContent)}.`);
1969
+ this.onreceive(e.data);
1970
+ }
1971
+ catch (error) {
1972
+ this._close(error);
1973
+ return;
1974
+ }
1975
+ }
1976
+ };
1977
+ // @ts-ignore: not using event on purpose
1978
+ eventSource.onerror = (e) => {
1979
+ // EventSource doesn't give any useful information about server side closes.
1980
+ if (opened) {
1981
+ this._close();
1982
+ }
1983
+ else {
1984
+ reject(new Error("EventSource failed to connect. The connection could not be found on the server,"
1985
+ + " either the connection ID is not present on the server, or a proxy is refusing/buffering the connection."
1986
+ + " If you have multiple servers check that sticky sessions are enabled."));
1987
+ }
1988
+ };
1989
+ eventSource.onopen = () => {
1990
+ this._logger.log(LogLevel.Information, `SSE connected to ${this._url}`);
1991
+ this._eventSource = eventSource;
1992
+ opened = true;
1993
+ resolve();
1994
+ };
1995
+ }
1996
+ catch (e) {
1997
+ reject(e);
1998
+ return;
1999
+ }
2000
+ });
2001
+ }
2002
+ async send(data) {
2003
+ if (!this._eventSource) {
2004
+ return Promise.reject(new Error("Cannot send until the transport is connected"));
2005
+ }
2006
+ return sendMessage(this._logger, "SSE", this._httpClient, this._url, this._accessTokenFactory, data, this._options);
2007
+ }
2008
+ stop() {
2009
+ this._close();
2010
+ return Promise.resolve();
2011
+ }
2012
+ _close(e) {
2013
+ if (this._eventSource) {
2014
+ this._eventSource.close();
2015
+ this._eventSource = undefined;
2016
+ if (this.onclose) {
2017
+ this.onclose(e);
2018
+ }
2019
+ }
2020
+ }
2021
+ }
2022
+
2023
+ // Licensed to the .NET Foundation under one or more agreements.
2024
+ /** @private */
2025
+ class WebSocketTransport {
2026
+ constructor(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) {
2027
+ this._logger = logger;
2028
+ this._accessTokenFactory = accessTokenFactory;
2029
+ this._logMessageContent = logMessageContent;
2030
+ this._webSocketConstructor = webSocketConstructor;
2031
+ this._httpClient = httpClient;
2032
+ this.onreceive = null;
2033
+ this.onclose = null;
2034
+ this._headers = headers;
2035
+ }
2036
+ async connect(url, transferFormat) {
2037
+ Arg.isRequired(url, "url");
2038
+ Arg.isRequired(transferFormat, "transferFormat");
2039
+ Arg.isIn(transferFormat, TransferFormat, "transferFormat");
2040
+ this._logger.log(LogLevel.Trace, "(WebSockets transport) Connecting.");
2041
+ if (this._accessTokenFactory) {
2042
+ const token = await this._accessTokenFactory();
2043
+ if (token) {
2044
+ url += (url.indexOf("?") < 0 ? "?" : "&") + `access_token=${encodeURIComponent(token)}`;
2045
+ }
2046
+ }
2047
+ return new Promise((resolve, reject) => {
2048
+ url = url.replace(/^http/, "ws");
2049
+ let webSocket;
2050
+ const cookies = this._httpClient.getCookieString(url);
2051
+ let opened = false;
2052
+ if (Platform.isNode) {
2053
+ const headers = {};
2054
+ const [name, value] = getUserAgentHeader();
2055
+ headers[name] = value;
2056
+ if (cookies) {
2057
+ headers[HeaderNames.Cookie] = `${cookies}`;
2058
+ }
2059
+ // Only pass headers when in non-browser environments
2060
+ webSocket = new this._webSocketConstructor(url, undefined, {
2061
+ headers: { ...headers, ...this._headers },
2062
+ });
2063
+ }
2064
+ if (!webSocket) {
2065
+ // Chrome is not happy with passing 'undefined' as protocol
2066
+ webSocket = new this._webSocketConstructor(url);
2067
+ }
2068
+ if (transferFormat === TransferFormat.Binary) {
2069
+ webSocket.binaryType = "arraybuffer";
2070
+ }
2071
+ webSocket.onopen = (_event) => {
2072
+ this._logger.log(LogLevel.Information, `WebSocket connected to ${url}.`);
2073
+ this._webSocket = webSocket;
2074
+ opened = true;
2075
+ resolve();
2076
+ };
2077
+ webSocket.onerror = (event) => {
2078
+ let error = null;
2079
+ // ErrorEvent is a browser only type we need to check if the type exists before using it
2080
+ if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
2081
+ error = event.error;
2082
+ }
2083
+ else {
2084
+ error = "There was an error with the transport";
2085
+ }
2086
+ this._logger.log(LogLevel.Information, `(WebSockets transport) ${error}.`);
2087
+ };
2088
+ webSocket.onmessage = (message) => {
2089
+ this._logger.log(LogLevel.Trace, `(WebSockets transport) data received. ${getDataDetail(message.data, this._logMessageContent)}.`);
2090
+ if (this.onreceive) {
2091
+ try {
2092
+ this.onreceive(message.data);
2093
+ }
2094
+ catch (error) {
2095
+ this._close(error);
2096
+ return;
2097
+ }
2098
+ }
2099
+ };
2100
+ webSocket.onclose = (event) => {
2101
+ // Don't call close handler if connection was never established
2102
+ // We'll reject the connect call instead
2103
+ if (opened) {
2104
+ this._close(event);
2105
+ }
2106
+ else {
2107
+ let error = null;
2108
+ // ErrorEvent is a browser only type we need to check if the type exists before using it
2109
+ if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
2110
+ error = event.error;
2111
+ }
2112
+ else {
2113
+ error = "WebSocket failed to connect. The connection could not be found on the server,"
2114
+ + " either the endpoint may not be a SignalR endpoint,"
2115
+ + " the connection ID is not present on the server, or there is a proxy blocking WebSockets."
2116
+ + " If you have multiple servers check that sticky sessions are enabled.";
2117
+ }
2118
+ reject(new Error(error));
2119
+ }
2120
+ };
2121
+ });
2122
+ }
2123
+ send(data) {
2124
+ if (this._webSocket && this._webSocket.readyState === this._webSocketConstructor.OPEN) {
2125
+ this._logger.log(LogLevel.Trace, `(WebSockets transport) sending data. ${getDataDetail(data, this._logMessageContent)}.`);
2126
+ this._webSocket.send(data);
2127
+ return Promise.resolve();
2128
+ }
2129
+ return Promise.reject("WebSocket is not in the OPEN state");
2130
+ }
2131
+ stop() {
2132
+ if (this._webSocket) {
2133
+ // Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning
2134
+ // This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects
2135
+ this._close(undefined);
2136
+ }
2137
+ return Promise.resolve();
2138
+ }
2139
+ _close(event) {
2140
+ // webSocket will be null if the transport did not start successfully
2141
+ if (this._webSocket) {
2142
+ // Clear websocket handlers because we are considering the socket closed now
2143
+ this._webSocket.onclose = () => { };
2144
+ this._webSocket.onmessage = () => { };
2145
+ this._webSocket.onerror = () => { };
2146
+ this._webSocket.close();
2147
+ this._webSocket = undefined;
2148
+ }
2149
+ this._logger.log(LogLevel.Trace, "(WebSockets transport) socket closed.");
2150
+ if (this.onclose) {
2151
+ if (this._isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {
2152
+ this.onclose(new Error(`WebSocket closed with status code: ${event.code} (${event.reason || "no reason given"}).`));
2153
+ }
2154
+ else if (event instanceof Error) {
2155
+ this.onclose(event);
2156
+ }
2157
+ else {
2158
+ this.onclose();
2159
+ }
2160
+ }
2161
+ }
2162
+ _isCloseEvent(event) {
2163
+ return event && typeof event.wasClean === "boolean" && typeof event.code === "number";
2164
+ }
2165
+ }
2166
+
2167
+ // Licensed to the .NET Foundation under one or more agreements.
2168
+ const MAX_REDIRECTS = 100;
2169
+ /** @private */
2170
+ class HttpConnection {
2171
+ constructor(url, options = {}) {
2172
+ this._stopPromiseResolver = () => { };
2173
+ this.features = {};
2174
+ this._negotiateVersion = 1;
2175
+ Arg.isRequired(url, "url");
2176
+ this._logger = createLogger(options.logger);
2177
+ this.baseUrl = this._resolveUrl(url);
2178
+ options = options || {};
2179
+ options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;
2180
+ if (typeof options.withCredentials === "boolean" || options.withCredentials === undefined) {
2181
+ options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;
2182
+ }
2183
+ else {
2184
+ throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");
2185
+ }
2186
+ options.timeout = options.timeout === undefined ? 100 * 1000 : options.timeout;
2187
+ let webSocketModule = null;
2188
+ let eventSourceModule = null;
2189
+ if (Platform.isNode && typeof require !== "undefined") {
2190
+ // In order to ignore the dynamic require in webpack builds we need to do this magic
2191
+ // @ts-ignore: TS doesn't know about these names
2192
+ const requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
2193
+ webSocketModule = requireFunc("ws");
2194
+ eventSourceModule = requireFunc("eventsource");
2195
+ }
2196
+ if (!Platform.isNode && typeof WebSocket !== "undefined" && !options.WebSocket) {
2197
+ options.WebSocket = WebSocket;
2198
+ }
2199
+ else if (Platform.isNode && !options.WebSocket) {
2200
+ if (webSocketModule) {
2201
+ options.WebSocket = webSocketModule;
2202
+ }
2203
+ }
2204
+ if (!Platform.isNode && typeof EventSource !== "undefined" && !options.EventSource) {
2205
+ options.EventSource = EventSource;
2206
+ }
2207
+ else if (Platform.isNode && !options.EventSource) {
2208
+ if (typeof eventSourceModule !== "undefined") {
2209
+ options.EventSource = eventSourceModule;
2210
+ }
2211
+ }
2212
+ this._httpClient = options.httpClient || new DefaultHttpClient(this._logger);
2213
+ this._connectionState = "Disconnected" /* Disconnected */;
2214
+ this._connectionStarted = false;
2215
+ this._options = options;
2216
+ this.onreceive = null;
2217
+ this.onclose = null;
2218
+ }
2219
+ async start(transferFormat) {
2220
+ transferFormat = transferFormat || TransferFormat.Binary;
2221
+ Arg.isIn(transferFormat, TransferFormat, "transferFormat");
2222
+ this._logger.log(LogLevel.Debug, `Starting connection with transfer format '${TransferFormat[transferFormat]}'.`);
2223
+ if (this._connectionState !== "Disconnected" /* Disconnected */) {
2224
+ return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));
2225
+ }
2226
+ this._connectionState = "Connecting" /* Connecting */;
2227
+ this._startInternalPromise = this._startInternal(transferFormat);
2228
+ await this._startInternalPromise;
2229
+ // The TypeScript compiler thinks that connectionState must be Connecting here. The TypeScript compiler is wrong.
2230
+ if (this._connectionState === "Disconnecting" /* Disconnecting */) {
2231
+ // stop() was called and transitioned the client into the Disconnecting state.
2232
+ const message = "Failed to start the HttpConnection before stop() was called.";
2233
+ this._logger.log(LogLevel.Error, message);
2234
+ // We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
2235
+ await this._stopPromise;
2236
+ return Promise.reject(new Error(message));
2237
+ }
2238
+ else if (this._connectionState !== "Connected" /* Connected */) {
2239
+ // stop() was called and transitioned the client into the Disconnecting state.
2240
+ const message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";
2241
+ this._logger.log(LogLevel.Error, message);
2242
+ return Promise.reject(new Error(message));
2243
+ }
2244
+ this._connectionStarted = true;
2245
+ }
2246
+ send(data) {
2247
+ if (this._connectionState !== "Connected" /* Connected */) {
2248
+ return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State."));
2249
+ }
2250
+ if (!this._sendQueue) {
2251
+ this._sendQueue = new TransportSendQueue(this.transport);
2252
+ }
2253
+ // Transport will not be null if state is connected
2254
+ return this._sendQueue.send(data);
2255
+ }
2256
+ async stop(error) {
2257
+ if (this._connectionState === "Disconnected" /* Disconnected */) {
2258
+ this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnected state.`);
2259
+ return Promise.resolve();
2260
+ }
2261
+ if (this._connectionState === "Disconnecting" /* Disconnecting */) {
2262
+ this._logger.log(LogLevel.Debug, `Call to HttpConnection.stop(${error}) ignored because the connection is already in the disconnecting state.`);
2263
+ return this._stopPromise;
2264
+ }
2265
+ this._connectionState = "Disconnecting" /* Disconnecting */;
2266
+ this._stopPromise = new Promise((resolve) => {
2267
+ // Don't complete stop() until stopConnection() completes.
2268
+ this._stopPromiseResolver = resolve;
2269
+ });
2270
+ // stopInternal should never throw so just observe it.
2271
+ await this._stopInternal(error);
2272
+ await this._stopPromise;
2273
+ }
2274
+ async _stopInternal(error) {
2275
+ // Set error as soon as possible otherwise there is a race between
2276
+ // the transport closing and providing an error and the error from a close message
2277
+ // We would prefer the close message error.
2278
+ this._stopError = error;
2279
+ try {
2280
+ await this._startInternalPromise;
2281
+ }
2282
+ catch (e) {
2283
+ // This exception is returned to the user as a rejected Promise from the start method.
2284
+ }
2285
+ // The transport's onclose will trigger stopConnection which will run our onclose event.
2286
+ // The transport should always be set if currently connected. If it wasn't set, it's likely because
2287
+ // stop was called during start() and start() failed.
2288
+ if (this.transport) {
2289
+ try {
2290
+ await this.transport.stop();
2291
+ }
2292
+ catch (e) {
2293
+ this._logger.log(LogLevel.Error, `HttpConnection.transport.stop() threw error '${e}'.`);
2294
+ this._stopConnection();
2295
+ }
2296
+ this.transport = undefined;
2297
+ }
2298
+ else {
2299
+ this._logger.log(LogLevel.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.");
2300
+ }
2301
+ }
2302
+ async _startInternal(transferFormat) {
2303
+ // Store the original base url and the access token factory since they may change
2304
+ // as part of negotiating
2305
+ let url = this.baseUrl;
2306
+ this._accessTokenFactory = this._options.accessTokenFactory;
2307
+ try {
2308
+ if (this._options.skipNegotiation) {
2309
+ if (this._options.transport === HttpTransportType.WebSockets) {
2310
+ // No need to add a connection ID in this case
2311
+ this.transport = this._constructTransport(HttpTransportType.WebSockets);
2312
+ // We should just call connect directly in this case.
2313
+ // No fallback or negotiate in this case.
2314
+ await this._startTransport(url, transferFormat);
2315
+ }
2316
+ else {
2317
+ throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");
2318
+ }
2319
+ }
2320
+ else {
2321
+ let negotiateResponse = null;
2322
+ let redirects = 0;
2323
+ do {
2324
+ negotiateResponse = await this._getNegotiationResponse(url);
2325
+ // the user tries to stop the connection when it is being started
2326
+ if (this._connectionState === "Disconnecting" /* Disconnecting */ || this._connectionState === "Disconnected" /* Disconnected */) {
2327
+ throw new Error("The connection was stopped during negotiation.");
2328
+ }
2329
+ if (negotiateResponse.error) {
2330
+ throw new Error(negotiateResponse.error);
2331
+ }
2332
+ if (negotiateResponse.ProtocolVersion) {
2333
+ 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.");
2334
+ }
2335
+ if (negotiateResponse.url) {
2336
+ url = negotiateResponse.url;
2337
+ }
2338
+ if (negotiateResponse.accessToken) {
2339
+ // Replace the current access token factory with one that uses
2340
+ // the returned access token
2341
+ const accessToken = negotiateResponse.accessToken;
2342
+ this._accessTokenFactory = () => accessToken;
2343
+ }
2344
+ redirects++;
2345
+ } while (negotiateResponse.url && redirects < MAX_REDIRECTS);
2346
+ if (redirects === MAX_REDIRECTS && negotiateResponse.url) {
2347
+ throw new Error("Negotiate redirection limit exceeded.");
2348
+ }
2349
+ await this._createTransport(url, this._options.transport, negotiateResponse, transferFormat);
2350
+ }
2351
+ if (this.transport instanceof LongPollingTransport) {
2352
+ this.features.inherentKeepAlive = true;
2353
+ }
2354
+ if (this._connectionState === "Connecting" /* Connecting */) {
2355
+ // Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.
2356
+ // start() will handle the case when stop was called and startInternal exits still in the disconnecting state.
2357
+ this._logger.log(LogLevel.Debug, "The HttpConnection connected successfully.");
2358
+ this._connectionState = "Connected" /* Connected */;
2359
+ }
2360
+ // stop() is waiting on us via this.startInternalPromise so keep this.transport around so it can clean up.
2361
+ // This is the only case startInternal can exit in neither the connected nor disconnected state because stopConnection()
2362
+ // will transition to the disconnected state. start() will wait for the transition using the stopPromise.
2363
+ }
2364
+ catch (e) {
2365
+ this._logger.log(LogLevel.Error, "Failed to start the connection: " + e);
2366
+ this._connectionState = "Disconnected" /* Disconnected */;
2367
+ this.transport = undefined;
2368
+ // if start fails, any active calls to stop assume that start will complete the stop promise
2369
+ this._stopPromiseResolver();
2370
+ return Promise.reject(e);
2371
+ }
2372
+ }
2373
+ async _getNegotiationResponse(url) {
2374
+ const headers = {};
2375
+ if (this._accessTokenFactory) {
2376
+ const token = await this._accessTokenFactory();
2377
+ if (token) {
2378
+ headers[HeaderNames.Authorization] = `Bearer ${token}`;
2379
+ }
2380
+ }
2381
+ const [name, value] = getUserAgentHeader();
2382
+ headers[name] = value;
2383
+ const negotiateUrl = this._resolveNegotiateUrl(url);
2384
+ this._logger.log(LogLevel.Debug, `Sending negotiation request: ${negotiateUrl}.`);
2385
+ try {
2386
+ const response = await this._httpClient.post(negotiateUrl, {
2387
+ content: "",
2388
+ headers: { ...headers, ...this._options.headers },
2389
+ timeout: this._options.timeout,
2390
+ withCredentials: this._options.withCredentials,
2391
+ });
2392
+ if (response.statusCode !== 200) {
2393
+ return Promise.reject(new Error(`Unexpected status code returned from negotiate '${response.statusCode}'`));
2394
+ }
2395
+ const negotiateResponse = JSON.parse(response.content);
2396
+ if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {
2397
+ // Negotiate version 0 doesn't use connectionToken
2398
+ // So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version
2399
+ negotiateResponse.connectionToken = negotiateResponse.connectionId;
2400
+ }
2401
+ return negotiateResponse;
2402
+ }
2403
+ catch (e) {
2404
+ let errorMessage = "Failed to complete negotiation with the server: " + e;
2405
+ if (e instanceof HttpError) {
2406
+ if (e.statusCode === 404) {
2407
+ errorMessage = errorMessage + " Either this is not a SignalR endpoint or there is a proxy blocking the connection.";
2408
+ }
2409
+ }
2410
+ this._logger.log(LogLevel.Error, errorMessage);
2411
+ return Promise.reject(new FailedToNegotiateWithServerError(errorMessage));
2412
+ }
2413
+ }
2414
+ _createConnectUrl(url, connectionToken) {
2415
+ if (!connectionToken) {
2416
+ return url;
2417
+ }
2418
+ return url + (url.indexOf("?") === -1 ? "?" : "&") + `id=${connectionToken}`;
2419
+ }
2420
+ async _createTransport(url, requestedTransport, negotiateResponse, requestedTransferFormat) {
2421
+ let connectUrl = this._createConnectUrl(url, negotiateResponse.connectionToken);
2422
+ if (this._isITransport(requestedTransport)) {
2423
+ this._logger.log(LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly.");
2424
+ this.transport = requestedTransport;
2425
+ await this._startTransport(connectUrl, requestedTransferFormat);
2426
+ this.connectionId = negotiateResponse.connectionId;
2427
+ return;
2428
+ }
2429
+ const transportExceptions = [];
2430
+ const transports = negotiateResponse.availableTransports || [];
2431
+ let negotiate = negotiateResponse;
2432
+ for (const endpoint of transports) {
2433
+ const transportOrError = this._resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);
2434
+ if (transportOrError instanceof Error) {
2435
+ // Store the error and continue, we don't want to cause a re-negotiate in these cases
2436
+ transportExceptions.push(`${endpoint.transport} failed:`);
2437
+ transportExceptions.push(transportOrError);
2438
+ }
2439
+ else if (this._isITransport(transportOrError)) {
2440
+ this.transport = transportOrError;
2441
+ if (!negotiate) {
2442
+ try {
2443
+ negotiate = await this._getNegotiationResponse(url);
2444
+ }
2445
+ catch (ex) {
2446
+ return Promise.reject(ex);
2447
+ }
2448
+ connectUrl = this._createConnectUrl(url, negotiate.connectionToken);
2449
+ }
2450
+ try {
2451
+ await this._startTransport(connectUrl, requestedTransferFormat);
2452
+ this.connectionId = negotiate.connectionId;
2453
+ return;
2454
+ }
2455
+ catch (ex) {
2456
+ this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);
2457
+ negotiate = undefined;
2458
+ transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, HttpTransportType[endpoint.transport]));
2459
+ if (this._connectionState !== "Connecting" /* Connecting */) {
2460
+ const message = "Failed to select transport before stop() was called.";
2461
+ this._logger.log(LogLevel.Debug, message);
2462
+ return Promise.reject(new Error(message));
2463
+ }
2464
+ }
2465
+ }
2466
+ }
2467
+ if (transportExceptions.length > 0) {
2468
+ return Promise.reject(new AggregateErrors(`Unable to connect to the server with any of the available transports. ${transportExceptions.join(" ")}`, transportExceptions));
2469
+ }
2470
+ return Promise.reject(new Error("None of the transports supported by the client are supported by the server."));
2471
+ }
2472
+ _constructTransport(transport) {
2473
+ switch (transport) {
2474
+ case HttpTransportType.WebSockets:
2475
+ if (!this._options.WebSocket) {
2476
+ throw new Error("'WebSocket' is not supported in your environment.");
2477
+ }
2478
+ return new WebSocketTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options.logMessageContent, this._options.WebSocket, this._options.headers || {});
2479
+ case HttpTransportType.ServerSentEvents:
2480
+ if (!this._options.EventSource) {
2481
+ throw new Error("'EventSource' is not supported in your environment.");
2482
+ }
2483
+ return new ServerSentEventsTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options);
2484
+ case HttpTransportType.LongPolling:
2485
+ return new LongPollingTransport(this._httpClient, this._accessTokenFactory, this._logger, this._options);
2486
+ default:
2487
+ throw new Error(`Unknown transport: ${transport}.`);
2488
+ }
2489
+ }
2490
+ _startTransport(url, transferFormat) {
2491
+ this.transport.onreceive = this.onreceive;
2492
+ this.transport.onclose = (e) => this._stopConnection(e);
2493
+ return this.transport.connect(url, transferFormat);
2494
+ }
2495
+ _resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat) {
2496
+ const transport = HttpTransportType[endpoint.transport];
2497
+ if (transport === null || transport === undefined) {
2498
+ this._logger.log(LogLevel.Debug, `Skipping transport '${endpoint.transport}' because it is not supported by this client.`);
2499
+ return new Error(`Skipping transport '${endpoint.transport}' because it is not supported by this client.`);
2500
+ }
2501
+ else {
2502
+ if (transportMatches(requestedTransport, transport)) {
2503
+ const transferFormats = endpoint.transferFormats.map((s) => TransferFormat[s]);
2504
+ if (transferFormats.indexOf(requestedTransferFormat) >= 0) {
2505
+ if ((transport === HttpTransportType.WebSockets && !this._options.WebSocket) ||
2506
+ (transport === HttpTransportType.ServerSentEvents && !this._options.EventSource)) {
2507
+ this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);
2508
+ return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, transport);
2509
+ }
2510
+ else {
2511
+ this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);
2512
+ try {
2513
+ return this._constructTransport(transport);
2514
+ }
2515
+ catch (ex) {
2516
+ return ex;
2517
+ }
2518
+ }
2519
+ }
2520
+ else {
2521
+ this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it does not support the requested transfer format '${TransferFormat[requestedTransferFormat]}'.`);
2522
+ return new Error(`'${HttpTransportType[transport]}' does not support ${TransferFormat[requestedTransferFormat]}.`);
2523
+ }
2524
+ }
2525
+ else {
2526
+ this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it was disabled by the client.`);
2527
+ return new DisabledTransportError(`'${HttpTransportType[transport]}' is disabled by the client.`, transport);
2528
+ }
2529
+ }
2530
+ }
2531
+ _isITransport(transport) {
2532
+ return transport && typeof (transport) === "object" && "connect" in transport;
2533
+ }
2534
+ _stopConnection(error) {
2535
+ this._logger.log(LogLevel.Debug, `HttpConnection.stopConnection(${error}) called while in state ${this._connectionState}.`);
2536
+ this.transport = undefined;
2537
+ // If we have a stopError, it takes precedence over the error from the transport
2538
+ error = this._stopError || error;
2539
+ this._stopError = undefined;
2540
+ if (this._connectionState === "Disconnected" /* Disconnected */) {
2541
+ this._logger.log(LogLevel.Debug, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is already in the disconnected state.`);
2542
+ return;
2543
+ }
2544
+ if (this._connectionState === "Connecting" /* Connecting */) {
2545
+ this._logger.log(LogLevel.Warning, `Call to HttpConnection.stopConnection(${error}) was ignored because the connection is still in the connecting state.`);
2546
+ throw new Error(`HttpConnection.stopConnection(${error}) was called while the connection is still in the connecting state.`);
2547
+ }
2548
+ if (this._connectionState === "Disconnecting" /* Disconnecting */) {
2549
+ // A call to stop() induced this call to stopConnection and needs to be completed.
2550
+ // Any stop() awaiters will be scheduled to continue after the onclose callback fires.
2551
+ this._stopPromiseResolver();
2552
+ }
2553
+ if (error) {
2554
+ this._logger.log(LogLevel.Error, `Connection disconnected with error '${error}'.`);
2555
+ }
2556
+ else {
2557
+ this._logger.log(LogLevel.Information, "Connection disconnected.");
2558
+ }
2559
+ if (this._sendQueue) {
2560
+ this._sendQueue.stop().catch((e) => {
2561
+ this._logger.log(LogLevel.Error, `TransportSendQueue.stop() threw error '${e}'.`);
2562
+ });
2563
+ this._sendQueue = undefined;
2564
+ }
2565
+ this.connectionId = undefined;
2566
+ this._connectionState = "Disconnected" /* Disconnected */;
2567
+ if (this._connectionStarted) {
2568
+ this._connectionStarted = false;
2569
+ try {
2570
+ if (this.onclose) {
2571
+ this.onclose(error);
2572
+ }
2573
+ }
2574
+ catch (e) {
2575
+ this._logger.log(LogLevel.Error, `HttpConnection.onclose(${error}) threw error '${e}'.`);
2576
+ }
2577
+ }
2578
+ }
2579
+ _resolveUrl(url) {
2580
+ // startsWith is not supported in IE
2581
+ if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
2582
+ return url;
2583
+ }
2584
+ if (!Platform.isBrowser) {
2585
+ throw new Error(`Cannot resolve '${url}'.`);
2586
+ }
2587
+ // Setting the url to the href propery of an anchor tag handles normalization
2588
+ // for us. There are 3 main cases.
2589
+ // 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b"
2590
+ // 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b"
2591
+ // 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b"
2592
+ const aTag = window.document.createElement("a");
2593
+ aTag.href = url;
2594
+ this._logger.log(LogLevel.Information, `Normalizing '${url}' to '${aTag.href}'.`);
2595
+ return aTag.href;
2596
+ }
2597
+ _resolveNegotiateUrl(url) {
2598
+ const index = url.indexOf("?");
2599
+ let negotiateUrl = url.substring(0, index === -1 ? url.length : index);
2600
+ if (negotiateUrl[negotiateUrl.length - 1] !== "/") {
2601
+ negotiateUrl += "/";
2602
+ }
2603
+ negotiateUrl += "negotiate";
2604
+ negotiateUrl += index === -1 ? "" : url.substring(index);
2605
+ if (negotiateUrl.indexOf("negotiateVersion") === -1) {
2606
+ negotiateUrl += index === -1 ? "?" : "&";
2607
+ negotiateUrl += "negotiateVersion=" + this._negotiateVersion;
2608
+ }
2609
+ return negotiateUrl;
2610
+ }
2611
+ }
2612
+ function transportMatches(requestedTransport, actualTransport) {
2613
+ return !requestedTransport || ((actualTransport & requestedTransport) !== 0);
2614
+ }
2615
+ /** @private */
2616
+ class TransportSendQueue {
2617
+ constructor(_transport) {
2618
+ this._transport = _transport;
2619
+ this._buffer = [];
2620
+ this._executing = true;
2621
+ this._sendBufferedData = new PromiseSource();
2622
+ this._transportResult = new PromiseSource();
2623
+ this._sendLoopPromise = this._sendLoop();
2624
+ }
2625
+ send(data) {
2626
+ this._bufferData(data);
2627
+ if (!this._transportResult) {
2628
+ this._transportResult = new PromiseSource();
2629
+ }
2630
+ return this._transportResult.promise;
2631
+ }
2632
+ stop() {
2633
+ this._executing = false;
2634
+ this._sendBufferedData.resolve();
2635
+ return this._sendLoopPromise;
2636
+ }
2637
+ _bufferData(data) {
2638
+ if (this._buffer.length && typeof (this._buffer[0]) !== typeof (data)) {
2639
+ throw new Error(`Expected data to be of type ${typeof (this._buffer)} but was of type ${typeof (data)}`);
2640
+ }
2641
+ this._buffer.push(data);
2642
+ this._sendBufferedData.resolve();
2643
+ }
2644
+ async _sendLoop() {
2645
+ while (true) {
2646
+ await this._sendBufferedData.promise;
2647
+ if (!this._executing) {
2648
+ if (this._transportResult) {
2649
+ this._transportResult.reject("Connection stopped.");
2650
+ }
2651
+ break;
2652
+ }
2653
+ this._sendBufferedData = new PromiseSource();
2654
+ const transportResult = this._transportResult;
2655
+ this._transportResult = undefined;
2656
+ const data = typeof (this._buffer[0]) === "string" ?
2657
+ this._buffer.join("") :
2658
+ TransportSendQueue._concatBuffers(this._buffer);
2659
+ this._buffer.length = 0;
2660
+ try {
2661
+ await this._transport.send(data);
2662
+ transportResult.resolve();
2663
+ }
2664
+ catch (error) {
2665
+ transportResult.reject(error);
2666
+ }
2667
+ }
2668
+ }
2669
+ static _concatBuffers(arrayBuffers) {
2670
+ const totalLength = arrayBuffers.map((b) => b.byteLength).reduce((a, b) => a + b);
2671
+ const result = new Uint8Array(totalLength);
2672
+ let offset = 0;
2673
+ for (const item of arrayBuffers) {
2674
+ result.set(new Uint8Array(item), offset);
2675
+ offset += item.byteLength;
2676
+ }
2677
+ return result.buffer;
2678
+ }
2679
+ }
2680
+ class PromiseSource {
2681
+ constructor() {
2682
+ this.promise = new Promise((resolve, reject) => [this._resolver, this._rejecter] = [resolve, reject]);
2683
+ }
2684
+ resolve() {
2685
+ this._resolver();
2686
+ }
2687
+ reject(reason) {
2688
+ this._rejecter(reason);
2689
+ }
2690
+ }
2691
+
2692
+ // Licensed to the .NET Foundation under one or more agreements.
2693
+ const JSON_HUB_PROTOCOL_NAME = "json";
2694
+ /** Implements the JSON Hub Protocol. */
2695
+ class JsonHubProtocol {
2696
+ constructor() {
2697
+ /** @inheritDoc */
2698
+ this.name = JSON_HUB_PROTOCOL_NAME;
2699
+ /** @inheritDoc */
2700
+ this.version = 1;
2701
+ /** @inheritDoc */
2702
+ this.transferFormat = TransferFormat.Text;
2703
+ }
2704
+ /** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
2705
+ *
2706
+ * @param {string} input A string containing the serialized representation.
2707
+ * @param {ILogger} logger A logger that will be used to log messages that occur during parsing.
2708
+ */
2709
+ parseMessages(input, logger) {
2710
+ // The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error.
2711
+ if (typeof input !== "string") {
2712
+ throw new Error("Invalid input for JSON hub protocol. Expected a string.");
2713
+ }
2714
+ if (!input) {
2715
+ return [];
2716
+ }
2717
+ if (logger === null) {
2718
+ logger = NullLogger.instance;
2719
+ }
2720
+ // Parse the messages
2721
+ const messages = TextMessageFormat.parse(input);
2722
+ const hubMessages = [];
2723
+ for (const message of messages) {
2724
+ const parsedMessage = JSON.parse(message);
2725
+ if (typeof parsedMessage.type !== "number") {
2726
+ throw new Error("Invalid payload.");
2727
+ }
2728
+ switch (parsedMessage.type) {
2729
+ case MessageType.Invocation:
2730
+ this._isInvocationMessage(parsedMessage);
2731
+ break;
2732
+ case MessageType.StreamItem:
2733
+ this._isStreamItemMessage(parsedMessage);
2734
+ break;
2735
+ case MessageType.Completion:
2736
+ this._isCompletionMessage(parsedMessage);
2737
+ break;
2738
+ case MessageType.Ping:
2739
+ // Single value, no need to validate
2740
+ break;
2741
+ case MessageType.Close:
2742
+ // All optional values, no need to validate
2743
+ break;
2744
+ default:
2745
+ // Future protocol changes can add message types, old clients can ignore them
2746
+ logger.log(LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored.");
2747
+ continue;
2748
+ }
2749
+ hubMessages.push(parsedMessage);
2750
+ }
2751
+ return hubMessages;
2752
+ }
2753
+ /** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
2754
+ *
2755
+ * @param {HubMessage} message The message to write.
2756
+ * @returns {string} A string containing the serialized representation of the message.
2757
+ */
2758
+ writeMessage(message) {
2759
+ return TextMessageFormat.write(JSON.stringify(message));
2760
+ }
2761
+ _isInvocationMessage(message) {
2762
+ this._assertNotEmptyString(message.target, "Invalid payload for Invocation message.");
2763
+ if (message.invocationId !== undefined) {
2764
+ this._assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message.");
2765
+ }
2766
+ }
2767
+ _isStreamItemMessage(message) {
2768
+ this._assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message.");
2769
+ if (message.item === undefined) {
2770
+ throw new Error("Invalid payload for StreamItem message.");
2771
+ }
2772
+ }
2773
+ _isCompletionMessage(message) {
2774
+ if (message.result && message.error) {
2775
+ throw new Error("Invalid payload for Completion message.");
2776
+ }
2777
+ if (!message.result && message.error) {
2778
+ this._assertNotEmptyString(message.error, "Invalid payload for Completion message.");
2779
+ }
2780
+ this._assertNotEmptyString(message.invocationId, "Invalid payload for Completion message.");
2781
+ }
2782
+ _assertNotEmptyString(value, errorMessage) {
2783
+ if (typeof value !== "string" || value === "") {
2784
+ throw new Error(errorMessage);
2785
+ }
2786
+ }
2787
+ }
2788
+
2789
+ // Licensed to the .NET Foundation under one or more agreements.
2790
+ const LogLevelNameMapping = {
2791
+ trace: LogLevel.Trace,
2792
+ debug: LogLevel.Debug,
2793
+ info: LogLevel.Information,
2794
+ information: LogLevel.Information,
2795
+ warn: LogLevel.Warning,
2796
+ warning: LogLevel.Warning,
2797
+ error: LogLevel.Error,
2798
+ critical: LogLevel.Critical,
2799
+ none: LogLevel.None,
2800
+ };
2801
+ function parseLogLevel(name) {
2802
+ // Case-insensitive matching via lower-casing
2803
+ // Yes, I know case-folding is a complicated problem in Unicode, but we only support
2804
+ // the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.
2805
+ const mapping = LogLevelNameMapping[name.toLowerCase()];
2806
+ if (typeof mapping !== "undefined") {
2807
+ return mapping;
2808
+ }
2809
+ else {
2810
+ throw new Error(`Unknown log level: ${name}`);
2811
+ }
2812
+ }
2813
+ /** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */
2814
+ class HubConnectionBuilder {
2815
+ configureLogging(logging) {
2816
+ Arg.isRequired(logging, "logging");
2817
+ if (isLogger(logging)) {
2818
+ this.logger = logging;
2819
+ }
2820
+ else if (typeof logging === "string") {
2821
+ const logLevel = parseLogLevel(logging);
2822
+ this.logger = new ConsoleLogger(logLevel);
2823
+ }
2824
+ else {
2825
+ this.logger = new ConsoleLogger(logging);
2826
+ }
2827
+ return this;
2828
+ }
2829
+ withUrl(url, transportTypeOrOptions) {
2830
+ Arg.isRequired(url, "url");
2831
+ Arg.isNotEmpty(url, "url");
2832
+ this.url = url;
2833
+ // Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed
2834
+ // to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.
2835
+ if (typeof transportTypeOrOptions === "object") {
2836
+ this.httpConnectionOptions = { ...this.httpConnectionOptions, ...transportTypeOrOptions };
2837
+ }
2838
+ else {
2839
+ this.httpConnectionOptions = {
2840
+ ...this.httpConnectionOptions,
2841
+ transport: transportTypeOrOptions,
2842
+ };
2843
+ }
2844
+ return this;
2845
+ }
2846
+ /** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.
2847
+ *
2848
+ * @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.
2849
+ */
2850
+ withHubProtocol(protocol) {
2851
+ Arg.isRequired(protocol, "protocol");
2852
+ this.protocol = protocol;
2853
+ return this;
2854
+ }
2855
+ withAutomaticReconnect(retryDelaysOrReconnectPolicy) {
2856
+ if (this.reconnectPolicy) {
2857
+ throw new Error("A reconnectPolicy has already been set.");
2858
+ }
2859
+ if (!retryDelaysOrReconnectPolicy) {
2860
+ this.reconnectPolicy = new DefaultReconnectPolicy();
2861
+ }
2862
+ else if (Array.isArray(retryDelaysOrReconnectPolicy)) {
2863
+ this.reconnectPolicy = new DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);
2864
+ }
2865
+ else {
2866
+ this.reconnectPolicy = retryDelaysOrReconnectPolicy;
2867
+ }
2868
+ return this;
2869
+ }
2870
+ /** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.
2871
+ *
2872
+ * @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.
2873
+ */
2874
+ build() {
2875
+ // If httpConnectionOptions has a logger, use it. Otherwise, override it with the one
2876
+ // provided to configureLogger
2877
+ const httpConnectionOptions = this.httpConnectionOptions || {};
2878
+ // If it's 'null', the user **explicitly** asked for null, don't mess with it.
2879
+ if (httpConnectionOptions.logger === undefined) {
2880
+ // If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.
2881
+ httpConnectionOptions.logger = this.logger;
2882
+ }
2883
+ // Now create the connection
2884
+ if (!this.url) {
2885
+ throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");
2886
+ }
2887
+ const connection = new HttpConnection(this.url, httpConnectionOptions);
2888
+ return HubConnection.create(connection, this.logger || NullLogger.instance, this.protocol || new JsonHubProtocol(), this.reconnectPolicy);
2889
+ }
2890
+ }
2891
+ function isLogger(logger) {
2892
+ return logger.log !== undefined;
2893
+ }
2894
+
2895
+ const { state, onChange, reset } = createStore({
2896
+ connecting: false,
2897
+ connected: false
2898
+ });
2899
+ const signalRStore = { state, onChange, reset };
2900
+
2901
+ class SignalRService {
2902
+ constructor() {
2903
+ console.log("Starting signalR");
2904
+ //TODO: update courseClassId
2905
+ var defaultCourseClassId = 1;
2906
+ var sparkleConfig = EnvironmentConfigService.getInstance().get('sparkle');
2907
+ this.connection = new HubConnectionBuilder()
2908
+ .withUrl(`${sparkleConfig.apiUrl}hubs/sparkle?url=${window.location.href}${"&courseClassId=" + defaultCourseClassId }`, {
2909
+ accessTokenFactory: () => this.getToken(),
2910
+ skipNegotiation: true,
2911
+ transport: HttpTransportType.WebSockets
2912
+ })
2913
+ .configureLogging(LogLevel.Debug)
2914
+ //.withAutomaticReconnect()
2915
+ .withAutomaticReconnect({
2916
+ nextRetryDelayInMilliseconds: retryContext => {
2917
+ if (retryContext.elapsedMilliseconds < 60000) {
2918
+ // If we've been reconnecting for less than 60 seconds so far,
2919
+ // wait between 0 and 10 seconds before the next reconnect attempt.
2920
+ return Math.random() * 10000;
2921
+ }
2922
+ else {
2923
+ // If we've been reconnecting for more than 60 seconds so far, stop reconnecting.
2924
+ return null;
2925
+ }
2926
+ }
2927
+ })
2928
+ .build();
2929
+ this.connection.on("SendMessage", (user, data) => {
2930
+ let payload = JSON.parse(data);
2931
+ console.log("Server said ", user, payload);
2932
+ });
2933
+ this.connection.onclose(error => {
2934
+ });
2935
+ this.connection.onreconnecting(error => {
2936
+ console.assert(this.connection.state === HubConnectionState.Reconnecting);
2937
+ });
2938
+ this.connection.onreconnected(connectionId => {
2939
+ console.assert(this.connection.state === HubConnectionState.Connected);
2940
+ });
2941
+ }
2942
+ static getInstance() {
2943
+ if (!SignalRService.instance) {
2944
+ SignalRService.instance = new SignalRService();
2945
+ }
2946
+ return SignalRService.instance;
2947
+ }
2948
+ async start() {
2949
+ console.log("start");
2950
+ try {
2951
+ signalRStore.state.connecting = true;
2952
+ signalRStore.state.connected = !signalRStore.state.connecting;
2953
+ await this.connection.start();
2954
+ console.log(this.connection);
2955
+ signalRStore.state.connecting = false;
2956
+ signalRStore.state.connected = !signalRStore.state.connecting;
2957
+ console.assert(this.connection.state === HubConnectionState.Connected);
2958
+ console.log("SignalR Connected.");
2959
+ }
2960
+ catch (err) {
2961
+ console.assert(this.connection.state === HubConnectionState.Disconnected);
2962
+ console.log(err);
2963
+ }
2964
+ }
2965
+ ;
2966
+ async callSignalR(hub, data) {
2967
+ console.log('signalR invoke', hub, this.connection.connectionState);
2968
+ if (!this.getToken()) {
2969
+ console.log("Cannot connect to signalR. Not logged in");
2970
+ return;
2971
+ }
2972
+ this.connection.invoke(hub, JSON.stringify(data));
2973
+ console.log('After signalR invoke', hub, this.connection.connectionState);
2974
+ }
2975
+ getToken() {
2976
+ var sparkleConfig = EnvironmentConfigService.getInstance().get('sparkle');
2977
+ if (!!sparkleConfig && !!sparkleConfig.auth && !!sparkleConfig.auth.getToken()) {
2978
+ return sparkle.auth.getToken();
2979
+ }
2980
+ return null;
2981
+ }
2982
+ }
2983
+
2984
+ export { SignalRService as S, signalRStore as s };