-
Notifications
You must be signed in to change notification settings - Fork 118
/
sails.io.js
1717 lines (1417 loc) · 75.4 KB
/
sails.io.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
//////////////////////////////////////////////////////////////////////////////////////
// //
// ███████╗ █████╗ ██╗██╗ ███████╗ ██╗ ██████╗ ██╗███████╗ //
// ██╔════╝██╔══██╗██║██║ ██╔════╝ ██║██╔═══██╗ ██║██╔════╝ //
// ███████╗███████║██║██║ ███████╗ ██║██║ ██║ ██║███████╗ //
// ╚════██║██╔══██║██║██║ ╚════██║ ██║██║ ██║ ██ ██║╚════██║ //
// ███████║██║ ██║██║███████╗███████║██╗██║╚██████╔╝██╗╚█████╔╝███████║ //
// ╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚═╝╚═╝ ╚═════╝ ╚═╝ ╚════╝ ╚══════╝ //
// //
// ╦╔═╗╦ ╦╔═╗╔═╗╔═╗╦═╗╦╔═╗╔╦╗ ╔═╗╦ ╦╔═╗╔╗╔╔╦╗ ╔═╗╔╦╗╦╔═ //
// ║╠═╣╚╗╔╝╠═╣╚═╗║ ╠╦╝║╠═╝ ║ ║ ║ ║║╣ ║║║ ║ ╚═╗ ║║╠╩╗ //
// ╚╝╩ ╩ ╚╝ ╩ ╩╚═╝╚═╝╩╚═╩╩ ╩ ╚═╝╩═╝╩╚═╝╝╚╝ ╩ ╚═╝═╩╝╩ ╩ //
// ┌─┐┌─┐┬─┐ ┌┐┌┌─┐┌┬┐┌─┐ ┬┌─┐ ┌─┐┌┐┌┌┬┐ ┌┬┐┬ ┬┌─┐ ┌┐ ┬─┐┌─┐┬ ┬┌─┐┌─┐┬─┐ //
// ├┤ │ │├┬┘ ││││ │ ││├┤ │└─┐ ├─┤│││ ││ │ ├─┤├┤ ├┴┐├┬┘│ ││││└─┐├┤ ├┬┘ //
// └ └─┘┴└─ ┘└┘└─┘─┴┘└─┘o└┘└─┘ ┴ ┴┘└┘─┴┘ ┴ ┴ ┴└─┘ └─┘┴└─└─┘└┴┘└─┘└─┘┴└─ //
// //
//////////////////////////////////////////////////////////////////////////////////////
/**
* sails.io.js
* ------------------------------------------------------------------------
* JavaScript Client (SDK) for communicating with Sails.
*
* Note that this script is completely optional, but it is handy if you're
* using WebSockets from the browser to talk to your Sails server.
*
* For tips and documentation, visit:
* http://sailsjs.com/documentation/reference/web-sockets/socket-client
* ------------------------------------------------------------------------
*
* This file allows you to send and receive socket.io messages to & from Sails
* by simulating a REST client interface on top of socket.io. It models its API
* after the $.ajax pattern from jQuery you might already be familiar with.
*
* So if you're switching from using AJAX to sockets, instead of:
* `$.post( url, [data], [cb] )`
*
* You would use:
* `socket.post( url, [data], [cb] )`
*/
(function() {
// ██████╗ ██████╗ ███╗ ██╗███████╗████████╗ █████╗ ███╗ ██╗████████╗███████╗
// ██╔════╝██╔═══██╗████╗ ██║██╔════╝╚══██╔══╝██╔══██╗████╗ ██║╚══██╔══╝██╔════╝
// ██║ ██║ ██║██╔██╗ ██║███████╗ ██║ ███████║██╔██╗ ██║ ██║ ███████╗
// ██║ ██║ ██║██║╚██╗██║╚════██║ ██║ ██╔══██║██║╚██╗██║ ██║ ╚════██║
// ╚██████╗╚██████╔╝██║ ╚████║███████║ ██║ ██║ ██║██║ ╚████║ ██║ ███████║
// ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚══════╝
//
/**
* Constant containing the names of all available options
* for individual sockets.
*
* @type {Array}
*/
var SOCKET_OPTIONS = [
'useCORSRouteToGetCookie',
'url',
'multiplex',
'transports',
'query',
'path',
'headers',
'initialConnectionHeaders',
'reconnection',
'reconnectionAttempts',
'reconnectionDelay',
'reconnectionDelayMax',
'rejectUnauthorized',
'randomizationFactor',
'timeout'
];
/**
* Constant containing the names of properties on `io.sails` which
* may be configured using HTML attributes on the script tag which
* loaded this file.
*
* @type {Array}
*
* (this is unused if loading from node.js)
*/
var CONFIGURABLE_VIA_HTML_ATTR = [
'autoConnect',
'reconnection',
'environment',
'headers',
'url',
'transports',
'path'
];
/**
* Constant containing the names of querystring
* parameters sent when connecting any SailsSocket.
*
* @type {Dictionary}
*/
var CONNECTION_METADATA_PARAMS = {
version: '__sails_io_sdk_version',
platform: '__sails_io_sdk_platform',
language: '__sails_io_sdk_language'
};
/**
* Constant containing metadata about the platform, language, and
* current version of this SDK.
*
* @type {Dictionary}
*/
var SDK_INFO = {
version: '1.2.1', // <-- pulled automatically from package.json, do not change!
language: 'javascript',
platform: (function (){
if (typeof module === 'object' && typeof module.exports !== 'undefined') {
return 'node';
}
else {
return 'browser';
}
})()
};
// Build `versionString` (a querystring snippet) by
// combining SDK_INFO and CONNECTION_METADATA_PARAMS.
SDK_INFO.versionString =
CONNECTION_METADATA_PARAMS.version + '=' + SDK_INFO.version + '&' +
CONNECTION_METADATA_PARAMS.platform + '=' + SDK_INFO.platform + '&' +
CONNECTION_METADATA_PARAMS.language + '=' + SDK_INFO.language;
// █████╗ ██████╗ ███████╗ ██████╗ ██████╗ ██████╗ ██╗ ██╗████████╗███╗ ███╗██╗
// ██╔══██╗██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔══██╗ ██║ ██║╚══██╔══╝████╗ ████║██║
// ███████║██████╔╝███████╗██║ ██║██████╔╝██████╔╝ ███████║ ██║ ██╔████╔██║██║
// ██╔══██║██╔══██╗╚════██║██║ ██║██╔══██╗██╔══██╗ ██╔══██║ ██║ ██║╚██╔╝██║██║
// ██║ ██║██████╔╝███████║╚██████╔╝██║ ██║██████╔╝ ██║ ██║ ██║ ██║ ╚═╝ ██║███████╗
// ╚═╝ ╚═╝╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═╝╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝
//
// █████╗ ████████╗████████╗██████╗ ██╗██████╗ ██╗ ██╗████████╗███████╗███████╗
// ██╔══██╗╚══██╔══╝╚══██╔══╝██╔══██╗██║██╔══██╗██║ ██║╚══██╔══╝██╔════╝██╔════╝
// ███████║ ██║ ██║ ██████╔╝██║██████╔╝██║ ██║ ██║ █████╗ ███████╗
// ██╔══██║ ██║ ██║ ██╔══██╗██║██╔══██╗██║ ██║ ██║ ██╔══╝ ╚════██║
// ██║ ██║ ██║ ██║ ██║ ██║██║██████╔╝╚██████╔╝ ██║ ███████╗███████║
// ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚══════╝
//
// ███████╗██████╗ ██████╗ ███╗ ███╗ ██╗███████╗ ██████╗██████╗ ██╗██████╗ ████████╗██╗
// ██╔════╝██╔══██╗██╔═══██╗████╗ ████║ ██╔╝██╔════╝██╔════╝██╔══██╗██║██╔══██╗╚══██╔══╝╚██╗
// █████╗ ██████╔╝██║ ██║██╔████╔██║ ██╔╝ ███████╗██║ ██████╔╝██║██████╔╝ ██║ ╚██╗
// ██╔══╝ ██╔══██╗██║ ██║██║╚██╔╝██║ ╚██╗ ╚════██║██║ ██╔══██╗██║██╔═══╝ ██║ ██╔╝
// ██║ ██║ ██║╚██████╔╝██║ ╚═╝ ██║ ╚██╗███████║╚██████╗██║ ██║██║██║ ██║ ██╔╝
// ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═╝ ╚═╝
//
//
// If available, grab the DOM element for the script tag which imported this file.
// (skip this if this SDK is being used outside of the DOM, i.e. in a Node process)
//
// This is used below to parse client-side sails.io.js configuration encoded as
// HTML attributes, as well as grabbing hold of the URL from whence the SDK was fetched.
var thisScriptTag = (function() {
if (
typeof window !== 'object' ||
typeof window.document !== 'object' ||
typeof window.document.getElementsByTagName !== 'function'
) {
return null;
}
// Return the URL of the last script loaded (i.e. this one)
// (this must run before nextTick; see http://stackoverflow.com/a/2976714/486547)
var allScriptsCurrentlyInDOM = window.document.getElementsByTagName('script');
return allScriptsCurrentlyInDOM[allScriptsCurrentlyInDOM.length - 1];
})();
// Variables to contain src URL and other script tag config (for use below).
var urlThisScriptWasFetchedFrom = '';
var scriptTagConfig = {};
if (thisScriptTag) {
// Save the URL that this script was fetched from.
urlThisScriptWasFetchedFrom = thisScriptTag.src;
// Now parse the most common client-side configuration settings
// from the script tag where they may be encoded as HTML attributes.
//
// Any configuration which may be provided as an HTML attribute may
// also be provided prefixed with `data-`. This is for folks who
// need to support browsers that have issues with nonstandard
// HTML attributes (or if the idea of using nonstandard HTML attributes
// just creeps you out)
//
// If a `data-` prefixed attr is provided, it takes precedence.
// (this is so that if you are already using one of these HTML
// attrs for some reason, you can keep it as-is and override
// it using `data-`. If you are using the `data-` prefixed version
// for some other purpose... well, in that case you'll just have to
// configure programmatically using `io.sails` instead.)
CONFIGURABLE_VIA_HTML_ATTR.forEach(function (configKey){
scriptTagConfig[configKey] = (function (){
// Support 'data-' prefixed or normal attributes.
// (prefixed versions take precedence if provided)
var htmlAttrVal = thisScriptTag.getAttribute( 'data-'+configKey );
if (!htmlAttrVal) {
htmlAttrVal = thisScriptTag.getAttribute( configKey );
}
// The HTML attribute value should always be a string or `null`.
// We'll try to parse it as JSON and use that, but worst case fall back
// to the default situation of it being a string.
if (typeof htmlAttrVal === 'string') {
try { return JSON.parse(htmlAttrVal); } catch (e) { return htmlAttrVal; }
}
// If `null` was returned from getAttribute(), it means that the HTML attribute
// was not specified, so we treat it as undefined (which will cause the property
// to be removed below)
else if (htmlAttrVal === null) {
return undefined;
}
// Any other contingency shouldn't be possible:
// - if no quotes are used in the HTML attribute, it still comes in as a string.
// - if no RHS is provided for the attribute, it still comes in as "" (empty string)
// (but we still handle this with an explicit error just in case--for debugging and support purposes)
else throw new Error('sails.io.js :: Unexpected/invalid script tag configuration for `'+configKey+'`: `'+htmlAttrVal+'` (a `'+typeof htmlAttrVal+'`). Should be a string.');
})();
if (scriptTagConfig[configKey] === undefined){
delete scriptTagConfig[configKey];
}
});
// Now that they've been parsed, do an extremely lean version of
// logical type validation/coercion of provided values.
//////////////////////////////////////////////////////////////////
// `autoConnect`
if (typeof scriptTagConfig.autoConnect !== 'undefined') {
if (scriptTagConfig.autoConnect === '') {
// Special case for empty string. It means `true` (see above).
scriptTagConfig.autoConnect = true;
}
else if (typeof scriptTagConfig.autoConnect !== 'boolean') {
throw new Error('sails.io.js :: Unexpected/invalid configuration for `autoConnect` provided in script tag: `'+scriptTagConfig.autoConnect+'` (a `'+typeof scriptTagConfig.autoConnect+'`). Should be a boolean.');
}
}
// `environment`
if (typeof scriptTagConfig.environment !== 'undefined') {
if (typeof scriptTagConfig.environment !== 'string') {
throw new Error('sails.io.js :: Unexpected/invalid configuration for `environment` provided in script tag: `'+scriptTagConfig.environment+'` (a `'+typeof scriptTagConfig.environment+'`). Should be a string.');
}
}
// `headers`
if (typeof scriptTagConfig.headers !== 'undefined') {
if (typeof scriptTagConfig.headers !== 'object' || Array.isArray(scriptTagConfig.headers)) {
throw new Error('sails.io.js :: Unexpected/invalid configuration for `headers` provided in script tag: `'+scriptTagConfig.headers+'` (a `'+typeof scriptTagConfig.headers+'`). Should be a JSON-compatible dictionary (i.e. `{}`). Don\'t forget those double quotes (""), even on key names! Use single quotes (\'\') to wrap the HTML attribute value; e.g. `headers=\'{"X-Auth": "foo"}\'`');
}
}
// `url`
if (typeof scriptTagConfig.url !== 'undefined') {
if (typeof scriptTagConfig.url !== 'string') {
throw new Error('sails.io.js :: Unexpected/invalid configuration for `url` provided in script tag: `'+scriptTagConfig.url+'` (a `'+typeof scriptTagConfig.url+'`). Should be a string.');
}
}
// OTHER `io.sails` options are NOT CURRENTLY SUPPORTED VIA HTML ATTRIBUTES.
}
// Grab a reference to the global socket.io client (if one is available).
// This is used via closure below to determine which `io` to use when the
// socket.io client instance (`io`) is augmented to become the Sails client
// SDK instance (still `io`).
var _existingGlobalSocketIO = (typeof io !== 'undefined') ? io : undefined;
//////////////////////////////////////////////////////////////
/////
///// NOW FOR BUNCHES OF:
///// - PRIVATE FUNCTION DEFINITIONS
///// - CONSTRUCTORS
///// - AND METHODS
/////
//////////////////////////////////////////////////////////////
//
// ███████╗ █████╗ ██╗██╗ ███████╗ ██╗ ██████╗ ██████╗██╗ ██╗███████╗███╗ ██╗████████╗
// ██╔════╝██╔══██╗██║██║ ██╔════╝ ██║██╔═══██╗ ██╔════╝██║ ██║██╔════╝████╗ ██║╚══██╔══╝
// ███████╗███████║██║██║ ███████╗█████╗██║██║ ██║█████╗██║ ██║ ██║█████╗ ██╔██╗ ██║ ██║
// ╚════██║██╔══██║██║██║ ╚════██║╚════╝██║██║ ██║╚════╝██║ ██║ ██║██╔══╝ ██║╚██╗██║ ██║
// ███████║██║ ██║██║███████╗███████║ ██║╚██████╔╝ ╚██████╗███████╗██║███████╗██║ ╚████║ ██║
// ╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═════╝╚══════╝╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝
//
/**
* SailsIOClient()
*
* Augment the provided Socket.io client object (`io`) with methods for
* talking and listening to one or more Sails backend(s). If no `io` was
* provided (i.e. in a browser setting), then attempt to use the global.
*
* This absorbs implicit `io.sails` configuration, sets a timer for
* automatically connecting a socket (if `io.sails.autoConnect` is enabled)
* and returns the augmented `io`.
*
* Note:
* The automatically-connected socket is exposed as `io.socket`. If this
* socket attempts to bind event listeners or send requests before it is
* connected, it will be queued up and replayed when the connection is
* successfully opened.
*
* @param {SocketIO} io
* @returns {SailsIOClient} [also called `io`]
*/
function SailsIOClient(_providedSocketIO) {
// First, determine which `io` we're augmenting.
//
// Prefer the passed-in `io` instance, but fall back to the
// global one if we've got it.
var io;
if (_providedSocketIO) {
io = _providedSocketIO;
}
else {
io = _existingGlobalSocketIO;
}
// (note that for readability, we deliberately do not short circuit or use the tertiary operator above)
// If a socket.io client (`io`) is not available, none of this will work.
if (!io) {
// If node:
if (SDK_INFO.platform === 'node') {
throw new Error('No socket.io client available. When requiring `sails.io.js` from Node.js, a socket.io client (`io`) must be passed in; e.g.:\n```\nvar io = require(\'sails.io.js\')( require(\'socket.io-client\') )\n```\n(see https://github.com/balderdashy/sails.io.js/tree/master/test for more examples)');
}
// Otherwise, this is a web browser:
else {
throw new Error('The Sails socket SDK depends on the socket.io client, but the socket.io global (`io`) was not available when `sails.io.js` loaded. Normally, the socket.io client code is bundled with sails.io.js, so something is a little off. Please check to be sure this version of `sails.io.js` has the minified Socket.io client at the top of the file.');
}
}
// If the chosen socket.io client (`io`) has ALREADY BEEN AUGMENTED by this SDK,
// (i.e. if it already has a `.sails` property) then throw an error.
if (io.sails) {
// If node:
if (SDK_INFO.platform === 'node') {
throw new Error('The provided socket.io client (`io`) has already been augmented into a Sails socket SDK instance (it has `io.sails`).');
}
// Otherwise, this is a web browser:
else {
throw new Error('The socket.io client (`io`) has already been augmented into a Sails socket SDK instance. Usually, this means you are bringing `sails.io.js` onto the page more than once.');
}
}
/**
* A little logger for this library to use internally.
* Basically just a wrapper around `console.log` with
* support for feature-detection.
*
* @api private
* @factory
*/
function LoggerFactory(options) {
options = options || {
prefix: true
};
// If `console.log` is not accessible, `log` is a noop.
if (
typeof console !== 'object' ||
typeof console.log !== 'function' ||
typeof console.log.bind !== 'function'
) {
return function noop() {};
}
return function log() {
var args = Array.prototype.slice.call(arguments);
// All logs are disabled when `io.sails.environment = 'production'`.
if (io.sails.environment === 'production') return;
// Add prefix to log messages (unless disabled)
var PREFIX = '';
if (options.prefix) {
args.unshift(PREFIX);
}
// Call wrapped logger
console.log
.bind(console)
.apply(this, args);
};
}//</LoggerFactory>
// Create a private logger instance
var consolog = LoggerFactory();
consolog.noPrefix = LoggerFactory({
prefix: false
});
/**
* What is the `requestQueue`?
*
* The request queue is used to simplify app-level connection logic--
* i.e. so you don't have to wait for the socket to be connected
* to start trying to synchronize data.
*
* @api private
* @param {SailsSocket} socket
*/
function runRequestQueue (socket) {
var queue = socket.requestQueue;
if (!queue) return;
for (var i in queue) {
// Double-check that `queue[i]` will not
// inadvertently discover extra properties attached to the Object
// and/or Array prototype by other libraries/frameworks/tools.
// (e.g. Ember does this. See https://github.com/balderdashy/sails.io.js/pull/5)
var isSafeToDereference = ({}).hasOwnProperty.call(queue, i);
if (isSafeToDereference) {
// Get the arguments that were originally made to the "request" method
var requestArgs = queue[i];
// Call the request method again in the context of the socket, with the original args
socket.request.apply(socket, requestArgs);
}
}
// Now empty the queue to remove it as a source of additional complexity.
socket.requestQueue = null;
}
/**
* Send a JSONP request.
*
* @param {Object} opts [optional]
* @param {Function} cb
* @return {XMLHttpRequest}
*/
function jsonp(opts, cb) {
opts = opts || {};
if (typeof window === 'undefined') {
// FUTURE: refactor node usage to live in here
return cb();
}
var scriptEl = document.createElement('script');
window._sailsIoJSConnect = function(response) {
// In rare circumstances our script may have been vaporised.
// Remove it, but only if it still exists
// https://github.com/balderdashy/sails.io.js/issues/92
if (scriptEl && scriptEl.parentNode) {
scriptEl.parentNode.removeChild(scriptEl);
}
cb(response);
};
scriptEl.src = opts.url;
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
// ██╗███████╗ ██████╗ ███╗ ██╗ ██╗ ██╗███████╗██████╗ ███████╗ ██████╗ ██████╗██╗ ██╗███████╗████████╗
// ██║██╔════╝██╔═══██╗████╗ ██║ ██║ ██║██╔════╝██╔══██╗██╔════╝██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝
// ██║███████╗██║ ██║██╔██╗ ██║█████╗██║ █╗ ██║█████╗ ██████╔╝███████╗██║ ██║██║ █████╔╝ █████╗ ██║
// ██ ██║╚════██║██║ ██║██║╚██╗██║╚════╝██║███╗██║██╔══╝ ██╔══██╗╚════██║██║ ██║██║ ██╔═██╗ ██╔══╝ ██║
// ╚█████╔╝███████║╚██████╔╝██║ ╚████║ ╚███╔███╔╝███████╗██████╔╝███████║╚██████╔╝╚██████╗██║ ██╗███████╗ ██║
// ╚════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚══╝╚══╝ ╚══════╝╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝
//
// ██████╗ ███████╗███████╗██████╗ ██████╗ ███╗ ██╗███████╗███████╗ ██╗ ██╗██╗ ██╗██████╗ ██╗
// ██╔══██╗██╔════╝██╔════╝██╔══██╗██╔═══██╗████╗ ██║██╔════╝██╔════╝ ██╔╝ ██║██║ ██║██╔══██╗╚██╗
// ██████╔╝█████╗ ███████╗██████╔╝██║ ██║██╔██╗ ██║███████╗█████╗ ██║ ██║██║ █╗ ██║██████╔╝ ██║
// ██╔══██╗██╔══╝ ╚════██║██╔═══╝ ██║ ██║██║╚██╗██║╚════██║██╔══╝ ██║ ██ ██║██║███╗██║██╔══██╗ ██║
// ██║ ██║███████╗███████║██║ ╚██████╔╝██║ ╚████║███████║███████╗ ╚██╗╚█████╔╝╚███╔███╔╝██║ ██║██╔╝
// ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝╚══════╝ ╚═╝ ╚════╝ ╚══╝╚══╝ ╚═╝ ╚═╝╚═╝
//
/**
* The JWR (JSON WebSocket Response) received from a Sails server.
*
* @api public
* @param {Object} responseCtx
* => :body
* => :statusCode
* => :headers
*
* @constructor
*/
function JWR(responseCtx) {
this.body = responseCtx.body;
this.headers = responseCtx.headers || {};
this.statusCode = (typeof responseCtx.statusCode === 'undefined') ? 200 : responseCtx.statusCode;
// FUTURE: Replace this typeof short-circuit with an assertion (statusCode should always be set)
if (this.statusCode < 200 || this.statusCode >= 400) {
// Determine the appropriate error message.
var msg;
if (this.statusCode === 0) {
msg = 'The socket request failed.';
}
else {
msg = 'Server responded with a ' + this.statusCode + ' status code';
msg += ':\n```\n' + JSON.stringify(this.body, null, 2) + '\n```';
// (^^Note that we should always be able to rely on socket.io to give us
// non-circular data here, so we don't have to worry about wrapping the
// above in a try...catch)
}
// Now build and attach Error instance.
this.error = new Error(msg);
}
}
JWR.prototype.toString = function() {
return '[ResponseFromSails]' + ' -- ' +
'Status: ' + this.statusCode + ' -- ' +
'Headers: ' + this.headers + ' -- ' +
'Body: ' + this.body;
};
JWR.prototype.toPOJO = function() {
return {
body: this.body,
headers: this.headers,
statusCode: this.statusCode
};
};
JWR.prototype.pipe = function() {
// FUTURE: look at substack's stuff
return new Error('Client-side streaming support not implemented yet.');
};
// ███████╗███╗ ███╗██╗████████╗███████╗██████╗ ██████╗ ███╗ ███╗ ██╗██╗
// ██╔════╝████╗ ████║██║╚══██╔══╝██╔════╝██╔══██╗██╔═══██╗████╗ ████║██╔╝╚██╗
// █████╗ ██╔████╔██║██║ ██║ █████╗ ██████╔╝██║ ██║██╔████╔██║██║ ██║
// ██╔══╝ ██║╚██╔╝██║██║ ██║ ██╔══╝ ██╔══██╗██║ ██║██║╚██╔╝██║██║ ██║
// ███████╗███████╗██║ ╚═╝ ██║██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚═╝ ██║╚██╗██╔╝
// ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝
//
/**
* @api private
* @param {SailsSocket} socket [description]
* @param {Object} requestCtx [description]
*/
function _emitFrom(socket, requestCtx) {
if (!socket._raw) {
throw new Error('Failed to emit from socket- raw SIO socket is missing.');
}
// Since callback is embedded in requestCtx,
// retrieve it and delete the key before continuing.
var cb = requestCtx.cb;
delete requestCtx.cb;
// Name of the appropriate socket.io listener on the server
// ( === the request method or "verb", e.g. 'get', 'post', 'put', etc. )
var sailsEndpoint = requestCtx.method;
socket._raw.emit(sailsEndpoint, requestCtx, function serverResponded(responseCtx) {
// Send back (emulatedHTTPBody, jsonWebSocketResponse)
if (cb && !requestCtx.calledCb) {
cb(responseCtx.body, new JWR(responseCtx));
// Set flag indicating that callback was called, to avoid duplicate calls.
requestCtx.calledCb = true;
// Remove the callback from the list.
socket._responseCbs.splice(socket._responseCbs.indexOf(cb), 1);
// Remove the context from the list.
socket._requestCtxs.splice(socket._requestCtxs.indexOf(requestCtx), 1);
}
});
}
// ███████╗ █████╗ ██╗██╗ ███████╗███████╗ ██████╗ ██████╗██╗ ██╗███████╗████████╗
// ██╔════╝██╔══██╗██║██║ ██╔════╝██╔════╝██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝
// ███████╗███████║██║██║ ███████╗███████╗██║ ██║██║ █████╔╝ █████╗ ██║
// ╚════██║██╔══██║██║██║ ╚════██║╚════██║██║ ██║██║ ██╔═██╗ ██╔══╝ ██║
// ███████║██║ ██║██║███████╗███████║███████║╚██████╔╝╚██████╗██║ ██╗███████╗ ██║
// ╚══════╝╚═╝ ╚═╝╚═╝╚══════╝╚══════╝╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝
//
/**
* SailsSocket
*
* A wrapper for an underlying Socket instance that communicates directly
* to the Socket.io server running inside of Sails.
*
* If no `socket` option is provied, SailsSocket will function as a mock. It will queue socket
* requests and event handler bindings, replaying them when the raw underlying socket actually
* connects. This is handy when we don't necessarily have the valid configuration to know
* WHICH SERVER to talk to yet, etc. It is also used by `io.socket` for your convenience.
*
* @constructor
* @api private
*
* ----------------------------------------------------------------------
* Note: This constructor should not be used directly. To obtain a `SailsSocket`
* instance of your very own, run:
* ```
* var mySocket = io.sails.connect();
* ```
* ----------------------------------------------------------------------
*/
function SailsSocket (opts){
var self = this;
opts = opts||{};
// Initialize private properties
self._isConnecting = false;
self._mightBeAboutToAutoConnect = false;
// Set up connection options so that they can only be changed when socket is disconnected.
var _opts = {};
SOCKET_OPTIONS.forEach(function(option) {
// Okay to change global headers while socket is connected
if (option == 'headers') {return;}
Object.defineProperty(self, option, {
get: function() {
if (option == 'url') {
return _opts[option] || (self._raw && self._raw.io && self._raw.io.uri);
}
return _opts[option];
},
set: function(value) {
// Don't allow value to be changed while socket is connected
if (self.isConnected() && io.sails.strict !== false && value != _opts[option]) {
throw new Error('Cannot change value of `' + option + '` while socket is connected.');
}
// If socket is attempting to reconnect, stop it.
if (self._raw && self._raw.io && self._raw.io.reconnecting && !self._raw.io.skipReconnect) {
self._raw.io.skipReconnect = true;
consolog('Stopping reconnect; use .reconnect() to connect socket after changing options.');
}
_opts[option] = value;
}
});
});
// Absorb opts into SailsSocket instance
// See http://sailsjs.com/documentation/reference/web-sockets/socket-client/sails-socket/properties
// for description of options
SOCKET_OPTIONS.forEach(function(option) {
self[option] = opts[option];
});
// Set up "eventQueue" to hold event handlers which have not been set on the actual raw socket yet.
self.eventQueue = {};
// Listen for special `parseError` event sent from sockets hook on the backend
// if an error occurs but a valid callback was not received from the client
// (i.e. so the server had no other way to send back the error information)
self.on('sails:parseError', function (err){
consolog('Sails encountered an error parsing a socket message sent from this client, and did not have access to a callback function to respond with.');
consolog('Error details:',err);
});
// FUTURE:
// Listen for a special private message on any connected that allows the server
// to set the environment (giving us 100% certainty that we guessed right)
// However, note that the `console.log`s called before and after connection
// are still forced to rely on our existing heuristics (to disable, tack #production
// onto the URL used to fetch this file.)
}//</SailsSocket>
/**
* `SailsSocket.prototype._connect()`
*
* Begin connecting this socket to the server.
*
* @api private
*/
SailsSocket.prototype._connect = function (){
var self = this;
self._isConnecting = true;
// Apply `io.sails` config as defaults
// (now that at least one tick has elapsed)
// See http://sailsjs.com/documentation/reference/web-sockets/socket-client/sails-socket/properties
// for description of options and default values
SOCKET_OPTIONS.forEach(function(option) {
if ('undefined' == typeof self[option]) {
self[option] = io.sails[option];
}
});
// Headers that will be sent with the initial request to /socket.io (Node.js only)
self.extraHeaders = self.initialConnectionHeaders || {};
// For browser usage (currently works with "polling" transport only)
self.transportOptions = self.transportOptions || {};
self.transports.forEach(function(transport) {
self.transportOptions[transport] = self.transportOptions[transport] || {};
self.transportOptions[transport].extraHeaders = self.initialConnectionHeaders || {};
});
// Log a warning if non-Node.js platform attempts to use `initialConnectionHeaders` for anything other than `polling`.
if (self.initialConnectionHeaders && SDK_INFO.platform !== 'node' && self.transports.indexOf('polling') === -1 || self.transports.length > 1) {
if (typeof console === 'object' && typeof console.warn === 'function') {
console.warn('When running in browser, `initialConnectionHeaders` option is only available for the `polling` transport.');
}
}
// Ensure URL has no trailing slash
self.url = self.url ? self.url.replace(/(\/)$/, '') : undefined;
// Mix the current SDK version into the query string in
// the connection request to the server:
if (typeof self.query === 'string') {
// (If provided as a string, trim leading question mark,
// just in case one was provided.)
self.query = self.query.replace(/^\?/, '');
self.query += '&' + SDK_INFO.versionString;
}
else if (self.query && typeof self.query === 'object') {
throw new Error('`query` setting does not currently support configuration as a dictionary (`{}`). Instead, it must be specified as a string like `foo=89&bar=hi`');
}
else if (!self.query) {
self.query = SDK_INFO.versionString;
}
else {
throw new Error('Unexpected data type provided for `query` setting: '+self.query);
}
// Determine whether this is a cross-origin socket by examining the
// hostname and port on the `window.location` object. If it's cross-origin,
// we'll attempt to get a cookie for the domain so that a Sails session can
// be established.
var isXOrigin = (function (){
// If `window` doesn't exist (i.e. being used from Node.js), then
// we won't bother attempting to get a cookie. If you're using sockets
// from Node.js and find you need to share a session between multiple
// socket connections, you'll need to make an HTTP request to the /__getcookie
// endpoint of the Sails server (or any endpoint that returns a set-cookie header)
// and then use the cookie value in the `initialConnectionHeaders` option to
// io.sails.connect()
if (typeof window === 'undefined' || typeof window.location === 'undefined') {
return false;
}
// If `self.url` (aka "target") is falsy, then we don't need to worry about it.
if (typeof self.url !== 'string') { return false; }
// Get information about the "target" (`self.url`)
var targetProtocol = (function (){
try {
targetProtocol = self.url.match(/^([a-z]+:\/\/)/i)[1].toLowerCase();
}
catch (e) {}
targetProtocol = targetProtocol || 'http://';
return targetProtocol;
})();
var isTargetSSL = !!self.url.match('^https');
var targetPort = (function (){
try {
return self.url.match(/^[a-z]+:\/\/[^:]*:([0-9]*)/i)[1];
}
catch (e){}
return isTargetSSL ? '443' : '80';
})();
var targetAfterProtocol = self.url.replace(/^([a-z]+:\/\/)/i, '');
// If target protocol is different than the actual protocol,
// then we'll consider this cross-origin.
if (targetProtocol.replace(/[:\/]/g, '') !== window.location.protocol.replace(/[:\/]/g,'')) {
return true;
}
// If target hostname is different than actual hostname, we'll consider this cross-origin.
var hasSameHostname = targetAfterProtocol.search(window.location.hostname) === 0;
if (!hasSameHostname) {
return true;
}
// If no actual port is explicitly set on the `window.location` object,
// we'll assume either 80 or 443.
var isLocationSSL = window.location.protocol.match(/https/i);
var locationPort = (window.location.port+'') || (isLocationSSL ? '443' : '80');
// Finally, if ports don't match, we'll consider this cross-origin.
if (targetPort !== locationPort) {
return true;
}
// Otherwise, it's the same origin.
return false;
})();
// Prepare to start connecting the socket
(function selfInvoking (cb){
// If this is an attempt at a cross-origin or cross-port
// socket connection via a browswe, send a JSONP request
// first to ensure that a valid cookie is available.
// This can be disabled by setting `io.sails.useCORSRouteToGetCookie`
// to false.
//
// Otherwise, skip the stuff below.
//
if (!(self.useCORSRouteToGetCookie && isXOrigin)) {
return cb();
}
// Figure out the x-origin CORS route
// (Sails provides a default)
var xOriginCookieURL = self.url;
if (typeof self.useCORSRouteToGetCookie === 'string') {
xOriginCookieURL += self.useCORSRouteToGetCookie;
}
else {
xOriginCookieURL += '/__getcookie';
}
// Make the AJAX request (CORS)
jsonp({
url: xOriginCookieURL,
method: 'GET'
}, cb);
})(function goAheadAndActuallyConnect() {
// Now that we're ready to connect, create a raw underlying Socket
// using Socket.io and save it as `_raw` (this will start it connecting)
self._raw = io(self.url, self);
// If the low-level transport throws an error _while connecting_, then set the _isConnecting flag
// to false (since we're no longer connecting with any chance of success anyway).
// Also, in this case (and in dev mode only) log a helpful message.
self._raw.io.engine.transport.on('error', function(err){
if (!self._isConnecting) { return; }
self._isConnecting = false;
// Track this timestamp for use in reconnection messages
// (only relevant if reconnection is enabled.)
self.connectionErrorTimestamp = (new Date()).getTime();
// Development-only message:
consolog('====================================');
consolog('The socket was unable to connect.');
consolog('The server may be offline, or the');
consolog('socket may have failed authorization');
consolog('based on its origin or other factors.');
consolog('You may want to check the values of');
consolog('`sails.config.sockets.onlyAllowOrigins`');
consolog('or (more rarely) `sails.config.sockets.beforeConnect`');
consolog('in your app.');
consolog('More info: https://sailsjs.com/config/sockets');
consolog('For help: https://sailsjs.com/support');
consolog('');
consolog('Technical details:');
consolog(err);
consolog('====================================');
});
// Replay event bindings from the eager socket
self.replay();
/**
* 'connect' event is triggered when the socket establishes a connection
* successfully.
*/
self.on('connect', function socketConnected() {
self._isConnecting = false;
consolog.noPrefix(
'\n' +
'\n' +
// ' |> ' + '\n' +
// ' \\___/ '+️
// '\n'+
' |> Now connected to '+(self.url ? self.url : 'Sails')+'.' + '\n' +
'\\___/ For help, see: http://bit.ly/2q0QDpf' + '\n' +
' (using sails.io.js '+io.sails.sdk.platform+' SDK @v'+io.sails.sdk.version+')'+ '\n' +
' Connected at: '+(new Date())+'\n'+
'\n'+
'\n'+
// '\n'+
''
// ' ⚓︎ (development mode)'
// 'e.g. to send a GET request to Sails via WebSockets, run:'+ '\n' +
// '`io.socket.get("/foo", function serverRespondedWith (body, jwr) { console.log(body); })`'+ '\n' +
);
});
self.on('disconnect', function() {
// Get a timestamp of when the disconnect was detected.
self.connectionLostTimestamp = (new Date()).getTime();
// Get a shallow clone of the internal array of response callbacks, in case any of the callbacks mutate it.
var responseCbs = [].concat(self._responseCbs || []);
// Wipe the internal array of response callbacks before executing them, in case a callback happens to add
// a new request to the queue.
self._responseCbs = [];
// Do the same for the internal request context list.
var requestCtxs = [].concat(self._requestCtxs || []);
self._requestCtxs = [];
// Loop through the callbacks for all in-progress requests, and call them each with an error indicating the disconnect.
if (responseCbs.length) {
responseCbs.forEach(function(responseCb) {
responseCb(new Error('The socket disconnected before the request completed.'), {
body: null,
statusCode: 0,
headers: {}
});
});
}
// If there is a list of request contexts, indicate that their callbacks have been
// called and then wipe the list. This prevents errors in the edge case of a response
// somehow coming back after the socket reconnects.
if (requestCtxs.length) {
requestCtxs.forEach(function(requestCtx) {
requestCtx.calledCb = true;
});
}
consolog('====================================');
consolog('Socket was disconnected from Sails.');
consolog('Usually, this is due to one of the following reasons:' + '\n' +
' -> the server ' + (self.url ? self.url + ' ' : '') + 'was taken down' + '\n' +
' -> your browser lost internet connectivity');
consolog('====================================');
});
self.on('reconnecting', function(numAttempts) {
consolog(
'\n'+
' Socket is trying to reconnect to '+(self.url ? self.url : 'Sails')+'...\n'+
'_-|>_- (attempt #' + numAttempts + ')'+'\n'+
'\n'
);
});
self.on('reconnect', function(transport, numAttempts) {
if (!self._isConnecting) {
self.on('connect', runRequestQueue.bind(self, self));