forked from kaerus-component/arango
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharango-1.0.0.js
More file actions
6184 lines (5605 loc) · 197 KB
/
arango-1.0.0.js
File metadata and controls
6184 lines (5605 loc) · 197 KB
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
;(function(){
/**
* Require the given path.
*
* @param {String} path
* @return {Object} exports
* @api public
*/
function require(p, parent, orig){
var path = require.resolve(p)
, mod = require.modules[path];
// lookup failed
if (null == path) {
orig = orig || p;
parent = parent || 'root';
throw new Error('failed to require "' + orig + '" from "' + parent + '"');
}
// perform real require()
// by invoking the module's
// registered function
if (!mod.exports) {
mod.exports = {};
mod.client = mod.component = true;
mod.call(this, mod, mod.exports, require.relative(path));
}
return mod.exports;
}
/**
* Registered modules.
*/
require.modules = {};
/**
* Registered aliases.
*/
require.aliases = {};
/**
* Resolve `path`.
*
* Lookup:
*
* - PATH/index.js
* - PATH.js
* - PATH
*
* @param {String} path
* @return {String} path or null
* @api private
*/
require.resolve = function(path){
var orig = path
, reg = path + '.js'
, regJSON = path + '.json'
, index = path + '/index.js'
, indexJSON = path + '/index.json';
return require.modules[reg] && reg
|| require.modules[regJSON] && regJSON
|| require.modules[index] && index
|| require.modules[indexJSON] && indexJSON
|| require.modules[orig] && orig
|| require.aliases[index];
};
/**
* Normalize `path` relative to the current path.
*
* @param {String} curr
* @param {String} path
* @return {String}
* @api private
*/
require.normalize = function(curr, path) {
var segs = [];
if ('.' != path.charAt(0)) return path;
curr = curr.split('/');
path = path.split('/');
for (var i = 0; i < path.length; ++i) {
if ('..' == path[i]) {
curr.pop();
} else if ('.' != path[i] && '' != path[i]) {
segs.push(path[i]);
}
}
return curr.concat(segs).join('/');
};
/**
* Register module at `path` with callback `fn`.
*
* @param {String} path
* @param {Function} fn
* @api private
*/
require.register = function(path, fn){
require.modules[path] = fn;
};
/**
* Alias a module definition.
*
* @param {String} from
* @param {String} to
* @api private
*/
require.alias = function(from, to){
var fn = require.modules[from];
if (!fn) throw new Error('failed to alias "' + from + '", it does not exist');
require.aliases[to] = from;
};
/**
* Return a require function relative to the `parent` path.
*
* @param {String} parent
* @return {Function}
* @api private
*/
require.relative = function(parent) {
var p = require.normalize(parent, '..');
/**
* lastIndexOf helper.
*/
function lastIndexOf(arr, obj){
var i = arr.length;
while (i--) {
if (arr[i] === obj) return i;
}
return -1;
}
/**
* The relative require() itself.
*/
function fn(path){
var orig = path;
path = fn.resolve(path);
return require(path, parent, orig);
}
/**
* Resolve relative to the parent.
*/
fn.resolve = function(path){
// resolve deps by returning
// the dep in the nearest "deps"
// directory
if ('.' != path.charAt(0)) {
var segs = parent.split('/');
var i = lastIndexOf(segs, 'deps') + 1;
if (!i) i = 0;
path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
return path;
}
return require.normalize(p, path);
};
/**
* Check if module is defined at `path`.
*/
fn.exists = function(path){
return !! require.modules[fn.resolve(path)];
};
return fn;
};require.register("kaerus-component-microTask/index.js", function(module, exports, require){
(function(root){
"use strict"
try {root = global} catch(e){ try {root = window} catch(e){} };
var defer, deferred, observer, queue = [];
if(root.process && typeof root.process.nextTick === 'function'){
/* avoid buggy nodejs setImmediate */
if(root.setImmediate && root.process.versions.node.split('.')[1] > '10') defer = root.setImmediate;
else defer = root.process.nextTick;
} else if(root.vertx && typeof root.vertx.runOnLoop === 'function') defer = root.vertx.RunOnLoop;
else if(root.vertx && typeof root.vertx.runOnContext === 'function') defer = root.vertx.runOnContext;
else if(observer = root.MutationObserver || root.WebKitMutationObserver) {
defer = (function(document, observer, drain) {
var el = document.createElement('div');
new observer(drain).observe(el, { attributes: true });
return function() { el.setAttribute('x', 'y'); };
}(document, observer, drain));
}
else if(typeof root.setTimeout === 'function' && (root.ActiveXObject || !root.postMessage)) {
/* use setTimeout to avoid buggy IE MessageChannel */
defer = function(f){ root.setTimeout(f,0); }
}
else if(root.MessageChannel && typeof root.MessageChannel === 'function') {
var fifo = [], channel = new root.MessageChannel();
channel.port1.onmessage = function () { (fifo.shift())() };
defer = function (f){ fifo[fifo.length] = f; channel.port2.postMessage(0); };
}
else if(typeof root.setTimeout === 'function') defer = function(f){ root.setTimeout(f,0); }
else throw new Error("No candidate for microtask defer()")
deferred = head;
function microtask(func,args,context){
deferred(func,args,context);
}
function head(func,args,context){
queue[queue.length] = [func,args,context];
deferred = tail;
defer(drain);
}
function tail(func,args,context){
queue[queue.length] = [func,args,context];
}
function drain(){
for(var i = 0; i < queue.length; i++){ queue[i][0].apply(queue[i][2],queue[i][1]) }
deferred = head;
queue = [];
}
if(module && module.exports) module.exports = microtask;
else if(typeof define ==='function' && define.amd) define(microtask);
else root.microtask = microtask;
}(this));
});
require.register("kaerus-component-uP/index.js", function(module, exports, require){
/**
* Provides A+ v1.1 compliant promises.
* @module uP
* @name microPromise
* @main uP
*/
var task = require('microtask'); // nextTick shim
(function(root){
"use strict"
try {root = global} catch(e){ try {root = window} catch(e){} };
var slice = Array.prototype.slice,
isArray = Array.isArray;
var uP = function microPromise(proto){
// object mixin
if(proto && typeof proto === 'object'){
for(var key in uP.prototype) proto[key] = uP.prototype[key];
proto._tuple = [];
return proto;
}
if(!(this instanceof microPromise))
return new microPromise(proto);
this._tuple = [];
// resolver callback
if(typeof proto === 'function') {
proto(this.resolve,this.reject,this.progress,this.timeout);
}
}
/**
* Attaches callback,errback,notify handlers and returns a promise
*
* Example: catch fulfillment or rejection
* var p = uP();
* p.then(function(value){
* console.log("received:", value);
* },function(error){
* console.log("failed with:", error);
* });
* p.fulfill('hello world!'); // => 'received: hello world!'
*
* Example: chainable then clauses
* p.then(function(v){
* console.log('v is:', v);
* if(v > 10) throw new RangeError('to large!');
* return v*2;
* }).then(function(v){
* // gets v*2 from above
* console.log('v is:', v)
* },function(e){
* console.log('error2:', e);
* });
* p.fulfill(142); // => v is: 142, error2: [RangeError:'to large']
*
* Example: undefined callbacks are ignored
* p.then(function(v){
* if(v < 0) throw v;
* return v;
* }).then(undefined,function(e){
* e = -e;
* return e;
* }).then(function(value){
* console.log('we got:', value);
* });
* p.fulfill(-5); // => we got: 5
*
* @param {Function} onFulfill callback
* @param {Function} onReject errback
* @param {Function} onNotify callback
* @return {Object} a decendant promise
* @api public
*/
uP.prototype.then = function(f,r,n){
var p = new uP();
this._tuple[this._tuple.length] = [p,f,r,n];
if(this._state) task(resolver,[this._tuple,this._state,this._value,this._opaque]);
return p;
}
/**
* Same semantic as `then` but spreads array value into separate arguments
*
* Example: Multiple fulfillment values
* p = uP();
* p.fulfill([1,2,3])
* p.spread(function(a,b,c){
* console.log(a,b,c); // => '1 2 3'
* });
*
* @param {Function} onFulfill callback
* @param {Function} onReject errback
* @param {Function} onNotify callback
* @return {Object} a decendant promise
* @api public
*/
uP.prototype.spread = function(f,r,n){
function s(v,a){
if(!Array.isArray(v)) v = [v];
return f.apply(f,v.concat(a));
}
return this.then(s,r,n);
}
/**
* Same as `then` but terminates a promise chain and calls onerror / throws error on unhandled Errors
*
* Example: capture error with done
* p.then(function(v){
* console.log('v is:', v);
* if(v > 10) throw new RangeError('to large!');
* return v*2;
* }).done(function(v){
* // gets v*2 from above
* console.log('v is:', v)
* });
* p.fulfill(142); // => v is: 142, throws [RangeError:'to large']
* Example: use onerror handler
* p.onerror = function(error){ console.log("Sorry:",error) };
* p.then(function(v){
* console.log('v is:', v);
* if(v > 10) throw new RangeError('to large!');
* return v*2;
* }).done(function(v){
* // gets v*2 from above
* console.log('v is:', v)
* });
* p.fulfill(142); // => v is: 142, "Sorry: [RangeError:'to large']"
*
* @param {Function} onFulfill callback
* @param {Function} onReject errback
* @param {Function} onNotify callback
* @api public
*/
uP.prototype.done = function(f,r,n){
if(typeof r !== 'function') r = handleError;
var self = this, p = this.then(f,r,n);
function handleError(e){
task(function(){
if(typeof self.onerror === 'function'){
self.onerror(e);
} else {
throw e;
}
});
}
}
/**
* Fulfills a promise with a `value`
*
* Example: fulfillment
* p = uP();
* p.fulfill(123);
*
* Example: multiple fulfillment values in array
* p = uP();
* p.fulfill([1,2,3]);
* p.resolved; // => [1,2,3]
*
* Example: Pass through opaque arguments (experimental)
* p = uP();
* p.fulfill("hello","world");
* p.then(function(x,o){
* console.log(x,o[0]); // => "hello world"
* o.push("!");
* return "bye bye";
* }).then(function(x,o){
* console.log(x,o.join('')); // => "bye bye world!"
* })
*
* @param {Object} value
* @return {Object} promise
* @api public
*/
uP.prototype.fulfill = function(x,o){
if(!this._state){
task(resolver,[this._tuple,this._state = 1,this._value = x, this._opaque = o]);
}
return this;
}
/**
* Resolves a promise with a `value` yielded from another promise
*
* Example: resolve literal value
* p = uP();
* p.resolve(123); // fulfills promise with 123
*
* Example: resolve value from another pending promise
* p1 = uP();
* p2 = uP();
* p1.resolve(p2);
* p2.fulfill(123) // => p2._value = 123
*
* @param {Object} value
* @return {Object} promise
* @api public
*/
uP.prototype.resolve = function(x,o){
var then, z = 0, p = this, z = 0;
if(!this._state){
if(x === p) p.reject(new TypeError("x === p"));
if(x && (typeof x === 'object' || typeof x === 'function')){
try { then = x.then } catch(e){ p.reject(e) }
}
if(typeof then !== 'function'){
task(resolver,[this._tuple,this._state = 1,this._value = x, this._opaque = o])
} else if(!z){
try {
then.apply(x,[function(y){
if(!z++) p.resolve(y,o);
},function(r){
if(!z++) p.reject(r);
}]);
} catch(e) {
if(!z++) p.reject(e);
}
}
}
return this;
}
/**
* Rejects promise with a `reason`
*
* Example:
* p = uP();
* p.then(function(ok){
* console.log("ok:",ok);
* }, function(error){
* console.log("error:",error);
* });
* p.reject('some error'); // outputs => 'error: some error'
*
* @param {Object} reason
* @return {Object} promise
* @api public
*/
uP.prototype.reject = function(x,o){
if(!this._state){
task(resolver,[this._tuple,this._state = 2,this._value = x, this._opaque = o]);
}
return this;
}
/**
* Notifies attached handlers
*
* Example:
* p = uP();
* p.then(function(ok){
* console.log("ok:",ok);
* }, function(error){
* console.log("error:",error);
* }, function(notify){
* console.log(notify);
* });
* p.progress("almost done"); // optputs => 'almost done'
* p.reject('some error'); // outputs => 'error: some error'
*
* @param {Object} arguments
* @api public
*/
uP.prototype.progress = function(){
var args = slice.call(arguments), fn;
for(var i = 0, l = this._tuple.length; i < l; i++){
if(typeof (fn = this._tuple[i][3]) === 'function')
fn.apply(this,arguments);
}
}
/**
* Timeout a pending promise and invoke callback function on timeout.
* Without a callback it throws a RangeError('exceeded timeout').
*
* Example: timeout & abort()
* var p = Promise();
* p.attach({abort:function(msg){console.log('Aborted:',msg)}});
* p.timeout(5000);
* // ... after 5 secs ... => Aborted: |RangeError: 'exceeded timeout']
*
* Example: cancel timeout
* p.timeout(5000);
* p.timeout(null); // timeout cancelled
*
* @param {Number} time timeout value in ms or null to clear timeout
* @param {Function} callback optional timeout function callback
* @throws {RangeError} If exceeded timeout
* @return {Object} promise
* @api public
*/
uP.prototype.timeout = function(msec,func){
var p = this;
if(msec === null) {
clearTimeout(p._timer);
p._timer = null;
} else if(!p._timer){
p._timer = setTimeout(onTimeout,msec);
}
function onTimeout(){
var e = RangeError("exceeded timeout");
if(!p._state) {
if(typeof func === 'function') func(p);
else if(typeof p.onerror === 'function') p.onerror(e);
else throw e;
}
}
return this;
}
/**
* Wraps a `proto` into a promise
*
* Example: wrap an Array
* p = Promise();
* c = p.wrap(Array);
* c(1,2,3); // => calls constructor and fulfills promise
* p.resolved; // => [1,2,3]
*
* @param {Object} proto
* @return {Object} promise
* @api public
*/
uP.prototype.wrap = function(proto){
var p = this;
return function(){
var args = slice.call(arguments), ret;
if(proto instanceof microPromise){
proto.fulfill(args).then(p.fulfill,p.reject);
} else if(typeof proto === 'function'){
try{
ret = proto.apply(p,args);
p.resolve(ret);
} catch(err) {
p.reject(err);
}
}
return p;
}
}
/**
* Deferres a task and fulfills with return value.
* The process may also return a promise itself which to wait on.
*
* Example: Make readFileSync async
* fs = require('fs');
* var asyncReadFile = uP().defer(fs.readFileSync,'./index.js','utf-8');
* asyncReadFile.then(function(data){
* console.log(data)
* },function(error){
* console.log("Read error:", error);
* });
*
* @return {Object} promise
* @api public
*/
uP.prototype.defer = function(){
var args = slice.call(arguments),
proc = args.shift(),
p = this;
if(typeof proc === 'function'){
task(enclose,args);
}
function enclose(){
try { p.resolve(proc.apply(p,args)) } catch(err) { p.reject(err) }
}
return this;
}
/**
* Adapted for nodejs style functions expecting a callback.
*
* Example: make readFile async
* fs = require('fs');
* var asyncReadFile = uP.async(fs.readFile,'./index.js','utf-8');
* asyncReadFile.then(function(data){
* console.log(data);
* },function(error){
* console.log("Read error:", error);
* });
*
* @return {Object} promise
* @api public
*/
uP.prototype.async = function(){
var p = this,
args = slice.call(arguments);
function callback(err,ret){ if(!err) p.fulfill(ret); else p.reject(ret); }
args[args.length] = callback;
return this.defer.apply(this,args);
}
/**
* Joins promises and collects results into an array.
* If any of the promises are rejected the chain is also rejected.
*
* Example: join with two promises
* a = uP();
* b = uP();
* c = uP();
* a.join([b,c]).spread(function(a,b,c){
* console.log(a,b,c);
* },function(err){
* console.log('error=',err);
* });
* b.fulfill('world');
* a.fulfill('hello');
* c.fulfill('!'); // => 'hello world !''
*
* @param {Array} promises
* @return {Object} promise
* @api public
*/
uP.prototype.join = function(j){
var p = this,
y = [],
u = new uP().resolve(p).then(function(v){y[0] = v});
if(arguments.length > 1) {
j = slice.call(arguments);
}
if(!isArray(j)) j = [j];
function collect(i){
j[i].done(function(v){
y[i+1] = v;
},u.reject);
return function(){return j[i]}
}
for(var i = 0; i < j.length; i++){
u = u.then(collect(i));
}
return u.then(function(){return y});
}
/* Resolver function, yields back a promised value to handlers */
function resolver(tuple,state,value,opaque){
var t, p, h, x = value;
while(t = tuple.shift()) {
p = t[0];
h = t[state];
if(typeof h === 'function') {
try {
x = h(value,opaque);
p.resolve(x,opaque);
} catch(e) {
p.reject(e);
}
} else {
p._state = state;
p._value = x;
p._opaque = opaque;
task(resolver,[p._tuple, p._state, p._value, p._opaque]);
}
}
}
/* expose this module */
if(module && module.exports) module.exports = uP;
else if(typeof define ==='function' && define.amd) define(uP);
else root.uP = uP;
}(this));
});
require.register("kaerus-component-ajax/index.js", function(module, exports, require){
var urlParser = require('urlparser');
/* default request timeout */
var DEFAULT_TIMEOUT = 5000;
/* Get browser xhr object */
var Xhr = (function() {
if(window.XDomainRequest) {
return window.XDomainRequest;
} else if(window.XMLHttpRequest) {
return window['XMLHttpRequest'];
} else if(window.ActiveXObject) {
['Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.3.0','Microsoft.XMLHTTP'].forEach(function(x) {
try { return window.ActiveXObject(x) } catch (e) {}
});
throw new Error('XHR ActiveXObject failed');
}
throw new Error('XHR support not found');
}());
/* ReadyState status codes */
var XHR_CLOSED = 0,
XHR_OPENED = 1,
XHR_SENT = 2,
XHR_RECEIVED = 3,
XHR_DONE = 4;
function Ajax(method,url,options,data,res) {
var xhr = new Xhr(), headers;
if(typeof options === 'function'){
res = options;
options = null;
data = null;
} else if(typeof data === 'function'){
res = data;
data = null;
}
options = options ? options : {};
if(typeof res === 'function') {
var clb = res;
res = {
resolve: function(x){
clb(undefined,x);
},
reject: function(x,c){
clb(c||-1,x);
},
progress: function(x){
clb(0,x);
}
}
} else if(typeof res !== 'object') {
res = {
resolve: function(x){
this.result = x;
if(this.onfulfill) this.onfulfill(x);
},
reject: function(x){
this.error = x;
if(this.onreject) this.onreject(x);
},
progress: function(x){
if(this.onprogress) this.onprogress(x);
},
when: function(f,r,p){
this.onfulfill = f;
this.onreject = r;
this.onprogress = p;
}
};
/* must be async */
options.async = true;
} /* else resolve using res */
if(options.async === undefined) options.async = true;
if(options.timeout === undefined) options.timeout = DEFAULT_TIMEOUT;
if(!options.headers) options.headers = {};
if(options.type || !options.headers['content-type'])
options.headers['content-type'] = options.type||'application/json';
if(options.accept || !options.headers.accept)
options.headers.accept = options.accept||'application/json';
if(options.charset) options.headers['accept-charset'] = options.charset;
if("withCredentials" in xhr || typeof XDomainRequest != "undefined") {
if(options.withCredentials === true)
xhr.withCredentials = true;
xhr.onload = function(){
res.resolve(xhr)
}
xhr.onerror = function(){
res.reject(xhr);
}
} else {
xhr.onreadystatechange = function() {
switch(xhr.readyState) {
case XHR_DONE:
if(xhr.status) res.resolve(xhr);
else res.reject(xhr); // status = 0 (timeout or Xdomain)
break;
}
}
}
/* getter for response headers */
Object.defineProperty(xhr,'headers',{
get: function(){
if(!headers) headers = parseHeaders(xhr.getAllResponseHeaders());
return headers;
}
});
/* response timeout */
if(options.timeout) {
setTimeout(function(){
xhr.abort();
}, options.timeout);
}
/* report progress */
if(xhr.upload && res.progress) {
xhr.upload.onprogress = function(e){
e.percent = e.loaded / e.total * 100;
res.progress(e);
}
}
/* parse url */
url = urlParser.parse(url);
if(!url.host) url.host = {};
/* merge host info with options */
if(!url.host.protocol && options.protocol) url.host.protocol = options.protocol;
if(!url.host.hostname && options.hostname) url.host.hostname = options.hostname;
if(!url.host.port && options.port) url.host.port = options.port;
url = url.toString();
try {
xhr.open(method,url,options.async);
} catch(error){
res.reject(error);
}
/* set request headers */
Object.keys(options.headers).forEach(function(header) {
xhr.setRequestHeader(header,options.headers[header]);
});
/* stringify json */
if(data && typeof data !== 'string' && options.headers['content-type'].indexOf('json')>=0){
try {
data = JSON.stringify(data);
} catch(error) {
res.reject(error);
}
}
/* request data */
try {
xhr.send(data);
} catch(error){
res.reject(error);
}
return res;
}
/* Object.create polyfill */
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
F.prototype = o;
return new F();
}
})();
}
function parseHeaders(h) {
var ret = Object.create(null), key, val, i;
h.split('\n').forEach(function(header) {
if((i=header.indexOf(':')) > 0) {
key = header.slice(0,i).replace(/^[\s]+|[\s]+$/g,'').toLowerCase();
val = header.slice(i+1,header.length).replace(/^[\s]+|[\s]+$/g,'');
if(key && key.length) ret[key] = val;
}
});
return ret;
}
['head','get','put','post','delete','patch','trace','connect','options']
.forEach(function(method) {
Ajax[method] = function(url,options,data,res) {
return Ajax(method,url,options,data,res);
}
});
module.exports = Ajax;
});
require.register("kaerus-component-urlparser/index.js", function(module, exports, require){
/**
* Provides with an Url parser that deconstructs an url into a managable object and back to a string.
*
* ### Examples:
*
* url = require('urlparser');
*
* var u = url.parse('http://user:[email protected]/login?x=42');
*
* u.host.hostname = 'database.kaerus.com'
* u.host.password = 'secret';
* u.host.port = 8529;
* u.query.parts.push('a=13');
* u.toString(); // 'http://user:[email protected]:8529/login?x=42&a=13'
*
* @module urlparser
* @name urlparser
* @main urlparser
*/
var URL = /^(?:(?:([A-Za-z]+):?\/{2})?(?:(\w+)?:?([^\x00-\x1F^\x7F^:]*)@)?([\w\-\.]+)?(?::(\d+))?)\/?(([^\x00-\x1F^\x7F^\#^\?^:]+)?(?::([^\x00-\x1F^\x7F^\#^\?]+))?(?:#([^\x00-\x1F^\?]+))?)(?:\?(.*))?$/;
function urlString(o){
var str = "";
o = o ? o : this;
str+= hostString(o);
str+= pathString(o);
str+= queryString(o);
return str;
}
module.exports.url = urlString;