├── .gitignore
├── axios-v1.x
├── test
│ ├── specs
│ │ ├── core
│ │ │ ├── enhanceError.spec.js
│ │ │ ├── buildFullPath.spec.js
│ │ │ └── transformData.spec.js
│ │ ├── utils
│ │ │ ├── trim.spec.js
│ │ │ ├── kindOf.js
│ │ │ ├── endsWith.js
│ │ │ ├── kindOfTest.js
│ │ │ ├── toArray.js
│ │ │ ├── toFlatObject.js
│ │ │ ├── extend.spec.js
│ │ │ └── forEach.spec.js
│ │ ├── helpers
│ │ │ ├── bind.spec.js
│ │ │ ├── isURLSameOrigin.spec.js
│ │ │ ├── spread.spec.js
│ │ │ ├── isAxiosError.spec.js
│ │ │ ├── isAbsoluteURL.spec.js
│ │ │ ├── combineURLs.spec.js
│ │ │ ├── cookies.spec.js
│ │ │ ├── validator.spec.js
│ │ │ ├── parseHeaders.spec.js
│ │ │ └── formDataToJSON.spec.js
│ │ ├── formdata.spec.js
│ │ ├── cancel
│ │ │ ├── isCancel.spec.js
│ │ │ └── CanceledError.spec.js
│ │ ├── __helpers.js
│ │ └── promise.spec.js
│ ├── manual
│ │ ├── fixture.json
│ │ ├── cors.html
│ │ ├── progress.html
│ │ └── basic.html
│ ├── unit
│ │ ├── adapters
│ │ │ ├── axios.png
│ │ │ ├── cert.pem
│ │ │ ├── adapters.js
│ │ │ └── key.pem
│ │ ├── helpers
│ │ │ ├── fromDataURI.js
│ │ │ └── parseProtocol.js
│ │ ├── regression
│ │ │ ├── bugs.js
│ │ │ └── SNYK-JS-AXIOS-1038255.js
│ │ └── defaults
│ │ │ └── transformReponse.js
│ └── module
│ │ ├── typings
│ │ ├── cjs
│ │ │ ├── tsconfig.json
│ │ │ └── package.json
│ │ └── esm
│ │ │ ├── tsconfig.json
│ │ │ └── package.json
│ │ ├── cjs
│ │ ├── package.json
│ │ └── index.js
│ │ ├── esm
│ │ ├── package.json
│ │ └── index.js
│ │ ├── ts
│ │ ├── package.json
│ │ └── index.ts
│ │ ├── ts-require
│ │ ├── package.json
│ │ ├── index.ts
│ │ └── index.js
│ │ └── ts-require-default
│ │ ├── package.json
│ │ ├── index.ts
│ │ └── index.js
├── lib
│ ├── env
│ │ ├── data.js
│ │ ├── classes
│ │ │ └── FormData.js
│ │ └── README.md
│ ├── helpers
│ │ ├── null.js
│ │ ├── bind.js
│ │ ├── parseProtocol.js
│ │ ├── README.md
│ │ ├── readBlob.js
│ │ ├── isAxiosError.js
│ │ ├── callbackify.js
│ │ ├── combineURLs.js
│ │ ├── isAbsoluteURL.js
│ │ ├── toURLEncodedForm.js
│ │ ├── spread.js
│ │ ├── ZlibHeaderTransformStream.js
│ │ ├── deprecatedMethod.js
│ │ ├── throttle.js
│ │ ├── progressEventReducer.js
│ │ ├── cookies.js
│ │ ├── speedometer.js
│ │ ├── trackStream.js
│ │ ├── composeSignals.js
│ │ ├── fromDataURI.js
│ │ ├── parseHeaders.js
│ │ ├── AxiosURLSearchParams.js
│ │ ├── buildURL.js
│ │ └── HttpStatusCode.js
│ ├── platform
│ │ ├── node
│ │ │ ├── classes
│ │ │ │ ├── FormData.js
│ │ │ │ └── URLSearchParams.js
│ │ │ └── index.js
│ │ ├── browser
│ │ │ ├── classes
│ │ │ │ ├── Blob.js
│ │ │ │ ├── FormData.js
│ │ │ │ └── URLSearchParams.js
│ │ │ └── index.js
│ │ ├── index.js
│ │ └── common
│ │ │ └── utils.js
│ ├── cancel
│ │ ├── isCancel.js
│ │ └── CanceledError.js
│ ├── defaults
│ │ └── transitional.js
│ ├── core
│ │ ├── README.md
│ │ ├── buildFullPath.js
│ │ ├── transformData.js
│ │ ├── settle.js
│ │ └── InterceptorManager.js
│ └── adapters
│ │ └── README.md
├── .github
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE
│ │ ├── config.yml
│ │ ├── DOCUMENTATION.yml
│ │ └── FEATURE_REQUEST.yml
│ ├── dependabot.yml
│ ├── workflows
│ │ ├── depsreview.yaml
│ │ ├── npm-tag.yml
│ │ ├── codeql-analysis.yml
│ │ ├── stale.yml
│ │ ├── notify.yml
│ │ └── ci.yml
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── ISSUE_TEMPLATE.md
├── MIGRATION_GUIDE.md
├── bin
│ ├── api.js
│ ├── helpers
│ │ ├── parser.js
│ │ └── colorize.js
│ ├── ssl_hotfix.js
│ ├── githubAxios.js
│ ├── actions
│ │ └── notify_published.js
│ ├── check-build-version.js
│ └── pr.js
├── templates
│ ├── pr_published.hbs
│ ├── pr.hbs
│ ├── prs.hbs
│ └── contributors.hbs
├── .npmignore
├── tsconfig.json
├── .gitignore
├── tslint.json
├── examples
│ ├── README.md
│ ├── upload
│ │ ├── server.js
│ │ └── index.html
│ ├── postMultipartFormData
│ │ └── server.js
│ ├── post
│ │ ├── server.js
│ │ └── index.html
│ ├── get
│ │ ├── server.js
│ │ └── index.html
│ ├── amd
│ │ └── index.html
│ ├── all
│ │ └── index.html
│ └── transform-response
│ │ └── index.html
├── SECURITY.md
├── .eslintrc.cjs
├── sandbox
│ └── client.js
├── webpack.config.js
├── bower.json
├── index.js
├── LICENSE
└── CONTRIBUTING.md
├── axios
├── index.js
├── test
│ ├── manual
│ │ ├── fixture.json
│ │ ├── cors.html
│ │ └── basic.html
│ └── specs
│ │ ├── basicAuth.spec.js
│ │ ├── utils
│ │ ├── trim.spec.js
│ │ ├── extend.spec.js
│ │ ├── merge.spec.js
│ │ ├── forEach.spec.js
│ │ └── deepMerge.spec.js
│ │ ├── helpers
│ │ ├── bind.spec.js
│ │ ├── spread.spec.js
│ │ ├── isURLSameOrigin.spec.js
│ │ ├── normalizeHeaderName.spec.js
│ │ ├── isAbsoluteURL.spec.js
│ │ ├── combineURLs.spec.js
│ │ ├── cookies.spec.js
│ │ ├── isValidXss.spec.js
│ │ └── parseHeaders.spec.js
│ │ ├── cancel
│ │ ├── isCancel.spec.js
│ │ └── Cancel.spec.js
│ │ ├── adapter.spec.js
│ │ ├── core
│ │ ├── transformData.spec.js
│ │ ├── enhanceError.spec.js
│ │ ├── buildFullPath.spec.js
│ │ └── createError.spec.js
│ │ └── promise.spec.js
├── lib
│ ├── cancel
│ │ ├── isCancel.js
│ │ ├── Cancel.js
│ │ └── CancelToken.js
│ ├── helpers
│ │ ├── isValidXss.js
│ │ ├── bind.js
│ │ ├── README.md
│ │ ├── normalizeHeaderName.js
│ │ ├── combineURLs.js
│ │ ├── isAbsoluteURL.js
│ │ ├── spread.js
│ │ ├── deprecatedMethod.js
│ │ ├── parseHeaders.js
│ │ ├── cookies.js
│ │ └── buildURL.js
│ ├── core
│ │ ├── README.md
│ │ ├── transformData.js
│ │ ├── createError.js
│ │ ├── buildFullPath.js
│ │ ├── settle.js
│ │ ├── enhanceError.js
│ │ └── InterceptorManager.js
│ ├── adapters
│ │ └── README.md
│ └── axios.js
├── .gitignore
├── examples
│ ├── README.md
│ ├── upload
│ │ ├── server.js
│ │ └── index.html
│ ├── post
│ │ ├── server.js
│ │ └── index.html
│ ├── get
│ │ ├── server.js
│ │ └── index.html
│ ├── cancel
│ │ └── server.js
│ ├── interceptors
│ │ └── server.js
│ ├── amd
│ │ └── index.html
│ ├── all
│ │ └── index.html
│ └── transform-response
│ │ └── index.html
├── .npmignore
├── sandbox
│ ├── client.js
│ └── server.js
├── .travis.yml
├── .github
│ ├── PULL_REQUEST_TEMPLATE.md
│ ├── ISSUE_TEMPLATE
│ │ ├── --feature-request.md
│ │ ├── ---documentation.md
│ │ ├── ---support-or-usage-question.md
│ │ └── ---bug-report.md
│ └── ISSUE_TEMPLATE.md
├── bower.json
├── webpack.config.js
├── LICENSE
└── CONTRIBUTING.md
├── images
├── axios-all.png
├── axios-instance.png
├── umi-request-image.png
├── axios-promise-chain.png
└── request-promise-chain.png
├── xmind
├── axios-all.xmind
├── axios-instance.xmind
├── promise-chain.xmind
└── promise-chain-zen.xmind
├── md-v1.x
└── axios-build
│ └── images
│ ├── .DS_Store
│ ├── dist-4.png
│ ├── debugger.png
│ ├── debugger-cmd.png
│ ├── debugger-js.png
│ ├── debugger-rollup.png
│ ├── npm-run-release-dry.png
│ ├── npm-run-release@若川.png
│ └── npm-run-release-dry-2.png
├── .vscode
└── launch.json
└── shells
└── cp.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/core/enhanceError.spec.js:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/axios/index.js:
--------------------------------------------------------------------------------
1 | module.exports = require('./lib/axios');
--------------------------------------------------------------------------------
/axios/test/manual/fixture.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "axios"
3 | }
--------------------------------------------------------------------------------
/axios-v1.x/lib/env/data.js:
--------------------------------------------------------------------------------
1 | export const VERSION = "1.7.0-beta.0";
--------------------------------------------------------------------------------
/axios-v1.x/test/manual/fixture.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "axios"
3 | }
--------------------------------------------------------------------------------
/axios-v1.x/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | open_collective: axios
2 | github: axios
3 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/ISSUE_TEMPLATE/config.yml:
--------------------------------------------------------------------------------
1 | blank_issues_enabled: true
2 |
--------------------------------------------------------------------------------
/axios-v1.x/MIGRATION_GUIDE.md:
--------------------------------------------------------------------------------
1 | # Migration Guide
2 |
3 | ## 0.x.x -> 1.1.0
4 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/null.js:
--------------------------------------------------------------------------------
1 | // eslint-disable-next-line strict
2 | export default null;
3 |
--------------------------------------------------------------------------------
/images/axios-all.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/images/axios-all.png
--------------------------------------------------------------------------------
/xmind/axios-all.xmind:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/xmind/axios-all.xmind
--------------------------------------------------------------------------------
/axios/test/specs/basicAuth.spec.js:
--------------------------------------------------------------------------------
1 | describe('basicAuth', function () {
2 | setupBasicAuthTest();
3 | });
4 |
--------------------------------------------------------------------------------
/images/axios-instance.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/images/axios-instance.png
--------------------------------------------------------------------------------
/xmind/axios-instance.xmind:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/xmind/axios-instance.xmind
--------------------------------------------------------------------------------
/xmind/promise-chain.xmind:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/xmind/promise-chain.xmind
--------------------------------------------------------------------------------
/images/umi-request-image.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/images/umi-request-image.png
--------------------------------------------------------------------------------
/axios-v1.x/bin/api.js:
--------------------------------------------------------------------------------
1 | import GithubAPI from "./GithubAPI.js";
2 |
3 | export default new GithubAPI('axios', 'axios');
4 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/node/classes/FormData.js:
--------------------------------------------------------------------------------
1 | import FormData from 'form-data';
2 |
3 | export default FormData;
4 |
--------------------------------------------------------------------------------
/images/axios-promise-chain.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/images/axios-promise-chain.png
--------------------------------------------------------------------------------
/xmind/promise-chain-zen.xmind:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/xmind/promise-chain-zen.xmind
--------------------------------------------------------------------------------
/images/request-promise-chain.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/images/request-promise-chain.png
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/browser/classes/Blob.js:
--------------------------------------------------------------------------------
1 | 'use strict'
2 |
3 | export default typeof Blob !== 'undefined' ? Blob : null
4 |
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/.DS_Store
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/dist-4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/dist-4.png
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/adapters/axios.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/axios-v1.x/test/unit/adapters/axios.png
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/debugger.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/debugger.png
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/browser/classes/FormData.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | export default typeof FormData !== 'undefined' ? FormData : null;
4 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/node/classes/URLSearchParams.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import url from 'url';
4 | export default url.URLSearchParams;
5 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/typings/cjs/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "checkJs": true,
4 | "module": "node16"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/typings/esm/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "checkJs": true,
4 | "module": "node16"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/debugger-cmd.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/debugger-cmd.png
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/debugger-js.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/debugger-js.png
--------------------------------------------------------------------------------
/axios-v1.x/lib/cancel/isCancel.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | export default function isCancel(value) {
4 | return !!(value && value.__CANCEL__);
5 | }
6 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/env/classes/FormData.js:
--------------------------------------------------------------------------------
1 | import _FormData from 'form-data';
2 | export default typeof FormData !== 'undefined' ? FormData : _FormData;
3 |
--------------------------------------------------------------------------------
/axios/lib/cancel/isCancel.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | module.exports = function isCancel(value) {
4 | return !!(value && value.__CANCEL__);
5 | };
6 |
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/debugger-rollup.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/debugger-rollup.png
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/npm-run-release-dry.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/npm-run-release-dry.png
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/npm-run-release@若川.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/npm-run-release@若川.png
--------------------------------------------------------------------------------
/md-v1.x/axios-build/images/npm-run-release-dry-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ruochuan12/axios-analysis/HEAD/md-v1.x/axios-build/images/npm-run-release-dry-2.png
--------------------------------------------------------------------------------
/axios-v1.x/lib/env/README.md:
--------------------------------------------------------------------------------
1 | # axios // env
2 |
3 | The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually.
4 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "github-actions"
4 | directory: "/"
5 | schedule:
6 | interval: "weekly"
7 |
--------------------------------------------------------------------------------
/axios-v1.x/templates/pr_published.hbs:
--------------------------------------------------------------------------------
1 | Hi, @{{ author.login }}! This PR has been published in [{{ release.tag }}]({{ release.url }}) release. Thank you for your contribution ❤️!
2 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/defaults/transitional.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | export default {
4 | silentJSONParsing: true,
5 | forcedJSONParsing: true,
6 | clarifyTimeoutError: false
7 | };
8 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/bind.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | export default function bind(fn, thisArg) {
4 | return function wrap() {
5 | return fn.apply(thisArg, arguments);
6 | };
7 | }
8 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/index.js:
--------------------------------------------------------------------------------
1 | import platform from './node/index.js';
2 | import * as utils from './common/utils.js';
3 |
4 | export default {
5 | ...utils,
6 | ...platform
7 | }
8 |
--------------------------------------------------------------------------------
/axios/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .idea
3 | .tscache
4 | .DS_Store
5 | node_modules/
6 | typings/
7 | coverage/
8 | test/typescript/axios.js*
9 | sauce_connect.log
10 | package-lock.json
11 |
--------------------------------------------------------------------------------
/axios-v1.x/.npmignore:
--------------------------------------------------------------------------------
1 | **/*
2 | !/dist/**
3 | !/lib/**
4 | !index.js
5 | !index.d.ts
6 | !index.d.cts
7 | !CHANGELOG.md
8 | !LICENSE
9 | !MIGRATION_GUIDE.md
10 | !README.md
11 | !SECURITY.md
12 |
--------------------------------------------------------------------------------
/axios-v1.x/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "node16",
4 | "lib": ["dom", "es2015"],
5 | "types": [],
6 | "strict": true,
7 | "noEmit": true
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/parseProtocol.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | export default function parseProtocol(url) {
4 | const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
5 | return match && match[1] || '';
6 | }
7 |
--------------------------------------------------------------------------------
/axios/lib/helpers/isValidXss.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | module.exports = function isValidXss(requestURL) {
4 | var xssRegex = /(\b)(on\w+)=|javascript|(<\s*)(\/*)script/gi;
5 | return xssRegex.test(requestURL);
6 | };
7 |
8 |
--------------------------------------------------------------------------------
/axios-v1.x/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .idea
3 | .tscache
4 | .DS_Store
5 | node_modules/
6 | coverage/
7 | test/typescript/axios.js*
8 | sauce_connect.log
9 | test/module/**/package-lock.json
10 | backup/
11 | /.husky/
12 | .npmrc
13 | .env
14 |
--------------------------------------------------------------------------------
/axios-v1.x/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "dtslint/dtslint.json",
3 | "rules": {
4 | "no-unnecessary-generics": false
5 | },
6 | "linterOptions": {
7 | "exclude": [
8 | "test/module/**"
9 | ]
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/browser/classes/URLSearchParams.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';
4 | export default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
5 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/README.md:
--------------------------------------------------------------------------------
1 | # axios examples
2 |
3 | To run the examples:
4 |
5 | 1. `git clone https://github.com/axios/axios.git`
6 | 2. `cd axios`
7 | 3. `npm install`
8 | 4. `npm run build`
9 | 5. `npm run examples`
10 | 6. [http://localhost:3000](http://localhost:3000)
--------------------------------------------------------------------------------
/axios/examples/README.md:
--------------------------------------------------------------------------------
1 | # axios examples
2 |
3 | To run the examples:
4 |
5 | 1. `git clone https://github.com/axios/axios.git`
6 | 2. `cd axios`
7 | 3. `npm install`
8 | 4. `grunt build`
9 | 5. `npm run examples`
10 | 6. [http://localhost:3000](http://localhost:3000)
11 |
--------------------------------------------------------------------------------
/axios-v1.x/templates/pr.hbs:
--------------------------------------------------------------------------------
1 | {{#if files}}
2 | ### Build info
3 |
4 | {{#each files}}
5 | - {{ name}} ({{ path }}) {{ filesize size }} (**{{ filesize gzip }}** gzipped)
6 | {{#each commits}}
7 | - {{ tag }} - {{filesize size}}
8 | {{/each}}
9 | {{/each}}
10 | {{/if}}
11 |
--------------------------------------------------------------------------------
/axios/.npmignore:
--------------------------------------------------------------------------------
1 | **/.*
2 | *.iml
3 | coverage/
4 | examples/
5 | node_modules/
6 | typings/
7 | sandbox/
8 | test/
9 | bower.json
10 | CODE_OF_CONDUCT.md
11 | COLLABORATOR_GUIDE.md
12 | CONTRIBUTING.md
13 | COOKBOOK.md
14 | ECOSYSTEM.md
15 | Gruntfile.js
16 | karma.conf.js
17 | webpack.*.js
18 | sauce_connect.log
19 |
--------------------------------------------------------------------------------
/axios/examples/upload/server.js:
--------------------------------------------------------------------------------
1 | module.exports = function (req, res) {
2 | var data = '';
3 |
4 | req.on('data', function (chunk) {
5 | data += chunk;
6 | });
7 |
8 | req.on('end', function () {
9 | console.log('File uploaded');
10 | res.writeHead(200);
11 | res.end();
12 | });
13 | };
14 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/upload/server.js:
--------------------------------------------------------------------------------
1 | export default function (req, res) {
2 | let data = '';
3 |
4 | req.on('data', function (chunk) {
5 | data += chunk;
6 | });
7 |
8 | req.on('end', function () {
9 | console.log('File uploaded');
10 | res.writeHead(200);
11 | res.end();
12 | });
13 | };
14 |
--------------------------------------------------------------------------------
/axios-v1.x/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Reporting a Vulnerability
2 |
3 | If you discover a security vulnerability in axios please disclose it via [our huntr page](https://huntr.dev/repos/axios/axios/). Bounty eligibility, CVE assignment, response times and past reports are all there.
4 |
5 |
6 | Thank you for improving the security of axios.
7 |
--------------------------------------------------------------------------------
/axios/lib/helpers/bind.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | module.exports = function bind(fn, thisArg) {
4 | return function wrap() {
5 | var args = new Array(arguments.length);
6 | for (var i = 0; i < args.length; i++) {
7 | args[i] = arguments[i];
8 | }
9 | return fn.apply(thisArg, args);
10 | };
11 | };
12 |
--------------------------------------------------------------------------------
/axios-v1.x/templates/prs.hbs:
--------------------------------------------------------------------------------
1 | {{#if prs}}
2 | ### PRs
3 | {{#each prs}}
4 | - {{title}} ( [#{{number}}]({{pull_request.url}}) ){{#if isHot}} 🔥{{/if}}{{#if isHot}} 🚀{{/if}}
5 | {{#if messages}}
6 | {{#each messages}}
7 | ```
8 | {{this}}
9 | ```
10 | {{/each}}
11 | {{/if}}
12 | {{/each}}
13 | {{/if}}
14 |
--------------------------------------------------------------------------------
/axios-v1.x/.eslintrc.cjs:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | "env": {
3 | "browser": true,
4 | "es2018": true,
5 | "node": true
6 | },
7 | "extends": "eslint:recommended",
8 | "parserOptions": {
9 | "ecmaVersion": 2018,
10 | "sourceType": "module"
11 | },
12 | "rules": {
13 | "no-cond-assign": 0
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/postMultipartFormData/server.js:
--------------------------------------------------------------------------------
1 | export default function (req, res) {
2 |
3 | req.on('data', function (chunk) {
4 | });
5 |
6 | req.on('end', function () {
7 | console.log('POST received');
8 | res.writeHead(200, {
9 | 'Content-Type': 'text/json'
10 | });
11 | res.end();
12 | });
13 | };
14 |
--------------------------------------------------------------------------------
/axios/test/specs/utils/trim.spec.js:
--------------------------------------------------------------------------------
1 | var trim = require('../../../lib/utils').trim;
2 |
3 | describe('utils::trim', function () {
4 | it('should trim spaces', function () {
5 | expect(trim(' foo ')).toEqual('foo');
6 | });
7 |
8 | it('should trim tabs', function () {
9 | expect(trim('\tfoo\t')).toEqual('foo');
10 | });
11 | });
12 |
13 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/trim.spec.js:
--------------------------------------------------------------------------------
1 | import utils from '../../../lib/utils';
2 |
3 | describe('utils::trim', function () {
4 | it('should trim spaces', function () {
5 | expect(utils.trim(' foo ')).toEqual('foo');
6 | });
7 |
8 | it('should trim tabs', function () {
9 | expect(utils.trim('\tfoo\t')).toEqual('foo');
10 | });
11 | });
12 |
13 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/bind.spec.js:
--------------------------------------------------------------------------------
1 | var bind = require('../../../lib/helpers/bind');
2 |
3 | describe('bind', function () {
4 | it('should bind an object to a function', function () {
5 | var o = { val: 123 };
6 | var f = bind(function (num) {
7 | return this.val * num;
8 | }, o);
9 |
10 | expect(f(2)).toEqual(246);
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/bind.spec.js:
--------------------------------------------------------------------------------
1 | import bind from '../../../lib/helpers/bind';
2 |
3 | describe('bind', function () {
4 | it('should bind an object to a function', function () {
5 | const o = { val: 123 };
6 | const f = bind(function (num) {
7 | return this.val * num;
8 | }, o);
9 |
10 | expect(f(2)).toEqual(246);
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/kindOf.js:
--------------------------------------------------------------------------------
1 | import {kindOfTest} from '../../../lib/utils';
2 |
3 | describe('utils::endsWith', function () {
4 | it('should return true if the string ends with passed substring', function () {
5 | const test = kindOfTest('number');
6 |
7 | expect(test(123)).toEqual(true);
8 | expect(test('123')).toEqual(false);
9 | });
10 | });
11 |
--------------------------------------------------------------------------------
/axios/lib/core/README.md:
--------------------------------------------------------------------------------
1 | # axios // core
2 |
3 | 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:
4 |
5 | - Dispatching requests
6 | - Managing interceptors
7 | - Handling config
8 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/node/index.js:
--------------------------------------------------------------------------------
1 | import URLSearchParams from './classes/URLSearchParams.js'
2 | import FormData from './classes/FormData.js'
3 |
4 | export default {
5 | isNode: true,
6 | classes: {
7 | URLSearchParams,
8 | FormData,
9 | Blob: typeof Blob !== 'undefined' && Blob || null
10 | },
11 | protocols: [ 'http', 'https', 'file', 'data' ]
12 | };
13 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/formdata.spec.js:
--------------------------------------------------------------------------------
1 |
2 | describe('FormData', function() {
3 | it('should allow FormData posting', function () {
4 | return axios.postForm('http://httpbin.org/post', {
5 | a: 'foo',
6 | b: 'bar'
7 | }).then(({data}) => {
8 | expect(data.form).toEqual({
9 | a: 'foo',
10 | b: 'bar'
11 | });
12 | });
13 | });
14 | })
15 |
--------------------------------------------------------------------------------
/axios/lib/helpers/README.md:
--------------------------------------------------------------------------------
1 | # axios // helpers
2 |
3 | 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:
4 |
5 | - Browser polyfills
6 | - Managing cookies
7 | - Parsing HTTP headers
8 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/README.md:
--------------------------------------------------------------------------------
1 | # axios // helpers
2 |
3 | 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:
4 |
5 | - Browser polyfills
6 | - Managing cookies
7 | - Parsing HTTP headers
8 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/browser/index.js:
--------------------------------------------------------------------------------
1 | import URLSearchParams from './classes/URLSearchParams.js'
2 | import FormData from './classes/FormData.js'
3 | import Blob from './classes/Blob.js'
4 |
5 | export default {
6 | isBrowser: true,
7 | classes: {
8 | URLSearchParams,
9 | FormData,
10 | Blob
11 | },
12 | protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
13 | };
14 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/cjs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cjs-entrypoint-test",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "npm i --no-save --no-package-lock && node index.js"
8 | },
9 | "keywords": [],
10 | "author": "",
11 | "license": "MIT",
12 | "dependencies": {
13 | "axios": "file:../../.."
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/endsWith.js:
--------------------------------------------------------------------------------
1 | import utils from '../../../lib/utils';
2 |
3 | const {kindOf} = utils;
4 |
5 | describe('utils::kindOf', function () {
6 | it('should return object tag', function () {
7 | expect(kindOf({})).toEqual('object');
8 | // cached result
9 | expect(kindOf({})).toEqual('object');
10 | expect(kindOf([])).toEqual('array');
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/kindOfTest.js:
--------------------------------------------------------------------------------
1 | import utils from '../../../lib/utils';
2 |
3 | const {kindOf} = utils;
4 |
5 | describe('utils::kindOf', function () {
6 | it('should return object tag', function () {
7 | expect(kindOf({})).toEqual('object');
8 | // cached result
9 | expect(kindOf({})).toEqual('object');
10 | expect(kindOf([])).toEqual('array');
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/readBlob.js:
--------------------------------------------------------------------------------
1 | const {asyncIterator} = Symbol;
2 |
3 | const readBlob = async function* (blob) {
4 | if (blob.stream) {
5 | yield* blob.stream()
6 | } else if (blob.arrayBuffer) {
7 | yield await blob.arrayBuffer()
8 | } else if (blob[asyncIterator]) {
9 | yield* blob[asyncIterator]();
10 | } else {
11 | yield blob;
12 | }
13 | }
14 |
15 | export default readBlob;
16 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/toArray.js:
--------------------------------------------------------------------------------
1 | import utils from '../../../lib/utils';
2 |
3 | const {toArray} = utils;
4 |
5 | describe('utils::kindOf', function () {
6 | it('should return object tag', function () {
7 | expect(toArray()).toEqual(null);
8 | expect(toArray([])).toEqual([]);
9 | expect(toArray([1])).toEqual([1]);
10 | expect(toArray([1, 2, 3])).toEqual([1, 2, 3]);
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios/examples/post/server.js:
--------------------------------------------------------------------------------
1 | module.exports = function (req, res) {
2 | var data = '';
3 |
4 | req.on('data', function (chunk) {
5 | data += chunk;
6 | });
7 |
8 | req.on('end', function () {
9 | console.log('POST data received');
10 | res.writeHead(200, {
11 | 'Content-Type': 'text/json'
12 | });
13 | res.write(JSON.stringify(data));
14 | res.end();
15 | });
16 | };
17 |
--------------------------------------------------------------------------------
/axios-v1.x/bin/helpers/parser.js:
--------------------------------------------------------------------------------
1 | export const matchAll = (text, regexp, cb) => {
2 | let match;
3 | while((match = regexp.exec(text))) {
4 | cb(match);
5 | }
6 | }
7 |
8 | export const parseSection = (body, name, cb) => {
9 | matchAll(body, new RegExp(`^(#+)\\s+${name}?(.*?)^\\1\\s+\\w+`, 'gims'), cb);
10 | }
11 |
12 | export const parseVersion = (rawVersion) => /^v?(\d+).(\d+).(\d+)/.exec(rawVersion);
13 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/post/server.js:
--------------------------------------------------------------------------------
1 | export default function (req, res) {
2 | let data = '';
3 |
4 | req.on('data', function (chunk) {
5 | data += chunk;
6 | });
7 |
8 | req.on('end', function () {
9 | console.log('POST data received');
10 | res.writeHead(200, {
11 | 'Content-Type': 'text/json'
12 | });
13 | res.write(JSON.stringify(data));
14 | res.end();
15 | });
16 | };
17 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/esm/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "esm-entrypoint-test",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "type": "module",
7 | "scripts": {
8 | "test": "npm i --no-save --no-package-lock && node index.js"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "MIT",
13 | "dependencies": {
14 | "axios": "file:../../.."
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/axios/lib/helpers/normalizeHeaderName.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var utils = require('../utils');
4 |
5 | module.exports = function normalizeHeaderName(headers, normalizedName) {
6 | utils.forEach(headers, function processHeader(value, name) {
7 | if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
8 | headers[normalizedName] = value;
9 | delete headers[name];
10 | }
11 | });
12 | };
13 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/core/README.md:
--------------------------------------------------------------------------------
1 | # axios // core
2 |
3 | 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:
4 |
5 | - Dispatching requests
6 | - Requests sent via `adapters/` (see lib/adapters/README.md)
7 | - Managing interceptors
8 | - Handling config
9 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/cjs/index.js:
--------------------------------------------------------------------------------
1 | const axios = require('axios');
2 | const assert = require('assert');
3 |
4 | const {CanceledError, AxiosError, AxiosHeaders} = axios;
5 |
6 | assert.strictEqual(typeof axios, 'function');
7 | assert.strictEqual(typeof CanceledError, 'function');
8 | assert.strictEqual(typeof AxiosError, 'function');
9 | assert.strictEqual(typeof AxiosHeaders, 'function');
10 |
11 | console.log('CommonJS importing test passed');
12 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/workflows/depsreview.yaml:
--------------------------------------------------------------------------------
1 | name: 'Dependency Review'
2 | on: [pull_request]
3 |
4 | permissions:
5 | contents: read
6 |
7 | jobs:
8 | dependency-review:
9 | runs-on: ubuntu-latest
10 | steps:
11 | - name: 'Checkout Repository'
12 | uses: actions/checkout@v3
13 | with:
14 | persist-credentials: false
15 | - name: 'Dependency Review'
16 | uses: actions/dependency-review-action@v3
17 |
--------------------------------------------------------------------------------
/axios/test/specs/cancel/isCancel.spec.js:
--------------------------------------------------------------------------------
1 | var isCancel = require('../../../lib/cancel/isCancel');
2 | var Cancel = require('../../../lib/cancel/Cancel');
3 |
4 | describe('isCancel', function() {
5 | it('returns true if value is a Cancel', function() {
6 | expect(isCancel(new Cancel())).toBe(true);
7 | });
8 |
9 | it('returns false if value is not a Cancel', function() {
10 | expect(isCancel({ foo: 'bar' })).toBe(false);
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios/test/specs/adapter.spec.js:
--------------------------------------------------------------------------------
1 | var axios = require('../../index');
2 |
3 | describe('adapter', function () {
4 | it('should support custom adapter', function (done) {
5 | var called = false;
6 |
7 | axios('/foo', {
8 | adapter: function (config) {
9 | called = true;
10 | }
11 | });
12 |
13 | setTimeout(function () {
14 | expect(called).toBe(true);
15 | done();
16 | }, 100);
17 | });
18 | });
19 |
20 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/isAxiosError.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import utils from './../utils.js';
4 |
5 | /**
6 | * Determines whether the payload is an error thrown by Axios
7 | *
8 | * @param {*} payload The value to test
9 | *
10 | * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
11 | */
12 | export default function isAxiosError(payload) {
13 | return utils.isObject(payload) && (payload.isAxiosError === true);
14 | }
15 |
--------------------------------------------------------------------------------
/axios/lib/helpers/combineURLs.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Creates a new URL by combining the specified URLs
5 | *
6 | * @param {string} baseURL The base URL
7 | * @param {string} relativeURL The relative URL
8 | * @returns {string} The combined URL
9 | */
10 | module.exports = function combineURLs(baseURL, relativeURL) {
11 | return relativeURL
12 | ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
13 | : baseURL;
14 | };
15 |
--------------------------------------------------------------------------------
/axios-v1.x/templates/contributors.hbs:
--------------------------------------------------------------------------------
1 | {{#if authors}}
2 | ### Contributors to this release
3 |
4 | {{#each authors}}
5 | {{#unless isBot}}
6 | {{#if login}}
7 | - {{#if avatar_url}}
{{/if}} [{{displayName}}]({{html_url}} "+{{insertions}}/-{{deletions}} ({{#each prs}}#{{this}} {{/each}})")
8 | {{else}}
9 | - {{displayName}}
10 | {{/if}}
11 | {{/unless}}
12 | {{/each}}
13 | {{/if}}
14 |
--------------------------------------------------------------------------------
/axios-v1.x/bin/helpers/colorize.js:
--------------------------------------------------------------------------------
1 | import chalk from 'chalk';
2 |
3 | export const colorize = (...colors)=> {
4 | if(!colors.length) {
5 | colors = ['green', 'cyan', 'magenta', 'blue', 'yellow', 'red'];
6 | }
7 |
8 | const colorsCount = colors.length;
9 |
10 | return (strings, ...values) => {
11 | const {length} = values;
12 | return strings.map((str, i) => i < length ? str + chalk[colors[i%colorsCount]].bold(values[i]) : str).join('');
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/callbackify.js:
--------------------------------------------------------------------------------
1 | import utils from "../utils.js";
2 |
3 | const callbackify = (fn, reducer) => {
4 | return utils.isAsyncFn(fn) ? function (...args) {
5 | const cb = args.pop();
6 | fn.apply(this, args).then((value) => {
7 | try {
8 | reducer ? cb(null, ...reducer(value)) : cb(null, value);
9 | } catch (err) {
10 | cb(err);
11 | }
12 | }, cb);
13 | } : fn;
14 | }
15 |
16 | export default callbackify;
17 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/isURLSameOrigin.spec.js:
--------------------------------------------------------------------------------
1 | import isURLSameOrigin from '../../../lib/helpers/isURLSameOrigin';
2 |
3 | describe('helpers::isURLSameOrigin', function () {
4 | it('should detect same origin', function () {
5 | expect(isURLSameOrigin(window.location.href)).toEqual(true);
6 | });
7 |
8 | it('should detect different origin', function () {
9 | expect(isURLSameOrigin('https://github.com/axios/axios')).toEqual(false);
10 | });
11 | });
12 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/combineURLs.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Creates a new URL by combining the specified URLs
5 | *
6 | * @param {string} baseURL The base URL
7 | * @param {string} relativeURL The relative URL
8 | *
9 | * @returns {string} The combined URL
10 | */
11 | export default function combineURLs(baseURL, relativeURL) {
12 | return relativeURL
13 | ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
14 | : baseURL;
15 | }
16 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/toFlatObject.js:
--------------------------------------------------------------------------------
1 | import utils from '../../../lib/utils';
2 |
3 | const {toFlatObject} = utils;
4 |
5 | describe('utils::toFlatObject', function () {
6 | it('should resolve object proto chain to a flat object representation', function () {
7 | const a = {x: 1};
8 | const b = Object.create(a, {y: {value: 2}});
9 | const c = Object.create(b, {z: {value: 3}});
10 | expect(toFlatObject(c)).toEqual({x: 1, y: 2, z: 3});
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/cancel/isCancel.spec.js:
--------------------------------------------------------------------------------
1 | import isCancel from '../../../lib/cancel/isCancel';
2 | import CanceledError from '../../../lib/cancel/CanceledError';
3 |
4 | describe('isCancel', function() {
5 | it('returns true if value is a CanceledError', function() {
6 | expect(isCancel(new CanceledError())).toBe(true);
7 | });
8 |
9 | it('returns false if value is not a CanceledError', function() {
10 | expect(isCancel({ foo: 'bar' })).toBe(false);
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/helpers/fromDataURI.js:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import fromDataURI from '../../../lib/helpers/fromDataURI.js';
3 |
4 | describe('helpers::fromDataURI', function () {
5 | it('should return buffer from data uri', function () {
6 | const buffer= Buffer.from('123');
7 |
8 | const dataURI = 'data:application/octet-stream;base64,' + buffer.toString('base64');
9 |
10 | assert.deepStrictEqual(fromDataURI(dataURI, false), buffer);
11 | });
12 | });
13 |
--------------------------------------------------------------------------------
/axios/lib/cancel/Cancel.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * A `Cancel` is an object that is thrown when an operation is canceled.
5 | *
6 | * @class
7 | * @param {string=} message The message.
8 | */
9 | function Cancel(message) {
10 | this.message = message;
11 | }
12 |
13 | Cancel.prototype.toString = function toString() {
14 | return 'Cancel' + (this.message ? ': ' + this.message : '');
15 | };
16 |
17 | Cancel.prototype.__CANCEL__ = true;
18 |
19 | module.exports = Cancel;
20 |
--------------------------------------------------------------------------------
/axios/sandbox/client.js:
--------------------------------------------------------------------------------
1 | var axios = require('../index');
2 |
3 | var URL = 'http://127.0.0.1:3000/api';
4 | var BODY = {
5 | foo: 'bar',
6 | baz: 1234
7 | };
8 |
9 | function handleSuccess(data) { console.log(data); }
10 | function handleFailure(data) { console.log('error', data); }
11 |
12 | // GET
13 | axios.get(URL, { params: BODY })
14 | .then(handleSuccess)
15 | .catch(handleFailure);
16 |
17 | // POST
18 | axios.post(URL, BODY)
19 | .then(handleSuccess)
20 | .catch(handleFailure);
--------------------------------------------------------------------------------
/axios-v1.x/sandbox/client.js:
--------------------------------------------------------------------------------
1 | import axios from '../index';
2 |
3 | const URL = 'http://127.0.0.1:3000/api';
4 | const BODY = {
5 | foo: 'bar',
6 | baz: 1234
7 | };
8 |
9 | function handleSuccess(data) { console.log(data); }
10 | function handleFailure(data) { console.log('error', data); }
11 |
12 | // GET
13 | axios.get(URL, { params: BODY })
14 | .then(handleSuccess)
15 | .catch(handleFailure);
16 |
17 | // POST
18 | axios.post(URL, BODY)
19 | .then(handleSuccess)
20 | .catch(handleFailure);
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ts-entrypoint-test",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "npm i --no-save --no-package-lock && npm run build && node index.js",
8 | "build": "tsc"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "MIT",
13 | "dependencies": {
14 | "@types/node": "^18.11.3",
15 | "axios": "file:../../.."
16 | },
17 | "devDependencies": {
18 | "typescript": "^4.8.4"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts-require/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ts-entrypoint-test",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "npm i --no-save --no-package-lock && npm run build && node index.js",
8 | "build": "tsc"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "MIT",
13 | "dependencies": {
14 | "@types/node": "^18.11.3",
15 | "axios": "file:../../.."
16 | },
17 | "devDependencies": {
18 | "typescript": "^4.8.4"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts-require-default/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ts-entrypoint-test",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "npm i --no-save --no-package-lock && npm run build && node index.js",
8 | "build": "tsc"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "MIT",
13 | "dependencies": {
14 | "@types/node": "^18.11.3",
15 | "axios": "file:../../.."
16 | },
17 | "devDependencies": {
18 | "typescript": "^4.8.4"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/typings/cjs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "commonjs-typings-test",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "npm i --no-save --no-package-lock && tsc -v && npm run test:types",
8 | "test:types": "tsc --noEmit"
9 | },
10 | "keywords": [],
11 | "author": "",
12 | "license": "MIT",
13 | "dependencies": {
14 | "@types/node": "^18.11.3",
15 | "axios": "file:../../../.."
16 | },
17 | "devDependencies": {
18 | "typescript": "^4.9.4"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/spread.spec.js:
--------------------------------------------------------------------------------
1 | import spread from '../../../lib/helpers/spread';
2 |
3 | describe('helpers::spread', function () {
4 | it('should spread array to arguments', function () {
5 | let value = 0;
6 | spread(function (a, b) {
7 | value = a * b;
8 | })([5, 10]);
9 |
10 | expect(value).toEqual(50);
11 | });
12 |
13 | it('should return callback result', function () {
14 | const value = spread(function (a, b) {
15 | return a * b;
16 | })([5, 10]);
17 |
18 | expect(value).toEqual(50);
19 | });
20 | });
21 |
22 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/spread.spec.js:
--------------------------------------------------------------------------------
1 | var spread = require('../../../lib/helpers/spread');
2 |
3 | describe('helpers::spread', function () {
4 | it('should spread array to arguments', function () {
5 | var value = 0;
6 | spread(function (a, b) {
7 | value = a * b;
8 | })([5, 10]);
9 |
10 | expect(value).toEqual(50);
11 | });
12 |
13 | it('should return callback result', function () {
14 | var value = spread(function (a, b) {
15 | return a * b;
16 | })([5, 10]);
17 |
18 | expect(value).toEqual(50);
19 | });
20 | });
21 |
22 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/typings/esm/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "esm-typings-test",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "type": "module",
7 | "scripts": {
8 | "test:types": "tsc --noEmit",
9 | "test": "npm i --no-save --no-package-lock && tsc -v && npm run test:types"
10 | },
11 | "keywords": [],
12 | "author": "",
13 | "license": "MIT",
14 | "dependencies": {
15 | "@types/node": "^18.11.3",
16 | "axios": "file:../../../.."
17 | },
18 | "devDependencies": {
19 | "typescript": "^4.9.4"
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/axios/.travis.yml:
--------------------------------------------------------------------------------
1 | services:
2 | - xvfb
3 | language: node_js
4 | node_js:
5 | - 10
6 | email:
7 | on_failure: change
8 | on_success: never
9 | after_success:
10 | - npm run coveralls
11 | env:
12 | global:
13 | - secure: LlXIBEaBLgJznkHWfTV6aftkGoBjH2vik4ZQhKq4k5pvoPLD+n5n28+0bjwlzDIHUdHb+n2YXtyM2PGvGzuqwltV+UY1gu0uG2RNR+5CBsp0pOr0FfGXK6YMXn0BYER6tGYIhaG7ElHBEO0SLcQeQV/xN/m3leyawbKEMBUGizU=
14 | - secure: XbXYzVddHJSVdbJRd/YtsdNu6Wlgx3pXvpuBpg9qBc3TytAF4LzhJNI8u1p4D1Gn8wANlxv1GNgEgkecxbzlTPST+mUrd6KlPLa1+Cmffgajr4oQjsh9ILKMe5Haqx8FOVrPK/leB1mi52liNLlkuo3/BK2r/tC2kMji+2zbses=
15 |
--------------------------------------------------------------------------------
/axios/test/manual/cors.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | An alert should be shown with {"status":"ok"}
9 |
10 |
11 |
12 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/axios-v1.x/test/manual/cors.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | An alert should be shown with {"status":"ok"}
9 |
10 |
11 |
12 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/axios-v1.x/test/manual/progress.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | See your console
8 |
9 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/axios/test/specs/cancel/Cancel.spec.js:
--------------------------------------------------------------------------------
1 | var Cancel = require('../../../lib/cancel/Cancel');
2 |
3 | describe('Cancel', function() {
4 | describe('toString', function() {
5 | it('returns correct result when message is not specified', function() {
6 | var cancel = new Cancel();
7 | expect(cancel.toString()).toBe('Cancel');
8 | });
9 |
10 | it('returns correct result when message is specified', function() {
11 | var cancel = new Cancel('Operation has been canceled.');
12 | expect(cancel.toString()).toBe('Cancel: Operation has been canceled.');
13 | });
14 | });
15 | });
16 |
--------------------------------------------------------------------------------
/axios/test/manual/basic.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | An alert should be shown with the {"name":"axios"}
9 |
10 |
11 |
12 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/axios-v1.x/test/manual/basic.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | An alert should be shown with the {"name":"axios"}
9 |
10 |
11 |
12 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/axios/lib/helpers/isAbsoluteURL.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Determines whether the specified URL is absolute
5 | *
6 | * @param {string} url The URL to test
7 | * @returns {boolean} True if the specified URL is absolute, otherwise false
8 | */
9 | module.exports = function isAbsoluteURL(url) {
10 | // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL).
11 | // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
12 | // by any combination of letters, digits, plus, period, or hyphen.
13 | return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
14 | };
15 |
--------------------------------------------------------------------------------
/axios-v1.x/bin/ssl_hotfix.js:
--------------------------------------------------------------------------------
1 | import {spawn} from 'child_process';
2 |
3 | const args = process.argv.slice(2);
4 |
5 | console.log(`Running ${args.join(' ')} on ${process.version}\n`);
6 |
7 | const match = /v(\d+)/.exec(process.version);
8 |
9 | const isHotfixNeeded = match && match[1] > 16;
10 |
11 | isHotfixNeeded && console.warn('Setting --openssl-legacy-provider as ssl hotfix');
12 |
13 | const test = spawn('cross-env',
14 | isHotfixNeeded ? ['NODE_OPTIONS=--openssl-legacy-provider', ...args] : args, {
15 | shell: true,
16 | stdio: 'inherit'
17 | }
18 | );
19 |
20 | test.on('exit', function (code) {
21 | process.exit(code)
22 | })
23 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/isAbsoluteURL.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Determines whether the specified URL is absolute
5 | *
6 | * @param {string} url The URL to test
7 | *
8 | * @returns {boolean} True if the specified URL is absolute, otherwise false
9 | */
10 | export default function isAbsoluteURL(url) {
11 | // A URL is considered absolute if it begins with "://" or "//" (protocol-relative URL).
12 | // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
13 | // by any combination of letters, digits, plus, period, or hyphen.
14 | return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
15 | }
16 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/toURLEncodedForm.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import utils from '../utils.js';
4 | import toFormData from './toFormData.js';
5 | import platform from '../platform/index.js';
6 |
7 | export default function toURLEncodedForm(data, options) {
8 | return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
9 | visitor: function(value, key, path, helpers) {
10 | if (platform.isNode && utils.isBuffer(value)) {
11 | this.append(key, value.toString('base64'));
12 | return false;
13 | }
14 |
15 | return helpers.defaultVisitor.apply(this, arguments);
16 | }
17 | }, options));
18 | }
19 |
--------------------------------------------------------------------------------
/axios/lib/core/transformData.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var utils = require('./../utils');
4 |
5 | /**
6 | * Transform the data for a request or a response
7 | *
8 | * @param {Object|String} data The data to be transformed
9 | * @param {Array} headers The headers for the request or response
10 | * @param {Array|Function} fns A single function or Array of functions
11 | * @returns {*} The resulting transformed data
12 | */
13 | module.exports = function transformData(data, headers, fns) {
14 | /*eslint no-param-reassign:0*/
15 | utils.forEach(fns, function transform(fn) {
16 | data = fn(data, headers);
17 | });
18 |
19 | return data;
20 | };
21 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/cancel/CanceledError.spec.js:
--------------------------------------------------------------------------------
1 | import CanceledError from '../../../lib/cancel/CanceledError';
2 |
3 | describe('Cancel', function() {
4 | describe('toString', function() {
5 | it('returns correct result when message is not specified', function() {
6 | const cancel = new CanceledError();
7 | expect(cancel.toString()).toBe('CanceledError: canceled');
8 | });
9 |
10 | it('returns correct result when message is specified', function() {
11 | const cancel = new CanceledError('Operation has been canceled.');
12 | expect(cancel.toString()).toBe('CanceledError: Operation has been canceled.');
13 | });
14 | });
15 | });
16 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/esm/index.js:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import axios, {CanceledError, AxiosError, AxiosHeaders} from 'axios';
3 | import settle from 'axios/unsafe/core/settle.js';
4 |
5 | assert.strictEqual(typeof axios, 'function');
6 | assert.strictEqual(typeof CanceledError, 'function');
7 | assert.strictEqual(typeof AxiosError, 'function');
8 | assert.strictEqual(typeof AxiosHeaders, 'function');
9 |
10 | assert.strictEqual(axios.CanceledError, CanceledError);
11 | assert.strictEqual(axios.AxiosError, AxiosError);
12 | assert.strictEqual(axios.AxiosHeaders, AxiosHeaders);
13 |
14 | assert.strictEqual(typeof settle, 'function');
15 |
16 | console.log('ESM importing test passed');
17 |
--------------------------------------------------------------------------------
/axios/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | #### Instructions
4 |
5 | Please read and follow the instructions before creating and submitting a pull request:
6 |
7 | - Create an issue explaining the feature. It could save you some effort in case we don't consider it should be included in axios.
8 | - If you're fixing a bug, try to commit the failing test/s and the code fixing it in different commits.
9 | - Ensure you're following our [contributing guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md).
10 |
11 | **⚠️👆 Delete the instructions before submitting the pull request 👆⚠️**
12 |
13 | Describe your pull request here.
14 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | #### Instructions
4 |
5 | Please read and follow the instructions before creating and submitting a pull request:
6 |
7 | - Create an issue explaining the feature. It could save you some effort in case we don't consider it should be included in axios.
8 | - If you're fixing a bug, try to commit the failing test/s and the code fixing it in different commits.
9 | - Ensure you're following our [contributing guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md).
10 |
11 | **⚠️👆 Delete the instructions before submitting the pull request 👆⚠️**
12 |
13 | Describe your pull request here.
14 |
--------------------------------------------------------------------------------
/axios/lib/helpers/spread.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Syntactic sugar for invoking a function and expanding an array for arguments.
5 | *
6 | * Common use case would be to use `Function.prototype.apply`.
7 | *
8 | * ```js
9 | * function f(x, y, z) {}
10 | * var args = [1, 2, 3];
11 | * f.apply(null, args);
12 | * ```
13 | *
14 | * With `spread` this example can be re-written.
15 | *
16 | * ```js
17 | * spread(function(x, y, z) {})([1, 2, 3]);
18 | * ```
19 | *
20 | * @param {Function} callback
21 | * @returns {Function}
22 | */
23 | module.exports = function spread(callback) {
24 | return function wrap(arr) {
25 | return callback.apply(null, arr);
26 | };
27 | };
28 |
--------------------------------------------------------------------------------
/axios-v1.x/webpack.config.js:
--------------------------------------------------------------------------------
1 | var config = {};
2 |
3 | function generateConfig(name) {
4 | var compress = name.indexOf('min') > -1;
5 | var config = {
6 | entry: './index.js',
7 | output: {
8 | path: __dirname + '/dist/',
9 | filename: name + '.js',
10 | sourceMapFilename: name + '.map',
11 | library: 'axios',
12 | libraryTarget: 'umd',
13 | globalObject: 'this'
14 | },
15 | node: false,
16 | devtool: 'source-map',
17 | mode: compress ? 'production' : 'development'
18 | };
19 | return config;
20 | }
21 |
22 | ['axios', 'axios.min'].forEach(function (key) {
23 | config[key] = generateConfig(key);
24 | });
25 |
26 | module.exports = config;
27 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/spread.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Syntactic sugar for invoking a function and expanding an array for arguments.
5 | *
6 | * Common use case would be to use `Function.prototype.apply`.
7 | *
8 | * ```js
9 | * function f(x, y, z) {}
10 | * var args = [1, 2, 3];
11 | * f.apply(null, args);
12 | * ```
13 | *
14 | * With `spread` this example can be re-written.
15 | *
16 | * ```js
17 | * spread(function(x, y, z) {})([1, 2, 3]);
18 | * ```
19 | *
20 | * @param {Function} callback
21 | *
22 | * @returns {Function}
23 | */
24 | export default function spread(callback) {
25 | return function wrap(arr) {
26 | return callback.apply(null, arr);
27 | };
28 | }
29 |
--------------------------------------------------------------------------------
/axios/.github/ISSUE_TEMPLATE/--feature-request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: "✨ Feature Request"
3 | about: Suggest an idea or feature
4 | title: ''
5 | labels: feature
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/axios/lib/core/createError.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var enhanceError = require('./enhanceError');
4 |
5 | /**
6 | * Create an Error with the specified message, config, error code, request and response.
7 | *
8 | * @param {string} message The error message.
9 | * @param {Object} config The config.
10 | * @param {string} [code] The error code (for example, 'ECONNABORTED').
11 | * @param {Object} [request] The request.
12 | * @param {Object} [response] The response.
13 | * @returns {Error} The created error.
14 | */
15 | module.exports = function createError(message, config, code, request, response) {
16 | var error = new Error(message);
17 | return enhanceError(error, config, code, request, response);
18 | };
19 |
--------------------------------------------------------------------------------
/axios-v1.x/bin/githubAxios.js:
--------------------------------------------------------------------------------
1 | import axios from '../index.js';
2 | import {colorize} from "./helpers/colorize.js";
3 |
4 | const {GITHUB_TOKEN} = process.env;
5 |
6 | GITHUB_TOKEN ? console.log(`[GITHUB_TOKEN OK]`) : console.warn(`[GITHUB_TOKEN is not defined]`);
7 |
8 | const defaultTransform = axios.defaults.transformRequest;
9 |
10 | export default axios.create({
11 | transformRequest: [defaultTransform[0], function (data) {
12 | console.log(colorize()`[${this.method.toUpperCase()}] Request [${new URL(axios.getUri(this)).pathname}]`);
13 | return data;
14 | }],
15 | baseURL: 'https://api.github.com/',
16 | headers: {
17 | Authorization: GITHUB_TOKEN ? `token ${GITHUB_TOKEN}` : null
18 | }
19 | });
20 |
--------------------------------------------------------------------------------
/axios-v1.x/bin/actions/notify_published.js:
--------------------------------------------------------------------------------
1 | import minimist from "minimist";
2 | import RepoBot from '../RepoBot.js';
3 | import fs from 'fs/promises';
4 |
5 | const argv = minimist(process.argv.slice(2));
6 | console.log(argv);
7 |
8 | let {tag} = argv;
9 |
10 | (async() => {
11 | if (!tag || tag === true) {
12 | const {version} = JSON.parse((await fs.readFile('./package.json')).toString());
13 |
14 | tag = 'v' + version;
15 | } else if (typeof tag !== 'string') {
16 |
17 | throw new Error('tag must be a string');
18 | }
19 |
20 | const bot = new RepoBot();
21 |
22 | try {
23 | await bot.notifyPublishedPRs(tag);
24 | } catch (err) {
25 | console.warn('Error:', err.message);
26 | }
27 | })();
28 |
29 |
--------------------------------------------------------------------------------
/axios/.github/ISSUE_TEMPLATE/---documentation.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: "\U0001F4DA Documentation"
3 | about: Report an error or area that needs clarification
4 | title: ''
5 | labels: documentation
6 | assignees: ''
7 |
8 | ---
9 |
10 |
16 |
17 | **Section/Content To Improve**
18 | Quote or link to section
19 |
20 | **Suggested Improvement**
21 | Identify what is confusing or incorrect and what could make it better
22 |
23 | **Relevant File(s)**: [e.g. README.md]
24 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/isURLSameOrigin.spec.js:
--------------------------------------------------------------------------------
1 | var isURLSameOrigin = require('../../../lib/helpers/isURLSameOrigin');
2 |
3 | describe('helpers::isURLSameOrigin', function () {
4 | it('should detect same origin', function () {
5 | expect(isURLSameOrigin(window.location.href)).toEqual(true);
6 | });
7 |
8 | it('should detect different origin', function () {
9 | expect(isURLSameOrigin('https://github.com/axios/axios')).toEqual(false);
10 | });
11 |
12 | it('should detect XSS scripts on a same origin request', function () {
13 | expect(function() {
14 | isURLSameOrigin('https://github.com/axios/axios?');
15 | }).toThrowError(Error, 'URL contains XSS injection attempt')
16 | });
17 | });
18 |
--------------------------------------------------------------------------------
/axios/lib/core/buildFullPath.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var isAbsoluteURL = require('../helpers/isAbsoluteURL');
4 | var combineURLs = require('../helpers/combineURLs');
5 |
6 | /**
7 | * Creates a new URL by combining the baseURL with the requestedURL,
8 | * only when the requestedURL is not already an absolute URL.
9 | * If the requestURL is absolute, this function returns the requestedURL untouched.
10 | *
11 | * @param {string} baseURL The base URL
12 | * @param {string} requestedURL Absolute or relative URL to combine
13 | * @returns {string} The combined full path
14 | */
15 | module.exports = function buildFullPath(baseURL, requestedURL) {
16 | if (baseURL && !isAbsoluteURL(requestedURL)) {
17 | return combineURLs(baseURL, requestedURL);
18 | }
19 | return requestedURL;
20 | };
21 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/core/buildFullPath.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
4 | import combineURLs from '../helpers/combineURLs.js';
5 |
6 | /**
7 | * Creates a new URL by combining the baseURL with the requestedURL,
8 | * only when the requestedURL is not already an absolute URL.
9 | * If the requestURL is absolute, this function returns the requestedURL untouched.
10 | *
11 | * @param {string} baseURL The base URL
12 | * @param {string} requestedURL Absolute or relative URL to combine
13 | *
14 | * @returns {string} The combined full path
15 | */
16 | export default function buildFullPath(baseURL, requestedURL) {
17 | if (baseURL && !isAbsoluteURL(requestedURL)) {
18 | return combineURLs(baseURL, requestedURL);
19 | }
20 | return requestedURL;
21 | }
22 |
--------------------------------------------------------------------------------
/axios/lib/core/settle.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var createError = require('./createError');
4 |
5 | /**
6 | * Resolve or reject a Promise based on response status.
7 | *
8 | * @param {Function} resolve A function that resolves the promise.
9 | * @param {Function} reject A function that rejects the promise.
10 | * @param {object} response The response.
11 | */
12 | module.exports = function settle(resolve, reject, response) {
13 | var validateStatus = response.config.validateStatus;
14 | if (!validateStatus || validateStatus(response.status)) {
15 | resolve(response);
16 | } else {
17 | reject(createError(
18 | 'Request failed with status code ' + response.status,
19 | response.config,
20 | null,
21 | response.request,
22 | response
23 | ));
24 | }
25 | };
26 |
--------------------------------------------------------------------------------
/axios-v1.x/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "axios",
3 | "main": "./dist/axios.js",
4 | "version": "1.7.0-beta.0",
5 | "homepage": "https://axios-http.com",
6 | "authors": [
7 | "Matt Zabriskie"
8 | ],
9 | "description": "Promise based HTTP client for the browser and node.js",
10 | "moduleType": [
11 | "amd",
12 | "globals"
13 | ],
14 | "keywords": [
15 | "xhr",
16 | "http",
17 | "ajax",
18 | "promise",
19 | "node"
20 | ],
21 | "license": "MIT",
22 | "ignore": [
23 | "**/.*",
24 | "*.iml",
25 | "examples",
26 | "lib",
27 | "node_modules",
28 | "sandbox",
29 | "test",
30 | "CONTRIBUTING.md",
31 | "COOKBOOK.md",
32 | "Gruntfile.js",
33 | "index.js",
34 | "karma.conf.js",
35 | "package.json",
36 | "webpack.*.js"
37 | ]
38 | }
--------------------------------------------------------------------------------
/axios/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "axios",
3 | "main": "./dist/axios.js",
4 | "version": "0.19.0",
5 | "homepage": "https://github.com/axios/axios",
6 | "authors": [
7 | "Matt Zabriskie"
8 | ],
9 | "description": "Promise based HTTP client for the browser and node.js",
10 | "moduleType": [
11 | "amd",
12 | "globals"
13 | ],
14 | "keywords": [
15 | "xhr",
16 | "http",
17 | "ajax",
18 | "promise",
19 | "node"
20 | ],
21 | "license": "MIT",
22 | "ignore": [
23 | "**/.*",
24 | "*.iml",
25 | "examples",
26 | "lib",
27 | "node_modules",
28 | "sandbox",
29 | "test",
30 | "CONTRIBUTING.md",
31 | "COOKBOOK.md",
32 | "Gruntfile.js",
33 | "index.js",
34 | "karma.conf.js",
35 | "package.json",
36 | "webpack.*.js"
37 | ]
38 | }
--------------------------------------------------------------------------------
/axios/examples/get/server.js:
--------------------------------------------------------------------------------
1 | var people = [
2 | {
3 | "name": "Matt Zabriskie",
4 | "github": "mzabriskie",
5 | "twitter": "mzabriskie",
6 | "avatar": "199035"
7 | },
8 | {
9 | "name": "Ryan Florence",
10 | "github": "rpflorence",
11 | "twitter": "ryanflorence",
12 | "avatar": "100200"
13 | },
14 | {
15 | "name": "Kent C. Dodds",
16 | "github": "kentcdodds",
17 | "twitter": "kentcdodds",
18 | "avatar": "1500684"
19 | },
20 | {
21 | "name": "Chris Esplin",
22 | "github": "deltaepsilon",
23 | "twitter": "chrisesplin",
24 | "avatar": "878947"
25 | }
26 | ];
27 |
28 | module.exports = function (req, res) {
29 | res.writeHead(200, {
30 | 'Content-Type': 'text/json'
31 | });
32 | res.write(JSON.stringify(people));
33 | res.end();
34 | };
35 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/get/server.js:
--------------------------------------------------------------------------------
1 | const people = [
2 | {
3 | "name": "Matt Zabriskie",
4 | "github": "mzabriskie",
5 | "twitter": "mzabriskie",
6 | "avatar": "199035"
7 | },
8 | {
9 | "name": "Ryan Florence",
10 | "github": "rpflorence",
11 | "twitter": "ryanflorence",
12 | "avatar": "100200"
13 | },
14 | {
15 | "name": "Kent C. Dodds",
16 | "github": "kentcdodds",
17 | "twitter": "kentcdodds",
18 | "avatar": "1500684"
19 | },
20 | {
21 | "name": "Chris Esplin",
22 | "github": "deltaepsilon",
23 | "twitter": "chrisesplin",
24 | "avatar": "878947"
25 | }
26 | ];
27 |
28 | export default function (req, res) {
29 | res.writeHead(200, {
30 | 'Content-Type': 'text/json'
31 | });
32 | res.write(JSON.stringify(people));
33 | res.end();
34 | };
35 |
--------------------------------------------------------------------------------
/axios/examples/cancel/server.js:
--------------------------------------------------------------------------------
1 | var people = [
2 | {
3 | "name": "Matt Zabriskie",
4 | "github": "mzabriskie",
5 | "twitter": "mzabriskie",
6 | "avatar": "199035"
7 | },
8 | {
9 | "name": "Ryan Florence",
10 | "github": "rpflorence",
11 | "twitter": "ryanflorence",
12 | "avatar": "100200"
13 | },
14 | {
15 | "name": "Kent C. Dodds",
16 | "github": "kentcdodds",
17 | "twitter": "kentcdodds",
18 | "avatar": "1500684"
19 | },
20 | {
21 | "name": "Chris Esplin",
22 | "github": "deltaepsilon",
23 | "twitter": "chrisesplin",
24 | "avatar": "878947"
25 | }
26 | ];
27 |
28 | module.exports = function (req, res) {
29 | res.writeHead(200, {
30 | 'Content-Type': 'text/json'
31 | });
32 | res.write(JSON.stringify(people));
33 | res.end();
34 | };
35 |
--------------------------------------------------------------------------------
/axios/examples/interceptors/server.js:
--------------------------------------------------------------------------------
1 | var people = [
2 | {
3 | "name": "Matt Zabriskie",
4 | "github": "mzabriskie",
5 | "twitter": "mzabriskie",
6 | "avatar": "199035"
7 | },
8 | {
9 | "name": "Ryan Florence",
10 | "github": "rpflorence",
11 | "twitter": "ryanflorence",
12 | "avatar": "100200"
13 | },
14 | {
15 | "name": "Kent C. Dodds",
16 | "github": "kentcdodds",
17 | "twitter": "kentcdodds",
18 | "avatar": "1500684"
19 | },
20 | {
21 | "name": "Chris Esplin",
22 | "github": "deltaepsilon",
23 | "twitter": "chrisesplin",
24 | "avatar": "878947"
25 | }
26 | ];
27 |
28 | module.exports = function (req, res) {
29 | res.writeHead(200, {
30 | 'Content-Type': 'text/json'
31 | });
32 | res.write(JSON.stringify(people));
33 | res.end();
34 | };
35 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/cancel/CanceledError.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import AxiosError from '../core/AxiosError.js';
4 | import utils from '../utils.js';
5 |
6 | /**
7 | * A `CanceledError` is an object that is thrown when an operation is canceled.
8 | *
9 | * @param {string=} message The message.
10 | * @param {Object=} config The config.
11 | * @param {Object=} request The request.
12 | *
13 | * @returns {CanceledError} The created error.
14 | */
15 | function CanceledError(message, config, request) {
16 | // eslint-disable-next-line no-eq-null,eqeqeq
17 | AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
18 | this.name = 'CanceledError';
19 | }
20 |
21 | utils.inherits(CanceledError, AxiosError, {
22 | __CANCEL__: true
23 | });
24 |
25 | export default CanceledError;
26 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/ZlibHeaderTransformStream.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | import stream from "stream";
4 |
5 | class ZlibHeaderTransformStream extends stream.Transform {
6 | __transform(chunk, encoding, callback) {
7 | this.push(chunk);
8 | callback();
9 | }
10 |
11 | _transform(chunk, encoding, callback) {
12 | if (chunk.length !== 0) {
13 | this._transform = this.__transform;
14 |
15 | // Add Default Compression headers if no zlib headers are present
16 | if (chunk[0] !== 120) { // Hex: 78
17 | const header = Buffer.alloc(2);
18 | header[0] = 120; // Hex: 78
19 | header[1] = 156; // Hex: 9C
20 | this.push(header, encoding);
21 | }
22 | }
23 |
24 | this.__transform(chunk, encoding, callback);
25 | }
26 | }
27 |
28 | export default ZlibHeaderTransformStream;
29 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/normalizeHeaderName.spec.js:
--------------------------------------------------------------------------------
1 | var normalizeHeaderName = require('../../../lib/helpers/normalizeHeaderName');
2 |
3 | describe('helpers::normalizeHeaderName', function () {
4 | it('should normalize matching header name', function () {
5 | var headers = {
6 | 'conTenT-Type': 'foo/bar',
7 | };
8 | normalizeHeaderName(headers, 'Content-Type');
9 | expect(headers['Content-Type']).toBe('foo/bar');
10 | expect(headers['conTenT-Type']).toBeUndefined();
11 | });
12 |
13 | it('should not change non-matching header name', function () {
14 | var headers = {
15 | 'content-type': 'foo/bar',
16 | };
17 | normalizeHeaderName(headers, 'Content-Length');
18 | expect(headers['content-type']).toBe('foo/bar');
19 | expect(headers['Content-Length']).toBeUndefined();
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/axios/test/specs/core/transformData.spec.js:
--------------------------------------------------------------------------------
1 | var transformData = require('../../../lib/core/transformData');
2 |
3 | describe('core::transformData', function () {
4 | it('should support a single transformer', function () {
5 | var data;
6 | data = transformData(data, null, function (data) {
7 | data = 'foo';
8 | return data;
9 | });
10 |
11 | expect(data).toEqual('foo');
12 | });
13 |
14 | it('should support an array of transformers', function () {
15 | var data = '';
16 | data = transformData(data, null, [function (data) {
17 | data += 'f';
18 | return data;
19 | }, function (data) {
20 | data += 'o';
21 | return data;
22 | }, function (data) {
23 | data += 'o';
24 | return data;
25 | }]);
26 |
27 | expect(data).toEqual('foo');
28 | });
29 | });
30 |
31 |
--------------------------------------------------------------------------------
/axios/lib/helpers/deprecatedMethod.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /*eslint no-console:0*/
4 |
5 | /**
6 | * Supply a warning to the developer that a method they are using
7 | * has been deprecated.
8 | *
9 | * @param {string} method The name of the deprecated method
10 | * @param {string} [instead] The alternate method to use if applicable
11 | * @param {string} [docs] The documentation URL to get further details
12 | */
13 | module.exports = function deprecatedMethod(method, instead, docs) {
14 | try {
15 | console.warn(
16 | 'DEPRECATED method `' + method + '`.' +
17 | (instead ? ' Use `' + instead + '` instead.' : '') +
18 | ' This method will be removed in a future release.');
19 |
20 | if (docs) {
21 | console.warn('For more information about usage see ' + docs);
22 | }
23 | } catch (e) { /* Ignore */ }
24 | };
25 |
--------------------------------------------------------------------------------
/axios-v1.x/index.js:
--------------------------------------------------------------------------------
1 | import axios from './lib/axios.js';
2 |
3 | // This module is intended to unwrap Axios default export as named.
4 | // Keep top-level export same with static properties
5 | // so that it can keep same with es module or cjs
6 | const {
7 | Axios,
8 | AxiosError,
9 | CanceledError,
10 | isCancel,
11 | CancelToken,
12 | VERSION,
13 | all,
14 | Cancel,
15 | isAxiosError,
16 | spread,
17 | toFormData,
18 | AxiosHeaders,
19 | HttpStatusCode,
20 | formToJSON,
21 | getAdapter,
22 | mergeConfig
23 | } = axios;
24 |
25 | export {
26 | axios as default,
27 | Axios,
28 | AxiosError,
29 | CanceledError,
30 | isCancel,
31 | CancelToken,
32 | VERSION,
33 | all,
34 | Cancel,
35 | isAxiosError,
36 | spread,
37 | toFormData,
38 | AxiosHeaders,
39 | HttpStatusCode,
40 | formToJSON,
41 | getAdapter,
42 | mergeConfig
43 | }
44 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/deprecatedMethod.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /*eslint no-console:0*/
4 |
5 | /**
6 | * Supply a warning to the developer that a method they are using
7 | * has been deprecated.
8 | *
9 | * @param {string} method The name of the deprecated method
10 | * @param {string} [instead] The alternate method to use if applicable
11 | * @param {string} [docs] The documentation URL to get further details
12 | *
13 | * @returns {void}
14 | */
15 | export default function deprecatedMethod(method, instead, docs) {
16 | try {
17 | console.warn(
18 | 'DEPRECATED method `' + method + '`.' +
19 | (instead ? ' Use `' + instead + '` instead.' : '') +
20 | ' This method will be removed in a future release.');
21 |
22 | if (docs) {
23 | console.warn('For more information about usage see ' + docs);
24 | }
25 | } catch (e) { /* Ignore */ }
26 | }
27 |
--------------------------------------------------------------------------------
/axios/test/specs/core/enhanceError.spec.js:
--------------------------------------------------------------------------------
1 | var enhanceError = require('../../../lib/core/enhanceError');
2 |
3 | describe('core::enhanceError', function() {
4 | it('should add config, config, request and response to error', function() {
5 | var error = new Error('Boom!');
6 | var request = { path: '/foo' };
7 | var response = { status: 200, data: { foo: 'bar' } };
8 |
9 | enhanceError(error, { foo: 'bar' }, 'ESOMETHING', request, response);
10 | expect(error.config).toEqual({ foo: 'bar' });
11 | expect(error.code).toBe('ESOMETHING');
12 | expect(error.request).toBe(request);
13 | expect(error.response).toBe(response);
14 | expect(error.isAxiosError).toBe(true);
15 | });
16 |
17 | it('should return error', function() {
18 | var error = new Error('Boom!');
19 | expect(enhanceError(error, { foo: 'bar' }, 'ESOMETHING')).toBe(error);
20 | });
21 | });
22 |
--------------------------------------------------------------------------------
/axios/test/specs/utils/extend.spec.js:
--------------------------------------------------------------------------------
1 | var extend = require('../../../lib/utils').extend;
2 |
3 | describe('utils::extend', function () {
4 | it('should be mutable', function () {
5 | var a = {};
6 | var b = {foo: 123};
7 |
8 | extend(a, b);
9 |
10 | expect(a.foo).toEqual(b.foo);
11 | });
12 |
13 | it('should extend properties', function () {
14 | var a = {foo: 123, bar: 456};
15 | var b = {bar: 789};
16 |
17 | a = extend(a, b);
18 |
19 | expect(a.foo).toEqual(123);
20 | expect(a.bar).toEqual(789);
21 | });
22 |
23 | it('should bind to thisArg', function () {
24 | var a = {};
25 | var b = {getFoo: function getFoo() { return this.foo; }};
26 | var thisArg = { foo: 'barbaz' };
27 |
28 | extend(a, b, thisArg);
29 |
30 | expect(typeof a.getFoo).toEqual('function');
31 | expect(a.getFoo()).toEqual(thisArg.foo);
32 | });
33 | });
34 |
35 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/throttle.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Throttle decorator
5 | * @param {Function} fn
6 | * @param {Number} freq
7 | * @return {Function}
8 | */
9 | function throttle(fn, freq) {
10 | let timestamp = 0;
11 | const threshold = 1000 / freq;
12 | let timer = null;
13 | return function throttled() {
14 | const force = this === true;
15 |
16 | const now = Date.now();
17 | if (force || now - timestamp > threshold) {
18 | if (timer) {
19 | clearTimeout(timer);
20 | timer = null;
21 | }
22 | timestamp = now;
23 | return fn.apply(null, arguments);
24 | }
25 | if (!timer) {
26 | timer = setTimeout(() => {
27 | timer = null;
28 | timestamp = Date.now();
29 | return fn.apply(null, arguments);
30 | }, threshold - (now - timestamp));
31 | }
32 | };
33 | }
34 |
35 | export default throttle;
36 |
--------------------------------------------------------------------------------
/axios-v1.x/bin/check-build-version.js:
--------------------------------------------------------------------------------
1 | import fs from 'fs';
2 | import assert from 'assert';
3 | import axios from '../index.js';
4 | import axiosBuild from '../dist/node/axios.cjs';
5 |
6 | const {version} = JSON.parse(fs.readFileSync('./package.json'));
7 |
8 | console.log('Checking versions...\n----------------------------')
9 |
10 | console.log(`Package version: v${version}`);
11 | console.log(`Axios version: v${axios.VERSION}`);
12 | console.log(`Axios build version: v${axiosBuild.VERSION}`);
13 | console.log(`----------------------------`);
14 |
15 | assert.strictEqual(
16 | version,
17 | axios.VERSION,
18 | `Version mismatch between package and Axios ${version} != ${axios.VERSION}`
19 | );
20 |
21 | assert.strictEqual(
22 | version,
23 | axiosBuild.VERSION,
24 | `Version mismatch between package and build ${version} != ${axiosBuild.VERSION}`
25 | );
26 |
27 | console.log('✔️ PASSED\n');
28 |
29 |
30 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/core/transformData.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import utils from './../utils.js';
4 | import defaults from '../defaults/index.js';
5 | import AxiosHeaders from '../core/AxiosHeaders.js';
6 |
7 | /**
8 | * Transform the data for a request or a response
9 | *
10 | * @param {Array|Function} fns A single function or Array of functions
11 | * @param {?Object} response The response object
12 | *
13 | * @returns {*} The resulting transformed data
14 | */
15 | export default function transformData(fns, response) {
16 | const config = this || defaults;
17 | const context = response || config;
18 | const headers = AxiosHeaders.from(context.headers);
19 | let data = context.data;
20 |
21 | utils.forEach(fns, function transform(fn) {
22 | data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
23 | });
24 |
25 | headers.normalize();
26 |
27 | return data;
28 | }
29 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/core/buildFullPath.spec.js:
--------------------------------------------------------------------------------
1 | import buildFullPath from '../../../lib/core/buildFullPath';
2 |
3 | describe('helpers::buildFullPath', function () {
4 | it('should combine URLs when the requestedURL is relative', function () {
5 | expect(buildFullPath('https://api.github.com', '/users')).toBe('https://api.github.com/users');
6 | });
7 |
8 | it('should return the requestedURL when it is absolute', function () {
9 | expect(buildFullPath('https://api.github.com', 'https://api.example.com/users')).toBe('https://api.example.com/users');
10 | });
11 |
12 | it('should not combine URLs when the baseURL is not configured', function () {
13 | expect(buildFullPath(undefined, '/users')).toBe('/users');
14 | });
15 |
16 | it('should combine URLs when the baseURL and requestedURL are relative', function () {
17 | expect(buildFullPath('/api', '/users')).toBe('/api/users');
18 | });
19 |
20 | });
21 |
--------------------------------------------------------------------------------
/axios/test/specs/core/buildFullPath.spec.js:
--------------------------------------------------------------------------------
1 | var buildFullPath = require('../../../lib/core/buildFullPath');
2 |
3 | describe('helpers::buildFullPath', function () {
4 | it('should combine URLs when the requestedURL is relative', function () {
5 | expect(buildFullPath('https://api.github.com', '/users')).toBe('https://api.github.com/users');
6 | });
7 |
8 | it('should return the requestedURL when it is absolute', function () {
9 | expect(buildFullPath('https://api.github.com', 'https://api.example.com/users')).toBe('https://api.example.com/users');
10 | });
11 |
12 | it('should not combine URLs when the baseURL is not configured', function () {
13 | expect(buildFullPath(undefined, '/users')).toBe('/users');
14 | });
15 |
16 | it('should combine URLs when the baseURL and requestedURL are relative', function () {
17 | expect(buildFullPath('/api', '/users')).toBe('/api/users');
18 | });
19 |
20 | });
21 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/extend.spec.js:
--------------------------------------------------------------------------------
1 | import utils from '../../../lib/utils';
2 |
3 | const {extend} = utils;
4 |
5 | describe('utils::extend', function () {
6 | it('should be mutable', function () {
7 | const a = {};
8 | const b = {foo: 123};
9 |
10 | extend(a, b);
11 |
12 | expect(a.foo).toEqual(b.foo);
13 | });
14 |
15 | it('should extend properties', function () {
16 | let a = {foo: 123, bar: 456};
17 | const b = {bar: 789};
18 |
19 | a = extend(a, b);
20 |
21 | expect(a.foo).toEqual(123);
22 | expect(a.bar).toEqual(789);
23 | });
24 |
25 | it('should bind to thisArg', function () {
26 | const a = {};
27 | const b = {getFoo: function getFoo() { return this.foo; }};
28 | const thisArg = { foo: 'barbaz' };
29 |
30 | extend(a, b, thisArg);
31 |
32 | expect(typeof a.getFoo).toEqual('function');
33 | expect(a.getFoo()).toEqual(thisArg.foo);
34 | });
35 | });
36 |
37 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/isAxiosError.spec.js:
--------------------------------------------------------------------------------
1 | import AxiosError from '../../../lib/core/AxiosError';
2 | import isAxiosError from '../../../lib/helpers/isAxiosError';
3 |
4 | describe('helpers::isAxiosError', function() {
5 | it('should return true if the error is created by core::createError', function() {
6 | expect(isAxiosError(new AxiosError('Boom!', null, { foo: 'bar' })))
7 | .toBe(true);
8 | });
9 |
10 | it('should return true if the error is enhanced by core::enhanceError', function() {
11 | expect(isAxiosError(AxiosError.from(new Error('Boom!'), null, { foo: 'bar' })))
12 | .toBe(true);
13 | });
14 |
15 | it('should return false if the error is a normal Error instance', function() {
16 | expect(isAxiosError(new Error('Boom!')))
17 | .toBe(false);
18 | });
19 |
20 | it('should return false if the error is null', function () {
21 | expect(isAxiosError(null))
22 | .toBe(false);
23 | });
24 | });
25 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/core/settle.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import AxiosError from './AxiosError.js';
4 |
5 | /**
6 | * Resolve or reject a Promise based on response status.
7 | *
8 | * @param {Function} resolve A function that resolves the promise.
9 | * @param {Function} reject A function that rejects the promise.
10 | * @param {object} response The response.
11 | *
12 | * @returns {object} The response.
13 | */
14 | export default function settle(resolve, reject, response) {
15 | const validateStatus = response.config.validateStatus;
16 | if (!response.status || !validateStatus || validateStatus(response.status)) {
17 | resolve(response);
18 | } else {
19 | reject(new AxiosError(
20 | 'Request failed with status code ' + response.status,
21 | [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
22 | response.config,
23 | response.request,
24 | response
25 | ));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/workflows/npm-tag.yml:
--------------------------------------------------------------------------------
1 | name: NPM Tag
2 | on:
3 | workflow_dispatch:
4 | inputs:
5 | version:
6 | required: true
7 | tag:
8 | required: true
9 | default: "latest"
10 | jobs:
11 | publish:
12 | runs-on: ubuntu-latest
13 | permissions:
14 | contents: write
15 | id-token: write
16 | steps:
17 | - uses: actions/checkout@v3
18 | - name: git config
19 | run: |
20 | git config user.name "${GITHUB_ACTOR}"
21 | git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
22 | - uses: actions/setup-node@v3
23 | with:
24 | node-version: 18
25 | registry-url: https://registry.npmjs.org/
26 | ############# TAG RELEASE ##############
27 | - name: Tag release
28 | run: npm dist-tag add axios@${{ github.event.inputs.version }} ${{ github.event.inputs.tag }}
29 | env:
30 | NODE_AUTH_TOKEN: ${{secrets.npm_token}}
31 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | name: 'CodeQL'
2 |
3 | on:
4 | push:
5 | branches: '**'
6 | pull_request:
7 | branches: '**'
8 | schedule:
9 | - cron: '21 23 * * 5'
10 |
11 | jobs:
12 | analyze:
13 | name: Analyze
14 | runs-on: ubuntu-latest
15 | permissions:
16 | actions: read
17 | contents: read
18 | security-events: write
19 |
20 | strategy:
21 | fail-fast: false
22 | matrix:
23 | language: [ 'javascript' ]
24 |
25 | steps:
26 | - name: Checkout repository
27 | uses: actions/checkout@v3
28 | with:
29 | persist-credentials: false
30 |
31 | # Initializes the CodeQL tools for scanning.
32 | - name: Initialize CodeQL
33 | uses: github/codeql-action/init@v2
34 | with:
35 | languages: ${{ matrix.language }}
36 | queries: security-extended,security-and-quality
37 |
38 | - name: Perform CodeQL Analysis
39 | uses: github/codeql-action/analyze@v2
40 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/helpers/parseProtocol.js:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import utils from '../../../lib/utils.js';
3 | import parseProtocol from '../../../lib/helpers/parseProtocol.js';
4 |
5 | describe('helpers::parseProtocol', function () {
6 | it('should parse protocol part if it exists', function () {
7 | utils.forEach({
8 | 'http://username:password@example.com/': 'http',
9 | 'ftp:google.com': 'ftp',
10 | 'sms:+15105550101?body=hello%20there': 'sms',
11 | 'tel:0123456789' : 'tel',
12 | '//google.com': '',
13 | 'google.com': '',
14 | 'admin://etc/default/grub' : 'admin',
15 | 'stratum+tcp://server:port': 'stratum+tcp',
16 | '/api/resource:customVerb': '',
17 | 'https://stackoverflow.com/questions/': 'https',
18 | 'mailto:jsmith@example.com' : 'mailto',
19 | 'chrome-extension://1234/.html' : 'chrome-extension'
20 | }, (expectedProtocol, url) => {
21 | assert.strictEqual(parseProtocol(url), expectedProtocol);
22 | });
23 | });
24 | });
25 |
--------------------------------------------------------------------------------
/axios/webpack.config.js:
--------------------------------------------------------------------------------
1 | var webpack = require('webpack');
2 | var config = {};
3 |
4 | function generateConfig(name) {
5 | var uglify = name.indexOf('min') > -1;
6 | var config = {
7 | entry: './index.js',
8 | output: {
9 | path: 'dist/',
10 | filename: name + '.js',
11 | sourceMapFilename: name + '.map',
12 | library: 'axios',
13 | libraryTarget: 'umd'
14 | },
15 | node: {
16 | process: false
17 | },
18 | devtool: 'source-map'
19 | };
20 |
21 | config.plugins = [
22 | new webpack.DefinePlugin({
23 | 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
24 | })
25 | ];
26 |
27 | if (uglify) {
28 | config.plugins.push(
29 | new webpack.optimize.UglifyJsPlugin({
30 | compressor: {
31 | warnings: false
32 | }
33 | })
34 | );
35 | }
36 |
37 | return config;
38 | }
39 |
40 | ['axios', 'axios.min'].forEach(function (key) {
41 | config[key] = generateConfig(key);
42 | });
43 |
44 | module.exports = config;
45 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/isAbsoluteURL.spec.js:
--------------------------------------------------------------------------------
1 | import isAbsoluteURL from '../../../lib/helpers/isAbsoluteURL';
2 |
3 | describe('helpers::isAbsoluteURL', function () {
4 | it('should return true if URL begins with valid scheme name', function () {
5 | expect(isAbsoluteURL('https://api.github.com/users')).toBe(true);
6 | expect(isAbsoluteURL('custom-scheme-v1.0://example.com/')).toBe(true);
7 | expect(isAbsoluteURL('HTTP://example.com/')).toBe(true);
8 | });
9 |
10 | it('should return false if URL begins with invalid scheme name', function () {
11 | expect(isAbsoluteURL('123://example.com/')).toBe(false);
12 | expect(isAbsoluteURL('!valid://example.com/')).toBe(false);
13 | });
14 |
15 | it('should return true if URL is protocol-relative', function () {
16 | expect(isAbsoluteURL('//example.com/')).toBe(true);
17 | });
18 |
19 | it('should return false if URL is relative', function () {
20 | expect(isAbsoluteURL('/foo')).toBe(false);
21 | expect(isAbsoluteURL('foo')).toBe(false);
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/isAbsoluteURL.spec.js:
--------------------------------------------------------------------------------
1 | var isAbsoluteURL = require('../../../lib/helpers/isAbsoluteURL');
2 |
3 | describe('helpers::isAbsoluteURL', function () {
4 | it('should return true if URL begins with valid scheme name', function () {
5 | expect(isAbsoluteURL('https://api.github.com/users')).toBe(true);
6 | expect(isAbsoluteURL('custom-scheme-v1.0://example.com/')).toBe(true);
7 | expect(isAbsoluteURL('HTTP://example.com/')).toBe(true);
8 | });
9 |
10 | it('should return false if URL begins with invalid scheme name', function () {
11 | expect(isAbsoluteURL('123://example.com/')).toBe(false);
12 | expect(isAbsoluteURL('!valid://example.com/')).toBe(false);
13 | });
14 |
15 | it('should return true if URL is protocol-relative', function () {
16 | expect(isAbsoluteURL('//example.com/')).toBe(true);
17 | });
18 |
19 | it('should return false if URL is relative', function () {
20 | expect(isAbsoluteURL('/foo')).toBe(false);
21 | expect(isAbsoluteURL('foo')).toBe(false);
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/combineURLs.spec.js:
--------------------------------------------------------------------------------
1 | var combineURLs = require('../../../lib/helpers/combineURLs');
2 |
3 | describe('helpers::combineURLs', function () {
4 | it('should combine URLs', function () {
5 | expect(combineURLs('https://api.github.com', '/users')).toBe('https://api.github.com/users');
6 | });
7 |
8 | it('should remove duplicate slashes', function () {
9 | expect(combineURLs('https://api.github.com/', '/users')).toBe('https://api.github.com/users');
10 | });
11 |
12 | it('should insert missing slash', function () {
13 | expect(combineURLs('https://api.github.com', 'users')).toBe('https://api.github.com/users');
14 | });
15 |
16 | it('should not insert slash when relative url missing/empty', function () {
17 | expect(combineURLs('https://api.github.com/users', '')).toBe('https://api.github.com/users');
18 | });
19 |
20 | it('should allow a single slash for relative url', function () {
21 | expect(combineURLs('https://api.github.com/users', '/')).toBe('https://api.github.com/users/');
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/combineURLs.spec.js:
--------------------------------------------------------------------------------
1 | import combineURLs from '../../../lib/helpers/combineURLs';
2 |
3 | describe('helpers::combineURLs', function () {
4 | it('should combine URLs', function () {
5 | expect(combineURLs('https://api.github.com', '/users')).toBe('https://api.github.com/users');
6 | });
7 |
8 | it('should remove duplicate slashes', function () {
9 | expect(combineURLs('https://api.github.com/', '/users')).toBe('https://api.github.com/users');
10 | });
11 |
12 | it('should insert missing slash', function () {
13 | expect(combineURLs('https://api.github.com', 'users')).toBe('https://api.github.com/users');
14 | });
15 |
16 | it('should not insert slash when relative url missing/empty', function () {
17 | expect(combineURLs('https://api.github.com/users', '')).toBe('https://api.github.com/users');
18 | });
19 |
20 | it('should allow a single slash for relative url', function () {
21 | expect(combineURLs('https://api.github.com/users', '/')).toBe('https://api.github.com/users/');
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/progressEventReducer.js:
--------------------------------------------------------------------------------
1 | import speedometer from "./speedometer.js";
2 | import throttle from "./throttle.js";
3 |
4 | export default (listener, isDownloadStream, freq = 3) => {
5 | let bytesNotified = 0;
6 | const _speedometer = speedometer(50, 250);
7 |
8 | return throttle(e => {
9 | const loaded = e.loaded;
10 | const total = e.lengthComputable ? e.total : undefined;
11 | const progressBytes = loaded - bytesNotified;
12 | const rate = _speedometer(progressBytes);
13 | const inRange = loaded <= total;
14 |
15 | bytesNotified = loaded;
16 |
17 | const data = {
18 | loaded,
19 | total,
20 | progress: total ? (loaded / total) : undefined,
21 | bytes: progressBytes,
22 | rate: rate ? rate : undefined,
23 | estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
24 | event: e,
25 | lengthComputable: total != null
26 | };
27 |
28 | data[isDownloadStream ? 'download' : 'upload'] = true;
29 |
30 | listener(data);
31 | }, freq);
32 | }
33 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/adapters/cert.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIICpDCCAYwCCQDbqELLwgbPdDANBgkqhkiG9w0BAQUFADAUMRIwEAYDVQQDDAls
3 | b2NhbGhvc3QwHhcNMjAwNjI2MjIxMTQ3WhcNNDcxMTExMjIxMTQ3WjAUMRIwEAYD
4 | VQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQD6
5 | Ogt99/dZ0UgbCuVV1RZ9n28Ov3DzrJCkjperQoXomIq3Fr4RUI1a2rwe3mtl3UzE
6 | 1IVZVvWPGdEsEQHwXfAsP/jFGTwI3HDyOhcqzFQSKsjvqJWYkOOb+2r3SBrFlRZW
7 | 09k/3lC+hx2XtuuG68u4Xgn3AlUvm2vplgCN7eiYcGeNwVuf2eHdOqTRTqiYCZLi
8 | T8GtdYMDXOrwsGZs/jUKd9U0ar/lqwMhmw07yzlVDM2MWM2tyq/asQ7Sf7vuoMFu
9 | oAtDJ3E+bK1k/7SNhdyP4RonhyUCkWG+mzoKDS1qgXroTiQSDUksAvOCTcj8BNIT
10 | ee+Lcn9FaTKNJiKiU9q/AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBAFi5ZpaUj+mU
11 | dsgOka+j2/njgNXux3cOjhm7z/N7LeTuDENAOrYa5b+j5JX/YM7RKHrkbXHsQbfs
12 | GB3ufH6QhSiCd/AdsXp/TbCE/8gdq8ykkjwVP1bvBle9oPH7x1aO/WP/odsepYUv
13 | o9aOZW4iNQVmwamU62ezglf3QD7HPeE4LnZueaFtuzRoC+aWT9v0MIeUPJLe3WDQ
14 | FEySwUuthMDJEv92/TeK0YOiunmseCu2mvdiDj6E3C9xa5q2DWgl+msu7+bPgvYO
15 | GuWaoNeQQGk7ebBO3Hk3IyaGx6Cbd8ty+YaZW7dUT+m7KCs1VkxdcDMjZJVWiJy4
16 | 4HcEcKboG4Y=
17 | -----END CERTIFICATE-----
18 |
--------------------------------------------------------------------------------
/axios-v1.x/LICENSE:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2014-present Matt Zabriskie & Collaborators
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 |
5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6 |
7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8 |
--------------------------------------------------------------------------------
/axios/lib/adapters/README.md:
--------------------------------------------------------------------------------
1 | # axios // adapters
2 |
3 | The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
4 |
5 | ## Example
6 |
7 | ```js
8 | var settle = require('./../core/settle');
9 |
10 | module.exports = function myAdapter(config) {
11 | // At this point:
12 | // - config has been merged with defaults
13 | // - request transformers have already run
14 | // - request interceptors have already run
15 |
16 | // Make the request using config provided
17 | // Upon response settle the Promise
18 |
19 | return new Promise(function(resolve, reject) {
20 |
21 | var response = {
22 | data: responseData,
23 | status: request.status,
24 | statusText: request.statusText,
25 | headers: responseHeaders,
26 | config: config,
27 | request: request
28 | };
29 |
30 | settle(resolve, reject, response);
31 |
32 | // From here:
33 | // - response transformers will run
34 | // - response interceptors will run
35 | });
36 | }
37 | ```
38 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/adapters/README.md:
--------------------------------------------------------------------------------
1 | # axios // adapters
2 |
3 | The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
4 |
5 | ## Example
6 |
7 | ```js
8 | var settle = require('./../core/settle');
9 |
10 | module.exports = function myAdapter(config) {
11 | // At this point:
12 | // - config has been merged with defaults
13 | // - request transformers have already run
14 | // - request interceptors have already run
15 |
16 | // Make the request using config provided
17 | // Upon response settle the Promise
18 |
19 | return new Promise(function(resolve, reject) {
20 |
21 | var response = {
22 | data: responseData,
23 | status: request.status,
24 | statusText: request.statusText,
25 | headers: responseHeaders,
26 | config: config,
27 | request: request
28 | };
29 |
30 | settle(resolve, reject, response);
31 |
32 | // From here:
33 | // - response transformers will run
34 | // - response interceptors will run
35 | });
36 | }
37 | ```
38 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/ISSUE_TEMPLATE/DOCUMENTATION.yml:
--------------------------------------------------------------------------------
1 | name: '📝 Documentation'
2 | description: Report an error or area that needs clarification.
3 | labels: ['documentation']
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: 'If you found an area that needs clarification, feel free to open a PR or list the section/content that could be improved below'
8 | - type: markdown
9 | attributes:
10 | value: '⚠️👆 Feel free to these instructions before submitting the issue 👆⚠️'
11 | - type: textarea
12 | id: content
13 | attributes:
14 | label: 'Section/Content To Improve'
15 | description: Quote or link to section
16 | validations:
17 | required: true
18 | - type: textarea
19 | id: solution
20 | attributes:
21 | label: 'Suggested Improvement'
22 | description: Identify what is confusing or incorrect and what could make it better
23 | validations:
24 | required: true
25 | - type: textarea
26 | id: files
27 | attributes:
28 | label: 'Relevant File(s)'
29 | placeholder: e.g. README.md
30 | render: bash
31 |
--------------------------------------------------------------------------------
/axios/test/specs/utils/merge.spec.js:
--------------------------------------------------------------------------------
1 | var merge = require('../../../lib/utils').merge;
2 |
3 | describe('utils::merge', function () {
4 | it('should be immutable', function () {
5 | var a = {};
6 | var b = {foo: 123};
7 | var c = {bar: 456};
8 |
9 | merge(a, b, c);
10 |
11 | expect(typeof a.foo).toEqual('undefined');
12 | expect(typeof a.bar).toEqual('undefined');
13 | expect(typeof b.bar).toEqual('undefined');
14 | expect(typeof c.foo).toEqual('undefined');
15 | });
16 |
17 | it('should merge properties', function () {
18 | var a = {foo: 123};
19 | var b = {bar: 456};
20 | var c = {foo: 789};
21 | var d = merge(a, b, c);
22 |
23 | expect(d.foo).toEqual(789);
24 | expect(d.bar).toEqual(456);
25 | });
26 |
27 | it('should merge recursively', function () {
28 | var a = {foo: {bar: 123}};
29 | var b = {foo: {baz: 456}, bar: {qux: 789}};
30 |
31 | expect(merge(a, b)).toEqual({
32 | foo: {
33 | bar: 123,
34 | baz: 456
35 | },
36 | bar: {
37 | qux: 789
38 | }
39 | });
40 | });
41 | });
42 |
43 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // 使用 IntelliSense 了解相关属性。
3 | // 悬停以查看现有属性的描述。
4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "type": "node",
9 | "request": "launch",
10 | "name": "Launch Program",
11 | "program": "${workspaceFolder}/axios/sandbox/client.js",
12 | "skipFiles": [
13 | "/**"
14 | ]
15 | },
16 | {
17 | "type": "node",
18 | "request": "launch",
19 | "name": "Launch Program",
20 | "program": "${workspaceFolder}/axios/sandbox/server.js",
21 | "skipFiles": [
22 | "/**"
23 | ]
24 | },
25 | {
26 | "type": "node",
27 | "request": "launch",
28 | "name": "Launch Program",
29 | "program": "${workspaceFolder}/axios/index",
30 | "skipFiles": [
31 | "/**"
32 | ]
33 | },
34 | ]
35 | }
--------------------------------------------------------------------------------
/axios/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2014-present Matt Zabriskie
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
20 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/amd/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | AMD
5 |
6 |
7 |
8 | AMD
9 |
10 |
11 |
User
12 |
13 |
![]()
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/axios/examples/amd/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | AMD
5 |
6 |
7 |
8 | AMD
9 |
10 |
11 |
User
12 |
13 |
![]()
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/__helpers.js:
--------------------------------------------------------------------------------
1 | import _axios from '../../index.js';
2 |
3 | window.axios = _axios;
4 |
5 | // Jasmine config
6 | jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
7 | jasmine.getEnv().defaultTimeoutInterval = 60000;
8 |
9 | // Get Ajax request using an increasing timeout to retry
10 | window.getAjaxRequest = (function () {
11 | let attempts = 0;
12 | const MAX_ATTEMPTS = 5;
13 | const ATTEMPT_DELAY_FACTOR = 5;
14 |
15 | function getAjaxRequest() {
16 | return new Promise(function (resolve, reject) {
17 | attempts = 0;
18 | attemptGettingAjaxRequest(resolve, reject);
19 | });
20 | }
21 |
22 | function attemptGettingAjaxRequest(resolve, reject) {
23 | const delay = attempts * attempts * ATTEMPT_DELAY_FACTOR;
24 |
25 | if (attempts++ > MAX_ATTEMPTS) {
26 | reject(new Error('No request was found'));
27 | return;
28 | }
29 |
30 | setTimeout(function () {
31 | const request = jasmine.Ajax.requests.mostRecent();
32 | if (request) {
33 | resolve(request);
34 | } else {
35 | attemptGettingAjaxRequest(resolve, reject);
36 | }
37 | }, delay);
38 | }
39 |
40 | return getAjaxRequest;
41 | })();
42 |
--------------------------------------------------------------------------------
/axios/lib/core/enhanceError.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Update an Error with the specified config, error code, and response.
5 | *
6 | * @param {Error} error The error to update.
7 | * @param {Object} config The config.
8 | * @param {string} [code] The error code (for example, 'ECONNABORTED').
9 | * @param {Object} [request] The request.
10 | * @param {Object} [response] The response.
11 | * @returns {Error} The error.
12 | */
13 | module.exports = function enhanceError(error, config, code, request, response) {
14 | error.config = config;
15 | if (code) {
16 | error.code = code;
17 | }
18 |
19 | error.request = request;
20 | error.response = response;
21 | error.isAxiosError = true;
22 |
23 | error.toJSON = function() {
24 | return {
25 | // Standard
26 | message: this.message,
27 | name: this.name,
28 | // Microsoft
29 | description: this.description,
30 | number: this.number,
31 | // Mozilla
32 | fileName: this.fileName,
33 | lineNumber: this.lineNumber,
34 | columnNumber: this.columnNumber,
35 | stack: this.stack,
36 | // Axios
37 | config: this.config,
38 | code: this.code
39 | };
40 | };
41 | return error;
42 | };
43 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/cookies.js:
--------------------------------------------------------------------------------
1 | import utils from './../utils.js';
2 | import platform from '../platform/index.js';
3 |
4 | export default platform.hasStandardBrowserEnv ?
5 |
6 | // Standard browser envs support document.cookie
7 | {
8 | write(name, value, expires, path, domain, secure) {
9 | const cookie = [name + '=' + encodeURIComponent(value)];
10 |
11 | utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
12 |
13 | utils.isString(path) && cookie.push('path=' + path);
14 |
15 | utils.isString(domain) && cookie.push('domain=' + domain);
16 |
17 | secure === true && cookie.push('secure');
18 |
19 | document.cookie = cookie.join('; ');
20 | },
21 |
22 | read(name) {
23 | const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
24 | return (match ? decodeURIComponent(match[3]) : null);
25 | },
26 |
27 | remove(name) {
28 | this.write(name, '', Date.now() - 86400000);
29 | }
30 | }
31 |
32 | :
33 |
34 | // Non-standard browser env (web workers, react-native) lack needed support.
35 | {
36 | write() {},
37 | read() {
38 | return null;
39 | },
40 | remove() {}
41 | };
42 |
43 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/cookies.spec.js:
--------------------------------------------------------------------------------
1 | var cookies = require('../../../lib/helpers/cookies');
2 |
3 | describe('helpers::cookies', function () {
4 | afterEach(function () {
5 | // Remove all the cookies
6 | var expires = Date.now() - (60 * 60 * 24 * 7);
7 | document.cookie.split(';').map(function (cookie) {
8 | return cookie.split('=')[0];
9 | }).forEach(function (name) {
10 | document.cookie = name + '=; expires=' + new Date(expires).toGMTString();
11 | });
12 | });
13 |
14 | it('should write cookies', function () {
15 | cookies.write('foo', 'baz');
16 | expect(document.cookie).toEqual('foo=baz');
17 | });
18 |
19 | it('should read cookies', function () {
20 | cookies.write('foo', 'abc');
21 | cookies.write('bar', 'def');
22 | expect(cookies.read('foo')).toEqual('abc');
23 | expect(cookies.read('bar')).toEqual('def');
24 | });
25 |
26 | it('should remove cookies', function () {
27 | cookies.write('foo', 'bar');
28 | cookies.remove('foo');
29 | expect(cookies.read('foo')).toEqual(null);
30 | });
31 |
32 | it('should uri encode values', function () {
33 | cookies.write('foo', 'bar baz%');
34 | expect(document.cookie).toEqual('foo=bar%20baz%25');
35 | });
36 | });
37 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/cookies.spec.js:
--------------------------------------------------------------------------------
1 | import cookies from '../../../lib/helpers/cookies';
2 |
3 | describe('helpers::cookies', function () {
4 | afterEach(function () {
5 | // Remove all the cookies
6 | const expires = Date.now() - (60 * 60 * 24 * 7);
7 | document.cookie.split(';').map(function (cookie) {
8 | return cookie.split('=')[0];
9 | }).forEach(function (name) {
10 | document.cookie = name + '=; expires=' + new Date(expires).toGMTString();
11 | });
12 | });
13 |
14 | it('should write cookies', function () {
15 | cookies.write('foo', 'baz');
16 | expect(document.cookie).toEqual('foo=baz');
17 | });
18 |
19 | it('should read cookies', function () {
20 | cookies.write('foo', 'abc');
21 | cookies.write('bar', 'def');
22 | expect(cookies.read('foo')).toEqual('abc');
23 | expect(cookies.read('bar')).toEqual('def');
24 | });
25 |
26 | it('should remove cookies', function () {
27 | cookies.write('foo', 'bar');
28 | cookies.remove('foo');
29 | expect(cookies.read('foo')).toEqual(null);
30 | });
31 |
32 | it('should uri encode values', function () {
33 | cookies.write('foo', 'bar baz%');
34 | expect(document.cookie).toEqual('foo=bar%20baz%25');
35 | });
36 | });
37 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts/index.ts:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import axios, {CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData} from 'axios';
3 |
4 | assert.strictEqual(typeof axios, 'function');
5 |
6 | assert.strictEqual(typeof CanceledError, 'function');
7 | assert.strictEqual(typeof AxiosError, 'function');
8 | assert.strictEqual(typeof AxiosHeaders, 'function');
9 | assert.strictEqual(typeof formToJSON, 'function');
10 | assert.strictEqual(typeof spread, 'function');
11 | assert.strictEqual(typeof isAxiosError, 'function');
12 | assert.strictEqual(typeof isCancel, 'function');
13 | assert.strictEqual(typeof all, 'function');
14 | assert.strictEqual(typeof toFormData, 'function');
15 |
16 | assert.strictEqual(typeof axios.CanceledError, 'function');
17 | assert.strictEqual(typeof axios.AxiosError, 'function');
18 | assert.strictEqual(typeof axios.AxiosHeaders, 'function');
19 | assert.strictEqual(typeof axios.formToJSON, 'function');
20 | assert.strictEqual(typeof axios.spread, 'function');
21 | assert.strictEqual(typeof axios.isAxiosError, 'function');
22 | assert.strictEqual(typeof axios.isCancel, 'function');
23 | assert.strictEqual(typeof axios.all, 'function');
24 | assert.strictEqual(typeof axios.toFormData, 'function');
25 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/validator.spec.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import validator from '../../../lib/helpers/validator';
4 |
5 | describe('validator::assertOptions', function() {
6 | it('should throw only if unknown an option was passed', function() {
7 | expect(function() {
8 | validator.assertOptions({
9 | x: true
10 | }, {
11 | y: validator.validators.boolean
12 | });
13 | }).toThrow(new Error('Unknown option x'));
14 |
15 | expect(function() {
16 | validator.assertOptions({
17 | x: true
18 | }, {
19 | x: validator.validators.boolean,
20 | y: validator.validators.boolean
21 | });
22 | }).not.toThrow(new Error('Unknown option x'));
23 | });
24 |
25 | it('should throw TypeError only if option type doesn\'t match', function() {
26 | expect(function() {
27 | validator.assertOptions({
28 | x: 123
29 | }, {
30 | x: validator.validators.boolean
31 | });
32 | }).toThrow(new TypeError('option x must be a boolean'));
33 |
34 | expect(function() {
35 | validator.assertOptions({
36 | x: true
37 | }, {
38 | x: validator.validators.boolean,
39 | y: validator.validators.boolean
40 | });
41 | }).not.toThrow();
42 | });
43 | });
44 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts-require/index.ts:
--------------------------------------------------------------------------------
1 | const assert = require('assert');
2 | const axios = require('axios');
3 | const {CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData} = axios;
4 |
5 | assert.strictEqual(typeof axios, 'function');
6 |
7 | assert.strictEqual(typeof CanceledError, 'function');
8 | assert.strictEqual(typeof AxiosError, 'function');
9 | assert.strictEqual(typeof AxiosHeaders, 'function');
10 | assert.strictEqual(typeof formToJSON, 'function');
11 | assert.strictEqual(typeof spread, 'function');
12 | assert.strictEqual(typeof isAxiosError, 'function');
13 | assert.strictEqual(typeof isCancel, 'function');
14 | assert.strictEqual(typeof all, 'function');
15 | assert.strictEqual(typeof toFormData, 'function');
16 |
17 | assert.strictEqual(typeof axios.CanceledError, 'function');
18 | assert.strictEqual(typeof axios.AxiosError, 'function');
19 | assert.strictEqual(typeof axios.AxiosHeaders, 'function');
20 | assert.strictEqual(typeof axios.formToJSON, 'function');
21 | assert.strictEqual(typeof axios.spread, 'function');
22 | assert.strictEqual(typeof axios.isAxiosError, 'function');
23 | assert.strictEqual(typeof axios.isCancel, 'function');
24 | assert.strictEqual(typeof axios.all, 'function');
25 | assert.strictEqual(typeof axios.toFormData, 'function');
26 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts-require/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const assert = require('assert');
3 | const axios = require('axios');
4 | const { CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData } = axios;
5 | assert.strictEqual(typeof axios, 'function');
6 | assert.strictEqual(typeof CanceledError, 'function');
7 | assert.strictEqual(typeof AxiosError, 'function');
8 | assert.strictEqual(typeof AxiosHeaders, 'function');
9 | assert.strictEqual(typeof formToJSON, 'function');
10 | assert.strictEqual(typeof spread, 'function');
11 | assert.strictEqual(typeof isAxiosError, 'function');
12 | assert.strictEqual(typeof isCancel, 'function');
13 | assert.strictEqual(typeof all, 'function');
14 | assert.strictEqual(typeof toFormData, 'function');
15 | assert.strictEqual(typeof axios.CanceledError, 'function');
16 | assert.strictEqual(typeof axios.AxiosError, 'function');
17 | assert.strictEqual(typeof axios.AxiosHeaders, 'function');
18 | assert.strictEqual(typeof axios.formToJSON, 'function');
19 | assert.strictEqual(typeof axios.spread, 'function');
20 | assert.strictEqual(typeof axios.isAxiosError, 'function');
21 | assert.strictEqual(typeof axios.isCancel, 'function');
22 | assert.strictEqual(typeof axios.all, 'function');
23 | assert.strictEqual(typeof axios.toFormData, 'function');
24 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts-require-default/index.ts:
--------------------------------------------------------------------------------
1 | const assert = require('assert');
2 | const axios = require('axios').default;
3 | const {CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData} = axios;
4 |
5 | assert.strictEqual(typeof axios, 'function');
6 |
7 | assert.strictEqual(typeof CanceledError, 'function');
8 | assert.strictEqual(typeof AxiosError, 'function');
9 | assert.strictEqual(typeof AxiosHeaders, 'function');
10 | assert.strictEqual(typeof formToJSON, 'function');
11 | assert.strictEqual(typeof spread, 'function');
12 | assert.strictEqual(typeof isAxiosError, 'function');
13 | assert.strictEqual(typeof isCancel, 'function');
14 | assert.strictEqual(typeof all, 'function');
15 | assert.strictEqual(typeof toFormData, 'function');
16 |
17 | assert.strictEqual(typeof axios.CanceledError, 'function');
18 | assert.strictEqual(typeof axios.AxiosError, 'function');
19 | assert.strictEqual(typeof axios.AxiosHeaders, 'function');
20 | assert.strictEqual(typeof axios.formToJSON, 'function');
21 | assert.strictEqual(typeof axios.spread, 'function');
22 | assert.strictEqual(typeof axios.isAxiosError, 'function');
23 | assert.strictEqual(typeof axios.isCancel, 'function');
24 | assert.strictEqual(typeof axios.all, 'function');
25 | assert.strictEqual(typeof axios.toFormData, 'function');
26 |
--------------------------------------------------------------------------------
/axios-v1.x/test/module/ts-require-default/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | const assert = require('assert');
3 | const axios = require('axios').default;
4 | const { CanceledError, AxiosError, AxiosHeaders, formToJSON, spread, isAxiosError, isCancel, all, toFormData } = axios;
5 | assert.strictEqual(typeof axios, 'function');
6 | assert.strictEqual(typeof CanceledError, 'function');
7 | assert.strictEqual(typeof AxiosError, 'function');
8 | assert.strictEqual(typeof AxiosHeaders, 'function');
9 | assert.strictEqual(typeof formToJSON, 'function');
10 | assert.strictEqual(typeof spread, 'function');
11 | assert.strictEqual(typeof isAxiosError, 'function');
12 | assert.strictEqual(typeof isCancel, 'function');
13 | assert.strictEqual(typeof all, 'function');
14 | assert.strictEqual(typeof toFormData, 'function');
15 | assert.strictEqual(typeof axios.CanceledError, 'function');
16 | assert.strictEqual(typeof axios.AxiosError, 'function');
17 | assert.strictEqual(typeof axios.AxiosHeaders, 'function');
18 | assert.strictEqual(typeof axios.formToJSON, 'function');
19 | assert.strictEqual(typeof axios.spread, 'function');
20 | assert.strictEqual(typeof axios.isAxiosError, 'function');
21 | assert.strictEqual(typeof axios.isCancel, 'function');
22 | assert.strictEqual(typeof axios.all, 'function');
23 | assert.strictEqual(typeof axios.toFormData, 'function');
24 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/speedometer.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | /**
4 | * Calculate data maxRate
5 | * @param {Number} [samplesCount= 10]
6 | * @param {Number} [min= 1000]
7 | * @returns {Function}
8 | */
9 | function speedometer(samplesCount, min) {
10 | samplesCount = samplesCount || 10;
11 | const bytes = new Array(samplesCount);
12 | const timestamps = new Array(samplesCount);
13 | let head = 0;
14 | let tail = 0;
15 | let firstSampleTS;
16 |
17 | min = min !== undefined ? min : 1000;
18 |
19 | return function push(chunkLength) {
20 | const now = Date.now();
21 |
22 | const startedAt = timestamps[tail];
23 |
24 | if (!firstSampleTS) {
25 | firstSampleTS = now;
26 | }
27 |
28 | bytes[head] = chunkLength;
29 | timestamps[head] = now;
30 |
31 | let i = tail;
32 | let bytesCount = 0;
33 |
34 | while (i !== head) {
35 | bytesCount += bytes[i++];
36 | i = i % samplesCount;
37 | }
38 |
39 | head = (head + 1) % samplesCount;
40 |
41 | if (head === tail) {
42 | tail = (tail + 1) % samplesCount;
43 | }
44 |
45 | if (now - firstSampleTS < min) {
46 | return;
47 | }
48 |
49 | const passed = startedAt && now - startedAt;
50 |
51 | return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
52 | };
53 | }
54 |
55 | export default speedometer;
56 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/isValidXss.spec.js:
--------------------------------------------------------------------------------
1 | var isValidXss = require('../../../lib/helpers/isValidXss');
2 |
3 | describe('helpers::isValidXss', function () {
4 | it('should detect script tags', function () {
5 | expect(isValidXss("")).toBe(true);
6 | expect(isValidXss("")).toBe(true);
7 | expect(isValidXss("")).toBe(true);
8 | expect(isValidXss("
xss")).toBe(true);
9 | expect(isValidXss("")).toBe(true);
10 | expect(isValidXss("onerror=alert('XSS')")).toBe(true);
11 | expect(isValidXss("Click Me")).toBe(true);
12 | });
13 |
14 | it('should not detect non script tags', function() {
15 | expect(isValidXss("/one/?foo=bar")).toBe(false);
16 | expect(isValidXss(" tags")).toBe(false);
17 | expect(isValidXss("")).toBe(false);
18 | expect(isValidXss(">>> safe <<<")).toBe(false);
19 | expect(isValidXss("<<< safe >>>")).toBe(false);
20 | expect(isValidXss("my script rules")).toBe(false);
21 | expect(isValidXss("")).toBe(false);
22 | expect(isValidXss("MyTitle
")).toBe(false);
23 | expect(isValidXss("
")).toBe(false);
24 | })
25 | });
26 |
--------------------------------------------------------------------------------
/shells/cp.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | function _info(){
4 | echo -e "\033[32m$1\033[0m"
5 | }
6 |
7 | function _warning(){
8 | echo -e "\033[33m$1\033[0m"
9 | }
10 |
11 | function _error(){
12 | echo -e "\033[31m$1\033[0m"
13 | }
14 |
15 | function _green(){
16 | echo "\033[32m"$1"\033[0m"
17 | }
18 |
19 | function _cyan(){
20 | echo "\033[36m"$1"\033[0m"
21 | }
22 |
23 | function _blue(){
24 | echo "\033[34m"$1"\033[0m"
25 | }
26 |
27 | function _magenta(){
28 | echo "\033[35m"$1"\033[0m"
29 | }
30 |
31 | function _grey(){
32 | echo "\033[37m"$1"\033[0m"
33 | }
34 |
35 | function _yellow(){
36 | echo "\033[33m"$1"\033[0m"
37 | }
38 |
39 | function _red(){
40 | echo "\033[31m"$1"\033[0m"
41 | }
42 |
43 | # 确保脚本抛出遇到的错误
44 | set -e
45 |
46 | _info '
47 | -------------------------------------
48 | 把当前项目拷贝到 blog 同步脚本
49 | -------------------------------------
50 | '
51 |
52 | cd ../blog/
53 | # git
54 | git pull
55 | git status
56 |
57 | cd ../axios-analysis
58 |
59 | rsync -av --exclude .git/ --exclude axios/ --exclude shells/ . ../blog/docs/axios
60 |
61 | echo
62 |
63 | cd ../blog/
64 |
65 | # git
66 | git pull
67 | git status
68 | git add docs/axios
69 | git commit -m "update: docs/axios 同步 axios-analysis :construction:"
70 | git push
71 |
72 |
73 | echo
74 |
75 | _info '
76 | -------------------------------------
77 | 同步完成,并提交到远程仓库
78 | -------------------------------------
79 | '
80 | cd -
81 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/workflows/stale.yml:
--------------------------------------------------------------------------------
1 | name: 'Close Stale'
2 |
3 | on:
4 | schedule:
5 | - cron: '0 0 * * 1'
6 |
7 | jobs:
8 | stale:
9 | permissions:
10 | issues: write # for actions/stale to close stale issues
11 | pull-requests: write # for actions/stale to close stale PRs
12 | runs-on: ubuntu-latest
13 | steps:
14 | - name: Close Stale Issues
15 | uses: actions/stale@v7
16 | with:
17 | repo-token: ${{ secrets.GITHUB_TOKEN }}
18 | stale-issue-message: |
19 | Hello! :wave:
20 |
21 | This issue is being automatically marked as stale because it has not been updated in a while. Please confirm that the issue is still present and reproducible. If no updates or new comments are received the issue will be closed in a few days.
22 |
23 | Thanks.
24 | stale-pr-message: |
25 | Hello! :wave:
26 |
27 | This pull request is being automatically marked as stale because it has not been updated in a while. Please confirm that the issue is still present and reproducible. If no updates or new comments are received the pull request will be closed in a few days.
28 |
29 | Thanks.
30 | stale-issue-label: 'status:stale'
31 | stale-pr-label: 'status:stale'
32 | only-labels: 'status:more info needed'
33 | days-before-stale: 30
34 | days-before-close: 14
35 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/trackStream.js:
--------------------------------------------------------------------------------
1 |
2 | export const streamChunk = function* (chunk, chunkSize) {
3 | let len = chunk.byteLength;
4 |
5 | if (!chunkSize || len < chunkSize) {
6 | yield chunk;
7 | return;
8 | }
9 |
10 | let pos = 0;
11 | let end;
12 |
13 | while (pos < len) {
14 | end = pos + chunkSize;
15 | yield chunk.slice(pos, end);
16 | pos = end;
17 | }
18 | }
19 |
20 | const encoder = new TextEncoder();
21 |
22 | export const readBytes = async function* (iterable, chunkSize) {
23 | for await (const chunk of iterable) {
24 | yield* streamChunk(ArrayBuffer.isView(chunk) ? chunk : (await encoder.encode(String(chunk))), chunkSize);
25 | }
26 | }
27 |
28 | export const trackStream = (stream, chunkSize, onProgress, onFinish) => {
29 | const iterator = readBytes(stream, chunkSize);
30 |
31 | let bytes = 0;
32 |
33 | return new ReadableStream({
34 | type: 'bytes',
35 |
36 | async pull(controller) {
37 | const {done, value} = await iterator.next();
38 |
39 | if (done) {
40 | controller.close();
41 | onFinish();
42 | return;
43 | }
44 |
45 | let len = value.byteLength;
46 | onProgress && onProgress(bytes += len);
47 | controller.enqueue(new Uint8Array(value));
48 | },
49 | cancel(reason) {
50 | onFinish(reason);
51 | return iterator.return();
52 | }
53 | }, {
54 | highWaterMark: 2
55 | })
56 | }
57 |
--------------------------------------------------------------------------------
/axios/examples/post/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - post example
5 |
6 |
7 |
8 | axios.post
9 |
10 |
17 |
18 |
19 |
20 |
21 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/post/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - post example
5 |
6 |
7 |
8 | axios.post
9 |
10 |
17 |
18 |
19 |
20 |
21 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/axios/test/specs/core/createError.spec.js:
--------------------------------------------------------------------------------
1 | var createError = require('../../../lib/core/createError');
2 |
3 | describe('core::createError', function() {
4 | it('should create an Error with message, config, code, request, response and isAxiosError', function() {
5 | var request = { path: '/foo' };
6 | var response = { status: 200, data: { foo: 'bar' } };
7 | var error = createError('Boom!', { foo: 'bar' }, 'ESOMETHING', request, response);
8 | expect(error instanceof Error).toBe(true);
9 | expect(error.message).toBe('Boom!');
10 | expect(error.config).toEqual({ foo: 'bar' });
11 | expect(error.code).toBe('ESOMETHING');
12 | expect(error.request).toBe(request);
13 | expect(error.response).toBe(response);
14 | expect(error.isAxiosError).toBe(true);
15 | });
16 | it('should create an Error that can be serialized to JSON', function() {
17 | // Attempting to serialize request and response results in
18 | // TypeError: Converting circular structure to JSON
19 | var request = { path: '/foo' };
20 | var response = { status: 200, data: { foo: 'bar' } };
21 | var error = createError('Boom!', { foo: 'bar' }, 'ESOMETHING', request, response);
22 | var json = error.toJSON();
23 | expect(json.message).toBe('Boom!');
24 | expect(json.config).toEqual({ foo: 'bar' });
25 | expect(json.code).toBe('ESOMETHING');
26 | expect(json.request).toBe(undefined);
27 | expect(json.response).toBe(undefined);
28 | });
29 | });
30 |
--------------------------------------------------------------------------------
/axios/test/specs/utils/forEach.spec.js:
--------------------------------------------------------------------------------
1 | var forEach = require('../../../lib/utils').forEach;
2 |
3 | describe('utils::forEach', function () {
4 | it('should loop over an array', function () {
5 | var sum = 0;
6 |
7 | forEach([1, 2, 3, 4, 5], function (val) {
8 | sum += val;
9 | });
10 |
11 | expect(sum).toEqual(15);
12 | });
13 |
14 | it('should loop over object keys', function () {
15 | var keys = '';
16 | var vals = 0;
17 | var obj = {
18 | b: 1,
19 | a: 2,
20 | r: 3
21 | };
22 |
23 | forEach(obj, function (v, k) {
24 | keys += k;
25 | vals += v;
26 | });
27 |
28 | expect(keys).toEqual('bar');
29 | expect(vals).toEqual(6);
30 | });
31 |
32 | it('should handle undefined gracefully', function () {
33 | var count = 0;
34 |
35 | forEach(undefined, function () {
36 | count++;
37 | });
38 |
39 | expect(count).toEqual(0);
40 | });
41 |
42 | it('should make an array out of non-array argument', function () {
43 | var count = 0;
44 |
45 | forEach(function () {}, function () {
46 | count++;
47 | });
48 |
49 | expect(count).toEqual(1);
50 | });
51 |
52 | it('should handle non object prototype gracefully', function () {
53 | var count = 0;
54 | var data = Object.create(null);
55 | data.foo = 'bar'
56 |
57 | forEach(data, function () {
58 | count++;
59 | });
60 |
61 | expect(count).toEqual(1);
62 | });
63 | });
64 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/composeSignals.js:
--------------------------------------------------------------------------------
1 | import CanceledError from "../cancel/CanceledError.js";
2 | import AxiosError from "../core/AxiosError.js";
3 |
4 | const composeSignals = (signals, timeout) => {
5 | let controller = new AbortController();
6 |
7 | let aborted;
8 |
9 | const onabort = function (cancel) {
10 | if (!aborted) {
11 | aborted = true;
12 | unsubscribe();
13 | const err = cancel instanceof Error ? cancel : this.reason;
14 | controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
15 | }
16 | }
17 |
18 | let timer = timeout && setTimeout(() => {
19 | onabort(new AxiosError(`timeout ${timeout} of ms exceeded`, AxiosError.ETIMEDOUT))
20 | }, timeout)
21 |
22 | const unsubscribe = () => {
23 | if (signals) {
24 | timer && clearTimeout(timer);
25 | timer = null;
26 | signals.forEach(signal => {
27 | signal &&
28 | (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));
29 | });
30 | signals = null;
31 | }
32 | }
33 |
34 | signals.forEach((signal) => signal && signal.addEventListener && signal.addEventListener('abort', onabort));
35 |
36 | const {signal} = controller;
37 |
38 | signal.unsubscribe = unsubscribe;
39 |
40 | return [signal, () => {
41 | timer && clearTimeout(timer);
42 | timer = null;
43 | }];
44 | }
45 |
46 | export default composeSignals;
47 |
--------------------------------------------------------------------------------
/axios/examples/get/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - get example
5 |
6 |
7 |
8 | axios.get
9 |
10 |
11 |
12 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/get/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - get example
5 |
6 |
7 |
8 | axios.get
9 |
10 |
11 |
12 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/axios/lib/core/InterceptorManager.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var utils = require('./../utils');
4 |
5 | function InterceptorManager() {
6 | this.handlers = [];
7 | }
8 |
9 | /**
10 | * Add a new interceptor to the stack
11 | *
12 | * @param {Function} fulfilled The function to handle `then` for a `Promise`
13 | * @param {Function} rejected The function to handle `reject` for a `Promise`
14 | *
15 | * @return {Number} An ID used to remove interceptor later
16 | */
17 | InterceptorManager.prototype.use = function use(fulfilled, rejected) {
18 | this.handlers.push({
19 | fulfilled: fulfilled,
20 | rejected: rejected
21 | });
22 | return this.handlers.length - 1;
23 | };
24 |
25 | /**
26 | * Remove an interceptor from the stack
27 | *
28 | * @param {Number} id The ID that was returned by `use`
29 | */
30 | InterceptorManager.prototype.eject = function eject(id) {
31 | if (this.handlers[id]) {
32 | this.handlers[id] = null;
33 | }
34 | };
35 |
36 | /**
37 | * Iterate over all the registered interceptors
38 | *
39 | * This method is particularly useful for skipping over any
40 | * interceptors that may have become `null` calling `eject`.
41 | *
42 | * @param {Function} fn The function to call for each interceptor
43 | */
44 | InterceptorManager.prototype.forEach = function forEach(fn) {
45 | utils.forEach(this.handlers, function forEachHandler(h) {
46 | if (h !== null) {
47 | fn(h);
48 | }
49 | });
50 | };
51 |
52 | module.exports = InterceptorManager;
53 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/utils/forEach.spec.js:
--------------------------------------------------------------------------------
1 | import utils from '../../../lib/utils';
2 |
3 | const {forEach} = utils;
4 |
5 | describe('utils::forEach', function () {
6 | it('should loop over an array', function () {
7 | let sum = 0;
8 |
9 | forEach([1, 2, 3, 4, 5], function (val) {
10 | sum += val;
11 | });
12 |
13 | expect(sum).toEqual(15);
14 | });
15 |
16 | it('should loop over object keys', function () {
17 | let keys = '';
18 | let vals = 0;
19 | const obj = {
20 | b: 1,
21 | a: 2,
22 | r: 3
23 | };
24 |
25 | forEach(obj, function (v, k) {
26 | keys += k;
27 | vals += v;
28 | });
29 |
30 | expect(keys).toEqual('bar');
31 | expect(vals).toEqual(6);
32 | });
33 |
34 | it('should handle undefined gracefully', function () {
35 | let count = 0;
36 |
37 | forEach(undefined, function () {
38 | count++;
39 | });
40 |
41 | expect(count).toEqual(0);
42 | });
43 |
44 | it('should make an array out of non-array argument', function () {
45 | let count = 0;
46 |
47 | forEach(function () {}, function () {
48 | count++;
49 | });
50 |
51 | expect(count).toEqual(1);
52 | });
53 |
54 | it('should handle non object prototype gracefully', function () {
55 | let count = 0;
56 | const data = Object.create(null);
57 | data.foo = 'bar'
58 |
59 | forEach(data, function () {
60 | count++;
61 | });
62 |
63 | expect(count).toEqual(1);
64 | });
65 | });
66 |
--------------------------------------------------------------------------------
/axios/lib/cancel/CancelToken.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Cancel = require('./Cancel');
4 |
5 | /**
6 | * A `CancelToken` is an object that can be used to request cancellation of an operation.
7 | *
8 | * @class
9 | * @param {Function} executor The executor function.
10 | */
11 | function CancelToken(executor) {
12 | if (typeof executor !== 'function') {
13 | throw new TypeError('executor must be a function.');
14 | }
15 |
16 | var resolvePromise;
17 | this.promise = new Promise(function promiseExecutor(resolve) {
18 | resolvePromise = resolve;
19 | });
20 |
21 | var token = this;
22 | executor(function cancel(message) {
23 | if (token.reason) {
24 | // Cancellation has already been requested
25 | return;
26 | }
27 |
28 | token.reason = new Cancel(message);
29 | resolvePromise(token.reason);
30 | });
31 | }
32 |
33 | /**
34 | * Throws a `Cancel` if cancellation has been requested.
35 | */
36 | CancelToken.prototype.throwIfRequested = function throwIfRequested() {
37 | if (this.reason) {
38 | throw this.reason;
39 | }
40 | };
41 |
42 | /**
43 | * Returns an object that contains a new `CancelToken` and a function that, when called,
44 | * cancels the `CancelToken`.
45 | */
46 | CancelToken.source = function source() {
47 | var cancel;
48 | var token = new CancelToken(function executor(c) {
49 | cancel = c;
50 | });
51 | return {
52 | token: token,
53 | cancel: cancel
54 | };
55 | };
56 |
57 | module.exports = CancelToken;
58 |
--------------------------------------------------------------------------------
/axios/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | #### Instructions
4 |
5 | Please read and follow the instructions before submitting an issue:
6 |
7 | - Read all our documentation, especially the [README](https://github.com/axios/axios/blob/master/README.md). It may contain information that helps you solve your issue.
8 | - Ensure your issue isn't already [reported](https://github.com/axios/axios/issues?utf8=%E2%9C%93&q=is%3Aissue).
9 | - If you aren't sure that the issue is caused by axios or you just need help, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/axios) or [our chat](https://gitter.im/mzabriskie/axios).
10 | - If you're reporting a bug, ensure it isn't already fixed in the latest axios version.
11 | - If you need a new feature there's a chance it's already implemented in a [library](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) or you can implement it using [interceptors](https://github.com/axios/axios#interceptors).
12 |
13 | **⚠️👆 Delete the instructions before submitting the issue 👆⚠️**
14 |
15 | #### Summary
16 |
17 | Describe your issue here, including as much detail as necessary.
18 |
19 | If you're reporting a bug, include the relevant code and stack traces to debug it (removing any private information).
20 |
21 | If you're requesting a feature, include some context and examples of code using it.
22 |
23 | #### Context
24 |
25 | - axios version: *e.g.: v0.16.0*
26 | - Environment: *e.g.: node v6.9.4, chrome 54, windows 7*
27 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/workflows/notify.yml:
--------------------------------------------------------------------------------
1 | name: notify
2 |
3 | on:
4 | #workflow_run:
5 | # workflows: ["publish"]
6 | # types:
7 | # - completed
8 | #repository_dispatch:
9 | # types: [ notify ]
10 | #release:
11 | # types: [published]
12 | # branches:
13 | # - main
14 | # - 'v**'
15 | #push:
16 | # tags:
17 | # - 'v[0-9]+.[0-9]+.[0-9]+'
18 | # branches:
19 | # - main
20 | # - 'v**'
21 |
22 | workflow_dispatch:
23 | inputs:
24 | tag:
25 | required: false
26 | jobs:
27 | notify:
28 | runs-on: ubuntu-latest
29 | #if: ${{ github.event_name == 'workflow_dispatch' || github.event.workflow_run.conclusion == 'success' }}
30 | steps:
31 | #- name: Dump GitHub context
32 | # env:
33 | # GITHUB_CONTEXT: ${{ toJson(github) }}
34 | # run: echo "$GITHUB_CONTEXT"
35 | - uses: actions/checkout@v3
36 | with:
37 | fetch-depth: 0
38 | - name: git config
39 | run: |
40 | git config user.name "${GITHUB_ACTOR}"
41 | git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
42 | - name: Setup node
43 | uses: actions/setup-node@v3
44 | with:
45 | node-version: 18
46 | cache: npm
47 | - run: npm ci
48 | - name: Notify published PRs
49 | env:
50 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
51 | run: node ./bin/actions/notify_published.js --tag ${{ github.event.inputs.tag || github.event.release.tag_name }}
52 |
--------------------------------------------------------------------------------
/axios-v1.x/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We are open to, and grateful for, any contributions made by the community. By contributing to axios, you agree to abide by the [code of conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md).
4 |
5 | ## Code Style
6 |
7 | Please follow the [node style guide](https://github.com/felixge/node-style-guide).
8 |
9 | ## Commit Messages
10 |
11 | Please follow [conventional commits](https://www.conventionalcommits.org/en/v1.0.0/)
12 |
13 | ## Testing
14 |
15 | Please update the tests to reflect your code changes. Pull requests will not be accepted if they are failing on GitHub actions.
16 |
17 | ## Documentation
18 |
19 | Please update the [docs](README.md) accordingly so that there are no discrepancies between the API and the documentation.
20 |
21 | ## Developing
22 |
23 | - `npm run test` run the jasmine and mocha tests
24 | - `npm run build` run webpack and bundle the source
25 | - `npm run version` prepare the code for release
26 |
27 | Please don't include changes to `dist/` in your pull request. This should only be updated when releasing a new version.
28 |
29 | ## Running Examples
30 |
31 | Examples are included in part to allow manual testing.
32 |
33 | Running example
34 |
35 | ```bash
36 | > npm run examples
37 | # Open 127.0.0.1:3000
38 | ```
39 |
40 | Running sandbox in browser
41 |
42 | ```bash
43 | > npm start
44 | # Open 127.0.0.1:3000
45 | ```
46 |
47 | Running sandbox in terminal
48 |
49 | ```bash
50 | > npm start
51 | > node ./sandbox/client
52 | ```
53 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: 'CI'
2 |
3 | on:
4 | push:
5 | branches: '**'
6 | pull_request:
7 | branches: '**'
8 |
9 | permissions:
10 | contents: read
11 |
12 | jobs:
13 | build:
14 | runs-on: ubuntu-latest
15 |
16 | strategy:
17 | matrix:
18 | node-version: [12.x, 14.x, 16.x, 18.x, 20.x, 21.x]
19 | fail-fast: false
20 |
21 | steps:
22 | - uses: actions/checkout@v3
23 | with:
24 | persist-credentials: true
25 | - name: Get changed files
26 | id: changed-files
27 | uses: tj-actions/changed-files@v40
28 | - name: List all changed files
29 | run: |
30 | for file in ${{ steps.changed-files.outputs.all_changed_files }}; do
31 | echo "$file was changed"
32 | done
33 | - name: Check changes
34 | id: changed-ignored
35 | uses: tj-actions/changed-files@v40
36 | with:
37 | files: |
38 | **.md
39 | sandbox/**
40 | examples/**
41 | .github/**
42 | templates/**
43 | bin/**
44 | - name: Setup node
45 | uses: actions/setup-node@v3
46 | with:
47 | node-version: ${{ matrix.node-version }}
48 | cache: npm
49 | if: steps.changed-ignored.outputs.only_modified == 'false'
50 | - run: npm ci
51 | if: steps.changed-ignored.outputs.only_modified == 'false'
52 | - run: npm test
53 | if: steps.changed-ignored.outputs.only_modified == 'false'
54 |
--------------------------------------------------------------------------------
/axios/examples/all/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - all example
5 |
6 |
7 |
8 | axios.all
9 |
10 |
11 |
User
12 |
13 |
![]()
14 |
15 |
16 |
17 |
18 |
19 |
Orgs
20 |
21 |
22 |
23 |
24 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/all/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - all example
5 |
6 |
7 |
8 | axios.all
9 |
10 |
11 |
User
12 |
13 |
![]()
14 |
15 |
16 |
17 |
18 |
19 |
Orgs
20 |
21 |
22 |
23 |
24 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/core/transformData.spec.js:
--------------------------------------------------------------------------------
1 | import transformData from '../../../lib/core/transformData';
2 |
3 | describe('core::transformData', function () {
4 | it('should support a single transformer', function () {
5 | let data;
6 |
7 | data = transformData.call({
8 |
9 | }, function (data) {
10 | data = 'foo';
11 | return data;
12 | })
13 |
14 | expect(data).toEqual('foo');
15 | });
16 |
17 | it('should support an array of transformers', function () {
18 | let data = '';
19 | data = transformData.call({data}, [function (data) {
20 | data += 'f';
21 | return data;
22 | }, function (data) {
23 | data += 'o';
24 | return data;
25 | }, function (data) {
26 | data += 'o';
27 | return data;
28 | }]);
29 |
30 | expect(data).toEqual('foo');
31 | });
32 |
33 | it('should support reference headers in transformData', function () {
34 | const headers = {
35 | 'content-type': 'foo/bar',
36 | };
37 | let data = '';
38 | data = transformData.call({data, headers}, [function (data, headers) {
39 | data += headers['content-type'];
40 | return data;
41 | }]);
42 |
43 | expect(data).toEqual('foo/bar');
44 | });
45 |
46 | it('should support reference status code in transformData', function () {
47 | let data = '';
48 | data = transformData.call({}, [function (data, headers, status) {
49 | data += status;
50 | return data;
51 | }], {data, status: 200});
52 |
53 | expect(data).toEqual('200');
54 | });
55 | });
56 |
57 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/fromDataURI.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import AxiosError from '../core/AxiosError.js';
4 | import parseProtocol from './parseProtocol.js';
5 | import platform from '../platform/index.js';
6 |
7 | const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
8 |
9 | /**
10 | * Parse data uri to a Buffer or Blob
11 | *
12 | * @param {String} uri
13 | * @param {?Boolean} asBlob
14 | * @param {?Object} options
15 | * @param {?Function} options.Blob
16 | *
17 | * @returns {Buffer|Blob}
18 | */
19 | export default function fromDataURI(uri, asBlob, options) {
20 | const _Blob = options && options.Blob || platform.classes.Blob;
21 | const protocol = parseProtocol(uri);
22 |
23 | if (asBlob === undefined && _Blob) {
24 | asBlob = true;
25 | }
26 |
27 | if (protocol === 'data') {
28 | uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
29 |
30 | const match = DATA_URL_PATTERN.exec(uri);
31 |
32 | if (!match) {
33 | throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
34 | }
35 |
36 | const mime = match[1];
37 | const isBase64 = match[2];
38 | const body = match[3];
39 | const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
40 |
41 | if (asBlob) {
42 | if (!_Blob) {
43 | throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
44 | }
45 |
46 | return new _Blob([buffer], {type: mime});
47 | }
48 |
49 | return buffer;
50 | }
51 |
52 | throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
53 | }
54 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/adapters/adapters.js:
--------------------------------------------------------------------------------
1 | import adapters from '../../../lib/adapters/adapters.js';
2 | import assert from 'assert';
3 |
4 |
5 | describe('adapters', function () {
6 | const store = {...adapters.adapters};
7 |
8 | beforeEach(() => {
9 | Object.keys(adapters.adapters).forEach((name) => {
10 | delete adapters.adapters[name];
11 | });
12 |
13 | Object.assign(adapters.adapters, store);
14 | });
15 |
16 | it('should support loading by fn handle', function () {
17 | const adapter = () => {};
18 | assert.strictEqual(adapters.getAdapter(adapter), adapter);
19 | });
20 |
21 | it('should support loading by name', function () {
22 | const adapter = () => {};
23 | adapters.adapters['testadapter'] = adapter;
24 | assert.strictEqual(adapters.getAdapter('testAdapter'), adapter);
25 | });
26 |
27 | it('should detect adapter unavailable status', function () {
28 | adapters.adapters['testadapter'] = null;
29 | assert.throws(()=> adapters.getAdapter('testAdapter'), /is not available in the build/)
30 | });
31 |
32 | it('should detect adapter unsupported status', function () {
33 | adapters.adapters['testadapter'] = false;
34 | assert.throws(()=> adapters.getAdapter('testAdapter'), /is not supported by the environment/)
35 | });
36 |
37 | it('should pick suitable adapter from the list', function () {
38 | const adapter = () => {};
39 |
40 | Object.assign(adapters.adapters, {
41 | foo: false,
42 | bar: null,
43 | baz: adapter
44 | });
45 |
46 | assert.strictEqual(adapters.getAdapter(['foo', 'bar', 'baz']), adapter);
47 | });
48 | });
49 |
--------------------------------------------------------------------------------
/axios/lib/helpers/parseHeaders.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var utils = require('./../utils');
4 |
5 | // Headers whose duplicates are ignored by node
6 | // c.f. https://nodejs.org/api/http.html#http_message_headers
7 | var ignoreDuplicateOf = [
8 | 'age', 'authorization', 'content-length', 'content-type', 'etag',
9 | 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
10 | 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
11 | 'referer', 'retry-after', 'user-agent'
12 | ];
13 |
14 | /**
15 | * Parse headers into an object
16 | *
17 | * ```
18 | * Date: Wed, 27 Aug 2014 08:58:49 GMT
19 | * Content-Type: application/json
20 | * Connection: keep-alive
21 | * Transfer-Encoding: chunked
22 | * ```
23 | *
24 | * @param {String} headers Headers needing to be parsed
25 | * @returns {Object} Headers parsed into an object
26 | */
27 | module.exports = function parseHeaders(headers) {
28 | var parsed = {};
29 | var key;
30 | var val;
31 | var i;
32 |
33 | if (!headers) { return parsed; }
34 |
35 | utils.forEach(headers.split('\n'), function parser(line) {
36 | i = line.indexOf(':');
37 | key = utils.trim(line.substr(0, i)).toLowerCase();
38 | val = utils.trim(line.substr(i + 1));
39 |
40 | if (key) {
41 | if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
42 | return;
43 | }
44 | if (key === 'set-cookie') {
45 | parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
46 | } else {
47 | parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
48 | }
49 | }
50 | });
51 |
52 | return parsed;
53 | };
54 |
--------------------------------------------------------------------------------
/axios/test/specs/helpers/parseHeaders.spec.js:
--------------------------------------------------------------------------------
1 | var parseHeaders = require('../../../lib/helpers/parseHeaders');
2 |
3 | describe('helpers::parseHeaders', function () {
4 | it('should parse headers', function () {
5 | var date = new Date();
6 | var parsed = parseHeaders(
7 | 'Date: ' + date.toISOString() + '\n' +
8 | 'Content-Type: application/json\n' +
9 | 'Connection: keep-alive\n' +
10 | 'Transfer-Encoding: chunked'
11 | );
12 |
13 | expect(parsed['date']).toEqual(date.toISOString());
14 | expect(parsed['content-type']).toEqual('application/json');
15 | expect(parsed['connection']).toEqual('keep-alive');
16 | expect(parsed['transfer-encoding']).toEqual('chunked');
17 | });
18 |
19 | it('should use array for set-cookie', function() {
20 | var parsedZero = parseHeaders('');
21 | var parsedSingle = parseHeaders(
22 | 'Set-Cookie: key=val;'
23 | );
24 | var parsedMulti = parseHeaders(
25 | 'Set-Cookie: key=val;\n' +
26 | 'Set-Cookie: key2=val2;\n'
27 | );
28 |
29 | expect(parsedZero['set-cookie']).toBeUndefined();
30 | expect(parsedSingle['set-cookie']).toEqual(['key=val;']);
31 | expect(parsedMulti['set-cookie']).toEqual(['key=val;', 'key2=val2;']);
32 | });
33 |
34 | it('should handle duplicates', function() {
35 | var parsed = parseHeaders(
36 | 'Age: age-a\n' + // age is in ignore duplicates blacklist
37 | 'Age: age-b\n' +
38 | 'Foo: foo-a\n' +
39 | 'Foo: foo-b\n'
40 | );
41 |
42 | expect(parsed['age']).toEqual('age-a');
43 | expect(parsed['foo']).toEqual('foo-a, foo-b');
44 | });
45 | });
46 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/parseHeaders.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import utils from './../utils.js';
4 |
5 | // RawAxiosHeaders whose duplicates are ignored by node
6 | // c.f. https://nodejs.org/api/http.html#http_message_headers
7 | const ignoreDuplicateOf = utils.toObjectSet([
8 | 'age', 'authorization', 'content-length', 'content-type', 'etag',
9 | 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
10 | 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
11 | 'referer', 'retry-after', 'user-agent'
12 | ]);
13 |
14 | /**
15 | * Parse headers into an object
16 | *
17 | * ```
18 | * Date: Wed, 27 Aug 2014 08:58:49 GMT
19 | * Content-Type: application/json
20 | * Connection: keep-alive
21 | * Transfer-Encoding: chunked
22 | * ```
23 | *
24 | * @param {String} rawHeaders Headers needing to be parsed
25 | *
26 | * @returns {Object} Headers parsed into an object
27 | */
28 | export default rawHeaders => {
29 | const parsed = {};
30 | let key;
31 | let val;
32 | let i;
33 |
34 | rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
35 | i = line.indexOf(':');
36 | key = line.substring(0, i).trim().toLowerCase();
37 | val = line.substring(i + 1).trim();
38 |
39 | if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
40 | return;
41 | }
42 |
43 | if (key === 'set-cookie') {
44 | if (parsed[key]) {
45 | parsed[key].push(val);
46 | } else {
47 | parsed[key] = [val];
48 | }
49 | } else {
50 | parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
51 | }
52 | });
53 |
54 | return parsed;
55 | };
56 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/parseHeaders.spec.js:
--------------------------------------------------------------------------------
1 | import parseHeaders from '../../../lib/helpers/parseHeaders';
2 |
3 | describe('helpers::parseHeaders', function () {
4 | it('should parse headers', function () {
5 | const date = new Date();
6 | const parsed = parseHeaders(
7 | 'Date: ' + date.toISOString() + '\n' +
8 | 'Content-Type: application/json\n' +
9 | 'Connection: keep-alive\n' +
10 | 'Transfer-Encoding: chunked'
11 | );
12 |
13 | expect(parsed['date']).toEqual(date.toISOString());
14 | expect(parsed['content-type']).toEqual('application/json');
15 | expect(parsed['connection']).toEqual('keep-alive');
16 | expect(parsed['transfer-encoding']).toEqual('chunked');
17 | });
18 |
19 | it('should use array for set-cookie', function() {
20 | const parsedZero = parseHeaders('');
21 | const parsedSingle = parseHeaders(
22 | 'Set-Cookie: key=val;'
23 | );
24 | const parsedMulti = parseHeaders(
25 | 'Set-Cookie: key=val;\n' +
26 | 'Set-Cookie: key2=val2;\n'
27 | );
28 |
29 | expect(parsedZero['set-cookie']).toBeUndefined();
30 | expect(parsedSingle['set-cookie']).toEqual(['key=val;']);
31 | expect(parsedMulti['set-cookie']).toEqual(['key=val;', 'key2=val2;']);
32 | });
33 |
34 | it('should handle duplicates', function() {
35 | const parsed = parseHeaders(
36 | 'Age: age-a\n' + // age is in ignore duplicates blocklist
37 | 'Age: age-b\n' +
38 | 'Foo: foo-a\n' +
39 | 'Foo: foo-b\n'
40 | );
41 |
42 | expect(parsed['age']).toEqual('age-a');
43 | expect(parsed['foo']).toEqual('foo-a, foo-b');
44 | });
45 | });
46 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/regression/bugs.js:
--------------------------------------------------------------------------------
1 | import assert from 'assert';
2 | import http from 'http';
3 | import axios from '../../../index.js';
4 |
5 | describe('issues', function () {
6 | describe('4999', function () {
7 | it('should not fail with query parsing', async function () {
8 | const {data} = await axios.get('https://postman-echo.com/get?foo1=bar1&foo2=bar2');
9 |
10 | assert.strictEqual(data.args.foo1, 'bar1');
11 | assert.strictEqual(data.args.foo2, 'bar2');
12 | });
13 | });
14 |
15 | describe('5028', function () {
16 | it('should handle set-cookie headers as an array', async function () {
17 | const cookie1 = 'something=else; path=/; expires=Wed, 12 Apr 2023 12:03:42 GMT; samesite=lax; secure; httponly';
18 | const cookie2 = 'something-ssr.sig=n4MlwVAaxQAxhbdJO5XbUpDw-lA; path=/; expires=Wed, 12 Apr 2023 12:03:42 GMT; samesite=lax; secure; httponly';
19 |
20 | const server = http.createServer((req, res) => {
21 | //res.setHeader('Set-Cookie', 'my=value');
22 | res.setHeader('Set-Cookie', [cookie1, cookie2]);
23 | res.writeHead(200);
24 | res.write('Hi there');
25 | res.end();
26 | }).listen(0);
27 |
28 | const request = axios.create();
29 |
30 | request.interceptors.response.use((res) => {
31 | assert.deepStrictEqual(res.headers['set-cookie'], [
32 | cookie1, cookie2
33 | ]);
34 | });
35 |
36 | try {
37 | await request({url: `http://localhost:${server.address().port}`});
38 | } finally {
39 | server.close()
40 | }
41 | });
42 | });
43 | });
44 |
--------------------------------------------------------------------------------
/axios/lib/helpers/cookies.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var utils = require('./../utils');
4 |
5 | module.exports = (
6 | utils.isStandardBrowserEnv() ?
7 |
8 | // Standard browser envs support document.cookie
9 | (function standardBrowserEnv() {
10 | return {
11 | write: function write(name, value, expires, path, domain, secure) {
12 | var cookie = [];
13 | cookie.push(name + '=' + encodeURIComponent(value));
14 |
15 | if (utils.isNumber(expires)) {
16 | cookie.push('expires=' + new Date(expires).toGMTString());
17 | }
18 |
19 | if (utils.isString(path)) {
20 | cookie.push('path=' + path);
21 | }
22 |
23 | if (utils.isString(domain)) {
24 | cookie.push('domain=' + domain);
25 | }
26 |
27 | if (secure === true) {
28 | cookie.push('secure');
29 | }
30 |
31 | document.cookie = cookie.join('; ');
32 | },
33 |
34 | read: function read(name) {
35 | var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
36 | return (match ? decodeURIComponent(match[3]) : null);
37 | },
38 |
39 | remove: function remove(name) {
40 | this.write(name, '', Date.now() - 86400000);
41 | }
42 | };
43 | })() :
44 |
45 | // Non standard browser env (web workers, react-native) lack needed support.
46 | (function nonStandardBrowserEnv() {
47 | return {
48 | write: function write() {},
49 | read: function read() { return null; },
50 | remove: function remove() {}
51 | };
52 | })()
53 | );
54 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/AxiosURLSearchParams.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import toFormData from './toFormData.js';
4 |
5 | /**
6 | * It encodes a string by replacing all characters that are not in the unreserved set with
7 | * their percent-encoded equivalents
8 | *
9 | * @param {string} str - The string to encode.
10 | *
11 | * @returns {string} The encoded string.
12 | */
13 | function encode(str) {
14 | const charMap = {
15 | '!': '%21',
16 | "'": '%27',
17 | '(': '%28',
18 | ')': '%29',
19 | '~': '%7E',
20 | '%20': '+',
21 | '%00': '\x00'
22 | };
23 | return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
24 | return charMap[match];
25 | });
26 | }
27 |
28 | /**
29 | * It takes a params object and converts it to a FormData object
30 | *
31 | * @param {Object} params - The parameters to be converted to a FormData object.
32 | * @param {Object} options - The options object passed to the Axios constructor.
33 | *
34 | * @returns {void}
35 | */
36 | function AxiosURLSearchParams(params, options) {
37 | this._pairs = [];
38 |
39 | params && toFormData(params, this, options);
40 | }
41 |
42 | const prototype = AxiosURLSearchParams.prototype;
43 |
44 | prototype.append = function append(name, value) {
45 | this._pairs.push([name, value]);
46 | };
47 |
48 | prototype.toString = function toString(encoder) {
49 | const _encode = encoder ? function(value) {
50 | return encoder.call(this, value, encode);
51 | } : encode;
52 |
53 | return this._pairs.map(function each(pair) {
54 | return _encode(pair[0]) + '=' + _encode(pair[1]);
55 | }, '').join('&');
56 | };
57 |
58 | export default AxiosURLSearchParams;
59 |
--------------------------------------------------------------------------------
/axios/.github/ISSUE_TEMPLATE/---support-or-usage-question.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: "\U0001F914 Support or Usage Question"
3 | about: Get help using Axios
4 | title: ''
5 | labels: question
6 | assignees: ''
7 |
8 | ---
9 |
10 |
21 |
22 | **Describe the issue**
23 | A clear and concise description of what the issue is.
24 |
25 | **Example Code**
26 | Code snippet to illustrate your question
27 |
28 | ```js
29 | // Example code here
30 | ```
31 |
32 | **Expected behavior, if applicable**
33 | A clear and concise description of what you expected to happen.
34 |
35 | **Environment:**
36 | - Axios Version [e.g. 0.18.0]
37 | - OS: [e.g. iOS 12.1.0, OSX 10.13.4]
38 | - Browser [e.g. Chrome, Safari]
39 | - Browser Version [e.g. 22]
40 | - Additional Library Versions [e.g. React 16.7, React Native 0.58.0]
41 |
42 | **Additional context/Screenshots**
43 | Add any other context about the problem here. If applicable, add screenshots to help explain.
44 |
--------------------------------------------------------------------------------
/axios/examples/transform-response/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - transform response example
5 |
6 |
7 |
8 | transformResponse
9 |
10 |
11 |
![]()
12 |
13 |
14 | Created:
15 | Updated:
16 |
17 |
18 |
19 |
20 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/axios/examples/upload/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - file upload example
5 |
6 |
7 |
8 | file upload
9 |
10 |
17 |
18 |
19 |
20 |
21 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/transform-response/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - transform response example
5 |
6 |
7 |
8 | transformResponse
9 |
10 |
11 |
![]()
12 |
13 |
14 | Created:
15 | Updated:
16 |
17 |
18 |
19 |
20 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/axios-v1.x/examples/upload/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | axios - file upload example
5 |
6 |
7 |
8 | file upload
9 |
10 |
17 |
18 |
19 |
20 |
21 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/platform/common/utils.js:
--------------------------------------------------------------------------------
1 | const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
2 |
3 | /**
4 | * Determine if we're running in a standard browser environment
5 | *
6 | * This allows axios to run in a web worker, and react-native.
7 | * Both environments support XMLHttpRequest, but not fully standard globals.
8 | *
9 | * web workers:
10 | * typeof window -> undefined
11 | * typeof document -> undefined
12 | *
13 | * react-native:
14 | * navigator.product -> 'ReactNative'
15 | * nativescript
16 | * navigator.product -> 'NativeScript' or 'NS'
17 | *
18 | * @returns {boolean}
19 | */
20 | const hasStandardBrowserEnv = (
21 | (product) => {
22 | return hasBrowserEnv && ['ReactNative', 'NativeScript', 'NS'].indexOf(product) < 0
23 | })(typeof navigator !== 'undefined' && navigator.product);
24 |
25 | /**
26 | * Determine if we're running in a standard browser webWorker environment
27 | *
28 | * Although the `isStandardBrowserEnv` method indicates that
29 | * `allows axios to run in a web worker`, the WebWorker will still be
30 | * filtered out due to its judgment standard
31 | * `typeof window !== 'undefined' && typeof document !== 'undefined'`.
32 | * This leads to a problem when axios post `FormData` in webWorker
33 | */
34 | const hasStandardBrowserWebWorkerEnv = (() => {
35 | return (
36 | typeof WorkerGlobalScope !== 'undefined' &&
37 | // eslint-disable-next-line no-undef
38 | self instanceof WorkerGlobalScope &&
39 | typeof self.importScripts === 'function'
40 | );
41 | })();
42 |
43 | const origin = hasBrowserEnv && window.location.href || 'http://localhost';
44 |
45 | export {
46 | hasBrowserEnv,
47 | hasStandardBrowserWebWorkerEnv,
48 | hasStandardBrowserEnv,
49 | origin
50 | }
51 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/adapters/key.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN RSA PRIVATE KEY-----
2 | MIIEogIBAAKCAQEA+joLfff3WdFIGwrlVdUWfZ9vDr9w86yQpI6Xq0KF6JiKtxa+
3 | EVCNWtq8Ht5rZd1MxNSFWVb1jxnRLBEB8F3wLD/4xRk8CNxw8joXKsxUEirI76iV
4 | mJDjm/tq90gaxZUWVtPZP95Qvocdl7brhuvLuF4J9wJVL5tr6ZYAje3omHBnjcFb
5 | n9nh3Tqk0U6omAmS4k/BrXWDA1zq8LBmbP41CnfVNGq/5asDIZsNO8s5VQzNjFjN
6 | rcqv2rEO0n+77qDBbqALQydxPmytZP+0jYXcj+EaJ4clApFhvps6Cg0taoF66E4k
7 | Eg1JLALzgk3I/ATSE3nvi3J/RWkyjSYiolPavwIDAQABAoIBAEbMi5ndwjfAlkVI
8 | hPEPNKjgpnymwB/CEL7utY04akkQeBcrsSWXBBfT0exuBDczMVhzxTMs/pe5t0xf
9 | l4vaGG18wDeMV0cukCqJMyrh21u0jVv5+DHNtQjaTz6eQSzsbQCuOkbu8SuncUEO
10 | +X8YUnDc8rbYCyBIOnVCAvAlg201uW0G5G9NEwJOu6cAKMKkogdHqv+FRX96C5hm
11 | gtbGEzpGV2vVClgMwMcX49ucluZvqLvit/yehNVd0VOtW/kuLup4R6q0abHRapDd
12 | 95rJAhPvar4mzP+UgJrGQ9hozqhizDthBjnsmGeMBUiBCkay7OXIZpvLoCpQkti1
13 | WIWuikkCgYEA/oZqq71RT1nPuI7rlcjx3AeWe2EUQtKhQMJBiPx5eLLP6gII8+v2
14 | pD1qlmJM2eyIK0lzuskLIulTAA5Z+ejORDbvmn/DdT0CSvdrUFrcvnrRQnt2M5M2
15 | 9VDRp6nvPE0H4kRZJrtITyLn0dv5ABf2L32i4dPCMePjKjSUygJSHrsCgYEA+61A
16 | cIqch/lrQTk8hG7Y6p0EJzSInFVaKuZoMYpLhlDQcVvSDIQbGgRAN6BKTdxeQ+tK
17 | hSxBSm2mze11aHig8GBGgdBFLaJOZRo6G+2fl+s1t1FCHfsaFhHwheZJONHMpKKd
18 | Qm/7L/V35QV9YG0lPZ01TM6d5lXuKsmUNvBJTc0CgYASYajAgGqn3WeX/5JZ/eoh
19 | ptaiUG+DJ+0HXUAYYYtwQRGs57q3yvnEAL963tyH/IIVBjf6bFyGh+07ms26s6p5
20 | 2LHTKZj3FZHd0iKI6hb5FquYLoxpyx7z9oM9pZMmerWwDJmXp3zgYjf1uvovnItm
21 | AJ/LyVxD+B5GxQdd028U0wKBgG4OllZglxDzJk7wa6FyI9N89Fr8oxzSSkrmVPwN
22 | APfskSpxP8qPXpai8z4gDz47NtG2q/DOqIKWrtHwnF4iGibjwxFzdTz+dA/MR0r9
23 | P8QcbHIMy7/2lbK/B5JWYQDC5h28qs5pz8tqKZLyMqCfOiDWhX9f/zbBrxPw8KqR
24 | q0ylAoGAL/0kemA/Tmxpwmp0S0oCqnA4gbCgS7qnApxB09xTewc/tuvraXc3Mzea
25 | EvqDXLXK0R7O4E3vo0Mr23SodRVlFPevsmUUJLPJMJcxdfnSJgX+qE/UC8Ux+UMi
26 | eYufYRDYSslfL2rt9D7abnnbqSfsHymJKukWpElIgJTklQUru4k=
27 | -----END RSA PRIVATE KEY-----
28 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 |
15 |
16 | #### Summary
17 |
18 | Describe your issue here, including as much detail as necessary.
19 |
20 | If you're reporting a bug, include the relevant code and stack traces to debug it (removing any private information).
21 |
22 | If you're requesting a feature, include some context and examples of code using it.
23 |
24 | #### Environment
25 | - Axios Version [e.g. 0.18.0]
26 | - Adapter [e.g. XHR/HTTP]
27 | - Browser [e.g. Chrome, Safari]
28 | - Browser Version [e.g. 22]
29 | - Node.js Version [e.g. 13.0.1]
30 | - OS: [e.g. iOS 12.1.0, OSX 10.13.4]
31 | - Additional Library Versions [e.g. React 16.7, React Native 0.58.0]
32 |
--------------------------------------------------------------------------------
/axios/lib/axios.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var utils = require('./utils');
4 | var bind = require('./helpers/bind');
5 | var Axios = require('./core/Axios');
6 | var mergeConfig = require('./core/mergeConfig');
7 | var defaults = require('./defaults');
8 |
9 | /**
10 | * Create an instance of Axios
11 | *
12 | * @param {Object} defaultConfig The default config for the instance
13 | * @return {Axios} A new instance of Axios
14 | */
15 | function createInstance(defaultConfig) {
16 | var context = new Axios(defaultConfig);
17 | var instance = bind(Axios.prototype.request, context);
18 |
19 | // Copy axios.prototype to instance
20 | utils.extend(instance, Axios.prototype, context);
21 |
22 | // Copy context to instance
23 | utils.extend(instance, context);
24 |
25 | return instance;
26 | }
27 |
28 | // Create the default instance to be exported
29 | // 导出 创建默认实例
30 | var axios = createInstance(defaults);
31 |
32 | // Expose Axios class to allow class inheritance
33 | // 暴露 Axios calss 允许 class 继承
34 | axios.Axios = Axios;
35 |
36 | // Factory for creating new instances
37 | // 工厂模式 创建新的实例 用户可以自定义一些参数
38 | axios.create = function create(instanceConfig) {
39 | return createInstance(mergeConfig(axios.defaults, instanceConfig));
40 | };
41 |
42 | // Expose Cancel & CancelToken
43 | // 导出 Cancel 和 CancelToken
44 | axios.Cancel = require('./cancel/Cancel');
45 | axios.CancelToken = require('./cancel/CancelToken');
46 | axios.isCancel = require('./cancel/isCancel');
47 |
48 | // Expose all/spread
49 | // 导出 all 和 spread API
50 | axios.all = function all(promises) {
51 | return Promise.all(promises);
52 | };
53 | axios.spread = require('./helpers/spread');
54 |
55 | module.exports = axios;
56 |
57 | // Allow use of default import syntax in TypeScript
58 | // 也就是可以以下方式引入
59 | // import axios from 'axios';
60 | module.exports.default = axios;
61 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/buildURL.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import utils from '../utils.js';
4 | import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
5 |
6 | /**
7 | * It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
8 | * URI encoded counterparts
9 | *
10 | * @param {string} val The value to be encoded.
11 | *
12 | * @returns {string} The encoded value.
13 | */
14 | function encode(val) {
15 | return encodeURIComponent(val).
16 | replace(/%3A/gi, ':').
17 | replace(/%24/g, '$').
18 | replace(/%2C/gi, ',').
19 | replace(/%20/g, '+').
20 | replace(/%5B/gi, '[').
21 | replace(/%5D/gi, ']');
22 | }
23 |
24 | /**
25 | * Build a URL by appending params to the end
26 | *
27 | * @param {string} url The base of the url (e.g., http://www.google.com)
28 | * @param {object} [params] The params to be appended
29 | * @param {?object} options
30 | *
31 | * @returns {string} The formatted url
32 | */
33 | export default function buildURL(url, params, options) {
34 | /*eslint no-param-reassign:0*/
35 | if (!params) {
36 | return url;
37 | }
38 |
39 | const _encode = options && options.encode || encode;
40 |
41 | const serializeFn = options && options.serialize;
42 |
43 | let serializedParams;
44 |
45 | if (serializeFn) {
46 | serializedParams = serializeFn(params, options);
47 | } else {
48 | serializedParams = utils.isURLSearchParams(params) ?
49 | params.toString() :
50 | new AxiosURLSearchParams(params, options).toString(_encode);
51 | }
52 |
53 | if (serializedParams) {
54 | const hashmarkIndex = url.indexOf("#");
55 |
56 | if (hashmarkIndex !== -1) {
57 | url = url.slice(0, hashmarkIndex);
58 | }
59 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
60 | }
61 |
62 | return url;
63 | }
64 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/core/InterceptorManager.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import utils from './../utils.js';
4 |
5 | class InterceptorManager {
6 | constructor() {
7 | this.handlers = [];
8 | }
9 |
10 | /**
11 | * Add a new interceptor to the stack
12 | *
13 | * @param {Function} fulfilled The function to handle `then` for a `Promise`
14 | * @param {Function} rejected The function to handle `reject` for a `Promise`
15 | *
16 | * @return {Number} An ID used to remove interceptor later
17 | */
18 | use(fulfilled, rejected, options) {
19 | this.handlers.push({
20 | fulfilled,
21 | rejected,
22 | synchronous: options ? options.synchronous : false,
23 | runWhen: options ? options.runWhen : null
24 | });
25 | return this.handlers.length - 1;
26 | }
27 |
28 | /**
29 | * Remove an interceptor from the stack
30 | *
31 | * @param {Number} id The ID that was returned by `use`
32 | *
33 | * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
34 | */
35 | eject(id) {
36 | if (this.handlers[id]) {
37 | this.handlers[id] = null;
38 | }
39 | }
40 |
41 | /**
42 | * Clear all interceptors from the stack
43 | *
44 | * @returns {void}
45 | */
46 | clear() {
47 | if (this.handlers) {
48 | this.handlers = [];
49 | }
50 | }
51 |
52 | /**
53 | * Iterate over all the registered interceptors
54 | *
55 | * This method is particularly useful for skipping over any
56 | * interceptors that may have become `null` calling `eject`.
57 | *
58 | * @param {Function} fn The function to call for each interceptor
59 | *
60 | * @returns {void}
61 | */
62 | forEach(fn) {
63 | utils.forEach(this.handlers, function forEachHandler(h) {
64 | if (h !== null) {
65 | fn(h);
66 | }
67 | });
68 | }
69 | }
70 |
71 | export default InterceptorManager;
72 |
--------------------------------------------------------------------------------
/axios/test/specs/promise.spec.js:
--------------------------------------------------------------------------------
1 | describe('promise', function () {
2 | beforeEach(function () {
3 | jasmine.Ajax.install();
4 | });
5 |
6 | afterEach(function () {
7 | jasmine.Ajax.uninstall();
8 | });
9 |
10 | it('should provide succinct object to then', function (done) {
11 | var response;
12 |
13 | axios('/foo').then(function (r) {
14 | response = r;
15 | });
16 |
17 | getAjaxRequest().then(function (request) {
18 | request.respondWith({
19 | status: 200,
20 | responseText: '{"hello":"world"}'
21 | });
22 |
23 | setTimeout(function () {
24 | expect(typeof response).toEqual('object');
25 | expect(response.data.hello).toEqual('world');
26 | expect(response.status).toEqual(200);
27 | expect(response.headers['content-type']).toEqual('application/json');
28 | expect(response.config.url).toEqual('/foo');
29 | done();
30 | }, 100);
31 | });
32 | });
33 |
34 | it('should support all', function (done) {
35 | var fulfilled = false;
36 |
37 | axios.all([true, 123]).then(function () {
38 | fulfilled = true;
39 | });
40 |
41 | setTimeout(function () {
42 | expect(fulfilled).toEqual(true);
43 | done();
44 | }, 100);
45 | });
46 |
47 | it('should support spread', function (done) {
48 | var sum = 0;
49 | var fulfilled = false;
50 | var result;
51 |
52 | axios
53 | .all([123, 456])
54 | .then(axios.spread(function (a, b) {
55 | sum = a + b;
56 | fulfilled = true;
57 | return 'hello world';
58 | }))
59 | .then(function (res) {
60 | result = res;
61 | });
62 |
63 | setTimeout(function () {
64 | expect(fulfilled).toEqual(true);
65 | expect(sum).toEqual(123 + 456);
66 | expect(result).toEqual('hello world');
67 | done();
68 | }, 100);
69 | });
70 | });
71 |
--------------------------------------------------------------------------------
/axios-v1.x/lib/helpers/HttpStatusCode.js:
--------------------------------------------------------------------------------
1 | const HttpStatusCode = {
2 | Continue: 100,
3 | SwitchingProtocols: 101,
4 | Processing: 102,
5 | EarlyHints: 103,
6 | Ok: 200,
7 | Created: 201,
8 | Accepted: 202,
9 | NonAuthoritativeInformation: 203,
10 | NoContent: 204,
11 | ResetContent: 205,
12 | PartialContent: 206,
13 | MultiStatus: 207,
14 | AlreadyReported: 208,
15 | ImUsed: 226,
16 | MultipleChoices: 300,
17 | MovedPermanently: 301,
18 | Found: 302,
19 | SeeOther: 303,
20 | NotModified: 304,
21 | UseProxy: 305,
22 | Unused: 306,
23 | TemporaryRedirect: 307,
24 | PermanentRedirect: 308,
25 | BadRequest: 400,
26 | Unauthorized: 401,
27 | PaymentRequired: 402,
28 | Forbidden: 403,
29 | NotFound: 404,
30 | MethodNotAllowed: 405,
31 | NotAcceptable: 406,
32 | ProxyAuthenticationRequired: 407,
33 | RequestTimeout: 408,
34 | Conflict: 409,
35 | Gone: 410,
36 | LengthRequired: 411,
37 | PreconditionFailed: 412,
38 | PayloadTooLarge: 413,
39 | UriTooLong: 414,
40 | UnsupportedMediaType: 415,
41 | RangeNotSatisfiable: 416,
42 | ExpectationFailed: 417,
43 | ImATeapot: 418,
44 | MisdirectedRequest: 421,
45 | UnprocessableEntity: 422,
46 | Locked: 423,
47 | FailedDependency: 424,
48 | TooEarly: 425,
49 | UpgradeRequired: 426,
50 | PreconditionRequired: 428,
51 | TooManyRequests: 429,
52 | RequestHeaderFieldsTooLarge: 431,
53 | UnavailableForLegalReasons: 451,
54 | InternalServerError: 500,
55 | NotImplemented: 501,
56 | BadGateway: 502,
57 | ServiceUnavailable: 503,
58 | GatewayTimeout: 504,
59 | HttpVersionNotSupported: 505,
60 | VariantAlsoNegotiates: 506,
61 | InsufficientStorage: 507,
62 | LoopDetected: 508,
63 | NotExtended: 510,
64 | NetworkAuthenticationRequired: 511,
65 | };
66 |
67 | Object.entries(HttpStatusCode).forEach(([key, value]) => {
68 | HttpStatusCode[value] = key;
69 | });
70 |
71 | export default HttpStatusCode;
72 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/promise.spec.js:
--------------------------------------------------------------------------------
1 | describe('promise', function () {
2 | beforeEach(function () {
3 | jasmine.Ajax.install();
4 | });
5 |
6 | afterEach(function () {
7 | jasmine.Ajax.uninstall();
8 | });
9 |
10 | it('should provide succinct object to then', function (done) {
11 | let response;
12 |
13 | axios('/foo').then(function (r) {
14 | response = r;
15 | });
16 |
17 | getAjaxRequest().then(function (request) {
18 | request.respondWith({
19 | status: 200,
20 | responseText: '{"hello":"world"}'
21 | });
22 |
23 | setTimeout(function () {
24 | expect(typeof response).toEqual('object');
25 | expect(response.data.hello).toEqual('world');
26 | expect(response.status).toEqual(200);
27 | expect(response.headers['content-type']).toEqual('application/json');
28 | expect(response.config.url).toEqual('/foo');
29 | done();
30 | }, 100);
31 | });
32 | });
33 |
34 | it('should support all', function (done) {
35 | let fulfilled = false;
36 |
37 | axios.all([true, 123]).then(function () {
38 | fulfilled = true;
39 | });
40 |
41 | setTimeout(function () {
42 | expect(fulfilled).toEqual(true);
43 | done();
44 | }, 100);
45 | });
46 |
47 | it('should support spread', function (done) {
48 | let sum = 0;
49 | let fulfilled = false;
50 | let result;
51 |
52 | axios
53 | .all([123, 456])
54 | .then(axios.spread(function (a, b) {
55 | sum = a + b;
56 | fulfilled = true;
57 | return 'hello world';
58 | }))
59 | .then(function (res) {
60 | result = res;
61 | }).catch(done);
62 |
63 | setTimeout(function () {
64 | expect(fulfilled).toEqual(true);
65 | expect(sum).toEqual(123 + 456);
66 | expect(result).toEqual('hello world');
67 | done();
68 | }, 100);
69 | });
70 | });
71 |
--------------------------------------------------------------------------------
/axios/test/specs/utils/deepMerge.spec.js:
--------------------------------------------------------------------------------
1 | var deepMerge = require('../../../lib/utils').deepMerge;
2 |
3 | describe('utils::deepMerge', function () {
4 | it('should be immutable', function () {
5 | var a = {};
6 | var b = {foo: 123};
7 | var c = {bar: 456};
8 |
9 | deepMerge(a, b, c);
10 |
11 | expect(typeof a.foo).toEqual('undefined');
12 | expect(typeof a.bar).toEqual('undefined');
13 | expect(typeof b.bar).toEqual('undefined');
14 | expect(typeof c.foo).toEqual('undefined');
15 | });
16 |
17 | it('should deepMerge properties', function () {
18 | var a = {foo: 123};
19 | var b = {bar: 456};
20 | var c = {foo: 789};
21 | var d = deepMerge(a, b, c);
22 |
23 | expect(d.foo).toEqual(789);
24 | expect(d.bar).toEqual(456);
25 | });
26 |
27 | it('should deepMerge recursively', function () {
28 | var a = {foo: {bar: 123}};
29 | var b = {foo: {baz: 456}, bar: {qux: 789}};
30 |
31 | expect(deepMerge(a, b)).toEqual({
32 | foo: {
33 | bar: 123,
34 | baz: 456
35 | },
36 | bar: {
37 | qux: 789
38 | }
39 | });
40 | });
41 |
42 | it('should remove all references from nested objects', function () {
43 | var a = {foo: {bar: 123}};
44 | var b = {};
45 | var d = deepMerge(a, b);
46 |
47 | expect(d).toEqual({
48 | foo: {
49 | bar: 123
50 | }
51 | });
52 |
53 | expect(d.foo).not.toBe(a.foo);
54 | });
55 |
56 | it('handles null and undefined arguments', function () {
57 | expect(deepMerge(undefined, undefined)).toEqual({});
58 | expect(deepMerge(undefined, {foo: 123})).toEqual({foo: 123});
59 | expect(deepMerge({foo: 123}, undefined)).toEqual({foo: 123});
60 |
61 | expect(deepMerge(null, null)).toEqual({});
62 | expect(deepMerge(null, {foo: 123})).toEqual({foo: 123});
63 | expect(deepMerge({foo: 123}, null)).toEqual({foo: 123});
64 | });
65 | });
66 |
67 |
--------------------------------------------------------------------------------
/axios/.github/ISSUE_TEMPLATE/---bug-report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: "\U0001F41E Bug Report"
3 | about: Report a reproducible bug
4 | title: ''
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 |
21 |
22 | **Describe the bug**
23 | A clear and concise description of what the bug is. **If your problem is not a bug, please file under Support or Usage Question**
24 |
25 | **To Reproduce**
26 | Code snippet to reproduce, ideally that will work by pasting into something like https://npm.runkit.com/axios, a hosted solution, or a repository that illustrates the issue. **If your problem is not reproducible, please file under Support or Usage Question**
27 |
28 | ```js
29 | // Example code here
30 | ```
31 |
32 | **Expected behavior**
33 | A clear and concise description of what you expected to happen.
34 |
35 | **Environment:**
36 | - Axios Version [e.g. 0.18.0]
37 | - OS: [e.g. iOS 12.1.0, OSX 10.13.4]
38 | - Browser [e.g. Chrome, Safari]
39 | - Browser Version [e.g. 22]
40 | - Additional Library Versions [e.g. React 16.7, React Native 0.58.0]
41 |
42 | **Additional context/Screenshots**
43 | Add any other context about the problem here. If applicable, add screenshots to help explain.
44 |
--------------------------------------------------------------------------------
/axios/sandbox/server.js:
--------------------------------------------------------------------------------
1 | var fs = require('fs');
2 | var url = require('url');
3 | var path = require('path');
4 | var http = require('http');
5 | var server;
6 |
7 | function pipeFileToResponse(res, file, type) {
8 | if (type) {
9 | res.writeHead(200, {
10 | 'Content-Type': type
11 | });
12 | }
13 |
14 | fs.createReadStream(path.join(__dirname, file)).pipe(res);
15 | }
16 |
17 | server = http.createServer(function (req, res) {
18 | req.setEncoding('utf8');
19 |
20 | var parsed = url.parse(req.url, true);
21 | var pathname = parsed.pathname;
22 |
23 | console.log('[' + new Date() + ']', req.method, pathname);
24 |
25 | if (pathname === '/') {
26 | pathname = '/index.html';
27 | }
28 |
29 | if (pathname === '/index.html') {
30 | pipeFileToResponse(res, './client.html');
31 | } else if (pathname === '/axios.js') {
32 | pipeFileToResponse(res, '../dist/axios.js', 'text/javascript');
33 | } else if (pathname === '/axios.map') {
34 | pipeFileToResponse(res, '../dist/axios.map', 'text/javascript');
35 | } else if (pathname === '/api') {
36 | var status;
37 | var result;
38 | var data = '';
39 |
40 | req.on('data', function (chunk) {
41 | data += chunk;
42 | });
43 |
44 | req.on('end', function () {
45 | try {
46 | status = 200;
47 | result = {
48 | url: req.url,
49 | data: data ? JSON.parse(data) : undefined,
50 | method: req.method,
51 | headers: req.headers
52 | };
53 | } catch (e) {
54 | console.error('Error:', e.message);
55 | status = 400;
56 | result = {
57 | error: e.message
58 | };
59 | }
60 |
61 | res.writeHead(status, {
62 | 'Content-Type': 'application/json'
63 | });
64 | res.end(JSON.stringify(result));
65 | });
66 | } else {
67 | res.writeHead(404);
68 | res.end('404 Not Found
');
69 | }
70 | });
71 |
72 | server.listen(3000);
--------------------------------------------------------------------------------
/axios/lib/helpers/buildURL.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var utils = require('./../utils');
4 |
5 | function encode(val) {
6 | return encodeURIComponent(val).
7 | replace(/%40/gi, '@').
8 | replace(/%3A/gi, ':').
9 | replace(/%24/g, '$').
10 | replace(/%2C/gi, ',').
11 | replace(/%20/g, '+').
12 | replace(/%5B/gi, '[').
13 | replace(/%5D/gi, ']');
14 | }
15 |
16 | /**
17 | * Build a URL by appending params to the end
18 | *
19 | * @param {string} url The base of the url (e.g., http://www.google.com)
20 | * @param {object} [params] The params to be appended
21 | * @returns {string} The formatted url
22 | */
23 | module.exports = function buildURL(url, params, paramsSerializer) {
24 | /*eslint no-param-reassign:0*/
25 | if (!params) {
26 | return url;
27 | }
28 |
29 | var serializedParams;
30 | if (paramsSerializer) {
31 | serializedParams = paramsSerializer(params);
32 | } else if (utils.isURLSearchParams(params)) {
33 | serializedParams = params.toString();
34 | } else {
35 | var parts = [];
36 |
37 | utils.forEach(params, function serialize(val, key) {
38 | if (val === null || typeof val === 'undefined') {
39 | return;
40 | }
41 |
42 | if (utils.isArray(val)) {
43 | key = key + '[]';
44 | } else {
45 | val = [val];
46 | }
47 |
48 | utils.forEach(val, function parseValue(v) {
49 | if (utils.isDate(v)) {
50 | v = v.toISOString();
51 | } else if (utils.isObject(v)) {
52 | v = JSON.stringify(v);
53 | }
54 | parts.push(encode(key) + '=' + encode(v));
55 | });
56 | });
57 |
58 | serializedParams = parts.join('&');
59 | }
60 |
61 | if (serializedParams) {
62 | var hashmarkIndex = url.indexOf('#');
63 | if (hashmarkIndex !== -1) {
64 | url = url.slice(0, hashmarkIndex);
65 | }
66 |
67 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
68 | }
69 |
70 | return url;
71 | };
72 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/regression/SNYK-JS-AXIOS-1038255.js:
--------------------------------------------------------------------------------
1 | // https://snyk.io/vuln/SNYK-JS-AXIOS-1038255
2 | // https://github.com/axios/axios/issues/3407
3 | // https://github.com/axios/axios/issues/3369
4 |
5 | import axios from '../../../index.js';
6 | import http from 'http';
7 | import assert from 'assert';
8 |
9 | const PROXY_PORT = 4777;
10 | const EVIL_PORT = 4666;
11 |
12 |
13 | describe('Server-Side Request Forgery (SSRF)', () => {
14 | let fail = false;
15 | let proxy;
16 | let server;
17 | let location;
18 | beforeEach(() => {
19 | server = http.createServer(function (req, res) {
20 | fail = true;
21 | res.end('rm -rf /');
22 | }).listen(EVIL_PORT);
23 |
24 | proxy = http.createServer(function (req, res) {
25 | if (new URL(req.url, 'http://' + req.headers.host).toString() === 'http://localhost:' + EVIL_PORT + '/') {
26 | return res.end(JSON.stringify({
27 | msg: 'Protected',
28 | headers: req.headers,
29 | }));
30 | }
31 | res.writeHead(302, { location })
32 | res.end()
33 | }).listen(PROXY_PORT);
34 | });
35 | afterEach(() => {
36 | server.close();
37 | proxy.close();
38 | });
39 |
40 | it('obeys proxy settings when following redirects', async () => {
41 | location = 'http://localhost:' + EVIL_PORT;
42 |
43 | let response = await axios({
44 | method: "get",
45 | url: "http://www.google.com/",
46 | proxy: {
47 | host: "localhost",
48 | port: PROXY_PORT,
49 | auth: {
50 | username: 'sam',
51 | password: 'password',
52 | }
53 | },
54 | });
55 |
56 | assert.strictEqual(fail, false);
57 | assert.strictEqual(response.data.msg, 'Protected');
58 | assert.strictEqual(response.data.headers.host, 'localhost:' + EVIL_PORT);
59 | assert.strictEqual(response.data.headers['proxy-authorization'], 'Basic ' + Buffer.from('sam:password').toString('base64'));
60 |
61 | return response;
62 |
63 | });
64 | });
65 |
--------------------------------------------------------------------------------
/axios-v1.x/test/specs/helpers/formDataToJSON.spec.js:
--------------------------------------------------------------------------------
1 | import formDataToJSON from '../../../lib/helpers/formDataToJSON';
2 |
3 | describe('formDataToJSON', function () {
4 | it('should convert a FormData Object to JSON Object', function () {
5 | const formData = new FormData();
6 |
7 | formData.append('foo[bar][baz]', '123');
8 |
9 | expect(formDataToJSON(formData)).toEqual({
10 | foo: {
11 | bar: {
12 | baz: '123'
13 | }
14 | }
15 | });
16 | });
17 |
18 | it('should convert repeatable values as an array', function () {
19 | const formData = new FormData();
20 |
21 | formData.append('foo', '1');
22 | formData.append('foo', '2');
23 |
24 | expect(formDataToJSON(formData)).toEqual({
25 | foo: ['1', '2']
26 | });
27 | });
28 |
29 | it('should convert props with empty brackets to arrays', function () {
30 | const formData = new FormData();
31 |
32 | formData.append('foo[]', '1');
33 | formData.append('foo[]', '2');
34 |
35 | expect(formDataToJSON(formData)).toEqual({
36 | foo: ['1', '2']
37 | });
38 | });
39 |
40 | it('should supported indexed arrays', function () {
41 | const formData = new FormData();
42 |
43 | formData.append('foo[0]', '1');
44 | formData.append('foo[1]', '2');
45 |
46 | expect(formDataToJSON(formData)).toEqual({
47 | foo: ['1', '2']
48 | });
49 | });
50 |
51 | it('should resist prototype pollution CVE', () => {
52 | const formData = new FormData();
53 |
54 | formData.append('foo[0]', '1');
55 | formData.append('foo[1]', '2');
56 | formData.append('__proto__.x', 'hack');
57 | formData.append('constructor.prototype.y', 'value');
58 |
59 | expect(formDataToJSON(formData)).toEqual({
60 | foo: ['1', '2'],
61 | constructor: {
62 | prototype: {
63 | y: 'value'
64 | }
65 | }
66 | });
67 |
68 | expect({}.x).toEqual(undefined);
69 | expect({}.y).toEqual(undefined);
70 | });
71 | });
72 |
--------------------------------------------------------------------------------
/axios-v1.x/bin/pr.js:
--------------------------------------------------------------------------------
1 | import util from "util";
2 | import cp from "child_process";
3 | import Handlebars from "handlebars";
4 | import fs from "fs/promises";
5 | import prettyBytes from 'pretty-bytes';
6 | import {gzipSize} from 'gzip-size';
7 |
8 | const exec = util.promisify(cp.exec);
9 |
10 | const getBlobHistory = async (filepath, maxCount= 5) => {
11 | const log = (await exec(
12 | `git log --max-count=${maxCount} --no-walk --tags=v* --oneline --format=%H%d -- ${filepath}`
13 | )).stdout;
14 |
15 | const commits = [];
16 |
17 | let match;
18 |
19 | const regexp = /^(\w+) \(tag: (v?[.\d]+)\)$/gm;
20 |
21 | while((match = regexp.exec(log))) {
22 | commits.push({
23 | sha: match[1],
24 | tag: match[2],
25 | size: await getBlobSize(filepath, match[1])
26 | })
27 | }
28 |
29 | return commits;
30 | }
31 |
32 | const getBlobSize = async (filepath, sha ='HEAD') => {
33 | const size = (await exec(
34 | `git cat-file -s ${sha}:${filepath}`
35 | )).stdout;
36 |
37 | return size ? +size : 0;
38 | }
39 |
40 | const generateFileReport = async (files) => {
41 | const stat = {};
42 |
43 | for(const [name, file] of Object.entries(files)) {
44 | const commits = await getBlobHistory(file);
45 |
46 | stat[file] = {
47 | name,
48 | size: (await fs.stat(file)).size,
49 | path: file,
50 | gzip: await gzipSize(String(await fs.readFile(file))),
51 | commits,
52 | history: commits.map(({tag, size}) => `${prettyBytes(size)} (${tag})`).join(' ← ')
53 | }
54 | }
55 |
56 | return stat;
57 | }
58 |
59 | const generateBody = async ({files, template = './templates/pr.hbs'} = {}) => {
60 | const data = {
61 | files: await generateFileReport(files)
62 | };
63 |
64 | Handlebars.registerHelper('filesize', (bytes)=> prettyBytes(bytes));
65 |
66 | return Handlebars.compile(String(await fs.readFile(template)))(data);
67 | }
68 |
69 | console.log(await generateBody({
70 | files: {
71 | 'Browser build (UMD)' : './dist/axios.min.js',
72 | 'Browser build (ESM)' : './dist/esm/axios.min.js',
73 | }
74 | }));
75 |
76 |
--------------------------------------------------------------------------------
/axios/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We are open to, and grateful for, any contributions made by the community. By contributing to axios, you agree to abide by the [code of conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md).
4 |
5 | ### Code Style
6 |
7 | Please follow the [node style guide](https://github.com/felixge/node-style-guide).
8 |
9 | ### Commit Messages
10 |
11 | Commit messages should be verb based, using the following pattern:
12 |
13 | - `Fixing ...`
14 | - `Adding ...`
15 | - `Updating ...`
16 | - `Removing ...`
17 |
18 | ### Testing
19 |
20 | Please update the tests to reflect your code changes. Pull requests will not be accepted if they are failing on [Travis CI](https://travis-ci.org/axios/axios).
21 |
22 | ### Documentation
23 |
24 | Please update the [docs](README.md) accordingly so that there are no discrepancies between the API and the documentation.
25 |
26 | ### Developing
27 |
28 | - `grunt test` run the jasmine and mocha tests
29 | - `grunt build` run webpack and bundle the source
30 | - `grunt version` prepare the code for release
31 | - `grunt watch:test` watch for changes and run `test`
32 | - `grunt watch:build` watch for changes and run `build`
33 |
34 | Please don't include changes to `dist/` in your pull request. This should only be updated when releasing a new version.
35 |
36 | ### Releasing
37 |
38 | Releasing a new version is mostly automated. For now the [CHANGELOG](https://github.com/axios/axios/blob/master/CHANGELOG.md) requires being updated manually. Once this has been done run the commands below. Versions should follow [semantic versioning](http://semver.org/).
39 |
40 | - `npm version -m "Releasing %s"`
41 | - `npm publish`
42 |
43 | ### Running Examples
44 |
45 | Examples are included in part to allow manual testing.
46 |
47 | Running example
48 |
49 | ```bash
50 | $ npm run examples
51 | # Open 127.0.0.1:3000
52 | ```
53 |
54 | Running sandbox in browser
55 |
56 | ```bash
57 | $ npm start
58 | # Open 127.0.0.1:3000
59 | ```
60 |
61 | Running sandbox in terminal
62 |
63 | ```bash
64 | $ npm start
65 | $ node ./sandbox/client
66 | ```
67 |
--------------------------------------------------------------------------------
/axios-v1.x/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml:
--------------------------------------------------------------------------------
1 | name: '✨ Feature Request'
2 | description: Suggest an idea or feature.
3 | labels: ['feature']
4 | body:
5 | - type: markdown
6 | attributes:
7 | value: 'Please read and follow the instructions before submitting an issue:'
8 | - type: markdown
9 | attributes:
10 | value: |
11 | - Read all our documentation, especially the [README](https://github.com/axios/axios/blob/master/README.md). It may contain information that helps you solve your issue.
12 | - Ensure your issue isn't already [reported](https://github.com/axios/axios/issues?utf8=%E2%9C%93&q=is%3Aissue).
13 | - If you aren't sure that the issue is caused by Axios or you just need help, please use [Stack Overflow](https://stackoverflow.com/questions/tagged/axios) or [our chat](https://gitter.im/mzabriskie/axios).
14 | - type: markdown
15 | attributes:
16 | value: '⚠️👆 Feel free to these instructions before submitting the issue 👆⚠️'
17 | - type: textarea
18 | id: description
19 | attributes:
20 | label: 'Is your feature request related to a problem? Please describe.'
21 | description: A clear and concise description of what the problem is.
22 | placeholder: I'm always frustrated when [...]
23 | validations:
24 | required: true
25 | - type: textarea
26 | id: solution
27 | attributes:
28 | label: Describe the solution you'd like
29 | description: A clear and concise description of what you want to happen.
30 | validations:
31 | required: false
32 | - type: textarea
33 | id: alternative
34 | attributes:
35 | label: Describe alternatives you've considered
36 | description: A clear and concise description of any alternative solutions or features you've considered.
37 | validations:
38 | required: false
39 | - type: textarea
40 | id: additional-context
41 | attributes:
42 | label: 'Additional context/Screenshots'
43 | description: Add any other context or screenshots about the feature request here.
44 | render: bash
45 | validations:
46 | required: false
47 |
--------------------------------------------------------------------------------
/axios-v1.x/test/unit/defaults/transformReponse.js:
--------------------------------------------------------------------------------
1 | import defaults from '../../../lib/defaults/index.js';
2 | import transformData from '../../../lib/core/transformData.js';
3 | import assert from 'assert';
4 |
5 | describe('transformResponse', function () {
6 | describe('200 request', function () {
7 | it('parses json', function () {
8 | const data = '{"message": "hello, world"}';
9 | const result = transformData.call({
10 | data,
11 | response: {
12 | headers: {'content-type': 'application/json'},
13 | status: 200
14 | }
15 | }, defaults.transformResponse);
16 | assert.strictEqual(result.message, 'hello, world');
17 | });
18 | it('ignores XML', function () {
19 | const data = 'hello, world';
20 | const result = transformData.call({
21 | data,
22 | response: {
23 | headers: {'content-type': 'text/xml'},
24 | status: 200
25 | }
26 | }, defaults.transformResponse);
27 | assert.strictEqual(result, data);
28 | });
29 | });
30 | describe('204 request', function () {
31 | it('does not parse the empty string', function () {
32 | const data = '';
33 | const result = transformData.call({
34 | data,
35 | response: {
36 | headers: {'content-type': undefined},
37 | status: 204
38 | }
39 | }, defaults.transformResponse);
40 | assert.strictEqual(result, '');
41 | });
42 | it('does not parse undefined', function () {
43 | const data = undefined;
44 | const result = transformData.call({
45 | data,
46 | response: {
47 | headers: {'content-type': undefined},
48 | status: 200
49 | }
50 | }, defaults.transformResponse);
51 | assert.strictEqual(result, data);
52 | });
53 | });
54 | });
55 |
--------------------------------------------------------------------------------