forked from pyrsmk/qwest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qwest.js
567 lines (537 loc) · 17 KB
/
qwest.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.qwest = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/**
* @preserve jquery-param (c) 2015 KNOWLEDGECODE | MIT
*/
/*global define */
(function (global) {
'use strict';
var param = function (a) {
var add = function (s, k, v) {
v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v;
s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
}, buildParams = function (prefix, obj, s) {
var i, len, key;
if (Object.prototype.toString.call(obj) === '[object Array]') {
for (i = 0, len = obj.length; i < len; i++) {
buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i], s);
}
} else if (obj && obj.toString() === '[object Object]') {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (prefix) {
buildParams(prefix + '[' + key + ']', obj[key], s, add);
} else {
buildParams(key, obj[key], s, add);
}
}
}
} else if (prefix) {
add(s, prefix, obj);
} else {
for (key in obj) {
add(s, key, obj[key]);
}
}
return s;
};
return buildParams('', a, []).join('&').replace(/%20/g, '+');
};
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = param;
} else if (typeof define === 'function' && define.amd) {
define([], function () {
return param;
});
} else {
global.param = param;
}
}(this));
},{}],2:[function(_dereq_,module,exports){
/*
* PinkySwear.js 2.2.2 - Minimalistic implementation of the Promises/A+ spec
*
* Public Domain. Use, modify and distribute it any way you like. No attribution required.
*
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*
* PinkySwear is a very small implementation of the Promises/A+ specification. After compilation with the
* Google Closure Compiler and gzipping it weighs less than 500 bytes. It is based on the implementation for
* Minified.js and should be perfect for embedding.
*
*
* PinkySwear has just three functions.
*
* To create a new promise in pending state, call pinkySwear():
* var promise = pinkySwear();
*
* The returned object has a Promises/A+ compatible then() implementation:
* promise.then(function(value) { alert("Success!"); }, function(value) { alert("Failure!"); });
*
*
* The promise returned by pinkySwear() is a function. To fulfill the promise, call the function with true as first argument and
* an optional array of values to pass to the then() handler. By putting more than one value in the array, you can pass more than one
* value to the then() handlers. Here an example to fulfill a promsise, this time with only one argument:
* promise(true, [42]);
*
* When the promise has been rejected, call it with false. Again, there may be more than one argument for the then() handler:
* promise(true, [6, 6, 6]);
*
* You can obtain the promise's current state by calling the function without arguments. It will be true if fulfilled,
* false if rejected, and otherwise undefined.
* var state = promise();
*
* https://github.com/timjansen/PinkySwear.js
*/
(function(target) {
var undef;
function isFunction(f) {
return typeof f == 'function';
}
function isObject(f) {
return typeof f == 'object';
}
function defer(callback) {
if (typeof setImmediate != 'undefined')
setImmediate(callback);
else if (typeof process != 'undefined' && process['nextTick'])
process['nextTick'](callback);
else
setTimeout(callback, 0);
}
target[0][target[1]] = function pinkySwear(extend) {
var state; // undefined/null = pending, true = fulfilled, false = rejected
var values = []; // an array of values as arguments for the then() handlers
var deferred = []; // functions to call when set() is invoked
var set = function(newState, newValues) {
if (state == null && newState != null) {
state = newState;
values = newValues;
if (deferred.length)
defer(function() {
for (var i = 0; i < deferred.length; i++)
deferred[i]();
});
}
return state;
};
set['then'] = function (onFulfilled, onRejected) {
var promise2 = pinkySwear(extend);
var callCallbacks = function() {
try {
var f = (state ? onFulfilled : onRejected);
if (isFunction(f)) {
function resolve(x) {
var then, cbCalled = 0;
try {
if (x && (isObject(x) || isFunction(x)) && isFunction(then = x['then'])) {
if (x === promise2)
throw new TypeError();
then['call'](x,
function() { if (!cbCalled++) resolve.apply(undef,arguments); } ,
function(value){ if (!cbCalled++) promise2(false,[value]);});
}
else
promise2(true, arguments);
}
catch(e) {
if (!cbCalled++)
promise2(false, [e]);
}
}
resolve(f.apply(undef, values || []));
}
else
promise2(state, values);
}
catch (e) {
promise2(false, [e]);
}
};
if (state != null)
defer(callCallbacks);
else
deferred.push(callCallbacks);
return promise2;
};
if(extend){
set = extend(set);
}
return set;
};
})(typeof module == 'undefined' ? [window, 'pinkySwear'] : [module, 'exports']);
},{}],"qwest":[function(_dereq_,module,exports){
/*! qwest 2.2.6 (https://github.com/pyrsmk/qwest) */
module.exports = function() {
var global = window || this,
pinkyswear = _dereq_('pinkyswear'),
jparam = _dereq_('jquery-param'),
// Default response type for XDR in auto mode
defaultXdrResponseType = 'json',
// Default data type
defaultDataType = 'post',
// Variables for limit mechanism
limit = null,
requests = 0,
request_stack = [],
// Get XMLHttpRequest object
getXHR = function(){
return global.XMLHttpRequest?
new global.XMLHttpRequest():
new ActiveXObject('Microsoft.XMLHTTP');
},
// Guess XHR version
xhr2 = (getXHR().responseType===''),
// Core function
qwest = function(method, url, data, options, before) {
// Format
method = method.toUpperCase();
data = data || null;
options = options || {};
// Define variables
var nativeResponseParsing = false,
crossOrigin,
xhr,
xdr = false,
timeoutInterval,
aborted = false,
attempts = 0,
headers = {},
mimeTypes = {
text: '*/*',
xml: 'text/xml',
json: 'application/json',
post: 'application/x-www-form-urlencoded'
},
accept = {
text: '*/*',
xml: 'application/xml; q=1.0, text/xml; q=0.8, */*; q=0.1',
json: 'application/json; q=1.0, text/*; q=0.8, */*; q=0.1'
},
vars = '',
i, j,
serialized,
response,
sending = false,
delayed = false,
timeout_start,
// Create the promise
promise = pinkyswear(function(pinky) {
pinky['catch'] = function(f) {
return pinky.then(null, f);
};
pinky.complete = function(f) {
return pinky.then(f, f);
};
// Override
if('pinkyswear' in options) {
for(i in options.pinkyswear) {
pinky[i] = options.pinkyswear[i];
}
}
pinky.send = function() {
// Prevent further send() calls
if(sending) {
return;
}
// Reached request limit, get out!
if(requests == limit) {
request_stack.push(pinky);
return;
}
++requests;
sending = true;
// Start the chrono
timeout_start = new Date().getTime();
// Get XHR object
xhr = getXHR();
if(crossOrigin) {
if(!('withCredentials' in xhr) && global.XDomainRequest) {
xhr = new XDomainRequest(); // CORS with IE8/9
xdr = true;
if(method!='GET' && method!='POST') {
method = 'POST';
}
}
}
// Open connection
if(xdr) {
xhr.open(method, url);
}
else {
xhr.open(method, url, options.async, options.user, options.password);
if(xhr2 && options.async) {
xhr.withCredentials = options.withCredentials;
}
}
// Set headers
if(!xdr) {
for(var i in headers) {
if(headers[i]) {
xhr.setRequestHeader(i, headers[i]);
}
}
}
// Verify if the response type is supported by the current browser
if(xhr2 && options.responseType!='document' && options.responseType!='auto') { // Don't verify for 'document' since we're using an internal routine
try {
xhr.responseType = options.responseType;
nativeResponseParsing = (xhr.responseType==options.responseType);
}
catch(e){}
}
// Plug response handler
if(xhr2 || xdr) {
xhr.onload = handleResponse;
xhr.onerror = handleError;
}
else {
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
handleResponse();
}
};
}
// Override mime type to ensure the response is well parsed
if(options.responseType!='auto' && 'overrideMimeType' in xhr) {
xhr.overrideMimeType(mimeTypes[options.responseType]);
}
// Run 'before' callback
if(before) {
before(xhr);
}
// Send request
if(xdr) {
// http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/
xhr.onprogress = function(){};
xhr.ontimeout = function(){};
xhr.onerror = function(){};
// https://developer.mozilla.org/en-US/docs/Web/API/XDomainRequest
setTimeout(function() {
xhr.send(method != 'GET'? data : null);
},0);
}
else {
xhr.send(method != 'GET' ? data : null);
}
};
return pinky;
}),
// Handle the response
handleResponse = function() {
// Prepare
var i, responseType;
--requests;
sending = false;
// Verify timeout state
// --- https://stackoverflow.com/questions/7287706/ie-9-javascript-error-c00c023f
if(new Date().getTime()-timeout_start >= options.timeout) {
if(!options.attempts || ++attempts!=options.attempts) {
promise.send();
}
else {
promise(false, [xhr,response,new Error('Timeout ('+url+')')]);
}
return;
}
// Launch next stacked request
if(request_stack.length) {
request_stack.shift().send();
}
// Handle response
try{
// Process response
if(nativeResponseParsing && 'response' in xhr && xhr.response!==null) {
response = xhr.response;
}
else if(options.responseType == 'document') {
var frame = document.createElement('iframe');
frame.style.display = 'none';
document.body.appendChild(frame);
frame.contentDocument.open();
frame.contentDocument.write(xhr.response);
frame.contentDocument.close();
response = frame.contentDocument;
document.body.removeChild(frame);
}
else{
// Guess response type
responseType = options.responseType;
if(responseType == 'auto') {
if(xdr) {
responseType = defaultXdrResponseType;
}
else {
var ct = xhr.getResponseHeader('Content-Type') || '';
if(ct.indexOf(mimeTypes.json)>-1) {
responseType = 'json';
}
else if(ct.indexOf(mimeTypes.xml)>-1) {
responseType = 'xml';
}
else {
responseType = 'text';
}
}
}
// Handle response type
switch(responseType) {
case 'json':
try {
if('JSON' in global) {
response = JSON.parse(xhr.responseText);
}
else {
response = eval('('+xhr.responseText+')');
}
}
catch(e) {
throw "Error while parsing JSON body : "+e;
}
break;
case 'xml':
// Based on jQuery's parseXML() function
try {
// Standard
if(global.DOMParser) {
response = (new DOMParser()).parseFromString(xhr.responseText,'text/xml');
}
// IE<9
else {
response = new ActiveXObject('Microsoft.XMLDOM');
response.async = 'false';
response.loadXML(xhr.responseText);
}
}
catch(e) {
response = undefined;
}
if(!response || !response.documentElement || response.getElementsByTagName('parsererror').length) {
throw 'Invalid XML';
}
break;
default:
response = xhr.responseText;
}
}
// Late status code verification to allow passing data when, per example, a 409 is returned
// --- https://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
if('status' in xhr && !/^2|1223/.test(xhr.status)) {
throw xhr.status+' ('+xhr.statusText+')';
}
// Fulfilled
promise(true, [xhr,response]);
}
catch(e) {
// Rejected
promise(false, [xhr,response,e]);
}
},
// Handle errors
handleError = function(e) {
--requests;
promise(false, [xhr,null,new Error('Connection aborted')]);
};
// Normalize options
options.async = 'async' in options?!!options.async:true;
options.cache = 'cache' in options?!!options.cache:false;
options.dataType = 'dataType' in options?options.dataType.toLowerCase():defaultDataType;
options.responseType = 'responseType' in options?options.responseType.toLowerCase():'auto';
options.user = options.user || '';
options.password = options.password || '';
options.withCredentials = !!options.withCredentials;
options.timeout = 'timeout' in options?parseInt(options.timeout,10):30000;
options.attempts = 'attempts' in options?parseInt(options.attempts,10):1;
// Guess if we're dealing with a cross-origin request
i = url.match(/\/\/(.+?)\//);
crossOrigin = i && (i[1]?i[1]!=location.host:false);
// Prepare data
if('ArrayBuffer' in global && data instanceof ArrayBuffer) {
options.dataType = 'arraybuffer';
}
else if('Blob' in global && data instanceof Blob) {
options.dataType = 'blob';
}
else if('Document' in global && data instanceof Document) {
options.dataType = 'document';
}
else if('FormData' in global && data instanceof FormData) {
options.dataType = 'formdata';
}
switch(options.dataType) {
case 'json':
data = JSON.stringify(data);
break;
case 'post':
data = jparam(data);
}
// Prepare headers
if(options.headers) {
var format = function(match,p1,p2) {
return p1 + p2.toUpperCase();
};
for(i in options.headers) {
headers[i.replace(/(^|-)([^-])/g,format)] = options.headers[i];
}
}
if(!('Content-Type' in headers) && method!='GET') {
if(options.dataType in mimeTypes) {
if(mimeTypes[options.dataType]) {
headers['Content-Type'] = mimeTypes[options.dataType];
}
}
}
if(!headers.Accept) {
headers.Accept = (options.responseType in accept)?accept[options.responseType]:'*/*';
}
if(!crossOrigin && !('X-Requested-With' in headers)) { // (that header breaks in legacy browsers with CORS)
headers['X-Requested-With'] = 'XMLHttpRequest';
}
if(!options.cache && !('Cache-Control' in headers)) {
headers['Cache-Control'] = 'no-cache';
}
// Prepare URL
if(method=='GET' && data) {
vars += data;
}
if(vars) {
url += (/\?/.test(url)?'&':'?')+vars;
}
// Start the request
if(options.async) {
promise.send();
}
// Return promise
return promise;
};
// Return the external qwest object
return {
base: '',
get: function(url, data, options, before) {
return qwest('GET', this.base+url, data, options, before);
},
post: function(url, data, options, before) {
return qwest('POST', this.base+url, data, options, before);
},
put: function(url, data, options, before) {
return qwest('PUT', this.base+url, data, options, before);
},
'delete': function(url, data, options, before) {
return qwest('DELETE', this.base+url, data, options, before);
},
map: function(type, url, data, options, before) {
return qwest(type.toUpperCase(), this.base+url, data, options, before);
},
xhr2: xhr2,
limit: function(by) {
limit = by;
},
setDefaultXdrResponseType: function(type) {
defaultXdrResponseType = type.toLowerCase();
},
setDefaultDataType: function(type) {
defaultDataType = type.toLowerCase();
}
};
}();
},{"jquery-param":1,"pinkyswear":2}]},{},[1,2])("qwest")
});