forked from balderdashy/sails.io.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sails.io.js
809 lines (649 loc) · 25 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
/**
* 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.org/#!documentation/reference/BrowserSDK/BrowserSDK.html
* ------------------------------------------------------------------------
*
* 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() {
// Save the URL that this script was fetched from for use below.
// (skip this if this SDK is being used outside of the DOM, i.e. in a Node process)
var urlThisScriptWasFetchedFrom = (function() {
if (
typeof window !== 'object' ||
typeof window.document !== 'object' ||
typeof window.document.getElementsByTagName !== 'function'
) {
return '';
}
// 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');
var thisScript = allScriptsCurrentlyInDOM[allScriptsCurrentlyInDOM.length - 1];
return thisScript.src;
})();
// Constants
var CONNECTION_METADATA_PARAMS = {
version: '__sails_io_sdk_version',
platform: '__sails_io_sdk_platform',
language: '__sails_io_sdk_language'
};
// Current version of this SDK (sailsDK?!?!) and other metadata
// that will be sent along w/ the initial connection request.
var SDK_INFO = {
version: '0.10.0', // TODO: pull this automatically from package.json during build.
platform: typeof module === 'undefined' ? 'browser' : 'node',
language: 'javascript'
};
SDK_INFO.versionString =
CONNECTION_METADATA_PARAMS.version + '=' + SDK_INFO.version + '&' +
CONNECTION_METADATA_PARAMS.platform + '=' + SDK_INFO.platform + '&' +
CONNECTION_METADATA_PARAMS.language + '=' + SDK_INFO.language;
// In case you're wrapping the socket.io client to prevent pollution of the
// global namespace, you can pass in your own `io` to replace the global one.
// But we still grab access to the global one if it's available here:
var _io = (typeof io !== 'undefined') ? io : null;
/**
* Augment the `io` object passed in with methods for talking and listening
* to one or more Sails backend(s). Automatically connects a socket and
* exposes it on `io.socket`. If a socket tries to make requests before it
* is connected, the sails.io.js client will queue it up.
*
* @param {SocketIO} io
*/
function SailsIOClient(io) {
// Prefer the passed-in `io` instance, but also use the global one if we've got it.
io = io || _io;
// If the socket.io client is not available, none of this will work.
if (!io) throw new Error('`sails.io.js` requires a socket.io client, but `io` was not passed in.');
//////////////////////////////////////////////////////////////
///// ///////////////////////////
///// PRIVATE METHODS/CONSTRUCTORS ///////////////////////////
///// ///////////////////////////
//////////////////////////////////////////////////////////////
/**
* TmpSocket
*
* A mock Socket used for binding events before the real thing
* has been instantiated (since we need to use io.connect() to
* instantiate the real thing, which would kick off the connection
* process w/ the server, and we don't necessarily have the valid
* configuration to know WHICH SERVER to talk to yet.)
*
* @api private
* @constructor
*/
function TmpSocket() {
var boundEvents = {};
this.on = function (evName, fn) {
if (!boundEvents[evName]) boundEvents[evName] = [fn];
else boundEvents[evName].push(fn);
return this;
};
this.become = function(actualSocket) {
// Pass events and a reference to the request queue
// off to the actualSocket for consumption
for (var evName in boundEvents) {
for (var i in boundEvents[evName]) {
actualSocket.on(evName, boundEvents[evName][i]);
}
}
actualSocket.requestQueue = this.requestQueue;
// Bind a one-time function to run the request queue
// when the actualSocket connects.
if (!_isConnected(actualSocket)) {
var alreadyRanRequestQueue = false;
actualSocket.on('connect', function onActualSocketConnect() {
if (alreadyRanRequestQueue) return;
runRequestQueue(actualSocket);
alreadyRanRequestQueue = true;
});
}
// Or run it immediately if actualSocket is already connected
else {
runRequestQueue(actualSocket);
}
return actualSocket;
};
// Uses `this` instead of `TmpSocket.prototype` purely
// for convenience, since it makes more sense to attach
// our extra methods to the `Socket` prototype down below.
// This could be optimized by moving those Socket method defs
// to the top of this SDK file instead of the bottom. Will
// gladly do it if it is an issue for anyone.
this.get = Socket.prototype.get;
this.post = Socket.prototype.post;
this.put = Socket.prototype.put;
this['delete'] = Socket.prototype['delete'];
this.request = Socket.prototype.request;
this._request = Socket.prototype._request;
}
/**
* 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);
};
}
// Create a private logger instance
var consolog = LoggerFactory();
consolog.noPrefix = LoggerFactory({
prefix: false
});
/**
* _isConnected
*
* @api private
* @param {Socket} socket
* @return {Boolean} whether the socket is connected and able to
* communicate w/ the server.
*/
function _isConnected(socket) {
return socket.socket && socket.socket.connected;
}
/**
* 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 {Socket} 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) {
// Emit the request.
_emitFrom(socket, queue[i]);
}
}
// Now empty the queue to remove it as a source of additional complexity.
queue = null;
}
/**
* Send a JSONP request.
*
* @param {Object} opts [optional]
* @param {Function} cb
* @return {XMLHttpRequest}
*/
function jsonp(opts, cb) {
opts = opts || {};
if (typeof window === 'undefined') {
// TODO: refactor node usage to live in here
return cb();
}
var scriptEl = document.createElement('script');
window._sailsIoJSConnect = cb;
scriptEl.src = opts.url;
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
/**
* The JWR (JSON WebSocket Response) received from a Sails server.
*
* @api private
* @param {Object} responseCtx
* => :body
* => :statusCode
* => :headers
* @constructor
*/
function JWR(responseCtx) {
this.body = responseCtx.body || {};
this.headers = responseCtx.headers || {};
this.statusCode = responseCtx.statusCode || 200;
}
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() {
// TODO: look at substack's stuff
return new Error('Not implemented yet.');
};
/**
* @api private
* @param {Socket} socket [description]
* @param {Object} requestCtx [description]
*/
function _emitFrom(socket, requestCtx) {
// Since callback is embedded in requestCtx,
// retrieve it and delete the key before continuing.
var cb = requestCtx.cb;
delete requestCtx.cb;
// Name of socket request listener on the server
// ( === the request method, e.g. 'get', 'post', 'put', etc. )
var sailsEndpoint = requestCtx.method;
socket.emit(sailsEndpoint, requestCtx, function serverResponded(responseCtx) {
// Adds backwards-compatibility for 0.9.x projects
// If `responseCtx.body` does not exist, the entire
// `responseCtx` object must actually be the `body`.
var body;
if (!responseCtx.body) {
body = responseCtx;
} else {
body = responseCtx.body;
}
// Send back (emulatedHTTPBody, jsonWebSocketResponse)
if (cb) {
cb(body, new JWR(responseCtx));
}
});
}
//////////////////////////////////////////////////////////////
///// </PRIVATE METHODS/CONSTRUCTORS> ////////////////////////
//////////////////////////////////////////////////////////////
// We'll be adding methods to `io.SocketNamespace.prototype`, the prototype for the
// Socket instance returned when the browser connects with `io.connect()`
var Socket = io.SocketNamespace;
/**
* Simulate a GET request to sails
* e.g.
* `socket.get('/user/3', Stats.populate)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.get = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'get',
data: data,
url: url
}, cb);
};
/**
* Simulate a POST request to sails
* e.g.
* `socket.post('/event', newMeeting, $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.post = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'post',
data: data,
url: url
}, cb);
};
/**
* Simulate a PUT request to sails
* e.g.
* `socket.post('/event/3', changedFields, $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype.put = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'put',
data: data,
url: url
}, cb);
};
/**
* Simulate a DELETE request to sails
* e.g.
* `socket.delete('/event', $spinner.hide)`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
*/
Socket.prototype['delete'] = function(url, data, cb) {
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: 'delete',
data: data,
url: url
}, cb);
};
/**
* Simulate an HTTP request to sails
* e.g.
* `socket.request('/user', newUser, $spinner.hide, 'post')`
*
* @api public
* @param {String} url :: destination URL
* @param {Object} params :: parameters to send with the request [optional]
* @param {Function} cb :: callback function to call when finished [optional]
* @param {String} method :: HTTP request method [optional]
*/
Socket.prototype.request = function(url, data, cb, method) {
// `cb` is optional
if (typeof cb === 'string') {
method = cb;
cb = null;
}
// `data` is optional
if (typeof data === 'function') {
cb = data;
data = {};
}
return this._request({
method: method || 'get',
data: data,
url: url
}, cb);
};
/**
* Socket.prototype._request
*
* Simulate HTTP over Socket.io.
*
* @api private
* @param {[type]} options [description]
* @param {Function} cb [description]
*/
Socket.prototype._request = function(options, cb) {
// Sanitize options (also data & headers)
var usage = 'Usage:\n socket.' +
(options.method || 'request') +
'( destinationURL, [dataToSend], [fnToCallWhenComplete] )';
options = options || {};
options.data = options.data || {};
options.headers = options.headers || {};
// Remove trailing slashes and spaces to make packets smaller.
options.url = options.url.replace(/^(.+)\/*\s*$/, '$1');
if (typeof options.url !== 'string') {
throw new Error('Invalid or missing URL!\n' + usage);
}
// Build a simulated request object.
var request = {
method: options.method,
data: options.data,
url: options.url,
headers: options.headers,
cb: cb
};
// If this socket is not connected yet, queue up this request
// instead of sending it.
// (so it can be replayed when the socket comes online.)
if (!_isConnected(this)) {
// If no queue array exists for this socket yet, create it.
this.requestQueue = this.requestQueue || [];
this.requestQueue.push(request);
return;
}
// Otherwise, our socket is ok!
// Send the request.
_emitFrom(this, request);
};
// Set a `sails` object that may be used for configuration before the
// first socket connects (i.e. to prevent auto-connect)
io.sails = {
// Whether to automatically connect a socket and save it as `io.socket`.
autoConnect: true,
// Whether to use JSONP to get a cookie for cross-origin requests
useCORSRouteToGetCookie: true,
// The environment we're running in.
// (logs are not displayed when this is set to 'production')
//
// Defaults to development unless this script was fetched from a URL
// that ends in `*.min.js` or '#production' (may also be manually overridden.)
//
environment: urlThisScriptWasFetchedFrom.match(/(\#production|\.min\.js)/g) ? 'production' : 'development'
};
/**
* Override `io.connect` to coerce it into using the io.sails
* connection URL config, as well as sending identifying information
* (most importantly, the current version of this SDK)
*
* @param {String} url [optional]
* @param {Object} opts [optional]
* @return {Socket}
*/
io.sails._origConnectFn = io.connect;
io.connect = function(url, opts) {
opts = opts || {};
// If explicit connection url is specified, use it
url = url || io.sails.url || undefined;
// Ensure URL has no trailing slash
url = url ? url.replace(/(\/)$/, '') : undefined;
// Mix the current SDK version into the query string in
// the connection request to the server:
if (typeof opts.query !== 'string') opts.query = SDK_INFO.versionString;
else opts.query += '&' + SDK_INFO.versionString;
return io.sails._origConnectFn(url, opts);
};
// io.socket
//
// The eager instance of Socket which will automatically try to connect
// using the host that this js file was served from.
//
// This can be disabled or configured by setting `io.socket.options` within the
// first cycle of the event loop.
//
// In the mean time, this eager socket will be defined as a TmpSocket
// so that events bound by the user before the first cycle of the event
// loop (using `.on()`) can be rebound on the true socket.
io.socket = new TmpSocket();
setTimeout(function() {
// If autoConnect is disabled, delete the TmpSocket and bail out.
if (!io.sails.autoConnect) {
delete io.socket;
return io;
}
// If this is an attempt at a cross-origin or cross-port
// socket connection, send a JSONP request first to ensure
// that a valid cookie is available. This can be disabled
// by setting `io.sails.useCORSRouteToGetCookie` to false.
var isXOrigin = io.sails.url && true; //url.match();
// TODO: check whether the URL is cross-domain
// var port = global.location.port || ('https:' == global.location.protocol ? 443 : 80);
// this.options.host !== global.location.hostname || this.options.port != port;
if (io.sails.useCORSRouteToGetCookie && isXOrigin) {
// Figure out the x-origin CORS route
// (Sails provides a default)
var xOriginCookieRoute = '/__getcookie';
if (typeof io.sails.useCORSRouteToGetCookie === 'string') {
xOriginCookieRoute = io.sails.useCORSRouteToGetCookie;
}
var xOriginCookieURL = io.sails.url + xOriginCookieRoute;
// Make the AJAX request (CORS)
if (typeof window !== 'undefined') {
jsonp({
url: xOriginCookieURL,
method: 'GET'
}, goAheadAndActuallyConnect);
}
// If there's no `window` object, we must be running in Node.js
// so just require the request module and send the HTTP request that
// way.
else {
var mikealsReq = require('request');
mikealsReq.get(io.sails.url + xOriginCookieRoute, function(err, httpResponse, body) {
if (err) {
consolog(
'Failed to connect socket (failed to get cookie)',
'Error:', err
);
return;
}
goAheadAndActuallyConnect();
});
}
} else goAheadAndActuallyConnect();
// Start connecting after the current cycle of the event loop
// has completed.
// consolog('Auto-connecting `io.socket` to Sails... (requests will be queued in the mean-time)');
function goAheadAndActuallyConnect() {
// Initiate connection
var actualSocket = io.connect(io.sails.url);
// Replay event bindings from the existing TmpSocket
io.socket = io.socket.become(actualSocket);
/**
* 'connect' event is triggered when the socket establishes a connection
* successfully.
*/
io.socket.on('connect', function socketConnected() {
consolog.noPrefix(
'\n' +
' |> ' + '\n' +
' \\___/ '
);
consolog(
'`io.socket` connected successfully.' + '\n' +
// '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' +
' (for help, see: http://sailsjs.org/#!documentation/reference/BrowserSDK/BrowserSDK.html)'
);
// consolog('(this app is running in development mode - log messages will be displayed)');
if (!io.socket.$events.disconnect) {
io.socket.on('disconnect', function() {
consolog('====================================');
consolog('io.socket was disconnected from Sails.');
consolog('Usually, this is due to one of the following reasons:' + '\n' +
' -> the server ' + (io.sails.url ? io.sails.url + ' ' : '') + 'was taken down' + '\n' +
' -> your browser lost internet connectivity');
consolog('====================================');
});
}
if (!io.socket.$events.reconnect) {
io.socket.on('reconnect', function(transport, numAttempts) {
var numSecsOffline = io.socket.msSinceConnectionLost / 1000;
consolog(
'io.socket reconnected successfully after being offline ' +
'for ' + numSecsOffline + ' seconds.');
});
}
if (!io.socket.$events.reconnecting) {
io.socket.on('reconnecting', function(msSinceConnectionLost, numAttempts) {
io.socket.msSinceConnectionLost = msSinceConnectionLost;
consolog(
'io.socket is trying to reconnect to Sails...' +
'(attempt #' + numAttempts + ')');
});
}
// 'error' event is triggered if connection can not be established.
// (usually because of a failed authorization, which is in turn
// usually due to a missing or invalid cookie)
if (!io.socket.$events.error) {
io.socket.on('error', function failedToConnect(err) {
// TODO:
// handle failed connections due to failed authorization
// in a smarter way (probably can listen for a different event)
// A bug in Socket.io 0.9.x causes `connect_failed`
// and `reconnect_failed` not to fire.
// Check out the discussion in github issues for details:
// https://github.com/LearnBoost/socket.io/issues/652
// io.socket.on('connect_failed', function () {
// consolog('io.socket emitted `connect_failed`');
// });
// io.socket.on('reconnect_failed', function () {
// consolog('io.socket emitted `reconnect_failed`');
// });
consolog(
'Failed to connect socket (probably due to failed authorization on server)',
'Error:', err
);
});
}
});
}
// TODO:
// 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.)
}, 0); // </setTimeout>
// Return the `io` object.
return io;
}
// Add CommonJS support to allow this client SDK to be used from Node.js.
if (typeof module === 'object' && typeof module.exports !== 'undefined') {
module.exports = SailsIOClient;
return SailsIOClient;
}
// Otherwise, try to instantiate the client:
// In case you're wrapping the socket.io client to prevent pollution of the
// global namespace, you can replace the global `io` with your own `io` here:
return SailsIOClient();
})();