UNPKG

56.7 kBJavaScriptView Raw
1(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.superagent = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2"use strict";
3
4/**
5 * Expose `Emitter`.
6 */
7if (typeof module !== 'undefined') {
8 module.exports = Emitter;
9}
10/**
11 * Initialize a new `Emitter`.
12 *
13 * @api public
14 */
15
16
17function Emitter(obj) {
18 if (obj) return mixin(obj);
19}
20
21;
22/**
23 * Mixin the emitter properties.
24 *
25 * @param {Object} obj
26 * @return {Object}
27 * @api private
28 */
29
30function mixin(obj) {
31 for (var key in Emitter.prototype) {
32 obj[key] = Emitter.prototype[key];
33 }
34
35 return obj;
36}
37/**
38 * Listen on the given `event` with `fn`.
39 *
40 * @param {String} event
41 * @param {Function} fn
42 * @return {Emitter}
43 * @api public
44 */
45
46
47Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
48 this._callbacks = this._callbacks || {};
49 (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
50 return this;
51};
52/**
53 * Adds an `event` listener that will be invoked a single
54 * time then automatically removed.
55 *
56 * @param {String} event
57 * @param {Function} fn
58 * @return {Emitter}
59 * @api public
60 */
61
62
63Emitter.prototype.once = function (event, fn) {
64 function on() {
65 this.off(event, on);
66 fn.apply(this, arguments);
67 }
68
69 on.fn = fn;
70 this.on(event, on);
71 return this;
72};
73/**
74 * Remove the given callback for `event` or all
75 * registered callbacks.
76 *
77 * @param {String} event
78 * @param {Function} fn
79 * @return {Emitter}
80 * @api public
81 */
82
83
84Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
85 this._callbacks = this._callbacks || {}; // all
86
87 if (0 == arguments.length) {
88 this._callbacks = {};
89 return this;
90 } // specific event
91
92
93 var callbacks = this._callbacks['$' + event];
94 if (!callbacks) return this; // remove all handlers
95
96 if (1 == arguments.length) {
97 delete this._callbacks['$' + event];
98 return this;
99 } // remove specific handler
100
101
102 var cb;
103
104 for (var i = 0; i < callbacks.length; i++) {
105 cb = callbacks[i];
106
107 if (cb === fn || cb.fn === fn) {
108 callbacks.splice(i, 1);
109 break;
110 }
111 } // Remove event specific arrays for event types that no
112 // one is subscribed for to avoid memory leak.
113
114
115 if (callbacks.length === 0) {
116 delete this._callbacks['$' + event];
117 }
118
119 return this;
120};
121/**
122 * Emit `event` with the given args.
123 *
124 * @param {String} event
125 * @param {Mixed} ...
126 * @return {Emitter}
127 */
128
129
130Emitter.prototype.emit = function (event) {
131 this._callbacks = this._callbacks || {};
132 var args = new Array(arguments.length - 1),
133 callbacks = this._callbacks['$' + event];
134
135 for (var i = 1; i < arguments.length; i++) {
136 args[i - 1] = arguments[i];
137 }
138
139 if (callbacks) {
140 callbacks = callbacks.slice(0);
141
142 for (var i = 0, len = callbacks.length; i < len; ++i) {
143 callbacks[i].apply(this, args);
144 }
145 }
146
147 return this;
148};
149/**
150 * Return array of callbacks for `event`.
151 *
152 * @param {String} event
153 * @return {Array}
154 * @api public
155 */
156
157
158Emitter.prototype.listeners = function (event) {
159 this._callbacks = this._callbacks || {};
160 return this._callbacks['$' + event] || [];
161};
162/**
163 * Check if this emitter has `event` handlers.
164 *
165 * @param {String} event
166 * @return {Boolean}
167 * @api public
168 */
169
170
171Emitter.prototype.hasListeners = function (event) {
172 return !!this.listeners(event).length;
173};
174
175},{}],2:[function(require,module,exports){
176"use strict";
177
178function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
179
180module.exports = stringify;
181stringify.default = stringify;
182stringify.stable = deterministicStringify;
183stringify.stableStringify = deterministicStringify;
184var arr = [];
185var replacerStack = []; // Regular stringify
186
187function stringify(obj, replacer, spacer) {
188 decirc(obj, '', [], undefined);
189 var res;
190
191 if (replacerStack.length === 0) {
192 res = JSON.stringify(obj, replacer, spacer);
193 } else {
194 res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
195 }
196
197 while (arr.length !== 0) {
198 var part = arr.pop();
199
200 if (part.length === 4) {
201 Object.defineProperty(part[0], part[1], part[3]);
202 } else {
203 part[0][part[1]] = part[2];
204 }
205 }
206
207 return res;
208}
209
210function decirc(val, k, stack, parent) {
211 var i;
212
213 if (_typeof(val) === 'object' && val !== null) {
214 for (i = 0; i < stack.length; i++) {
215 if (stack[i] === val) {
216 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
217
218 if (propertyDescriptor.get !== undefined) {
219 if (propertyDescriptor.configurable) {
220 Object.defineProperty(parent, k, {
221 value: '[Circular]'
222 });
223 arr.push([parent, k, val, propertyDescriptor]);
224 } else {
225 replacerStack.push([val, k]);
226 }
227 } else {
228 parent[k] = '[Circular]';
229 arr.push([parent, k, val]);
230 }
231
232 return;
233 }
234 }
235
236 stack.push(val); // Optimize for Arrays. Big arrays could kill the performance otherwise!
237
238 if (Array.isArray(val)) {
239 for (i = 0; i < val.length; i++) {
240 decirc(val[i], i, stack, val);
241 }
242 } else {
243 var keys = Object.keys(val);
244
245 for (i = 0; i < keys.length; i++) {
246 var key = keys[i];
247 decirc(val[key], key, stack, val);
248 }
249 }
250
251 stack.pop();
252 }
253} // Stable-stringify
254
255
256function compareFunction(a, b) {
257 if (a < b) {
258 return -1;
259 }
260
261 if (a > b) {
262 return 1;
263 }
264
265 return 0;
266}
267
268function deterministicStringify(obj, replacer, spacer) {
269 var tmp = deterministicDecirc(obj, '', [], undefined) || obj;
270 var res;
271
272 if (replacerStack.length === 0) {
273 res = JSON.stringify(tmp, replacer, spacer);
274 } else {
275 res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);
276 }
277
278 while (arr.length !== 0) {
279 var part = arr.pop();
280
281 if (part.length === 4) {
282 Object.defineProperty(part[0], part[1], part[3]);
283 } else {
284 part[0][part[1]] = part[2];
285 }
286 }
287
288 return res;
289}
290
291function deterministicDecirc(val, k, stack, parent) {
292 var i;
293
294 if (_typeof(val) === 'object' && val !== null) {
295 for (i = 0; i < stack.length; i++) {
296 if (stack[i] === val) {
297 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
298
299 if (propertyDescriptor.get !== undefined) {
300 if (propertyDescriptor.configurable) {
301 Object.defineProperty(parent, k, {
302 value: '[Circular]'
303 });
304 arr.push([parent, k, val, propertyDescriptor]);
305 } else {
306 replacerStack.push([val, k]);
307 }
308 } else {
309 parent[k] = '[Circular]';
310 arr.push([parent, k, val]);
311 }
312
313 return;
314 }
315 }
316
317 if (typeof val.toJSON === 'function') {
318 return;
319 }
320
321 stack.push(val); // Optimize for Arrays. Big arrays could kill the performance otherwise!
322
323 if (Array.isArray(val)) {
324 for (i = 0; i < val.length; i++) {
325 deterministicDecirc(val[i], i, stack, val);
326 }
327 } else {
328 // Create a temporary object in the required way
329 var tmp = {};
330 var keys = Object.keys(val).sort(compareFunction);
331
332 for (i = 0; i < keys.length; i++) {
333 var key = keys[i];
334 deterministicDecirc(val[key], key, stack, val);
335 tmp[key] = val[key];
336 }
337
338 if (parent !== undefined) {
339 arr.push([parent, k, val]);
340 parent[k] = tmp;
341 } else {
342 return tmp;
343 }
344 }
345
346 stack.pop();
347 }
348} // wraps replacer function to handle values we couldn't replace
349// and mark them as [Circular]
350
351
352function replaceGetterValues(replacer) {
353 replacer = replacer !== undefined ? replacer : function (k, v) {
354 return v;
355 };
356 return function (key, val) {
357 if (replacerStack.length > 0) {
358 for (var i = 0; i < replacerStack.length; i++) {
359 var part = replacerStack[i];
360
361 if (part[1] === key && part[0] === val) {
362 val = '[Circular]';
363 replacerStack.splice(i, 1);
364 break;
365 }
366 }
367 }
368
369 return replacer.call(this, key, val);
370 };
371}
372
373},{}],3:[function(require,module,exports){
374"use strict";
375
376function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
377
378function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
379
380function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
381
382function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
383
384function Agent() {
385 this._defaults = [];
386}
387
388['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) {
389 // Default setting for all requests from this agent
390 Agent.prototype[fn] = function () {
391 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
392 args[_key] = arguments[_key];
393 }
394
395 this._defaults.push({
396 fn: fn,
397 args: args
398 });
399
400 return this;
401 };
402});
403
404Agent.prototype._setDefaults = function (req) {
405 this._defaults.forEach(function (def) {
406 req[def.fn].apply(req, _toConsumableArray(def.args));
407 });
408};
409
410module.exports = Agent;
411
412},{}],4:[function(require,module,exports){
413"use strict";
414
415function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
416
417/**
418 * Check if `obj` is an object.
419 *
420 * @param {Object} obj
421 * @return {Boolean}
422 * @api private
423 */
424function isObject(obj) {
425 return obj !== null && _typeof(obj) === 'object';
426}
427
428module.exports = isObject;
429
430},{}],5:[function(require,module,exports){
431"use strict";
432
433function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
434
435/**
436 * Root reference for iframes.
437 */
438var root;
439
440if (typeof window !== 'undefined') {
441 // Browser window
442 root = window;
443} else if (typeof self === 'undefined') {
444 // Other environments
445 console.warn('Using browser-only version of superagent in non-browser environment');
446 root = void 0;
447} else {
448 // Web Worker
449 root = self;
450}
451
452var Emitter = require('component-emitter');
453
454var safeStringify = require('fast-safe-stringify');
455
456var RequestBase = require('./request-base');
457
458var isObject = require('./is-object');
459
460var ResponseBase = require('./response-base');
461
462var Agent = require('./agent-base');
463/**
464 * Noop.
465 */
466
467
468function noop() {}
469/**
470 * Expose `request`.
471 */
472
473
474module.exports = function (method, url) {
475 // callback
476 if (typeof url === 'function') {
477 return new exports.Request('GET', method).end(url);
478 } // url first
479
480
481 if (arguments.length === 1) {
482 return new exports.Request('GET', method);
483 }
484
485 return new exports.Request(method, url);
486};
487
488exports = module.exports;
489var request = exports;
490exports.Request = Request;
491/**
492 * Determine XHR.
493 */
494
495request.getXHR = function () {
496 if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) {
497 return new XMLHttpRequest();
498 }
499
500 try {
501 return new ActiveXObject('Microsoft.XMLHTTP');
502 } catch (_unused) {}
503
504 try {
505 return new ActiveXObject('Msxml2.XMLHTTP.6.0');
506 } catch (_unused2) {}
507
508 try {
509 return new ActiveXObject('Msxml2.XMLHTTP.3.0');
510 } catch (_unused3) {}
511
512 try {
513 return new ActiveXObject('Msxml2.XMLHTTP');
514 } catch (_unused4) {}
515
516 throw new Error('Browser-only version of superagent could not find XHR');
517};
518/**
519 * Removes leading and trailing whitespace, added to support IE.
520 *
521 * @param {String} s
522 * @return {String}
523 * @api private
524 */
525
526
527var trim = ''.trim ? function (s) {
528 return s.trim();
529} : function (s) {
530 return s.replace(/(^\s*|\s*$)/g, '');
531};
532/**
533 * Serialize the given `obj`.
534 *
535 * @param {Object} obj
536 * @return {String}
537 * @api private
538 */
539
540function serialize(obj) {
541 if (!isObject(obj)) return obj;
542 var pairs = [];
543
544 for (var key in obj) {
545 if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]);
546 }
547
548 return pairs.join('&');
549}
550/**
551 * Helps 'serialize' with serializing arrays.
552 * Mutates the pairs array.
553 *
554 * @param {Array} pairs
555 * @param {String} key
556 * @param {Mixed} val
557 */
558
559
560function pushEncodedKeyValuePair(pairs, key, val) {
561 if (val === undefined) return;
562
563 if (val === null) {
564 pairs.push(encodeURI(key));
565 return;
566 }
567
568 if (Array.isArray(val)) {
569 val.forEach(function (v) {
570 pushEncodedKeyValuePair(pairs, key, v);
571 });
572 } else if (isObject(val)) {
573 for (var subkey in val) {
574 if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]);
575 }
576 } else {
577 pairs.push(encodeURI(key) + '=' + encodeURIComponent(val));
578 }
579}
580/**
581 * Expose serialization method.
582 */
583
584
585request.serializeObject = serialize;
586/**
587 * Parse the given x-www-form-urlencoded `str`.
588 *
589 * @param {String} str
590 * @return {Object}
591 * @api private
592 */
593
594function parseString(str) {
595 var obj = {};
596 var pairs = str.split('&');
597 var pair;
598 var pos;
599
600 for (var i = 0, len = pairs.length; i < len; ++i) {
601 pair = pairs[i];
602 pos = pair.indexOf('=');
603
604 if (pos === -1) {
605 obj[decodeURIComponent(pair)] = '';
606 } else {
607 obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1));
608 }
609 }
610
611 return obj;
612}
613/**
614 * Expose parser.
615 */
616
617
618request.parseString = parseString;
619/**
620 * Default MIME type map.
621 *
622 * superagent.types.xml = 'application/xml';
623 *
624 */
625
626request.types = {
627 html: 'text/html',
628 json: 'application/json',
629 xml: 'text/xml',
630 urlencoded: 'application/x-www-form-urlencoded',
631 form: 'application/x-www-form-urlencoded',
632 'form-data': 'application/x-www-form-urlencoded'
633};
634/**
635 * Default serialization map.
636 *
637 * superagent.serialize['application/xml'] = function(obj){
638 * return 'generated xml here';
639 * };
640 *
641 */
642
643request.serialize = {
644 'application/x-www-form-urlencoded': serialize,
645 'application/json': safeStringify
646};
647/**
648 * Default parsers.
649 *
650 * superagent.parse['application/xml'] = function(str){
651 * return { object parsed from str };
652 * };
653 *
654 */
655
656request.parse = {
657 'application/x-www-form-urlencoded': parseString,
658 'application/json': JSON.parse
659};
660/**
661 * Parse the given header `str` into
662 * an object containing the mapped fields.
663 *
664 * @param {String} str
665 * @return {Object}
666 * @api private
667 */
668
669function parseHeader(str) {
670 var lines = str.split(/\r?\n/);
671 var fields = {};
672 var index;
673 var line;
674 var field;
675 var val;
676
677 for (var i = 0, len = lines.length; i < len; ++i) {
678 line = lines[i];
679 index = line.indexOf(':');
680
681 if (index === -1) {
682 // could be empty line, just skip it
683 continue;
684 }
685
686 field = line.slice(0, index).toLowerCase();
687 val = trim(line.slice(index + 1));
688 fields[field] = val;
689 }
690
691 return fields;
692}
693/**
694 * Check if `mime` is json or has +json structured syntax suffix.
695 *
696 * @param {String} mime
697 * @return {Boolean}
698 * @api private
699 */
700
701
702function isJSON(mime) {
703 // should match /json or +json
704 // but not /json-seq
705 return /[/+]json($|[^-\w])/.test(mime);
706}
707/**
708 * Initialize a new `Response` with the given `xhr`.
709 *
710 * - set flags (.ok, .error, etc)
711 * - parse header
712 *
713 * Examples:
714 *
715 * Aliasing `superagent` as `request` is nice:
716 *
717 * request = superagent;
718 *
719 * We can use the promise-like API, or pass callbacks:
720 *
721 * request.get('/').end(function(res){});
722 * request.get('/', function(res){});
723 *
724 * Sending data can be chained:
725 *
726 * request
727 * .post('/user')
728 * .send({ name: 'tj' })
729 * .end(function(res){});
730 *
731 * Or passed to `.send()`:
732 *
733 * request
734 * .post('/user')
735 * .send({ name: 'tj' }, function(res){});
736 *
737 * Or passed to `.post()`:
738 *
739 * request
740 * .post('/user', { name: 'tj' })
741 * .end(function(res){});
742 *
743 * Or further reduced to a single call for simple cases:
744 *
745 * request
746 * .post('/user', { name: 'tj' }, function(res){});
747 *
748 * @param {XMLHTTPRequest} xhr
749 * @param {Object} options
750 * @api private
751 */
752
753
754function Response(req) {
755 this.req = req;
756 this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers
757
758 this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null;
759 this.statusText = this.req.xhr.statusText;
760 var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
761
762 if (status === 1223) {
763 status = 204;
764 }
765
766 this._setStatusProperties(status);
767
768 this.headers = parseHeader(this.xhr.getAllResponseHeaders());
769 this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
770 // getResponseHeader still works. so we get content-type even if getting
771 // other headers fails.
772
773 this.header['content-type'] = this.xhr.getResponseHeader('content-type');
774
775 this._setHeaderProperties(this.header);
776
777 if (this.text === null && req._responseType) {
778 this.body = this.xhr.response;
779 } else {
780 this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response);
781 }
782} // eslint-disable-next-line new-cap
783
784
785ResponseBase(Response.prototype);
786/**
787 * Parse the given body `str`.
788 *
789 * Used for auto-parsing of bodies. Parsers
790 * are defined on the `superagent.parse` object.
791 *
792 * @param {String} str
793 * @return {Mixed}
794 * @api private
795 */
796
797Response.prototype._parseBody = function (str) {
798 var parse = request.parse[this.type];
799
800 if (this.req._parser) {
801 return this.req._parser(this, str);
802 }
803
804 if (!parse && isJSON(this.type)) {
805 parse = request.parse['application/json'];
806 }
807
808 return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null;
809};
810/**
811 * Return an `Error` representative of this response.
812 *
813 * @return {Error}
814 * @api public
815 */
816
817
818Response.prototype.toError = function () {
819 var req = this.req;
820 var method = req.method;
821 var url = req.url;
822 var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")");
823 var err = new Error(msg);
824 err.status = this.status;
825 err.method = method;
826 err.url = url;
827 return err;
828};
829/**
830 * Expose `Response`.
831 */
832
833
834request.Response = Response;
835/**
836 * Initialize a new `Request` with the given `method` and `url`.
837 *
838 * @param {String} method
839 * @param {String} url
840 * @api public
841 */
842
843function Request(method, url) {
844 var self = this;
845 this._query = this._query || [];
846 this.method = method;
847 this.url = url;
848 this.header = {}; // preserves header name case
849
850 this._header = {}; // coerces header names to lowercase
851
852 this.on('end', function () {
853 var err = null;
854 var res = null;
855
856 try {
857 res = new Response(self);
858 } catch (err_) {
859 err = new Error('Parser is unable to parse the response');
860 err.parse = true;
861 err.original = err_; // issue #675: return the raw response if the response parsing fails
862
863 if (self.xhr) {
864 // ie9 doesn't have 'response' property
865 err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails
866
867 err.status = self.xhr.status ? self.xhr.status : null;
868 err.statusCode = err.status; // backwards-compat only
869 } else {
870 err.rawResponse = null;
871 err.status = null;
872 }
873
874 return self.callback(err);
875 }
876
877 self.emit('response', res);
878 var new_err;
879
880 try {
881 if (!self._isResponseOK(res)) {
882 new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response');
883 }
884 } catch (err_) {
885 new_err = err_; // ok() callback can throw
886 } // #1000 don't catch errors from the callback to avoid double calling it
887
888
889 if (new_err) {
890 new_err.original = err;
891 new_err.response = res;
892 new_err.status = res.status;
893 self.callback(new_err, res);
894 } else {
895 self.callback(null, res);
896 }
897 });
898}
899/**
900 * Mixin `Emitter` and `RequestBase`.
901 */
902// eslint-disable-next-line new-cap
903
904
905Emitter(Request.prototype); // eslint-disable-next-line new-cap
906
907RequestBase(Request.prototype);
908/**
909 * Set Content-Type to `type`, mapping values from `request.types`.
910 *
911 * Examples:
912 *
913 * superagent.types.xml = 'application/xml';
914 *
915 * request.post('/')
916 * .type('xml')
917 * .send(xmlstring)
918 * .end(callback);
919 *
920 * request.post('/')
921 * .type('application/xml')
922 * .send(xmlstring)
923 * .end(callback);
924 *
925 * @param {String} type
926 * @return {Request} for chaining
927 * @api public
928 */
929
930Request.prototype.type = function (type) {
931 this.set('Content-Type', request.types[type] || type);
932 return this;
933};
934/**
935 * Set Accept to `type`, mapping values from `request.types`.
936 *
937 * Examples:
938 *
939 * superagent.types.json = 'application/json';
940 *
941 * request.get('/agent')
942 * .accept('json')
943 * .end(callback);
944 *
945 * request.get('/agent')
946 * .accept('application/json')
947 * .end(callback);
948 *
949 * @param {String} accept
950 * @return {Request} for chaining
951 * @api public
952 */
953
954
955Request.prototype.accept = function (type) {
956 this.set('Accept', request.types[type] || type);
957 return this;
958};
959/**
960 * Set Authorization field value with `user` and `pass`.
961 *
962 * @param {String} user
963 * @param {String} [pass] optional in case of using 'bearer' as type
964 * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
965 * @return {Request} for chaining
966 * @api public
967 */
968
969
970Request.prototype.auth = function (user, pass, options) {
971 if (arguments.length === 1) pass = '';
972
973 if (_typeof(pass) === 'object' && pass !== null) {
974 // pass is optional and can be replaced with options
975 options = pass;
976 pass = '';
977 }
978
979 if (!options) {
980 options = {
981 type: typeof btoa === 'function' ? 'basic' : 'auto'
982 };
983 }
984
985 var encoder = function encoder(string) {
986 if (typeof btoa === 'function') {
987 return btoa(string);
988 }
989
990 throw new Error('Cannot use basic auth, btoa is not a function');
991 };
992
993 return this._auth(user, pass, options, encoder);
994};
995/**
996 * Add query-string `val`.
997 *
998 * Examples:
999 *
1000 * request.get('/shoes')
1001 * .query('size=10')
1002 * .query({ color: 'blue' })
1003 *
1004 * @param {Object|String} val
1005 * @return {Request} for chaining
1006 * @api public
1007 */
1008
1009
1010Request.prototype.query = function (val) {
1011 if (typeof val !== 'string') val = serialize(val);
1012 if (val) this._query.push(val);
1013 return this;
1014};
1015/**
1016 * Queue the given `file` as an attachment to the specified `field`,
1017 * with optional `options` (or filename).
1018 *
1019 * ``` js
1020 * request.post('/upload')
1021 * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
1022 * .end(callback);
1023 * ```
1024 *
1025 * @param {String} field
1026 * @param {Blob|File} file
1027 * @param {String|Object} options
1028 * @return {Request} for chaining
1029 * @api public
1030 */
1031
1032
1033Request.prototype.attach = function (field, file, options) {
1034 if (file) {
1035 if (this._data) {
1036 throw new Error("superagent can't mix .send() and .attach()");
1037 }
1038
1039 this._getFormData().append(field, file, options || file.name);
1040 }
1041
1042 return this;
1043};
1044
1045Request.prototype._getFormData = function () {
1046 if (!this._formData) {
1047 this._formData = new root.FormData();
1048 }
1049
1050 return this._formData;
1051};
1052/**
1053 * Invoke the callback with `err` and `res`
1054 * and handle arity check.
1055 *
1056 * @param {Error} err
1057 * @param {Response} res
1058 * @api private
1059 */
1060
1061
1062Request.prototype.callback = function (err, res) {
1063 if (this._shouldRetry(err, res)) {
1064 return this._retry();
1065 }
1066
1067 var fn = this._callback;
1068 this.clearTimeout();
1069
1070 if (err) {
1071 if (this._maxRetries) err.retries = this._retries - 1;
1072 this.emit('error', err);
1073 }
1074
1075 fn(err, res);
1076};
1077/**
1078 * Invoke callback with x-domain error.
1079 *
1080 * @api private
1081 */
1082
1083
1084Request.prototype.crossDomainError = function () {
1085 var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
1086 err.crossDomain = true;
1087 err.status = this.status;
1088 err.method = this.method;
1089 err.url = this.url;
1090 this.callback(err);
1091}; // This only warns, because the request is still likely to work
1092
1093
1094Request.prototype.agent = function () {
1095 console.warn('This is not supported in browser version of superagent');
1096 return this;
1097};
1098
1099Request.prototype.ca = Request.prototype.agent;
1100Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected
1101
1102Request.prototype.write = function () {
1103 throw new Error('Streaming is not supported in browser version of superagent');
1104};
1105
1106Request.prototype.pipe = Request.prototype.write;
1107/**
1108 * Check if `obj` is a host object,
1109 * we don't want to serialize these :)
1110 *
1111 * @param {Object} obj host object
1112 * @return {Boolean} is a host object
1113 * @api private
1114 */
1115
1116Request.prototype._isHost = function (obj) {
1117 // Native objects stringify to [object File], [object Blob], [object FormData], etc.
1118 return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
1119};
1120/**
1121 * Initiate request, invoking callback `fn(res)`
1122 * with an instanceof `Response`.
1123 *
1124 * @param {Function} fn
1125 * @return {Request} for chaining
1126 * @api public
1127 */
1128
1129
1130Request.prototype.end = function (fn) {
1131 if (this._endCalled) {
1132 console.warn('Warning: .end() was called twice. This is not supported in superagent');
1133 }
1134
1135 this._endCalled = true; // store callback
1136
1137 this._callback = fn || noop; // querystring
1138
1139 this._finalizeQueryString();
1140
1141 this._end();
1142};
1143
1144Request.prototype._setUploadTimeout = function () {
1145 var self = this; // upload timeout it's wokrs only if deadline timeout is off
1146
1147 if (this._uploadTimeout && !this._uploadTimeoutTimer) {
1148 this._uploadTimeoutTimer = setTimeout(function () {
1149 self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT');
1150 }, this._uploadTimeout);
1151 }
1152}; // eslint-disable-next-line complexity
1153
1154
1155Request.prototype._end = function () {
1156 if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
1157 var self = this;
1158 this.xhr = request.getXHR();
1159 var xhr = this.xhr;
1160 var data = this._formData || this._data;
1161
1162 this._setTimeouts(); // state change
1163
1164
1165 xhr.onreadystatechange = function () {
1166 var readyState = xhr.readyState;
1167
1168 if (readyState >= 2 && self._responseTimeoutTimer) {
1169 clearTimeout(self._responseTimeoutTimer);
1170 }
1171
1172 if (readyState !== 4) {
1173 return;
1174 } // In IE9, reads to any property (e.g. status) off of an aborted XHR will
1175 // result in the error "Could not complete the operation due to error c00c023f"
1176
1177
1178 var status;
1179
1180 try {
1181 status = xhr.status;
1182 } catch (_unused5) {
1183 status = 0;
1184 }
1185
1186 if (!status) {
1187 if (self.timedout || self._aborted) return;
1188 return self.crossDomainError();
1189 }
1190
1191 self.emit('end');
1192 }; // progress
1193
1194
1195 var handleProgress = function handleProgress(direction, e) {
1196 if (e.total > 0) {
1197 e.percent = e.loaded / e.total * 100;
1198
1199 if (e.percent === 100) {
1200 clearTimeout(self._uploadTimeoutTimer);
1201 }
1202 }
1203
1204 e.direction = direction;
1205 self.emit('progress', e);
1206 };
1207
1208 if (this.hasListeners('progress')) {
1209 try {
1210 xhr.addEventListener('progress', handleProgress.bind(null, 'download'));
1211
1212 if (xhr.upload) {
1213 xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload'));
1214 }
1215 } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
1216 // Reported here:
1217 // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
1218 }
1219 }
1220
1221 if (xhr.upload) {
1222 this._setUploadTimeout();
1223 } // initiate request
1224
1225
1226 try {
1227 if (this.username && this.password) {
1228 xhr.open(this.method, this.url, true, this.username, this.password);
1229 } else {
1230 xhr.open(this.method, this.url, true);
1231 }
1232 } catch (err) {
1233 // see #1149
1234 return this.callback(err);
1235 } // CORS
1236
1237
1238 if (this._withCredentials) xhr.withCredentials = true; // body
1239
1240 if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) {
1241 // serialize stuff
1242 var contentType = this._header['content-type'];
1243
1244 var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
1245
1246 if (!_serialize && isJSON(contentType)) {
1247 _serialize = request.serialize['application/json'];
1248 }
1249
1250 if (_serialize) data = _serialize(data);
1251 } // set header fields
1252
1253
1254 for (var field in this.header) {
1255 if (this.header[field] === null) continue;
1256 if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]);
1257 }
1258
1259 if (this._responseType) {
1260 xhr.responseType = this._responseType;
1261 } // send stuff
1262
1263
1264 this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
1265 // We need null here if data is undefined
1266
1267 xhr.send(typeof data === 'undefined' ? null : data);
1268};
1269
1270request.agent = function () {
1271 return new Agent();
1272};
1273
1274['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) {
1275 Agent.prototype[method.toLowerCase()] = function (url, fn) {
1276 var req = new request.Request(method, url);
1277
1278 this._setDefaults(req);
1279
1280 if (fn) {
1281 req.end(fn);
1282 }
1283
1284 return req;
1285 };
1286});
1287Agent.prototype.del = Agent.prototype.delete;
1288/**
1289 * GET `url` with optional callback `fn(res)`.
1290 *
1291 * @param {String} url
1292 * @param {Mixed|Function} [data] or fn
1293 * @param {Function} [fn]
1294 * @return {Request}
1295 * @api public
1296 */
1297
1298request.get = function (url, data, fn) {
1299 var req = request('GET', url);
1300
1301 if (typeof data === 'function') {
1302 fn = data;
1303 data = null;
1304 }
1305
1306 if (data) req.query(data);
1307 if (fn) req.end(fn);
1308 return req;
1309};
1310/**
1311 * HEAD `url` with optional callback `fn(res)`.
1312 *
1313 * @param {String} url
1314 * @param {Mixed|Function} [data] or fn
1315 * @param {Function} [fn]
1316 * @return {Request}
1317 * @api public
1318 */
1319
1320
1321request.head = function (url, data, fn) {
1322 var req = request('HEAD', url);
1323
1324 if (typeof data === 'function') {
1325 fn = data;
1326 data = null;
1327 }
1328
1329 if (data) req.query(data);
1330 if (fn) req.end(fn);
1331 return req;
1332};
1333/**
1334 * OPTIONS query to `url` with optional callback `fn(res)`.
1335 *
1336 * @param {String} url
1337 * @param {Mixed|Function} [data] or fn
1338 * @param {Function} [fn]
1339 * @return {Request}
1340 * @api public
1341 */
1342
1343
1344request.options = function (url, data, fn) {
1345 var req = request('OPTIONS', url);
1346
1347 if (typeof data === 'function') {
1348 fn = data;
1349 data = null;
1350 }
1351
1352 if (data) req.send(data);
1353 if (fn) req.end(fn);
1354 return req;
1355};
1356/**
1357 * DELETE `url` with optional `data` and callback `fn(res)`.
1358 *
1359 * @param {String} url
1360 * @param {Mixed} [data]
1361 * @param {Function} [fn]
1362 * @return {Request}
1363 * @api public
1364 */
1365
1366
1367function del(url, data, fn) {
1368 var req = request('DELETE', url);
1369
1370 if (typeof data === 'function') {
1371 fn = data;
1372 data = null;
1373 }
1374
1375 if (data) req.send(data);
1376 if (fn) req.end(fn);
1377 return req;
1378}
1379
1380request.del = del;
1381request.delete = del;
1382/**
1383 * PATCH `url` with optional `data` and callback `fn(res)`.
1384 *
1385 * @param {String} url
1386 * @param {Mixed} [data]
1387 * @param {Function} [fn]
1388 * @return {Request}
1389 * @api public
1390 */
1391
1392request.patch = function (url, data, fn) {
1393 var req = request('PATCH', url);
1394
1395 if (typeof data === 'function') {
1396 fn = data;
1397 data = null;
1398 }
1399
1400 if (data) req.send(data);
1401 if (fn) req.end(fn);
1402 return req;
1403};
1404/**
1405 * POST `url` with optional `data` and callback `fn(res)`.
1406 *
1407 * @param {String} url
1408 * @param {Mixed} [data]
1409 * @param {Function} [fn]
1410 * @return {Request}
1411 * @api public
1412 */
1413
1414
1415request.post = function (url, data, fn) {
1416 var req = request('POST', url);
1417
1418 if (typeof data === 'function') {
1419 fn = data;
1420 data = null;
1421 }
1422
1423 if (data) req.send(data);
1424 if (fn) req.end(fn);
1425 return req;
1426};
1427/**
1428 * PUT `url` with optional `data` and callback `fn(res)`.
1429 *
1430 * @param {String} url
1431 * @param {Mixed|Function} [data] or fn
1432 * @param {Function} [fn]
1433 * @return {Request}
1434 * @api public
1435 */
1436
1437
1438request.put = function (url, data, fn) {
1439 var req = request('PUT', url);
1440
1441 if (typeof data === 'function') {
1442 fn = data;
1443 data = null;
1444 }
1445
1446 if (data) req.send(data);
1447 if (fn) req.end(fn);
1448 return req;
1449};
1450
1451},{"./agent-base":3,"./is-object":4,"./request-base":6,"./response-base":7,"component-emitter":1,"fast-safe-stringify":2}],6:[function(require,module,exports){
1452"use strict";
1453
1454function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
1455
1456/**
1457 * Module of mixed-in functions shared between node and client code
1458 */
1459var isObject = require('./is-object');
1460/**
1461 * Expose `RequestBase`.
1462 */
1463
1464
1465module.exports = RequestBase;
1466/**
1467 * Initialize a new `RequestBase`.
1468 *
1469 * @api public
1470 */
1471
1472function RequestBase(obj) {
1473 if (obj) return mixin(obj);
1474}
1475/**
1476 * Mixin the prototype properties.
1477 *
1478 * @param {Object} obj
1479 * @return {Object}
1480 * @api private
1481 */
1482
1483
1484function mixin(obj) {
1485 for (var key in RequestBase.prototype) {
1486 if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key];
1487 }
1488
1489 return obj;
1490}
1491/**
1492 * Clear previous timeout.
1493 *
1494 * @return {Request} for chaining
1495 * @api public
1496 */
1497
1498
1499RequestBase.prototype.clearTimeout = function () {
1500 clearTimeout(this._timer);
1501 clearTimeout(this._responseTimeoutTimer);
1502 clearTimeout(this._uploadTimeoutTimer);
1503 delete this._timer;
1504 delete this._responseTimeoutTimer;
1505 delete this._uploadTimeoutTimer;
1506 return this;
1507};
1508/**
1509 * Override default response body parser
1510 *
1511 * This function will be called to convert incoming data into request.body
1512 *
1513 * @param {Function}
1514 * @api public
1515 */
1516
1517
1518RequestBase.prototype.parse = function (fn) {
1519 this._parser = fn;
1520 return this;
1521};
1522/**
1523 * Set format of binary response body.
1524 * In browser valid formats are 'blob' and 'arraybuffer',
1525 * which return Blob and ArrayBuffer, respectively.
1526 *
1527 * In Node all values result in Buffer.
1528 *
1529 * Examples:
1530 *
1531 * req.get('/')
1532 * .responseType('blob')
1533 * .end(callback);
1534 *
1535 * @param {String} val
1536 * @return {Request} for chaining
1537 * @api public
1538 */
1539
1540
1541RequestBase.prototype.responseType = function (val) {
1542 this._responseType = val;
1543 return this;
1544};
1545/**
1546 * Override default request body serializer
1547 *
1548 * This function will be called to convert data set via .send or .attach into payload to send
1549 *
1550 * @param {Function}
1551 * @api public
1552 */
1553
1554
1555RequestBase.prototype.serialize = function (fn) {
1556 this._serializer = fn;
1557 return this;
1558};
1559/**
1560 * Set timeouts.
1561 *
1562 * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
1563 * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
1564 * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
1565 *
1566 * Value of 0 or false means no timeout.
1567 *
1568 * @param {Number|Object} ms or {response, deadline}
1569 * @return {Request} for chaining
1570 * @api public
1571 */
1572
1573
1574RequestBase.prototype.timeout = function (options) {
1575 if (!options || _typeof(options) !== 'object') {
1576 this._timeout = options;
1577 this._responseTimeout = 0;
1578 this._uploadTimeout = 0;
1579 return this;
1580 }
1581
1582 for (var option in options) {
1583 if (Object.prototype.hasOwnProperty.call(options, option)) {
1584 switch (option) {
1585 case 'deadline':
1586 this._timeout = options.deadline;
1587 break;
1588
1589 case 'response':
1590 this._responseTimeout = options.response;
1591 break;
1592
1593 case 'upload':
1594 this._uploadTimeout = options.upload;
1595 break;
1596
1597 default:
1598 console.warn('Unknown timeout option', option);
1599 }
1600 }
1601 }
1602
1603 return this;
1604};
1605/**
1606 * Set number of retry attempts on error.
1607 *
1608 * Failed requests will be retried 'count' times if timeout or err.code >= 500.
1609 *
1610 * @param {Number} count
1611 * @param {Function} [fn]
1612 * @return {Request} for chaining
1613 * @api public
1614 */
1615
1616
1617RequestBase.prototype.retry = function (count, fn) {
1618 // Default to 1 if no count passed or true
1619 if (arguments.length === 0 || count === true) count = 1;
1620 if (count <= 0) count = 0;
1621 this._maxRetries = count;
1622 this._retries = 0;
1623 this._retryCallback = fn;
1624 return this;
1625};
1626
1627var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT'];
1628/**
1629 * Determine if a request should be retried.
1630 * (Borrowed from segmentio/superagent-retry)
1631 *
1632 * @param {Error} err an error
1633 * @param {Response} [res] response
1634 * @returns {Boolean} if segment should be retried
1635 */
1636
1637RequestBase.prototype._shouldRetry = function (err, res) {
1638 if (!this._maxRetries || this._retries++ >= this._maxRetries) {
1639 return false;
1640 }
1641
1642 if (this._retryCallback) {
1643 try {
1644 var override = this._retryCallback(err, res);
1645
1646 if (override === true) return true;
1647 if (override === false) return false; // undefined falls back to defaults
1648 } catch (err_) {
1649 console.error(err_);
1650 }
1651 }
1652
1653 if (res && res.status && res.status >= 500 && res.status !== 501) return true;
1654
1655 if (err) {
1656 if (err.code && ERROR_CODES.includes(err.code)) return true; // Superagent timeout
1657
1658 if (err.timeout && err.code === 'ECONNABORTED') return true;
1659 if (err.crossDomain) return true;
1660 }
1661
1662 return false;
1663};
1664/**
1665 * Retry request
1666 *
1667 * @return {Request} for chaining
1668 * @api private
1669 */
1670
1671
1672RequestBase.prototype._retry = function () {
1673 this.clearTimeout(); // node
1674
1675 if (this.req) {
1676 this.req = null;
1677 this.req = this.request();
1678 }
1679
1680 this._aborted = false;
1681 this.timedout = false;
1682 this.timedoutError = null;
1683 return this._end();
1684};
1685/**
1686 * Promise support
1687 *
1688 * @param {Function} resolve
1689 * @param {Function} [reject]
1690 * @return {Request}
1691 */
1692
1693
1694RequestBase.prototype.then = function (resolve, reject) {
1695 var _this = this;
1696
1697 if (!this._fullfilledPromise) {
1698 var self = this;
1699
1700 if (this._endCalled) {
1701 console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
1702 }
1703
1704 this._fullfilledPromise = new Promise(function (resolve, reject) {
1705 self.on('abort', function () {
1706 if (_this.timedout && _this.timedoutError) {
1707 reject(_this.timedoutError);
1708 return;
1709 }
1710
1711 var err = new Error('Aborted');
1712 err.code = 'ABORTED';
1713 err.status = _this.status;
1714 err.method = _this.method;
1715 err.url = _this.url;
1716 reject(err);
1717 });
1718 self.end(function (err, res) {
1719 if (err) reject(err);else resolve(res);
1720 });
1721 });
1722 }
1723
1724 return this._fullfilledPromise.then(resolve, reject);
1725};
1726
1727RequestBase.prototype.catch = function (cb) {
1728 return this.then(undefined, cb);
1729};
1730/**
1731 * Allow for extension
1732 */
1733
1734
1735RequestBase.prototype.use = function (fn) {
1736 fn(this);
1737 return this;
1738};
1739
1740RequestBase.prototype.ok = function (cb) {
1741 if (typeof cb !== 'function') throw new Error('Callback required');
1742 this._okCallback = cb;
1743 return this;
1744};
1745
1746RequestBase.prototype._isResponseOK = function (res) {
1747 if (!res) {
1748 return false;
1749 }
1750
1751 if (this._okCallback) {
1752 return this._okCallback(res);
1753 }
1754
1755 return res.status >= 200 && res.status < 300;
1756};
1757/**
1758 * Get request header `field`.
1759 * Case-insensitive.
1760 *
1761 * @param {String} field
1762 * @return {String}
1763 * @api public
1764 */
1765
1766
1767RequestBase.prototype.get = function (field) {
1768 return this._header[field.toLowerCase()];
1769};
1770/**
1771 * Get case-insensitive header `field` value.
1772 * This is a deprecated internal API. Use `.get(field)` instead.
1773 *
1774 * (getHeader is no longer used internally by the superagent code base)
1775 *
1776 * @param {String} field
1777 * @return {String}
1778 * @api private
1779 * @deprecated
1780 */
1781
1782
1783RequestBase.prototype.getHeader = RequestBase.prototype.get;
1784/**
1785 * Set header `field` to `val`, or multiple fields with one object.
1786 * Case-insensitive.
1787 *
1788 * Examples:
1789 *
1790 * req.get('/')
1791 * .set('Accept', 'application/json')
1792 * .set('X-API-Key', 'foobar')
1793 * .end(callback);
1794 *
1795 * req.get('/')
1796 * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
1797 * .end(callback);
1798 *
1799 * @param {String|Object} field
1800 * @param {String} val
1801 * @return {Request} for chaining
1802 * @api public
1803 */
1804
1805RequestBase.prototype.set = function (field, val) {
1806 if (isObject(field)) {
1807 for (var key in field) {
1808 if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]);
1809 }
1810
1811 return this;
1812 }
1813
1814 this._header[field.toLowerCase()] = val;
1815 this.header[field] = val;
1816 return this;
1817};
1818/**
1819 * Remove header `field`.
1820 * Case-insensitive.
1821 *
1822 * Example:
1823 *
1824 * req.get('/')
1825 * .unset('User-Agent')
1826 * .end(callback);
1827 *
1828 * @param {String} field field name
1829 */
1830
1831
1832RequestBase.prototype.unset = function (field) {
1833 delete this._header[field.toLowerCase()];
1834 delete this.header[field];
1835 return this;
1836};
1837/**
1838 * Write the field `name` and `val`, or multiple fields with one object
1839 * for "multipart/form-data" request bodies.
1840 *
1841 * ``` js
1842 * request.post('/upload')
1843 * .field('foo', 'bar')
1844 * .end(callback);
1845 *
1846 * request.post('/upload')
1847 * .field({ foo: 'bar', baz: 'qux' })
1848 * .end(callback);
1849 * ```
1850 *
1851 * @param {String|Object} name name of field
1852 * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
1853 * @return {Request} for chaining
1854 * @api public
1855 */
1856
1857
1858RequestBase.prototype.field = function (name, val) {
1859 // name should be either a string or an object.
1860 if (name === null || undefined === name) {
1861 throw new Error('.field(name, val) name can not be empty');
1862 }
1863
1864 if (this._data) {
1865 throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
1866 }
1867
1868 if (isObject(name)) {
1869 for (var key in name) {
1870 if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]);
1871 }
1872
1873 return this;
1874 }
1875
1876 if (Array.isArray(val)) {
1877 for (var i in val) {
1878 if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]);
1879 }
1880
1881 return this;
1882 } // val should be defined now
1883
1884
1885 if (val === null || undefined === val) {
1886 throw new Error('.field(name, val) val can not be empty');
1887 }
1888
1889 if (typeof val === 'boolean') {
1890 val = String(val);
1891 }
1892
1893 this._getFormData().append(name, val);
1894
1895 return this;
1896};
1897/**
1898 * Abort the request, and clear potential timeout.
1899 *
1900 * @return {Request} request
1901 * @api public
1902 */
1903
1904
1905RequestBase.prototype.abort = function () {
1906 if (this._aborted) {
1907 return this;
1908 }
1909
1910 this._aborted = true;
1911 if (this.xhr) this.xhr.abort(); // browser
1912
1913 if (this.req) this.req.abort(); // node
1914
1915 this.clearTimeout();
1916 this.emit('abort');
1917 return this;
1918};
1919
1920RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
1921 switch (options.type) {
1922 case 'basic':
1923 this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
1924 break;
1925
1926 case 'auto':
1927 this.username = user;
1928 this.password = pass;
1929 break;
1930
1931 case 'bearer':
1932 // usage would be .auth(accessToken, { type: 'bearer' })
1933 this.set('Authorization', "Bearer ".concat(user));
1934 break;
1935
1936 default:
1937 break;
1938 }
1939
1940 return this;
1941};
1942/**
1943 * Enable transmission of cookies with x-domain requests.
1944 *
1945 * Note that for this to work the origin must not be
1946 * using "Access-Control-Allow-Origin" with a wildcard,
1947 * and also must set "Access-Control-Allow-Credentials"
1948 * to "true".
1949 *
1950 * @api public
1951 */
1952
1953
1954RequestBase.prototype.withCredentials = function (on) {
1955 // This is browser-only functionality. Node side is no-op.
1956 if (on === undefined) on = true;
1957 this._withCredentials = on;
1958 return this;
1959};
1960/**
1961 * Set the max redirects to `n`. Does nothing in browser XHR implementation.
1962 *
1963 * @param {Number} n
1964 * @return {Request} for chaining
1965 * @api public
1966 */
1967
1968
1969RequestBase.prototype.redirects = function (n) {
1970 this._maxRedirects = n;
1971 return this;
1972};
1973/**
1974 * Maximum size of buffered response body, in bytes. Counts uncompressed size.
1975 * Default 200MB.
1976 *
1977 * @param {Number} n number of bytes
1978 * @return {Request} for chaining
1979 */
1980
1981
1982RequestBase.prototype.maxResponseSize = function (n) {
1983 if (typeof n !== 'number') {
1984 throw new TypeError('Invalid argument');
1985 }
1986
1987 this._maxResponseSize = n;
1988 return this;
1989};
1990/**
1991 * Convert to a plain javascript object (not JSON string) of scalar properties.
1992 * Note as this method is designed to return a useful non-this value,
1993 * it cannot be chained.
1994 *
1995 * @return {Object} describing method, url, and data of this request
1996 * @api public
1997 */
1998
1999
2000RequestBase.prototype.toJSON = function () {
2001 return {
2002 method: this.method,
2003 url: this.url,
2004 data: this._data,
2005 headers: this._header
2006 };
2007};
2008/**
2009 * Send `data` as the request body, defaulting the `.type()` to "json" when
2010 * an object is given.
2011 *
2012 * Examples:
2013 *
2014 * // manual json
2015 * request.post('/user')
2016 * .type('json')
2017 * .send('{"name":"tj"}')
2018 * .end(callback)
2019 *
2020 * // auto json
2021 * request.post('/user')
2022 * .send({ name: 'tj' })
2023 * .end(callback)
2024 *
2025 * // manual x-www-form-urlencoded
2026 * request.post('/user')
2027 * .type('form')
2028 * .send('name=tj')
2029 * .end(callback)
2030 *
2031 * // auto x-www-form-urlencoded
2032 * request.post('/user')
2033 * .type('form')
2034 * .send({ name: 'tj' })
2035 * .end(callback)
2036 *
2037 * // defaults to x-www-form-urlencoded
2038 * request.post('/user')
2039 * .send('name=tobi')
2040 * .send('species=ferret')
2041 * .end(callback)
2042 *
2043 * @param {String|Object} data
2044 * @return {Request} for chaining
2045 * @api public
2046 */
2047// eslint-disable-next-line complexity
2048
2049
2050RequestBase.prototype.send = function (data) {
2051 var isObj = isObject(data);
2052 var type = this._header['content-type'];
2053
2054 if (this._formData) {
2055 throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
2056 }
2057
2058 if (isObj && !this._data) {
2059 if (Array.isArray(data)) {
2060 this._data = [];
2061 } else if (!this._isHost(data)) {
2062 this._data = {};
2063 }
2064 } else if (data && this._data && this._isHost(this._data)) {
2065 throw new Error("Can't merge these send calls");
2066 } // merge
2067
2068
2069 if (isObj && isObject(this._data)) {
2070 for (var key in data) {
2071 if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key];
2072 }
2073 } else if (typeof data === 'string') {
2074 // default to x-www-form-urlencoded
2075 if (!type) this.type('form');
2076 type = this._header['content-type'];
2077
2078 if (type === 'application/x-www-form-urlencoded') {
2079 this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
2080 } else {
2081 this._data = (this._data || '') + data;
2082 }
2083 } else {
2084 this._data = data;
2085 }
2086
2087 if (!isObj || this._isHost(data)) {
2088 return this;
2089 } // default to json
2090
2091
2092 if (!type) this.type('json');
2093 return this;
2094};
2095/**
2096 * Sort `querystring` by the sort function
2097 *
2098 *
2099 * Examples:
2100 *
2101 * // default order
2102 * request.get('/user')
2103 * .query('name=Nick')
2104 * .query('search=Manny')
2105 * .sortQuery()
2106 * .end(callback)
2107 *
2108 * // customized sort function
2109 * request.get('/user')
2110 * .query('name=Nick')
2111 * .query('search=Manny')
2112 * .sortQuery(function(a, b){
2113 * return a.length - b.length;
2114 * })
2115 * .end(callback)
2116 *
2117 *
2118 * @param {Function} sort
2119 * @return {Request} for chaining
2120 * @api public
2121 */
2122
2123
2124RequestBase.prototype.sortQuery = function (sort) {
2125 // _sort default to true but otherwise can be a function or boolean
2126 this._sort = typeof sort === 'undefined' ? true : sort;
2127 return this;
2128};
2129/**
2130 * Compose querystring to append to req.url
2131 *
2132 * @api private
2133 */
2134
2135
2136RequestBase.prototype._finalizeQueryString = function () {
2137 var query = this._query.join('&');
2138
2139 if (query) {
2140 this.url += (this.url.includes('?') ? '&' : '?') + query;
2141 }
2142
2143 this._query.length = 0; // Makes the call idempotent
2144
2145 if (this._sort) {
2146 var index = this.url.indexOf('?');
2147
2148 if (index >= 0) {
2149 var queryArr = this.url.slice(index + 1).split('&');
2150
2151 if (typeof this._sort === 'function') {
2152 queryArr.sort(this._sort);
2153 } else {
2154 queryArr.sort();
2155 }
2156
2157 this.url = this.url.slice(0, index) + '?' + queryArr.join('&');
2158 }
2159 }
2160}; // For backwards compat only
2161
2162
2163RequestBase.prototype._appendQueryString = function () {
2164 console.warn('Unsupported');
2165};
2166/**
2167 * Invoke callback with timeout error.
2168 *
2169 * @api private
2170 */
2171
2172
2173RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
2174 if (this._aborted) {
2175 return;
2176 }
2177
2178 var err = new Error("".concat(reason + timeout, "ms exceeded"));
2179 err.timeout = timeout;
2180 err.code = 'ECONNABORTED';
2181 err.errno = errno;
2182 this.timedout = true;
2183 this.timedoutError = err;
2184 this.abort();
2185 this.callback(err);
2186};
2187
2188RequestBase.prototype._setTimeouts = function () {
2189 var self = this; // deadline
2190
2191 if (this._timeout && !this._timer) {
2192 this._timer = setTimeout(function () {
2193 self._timeoutError('Timeout of ', self._timeout, 'ETIME');
2194 }, this._timeout);
2195 } // response timeout
2196
2197
2198 if (this._responseTimeout && !this._responseTimeoutTimer) {
2199 this._responseTimeoutTimer = setTimeout(function () {
2200 self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
2201 }, this._responseTimeout);
2202 }
2203};
2204
2205},{"./is-object":4}],7:[function(require,module,exports){
2206"use strict";
2207
2208/**
2209 * Module dependencies.
2210 */
2211var utils = require('./utils');
2212/**
2213 * Expose `ResponseBase`.
2214 */
2215
2216
2217module.exports = ResponseBase;
2218/**
2219 * Initialize a new `ResponseBase`.
2220 *
2221 * @api public
2222 */
2223
2224function ResponseBase(obj) {
2225 if (obj) return mixin(obj);
2226}
2227/**
2228 * Mixin the prototype properties.
2229 *
2230 * @param {Object} obj
2231 * @return {Object}
2232 * @api private
2233 */
2234
2235
2236function mixin(obj) {
2237 for (var key in ResponseBase.prototype) {
2238 if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key];
2239 }
2240
2241 return obj;
2242}
2243/**
2244 * Get case-insensitive `field` value.
2245 *
2246 * @param {String} field
2247 * @return {String}
2248 * @api public
2249 */
2250
2251
2252ResponseBase.prototype.get = function (field) {
2253 return this.header[field.toLowerCase()];
2254};
2255/**
2256 * Set header related properties:
2257 *
2258 * - `.type` the content type without params
2259 *
2260 * A response of "Content-Type: text/plain; charset=utf-8"
2261 * will provide you with a `.type` of "text/plain".
2262 *
2263 * @param {Object} header
2264 * @api private
2265 */
2266
2267
2268ResponseBase.prototype._setHeaderProperties = function (header) {
2269 // TODO: moar!
2270 // TODO: make this a util
2271 // content-type
2272 var ct = header['content-type'] || '';
2273 this.type = utils.type(ct); // params
2274
2275 var params = utils.params(ct);
2276
2277 for (var key in params) {
2278 if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key];
2279 }
2280
2281 this.links = {}; // links
2282
2283 try {
2284 if (header.link) {
2285 this.links = utils.parseLinks(header.link);
2286 }
2287 } catch (_unused) {// ignore
2288 }
2289};
2290/**
2291 * Set flags such as `.ok` based on `status`.
2292 *
2293 * For example a 2xx response will give you a `.ok` of __true__
2294 * whereas 5xx will be __false__ and `.error` will be __true__. The
2295 * `.clientError` and `.serverError` are also available to be more
2296 * specific, and `.statusType` is the class of error ranging from 1..5
2297 * sometimes useful for mapping respond colors etc.
2298 *
2299 * "sugar" properties are also defined for common cases. Currently providing:
2300 *
2301 * - .noContent
2302 * - .badRequest
2303 * - .unauthorized
2304 * - .notAcceptable
2305 * - .notFound
2306 *
2307 * @param {Number} status
2308 * @api private
2309 */
2310
2311
2312ResponseBase.prototype._setStatusProperties = function (status) {
2313 var type = status / 100 | 0; // status / class
2314
2315 this.statusCode = status;
2316 this.status = this.statusCode;
2317 this.statusType = type; // basics
2318
2319 this.info = type === 1;
2320 this.ok = type === 2;
2321 this.redirect = type === 3;
2322 this.clientError = type === 4;
2323 this.serverError = type === 5;
2324 this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
2325
2326 this.created = status === 201;
2327 this.accepted = status === 202;
2328 this.noContent = status === 204;
2329 this.badRequest = status === 400;
2330 this.unauthorized = status === 401;
2331 this.notAcceptable = status === 406;
2332 this.forbidden = status === 403;
2333 this.notFound = status === 404;
2334 this.unprocessableEntity = status === 422;
2335};
2336
2337},{"./utils":8}],8:[function(require,module,exports){
2338"use strict";
2339
2340/**
2341 * Return the mime type for the given `str`.
2342 *
2343 * @param {String} str
2344 * @return {String}
2345 * @api private
2346 */
2347exports.type = function (str) {
2348 return str.split(/ *; */).shift();
2349};
2350/**
2351 * Return header field parameters.
2352 *
2353 * @param {String} str
2354 * @return {Object}
2355 * @api private
2356 */
2357
2358
2359exports.params = function (str) {
2360 return str.split(/ *; */).reduce(function (obj, str) {
2361 var parts = str.split(/ *= */);
2362 var key = parts.shift();
2363 var val = parts.shift();
2364 if (key && val) obj[key] = val;
2365 return obj;
2366 }, {});
2367};
2368/**
2369 * Parse Link header fields.
2370 *
2371 * @param {String} str
2372 * @return {Object}
2373 * @api private
2374 */
2375
2376
2377exports.parseLinks = function (str) {
2378 return str.split(/ *, */).reduce(function (obj, str) {
2379 var parts = str.split(/ *; */);
2380 var url = parts[0].slice(1, -1);
2381 var rel = parts[1].split(/ *= */)[1].slice(1, -1);
2382 obj[rel] = url;
2383 return obj;
2384 }, {});
2385};
2386/**
2387 * Strip content related fields from `header`.
2388 *
2389 * @param {Object} header
2390 * @return {Object} header
2391 * @api private
2392 */
2393
2394
2395exports.cleanHeader = function (header, changesOrigin) {
2396 delete header['content-type'];
2397 delete header['content-length'];
2398 delete header['transfer-encoding'];
2399 delete header.host; // secuirty
2400
2401 if (changesOrigin) {
2402 delete header.authorization;
2403 delete header.cookie;
2404 }
2405
2406 return header;
2407};
2408
2409},{}]},{},[5])(5)
2410});