-
Notifications
You must be signed in to change notification settings - Fork 16
/
Client.js
2325 lines (2084 loc) · 79.1 KB
/
Client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {TransportRegistry} from "./TransportRegistry.js";
import {CallbackPollingTransport} from "./CallbackPollingTransport.js";
import {LongPollingTransport} from "./LongPollingTransport.js";
import {WebSocketTransport} from "./WebSocketTransport.js";
/**
* Browsers may throttle the Window scheduler,
* so we may replace it with a Worker scheduler.
*/
function Scheduler() {
let _ids = 0;
const _tasks = {};
this.register = (funktion) => {
const id = ++_ids;
_tasks[id] = funktion;
return id;
};
this.unregister = (id) => {
const funktion = _tasks[id];
delete _tasks[id];
return funktion;
};
this.setTimeout = (funktion, delay) => window.setTimeout(funktion, delay);
this.clearTimeout = (id) => {
window.clearTimeout(id);
};
}
/**
* The scheduler code that will run in the Worker.
* Workers have a built-in `self` variable similar to `window`.
*/
function WorkerScheduler() {
const _tasks = {};
self.onmessage = (e) => {
const cmd = e.data;
const id = _tasks[cmd.id];
switch (cmd.type) {
case "setTimeout":
_tasks[cmd.id] = self.setTimeout(() => {
delete _tasks[cmd.id];
self.postMessage({
id: cmd.id,
});
}, cmd.delay);
break;
case "clearTimeout":
delete _tasks[cmd.id];
if (id) {
self.clearTimeout(id);
}
break;
default:
throw new Error("Unknown command " + cmd.type);
}
};
}
/**
* The constructor for a CometD object, identified by an optional name.
* The default name is the string "default".
* @param name the optional name of this cometd object
*/
export class CometD {
#scheduler = new Scheduler();
#name;
#crossDomain = false;
#transports = new TransportRegistry();
#transport;
#status = "disconnected";
#messageId = 0;
#clientId = null;
#batch = 0;
#messageQueue = [];
#internalBatch = false;
#listenerId = 0;
#listeners = {};
#transportListeners = {};
#backoff = 0;
#scheduledSend = null;
#extensions = [];
#advice = {};
#handshakeProps;
#handshakeCallback;
#callbacks = {};
#remoteCalls = {};
#reestablish = false;
#connected = false;
#unconnectTime = 0;
#handshakeMessages = 0;
#metaConnect = null;
#config = {
useWorkerScheduler: true,
protocol: null,
stickyReconnect: true,
connectTimeout: 0,
maxConnections: 2,
backoffIncrement: 1000,
maxBackoff: 60000,
logLevel: "info",
maxNetworkDelay: 10000,
requestHeaders: {},
appendMessageTypeToURL: true,
autoBatch: false,
urls: {},
maxURILength: 2000,
maxSendBayeuxMessageSize: 8192,
advice: {
timeout: 60000,
interval: 0,
reconnect: undefined,
maxInterval: 0
}
};
constructor(name) {
this.#name = name || "default";
// Initialize transports.
if (window.WebSocket) {
this.registerTransport("websocket", new WebSocketTransport());
}
this.registerTransport("long-polling", new LongPollingTransport());
this.registerTransport("callback-polling", new CallbackPollingTransport());
}
static #fieldValue(object, name) {
try {
return object[name];
} catch (x) {
return undefined;
}
}
/**
* Mixes in the given objects into the target object by copying the properties.
* @param deep if the copy must be deep
* @param target the target object
* @param objects the objects whose properties are copied into the target
*/
_mixin(deep, target, objects) {
const result = target || {};
// Skip first 2 parameters (deep and target), and loop over the others.
for (let i = 2; i < arguments.length; ++i) {
const object = arguments[i];
if (object === undefined || object === null) {
continue;
}
for (let propName in object) {
if (object.hasOwnProperty(propName)) {
const prop = CometD.#fieldValue(object, propName);
const targ = CometD.#fieldValue(result, propName);
// Avoid infinite loops.
if (prop === target) {
continue;
}
// Do not mixin undefined values.
if (prop === undefined) {
continue;
}
if (deep && typeof prop === "object" && prop !== null) {
if (prop instanceof Array) {
result[propName] = this._mixin(deep, targ instanceof Array ? targ : [], prop);
} else {
const source = typeof targ === "object" && !(targ instanceof Array) ? targ : {};
result[propName] = this._mixin(deep, source, prop);
}
} else {
result[propName] = prop;
}
}
}
}
return result;
};
static #isString(value) {
if (value === undefined || value === null) {
return false;
}
return typeof value === "string" || value instanceof String;
}
static #isAlpha(char) {
if (char >= "A" && char <= "Z") {
return true;
}
return char >= "a" && char <= "z";
}
static #isNumeric(char) {
return char >= "0" && char <= "9";
}
static #isAllowed(char) {
switch (char) {
case " ":
case "!":
case "#":
case "$":
case "(":
case ")":
case "*":
case "+":
case "-":
case ".":
case "/":
case "@":
case "_":
case "{":
case "~":
case "}":
return true;
default:
return false;
}
}
static #isValidChannel(value) {
if (!CometD.#isString(value)) {
return false;
}
if (value.length < 2) {
return false;
}
if (value.charAt(0) !== "/") {
return false;
}
for (let i = 1; i < value.length; ++i) {
const char = value.charAt(i);
if (CometD.#isAlpha(char) || CometD.#isNumeric(char) || CometD.#isAllowed(char)) {
continue;
}
return false;
}
return true;
}
static #isFunction(value) {
if (value === undefined || value === null) {
return false;
}
return typeof value === "function";
}
static #zeroPad(value, length) {
let result = "";
while (--length > 0) {
if (value >= Math.pow(10, length)) {
break;
}
result += "0";
}
result += value;
return result;
}
#log(level, args) {
if (window.console) {
const logger = window.console[level];
if (CometD.#isFunction(logger)) {
const now = new Date();
[].splice.call(args, 0, 0, CometD.#zeroPad(now.getHours(), 2) + ":" + CometD.#zeroPad(now.getMinutes(), 2) + ":" +
CometD.#zeroPad(now.getSeconds(), 2) + "." + CometD.#zeroPad(now.getMilliseconds(), 3));
logger.apply(window.console, args);
}
}
}
_warn() {
this.#log("warn", arguments);
};
_info() {
if (this.#config.logLevel !== "warn") {
this.#log("info", arguments);
}
};
_debug() {
if (this.#config.logLevel === "debug") {
this.#log("debug", arguments);
}
};
static #splitURL(url) {
// [1] = protocol://,
// [2] = host:port,
// [3] = host,
// [4] = IPv6_host,
// [5] = IPv4_host,
// [6] = :port,
// [7] = port,
// [8] = uri,
// [9] = rest (query / fragment)
return new RegExp("(^https?://)?(((\\[[^\\]]+])|([^:/?#]+))(:(\\d+))?)?([^?#]*)(.*)?").exec(url);
}
/**
* Returns whether the given hostAndPort is cross domain.
* The default implementation checks against window.location.host
* but this function can be overridden to make it work in non-browser
* environments.
*
* @param hostAndPort the host and port in format host:port
* @return whether the given hostAndPort is cross domain
*/
#isCrossDomain(hostAndPort) {
if (window.location && window.location.host) {
if (hostAndPort) {
return hostAndPort !== window.location.host;
}
}
return false;
};
#configure(configuration) {
this._debug("Configuring cometd object with", configuration);
// Support old style param, where only the Bayeux server URL was passed.
if (CometD.#isString(configuration)) {
configuration = {
url: configuration
};
}
if (!configuration) {
configuration = {};
}
this.#config = this._mixin(false, this.#config, configuration);
const url = this.getURL();
if (!url) {
throw new Error("Missing required configuration parameter 'url' specifying the Bayeux server URL");
}
// Check if we're cross domain.
const urlParts = CometD.#splitURL(url);
const hostAndPort = urlParts[2];
const uri = urlParts[8];
const afterURI = urlParts[9];
this.#crossDomain = this.#isCrossDomain(hostAndPort);
// Check if appending extra path is supported.
if (this.#config.appendMessageTypeToURL) {
if (afterURI !== undefined && afterURI.length > 0) {
this._info("Appending message type to URI", uri, afterURI, "is not supported, disabling 'appendMessageTypeToURL' configuration");
this.#config.appendMessageTypeToURL = false;
} else {
const uriSegments = uri.split("/");
let lastSegmentIndex = uriSegments.length - 1;
if (uri.match(/\/$/)) {
lastSegmentIndex -= 1;
}
if (uriSegments[lastSegmentIndex].indexOf(".") >= 0) {
// Very likely the CometD servlet's URL pattern is mapped to an extension,
// such as *.cometd, so cannot add the extra path in this case.
this._info("Appending message type to URI", uri, "is not supported, disabling 'appendMessageTypeToURL' configuration");
this.#config.appendMessageTypeToURL = false;
}
}
}
if (window.Worker && window.Blob && window.URL && this.#config.useWorkerScheduler) {
let code = WorkerScheduler.toString();
// Remove the function declaration, the opening brace and the closing brace.
code = code.substring(code.indexOf("{") + 1, code.lastIndexOf("}"));
const blob = new window.Blob([code], {
type: "application/json"
});
const blobURL = window.URL.createObjectURL(blob);
const worker = new window.Worker(blobURL);
// Replace setTimeout() and clearTimeout() with the worker implementation.
this.#scheduler.setTimeout = (funktion, delay) => {
const id = this.#scheduler.register(funktion);
worker.postMessage({
id: id,
type: "setTimeout",
delay: delay
});
return id;
};
this.#scheduler.clearTimeout = (id) => {
this.#scheduler.unregister(id);
worker.postMessage({
id: id,
type: "clearTimeout",
});
};
worker.onmessage = (e) => {
const id = e.data.id;
const funktion = this.#scheduler.unregister(id);
if (funktion) {
funktion();
}
};
}
}
#removeListener(subscription) {
if (subscription) {
const subscriptions = this.#listeners[subscription.channel];
if (subscriptions && subscriptions[subscription.id]) {
delete subscriptions[subscription.id];
this._debug("Removed", subscription.listener ? "listener" : "subscription", subscription);
}
}
}
#removeSubscription(subscription) {
if (subscription && !subscription.listener) {
this.#removeListener(subscription);
}
}
#clearSubscriptions() {
for (let channel in this.#listeners) {
if (this.#listeners.hasOwnProperty(channel)) {
const subscriptions = this.#listeners[channel];
if (subscriptions) {
for (let id in subscriptions) {
if (subscriptions.hasOwnProperty(id)) {
this.#removeSubscription(subscriptions[id]);
}
}
}
}
}
}
#setStatus(newStatus) {
const oldStatus = this.getStatus();
if (oldStatus !== newStatus) {
this._debug("Status", oldStatus, "->", newStatus);
this.#status = newStatus;
}
}
#isDisconnected() {
const status = this.#status;
return status === "disconnecting" || status === "disconnected";
}
#nextMessageId() {
const result = ++this.#messageId;
return "" + result;
}
#applyExtension(scope, callback, name, message, outgoing) {
try {
return callback.call(scope, message);
} catch (x) {
const handler = this.onExtensionException;
if (CometD.#isFunction(handler)) {
this._debug("Invoking extension exception handler", name, x);
try {
handler.call(this, x, name, outgoing, message);
} catch (xx) {
this._info("Exception during execution of extension exception handler", name, xx);
}
} else {
this._info("Exception during execution of extension", name, x);
}
return message;
}
}
#applyIncomingExtensions(message) {
for (let i = 0; i < this.#extensions.length; ++i) {
if (message === undefined || message === null) {
break;
}
const extension = this.#extensions[i];
const callback = extension.extension.incoming;
if (CometD.#isFunction(callback)) {
const result = this.#applyExtension(extension.extension, callback, extension.name, message, false);
message = result === undefined ? message : result;
}
}
return message;
}
#applyOutgoingExtensions(message) {
for (let i = this.#extensions.length - 1; i >= 0; --i) {
if (message === undefined || message === null) {
break;
}
const extension = this.#extensions[i];
const callback = extension.extension.outgoing;
if (CometD.#isFunction(callback)) {
const result = this.#applyExtension(extension.extension, callback, extension.name, message, true);
message = result === undefined ? message : result;
}
}
return message;
}
#notify(channel, message) {
const subscriptions = this.#listeners[channel];
if (subscriptions) {
for (let id in subscriptions) {
if (subscriptions.hasOwnProperty(id)) {
const subscription = subscriptions[id];
// Subscriptions may come and go, so the array may have holes.
if (subscription) {
try {
subscription.callback.call(subscription.scope, message);
} catch (x) {
const handler = this.onListenerException;
if (CometD.#isFunction(handler)) {
this._debug("Invoking listener exception handler", subscription, x);
try {
handler.call(this, x, subscription, subscription.listener, message);
} catch (xx) {
this._info("Exception during execution of listener exception handler", subscription, xx);
}
} else {
this._info("Exception during execution of listener", subscription, message, x);
}
}
}
}
}
}
}
#notifyListeners(channel, message) {
// Notify direct listeners
this.#notify(channel, message);
// Notify the globbing listeners
const channelParts = channel.split("/");
const last = channelParts.length - 1;
for (let i = last; i > 0; --i) {
let channelPart = channelParts.slice(0, i).join("/") + "/*";
// We don't want to notify /foo/* if the channel is /foo/bar/baz,
// so we stop at the first non-recursive globbing.
if (i === last) {
this.#notify(channelPart, message);
}
// Add the recursive globber and notify.
channelPart += "*";
this.#notify(channelPart, message);
}
}
#cancelDelayedSend() {
if (this.#scheduledSend !== null) {
this.clearTimeout(this.#scheduledSend);
}
this.#scheduledSend = null;
}
#delayedSend(operation, delay) {
this.#cancelDelayedSend();
const time = this.#advice.interval + delay;
this._debug("Function scheduled in", time, "ms, interval =", this.#advice.interval, "backoff =", this.#backoff, operation);
this.#scheduledSend = this.setTimeout(operation, time);
}
/**
* Delivers the messages to the CometD server
* @param messages the array of messages to send
* @param metaConnect true if this send is on /meta/connect
* @param extraPath an extra path to append to the Bayeux server URL
*/
#send(messages, metaConnect, extraPath) {
// We must be sure that the messages have a clientId.
// This is not guaranteed since the handshake may take time to return
// (and hence the clientId is not known yet) and the application
// may create other messages.
for (let i = 0; i < messages.length; ++i) {
let message = messages[i];
const messageId = message.id;
const clientId = this.getClientId();
if (clientId) {
message.clientId = clientId;
}
message = this.#applyOutgoingExtensions(message);
if (message !== undefined && message !== null) {
// Extensions may have modified the message id, but we need to own it.
message.id = messageId;
messages[i] = message;
} else {
delete this.#callbacks[messageId];
messages.splice(i--, 1);
}
}
if (messages.length === 0) {
return;
}
if (metaConnect) {
this.#metaConnect = messages[0];
}
let url = this.getURL();
if (this.#config.appendMessageTypeToURL) {
// If url does not end with "/", then append it
if (!url.match(/\/$/)) {
url = url + "/";
}
if (extraPath) {
url = url + extraPath;
}
}
const envelope = {
url: url,
sync: false,
messages: messages,
onSuccess: (rcvdMessages) => {
try {
this.#handleMessages(rcvdMessages);
} catch (x) {
this._info("Exception during handling of messages", x);
}
},
onFailure: (conduit, messages, failure) => {
try {
const transport = this.getTransport();
failure.connectionType = transport ? transport.type : "unknown";
this.#handleFailure(conduit, messages, failure);
} catch (x) {
this._info("Exception during handling of failure", x);
}
},
};
this._debug("Send", envelope);
this.getTransport().send(envelope, metaConnect);
}
#queueSend(message) {
if (this.#batch > 0 || this.#internalBatch === true) {
this.#messageQueue.push(message);
} else {
this.#send([message], false);
}
}
/**
* Sends a complete bayeux message.
* This method is exposed as a public so that extensions may use it
* to send bayeux message directly, for example in case of re-sending
* messages that have already been sent but that for some reason must
* be resent.
*/
send(message) {
this.#queueSend(message);
}
#resetBackoff() {
this.#backoff = 0;
}
#increaseBackoff() {
if (this.#backoff < this.#config.maxBackoff) {
this.#backoff += this.getBackoffIncrement();
}
return this.#backoff;
}
/**
* Starts the batch of messages to be sent in a single request.
*/
#startBatch() {
++this.#batch;
this._debug("Starting batch, depth", this.#batch);
}
#flushBatch() {
const messages = this.#messageQueue;
this.#messageQueue = [];
if (messages.length > 0) {
this.#send(messages, false);
}
}
/**
* Ends the batch of messages to be sent in a single request,
* optionally sending messages present in the message queue depending
* on the given argument.
*/
#endBatch() {
--this.#batch;
this._debug("Ending batch, depth", this.#batch);
if (this.#batch < 0) {
throw new Error("Calls to startBatch() and endBatch() are not paired");
}
if (this.#batch === 0 && !this.isDisconnected() && !this.#internalBatch) {
this.#flushBatch();
}
}
/**
* Sends the connect message
*/
#connect() {
if (!this.isDisconnected()) {
const bayeuxMessage = {
id: this.#nextMessageId(),
channel: "/meta/connect",
connectionType: this.getTransport().type,
};
// In case of reload or temporary loss of connection
// we want the next successful connect to return immediately
// instead of being held by the server, so that connect listeners
// can be notified that the connection has been re-established
if (!this.#connected) {
bayeuxMessage.advice = {
timeout: 0,
};
}
this.#setStatus("connecting");
this._debug("Connect sent", bayeuxMessage);
this.#send([bayeuxMessage], true, "connect");
this.#setStatus("connected");
}
}
#delayedConnect(delay) {
this.#setStatus("connecting");
this.#delayedSend(() => {
this.#connect();
}, delay);
}
#updateAdvice(newAdvice) {
if (newAdvice) {
this.#advice = this._mixin(false, {}, this.#config.advice, newAdvice);
this._debug("New advice", this.#advice);
}
}
#disconnect(abort) {
this.#cancelDelayedSend();
const transport = this.getTransport();
if (abort && transport) {
transport.abort();
}
this.#crossDomain = false;
this.#transport = null;
this.#setStatus("disconnected");
this.#clientId = null;
this.#batch = 0;
this.#resetBackoff();
this.#reestablish = false;
this.#connected = false;
this.#unconnectTime = 0;
this.#metaConnect = null;
// Fail any existing queued message
if (this.#messageQueue.length > 0) {
const messages = this.#messageQueue;
this.#messageQueue = [];
this.#handleFailure(undefined, messages, {
reason: "Disconnected",
});
}
}
#notifyTransportException(oldTransport, newTransport, failure) {
const handler = this.onTransportException;
if (CometD.#isFunction(handler)) {
this._debug("Invoking transport exception handler", oldTransport, newTransport, failure);
try {
handler.call(this, failure, oldTransport, newTransport);
} catch (x) {
this._info("Exception during execution of transport exception handler", x);
}
}
}
/**
* Sends the initial handshake message
*/
#handshake(handshakeProps, handshakeCallback) {
if (CometD.#isFunction(handshakeProps)) {
handshakeCallback = handshakeProps;
handshakeProps = undefined;
}
this.#clientId = null;
this.clearSubscriptions();
// Reset the transports if we're not retrying the handshake
if (this.isDisconnected()) {
this.#transports.reset(true);
}
// Reset the advice.
this.#updateAdvice({});
this.#batch = 0;
// Mark the start of an internal batch.
// This is needed because handshake and connect are async.
// It may happen that the application calls init() then subscribe()
// and the subscribe message is sent before the connect message, if
// the subscribe message is not held until the connect message is sent.
// So here we start a batch to hold temporarily any message until
// the connection is fully established.
this.#internalBatch = true;
// Save the properties provided by the user, so that
// we can reuse them during automatic re-handshake
this.#handshakeProps = handshakeProps;
this.#handshakeCallback = handshakeCallback;
const version = "1.0";
// Figure out the transports to send to the server
const url = this.getURL();
const transportTypes = this.#transports.findTransportTypes(version, this.#crossDomain, url);
const bayeuxMessage = {
id: this.#nextMessageId(),
version: version,
minimumVersion: version,
channel: "/meta/handshake",
supportedConnectionTypes: transportTypes,
advice: {
timeout: this.#advice.timeout,
interval: this.#advice.interval
}
};
// Do not allow the user to override important fields.
const message = this._mixin(false, {}, this.#handshakeProps, bayeuxMessage);
// Save the callback.
this._putCallback(message.id, handshakeCallback);
// Pick up the first available transport as initial transport
// since we don't know if the server supports it
if (!this.#transport) {
this.#transport = this.#transports.negotiateTransport(transportTypes, version, this.#crossDomain, url);
if (!this.#transport) {
const failure = "Could not find initial transport among: " + this.getTransportTypes();
this._warn(failure);
throw new Error(failure);
}
}
this._debug("Initial transport is", this.#transport.type);
// We started a batch to hold the application messages,
// so here we must bypass it and send immediately.
this.#setStatus("handshaking");
this._debug("Handshake sent", message);
this.#send([message], false, "handshake");
}
#delayedHandshake(delay) {
this.#setStatus("handshaking");
// We will call #handshake() which will reset #clientId, but we want to avoid
// that between the end of this method and the call to #handshake() someone may
// call publish() (or other methods that call #queueSend()).
this.#internalBatch = true;
this.#delayedSend(() => {
this.#handshake(this.#handshakeProps, this.#handshakeCallback);
}, delay);
}
#notifyCallback(callback, message) {
try {
callback.call(this, message);
} catch (x) {
const handler = this.onCallbackException;
if (CometD.#isFunction(handler)) {
this._debug("Invoking callback exception handler", x);
try {
handler.call(this, x, message);
} catch (xx) {
this._info("Exception during execution of callback exception handler", xx);
}
} else {
this._info("Exception during execution of message callback", x);
}
}
}
_getCallback(messageId) {
return this.#callbacks[messageId];
}
_putCallback(messageId, callback) {
const result = this._getCallback(messageId);
if (CometD.#isFunction(callback)) {
this.#callbacks[messageId] = callback;
}
return result;
};
#handleCallback(message) {
const callback = this._getCallback([message.id]);
if (CometD.#isFunction(callback)) {
delete this.#callbacks[message.id];
this.#notifyCallback(callback, message);
}
}
#handleRemoteCall(message) {
const context = this.#remoteCalls[message.id];
delete this.#remoteCalls[message.id];
if (context) {
this._debug("Handling remote call response for", message, "with context", context);
// Clear the timeout, if present.
const timeout = context.timeout;
if (timeout) {
this.clearTimeout(timeout);
}
const callback = context.callback;
if (CometD.#isFunction(callback)) {
this.#notifyCallback(callback, message);
return true;
}
}
return false;
}
onTransportFailure(message, failureInfo, failureHandler) {
this._debug("Transport failure", failureInfo, "for", message);
const transports = this.getTransportRegistry();
const url = this.getURL();
const crossDomain = this.#isCrossDomain(CometD.#splitURL(url)[2]);
const version = "1.0";
const transportTypes = transports.findTransportTypes(version, crossDomain, url);
if (failureInfo.action === "none") {
if (message.channel === "/meta/handshake") {
if (!failureInfo.transport) {
const failure = "Could not negotiate transport, client=[" + transportTypes + "], server=[" + message.supportedConnectionTypes + "]";
this._warn(failure);
const transport = this.getTransport();
if (transport) {
const transportType = transport.type;
this.#notifyTransportException(transportType, null, {
reason: failure,
connectionType: transportType,
transport: transport
});
}
}
}
} else {
failureInfo.delay = this.getBackoffPeriod();
// Different logic depending on whether we are handshaking or connecting.
if (message.channel === "/meta/handshake") {
if (!failureInfo.transport) {
// The transport is invalid, try to negotiate again.
const oldTransportType = this.#transport ? this.#transport.type : null;
const newTransport = transports.negotiateTransport(transportTypes, version, crossDomain, url);
if (!newTransport) {
this._warn("Could not negotiate transport, client=[" + transportTypes + "]");
this.#notifyTransportException(oldTransportType, null, message.failure);
failureInfo.action = "none";
} else {
const newTransportType = newTransport.type;
this._debug("Transport", oldTransportType, "->", newTransportType);
this.#notifyTransportException(oldTransportType, newTransportType, message.failure);
failureInfo.action = "handshake";
failureInfo.transport = newTransport;
}
}
if (failureInfo.action !== "none") {