forked from MrSwitch/hello.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hello.all.js
5119 lines (4098 loc) · 121 KB
/
hello.all.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
/*! hellojs v1.6.0 | (c) 2012-2015 Andrew Dodson | MIT https://adodson.com/hello.js/LICENSE */
// ES5 Object.create
if (!Object.create) {
// Shim, Object create
// A shim for Object.create(), it adds a prototype to a new object
Object.create = (function() {
function F() {}
return function(o) {
if (arguments.length != 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o;
return new F();
};
})();
}
// ES5 [].indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(s) {
for (var j = 0; j < this.length; j++) {
if (this[j] === s) {
return j;
}
}
return -1;
};
}
// ES5 [].forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun/*, thisArg*/) {
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
fun.call(thisArg, t[i], i, t);
}
}
return this;
};
}
// ES5 [].filter
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun, thisArg) {
var a = [];
this.forEach(function(val, i, t) {
if (fun.call(thisArg || void 0, val, i, t)) {
a.push(val);
}
});
return a;
};
}
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(fun, thisArg) {
var a = [];
this.forEach(function(val, i, t) {
a.push(fun.call(thisArg || void 0, val, i, t));
});
return a;
};
}
// ES5 isArray
if (!Array.isArray) {
// Function Array.isArray
Array.isArray = function(o) {
return Object.prototype.toString.call(o) === '[object Array]';
};
}
// Test for location.assign
if (typeof window === 'object' && typeof window.location === 'object' && !window.location.assign) {
window.location.assign = function(url) {
window.location = url;
};
}
// Test for Function.bind
if (!Function.prototype.bind) {
// MDN
// Polyfill IE8, does not support native Function.bind
Function.prototype.bind = function(b) {
if (typeof this !== 'function') {
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
function C() {}
var a = [].slice;
var f = a.call(arguments, 1);
var _this = this;
var D = function() {
return _this.apply(this instanceof C ? this : b || window, f.concat(a.call(arguments)));
};
C.prototype = this.prototype;
D.prototype = new C();
return D;
};
}
/**
* @hello.js
*
* HelloJS is a client side Javascript SDK for making OAuth2 logins and subsequent REST calls.
*
* @author Andrew Dodson
* @website https://adodson.com/hello.js/
*
* @copyright Andrew Dodson, 2012 - 2015
* @license MIT: You are free to use and modify this code for any use, on the condition that this copyright notice remains.
*/
var hello = function(name) {
return hello.use(name);
};
hello.utils = {
// Extend the first object with the properties and methods of the second
extend: function(r /*, a[, b[, ...]] */) {
// Get the arguments as an array but ommit the initial item
Array.prototype.slice.call(arguments, 1).forEach(function(a) {
if (r instanceof Object && a instanceof Object && r !== a) {
for (var x in a) {
r[x] = hello.utils.extend(r[x], a[x]);
}
}
else {
r = a;
}
});
return r;
}
};
// Core library
hello.utils.extend(hello, {
settings: {
// OAuth2 authentication defaults
redirect_uri: window.location.href.split('#')[0],
response_type: 'token',
display: 'popup',
state: '',
// OAuth1 shim
// The path to the OAuth1 server for signing user requests
// Want to recreate your own? Checkout https://github.com/MrSwitch/node-oauth-shim
oauth_proxy: 'https://auth-server.herokuapp.com/proxy',
// API timeout in milliseconds
timeout: 20000,
// Default service / network
default_service: null,
// Force authentication
// When hello.login is fired.
// (null): ignore current session expiry and continue with login
// (true): ignore current session expiry and continue with login, ask for user to reauthenticate
// (false): if the current session looks good for the request scopes return the current session.
force: null,
// Page URL
// When 'display=page' this property defines where the users page should end up after redirect_uri
// Ths could be problematic if the redirect_uri is indeed the final place,
// Typically this circumvents the problem of the redirect_url being a dumb relay page.
page_uri: window.location.href
},
// Service configuration objects
services: {},
// Use
// Define a new instance of the HelloJS library with a default service
use: function(service) {
// Create self, which inherits from its parent
var self = Object.create(this);
// Inherit the prototype from its parent
self.settings = Object.create(this.settings);
// Define the default service
if (service) {
self.settings.default_service = service;
}
// Create an instance of Events
self.utils.Event.call(self);
return self;
},
// Initialize
// Define the client_ids for the endpoint services
// @param object o, contains a key value pair, service => clientId
// @param object opts, contains a key value pair of options used for defining the authentication defaults
// @param number timeout, timeout in seconds
init: function(services, options) {
var utils = this.utils;
if (!services) {
return this.services;
}
// Define provider credentials
// Reformat the ID field
for (var x in services) {if (services.hasOwnProperty(x)) {
if (typeof (services[x]) !== 'object') {
services[x] = {id: services[x]};
}
}}
// Merge services if there already exists some
utils.extend(this.services, services);
// Format the incoming
for (x in this.services) {
if (this.services.hasOwnProperty(x)) {
this.services[x].scope = this.services[x].scope || {};
}
}
//
// Update the default settings with this one.
if (options) {
utils.extend(this.settings, options);
// Do this immediatly incase the browser changes the current path.
if ('redirect_uri' in options) {
this.settings.redirect_uri = utils.url(options.redirect_uri).href;
}
}
return this;
},
// Login
// Using the endpoint
// @param network stringify name to connect to
// @param options object (optional) {display mode, is either none|popup(default)|page, scope: email,birthday,publish, .. }
// @param callback function (optional) fired on signin
login: function() {
// Create an object which inherits its parent as the prototype and constructs a new event chain.
var _this = this;
var utils = _this.utils;
var error = utils.error;
var promise = utils.Promise();
// Get parameters
var p = utils.args({network: 's', options: 'o', callback: 'f'}, arguments);
// Local vars
var url;
// Merge/override options with app defaults
var opts = p.options = utils.merge(_this.settings, p.options || {});
// Network
p.network = p.network || _this.settings.default_service;
// Bind callback to both reject and fulfill states
promise.proxy.then(p.callback, p.callback);
// Trigger an event on the global listener
function emit(s, value) {
hello.emit(s, value);
}
promise.proxy.then(emit.bind(this, 'auth.login auth'), emit.bind(this, 'auth.failed auth'));
// Is our service valid?
if (typeof (p.network) !== 'string' || !(p.network in _this.services)) {
// Trigger the default login.
// Ahh we dont have one.
return promise.reject(error('invalid_network', 'The provided network was not recognized'));
}
var provider = _this.services[p.network];
// Create a global listener to capture events triggered out of scope
var callbackId = utils.globalEvent(function(str) {
// The responseHandler returns a string, lets save this locally
var obj;
if (str) {
obj = JSON.parse(str);
}
else {
obj = error('cancelled', 'The authentication was not completed');
}
// Handle these response using the local
// Trigger on the parent
if (!obj.error) {
// Save on the parent window the new credentials
// This fixes an IE10 bug i think... atleast it does for me.
utils.store(obj.network, obj);
// Fulfill a successful login
promise.fulfill({
network: obj.network,
authResponse: obj
});
}
else {
// Reject a successful login
promise.reject(obj);
}
});
var redirectUri = utils.url(opts.redirect_uri).href;
// May be a space-delimited list of multiple, complementary types
var responseType = provider.oauth.response_type || opts.response_type;
// Fallback to token if the module hasn't defined a grant url
if (/\bcode\b/.test(responseType) && !provider.oauth.grant) {
responseType = responseType.replace(/\bcode\b/, 'token');
}
// Query string parameters, we may pass our own arguments to form the querystring
p.qs = {
client_id: encodeURIComponent(provider.id),
response_type: encodeURIComponent(responseType),
redirect_uri: encodeURIComponent(redirectUri),
display: opts.display,
scope: 'basic',
state: {
client_id: provider.id,
network: p.network,
display: opts.display,
callback: callbackId,
state: opts.state,
redirect_uri: redirectUri
}
};
// Get current session for merging scopes, and for quick auth response
var session = utils.store(p.network);
// Scopes (authentication permisions)
// Convert any array, or falsy value to a string.
var scope = (opts.scope || '').toString();
scope = (scope ? scope + ',' : '') + p.qs.scope;
// Append scopes from a previous session.
// This helps keep app credentials constant,
// Avoiding having to keep tabs on what scopes are authorized
if (session && 'scope' in session && session.scope instanceof String) {
scope += ',' + session.scope;
}
// Save in the State
// Convert to a string because IE, has a problem moving Arrays between windows
p.qs.state.scope = utils.unique(scope.split(/[,\s]+/)).join(',');
// Map replace each scope with the providers default scopes
p.qs.scope = scope.replace(/[^,\s]+/ig, function(m) {
// Does this have a mapping?
if (m in provider.scope) {
return provider.scope[m];
}
else {
// Loop through all services and determine whether the scope is generic
for (var x in _this.services) {
var serviceScopes = _this.services[x].scope;
if (serviceScopes && m in serviceScopes) {
// Found an instance of this scope, so lets not assume its special
return '';
}
}
// This is a unique scope to this service so lets in it.
return m;
}
}).replace(/[,\s]+/ig, ',');
// Remove duplication and empty spaces
p.qs.scope = utils.unique(p.qs.scope.split(/,+/)).join(provider.scope_delim || ',');
// Is the user already signed in with the appropriate scopes, valid access_token?
if (opts.force === false) {
if (session && 'access_token' in session && session.access_token && 'expires' in session && session.expires > ((new Date()).getTime() / 1e3)) {
// What is different about the scopes in the session vs the scopes in the new login?
var diff = utils.diff(session.scope || [], p.qs.state.scope || []);
if (diff.length === 0) {
// OK trigger the callback
promise.fulfill({
unchanged: true,
network: p.network,
authResponse: session
});
// Nothing has changed
return promise;
}
}
}
// Page URL
if (opts.display === 'page' && opts.page_uri) {
// Add a page location, place to endup after session has authenticated
p.qs.state.page_uri = utils.url(opts.page_uri).href;
}
// Bespoke
// Override login querystrings from auth_options
if ('login' in provider && typeof (provider.login) === 'function') {
// Format the paramaters according to the providers formatting function
provider.login(p);
}
// Add OAuth to state
// Where the service is going to take advantage of the oauth_proxy
if (!/\btoken\b/.test(responseType) ||
parseInt(provider.oauth.version, 10) < 2 ||
(opts.display === 'none' && provider.oauth.grant && session && session.refresh_token)) {
// Add the oauth endpoints
p.qs.state.oauth = provider.oauth;
// Add the proxy url
p.qs.state.oauth_proxy = opts.oauth_proxy;
}
// Convert state to a string
p.qs.state = encodeURIComponent(JSON.stringify(p.qs.state));
// URL
if (parseInt(provider.oauth.version, 10) === 1) {
// Turn the request to the OAuth Proxy for 3-legged auth
url = utils.qs(opts.oauth_proxy, p.qs, encodeFunction);
}
// Refresh token
else if (opts.display === 'none' && provider.oauth.grant && session && session.refresh_token) {
// Add the refresh_token to the request
p.qs.refresh_token = session.refresh_token;
// Define the request path
url = utils.qs(opts.oauth_proxy, p.qs, encodeFunction);
}
else {
url = utils.qs(provider.oauth.auth, p.qs, encodeFunction);
}
// Execute
// Trigger how we want self displayed
if (opts.display === 'none') {
// Sign-in in the background, iframe
utils.iframe(url);
}
// Triggering popup?
else if (opts.display === 'popup') {
var popup = utils.popup(url, redirectUri, opts.window_width || 500, opts.window_height || 550);
var timer = setInterval(function() {
if (!popup || popup.closed) {
clearInterval(timer);
if (!promise.state) {
var response = error('cancelled', 'Login has been cancelled');
if (!popup) {
response = error('blocked', 'Popup was blocked');
}
response.network = p.network;
promise.reject(response);
}
}
}, 100);
}
else {
window.location = url;
}
return promise.proxy;
function encodeFunction(s) {return s;}
},
// Remove any data associated with a given service
// @param string name of the service
// @param function callback
logout: function() {
var _this = this;
var utils = _this.utils;
var error = utils.error;
// Create a new promise
var promise = utils.Promise();
var p = utils.args({name:'s', options: 'o', callback: 'f'}, arguments);
p.options = p.options || {};
// Add callback to events
promise.proxy.then(p.callback, p.callback);
// Trigger an event on the global listener
function emit(s, value) {
hello.emit(s, value);
}
promise.proxy.then(emit.bind(this, 'auth.logout auth'), emit.bind(this, 'error'));
// Network
p.name = p.name || this.settings.default_service;
if (p.name && !(p.name in _this.services)) {
promise.reject(error('invalid_network', 'The network was unrecognized'));
}
else if (p.name && utils.store(p.name)) {
// Define the callback
var callback = function(opts) {
// Remove from the store
utils.store(p.name, '');
// Emit events by default
promise.fulfill(hello.utils.merge({network:p.name}, opts || {}));
};
// Run an async operation to remove the users session
var _opts = {};
if (p.options.force) {
var logout = _this.services[p.name].logout;
if (logout) {
// Convert logout to URL string,
// If no string is returned, then this function will handle the logout async style
if (typeof (logout) === 'function') {
logout = logout(callback);
}
// If logout is a string then assume URL and open in iframe.
if (typeof (logout) === 'string') {
utils.iframe(logout);
_opts.force = null;
_opts.message = 'Logout success on providers site was indeterminate';
}
else if (logout === undefined) {
// The callback function will handle the response.
return promise.proxy;
}
}
}
// Remove local credentials
callback(_opts);
}
else {
promise.reject(error('invalid_session', 'There was no session to remove'));
}
return promise.proxy;
},
// Returns all the sessions that are subscribed too
// @param string optional, name of the service to get information about.
getAuthResponse: function(service) {
// If the service doesn't exist
service = service || this.settings.default_service;
if (!service || !(service in this.services)) {
return null;
}
return this.utils.store(service) || null;
},
// Events: placeholder for the events
events: {}
});
// Core utilities
hello.utils.extend(hello.utils, {
// Error
error: function(code, message) {
return {
error: {
code: code,
message: message
}
};
},
// Append the querystring to a url
// @param string url
// @param object parameters
qs: function(url, params, formatFunction) {
if (params) {
var reg;
for (var x in params) {
if (url.indexOf(x) > -1) {
var str = '[\\?\\&]' + x + '=[^\\&]*';
reg = new RegExp(str);
url = url.replace(reg, '');
}
}
}
return url + (!this.isEmpty(params) ? (url.indexOf('?') > -1 ? '&' : '?') + this.param(params, formatFunction) : '');
},
// Param
// Explode/encode the parameters of an URL string/object
// @param string s, string to decode
param: function(s, formatFunction) {
var b;
var a = {};
var m;
if (typeof (s) === 'string') {
formatFunction = formatFunction || decodeURIComponent;
m = s.replace(/^[\#\?]/, '').match(/([^=\/\&]+)=([^\&]+)/g);
if (m) {
for (var i = 0; i < m.length; i++) {
b = m[i].match(/([^=]+)=(.*)/);
a[b[1]] = formatFunction(b[2]);
}
}
return a;
}
else {
formatFunction = formatFunction || encodeURIComponent;
var o = s;
a = [];
for (var x in o) {if (o.hasOwnProperty(x)) {
if (o.hasOwnProperty(x)) {
a.push([x, o[x] === '?' ? '?' : formatFunction(o[x])].join('='));
}
}}
return a.join('&');
}
},
// Local storage facade
store: (function(localStorage) {
var a = [localStorage, window.sessionStorage];
var i = 0;
// Set LocalStorage
localStorage = a[i++];
while (localStorage) {
try {
localStorage.setItem(i, i);
localStorage.removeItem(i);
break;
}
catch (e) {
localStorage = a[i++];
}
}
if (!localStorage) {
localStorage = {
getItem: function(prop) {
prop = prop + '=';
var m = document.cookie.split(';');
for (var i = 0; i < m.length; i++) {
var _m = m[i].replace(/(^\s+|\s+$)/, '');
if (_m && _m.indexOf(prop) === 0) {
return _m.substr(prop.length);
}
}
return null;
},
setItem: function(prop, value) {
document.cookie = prop + '=' + value;
}
};
}
function get() {
var json = {};
try {
json = JSON.parse(localStorage.getItem('hello')) || {};
}
catch (e) {}
return json;
}
function set(json) {
localStorage.setItem('hello', JSON.stringify(json));
}
// Check if the browser support local storage
return function(name, value, days) {
// Local storage
var json = get();
if (name && value === undefined) {
return json[name] || null;
}
else if (name && value === null) {
try {
delete json[name];
}
catch (e) {
json[name] = null;
}
}
else if (name) {
json[name] = value;
}
else {
return json;
}
set(json);
return json || null;
};
})(window.localStorage),
// Create and Append new DOM elements
// @param node string
// @param attr object literal
// @param dom/string
append: function(node, attr, target) {
var n = typeof (node) === 'string' ? document.createElement(node) : node;
if (typeof (attr) === 'object') {
if ('tagName' in attr) {
target = attr;
}
else {
for (var x in attr) {if (attr.hasOwnProperty(x)) {
if (typeof (attr[x]) === 'object') {
for (var y in attr[x]) {if (attr[x].hasOwnProperty(y)) {
n[x][y] = attr[x][y];
}}
}
else if (x === 'html') {
n.innerHTML = attr[x];
}
// IE doesn't like us setting methods with setAttribute
else if (!/^on/.test(x)) {
n.setAttribute(x, attr[x]);
}
else {
n[x] = attr[x];
}
}}
}
}
if (target === 'body') {
(function self() {
if (document.body) {
document.body.appendChild(n);
}
else {
setTimeout(self, 16);
}
})();
}
else if (typeof (target) === 'object') {
target.appendChild(n);
}
else if (typeof (target) === 'string') {
document.getElementsByTagName(target)[0].appendChild(n);
}
return n;
},
// An easy way to create a hidden iframe
// @param string src
iframe: function(src) {
this.append('iframe', {src: src, style: {position:'absolute', left: '-1000px', bottom: 0, height: '1px', width: '1px'}}, 'body');
},
// Recursive merge two objects into one, second parameter overides the first
// @param a array
merge: function(/* Args: a, b, c, .. n */) {
var args = Array.prototype.slice.call(arguments);
args.unshift({});
return this.extend.apply(null, args);
},
// Makes it easier to assign parameters, where some are optional
// @param o object
// @param a arguments
args: function(o, args) {
var p = {};
var i = 0;
var t = null;
var x = null;
// 'x' is the first key in the list of object parameters
for (x in o) {if (o.hasOwnProperty(x)) {
break;
}}
// Passing in hash object of arguments?
// Where the first argument can't be an object
if ((args.length === 1) && (typeof (args[0]) === 'object') && o[x] != 'o!') {
// Could this object still belong to a property?
// Check the object keys if they match any of the property keys
for (x in args[0]) {if (o.hasOwnProperty(x)) {
// Does this key exist in the property list?
if (x in o) {
// Yes this key does exist so its most likely this function has been invoked with an object parameter
// Return first argument as the hash of all arguments
return args[0];
}
}}
}
// Else loop through and account for the missing ones.
for (x in o) {if (o.hasOwnProperty(x)) {
t = typeof (args[i]);
if ((typeof (o[x]) === 'function' && o[x].test(args[i])) || (typeof (o[x]) === 'string' && (
(o[x].indexOf('s') > -1 && t === 'string') ||
(o[x].indexOf('o') > -1 && t === 'object') ||
(o[x].indexOf('i') > -1 && t === 'number') ||
(o[x].indexOf('a') > -1 && t === 'object') ||
(o[x].indexOf('f') > -1 && t === 'function')
))
) {
p[x] = args[i++];
}
else if (typeof (o[x]) === 'string' && o[x].indexOf('!') > -1) {
return false;
}
}}
return p;
},
// Returns a URL instance
url: function(path) {
// If the path is empty
if (!path) {
return window.location;
}
// Chrome and FireFox support new URL() to extract URL objects
else if (window.URL && URL instanceof Function && URL.length !== 0) {
return new URL(path, window.location);
}
// Ugly shim, it works!
else {
var a = document.createElement('a');
a.href = path;
return a;
}
},
diff: function(a, b) {
return b.filter(function(item) {
return a.indexOf(item) === -1;
});
},
// Unique
// Remove duplicate and null values from an array
// @param a array
unique: function(a) {
if (!Array.isArray(a)) { return []; }
return a.filter(function(item, index) {
// Is this the first location of item
return a.indexOf(item) === index;
});
},
isEmpty: function(obj) {
// Scalar
if (!obj)
return true;
// Array
if (Array.isArray(obj)) {
return !obj.length;
}
else if (typeof (obj) === 'object') {
// Object
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
}
return true;
},
//jscs:disable
/*!
** Thenable -- Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable
** Copyright (c) 2013-2014 Ralf S. Engelschall <http://engelschall.com>
** Licensed under The MIT License <http://opensource.org/licenses/MIT>
** Source-Code distributed on <http://github.com/rse/thenable>
*/
Promise: (function(){
/* promise states [Promises/A+ 2.1] */
var STATE_PENDING = 0; /* [Promises/A+ 2.1.1] */
var STATE_FULFILLED = 1; /* [Promises/A+ 2.1.2] */
var STATE_REJECTED = 2; /* [Promises/A+ 2.1.3] */
/* promise object constructor */
var api = function (executor) {
/* optionally support non-constructor/plain-function call */
if (!(this instanceof api))
return new api(executor);