superagent.js 56 KB

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