summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/adapters/README.md37
-rwxr-xr-xlib/adapters/http.js303
-rw-r--r--lib/adapters/xhr.js179
-rw-r--r--lib/axios.js56
-rw-r--r--lib/cancel/Cancel.js19
-rw-r--r--lib/cancel/CancelToken.js57
-rw-r--r--lib/cancel/isCancel.js5
-rw-r--r--lib/core/Axios.js95
-rw-r--r--lib/core/InterceptorManager.js52
-rw-r--r--lib/core/README.md7
-rw-r--r--lib/core/buildFullPath.js20
-rw-r--r--lib/core/createError.js18
-rw-r--r--lib/core/dispatchRequest.js79
-rw-r--r--lib/core/enhanceError.js42
-rw-r--r--lib/core/mergeConfig.js87
-rw-r--r--lib/core/settle.js25
-rw-r--r--lib/core/transformData.js20
-rw-r--r--lib/defaults.js98
-rw-r--r--lib/helpers/README.md7
-rw-r--r--lib/helpers/bind.js11
-rw-r--r--lib/helpers/buildURL.js70
-rw-r--r--lib/helpers/combineURLs.js14
-rw-r--r--lib/helpers/cookies.js53
-rw-r--r--lib/helpers/deprecatedMethod.js24
-rw-r--r--lib/helpers/isAbsoluteURL.js14
-rw-r--r--lib/helpers/isAxiosError.js11
-rw-r--r--lib/helpers/isURLSameOrigin.js68
-rw-r--r--lib/helpers/normalizeHeaderName.js12
-rw-r--r--lib/helpers/parseHeaders.js53
-rw-r--r--lib/helpers/spread.js27
-rw-r--r--lib/utils.js351
31 files changed, 1914 insertions, 0 deletions
diff --git a/lib/adapters/README.md b/lib/adapters/README.md
new file mode 100644
index 0000000..68f1118
--- /dev/null
+++ b/lib/adapters/README.md
@@ -0,0 +1,37 @@
+# axios // adapters
+
+The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
+
+## Example
+
+```js
+var settle = require('./../core/settle');
+
+module.exports = function myAdapter(config) {
+ // At this point:
+ // - config has been merged with defaults
+ // - request transformers have already run
+ // - request interceptors have already run
+
+ // Make the request using config provided
+ // Upon response settle the Promise
+
+ return new Promise(function(resolve, reject) {
+
+ var response = {
+ data: responseData,
+ status: request.status,
+ statusText: request.statusText,
+ headers: responseHeaders,
+ config: config,
+ request: request
+ };
+
+ settle(resolve, reject, response);
+
+ // From here:
+ // - response transformers will run
+ // - response interceptors will run
+ });
+}
+```
diff --git a/lib/adapters/http.js b/lib/adapters/http.js
new file mode 100755
index 0000000..f32241f
--- /dev/null
+++ b/lib/adapters/http.js
@@ -0,0 +1,303 @@
+'use strict';
+
+var utils = require('./../utils');
+var settle = require('./../core/settle');
+var buildFullPath = require('../core/buildFullPath');
+var buildURL = require('./../helpers/buildURL');
+var http = require('http');
+var https = require('https');
+var httpFollow = require('follow-redirects').http;
+var httpsFollow = require('follow-redirects').https;
+var url = require('url');
+var zlib = require('zlib');
+var pkg = require('./../../package.json');
+var createError = require('../core/createError');
+var enhanceError = require('../core/enhanceError');
+
+var isHttps = /https:?/;
+
+/**
+ *
+ * @param {http.ClientRequestArgs} options
+ * @param {AxiosProxyConfig} proxy
+ * @param {string} location
+ */
+function setProxy(options, proxy, location) {
+ options.hostname = proxy.host;
+ options.host = proxy.host;
+ options.port = proxy.port;
+ options.path = location;
+
+ // Basic proxy authorization
+ if (proxy.auth) {
+ var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
+ options.headers['Proxy-Authorization'] = 'Basic ' + base64;
+ }
+
+ // If a proxy is used, any redirects must also pass through the proxy
+ options.beforeRedirect = function beforeRedirect(redirection) {
+ redirection.headers.host = redirection.host;
+ setProxy(redirection, proxy, redirection.href);
+ };
+}
+
+/*eslint consistent-return:0*/
+module.exports = function httpAdapter(config) {
+ return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
+ var resolve = function resolve(value) {
+ resolvePromise(value);
+ };
+ var reject = function reject(value) {
+ rejectPromise(value);
+ };
+ var data = config.data;
+ var headers = config.headers;
+
+ // Set User-Agent (required by some servers)
+ // Only set header if it hasn't been set in config
+ // See https://github.com/axios/axios/issues/69
+ if (!headers['User-Agent'] && !headers['user-agent']) {
+ headers['User-Agent'] = 'axios/' + pkg.version;
+ }
+
+ if (data && !utils.isStream(data)) {
+ if (Buffer.isBuffer(data)) {
+ // Nothing to do...
+ } else if (utils.isArrayBuffer(data)) {
+ data = Buffer.from(new Uint8Array(data));
+ } else if (utils.isString(data)) {
+ data = Buffer.from(data, 'utf-8');
+ } else {
+ return reject(createError(
+ 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
+ config
+ ));
+ }
+
+ // Add Content-Length header if data exists
+ headers['Content-Length'] = data.length;
+ }
+
+ // HTTP basic authentication
+ var auth = undefined;
+ if (config.auth) {
+ var username = config.auth.username || '';
+ var password = config.auth.password || '';
+ auth = username + ':' + password;
+ }
+
+ // Parse url
+ var fullPath = buildFullPath(config.baseURL, config.url);
+ var parsed = url.parse(fullPath);
+ var protocol = parsed.protocol || 'http:';
+
+ if (!auth && parsed.auth) {
+ var urlAuth = parsed.auth.split(':');
+ var urlUsername = urlAuth[0] || '';
+ var urlPassword = urlAuth[1] || '';
+ auth = urlUsername + ':' + urlPassword;
+ }
+
+ if (auth) {
+ delete headers.Authorization;
+ }
+
+ var isHttpsRequest = isHttps.test(protocol);
+ var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
+
+ var options = {
+ path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
+ method: config.method.toUpperCase(),
+ headers: headers,
+ agent: agent,
+ agents: { http: config.httpAgent, https: config.httpsAgent },
+ auth: auth
+ };
+
+ if (config.socketPath) {
+ options.socketPath = config.socketPath;
+ } else {
+ options.hostname = parsed.hostname;
+ options.port = parsed.port;
+ }
+
+ var proxy = config.proxy;
+ if (!proxy && proxy !== false) {
+ var proxyEnv = protocol.slice(0, -1) + '_proxy';
+ var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
+ if (proxyUrl) {
+ var parsedProxyUrl = url.parse(proxyUrl);
+ var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;
+ var shouldProxy = true;
+
+ if (noProxyEnv) {
+ var noProxy = noProxyEnv.split(',').map(function trim(s) {
+ return s.trim();
+ });
+
+ shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {
+ if (!proxyElement) {
+ return false;
+ }
+ if (proxyElement === '*') {
+ return true;
+ }
+ if (proxyElement[0] === '.' &&
+ parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {
+ return true;
+ }
+
+ return parsed.hostname === proxyElement;
+ });
+ }
+
+ if (shouldProxy) {
+ proxy = {
+ host: parsedProxyUrl.hostname,
+ port: parsedProxyUrl.port,
+ protocol: parsedProxyUrl.protocol
+ };
+
+ if (parsedProxyUrl.auth) {
+ var proxyUrlAuth = parsedProxyUrl.auth.split(':');
+ proxy.auth = {
+ username: proxyUrlAuth[0],
+ password: proxyUrlAuth[1]
+ };
+ }
+ }
+ }
+ }
+
+ if (proxy) {
+ options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
+ setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
+ }
+
+ var transport;
+ var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
+ if (config.transport) {
+ transport = config.transport;
+ } else if (config.maxRedirects === 0) {
+ transport = isHttpsProxy ? https : http;
+ } else {
+ if (config.maxRedirects) {
+ options.maxRedirects = config.maxRedirects;
+ }
+ transport = isHttpsProxy ? httpsFollow : httpFollow;
+ }
+
+ if (config.maxBodyLength > -1) {
+ options.maxBodyLength = config.maxBodyLength;
+ }
+
+ // Create the request
+ var req = transport.request(options, function handleResponse(res) {
+ if (req.aborted) return;
+
+ // uncompress the response body transparently if required
+ var stream = res;
+
+ // return the last request in case of redirects
+ var lastRequest = res.req || req;
+
+
+ // if no content, is HEAD request or decompress disabled we should not decompress
+ if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {
+ switch (res.headers['content-encoding']) {
+ /*eslint default-case:0*/
+ case 'gzip':
+ case 'compress':
+ case 'deflate':
+ // add the unzipper to the body stream processing pipeline
+ stream = stream.pipe(zlib.createUnzip());
+
+ // remove the content-encoding in order to not confuse downstream operations
+ delete res.headers['content-encoding'];
+ break;
+ }
+ }
+
+ var response = {
+ status: res.statusCode,
+ statusText: res.statusMessage,
+ headers: res.headers,
+ config: config,
+ request: lastRequest
+ };
+
+ if (config.responseType === 'stream') {
+ response.data = stream;
+ settle(resolve, reject, response);
+ } else {
+ var responseBuffer = [];
+ stream.on('data', function handleStreamData(chunk) {
+ responseBuffer.push(chunk);
+
+ // make sure the content length is not over the maxContentLength if specified
+ if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
+ stream.destroy();
+ reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
+ config, null, lastRequest));
+ }
+ });
+
+ stream.on('error', function handleStreamError(err) {
+ if (req.aborted) return;
+ reject(enhanceError(err, config, null, lastRequest));
+ });
+
+ stream.on('end', function handleStreamEnd() {
+ var responseData = Buffer.concat(responseBuffer);
+ if (config.responseType !== 'arraybuffer') {
+ responseData = responseData.toString(config.responseEncoding);
+ if (!config.responseEncoding || config.responseEncoding === 'utf8') {
+ responseData = utils.stripBOM(responseData);
+ }
+ }
+
+ response.data = responseData;
+ settle(resolve, reject, response);
+ });
+ }
+ });
+
+ // Handle errors
+ req.on('error', function handleRequestError(err) {
+ if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return;
+ reject(enhanceError(err, config, null, req));
+ });
+
+ // Handle request timeout
+ if (config.timeout) {
+ // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
+ // And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
+ // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
+ // And then these socket which be hang up will devoring CPU little by little.
+ // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
+ req.setTimeout(config.timeout, function handleRequestTimeout() {
+ req.abort();
+ reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req));
+ });
+ }
+
+ if (config.cancelToken) {
+ // Handle cancellation
+ config.cancelToken.promise.then(function onCanceled(cancel) {
+ if (req.aborted) return;
+
+ req.abort();
+ reject(cancel);
+ });
+ }
+
+ // Send the request
+ if (utils.isStream(data)) {
+ data.on('error', function handleStreamError(err) {
+ reject(enhanceError(err, config, null, req));
+ }).pipe(req);
+ } else {
+ req.end(data);
+ }
+ });
+};
diff --git a/lib/adapters/xhr.js b/lib/adapters/xhr.js
new file mode 100644
index 0000000..3027752
--- /dev/null
+++ b/lib/adapters/xhr.js
@@ -0,0 +1,179 @@
+'use strict';
+
+var utils = require('./../utils');
+var settle = require('./../core/settle');
+var cookies = require('./../helpers/cookies');
+var buildURL = require('./../helpers/buildURL');
+var buildFullPath = require('../core/buildFullPath');
+var parseHeaders = require('./../helpers/parseHeaders');
+var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
+var createError = require('../core/createError');
+
+module.exports = function xhrAdapter(config) {
+ return new Promise(function dispatchXhrRequest(resolve, reject) {
+ var requestData = config.data;
+ var requestHeaders = config.headers;
+
+ if (utils.isFormData(requestData)) {
+ delete requestHeaders['Content-Type']; // Let the browser set it
+ }
+
+ var request = new XMLHttpRequest();
+
+ // HTTP basic authentication
+ if (config.auth) {
+ var username = config.auth.username || '';
+ var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
+ requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
+ }
+
+ var fullPath = buildFullPath(config.baseURL, config.url);
+ request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
+
+ // Set the request timeout in MS
+ request.timeout = config.timeout;
+
+ // Listen for ready state
+ request.onreadystatechange = function handleLoad() {
+ if (!request || request.readyState !== 4) {
+ return;
+ }
+
+ // The request errored out and we didn't get a response, this will be
+ // handled by onerror instead
+ // With one exception: request that using file: protocol, most browsers
+ // will return status as 0 even though it's a successful request
+ if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
+ return;
+ }
+
+ // Prepare the response
+ var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
+ var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
+ var response = {
+ data: responseData,
+ status: request.status,
+ statusText: request.statusText,
+ headers: responseHeaders,
+ config: config,
+ request: request
+ };
+
+ settle(resolve, reject, response);
+
+ // Clean up request
+ request = null;
+ };
+
+ // Handle browser request cancellation (as opposed to a manual cancellation)
+ request.onabort = function handleAbort() {
+ if (!request) {
+ return;
+ }
+
+ reject(createError('Request aborted', config, 'ECONNABORTED', request));
+
+ // Clean up request
+ request = null;
+ };
+
+ // Handle low level network errors
+ request.onerror = function handleError() {
+ // Real errors are hidden from us by the browser
+ // onerror should only fire if it's a network error
+ reject(createError('Network Error', config, null, request));
+
+ // Clean up request
+ request = null;
+ };
+
+ // Handle timeout
+ request.ontimeout = function handleTimeout() {
+ var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
+ if (config.timeoutErrorMessage) {
+ timeoutErrorMessage = config.timeoutErrorMessage;
+ }
+ reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
+ request));
+
+ // Clean up request
+ request = null;
+ };
+
+ // Add xsrf header
+ // This is only done if running in a standard browser environment.
+ // Specifically not if we're in a web worker, or react-native.
+ if (utils.isStandardBrowserEnv()) {
+ // Add xsrf header
+ var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
+ cookies.read(config.xsrfCookieName) :
+ undefined;
+
+ if (xsrfValue) {
+ requestHeaders[config.xsrfHeaderName] = xsrfValue;
+ }
+ }
+
+ // Add headers to the request
+ if ('setRequestHeader' in request) {
+ utils.forEach(requestHeaders, function setRequestHeader(val, key) {
+ if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
+ // Remove Content-Type if data is undefined
+ delete requestHeaders[key];
+ } else {
+ // Otherwise add header to the request
+ request.setRequestHeader(key, val);
+ }
+ });
+ }
+
+ // Add withCredentials to request if needed
+ if (!utils.isUndefined(config.withCredentials)) {
+ request.withCredentials = !!config.withCredentials;
+ }
+
+ // Add responseType to request if needed
+ if (config.responseType) {
+ try {
+ request.responseType = config.responseType;
+ } catch (e) {
+ // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
+ // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
+ if (config.responseType !== 'json') {
+ throw e;
+ }
+ }
+ }
+
+ // Handle progress if needed
+ if (typeof config.onDownloadProgress === 'function') {
+ request.addEventListener('progress', config.onDownloadProgress);
+ }
+
+ // Not all browsers support upload events
+ if (typeof config.onUploadProgress === 'function' && request.upload) {
+ request.upload.addEventListener('progress', config.onUploadProgress);
+ }
+
+ if (config.cancelToken) {
+ // Handle cancellation
+ config.cancelToken.promise.then(function onCanceled(cancel) {
+ if (!request) {
+ return;
+ }
+
+ request.abort();
+ reject(cancel);
+ // Clean up request
+ request = null;
+ });
+ }
+
+ if (!requestData) {
+ requestData = null;
+ }
+
+ // Send the request
+ request.send(requestData);
+ });
+};
diff --git a/lib/axios.js b/lib/axios.js
new file mode 100644
index 0000000..c6357b0
--- /dev/null
+++ b/lib/axios.js
@@ -0,0 +1,56 @@
+'use strict';
+
+var utils = require('./utils');
+var bind = require('./helpers/bind');
+var Axios = require('./core/Axios');
+var mergeConfig = require('./core/mergeConfig');
+var defaults = require('./defaults');
+
+/**
+ * Create an instance of Axios
+ *
+ * @param {Object} defaultConfig The default config for the instance
+ * @return {Axios} A new instance of Axios
+ */
+function createInstance(defaultConfig) {
+ var context = new Axios(defaultConfig);
+ var instance = bind(Axios.prototype.request, context);
+
+ // Copy axios.prototype to instance
+ utils.extend(instance, Axios.prototype, context);
+
+ // Copy context to instance
+ utils.extend(instance, context);
+
+ return instance;
+}
+
+// Create the default instance to be exported
+var axios = createInstance(defaults);
+
+// Expose Axios class to allow class inheritance
+axios.Axios = Axios;
+
+// Factory for creating new instances
+axios.create = function create(instanceConfig) {
+ return createInstance(mergeConfig(axios.defaults, instanceConfig));
+};
+
+// Expose Cancel & CancelToken
+axios.Cancel = require('./cancel/Cancel');
+axios.CancelToken = require('./cancel/CancelToken');
+axios.isCancel = require('./cancel/isCancel');
+
+// Expose all/spread
+axios.all = function all(promises) {
+ return Promise.all(promises);
+};
+axios.spread = require('./helpers/spread');
+
+// Expose isAxiosError
+axios.isAxiosError = require('./helpers/isAxiosError');
+
+module.exports = axios;
+
+// Allow use of default import syntax in TypeScript
+module.exports.default = axios;
diff --git a/lib/cancel/Cancel.js b/lib/cancel/Cancel.js
new file mode 100644
index 0000000..e0de400
--- /dev/null
+++ b/lib/cancel/Cancel.js
@@ -0,0 +1,19 @@
+'use strict';
+
+/**
+ * A `Cancel` is an object that is thrown when an operation is canceled.
+ *
+ * @class
+ * @param {string=} message The message.
+ */
+function Cancel(message) {
+ this.message = message;
+}
+
+Cancel.prototype.toString = function toString() {
+ return 'Cancel' + (this.message ? ': ' + this.message : '');
+};
+
+Cancel.prototype.__CANCEL__ = true;
+
+module.exports = Cancel;
diff --git a/lib/cancel/CancelToken.js b/lib/cancel/CancelToken.js
new file mode 100644
index 0000000..6b46e66
--- /dev/null
+++ b/lib/cancel/CancelToken.js
@@ -0,0 +1,57 @@
+'use strict';
+
+var Cancel = require('./Cancel');
+
+/**
+ * A `CancelToken` is an object that can be used to request cancellation of an operation.
+ *
+ * @class
+ * @param {Function} executor The executor function.
+ */
+function CancelToken(executor) {
+ if (typeof executor !== 'function') {
+ throw new TypeError('executor must be a function.');
+ }
+
+ var resolvePromise;
+ this.promise = new Promise(function promiseExecutor(resolve) {
+ resolvePromise = resolve;
+ });
+
+ var token = this;
+ executor(function cancel(message) {
+ if (token.reason) {
+ // Cancellation has already been requested
+ return;
+ }
+
+ token.reason = new Cancel(message);
+ resolvePromise(token.reason);
+ });
+}
+
+/**
+ * Throws a `Cancel` if cancellation has been requested.
+ */
+CancelToken.prototype.throwIfRequested = function throwIfRequested() {
+ if (this.reason) {
+ throw this.reason;
+ }
+};
+
+/**
+ * Returns an object that contains a new `CancelToken` and a function that, when called,
+ * cancels the `CancelToken`.
+ */
+CancelToken.source = function source() {
+ var cancel;
+ var token = new CancelToken(function executor(c) {
+ cancel = c;
+ });
+ return {
+ token: token,
+ cancel: cancel
+ };
+};
+
+module.exports = CancelToken;
diff --git a/lib/cancel/isCancel.js b/lib/cancel/isCancel.js
new file mode 100644
index 0000000..051f3ae
--- /dev/null
+++ b/lib/cancel/isCancel.js
@@ -0,0 +1,5 @@
+'use strict';
+
+module.exports = function isCancel(value) {
+ return !!(value && value.__CANCEL__);
+};
diff --git a/lib/core/Axios.js b/lib/core/Axios.js
new file mode 100644
index 0000000..c28c413
--- /dev/null
+++ b/lib/core/Axios.js
@@ -0,0 +1,95 @@
+'use strict';
+
+var utils = require('./../utils');
+var buildURL = require('../helpers/buildURL');
+var InterceptorManager = require('./InterceptorManager');
+var dispatchRequest = require('./dispatchRequest');
+var mergeConfig = require('./mergeConfig');
+
+/**
+ * Create a new instance of Axios
+ *
+ * @param {Object} instanceConfig The default config for the instance
+ */
+function Axios(instanceConfig) {
+ this.defaults = instanceConfig;
+ this.interceptors = {
+ request: new InterceptorManager(),
+ response: new InterceptorManager()
+ };
+}
+
+/**
+ * Dispatch a request
+ *
+ * @param {Object} config The config specific for this request (merged with this.defaults)
+ */
+Axios.prototype.request = function request(config) {
+ /*eslint no-param-reassign:0*/
+ // Allow for axios('example/url'[, config]) a la fetch API
+ if (typeof config === 'string') {
+ config = arguments[1] || {};
+ config.url = arguments[0];
+ } else {
+ config = config || {};
+ }
+
+ config = mergeConfig(this.defaults, config);
+
+ // Set config.method
+ if (config.method) {
+ config.method = config.method.toLowerCase();
+ } else if (this.defaults.method) {
+ config.method = this.defaults.method.toLowerCase();
+ } else {
+ config.method = 'get';
+ }
+
+ // Hook up interceptors middleware
+ var chain = [dispatchRequest, undefined];
+ var promise = Promise.resolve(config);
+
+ this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
+ chain.unshift(interceptor.fulfilled, interceptor.rejected);
+ });
+
+ this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
+ chain.push(interceptor.fulfilled, interceptor.rejected);
+ });
+
+ while (chain.length) {
+ promise = promise.then(chain.shift(), chain.shift());
+ }
+
+ return promise;
+};
+
+Axios.prototype.getUri = function getUri(config) {
+ config = mergeConfig(this.defaults, config);
+ return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
+};
+
+// Provide aliases for supported request methods
+utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
+ /*eslint func-names:0*/
+ Axios.prototype[method] = function(url, config) {
+ return this.request(mergeConfig(config || {}, {
+ method: method,
+ url: url,
+ data: (config || {}).data
+ }));
+ };
+});
+
+utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
+ /*eslint func-names:0*/
+ Axios.prototype[method] = function(url, data, config) {
+ return this.request(mergeConfig(config || {}, {
+ method: method,
+ url: url,
+ data: data
+ }));
+ };
+});
+
+module.exports = Axios;
diff --git a/lib/core/InterceptorManager.js b/lib/core/InterceptorManager.js
new file mode 100644
index 0000000..50d667b
--- /dev/null
+++ b/lib/core/InterceptorManager.js
@@ -0,0 +1,52 @@
+'use strict';
+
+var utils = require('./../utils');
+
+function InterceptorManager() {
+ this.handlers = [];
+}
+
+/**
+ * Add a new interceptor to the stack
+ *
+ * @param {Function} fulfilled The function to handle `then` for a `Promise`
+ * @param {Function} rejected The function to handle `reject` for a `Promise`
+ *
+ * @return {Number} An ID used to remove interceptor later
+ */
+InterceptorManager.prototype.use = function use(fulfilled, rejected) {
+ this.handlers.push({
+ fulfilled: fulfilled,
+ rejected: rejected
+ });
+ return this.handlers.length - 1;
+};
+
+/**
+ * Remove an interceptor from the stack
+ *
+ * @param {Number} id The ID that was returned by `use`
+ */
+InterceptorManager.prototype.eject = function eject(id) {
+ if (this.handlers[id]) {
+ this.handlers[id] = null;
+ }
+};
+
+/**
+ * Iterate over all the registered interceptors
+ *
+ * This method is particularly useful for skipping over any
+ * interceptors that may have become `null` calling `eject`.
+ *
+ * @param {Function} fn The function to call for each interceptor
+ */
+InterceptorManager.prototype.forEach = function forEach(fn) {
+ utils.forEach(this.handlers, function forEachHandler(h) {
+ if (h !== null) {
+ fn(h);
+ }
+ });
+};
+
+module.exports = InterceptorManager;
diff --git a/lib/core/README.md b/lib/core/README.md
new file mode 100644
index 0000000..253bc48
--- /dev/null
+++ b/lib/core/README.md
@@ -0,0 +1,7 @@
+# axios // core
+
+The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are:
+
+- Dispatching requests
+- Managing interceptors
+- Handling config
diff --git a/lib/core/buildFullPath.js b/lib/core/buildFullPath.js
new file mode 100644
index 0000000..00b2b05
--- /dev/null
+++ b/lib/core/buildFullPath.js
@@ -0,0 +1,20 @@
+'use strict';
+
+var isAbsoluteURL = require('../helpers/isAbsoluteURL');
+var combineURLs = require('../helpers/combineURLs');
+
+/**
+ * Creates a new URL by combining the baseURL with the requestedURL,
+ * only when the requestedURL is not already an absolute URL.
+ * If the requestURL is absolute, this function returns the requestedURL untouched.
+ *
+ * @param {string} baseURL The base URL
+ * @param {string} requestedURL Absolute or relative URL to combine
+ * @returns {string} The combined full path
+ */
+module.exports = function buildFullPath(baseURL, requestedURL) {
+ if (baseURL && !isAbsoluteURL(requestedURL)) {
+ return combineURLs(baseURL, requestedURL);
+ }
+ return requestedURL;
+};
diff --git a/lib/core/createError.js b/lib/core/createError.js
new file mode 100644
index 0000000..933680f
--- /dev/null
+++ b/lib/core/createError.js
@@ -0,0 +1,18 @@
+'use strict';
+
+var enhanceError = require('./enhanceError');
+
+/**
+ * Create an Error with the specified message, config, error code, request and response.
+ *
+ * @param {string} message The error message.
+ * @param {Object} config The config.
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
+ * @param {Object} [request] The request.
+ * @param {Object} [response] The response.
+ * @returns {Error} The created error.
+ */
+module.exports = function createError(message, config, code, request, response) {
+ var error = new Error(message);
+ return enhanceError(error, config, code, request, response);
+};
diff --git a/lib/core/dispatchRequest.js b/lib/core/dispatchRequest.js
new file mode 100644
index 0000000..c8267ad
--- /dev/null
+++ b/lib/core/dispatchRequest.js
@@ -0,0 +1,79 @@
+'use strict';
+
+var utils = require('./../utils');
+var transformData = require('./transformData');
+var isCancel = require('../cancel/isCancel');
+var defaults = require('../defaults');
+
+/**
+ * Throws a `Cancel` if cancellation has been requested.
+ */
+function throwIfCancellationRequested(config) {
+ if (config.cancelToken) {
+ config.cancelToken.throwIfRequested();
+ }
+}
+
+/**
+ * Dispatch a request to the server using the configured adapter.
+ *
+ * @param {object} config The config that is to be used for the request
+ * @returns {Promise} The Promise to be fulfilled
+ */
+module.exports = function dispatchRequest(config) {
+ throwIfCancellationRequested(config);
+
+ // Ensure headers exist
+ config.headers = config.headers || {};
+
+ // Transform request data
+ config.data = transformData(
+ config.data,
+ config.headers,
+ config.transformRequest
+ );
+
+ // Flatten headers
+ config.headers = utils.merge(
+ config.headers.common || {},
+ config.headers[config.method] || {},
+ config.headers
+ );
+
+ utils.forEach(
+ ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
+ function cleanHeaderConfig(method) {
+ delete config.headers[method];
+ }
+ );
+
+ var adapter = config.adapter || defaults.adapter;
+
+ return adapter(config).then(function onAdapterResolution(response) {
+ throwIfCancellationRequested(config);
+
+ // Transform response data
+ response.data = transformData(
+ response.data,
+ response.headers,
+ config.transformResponse
+ );
+
+ return response;
+ }, function onAdapterRejection(reason) {
+ if (!isCancel(reason)) {
+ throwIfCancellationRequested(config);
+
+ // Transform response data
+ if (reason && reason.response) {
+ reason.response.data = transformData(
+ reason.response.data,
+ reason.response.headers,
+ config.transformResponse
+ );
+ }
+ }
+
+ return Promise.reject(reason);
+ });
+};
diff --git a/lib/core/enhanceError.js b/lib/core/enhanceError.js
new file mode 100644
index 0000000..b6bc444
--- /dev/null
+++ b/lib/core/enhanceError.js
@@ -0,0 +1,42 @@
+'use strict';
+
+/**
+ * Update an Error with the specified config, error code, and response.
+ *
+ * @param {Error} error The error to update.
+ * @param {Object} config The config.
+ * @param {string} [code] The error code (for example, 'ECONNABORTED').
+ * @param {Object} [request] The request.
+ * @param {Object} [response] The response.
+ * @returns {Error} The error.
+ */
+module.exports = function enhanceError(error, config, code, request, response) {
+ error.config = config;
+ if (code) {
+ error.code = code;
+ }
+
+ error.request = request;
+ error.response = response;
+ error.isAxiosError = true;
+
+ error.toJSON = function toJSON() {
+ return {
+ // Standard
+ message: this.message,
+ name: this.name,
+ // Microsoft
+ description: this.description,
+ number: this.number,
+ // Mozilla
+ fileName: this.fileName,
+ lineNumber: this.lineNumber,
+ columnNumber: this.columnNumber,
+ stack: this.stack,
+ // Axios
+ config: this.config,
+ code: this.code
+ };
+ };
+ return error;
+};
diff --git a/lib/core/mergeConfig.js b/lib/core/mergeConfig.js
new file mode 100644
index 0000000..5a2c10c
--- /dev/null
+++ b/lib/core/mergeConfig.js
@@ -0,0 +1,87 @@
+'use strict';
+
+var utils = require('../utils');
+
+/**
+ * Config-specific merge-function which creates a new config-object
+ * by merging two configuration objects together.
+ *
+ * @param {Object} config1
+ * @param {Object} config2
+ * @returns {Object} New object resulting from merging config2 to config1
+ */
+module.exports = function mergeConfig(config1, config2) {
+ // eslint-disable-next-line no-param-reassign
+ config2 = config2 || {};
+ var config = {};
+
+ var valueFromConfig2Keys = ['url', 'method', 'data'];
+ var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
+ var defaultToConfig2Keys = [
+ 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
+ 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
+ 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
+ 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
+ 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
+ ];
+ var directMergeKeys = ['validateStatus'];
+
+ function getMergedValue(target, source) {
+ if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
+ return utils.merge(target, source);
+ } else if (utils.isPlainObject(source)) {
+ return utils.merge({}, source);
+ } else if (utils.isArray(source)) {
+ return source.slice();
+ }
+ return source;
+ }
+
+ function mergeDeepProperties(prop) {
+ if (!utils.isUndefined(config2[prop])) {
+ config[prop] = getMergedValue(config1[prop], config2[prop]);
+ } else if (!utils.isUndefined(config1[prop])) {
+ config[prop] = getMergedValue(undefined, config1[prop]);
+ }
+ }
+
+ utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
+ if (!utils.isUndefined(config2[prop])) {
+ config[prop] = getMergedValue(undefined, config2[prop]);
+ }
+ });
+
+ utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
+
+ utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
+ if (!utils.isUndefined(config2[prop])) {
+ config[prop] = getMergedValue(undefined, config2[prop]);
+ } else if (!utils.isUndefined(config1[prop])) {
+ config[prop] = getMergedValue(undefined, config1[prop]);
+ }
+ });
+
+ utils.forEach(directMergeKeys, function merge(prop) {
+ if (prop in config2) {
+ config[prop] = getMergedValue(config1[prop], config2[prop]);
+ } else if (prop in config1) {
+ config[prop] = getMergedValue(undefined, config1[prop]);
+ }
+ });
+
+ var axiosKeys = valueFromConfig2Keys
+ .concat(mergeDeepPropertiesKeys)
+ .concat(defaultToConfig2Keys)
+ .concat(directMergeKeys);
+
+ var otherKeys = Object
+ .keys(config1)
+ .concat(Object.keys(config2))
+ .filter(function filterAxiosKeys(key) {
+ return axiosKeys.indexOf(key) === -1;
+ });
+
+ utils.forEach(otherKeys, mergeDeepProperties);
+
+ return config;
+};
diff --git a/lib/core/settle.js b/lib/core/settle.js
new file mode 100644
index 0000000..886adb0
--- /dev/null
+++ b/lib/core/settle.js
@@ -0,0 +1,25 @@
+'use strict';
+
+var createError = require('./createError');
+
+/**
+ * Resolve or reject a Promise based on response status.
+ *
+ * @param {Function} resolve A function that resolves the promise.
+ * @param {Function} reject A function that rejects the promise.
+ * @param {object} response The response.
+ */
+module.exports = function settle(resolve, reject, response) {
+ var validateStatus = response.config.validateStatus;
+ if (!response.status || !validateStatus || validateStatus(response.status)) {
+ resolve(response);
+ } else {
+ reject(createError(
+ 'Request failed with status code ' + response.status,
+ response.config,
+ null,
+ response.request,
+ response
+ ));
+ }
+};
diff --git a/lib/core/transformData.js b/lib/core/transformData.js
new file mode 100644
index 0000000..e065362
--- /dev/null
+++ b/lib/core/transformData.js
@@ -0,0 +1,20 @@
+'use strict';
+
+var utils = require('./../utils');
+
+/**
+ * Transform the data for a request or a response
+ *
+ * @param {Object|String} data The data to be transformed
+ * @param {Array} headers The headers for the request or response
+ * @param {Array|Function} fns A single function or Array of functions
+ * @returns {*} The resulting transformed data
+ */
+module.exports = function transformData(data, headers, fns) {
+ /*eslint no-param-reassign:0*/
+ utils.forEach(fns, function transform(fn) {
+ data = fn(data, headers);
+ });
+
+ return data;
+};
diff --git a/lib/defaults.js b/lib/defaults.js
new file mode 100644
index 0000000..2b2a1a7
--- /dev/null
+++ b/lib/defaults.js
@@ -0,0 +1,98 @@
+'use strict';
+
+var utils = require('./utils');
+var normalizeHeaderName = require('./helpers/normalizeHeaderName');
+
+var DEFAULT_CONTENT_TYPE = {
+ 'Content-Type': 'application/x-www-form-urlencoded'
+};
+
+function setContentTypeIfUnset(headers, value) {
+ if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
+ headers['Content-Type'] = value;
+ }
+}
+
+function getDefaultAdapter() {
+ var adapter;
+ if (typeof XMLHttpRequest !== 'undefined') {
+ // For browsers use XHR adapter
+ adapter = require('./adapters/xhr');
+ } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
+ // For node use HTTP adapter
+ adapter = require('./adapters/http');
+ }
+ return adapter;
+}
+
+var defaults = {
+ adapter: getDefaultAdapter(),
+
+ transformRequest: [function transformRequest(data, headers) {
+ normalizeHeaderName(headers, 'Accept');
+ normalizeHeaderName(headers, 'Content-Type');
+ if (utils.isFormData(data) ||
+ utils.isArrayBuffer(data) ||
+ utils.isBuffer(data) ||
+ utils.isStream(data) ||
+ utils.isFile(data) ||
+ utils.isBlob(data)
+ ) {
+ return data;
+ }
+ if (utils.isArrayBufferView(data)) {
+ return data.buffer;
+ }
+ if (utils.isURLSearchParams(data)) {
+ setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
+ return data.toString();
+ }
+ if (utils.isObject(data)) {
+ setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
+ return JSON.stringify(data);
+ }
+ return data;
+ }],
+
+ transformResponse: [function transformResponse(data) {
+ /*eslint no-param-reassign:0*/
+ if (typeof data === 'string') {
+ try {
+ data = JSON.parse(data);
+ } catch (e) { /* Ignore */ }
+ }
+ return data;
+ }],
+
+ /**
+ * A timeout in milliseconds to abort a request. If set to 0 (default) a
+ * timeout is not created.
+ */
+ timeout: 0,
+
+ xsrfCookieName: 'XSRF-TOKEN',
+ xsrfHeaderName: 'X-XSRF-TOKEN',
+
+ maxContentLength: -1,
+ maxBodyLength: -1,
+
+ validateStatus: function validateStatus(status) {
+ return status >= 200 && status < 300;
+ }
+};
+
+defaults.headers = {
+ common: {
+ 'Accept': 'application/json, text/plain, */*'
+ }
+};
+
+utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
+ defaults.headers[method] = {};
+});
+
+utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
+ defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
+});
+
+module.exports = defaults;
diff --git a/lib/helpers/README.md b/lib/helpers/README.md
new file mode 100644
index 0000000..4ae3419
--- /dev/null
+++ b/lib/helpers/README.md
@@ -0,0 +1,7 @@
+# axios // helpers
+
+The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like:
+
+- Browser polyfills
+- Managing cookies
+- Parsing HTTP headers
diff --git a/lib/helpers/bind.js b/lib/helpers/bind.js
new file mode 100644
index 0000000..6147c60
--- /dev/null
+++ b/lib/helpers/bind.js
@@ -0,0 +1,11 @@
+'use strict';
+
+module.exports = function bind(fn, thisArg) {
+ return function wrap() {
+ var args = new Array(arguments.length);
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i];
+ }
+ return fn.apply(thisArg, args);
+ };
+};
diff --git a/lib/helpers/buildURL.js b/lib/helpers/buildURL.js
new file mode 100644
index 0000000..31595c3
--- /dev/null
+++ b/lib/helpers/buildURL.js
@@ -0,0 +1,70 @@
+'use strict';
+
+var utils = require('./../utils');
+
+function encode(val) {
+ return encodeURIComponent(val).
+ replace(/%3A/gi, ':').
+ replace(/%24/g, '$').
+ replace(/%2C/gi, ',').
+ replace(/%20/g, '+').
+ replace(/%5B/gi, '[').
+ replace(/%5D/gi, ']');
+}
+
+/**
+ * Build a URL by appending params to the end
+ *
+ * @param {string} url The base of the url (e.g., http://www.google.com)
+ * @param {object} [params] The params to be appended
+ * @returns {string} The formatted url
+ */
+module.exports = function buildURL(url, params, paramsSerializer) {
+ /*eslint no-param-reassign:0*/
+ if (!params) {
+ return url;
+ }
+
+ var serializedParams;
+ if (paramsSerializer) {
+ serializedParams = paramsSerializer(params);
+ } else if (utils.isURLSearchParams(params)) {
+ serializedParams = params.toString();
+ } else {
+ var parts = [];
+
+ utils.forEach(params, function serialize(val, key) {
+ if (val === null || typeof val === 'undefined') {
+ return;
+ }
+
+ if (utils.isArray(val)) {
+ key = key + '[]';
+ } else {
+ val = [val];
+ }
+
+ utils.forEach(val, function parseValue(v) {
+ if (utils.isDate(v)) {
+ v = v.toISOString();
+ } else if (utils.isObject(v)) {
+ v = JSON.stringify(v);
+ }
+ parts.push(encode(key) + '=' + encode(v));
+ });
+ });
+
+ serializedParams = parts.join('&');
+ }
+
+ if (serializedParams) {
+ var hashmarkIndex = url.indexOf('#');
+ if (hashmarkIndex !== -1) {
+ url = url.slice(0, hashmarkIndex);
+ }
+
+ url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
+ }
+
+ return url;
+};
diff --git a/lib/helpers/combineURLs.js b/lib/helpers/combineURLs.js
new file mode 100644
index 0000000..f1b58a5
--- /dev/null
+++ b/lib/helpers/combineURLs.js
@@ -0,0 +1,14 @@
+'use strict';
+
+/**
+ * Creates a new URL by combining the specified URLs
+ *
+ * @param {string} baseURL The base URL
+ * @param {string} relativeURL The relative URL
+ * @returns {string} The combined URL
+ */
+module.exports = function combineURLs(baseURL, relativeURL) {
+ return relativeURL
+ ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
+ : baseURL;
+};
diff --git a/lib/helpers/cookies.js b/lib/helpers/cookies.js
new file mode 100644
index 0000000..5a8a666
--- /dev/null
+++ b/lib/helpers/cookies.js
@@ -0,0 +1,53 @@
+'use strict';
+
+var utils = require('./../utils');
+
+module.exports = (
+ utils.isStandardBrowserEnv() ?
+
+ // Standard browser envs support document.cookie
+ (function standardBrowserEnv() {
+ return {
+ write: function write(name, value, expires, path, domain, secure) {
+ var cookie = [];
+ cookie.push(name + '=' + encodeURIComponent(value));
+
+ if (utils.isNumber(expires)) {
+ cookie.push('expires=' + new Date(expires).toGMTString());
+ }
+
+ if (utils.isString(path)) {
+ cookie.push('path=' + path);
+ }
+
+ if (utils.isString(domain)) {
+ cookie.push('domain=' + domain);
+ }
+
+ if (secure === true) {
+ cookie.push('secure');
+ }
+
+ document.cookie = cookie.join('; ');
+ },
+
+ read: function read(name) {
+ var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
+ return (match ? decodeURIComponent(match[3]) : null);
+ },
+
+ remove: function remove(name) {
+ this.write(name, '', Date.now() - 86400000);
+ }
+ };
+ })() :
+
+ // Non standard browser env (web workers, react-native) lack needed support.
+ (function nonStandardBrowserEnv() {
+ return {
+ write: function write() {},
+ read: function read() { return null; },
+ remove: function remove() {}
+ };
+ })()
+);
diff --git a/lib/helpers/deprecatedMethod.js b/lib/helpers/deprecatedMethod.js
new file mode 100644
index 0000000..ed40965
--- /dev/null
+++ b/lib/helpers/deprecatedMethod.js
@@ -0,0 +1,24 @@
+'use strict';
+
+/*eslint no-console:0*/
+
+/**
+ * Supply a warning to the developer that a method they are using
+ * has been deprecated.
+ *
+ * @param {string} method The name of the deprecated method
+ * @param {string} [instead] The alternate method to use if applicable
+ * @param {string} [docs] The documentation URL to get further details
+ */
+module.exports = function deprecatedMethod(method, instead, docs) {
+ try {
+ console.warn(
+ 'DEPRECATED method `' + method + '`.' +
+ (instead ? ' Use `' + instead + '` instead.' : '') +
+ ' This method will be removed in a future release.');
+
+ if (docs) {
+ console.warn('For more information about usage see ' + docs);
+ }
+ } catch (e) { /* Ignore */ }
+};
diff --git a/lib/helpers/isAbsoluteURL.js b/lib/helpers/isAbsoluteURL.js
new file mode 100644
index 0000000..d33e992
--- /dev/null
+++ b/lib/helpers/isAbsoluteURL.js
@@ -0,0 +1,14 @@
+'use strict';
+
+/**
+ * Determines whether the specified URL is absolute
+ *
+ * @param {string} url The URL to test
+ * @returns {boolean} True if the specified URL is absolute, otherwise false
+ */
+module.exports = function isAbsoluteURL(url) {
+ // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
+ // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
+ // by any combination of letters, digits, plus, period, or hyphen.
+ return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
+};
diff --git a/lib/helpers/isAxiosError.js b/lib/helpers/isAxiosError.js
new file mode 100644
index 0000000..29ff41a
--- /dev/null
+++ b/lib/helpers/isAxiosError.js
@@ -0,0 +1,11 @@
+'use strict';
+
+/**
+ * Determines whether the payload is an error thrown by Axios
+ *
+ * @param {*} payload The value to test
+ * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
+ */
+module.exports = function isAxiosError(payload) {
+ return (typeof payload === 'object') && (payload.isAxiosError === true);
+};
diff --git a/lib/helpers/isURLSameOrigin.js b/lib/helpers/isURLSameOrigin.js
new file mode 100644
index 0000000..f1d89ad
--- /dev/null
+++ b/lib/helpers/isURLSameOrigin.js
@@ -0,0 +1,68 @@
+'use strict';
+
+var utils = require('./../utils');
+
+module.exports = (
+ utils.isStandardBrowserEnv() ?
+
+ // Standard browser envs have full support of the APIs needed to test
+ // whether the request URL is of the same origin as current location.
+ (function standardBrowserEnv() {
+ var msie = /(msie|trident)/i.test(navigator.userAgent);
+ var urlParsingNode = document.createElement('a');
+ var originURL;
+
+ /**
+ * Parse a URL to discover it's components
+ *
+ * @param {String} url The URL to be parsed
+ * @returns {Object}
+ */
+ function resolveURL(url) {
+ var href = url;
+
+ if (msie) {
+ // IE needs attribute set twice to normalize properties
+ urlParsingNode.setAttribute('href', href);
+ href = urlParsingNode.href;
+ }
+
+ urlParsingNode.setAttribute('href', href);
+
+ // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
+ return {
+ href: urlParsingNode.href,
+ protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
+ host: urlParsingNode.host,
+ search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
+ hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
+ hostname: urlParsingNode.hostname,
+ port: urlParsingNode.port,
+ pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
+ urlParsingNode.pathname :
+ '/' + urlParsingNode.pathname
+ };
+ }
+
+ originURL = resolveURL(window.location.href);
+
+ /**
+ * Determine if a URL shares the same origin as the current location
+ *
+ * @param {String} requestURL The URL to test
+ * @returns {boolean} True if URL shares the same origin, otherwise false
+ */
+ return function isURLSameOrigin(requestURL) {
+ var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
+ return (parsed.protocol === originURL.protocol &&
+ parsed.host === originURL.host);
+ };
+ })() :
+
+ // Non standard browser envs (web workers, react-native) lack needed support.
+ (function nonStandardBrowserEnv() {
+ return function isURLSameOrigin() {
+ return true;
+ };
+ })()
+);
diff --git a/lib/helpers/normalizeHeaderName.js b/lib/helpers/normalizeHeaderName.js
new file mode 100644
index 0000000..738c9fe
--- /dev/null
+++ b/lib/helpers/normalizeHeaderName.js
@@ -0,0 +1,12 @@
+'use strict';
+
+var utils = require('../utils');
+
+module.exports = function normalizeHeaderName(headers, normalizedName) {
+ utils.forEach(headers, function processHeader(value, name) {
+ if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
+ headers[normalizedName] = value;
+ delete headers[name];
+ }
+ });
+};
diff --git a/lib/helpers/parseHeaders.js b/lib/helpers/parseHeaders.js
new file mode 100644
index 0000000..8af2cc7
--- /dev/null
+++ b/lib/helpers/parseHeaders.js
@@ -0,0 +1,53 @@
+'use strict';
+
+var utils = require('./../utils');
+
+// Headers whose duplicates are ignored by node
+// c.f. https://nodejs.org/api/http.html#http_message_headers
+var ignoreDuplicateOf = [
+ 'age', 'authorization', 'content-length', 'content-type', 'etag',
+ 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
+ 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
+ 'referer', 'retry-after', 'user-agent'
+];
+
+/**
+ * Parse headers into an object
+ *
+ * ```
+ * Date: Wed, 27 Aug 2014 08:58:49 GMT
+ * Content-Type: application/json
+ * Connection: keep-alive
+ * Transfer-Encoding: chunked
+ * ```
+ *
+ * @param {String} headers Headers needing to be parsed
+ * @returns {Object} Headers parsed into an object
+ */
+module.exports = function parseHeaders(headers) {
+ var parsed = {};
+ var key;
+ var val;
+ var i;
+
+ if (!headers) { return parsed; }
+
+ utils.forEach(headers.split('\n'), function parser(line) {
+ i = line.indexOf(':');
+ key = utils.trim(line.substr(0, i)).toLowerCase();
+ val = utils.trim(line.substr(i + 1));
+
+ if (key) {
+ if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
+ return;
+ }
+ if (key === 'set-cookie') {
+ parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
+ } else {
+ parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
+ }
+ }
+ });
+
+ return parsed;
+};
diff --git a/lib/helpers/spread.js b/lib/helpers/spread.js
new file mode 100644
index 0000000..25e3cdd
--- /dev/null
+++ b/lib/helpers/spread.js
@@ -0,0 +1,27 @@
+'use strict';
+
+/**
+ * Syntactic sugar for invoking a function and expanding an array for arguments.
+ *
+ * Common use case would be to use `Function.prototype.apply`.
+ *
+ * ```js
+ * function f(x, y, z) {}
+ * var args = [1, 2, 3];
+ * f.apply(null, args);
+ * ```
+ *
+ * With `spread` this example can be re-written.
+ *
+ * ```js
+ * spread(function(x, y, z) {})([1, 2, 3]);
+ * ```
+ *
+ * @param {Function} callback
+ * @returns {Function}
+ */
+module.exports = function spread(callback) {
+ return function wrap(arr) {
+ return callback.apply(null, arr);
+ };
+};
diff --git a/lib/utils.js b/lib/utils.js
new file mode 100644
index 0000000..83eb1c6
--- /dev/null
+++ b/lib/utils.js
@@ -0,0 +1,351 @@
+'use strict';
+
+var bind = require('./helpers/bind');
+
+/*global toString:true*/
+
+// utils is a library of generic helper functions non-specific to axios
+
+var toString = Object.prototype.toString;
+
+/**
+ * Determine if a value is an Array
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is an Array, otherwise false
+ */
+function isArray(val) {
+ return toString.call(val) === '[object Array]';
+}
+
+/**
+ * Determine if a value is undefined
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if the value is undefined, otherwise false
+ */
+function isUndefined(val) {
+ return typeof val === 'undefined';
+}
+
+/**
+ * Determine if a value is a Buffer
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a Buffer, otherwise false
+ */
+function isBuffer(val) {
+ return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
+ && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
+}
+
+/**
+ * Determine if a value is an ArrayBuffer
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is an ArrayBuffer, otherwise false
+ */
+function isArrayBuffer(val) {
+ return toString.call(val) === '[object ArrayBuffer]';
+}
+
+/**
+ * Determine if a value is a FormData
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is an FormData, otherwise false
+ */
+function isFormData(val) {
+ return (typeof FormData !== 'undefined') && (val instanceof FormData);
+}
+
+/**
+ * Determine if a value is a view on an ArrayBuffer
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
+ */
+function isArrayBufferView(val) {
+ var result;
+ if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
+ result = ArrayBuffer.isView(val);
+ } else {
+ result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
+ }
+ return result;
+}
+
+/**
+ * Determine if a value is a String
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a String, otherwise false
+ */
+function isString(val) {
+ return typeof val === 'string';
+}
+
+/**
+ * Determine if a value is a Number
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a Number, otherwise false
+ */
+function isNumber(val) {
+ return typeof val === 'number';
+}
+
+/**
+ * Determine if a value is an Object
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is an Object, otherwise false
+ */
+function isObject(val) {
+ return val !== null && typeof val === 'object';
+}
+
+/**
+ * Determine if a value is a plain Object
+ *
+ * @param {Object} val The value to test
+ * @return {boolean} True if value is a plain Object, otherwise false
+ */
+function isPlainObject(val) {
+ if (toString.call(val) !== '[object Object]') {
+ return false;
+ }
+
+ var prototype = Object.getPrototypeOf(val);
+ return prototype === null || prototype === Object.prototype;
+}
+
+/**
+ * Determine if a value is a Date
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a Date, otherwise false
+ */
+function isDate(val) {
+ return toString.call(val) === '[object Date]';
+}
+
+/**
+ * Determine if a value is a File
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a File, otherwise false
+ */
+function isFile(val) {
+ return toString.call(val) === '[object File]';
+}
+
+/**
+ * Determine if a value is a Blob
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a Blob, otherwise false
+ */
+function isBlob(val) {
+ return toString.call(val) === '[object Blob]';
+}
+
+/**
+ * Determine if a value is a Function
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a Function, otherwise false
+ */
+function isFunction(val) {
+ return toString.call(val) === '[object Function]';
+}
+
+/**
+ * Determine if a value is a Stream
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a Stream, otherwise false
+ */
+function isStream(val) {
+ return isObject(val) && isFunction(val.pipe);
+}
+
+/**
+ * Determine if a value is a URLSearchParams object
+ *
+ * @param {Object} val The value to test
+ * @returns {boolean} True if value is a URLSearchParams object, otherwise false
+ */
+function isURLSearchParams(val) {
+ return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
+}
+
+/**
+ * Trim excess whitespace off the beginning and end of a string
+ *
+ * @param {String} str The String to trim
+ * @returns {String} The String freed of excess whitespace
+ */
+function trim(str) {
+ return str.replace(/^\s*/, '').replace(/\s*$/, '');
+}
+
+/**
+ * Determine if we're running in a standard browser environment
+ *
+ * This allows axios to run in a web worker, and react-native.
+ * Both environments support XMLHttpRequest, but not fully standard globals.
+ *
+ * web workers:
+ * typeof window -> undefined
+ * typeof document -> undefined
+ *
+ * react-native:
+ * navigator.product -> 'ReactNative'
+ * nativescript
+ * navigator.product -> 'NativeScript' or 'NS'
+ */
+function isStandardBrowserEnv() {
+ if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
+ navigator.product === 'NativeScript' ||
+ navigator.product === 'NS')) {
+ return false;
+ }
+ return (
+ typeof window !== 'undefined' &&
+ typeof document !== 'undefined'
+ );
+}
+
+/**
+ * Iterate over an Array or an Object invoking a function for each item.
+ *
+ * If `obj` is an Array callback will be called passing
+ * the value, index, and complete array for each item.
+ *
+ * If 'obj' is an Object callback will be called passing
+ * the value, key, and complete object for each property.
+ *
+ * @param {Object|Array} obj The object to iterate
+ * @param {Function} fn The callback to invoke for each item
+ */
+function forEach(obj, fn) {
+ // Don't bother if no value provided
+ if (obj === null || typeof obj === 'undefined') {
+ return;
+ }
+
+ // Force an array if not already something iterable
+ if (typeof obj !== 'object') {
+ /*eslint no-param-reassign:0*/
+ obj = [obj];
+ }
+
+ if (isArray(obj)) {
+ // Iterate over array values
+ for (var i = 0, l = obj.length; i < l; i++) {
+ fn.call(null, obj[i], i, obj);
+ }
+ } else {
+ // Iterate over object keys
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ fn.call(null, obj[key], key, obj);
+ }
+ }
+ }
+}
+
+/**
+ * Accepts varargs expecting each argument to be an object, then
+ * immutably merges the properties of each object and returns result.
+ *
+ * When multiple objects contain the same key the later object in
+ * the arguments list will take precedence.
+ *
+ * Example:
+ *
+ * ```js
+ * var result = merge({foo: 123}, {foo: 456});
+ * console.log(result.foo); // outputs 456
+ * ```
+ *
+ * @param {Object} obj1 Object to merge
+ * @returns {Object} Result of all merge properties
+ */
+function merge(/* obj1, obj2, obj3, ... */) {
+ var result = {};
+ function assignValue(val, key) {
+ if (isPlainObject(result[key]) && isPlainObject(val)) {
+ result[key] = merge(result[key], val);
+ } else if (isPlainObject(val)) {
+ result[key] = merge({}, val);
+ } else if (isArray(val)) {
+ result[key] = val.slice();
+ } else {
+ result[key] = val;
+ }
+ }
+
+ for (var i = 0, l = arguments.length; i < l; i++) {
+ forEach(arguments[i], assignValue);
+ }
+ return result;
+}
+
+/**
+ * Extends object a by mutably adding to it the properties of object b.
+ *
+ * @param {Object} a The object to be extended
+ * @param {Object} b The object to copy properties from
+ * @param {Object} thisArg The object to bind function to
+ * @return {Object} The resulting value of object a
+ */
+function extend(a, b, thisArg) {
+ forEach(b, function assignValue(val, key) {
+ if (thisArg && typeof val === 'function') {
+ a[key] = bind(val, thisArg);
+ } else {
+ a[key] = val;
+ }
+ });
+ return a;
+}
+
+/**
+ * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
+ *
+ * @param {string} content with BOM
+ * @return {string} content value without BOM
+ */
+function stripBOM(content) {
+ if (content.charCodeAt(0) === 0xFEFF) {
+ content = content.slice(1);
+ }
+ return content;
+}
+
+module.exports = {
+ isArray: isArray,
+ isArrayBuffer: isArrayBuffer,
+ isBuffer: isBuffer,
+ isFormData: isFormData,
+ isArrayBufferView: isArrayBufferView,
+ isString: isString,
+ isNumber: isNumber,
+ isObject: isObject,
+ isPlainObject: isPlainObject,
+ isUndefined: isUndefined,
+ isDate: isDate,
+ isFile: isFile,
+ isBlob: isBlob,
+ isFunction: isFunction,
+ isStream: isStream,
+ isURLSearchParams: isURLSearchParams,
+ isStandardBrowserEnv: isStandardBrowserEnv,
+ forEach: forEach,
+ merge: merge,
+ extend: extend,
+ trim: trim,
+ stripBOM: stripBOM
+};