Making updates to sigcrafting

master
sigonasr2 2 years ago
parent 7dd9f5d0b5
commit 8eabca4138
  1. 20
      docker-compose.yml
  2. 8
      frontend/src/App.js
  3. 1005
      frontend/src/setupProxy.js
  4. 1
      server/.dockerignore
  5. 98
      server/Dockerfile
  6. 89
      server/Dockerfile_old
  7. 13
      server/app.js
  8. BIN
      server/files/JPOrbsP4S.png
  9. BIN
      server/files/SigTerm.txt
  10. 1
      server/files/leaderboard
  11. 1
      server/files/leaderboardinfo
  12. 1
      server/files/leaderboardinfo.1
  13. 72
      server/node_modules/assert-options/README.md
  14. 33
      server/node_modules/assert-options/dist/index.js
  15. 4
      server/node_modules/assert-options/dist/src/index.d.ts
  16. 34
      server/node_modules/assert-options/dist/src/index.js
  17. 76
      server/node_modules/assert-options/package.json
  18. 278
      server/node_modules/axios/CHANGELOG.md
  19. 0
      server/node_modules/axios/LICENSE
  20. 129
      server/node_modules/axios/README.md
  21. 2
      server/node_modules/axios/UPGRADE_GUIDE.md
  22. 321
      server/node_modules/axios/dist/axios.js
  23. 2
      server/node_modules/axios/dist/axios.map
  24. 4
      server/node_modules/axios/dist/axios.min.js
  25. 2
      server/node_modules/axios/dist/axios.min.map
  26. 22
      server/node_modules/axios/index.d.ts
  27. 0
      server/node_modules/axios/index.js
  28. 0
      server/node_modules/axios/lib/adapters/README.md
  29. 78
      server/node_modules/axios/lib/adapters/http.js
  30. 7
      server/node_modules/axios/lib/adapters/xhr.js
  31. 3
      server/node_modules/axios/lib/axios.js
  32. 0
      server/node_modules/axios/lib/cancel/Cancel.js
  33. 0
      server/node_modules/axios/lib/cancel/CancelToken.js
  34. 0
      server/node_modules/axios/lib/cancel/isCancel.js
  35. 7
      server/node_modules/axios/lib/core/Axios.js
  36. 0
      server/node_modules/axios/lib/core/InterceptorManager.js
  37. 0
      server/node_modules/axios/lib/core/README.md
  38. 0
      server/node_modules/axios/lib/core/buildFullPath.js
  39. 0
      server/node_modules/axios/lib/core/createError.js
  40. 0
      server/node_modules/axios/lib/core/dispatchRequest.js
  41. 2
      server/node_modules/axios/lib/core/enhanceError.js
  42. 78
      server/node_modules/axios/lib/core/mergeConfig.js
  43. 2
      server/node_modules/axios/lib/core/settle.js
  44. 0
      server/node_modules/axios/lib/core/transformData.js
  45. 1
      server/node_modules/axios/lib/defaults.js
  46. 0
      server/node_modules/axios/lib/helpers/README.md
  47. 0
      server/node_modules/axios/lib/helpers/bind.js
  48. 1
      server/node_modules/axios/lib/helpers/buildURL.js
  49. 0
      server/node_modules/axios/lib/helpers/combineURLs.js
  50. 0
      server/node_modules/axios/lib/helpers/cookies.js
  51. 0
      server/node_modules/axios/lib/helpers/deprecatedMethod.js
  52. 0
      server/node_modules/axios/lib/helpers/isAbsoluteURL.js
  53. 11
      server/node_modules/axios/lib/helpers/isAxiosError.js
  54. 0
      server/node_modules/axios/lib/helpers/isURLSameOrigin.js
  55. 0
      server/node_modules/axios/lib/helpers/normalizeHeaderName.js
  56. 0
      server/node_modules/axios/lib/helpers/parseHeaders.js
  57. 0
      server/node_modules/axios/lib/helpers/spread.js
  58. 65
      server/node_modules/axios/lib/utils.js
  59. 18
      server/node_modules/axios/node_modules/follow-redirects/LICENSE
  60. 148
      server/node_modules/axios/node_modules/follow-redirects/README.md
  61. 14
      server/node_modules/axios/node_modules/follow-redirects/debug.js
  62. 1
      server/node_modules/axios/node_modules/follow-redirects/http.js
  63. 1
      server/node_modules/axios/node_modules/follow-redirects/https.js
  64. 504
      server/node_modules/axios/node_modules/follow-redirects/index.js
  65. 98
      server/node_modules/axios/node_modules/follow-redirects/package.json
  66. 34
      server/node_modules/axios/package.json
  67. 2
      server/node_modules/bluebird/LICENSE
  68. 10
      server/node_modules/bluebird/README.md
  69. 0
      server/node_modules/bluebird/changelog.md
  70. 475
      server/node_modules/bluebird/js/browser/bluebird.core.js
  71. 8
      server/node_modules/bluebird/js/browser/bluebird.core.min.js
  72. 527
      server/node_modules/bluebird/js/browser/bluebird.js
  73. 10
      server/node_modules/bluebird/js/browser/bluebird.min.js
  74. 0
      server/node_modules/bluebird/js/release/any.js
  75. 0
      server/node_modules/bluebird/js/release/assert.js
  76. 71
      server/node_modules/bluebird/js/release/async.js
  77. 0
      server/node_modules/bluebird/js/release/bind.js
  78. 0
      server/node_modules/bluebird/js/release/bluebird.js
  79. 0
      server/node_modules/bluebird/js/release/call_get.js
  80. 0
      server/node_modules/bluebird/js/release/cancel.js
  81. 0
      server/node_modules/bluebird/js/release/catch_filter.js
  82. 0
      server/node_modules/bluebird/js/release/context.js
  83. 143
      server/node_modules/bluebird/js/release/debuggability.js
  84. 0
      server/node_modules/bluebird/js/release/direct_resolve.js
  85. 0
      server/node_modules/bluebird/js/release/each.js
  86. 0
      server/node_modules/bluebird/js/release/errors.js
  87. 0
      server/node_modules/bluebird/js/release/es5.js
  88. 0
      server/node_modules/bluebird/js/release/filter.js
  89. 39
      server/node_modules/bluebird/js/release/finally.js
  90. 2
      server/node_modules/bluebird/js/release/generators.js
  91. 11
      server/node_modules/bluebird/js/release/join.js
  92. 13
      server/node_modules/bluebird/js/release/map.js
  93. 0
      server/node_modules/bluebird/js/release/method.js
  94. 0
      server/node_modules/bluebird/js/release/nodeback.js
  95. 0
      server/node_modules/bluebird/js/release/nodeify.js
  96. 132
      server/node_modules/bluebird/js/release/promise.js
  97. 2
      server/node_modules/bluebird/js/release/promise_array.js
  98. 0
      server/node_modules/bluebird/js/release/promisify.js
  99. 2
      server/node_modules/bluebird/js/release/props.js
  100. 0
      server/node_modules/bluebird/js/release/queue.js
  101. Some files were not shown because too many files have changed in this diff Show More

@ -24,7 +24,7 @@ services:
depends_on:
- postgres
ports:
- "4504:4504"
- "443:443"
working_dir: /server2
volumes:
- ./server2:/server2
@ -51,20 +51,6 @@ services:
max-size: "1m"
max-file: "3"
imgparser:
build: imgparser
restart: always
ports:
- "4503:4503"
volumes:
- ./imgparser:/imgparser
working_dir: /imgparser/projectDivaImgParser
logging:
options:
max-size: "1m"
max-file: "3"
postgres:
image: postgres:10.4
restart: always
@ -90,7 +76,7 @@ services:
- postgres
- server
ports:
- "80:3000"
- "4500:3000"
environment:
- CHOKIDAR_USEPOLLING=true
stdin_open: true
@ -135,4 +121,4 @@ services:
# context: frontend
# dockerfile: Dockerfile.prod
# ports:
# - '3004:80'
# - '3004:80'

@ -842,7 +842,7 @@ function BestPlaysPanel(p) {
var [update,setUpdate] = useState(false)
useEffect(()=>{
axios.get("http://www.projectdivar.com/bestplays/"+p.username+"?fails=false&limit=5&offset=0")
axios.get("http://projectdivar.com/bestplays/"+p.username+"?fails=false&limit=5&offset=0")
.then((data)=>{setBestPlays(data.data);})
},[p.profileUpdate,update,p.username])
@ -851,7 +851,7 @@ function BestPlaysPanel(p) {
{bestPlays.map((play,i)=>{return <li key={i} className={"list-group-item list-group-item-action "+(i%2==0?"background-list-1":"background-list-2")}>
<Play setModalSrc={p.setModalSrc} setModalVisible={p.setModalVisible} index={i} play={play} song={p.songs[play.songid]}/>
</li>})}
<LoadMore username={p.username} profileUpdate={p.profileUpdate} listItem={true} url={"http://www.projectdivar.com/bestplays/"+p.username} params={{fails:false,limit:15,offset:5}} value={bestPlays} setValue={setBestPlays}/>
<LoadMore username={p.username} profileUpdate={p.profileUpdate} listItem={true} url={"http://projectdivar.com/bestplays/"+p.username} params={{fails:false,limit:15,offset:5}} value={bestPlays} setValue={setBestPlays}/>
</ul>
</div>
@ -948,7 +948,7 @@ function PlayData(p) {
<h5>Individual Plays for {p.song.name} from {p.username}</h5>
<div className="border rounded">
{data.map((play,i)=><Play setModalSrc={p.setModalSrc} setModalVisible={p.setModalVisible} key={i} play={play} mini={true} song={p.song}/>)}
<LoadMore profileUpdate={p.profileUpdate} username={p.username} url={"http://www.projectdivar.com/plays/"+p.username+"/"+p.song.id} params={{limit:15,offset:5}} value={data} setValue={setData}/>
<LoadMore profileUpdate={p.profileUpdate} username={p.username} url={"http://projectdivar.com/plays/"+p.username+"/"+p.song.id} params={{limit:15,offset:5}} value={data} setValue={setData}/>
</div>
</div>
</>
@ -2407,7 +2407,7 @@ function Website() {
const [userSettings,setUserSettings] = useState({})
useEffect(()=>{
axios.get("http://www.projectdivar.com/songs")
axios.get("http://.projectdivar.com/songs")
.then((data)=>{
setSongs(data.data)
})

File diff suppressed because it is too large Load Diff

@ -0,0 +1 @@
/node_modules

@ -1,89 +1,37 @@
FROM phusion/baseimage:bionic-1.0.0
from node:16-alpine
CMD ["/sbin/my_init"]
RUN apk update
ENV JAVA_MAJOR_VERSION=11
RUN apk add --no-cache \
sudo \
curl \
build-base \
g++ \
libpng \
libpng-dev \
jpeg-dev \
pango-dev \
cairo-dev \
giflib-dev \
python3
RUN mkdir -p /src/app
RUN apt-get update \
&& apt-get install -y --no-install-recommends tzdata curl ca-certificates fontconfig locales \
&& echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen \
&& locale-gen en_US.UTF-8 \
&& rm -rf /var/lib/apt/lists/*
RUN apk add --no-cache tini
ENV JAVA_VERSION jdk-11.0.8+10
RUN apk add ffmpeg
RUN set -eux; \
ARCH="$(dpkg --print-architecture)"; \
case "${ARCH}" in \
aarch64|arm64) \
ESUM='286c869dbaefda9b470ae71d1250fdecf9f06d8da97c0f7df9021d381d749106'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_aarch64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
armhf|armv7l) \
ESUM='ffa627b2d0c6001448bb8f1f24f7c9921dad37e67637f6ed0a9a479e680a3393'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_arm_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
ppc64el|ppc64le) \
ESUM='89231e1667d7cc4202d1a401497bb287d4eb12281c90c17e2570211cc4e901a3'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_ppc64le_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
s390x) \
ESUM='dc0e715c17abcb12bedf77c638e58e67d828d3c4bf24a898f0d4b053caaeb25f'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_s390x_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
amd64|x86_64) \
ESUM='98615b1b369509965a612232622d39b5cefe117d6189179cbad4dcef2ee2f4e1'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_x64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
*) \
echo "Unsupported arch: ${ARCH}"; \
exit 1; \
;; \
esac; \
curl -LfsSo /tmp/openjdk.tar.gz ${BINARY_URL}; \
echo "${ESUM} */tmp/openjdk.tar.gz" | sha256sum -c -; \
mkdir -p /opt/java/openjdk; \
cd /opt/java/openjdk; \
tar -xf /tmp/openjdk.tar.gz --strip-components=1; \
rm -rf /tmp/openjdk.tar.gz;
ENV JAVA_HOME=/opt/java/openjdk \
PATH="/opt/java/openjdk/bin:$PATH"
RUN apt-get update && \
apt-get install -y ffmpeg && \
apt-get clean;
RUN yarn global add nodemon
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && \
apt-get install -y yarn;
WORKDIR /src/app
COPY ./package.json ./package-lock.json /src/app/
WORKDIR /src/app
RUN npm install
COPY . /src/app
RUN yarn global add nodemon
# update
RUN apt-get update
# install curl
RUN apt-get install -y curl
# get install script and pass it to execute:
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash
# and install node
RUN apt-get install -y nodejs
# confirm that it was successful
RUN node -v
# npm installs automatically
RUN npm -v
EXPOSE 3005
ENV TINI_VERSION v0.19.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
RUN chmod +x /tini
ENTRYPOINT ["/tini", "--"]
ENTRYPOINT ["/sbin/tini", "--"]
EXPOSE 3005
CMD [ "nodemon", "app.js" ]
CMD [ "nodemon", "app.js" ]

@ -0,0 +1,89 @@
FROM phusion/baseimage:bionic-1.0.0
CMD ["/sbin/my_init"]
ENV JAVA_MAJOR_VERSION=11
RUN mkdir -p /src/app
RUN apt-get update \
&& apt-get install -y --no-install-recommends tzdata curl ca-certificates fontconfig locales \
&& echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen \
&& locale-gen en_US.UTF-8 \
&& rm -rf /var/lib/apt/lists/*
ENV JAVA_VERSION jdk-11.0.8+10
RUN set -eux; \
ARCH="$(dpkg --print-architecture)"; \
case "${ARCH}" in \
aarch64|arm64) \
ESUM='286c869dbaefda9b470ae71d1250fdecf9f06d8da97c0f7df9021d381d749106'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_aarch64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
armhf|armv7l) \
ESUM='ffa627b2d0c6001448bb8f1f24f7c9921dad37e67637f6ed0a9a479e680a3393'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_arm_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
ppc64el|ppc64le) \
ESUM='89231e1667d7cc4202d1a401497bb287d4eb12281c90c17e2570211cc4e901a3'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_ppc64le_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
s390x) \
ESUM='dc0e715c17abcb12bedf77c638e58e67d828d3c4bf24a898f0d4b053caaeb25f'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_s390x_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
amd64|x86_64) \
ESUM='98615b1b369509965a612232622d39b5cefe117d6189179cbad4dcef2ee2f4e1'; \
BINARY_URL='https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/download/jdk-11.0.8%2B10/OpenJDK11U-jre_x64_linux_hotspot_11.0.8_10.tar.gz'; \
;; \
*) \
echo "Unsupported arch: ${ARCH}"; \
exit 1; \
;; \
esac; \
curl -LfsSo /tmp/openjdk.tar.gz ${BINARY_URL}; \
echo "${ESUM} */tmp/openjdk.tar.gz" | sha256sum -c -; \
mkdir -p /opt/java/openjdk; \
cd /opt/java/openjdk; \
tar -xf /tmp/openjdk.tar.gz --strip-components=1; \
rm -rf /tmp/openjdk.tar.gz;
ENV JAVA_HOME=/opt/java/openjdk \
PATH="/opt/java/openjdk/bin:$PATH"
RUN apt-get update && \
apt-get install -y ffmpeg && \
apt-get clean;
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - && \
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list && \
apt-get update && \
apt-get install -y yarn;
WORKDIR /src/app
COPY . /src/app
RUN yarn global add nodemon
# update
RUN apt-get update
# install curl
RUN apt-get install -y curl
# get install script and pass it to execute:
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash
# and install node
RUN apt-get install -y nodejs
# confirm that it was successful
RUN node -v
# npm installs automatically
RUN npm -v
ENV TINI_VERSION v0.19.0
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /tini
RUN chmod +x /tini
ENTRYPOINT ["/tini", "--"]
EXPOSE 3005
CMD [ "nodemon", "app.js" ]

@ -54,12 +54,8 @@ const db2 = new Pool({
port: 5432,
});
app.use((req, _, next) => {
req.db = db;
next()
})
exports.app = app;
exports.db = db;
require("./routes/d4dj-routes");
@ -2863,9 +2859,12 @@ function Process(data, ind) {
app.use(
"/files",
express.static("files", {
express.static("files"
/*,
{
maxAge: 86400000 * 30,
})
}*/
)
);
/*

Binary file not shown.

After

Width:  |  Height:  |  Size: 690 KiB

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -0,0 +1,72 @@
# assert-options
Smart `options` handling, with one line of code:
* throw detailed error on invalid options
* set default values for missing options
Strongly-typed, built with TypeScript 4.x `strict` mode, for JavaScript clients.
[![Build Status](https://travis-ci.org/vitaly-t/assert-options.svg?branch=master)](https://travis-ci.org/vitaly-t/assert-options)
[![Coverage Status](https://coveralls.io/repos/vitaly-t/assert-options/badge.svg?branch=master)](https://coveralls.io/r/vitaly-t/assert-options?branch=master)
## Rationale
* Passing in invalid or misspelled option names is one of the most common errors in JavaScript.
* Assigning defaults is the most common operation for methods that take options.
This module automates proper options handling - parsing and setting defaults where needed.
Although this library is implemented in TypeScript, its objective is mainly to help JavaScript clients,
because TypeScript itself can handle invalid options and defaults natively.
## Installation
```
$ npm i assert-options
```
## Usage
```js
const { assertOptions } = require('assert-options');
function functionWithOptions(options) {
options = assertOptions(options, {first: 123, second: null});
// options is a safe object here, with all missing defaults set.
}
```
When default values are not needed, you can just use an array of strings:
```js
function functionWithOptions(options) {
options = assertOptions(options, ['first', 'second']);
// the result is exactly the same as using the following:
// options = assertOptions(options, {first: undefined, second: undefined});
// options is a safe object here, without defaults.
}
```
## API
### `assertOptions(options, defaults) => {}`
* When `options` is `null`/`undefined`, new `{}` is returned, applying `defaults` as specified.
* When `options` contains an unknown property, [Error] `Option "name" is not recognized.` is thrown.
* When a property in `options` is missing or `undefined`, its value is set from the `defaults`,
provided it is available and its value is not `undefined`.
* When `options` is not `null`/`undefined`, it must be of type `object`, or else [TypeError] is thrown:
`Invalid "options" parameter: value`.
* Parameter `defaults` is required, as a non-`null` object or an array of strings, or else [TypeError]
is thrown: `Invalid "defaults" parameter: value`.
[Error]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
[TypeError]:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError

@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function assertOptions(options, defaults) {
if (options !== null && options !== undefined && typeof options !== 'object') {
throw new TypeError('Invalid "options" parameter: ' + JSON.stringify(options));
}
var isArray = Array.isArray(defaults);
if (!isArray && (!defaults || typeof defaults !== 'object')) {
throw new TypeError('Invalid "defaults" parameter: ' + JSON.stringify(defaults));
}
if (options) {
for (var _i = 0, _a = Object.keys(options); _i < _a.length; _i++) {
var a = _a[_i];
if ((isArray && defaults.indexOf(a) === -1) || (!isArray && !(a in defaults))) {
throw new Error('Option "' + a + '" is not recognized.');
}
}
}
else {
options = {};
}
if (!isArray) {
var defs = defaults;
for (var _b = 0, _c = Object.keys(defs); _b < _c.length; _b++) {
var d = _c[_b];
if (options[d] === undefined && defs[d] !== undefined) {
options[d] = defs[d];
}
}
}
return options;
}
exports.assertOptions = assertOptions;

@ -0,0 +1,4 @@
export declare type NamedValues = {
[name: string]: any;
};
export declare function assertOptions(options: NamedValues | null | undefined, defaults: NamedValues | string[]): NamedValues;

@ -0,0 +1,34 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertOptions = void 0;
function assertOptions(options, defaults) {
if (options !== null && options !== undefined && typeof options !== 'object') {
throw new TypeError('Invalid "options" parameter: ' + JSON.stringify(options));
}
var isArray = Array.isArray(defaults);
if (!isArray && (!defaults || typeof defaults !== 'object')) {
throw new TypeError('Invalid "defaults" parameter: ' + JSON.stringify(defaults));
}
if (options) {
for (var _i = 0, _a = Object.keys(options); _i < _a.length; _i++) {
var a = _a[_i];
if ((isArray && defaults.indexOf(a) === -1) || (!isArray && !(a in defaults))) {
throw new Error('Option "' + a + '" is not recognized.');
}
}
}
else {
options = {};
}
if (!isArray) {
var defs = defaults;
for (var _b = 0, _c = Object.keys(defs); _b < _c.length; _b++) {
var d = _c[_b];
if (options[d] === undefined && defs[d] !== undefined) {
options[d] = defs[d];
}
}
}
return options;
}
exports.assertOptions = assertOptions;

@ -0,0 +1,76 @@
{
"_from": "assert-options@0.7.0",
"_id": "assert-options@0.7.0",
"_inBundle": false,
"_integrity": "sha512-7q9uNH/Dh8gFgpIIb9ja8PJEWA5AQy3xnBC8jtKs8K/gNVCr1K6kIvlm59HUyYgvM7oEDoLzGgPcGd9FqhtXEQ==",
"_location": "/assert-options",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "assert-options@0.7.0",
"name": "assert-options",
"escapedName": "assert-options",
"rawSpec": "0.7.0",
"saveSpec": null,
"fetchSpec": "0.7.0"
},
"_requiredBy": [
"/pg-promise"
],
"_resolved": "https://registry.npmjs.org/assert-options/-/assert-options-0.7.0.tgz",
"_shasum": "82c27618d9c0baa5e9da8ef607ee261a44ed6e5e",
"_spec": "assert-options@0.7.0",
"_where": "/home/sigonasr2/divar/server/node_modules/pg-promise",
"author": {
"name": "Vitaly Tomilov",
"email": "vitaly.tomilov@gmail.com"
},
"bugs": {
"url": "https://github.com/vitaly-t/assert-options/issues",
"email": "vitaly.tomilov@gmail.com"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Generic options parameter handling.",
"devDependencies": {
"@types/chai": "4.2.14",
"@types/mocha": "8.2.0",
"@types/node": "14.14.14",
"chai": "4.2.0",
"coveralls": "3.1.0",
"mocha": "8.2.1",
"mocha-lcov-reporter": "1.3.0",
"nyc": "15.1.0",
"ts-node": "9.1.1",
"tslint": "6.1.3",
"typescript": "4.1.3"
},
"engines": {
"node": ">=8.0.0"
},
"files": [
"dist/src",
"dist/index.js"
],
"homepage": "https://github.com/vitaly-t/assert-options",
"keywords": [
"assert",
"options"
],
"license": "MIT",
"main": "dist/src/index.js",
"name": "assert-options",
"repository": {
"type": "git",
"url": "git+https://github.com/vitaly-t/assert-options.git"
},
"scripts": {
"all": "tsc && npm test && npm run lint",
"lint": "tslint --fix ./src/**/*.ts ./test/**/*.ts",
"test": "nyc mocha -r ts-node/register test/**/*.spec.ts",
"travis": "nyc npm test && nyc report --reporter=text-lcov | coveralls"
},
"types": "dist/src/index.d.ts",
"version": "0.7.0"
}

@ -1,5 +1,277 @@
# Changelog
### 0.21.1 (December 21, 2020)
Fixes and Functionality:
- Hotfix: Prevent SSRF (#3410)
- Protocol not parsed when setting proxy config from env vars (#3070)
- Updating axios in types to be lower case (#2797)
- Adding a type guard for `AxiosError` (#2949)
Internal and Tests:
- Remove the skipping of the `socket` http test (#3364)
- Use different socket for Win32 test (#3375)
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- Daniel Lopretto <timemachine3030@users.noreply.github.com>
- Jason Kwok <JasonHK@users.noreply.github.com>
- Jay <jasonsaayman@gmail.com>
- Jonathan Foster <jonathan@jonathanfoster.io>
- Remco Haszing <remcohaszing@gmail.com>
- Xianming Zhong <chinesedfan@qq.com>
### 0.21.0 (October 23, 2020)
Fixes and Functionality:
- Fixing requestHeaders.Authorization ([#3287](https://github.com/axios/axios/pull/3287))
- Fixing node types ([#3237](https://github.com/axios/axios/pull/3237))
- Fixing axios.delete ignores config.data ([#3282](https://github.com/axios/axios/pull/3282))
- Revert "Fixing overwrite Blob/File type as Content-Type in browser. (#1773)" ([#3289](https://github.com/axios/axios/pull/3289))
- Fixing an issue that type 'null' and 'undefined' is not assignable to validateStatus when typescript strict option is enabled ([#3200](https://github.com/axios/axios/pull/3200))
Internal and Tests:
- Lock travis to not use node v15 ([#3361](https://github.com/axios/axios/pull/3361))
Documentation:
- Fixing simple typo, existant -> existent ([#3252](https://github.com/axios/axios/pull/3252))
- Fixing typos ([#3309](https://github.com/axios/axios/pull/3309))
Huge thanks to everyone who contributed to this release via code (authors listed below) or via reviews and triaging on GitHub:
- Allan Cruz <57270969+Allanbcruz@users.noreply.github.com>
- George Cheng <Gerhut@GMail.com>
- Jay <jasonsaayman@gmail.com>
- Kevin Kirsche <Kev.Kirsche+GitHub@gmail.com>
- Remco Haszing <remcohaszing@gmail.com>
- Taemin Shin <cprayer13@gmail.com>
- Tim Gates <tim.gates@iress.com>
- Xianming Zhong <chinesedfan@qq.com>
### 0.20.0 (August 20, 2020)
Release of 0.20.0-pre as a full release with no other changes.
### 0.20.0-pre (July 15, 2020)
Fixes and Functionality:
- Fixing response with utf-8 BOM can not parse to json ([#2419](https://github.com/axios/axios/pull/2419))
- fix: remove byte order marker (UTF-8 BOM) when transform response
- fix: remove BOM only utf-8
- test: utf-8 BOM
- fix: incorrect param name
- Refactor mergeConfig without utils.deepMerge ([#2844](https://github.com/axios/axios/pull/2844))
- Adding failing test
- Fixing #2587 default custom config persisting
- Adding Concat keys and filter duplicates
- Fixed value from CPE
- update for review feedbacks
- no deepMerge
- only merge between plain objects
- fix rename
- always merge config by mergeConfig
- extract function mergeDeepProperties
- refactor mergeConfig with all keys, and add special logic for validateStatus
- add test for resetting headers
- add lots of tests and fix a bug
- should not inherit `data`
- use simple toString
- Fixing overwrite Blob/File type as Content-Type in browser. ([#1773](https://github.com/axios/axios/pull/1773))
- Fixing an issue that type 'null' is not assignable to validateStatus ([#2773](https://github.com/axios/axios/pull/2773))
- Fixing special char encoding ([#1671](https://github.com/axios/axios/pull/1671))
- removing @ character from replacement list since it is a reserved character
- Updating buildURL test to not include the @ character
- Removing console logs
- Fixing password encoding with special characters in basic authentication ([#1492](https://github.com/axios/axios/pull/1492))
- Fixing password encoding with special characters in basic authentication
- Adding test to check if password with non-Latin1 characters pass
- Fixing 'Network Error' in react native android ([#1487](https://github.com/axios/axios/pull/1487))
There is a bug in react native Android platform when using get method. It will trigger a 'Network Error' when passing the requestData which is an empty string to request.send function. So if the requestData is an empty string we can set it to null as well to fix the bug.
- Fixing Cookie Helper with Asyc Components ([#1105](https://github.com/axios/axios/pull/1105)) ([#1107](https://github.com/axios/axios/pull/1107))
- Fixing 'progressEvent' type ([#2851](https://github.com/axios/axios/pull/2851))
- Fix 'progressEvent' type
- Update axios.ts
- Fixing getting local files (file://) failed ([#2470](https://github.com/axios/axios/pull/2470))
- fix issue #2416, #2396
- fix Eslint warn
- Modify judgment conditions
- add unit test
- update unit test
- update unit test
- Allow PURGE method in typings ([#2191](https://github.com/axios/axios/pull/2191))
- Adding option to disable automatic decompression ([#2661](https://github.com/axios/axios/pull/2661))
- Adding ability to disable auto decompression
- Updating decompress documentation in README
- Fixing test\unit\adapters\http.js lint errors
- Adding test for disabling auto decompression
- Removing changes that fixed lint errors in tests
- Removing formatting change to unit test
- Add independent `maxBodyLength` option ([#2781](https://github.com/axios/axios/pull/2781))
- Add independent option to set the maximum size of the request body
- Remove maxBodyLength check
- Update README
- Assert for error code and message
- Adding responseEncoding to mergeConfig ([#1745](https://github.com/axios/axios/pull/1745))
- Compatible with follow-redirect aborts the request ([#2689](https://github.com/axios/axios/pull/2689))
- Compatible with follow-redirect aborts the request
- Use the error code
- Fix merging of params ([#2656](https://github.com/axios/axios/pull/2656))
- Name function to avoid ESLint func-names warning
- Switch params config to merge list and update tests
- Restore testing of both false and null
- Restore test cases for keys without defaults
- Include test for non-object values that aren't false-y.
- Revert `finally` as `then` ([#2683](https://github.com/axios/axios/pull/2683))
Internal and Tests:
- Fix stale bot config ([#3049](https://github.com/axios/axios/pull/3049))
- fix stale bot config
- fix multiple lines
- Add days and change name to work ([#3035](https://github.com/axios/axios/pull/3035))
- Update close-issues.yml ([#3031](https://github.com/axios/axios/pull/3031))
- Update close-issues.yml
Update close message to read better 😄
- Fix use of quotations
Use single quotes as per other .yml files
- Remove user name form message
- Add GitHub actions to close stale issues/prs ([#3029](https://github.com/axios/axios/pull/3029))
- prepare stale actions
- update messages
- Add exempt labels and lighten up comments
- Add GitHub actions to close invalid issues ([#3022](https://github.com/axios/axios/pull/3022))
- add close actions
- fix with checkout
- update issue templates
- add reminder
- update close message
- Add test with Node.js 12 ([#2860](https://github.com/axios/axios/pull/2860))
- test with Node.js 12
- test with latest
- Adding console log on sandbox server startup ([#2210](https://github.com/axios/axios/pull/2210))
- Adding console log on sandbox server startup
- Update server.js
Add server error handling
- Update server.js
Better error message, remove retry.
- Adding tests for method `options` type definitions ([#1996](https://github.com/axios/axios/pull/1996))
Update tests.
- Add test for redirecting with too large response ([#2695](https://github.com/axios/axios/pull/2695))
- Fixing unit test failure in Windows OS ([#2601](https://github.com/axios/axios/pull/2601))
- Fixing issue for HEAD method and gzipped response ([#2666](https://github.com/axios/axios/pull/2666))
- Fix tests in browsers ([#2748](https://github.com/axios/axios/pull/2748))
- chore: add `jsdelivr` and `unpkg` support ([#2443](https://github.com/axios/axios/pull/2443))
Documentation:
- Adding support for URLSearchParams in node ([#1900](https://github.com/axios/axios/pull/1900))
- Adding support for URLSearchParams in node
- Remove un-needed code
- Update utils.js
- Make changes as suggested
- Adding table of content (preview) ([#3050](https://github.com/axios/axios/pull/3050))
- add toc (preview)
- remove toc in toc
Signed-off-by: Moni <usmoni@gmail.com>
- fix sublinks
- fix indentation
- remove redundant table links
- update caps and indent
- remove axios
- Replace 'blacklist' with 'blocklist' ([#3006](https://github.com/axios/axios/pull/3006))
- docs(): Detailed config options environment. ([#2088](https://github.com/axios/axios/pull/2088))
- docs(): Detailed config options environment.
- Update README.md
- Include axios-data-unpacker in ECOSYSTEM.md ([#2080](https://github.com/axios/axios/pull/2080))
- Allow opening examples in Gitpod ([#1958](https://github.com/axios/axios/pull/1958))
- Remove axios.all() and axios.spread() from Readme.md ([#2727](https://github.com/axios/axios/pull/2727))
- remove axios.all(), axios.spread()
- replace example
- axios.all() -> Promise.all()
- axios.spread(function (acct, perms)) -> function (acct, perms)
- add deprecated mark
- Update README.md ([#2887](https://github.com/axios/axios/pull/2887))
Small change to the data attribute doc of the config. A request body can also be set for DELETE methods but this wasn't mentioned in the documentation (it only mentioned POST, PUT and PATCH). Took my some 10-20 minutes until I realized that I don't need to manipulate the request body with transformRequest in the case of DELETE.
- Include swagger-taxos-codegen in ECOSYSTEM.md ([#2162](https://github.com/axios/axios/pull/2162))
- Add CDNJS version badge in README.md ([#878](https://github.com/axios/axios/pull/878))
This badge will show the version on CDNJS!
- Documentation update to clear up ambiguity in code examples ([#2928](https://github.com/axios/axios/pull/2928))
- Made an adjustment to the documentation to clear up any ambiguity around the use of "fs". This should help clear up that the code examples with "fs" cannot be used on the client side.
- Update README.md about validateStatus ([#2912](https://github.com/axios/axios/pull/2912))
Rewrote the comment from "Reject only if the status code is greater than or equal to 500" to "Resolve only if the status code is less than 500"
- Updating documentation for usage form-data ([#2805](https://github.com/axios/axios/pull/2805))
Closes #2049
- Fixing CHANGELOG.md issue link ([#2784](https://github.com/axios/axios/pull/2784))
- Include axios-hooks in ECOSYSTEM.md ([#2003](https://github.com/axios/axios/pull/2003))
- Added Response header access instructions ([#1901](https://github.com/axios/axios/pull/1901))
- Added Response header access instructions
- Added note about using bracket notation
- Add `onUploadProgress` and `onDownloadProgress` are browser only ([#2763](https://github.com/axios/axios/pull/2763))
Saw in #928 and #1966 that `onUploadProgress` and `onDownloadProgress` only work in the browser and was missing that from the README.
- Update ' sign to ` in proxy spec ([#2778](https://github.com/axios/axios/pull/2778))
- Adding jsDelivr link in README ([#1110](https://github.com/axios/axios/pull/1110))
- Adding jsDelivr link
- Add SRI
- Remove SRI
Huge thanks to everyone who contributed to this release via code (authors listed
below) or via reviews and triaging on GitHub:
- Alan Wang <wp_scut@163.com>
- Alexandru Ungureanu <khakcarot@gmail.com>
- Anubhav Srivastava <anubhav.srivastava00@gmail.com>
- Benny Neugebauer <bn@bennyn.de>
- Cr <631807682@qq.com>
- David <cygnidavid@gmail.com>
- David Ko <david.ko@pvtmethod.com>
- David Tanner <david.tanner@lifeomic.com>
- Emily Morehouse <emilyemorehouse@gmail.com>
- Felipe Martins <felipewmartins@gmail.com>
- Fonger <5862369+Fonger@users.noreply.github.com>
- Frostack <soulburn007@gmail.com>
- George Cheng <Gerhut@GMail.com>
- grumblerchester <grumblerchester@users.noreply.github.com>
- Gustavo López <gualopezb@gmail.com>
- hexaez <45806662+hexaez@users.noreply.github.com>
- huangzuizui <huangzuizui@gmail.com>
- Ian Wijma <ian@wij.ma>
- Jay <jasonsaayman@gmail.com>
- jeffjing <zgayjjf@qq.com>
- jennynju <46782518+jennynju@users.noreply.github.com>
- Jimmy Liao <52391190+jimmy-liao-gogoro@users.noreply.github.com>
- Jonathan Sharpe <j.r.sharpe@gmail.com>
- JounQin <admin@1stg.me>
- Justin Beckwith <justin.beckwith@gmail.com>
- Kamil Posiadała <3dcreator.pl@gmail.com>
- Lukas Drgon <lukas.drgon@gmail.com>
- marcinx <mail@marcinx.com>
- Martti Laine <martti@codeclown.net>
- Michał Zarach <michal.m.zarach@gmail.com>
- Moni <usmoni@gmail.com>
- Motonori Iwata <121048+iwata@users.noreply.github.com>
- Nikita Galkin <nikita@galk.in>
- Petr Mares <petr@mares.tw>
- Philippe Recto <precto1285@gmal.com>
- Remco Haszing <remcohaszing@gmail.com>
- rockcs1992 <chengshi1219@gmail.com>
- Ryan Bown <rbown@niftee.com.au>
- Samina Fu <sufuf3@gmail.com>
- Simone Busoli <simone.busoli@gmail.com>
- Spencer von der Ohe <s.vonderohe40@gmail.com>
- Sven Efftinge <sven.efftinge@typefox.io>
- Taegyeoung Oh <otk1090@naver.com>
- Taemin Shin <cprayer13@gmail.com>
- Thibault Ehrhart <1208424+ehrhart@users.noreply.github.com>
- Xianming Zhong <chinesedfan@qq.com>
- Yasu Flores <carlosyasu91@gmail.com>
- Zac Delventhal <delventhalz@gmail.com>
### 0.19.2 (Jan 20, 2020)
- Remove unnecessary XSS check ([#2679](https://github.com/axios/axios/pull/2679)) (see ([#2646](https://github.com/axios/axios/issues/2646)) for discussion)
@ -25,7 +297,7 @@ Fixes and Functionality:
- Add error toJSON example ([#2466](https://github.com/axios/axios/pull/2466))
- Fixing Vulnerability A Fortify Scan finds a critical Cross-Site Scrip… ([#2451](https://github.com/axios/axios/pull/2451))
- Fixing subdomain handling on no_proxy ([#2442](https://github.com/axios/axios/pull/2442))
- Make redirection from HTTP to HTTPS work ([#2426](https://github.com/axios/axios/pull/2426] and ([#2547](https://github.com/axios/axios/pull/2547))
- Make redirection from HTTP to HTTPS work ([#2426](https://github.com/axios/axios/pull/2426)) and ([#2547](https://github.com/axios/axios/pull/2547))
- Add toJSON property to AxiosError type ([#2427](https://github.com/axios/axios/pull/2427))
- Fixing socket hang up error on node side for slow response. ([#1752](https://github.com/axios/axios/pull/1752))
- Alternative syntax to send data into the body ([#2317](https://github.com/axios/axios/pull/2317))
@ -57,7 +329,7 @@ Documentation:
- Update response interceptor docs ([#2399](https://github.com/axios/axios/pull/2399))
- Update README.md ([#2504](https://github.com/axios/axios/pull/2504))
- Fix word 'sintaxe' to 'syntax' in README.md ([#2432](https://github.com/axios/axios/pull/2432))
- upadating README: notes on CommonJS autocomplete ([#2256](https://github.com/axios/axios/pull/2256))
- updating README: notes on CommonJS autocomplete ([#2256](https://github.com/axios/axios/pull/2256))
- Fix grammar in README.md ([#2271](https://github.com/axios/axios/pull/2271))
- Doc fixes, minor examples cleanup ([#2198](https://github.com/axios/axios/pull/2198))
@ -110,7 +382,7 @@ New Functionality:
- Add getUri method ([#1712](https://github.com/axios/axios/issues/1712))
- Add support for no_proxy env variable ([#1693](https://github.com/axios/axios/issues/1693))
- Add toJSON to decorated Axios errors to faciliate serialization ([#1625](https://github.com/axios/axios/issues/1625))
- Add toJSON to decorated Axios errors to facilitate serialization ([#1625](https://github.com/axios/axios/issues/1625))
- Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623))
- Typings: allow custom return types
- Add option to specify character set in responses (with http adapter)

129
server/node_modules/axios/README.md generated vendored

@ -1,6 +1,7 @@
# axios
[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
[![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios)
[![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios)
[![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios)
[![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios)
@ -9,6 +10,37 @@
[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
Promise based HTTP client for the browser and node.js
## Table of Contents
- [Features](#features)
- [Browser Support](#browser-support)
- [Installing](#installing)
- [Example](#example)
- [Axios API](#axios-api)
- [Request method aliases](#request-method-aliases)
- [Concurrency (Deprecated)](#concurrency-deprecated)
- [Creating an instance](#creating-an-instance)
- [Instance methods](#instance-methods)
- [Request Config](#request-config)
- [Response Schema](#response-schema)
- [Config Defaults](#config-defaults)
- [Global axios defaults](#global-axios-defaults)
- [Custom instance defaults](#custom-instance-defaults)
- [Config order of precedence](#config-order-of-precedence)
- [Interceptors](#interceptors)
- [Handling Errors](#handling-errors)
- [Cancellation](#cancellation)
- [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
- [Browser](#browser)
- [Node.js](#nodejs)
- [Query string](#query-string)
- [Form data](#form-data)
- [Semver](#semver)
- [Promises](#promises)
- [TypeScript](#typescript)
- [Resources](#resources)
- [Credits](#credits)
- [License](#license)
## Features
@ -49,7 +81,13 @@ Using yarn:
$ yarn add axios
```
Using cdn:
Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
@ -81,7 +119,7 @@ axios.get('/user?ID=12345')
// handle error
console.log(error);
})
.finally(function () {
.then(function () {
// always executed
});
@ -97,7 +135,7 @@ axios.get('/user', {
.catch(function (error) {
console.log(error);
})
.finally(function () {
.then(function () {
// always executed
});
@ -141,10 +179,11 @@ function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// Both requests are now complete
}));
Promise.all([getUserAccount(), getUserPermissions()])
.then(function (results) {
const acct = results[0];
const perm = results[1];
});
```
## axios API
@ -166,7 +205,7 @@ axios({
```
```js
// GET request for remote image
// GET request for remote image in node.js
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
@ -200,12 +239,13 @@ For convenience aliases have been provided for all supported request methods.
###### NOTE
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
### Concurrency
### Concurrency (Deprecated)
Please use `Promise.all` to replace the below functions.
Helper functions for dealing with concurrent requests.
##### axios.all(iterable)
##### axios.spread(callback)
axios.all(iterable)
axios.spread(callback)
### Creating an instance
@ -287,7 +327,7 @@ These are the available config options for making requests. Only the `url` is re
},
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
@ -330,7 +370,7 @@ These are the available config options for making requests. Only the `url` is re
// browser only: 'blob'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses
// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
@ -341,18 +381,23 @@ These are the available config options for making requests. Only the `url` is re
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` allows handling of progress events for uploads
// browser only
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` allows handling of progress events for downloads
// browser only
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength` defines the max size of the http response content in bytes allowed
// `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
maxContentLength: 2000,
// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
maxBodyLength: 2000,
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
@ -377,7 +422,7 @@ These are the available config options for making requests. Only the `url` is re
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' defines the hostname and port of the proxy server.
// `proxy` defines the hostname, port, and protocol of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
@ -387,7 +432,9 @@ These are the available config options for making requests. Only the `url` is re
// supplies credentials.
// This will set an `Proxy-Authorization` header, overwriting any existing
// `Proxy-Authorization` custom headers you have set using `headers`.
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
@ -399,7 +446,14 @@ These are the available config options for making requests. Only the `url` is re
// `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}),
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// - Node only (XHR cannot turn off decompression)
decompress: true // default
}
```
@ -418,8 +472,9 @@ The response for a request contains the following information.
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
// All header names are lower cased
// `headers` the HTTP headers that the server responded with
// All header names are lower cased and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
@ -559,7 +614,7 @@ Using the `validateStatus` config option, you can define HTTP code(s) that shoul
```js
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
return status < 500; // Resolve only if the status code is less than 500
}
})
```
@ -664,6 +719,8 @@ axios(options);
### Node.js
#### Query string
In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
```js
@ -671,11 +728,45 @@ const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
```
or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows:
```js
const url = require('url');
const params = new url.URLSearchParams({ foo: 'bar' });
axios.post('http://something.com/', params.toString());
```
You can also use the [`qs`](https://github.com/ljharb/qs) library.
###### NOTE
The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).
#### Form data
In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows:
```js
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', new Buffer(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form, { headers: form.getHeaders() })
```
Alternatively, use an interceptor:
```js
axios.interceptors.request.use(config => {
if (config.data instanceof FormData) {
Object.assign(config.headers, config.data.getHeaders());
}
return config;
});
```
## Semver
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.

@ -135,7 +135,7 @@ This will polyfill the global environment, and only needs to be done once.
#### `axios.success`/`axios.error`
The `success`, and `error` aliases were deprectated in [0.4.0](https://github.com/axios/axios/blob/master/CHANGELOG.md#040-oct-03-2014). As of this release they have been removed entirely. Instead please use `axios.then`, and `axios.catch` respectively.
The `success`, and `error` aliases were deprecated in [0.4.0](https://github.com/axios/axios/blob/master/CHANGELOG.md#040-oct-03-2014). As of this release they have been removed entirely. Instead please use `axios.then`, and `axios.catch` respectively.
```js
axios.get('some/url')

@ -1,4 +1,4 @@
/* axios v0.19.2 | (c) 2020 by Matt Zabriskie */
/* axios v0.21.1 | (c) 2020 by Matt Zabriskie */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
@ -110,6 +110,9 @@ return /******/ (function(modules) { // webpackBootstrap
};
axios.spread = __webpack_require__(25);
// Expose isAxiosError
axios.isAxiosError = __webpack_require__(26);
module.exports = axios;
// Allow use of default import syntax in TypeScript
@ -227,6 +230,21 @@ return /******/ (function(modules) { // webpackBootstrap
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
@ -383,34 +401,12 @@ return /******/ (function(modules) { // webpackBootstrap
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
@ -441,6 +437,19 @@ return /******/ (function(modules) { // webpackBootstrap
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
@ -450,6 +459,7 @@ return /******/ (function(modules) { // webpackBootstrap
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
@ -460,9 +470,9 @@ return /******/ (function(modules) { // webpackBootstrap
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
deepMerge: deepMerge,
extend: extend,
trim: trim
trim: trim,
stripBOM: stripBOM
};
@ -562,9 +572,10 @@ return /******/ (function(modules) { // webpackBootstrap
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
return this.request(mergeConfig(config || {}, {
method: method,
url: url
url: url,
data: (config || {}).data
}));
};
});
@ -572,7 +583,7 @@ return /******/ (function(modules) { // webpackBootstrap
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: data
@ -593,7 +604,6 @@ return /******/ (function(modules) { // webpackBootstrap
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
@ -920,6 +930,7 @@ return /******/ (function(modules) { // webpackBootstrap
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
@ -969,10 +980,11 @@ return /******/ (function(modules) { // webpackBootstrap
var utils = __webpack_require__(2);
var settle = __webpack_require__(13);
var cookies = __webpack_require__(16);
var buildURL = __webpack_require__(5);
var buildFullPath = __webpack_require__(16);
var parseHeaders = __webpack_require__(19);
var isURLSameOrigin = __webpack_require__(20);
var buildFullPath = __webpack_require__(17);
var parseHeaders = __webpack_require__(20);
var isURLSameOrigin = __webpack_require__(21);
var createError = __webpack_require__(14);
module.exports = function xhrAdapter(config) {
@ -989,7 +1001,7 @@ return /******/ (function(modules) { // webpackBootstrap
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
@ -1070,8 +1082,6 @@ return /******/ (function(modules) { // webpackBootstrap
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(21);
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
@ -1137,7 +1147,7 @@ return /******/ (function(modules) { // webpackBootstrap
});
}
if (requestData === undefined) {
if (!requestData) {
requestData = null;
}
@ -1164,7 +1174,7 @@ return /******/ (function(modules) { // webpackBootstrap
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!validateStatus || validateStatus(response.status)) {
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
@ -1228,7 +1238,7 @@ return /******/ (function(modules) { // webpackBootstrap
error.response = response;
error.isAxiosError = true;
error.toJSON = function() {
error.toJSON = function toJSON() {
return {
// Standard
message: this.message,
@ -1256,8 +1266,67 @@ return /******/ (function(modules) { // webpackBootstrap
'use strict';
var isAbsoluteURL = __webpack_require__(17);
var combineURLs = __webpack_require__(18);
var utils = __webpack_require__(2);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var isAbsoluteURL = __webpack_require__(18);
var combineURLs = __webpack_require__(19);
/**
* Creates a new URL by combining the baseURL with the requestedURL,
@ -1277,7 +1346,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
/* 17 */
/* 18 */
/***/ (function(module, exports) {
'use strict';
@ -1297,7 +1366,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
/* 18 */
/* 19 */
/***/ (function(module, exports) {
'use strict';
@ -1317,7 +1386,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
/* 19 */
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
@ -1376,7 +1445,7 @@ return /******/ (function(modules) { // webpackBootstrap
/***/ }),
/* 20 */
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
@ -1449,65 +1518,6 @@ return /******/ (function(modules) { // webpackBootstrap
);
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
@ -1529,59 +1539,73 @@ return /******/ (function(modules) { // webpackBootstrap
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var valueFromConfig2Keys = ['url', 'method', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
var defaultToConfig2Keys = [
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath'
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
];
var directMergeKeys = ['validateStatus'];
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
}
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
}
});
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
} else if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (utils.isObject(config1[prop])) {
config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
utils.forEach(directMergeKeys, function merge(prop) {
if (prop in config2) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys);
.concat(defaultToConfig2Keys)
.concat(directMergeKeys);
var otherKeys = Object
.keys(config2)
.keys(config1)
.concat(Object.keys(config2))
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
utils.forEach(otherKeys, mergeDeepProperties);
return config;
};
@ -1708,6 +1732,23 @@ return /******/ (function(modules) { // webpackBootstrap
};
/***/ }),
/* 26 */
/***/ (function(module, exports) {
'use strict';
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return (typeof payload === 'object') && (payload.isAxiosError === true);
};
/***/ })
/******/ ])
});

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -29,15 +29,16 @@ export type Method =
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK'
export type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
export type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream'
export interface AxiosRequestConfig {
@ -61,13 +62,15 @@ export interface AxiosRequestConfig {
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: (status: number) => boolean;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
socketPath?: string | null;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
}
export interface AxiosResponse<T = any> {
@ -150,8 +153,9 @@ export interface AxiosStatic extends AxiosInstance {
isCancel(value: any): boolean;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
isAxiosError(payload: any): payload is AxiosError;
}
declare const Axios: AxiosStatic;
declare const axios: AxiosStatic;
export default Axios;
export default axios;

@ -16,6 +16,31 @@ var enhanceError = require('../core/enhanceError');
var isHttps = /https:?/;
/**
*
* @param {http.ClientRequestArgs} options
* @param {AxiosProxyConfig} proxy
* @param {string} location
*/
function setProxy(options, proxy, location) {
options.hostname = proxy.host;
options.host = proxy.host;
options.port = proxy.port;
options.path = location;
// Basic proxy authorization
if (proxy.auth) {
var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
}
// If a proxy is used, any redirects must also pass through the proxy
options.beforeRedirect = function beforeRedirect(redirection) {
redirection.headers.host = redirection.host;
setProxy(redirection, proxy, redirection.href);
};
}
/*eslint consistent-return:0*/
module.exports = function httpAdapter(config) {
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
@ -126,11 +151,11 @@ module.exports = function httpAdapter(config) {
});
}
if (shouldProxy) {
proxy = {
host: parsedProxyUrl.hostname,
port: parsedProxyUrl.port
port: parsedProxyUrl.port,
protocol: parsedProxyUrl.protocol
};
if (parsedProxyUrl.auth) {
@ -145,17 +170,8 @@ module.exports = function httpAdapter(config) {
}
if (proxy) {
options.hostname = proxy.host;
options.host = proxy.host;
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
options.port = proxy.port;
options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path;
// Basic proxy authorization
if (proxy.auth) {
var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
}
setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
}
var transport;
@ -171,8 +187,8 @@ module.exports = function httpAdapter(config) {
transport = isHttpsProxy ? httpsFollow : httpFollow;
}
if (config.maxContentLength && config.maxContentLength > -1) {
options.maxBodyLength = config.maxContentLength;
if (config.maxBodyLength > -1) {
options.maxBodyLength = config.maxBodyLength;
}
// Create the request
@ -181,22 +197,27 @@ module.exports = function httpAdapter(config) {
// uncompress the response body transparently if required
var stream = res;
switch (res.headers['content-encoding']) {
/*eslint default-case:0*/
case 'gzip':
case 'compress':
case 'deflate':
// add the unzipper to the body stream processing pipeline
stream = (res.statusCode === 204) ? stream : stream.pipe(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
}
// return the last request in case of redirects
var lastRequest = res.req || req;
// if no content, is HEAD request or decompress disabled we should not decompress
if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {
switch (res.headers['content-encoding']) {
/*eslint default-case:0*/
case 'gzip':
case 'compress':
case 'deflate':
// add the unzipper to the body stream processing pipeline
stream = stream.pipe(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
}
}
var response = {
status: res.statusCode,
statusText: res.statusMessage,
@ -230,6 +251,9 @@ module.exports = function httpAdapter(config) {
var responseData = Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') {
responseData = responseData.toString(config.responseEncoding);
if (!config.responseEncoding || config.responseEncoding === 'utf8') {
responseData = utils.stripBOM(responseData);
}
}
response.data = responseData;
@ -240,7 +264,7 @@ module.exports = function httpAdapter(config) {
// Handle errors
req.on('error', function handleRequestError(err) {
if (req.aborted) return;
if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return;
reject(enhanceError(err, config, null, req));
});

@ -2,6 +2,7 @@
var utils = require('./../utils');
var settle = require('./../core/settle');
var cookies = require('./../helpers/cookies');
var buildURL = require('./../helpers/buildURL');
var buildFullPath = require('../core/buildFullPath');
var parseHeaders = require('./../helpers/parseHeaders');
@ -22,7 +23,7 @@ module.exports = function xhrAdapter(config) {
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
@ -103,8 +104,6 @@ module.exports = function xhrAdapter(config) {
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = require('./../helpers/cookies');
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
@ -170,7 +169,7 @@ module.exports = function xhrAdapter(config) {
});
}
if (requestData === undefined) {
if (!requestData) {
requestData = null;
}

@ -47,6 +47,9 @@ axios.all = function all(promises) {
};
axios.spread = require('./helpers/spread');
// Expose isAxiosError
axios.isAxiosError = require('./helpers/isAxiosError');
module.exports = axios;
// Allow use of default import syntax in TypeScript

@ -73,9 +73,10 @@ Axios.prototype.getUri = function getUri(config) {
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
return this.request(mergeConfig(config || {}, {
method: method,
url: url
url: url,
data: (config || {}).data
}));
};
});
@ -83,7 +84,7 @@ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: data

@ -20,7 +20,7 @@ module.exports = function enhanceError(error, config, code, request, response) {
error.response = response;
error.isAxiosError = true;
error.toJSON = function() {
error.toJSON = function toJSON() {
return {
// Standard
message: this.message,

@ -15,59 +15,73 @@ module.exports = function mergeConfig(config1, config2) {
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var valueFromConfig2Keys = ['url', 'method', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
var defaultToConfig2Keys = [
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath'
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
];
var directMergeKeys = ['validateStatus'];
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
}
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
}
});
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
} else if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (utils.isObject(config1[prop])) {
config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
utils.forEach(directMergeKeys, function merge(prop) {
if (prop in config2) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys);
.concat(defaultToConfig2Keys)
.concat(directMergeKeys);
var otherKeys = Object
.keys(config2)
.keys(config1)
.concat(Object.keys(config2))
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
utils.forEach(otherKeys, mergeDeepProperties);
return config;
};

@ -11,7 +11,7 @@ var createError = require('./createError');
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!validateStatus || validateStatus(response.status)) {
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(

@ -74,6 +74,7 @@ var defaults = {
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;

@ -4,7 +4,6 @@ var utils = require('./../utils');
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').

@ -0,0 +1,11 @@
'use strict';
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
return (typeof payload === 'object') && (payload.isAxiosError === true);
};

@ -105,6 +105,21 @@ function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @return {boolean} True if value is a plain Object, otherwise false
*/
function isPlainObject(val) {
if (toString.call(val) !== '[object Object]') {
return false;
}
var prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
@ -261,34 +276,12 @@ function forEach(obj, fn) {
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else if (isPlainObject(val)) {
result[key] = merge({}, val);
} else if (isArray(val)) {
result[key] = val.slice();
} else {
result[key] = val;
}
@ -319,6 +312,19 @@ function extend(a, b, thisArg) {
return a;
}
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
* @return {string} content value without BOM
*/
function stripBOM(content) {
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1);
}
return content;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
@ -328,6 +334,7 @@ module.exports = {
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
@ -338,7 +345,7 @@ module.exports = {
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
deepMerge: deepMerge,
extend: extend,
trim: trim
trim: trim,
stripBOM: stripBOM
};

@ -0,0 +1,18 @@
Copyright 2014–present Olivier Lalonde <olalonde@gmail.com>, James Talmage <james@talmage.io>, Ruben Verborgh
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:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
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.

@ -0,0 +1,148 @@
## Follow Redirects
Drop-in replacement for Node's `http` and `https` modules that automatically follows redirects.
[![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)
[![Build Status](https://github.com/follow-redirects/follow-redirects/workflows/CI/badge.svg)](https://github.com/follow-redirects/follow-redirects/actions)
[![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master)
[![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects)
[![Sponsor on GitHub](https://img.shields.io/static/v1?label=Sponsor&message=%F0%9F%92%96&logo=GitHub)](https://github.com/sponsors/RubenVerborgh)
`follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback)
methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback)
modules, with the exception that they will seamlessly follow redirects.
```javascript
const { http, https } = require('follow-redirects');
http.get('http://bit.ly/900913', response => {
response.on('data', chunk => {
console.log(chunk);
});
}).on('error', err => {
console.error(err);
});
```
You can inspect the final redirected URL through the `responseUrl` property on the `response`.
If no redirection happened, `responseUrl` is the original request URL.
```javascript
const request = https.request({
host: 'bitly.com',
path: '/UHfDGO',
}, response => {
console.log(response.responseUrl);
// 'http://duckduckgo.com/robots.txt'
});
request.end();
```
## Options
### Global options
Global options are set directly on the `follow-redirects` module:
```javascript
const followRedirects = require('follow-redirects');
followRedirects.maxRedirects = 10;
followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB
```
The following global options are supported:
- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
### Per-request options
Per-request options are set by passing an `options` object:
```javascript
const url = require('url');
const { http, https } = require('follow-redirects');
const options = url.parse('http://bit.ly/900913');
options.maxRedirects = 10;
options.beforeRedirect = (options, { headers }) => {
// Use this to adjust the request options upon redirecting,
// to inspect the latest response headers,
// or to cancel the request by throwing an error
if (options.hostname === "example.com") {
options.auth = "user:password";
}
};
http.request(options);
```
In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback),
the following per-request options are supported:
- `followRedirects` (default: `true`) – whether redirects should be followed.
- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
- `beforeRedirect` (default: `undefined`) – optionally change the request `options` on redirects, or abort the request by throwing an error.
- `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }`
- `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object.
### Advanced usage
By default, `follow-redirects` will use the Node.js default implementations
of [`http`](https://nodejs.org/api/http.html)
and [`https`](https://nodejs.org/api/https.html).
To enable features such as caching and/or intermediate request tracking,
you might instead want to wrap `follow-redirects` around custom protocol implementations:
```javascript
const { http, https } = require('follow-redirects').wrap({
http: require('your-custom-http'),
https: require('your-custom-https'),
});
```
Such custom protocols only need an implementation of the `request` method.
## Browser Usage
Due to the way the browser works,
the `http` and `https` browser equivalents perform redirects by default.
By requiring `follow-redirects` this way:
```javascript
const http = require('follow-redirects/http');
const https = require('follow-redirects/https');
```
you can easily tell webpack and friends to replace
`follow-redirect` by the built-in versions:
```json
{
"follow-redirects/http" : "http",
"follow-redirects/https" : "https"
}
```
## Contributing
Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues)
detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied
by tests. You can run the test suite locally with a simple `npm test` command.
## Debug Logging
`follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging
set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test
suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well.
## Authors
- [Ruben Verborgh](https://ruben.verborgh.org/)
- [Olivier Lalonde](mailto:olalonde@gmail.com)
- [James Talmage](mailto:james@talmage.io)
## License
[MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE)

@ -0,0 +1,14 @@
var debug;
module.exports = function () {
if (!debug) {
try {
/* eslint global-require: off */
debug = require("debug")("follow-redirects");
}
catch (error) {
debug = function () { /* */ };
}
}
debug.apply(null, arguments);
};

@ -0,0 +1 @@
module.exports = require("./").http;

@ -0,0 +1 @@
module.exports = require("./").https;

@ -0,0 +1,504 @@
var url = require("url");
var URL = url.URL;
var http = require("http");
var https = require("https");
var Writable = require("stream").Writable;
var assert = require("assert");
var debug = require("./debug");
// Create handlers that pass events from native requests
var eventHandlers = Object.create(null);
["abort", "aborted", "connect", "error", "socket", "timeout"].forEach(function (event) {
eventHandlers[event] = function (arg1, arg2, arg3) {
this._redirectable.emit(event, arg1, arg2, arg3);
};
});
// Error types with codes
var RedirectionError = createErrorType(
"ERR_FR_REDIRECTION_FAILURE",
""
);
var TooManyRedirectsError = createErrorType(
"ERR_FR_TOO_MANY_REDIRECTS",
"Maximum number of redirects exceeded"
);
var MaxBodyLengthExceededError = createErrorType(
"ERR_FR_MAX_BODY_LENGTH_EXCEEDED",
"Request body larger than maxBodyLength limit"
);
var WriteAfterEndError = createErrorType(
"ERR_STREAM_WRITE_AFTER_END",
"write after end"
);
// An HTTP(S) request that can be redirected
function RedirectableRequest(options, responseCallback) {
// Initialize the request
Writable.call(this);
this._sanitizeOptions(options);
this._options = options;
this._ended = false;
this._ending = false;
this._redirectCount = 0;
this._redirects = [];
this._requestBodyLength = 0;
this._requestBodyBuffers = [];
// Attach a callback if passed
if (responseCallback) {
this.on("response", responseCallback);
}
// React to responses of native requests
var self = this;
this._onNativeResponse = function (response) {
self._processResponse(response);
};
// Perform the first request
this._performRequest();
}
RedirectableRequest.prototype = Object.create(Writable.prototype);
// Writes buffered data to the current native request
RedirectableRequest.prototype.write = function (data, encoding, callback) {
// Writing is not allowed if end has been called
if (this._ending) {
throw new WriteAfterEndError();
}
// Validate input and shift parameters if necessary
if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
throw new TypeError("data should be a string, Buffer or Uint8Array");
}
if (typeof encoding === "function") {
callback = encoding;
encoding = null;
}
// Ignore empty buffers, since writing them doesn't invoke the callback
// https://github.com/nodejs/node/issues/22066
if (data.length === 0) {
if (callback) {
callback();
}
return;
}
// Only write when we don't exceed the maximum body length
if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
this._requestBodyLength += data.length;
this._requestBodyBuffers.push({ data: data, encoding: encoding });
this._currentRequest.write(data, encoding, callback);
}
// Error when we exceed the maximum body length
else {
this.emit("error", new MaxBodyLengthExceededError());
this.abort();
}
};
// Ends the current native request
RedirectableRequest.prototype.end = function (data, encoding, callback) {
// Shift parameters if necessary
if (typeof data === "function") {
callback = data;
data = encoding = null;
}
else if (typeof encoding === "function") {
callback = encoding;
encoding = null;
}
// Write data if needed and end
if (!data) {
this._ended = this._ending = true;
this._currentRequest.end(null, null, callback);
}
else {
var self = this;
var currentRequest = this._currentRequest;
this.write(data, encoding, function () {
self._ended = true;
currentRequest.end(null, null, callback);
});
this._ending = true;
}
};
// Sets a header value on the current native request
RedirectableRequest.prototype.setHeader = function (name, value) {
this._options.headers[name] = value;
this._currentRequest.setHeader(name, value);
};
// Clears a header value on the current native request
RedirectableRequest.prototype.removeHeader = function (name) {
delete this._options.headers[name];
this._currentRequest.removeHeader(name);
};
// Global timeout for all underlying requests
RedirectableRequest.prototype.setTimeout = function (msecs, callback) {
if (callback) {
this.once("timeout", callback);
}
if (this.socket) {
startTimer(this, msecs);
}
else {
var self = this;
this._currentRequest.once("socket", function () {
startTimer(self, msecs);
});
}
this.once("response", clearTimer);
this.once("error", clearTimer);
return this;
};
function startTimer(request, msecs) {
clearTimeout(request._timeout);
request._timeout = setTimeout(function () {
request.emit("timeout");
}, msecs);
}
function clearTimer() {
clearTimeout(this._timeout);
}
// Proxy all other public ClientRequest methods
[
"abort", "flushHeaders", "getHeader",
"setNoDelay", "setSocketKeepAlive",
].forEach(function (method) {
RedirectableRequest.prototype[method] = function (a, b) {
return this._currentRequest[method](a, b);
};
});
// Proxy all public ClientRequest properties
["aborted", "connection", "socket"].forEach(function (property) {
Object.defineProperty(RedirectableRequest.prototype, property, {
get: function () { return this._currentRequest[property]; },
});
});
RedirectableRequest.prototype._sanitizeOptions = function (options) {
// Ensure headers are always present
if (!options.headers) {
options.headers = {};
}
// Since http.request treats host as an alias of hostname,
// but the url module interprets host as hostname plus port,
// eliminate the host property to avoid confusion.
if (options.host) {
// Use hostname if set, because it has precedence
if (!options.hostname) {
options.hostname = options.host;
}
delete options.host;
}
// Complete the URL object when necessary
if (!options.pathname && options.path) {
var searchPos = options.path.indexOf("?");
if (searchPos < 0) {
options.pathname = options.path;
}
else {
options.pathname = options.path.substring(0, searchPos);
options.search = options.path.substring(searchPos);
}
}
};
// Executes the next native request (initial or redirect)
RedirectableRequest.prototype._performRequest = function () {
// Load the native protocol
var protocol = this._options.protocol;
var nativeProtocol = this._options.nativeProtocols[protocol];
if (!nativeProtocol) {
this.emit("error", new TypeError("Unsupported protocol " + protocol));
return;
}
// If specified, use the agent corresponding to the protocol
// (HTTP and HTTPS use different types of agents)
if (this._options.agents) {
var scheme = protocol.substr(0, protocol.length - 1);
this._options.agent = this._options.agents[scheme];
}
// Create the native request
var request = this._currentRequest =
nativeProtocol.request(this._options, this._onNativeResponse);
this._currentUrl = url.format(this._options);
// Set up event handlers
request._redirectable = this;
for (var event in eventHandlers) {
/* istanbul ignore else */
if (event) {
request.on(event, eventHandlers[event]);
}
}
// End a redirected request
// (The first request must be ended explicitly with RedirectableRequest#end)
if (this._isRedirect) {
// Write the request entity and end.
var i = 0;
var self = this;
var buffers = this._requestBodyBuffers;
(function writeNext(error) {
// Only write if this request has not been redirected yet
/* istanbul ignore else */
if (request === self._currentRequest) {
// Report any write errors
/* istanbul ignore if */
if (error) {
self.emit("error", error);
}
// Write the next buffer if there are still left
else if (i < buffers.length) {
var buffer = buffers[i++];
/* istanbul ignore else */
if (!request.finished) {
request.write(buffer.data, buffer.encoding, writeNext);
}
}
// End the request if `end` has been called on us
else if (self._ended) {
request.end();
}
}
}());
}
};
// Processes a response from the current native request
RedirectableRequest.prototype._processResponse = function (response) {
// Store the redirected response
var statusCode = response.statusCode;
if (this._options.trackRedirects) {
this._redirects.push({
url: this._currentUrl,
headers: response.headers,
statusCode: statusCode,
});
}
// RFC7231§6.4: The 3xx (Redirection) class of status code indicates
// that further action needs to be taken by the user agent in order to
// fulfill the request. If a Location header field is provided,
// the user agent MAY automatically redirect its request to the URI
// referenced by the Location field value,
// even if the specific status code is not understood.
var location = response.headers.location;
if (location && this._options.followRedirects !== false &&
statusCode >= 300 && statusCode < 400) {
// Abort the current request
this._currentRequest.removeAllListeners();
this._currentRequest.on("error", noop);
this._currentRequest.abort();
// Discard the remainder of the response to avoid waiting for data
response.destroy();
// RFC7231§6.4: A client SHOULD detect and intervene
// in cyclical redirections (i.e., "infinite" redirection loops).
if (++this._redirectCount > this._options.maxRedirects) {
this.emit("error", new TooManyRedirectsError());
return;
}
// RFC7231§6.4: Automatic redirection needs to done with
// care for methods not known to be safe, […]
// RFC7231§6.4.2–3: For historical reasons, a user agent MAY change
// the request method from POST to GET for the subsequent request.
if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" ||
// RFC7231§6.4.4: The 303 (See Other) status code indicates that
// the server is redirecting the user agent to a different resource […]
// A user agent can perform a retrieval request targeting that URI
// (a GET or HEAD request if using HTTP) […]
(statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) {
this._options.method = "GET";
// Drop a possible entity and headers related to it
this._requestBodyBuffers = [];
removeMatchingHeaders(/^content-/i, this._options.headers);
}
// Drop the Host header, as the redirect might lead to a different host
var previousHostName = removeMatchingHeaders(/^host$/i, this._options.headers) ||
url.parse(this._currentUrl).hostname;
// Create the redirected request
var redirectUrl = url.resolve(this._currentUrl, location);
debug("redirecting to", redirectUrl);
this._isRedirect = true;
var redirectUrlParts = url.parse(redirectUrl);
Object.assign(this._options, redirectUrlParts);
// Drop the Authorization header if redirecting to another host
if (redirectUrlParts.hostname !== previousHostName) {
removeMatchingHeaders(/^authorization$/i, this._options.headers);
}
// Evaluate the beforeRedirect callback
if (typeof this._options.beforeRedirect === "function") {
var responseDetails = { headers: response.headers };
try {
this._options.beforeRedirect.call(null, this._options, responseDetails);
}
catch (err) {
this.emit("error", err);
return;
}
this._sanitizeOptions(this._options);
}
// Perform the redirected request
try {
this._performRequest();
}
catch (cause) {
var error = new RedirectionError("Redirected request failed: " + cause.message);
error.cause = cause;
this.emit("error", error);
}
}
else {
// The response is not a redirect; return it as-is
response.responseUrl = this._currentUrl;
response.redirects = this._redirects;
this.emit("response", response);
// Clean up
this._requestBodyBuffers = [];
}
};
// Wraps the key/value object of protocols with redirect functionality
function wrap(protocols) {
// Default settings
var exports = {
maxRedirects: 21,
maxBodyLength: 10 * 1024 * 1024,
};
// Wrap each protocol
var nativeProtocols = {};
Object.keys(protocols).forEach(function (scheme) {
var protocol = scheme + ":";
var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
// Executes a request, following redirects
function request(input, options, callback) {
// Parse parameters
if (typeof input === "string") {
var urlStr = input;
try {
input = urlToOptions(new URL(urlStr));
}
catch (err) {
/* istanbul ignore next */
input = url.parse(urlStr);
}
}
else if (URL && (input instanceof URL)) {
input = urlToOptions(input);
}
else {
callback = options;
options = input;
input = { protocol: protocol };
}
if (typeof options === "function") {
callback = options;
options = null;
}
// Set defaults
options = Object.assign({
maxRedirects: exports.maxRedirects,
maxBodyLength: exports.maxBodyLength,
}, input, options);
options.nativeProtocols = nativeProtocols;
assert.equal(options.protocol, protocol, "protocol mismatch");
debug("options", options);
return new RedirectableRequest(options, callback);
}
// Executes a GET request, following redirects
function get(input, options, callback) {
var wrappedRequest = wrappedProtocol.request(input, options, callback);
wrappedRequest.end();
return wrappedRequest;
}
// Expose the properties on the wrapped protocol
Object.defineProperties(wrappedProtocol, {
request: { value: request, configurable: true, enumerable: true, writable: true },
get: { value: get, configurable: true, enumerable: true, writable: true },
});
});
return exports;
}
/* istanbul ignore next */
function noop() { /* empty */ }
// from https://github.com/nodejs/node/blob/master/lib/internal/url.js
function urlToOptions(urlObject) {
var options = {
protocol: urlObject.protocol,
hostname: urlObject.hostname.startsWith("[") ?
/* istanbul ignore next */
urlObject.hostname.slice(1, -1) :
urlObject.hostname,
hash: urlObject.hash,
search: urlObject.search,
pathname: urlObject.pathname,
path: urlObject.pathname + urlObject.search,
href: urlObject.href,
};
if (urlObject.port !== "") {
options.port = Number(urlObject.port);
}
return options;
}
function removeMatchingHeaders(regex, headers) {
var lastValue;
for (var header in headers) {
if (regex.test(header)) {
lastValue = headers[header];
delete headers[header];
}
}
return lastValue;
}
function createErrorType(code, defaultMessage) {
function CustomError(message) {
Error.captureStackTrace(this, this.constructor);
this.message = message || defaultMessage;
}
CustomError.prototype = new Error();
CustomError.prototype.constructor = CustomError;
CustomError.prototype.name = "Error [" + code + "]";
CustomError.prototype.code = code;
return CustomError;
}
// Exports
module.exports = wrap({ http: http, https: https });
module.exports.wrap = wrap;

@ -0,0 +1,98 @@
{
"_args": [
[
"follow-redirects@1.13.2",
"/home/sigonasr2/divar/server"
]
],
"_from": "follow-redirects@1.13.2",
"_id": "follow-redirects@1.13.2",
"_inBundle": false,
"_integrity": "sha512-6mPTgLxYm3r6Bkkg0vNM0HTjfGrOEtsfbhagQvbxDEsEkpNhw582upBaoRZylzen6krEmxXJgt9Ju6HiI4O7BA==",
"_location": "/axios/follow-redirects",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "follow-redirects@1.13.2",
"name": "follow-redirects",
"escapedName": "follow-redirects",
"rawSpec": "1.13.2",
"saveSpec": null,
"fetchSpec": "1.13.2"
},
"_requiredBy": [
"/axios"
],
"_resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.13.2.tgz",
"_spec": "1.13.2",
"_where": "/home/sigonasr2/divar/server",
"author": {
"name": "Ruben Verborgh",
"email": "ruben@verborgh.org",
"url": "https://ruben.verborgh.org/"
},
"bugs": {
"url": "https://github.com/follow-redirects/follow-redirects/issues"
},
"contributors": [
{
"name": "Olivier Lalonde",
"email": "olalonde@gmail.com",
"url": "http://www.syskall.com"
},
{
"name": "James Talmage",
"email": "james@talmage.io"
}
],
"description": "HTTP and HTTPS modules that follow redirects.",
"devDependencies": {
"concat-stream": "^2.0.0",
"eslint": "^5.16.0",
"express": "^4.16.4",
"lolex": "^3.1.0",
"mocha": "^6.0.2",
"nyc": "^14.1.1"
},
"engines": {
"node": ">=4.0"
},
"files": [
"*.js"
],
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"homepage": "https://github.com/follow-redirects/follow-redirects",
"keywords": [
"http",
"https",
"url",
"redirect",
"client",
"location",
"utility"
],
"license": "MIT",
"main": "index.js",
"name": "follow-redirects",
"peerDependenciesMeta": {
"debug": {
"optional": true
}
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/follow-redirects/follow-redirects.git"
},
"scripts": {
"lint": "eslint *.js test",
"mocha": "nyc mocha",
"test": "npm run lint && npm run mocha"
},
"version": "1.13.2"
}

@ -1,27 +1,31 @@
{
"_from": "axios@^0.19.2",
"_id": "axios@0.19.2",
"_args": [
[
"axios@0.21.1",
"/home/sigonasr2/divar/server"
]
],
"_from": "axios@0.21.1",
"_id": "axios@0.21.1",
"_inBundle": false,
"_integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==",
"_integrity": "sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==",
"_location": "/axios",
"_phantomChildren": {},
"_requested": {
"type": "range",
"type": "version",
"registry": true,
"raw": "axios@^0.19.2",
"raw": "axios@0.21.1",
"name": "axios",
"escapedName": "axios",
"rawSpec": "^0.19.2",
"rawSpec": "0.21.1",
"saveSpec": null,
"fetchSpec": "^0.19.2"
"fetchSpec": "0.21.1"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz",
"_shasum": "3ea36c5d8818d0d5f8a8a97a6d36b86cdc00cb27",
"_spec": "axios@^0.19.2",
"_resolved": "https://registry.npmjs.org/axios/-/axios-0.21.1.tgz",
"_spec": "0.21.1",
"_where": "/home/sigonasr2/divar/server",
"author": {
"name": "Matt Zabriskie"
@ -32,7 +36,6 @@
"bugs": {
"url": "https://github.com/axios/axios/issues"
},
"bundleDependencies": false,
"bundlesize": [
{
"path": "./dist/axios.min.js",
@ -40,9 +43,8 @@
}
],
"dependencies": {
"follow-redirects": "1.5.10"
"follow-redirects": "^1.10.0"
},
"deprecated": false,
"description": "Promise based HTTP client for the browser and node.js",
"devDependencies": {
"bundlesize": "^0.17.0",
@ -82,6 +84,7 @@
"webpack-dev-server": "^1.14.1"
},
"homepage": "https://github.com/axios/axios",
"jsdelivr": "dist/axios.min.js",
"keywords": [
"xhr",
"http",
@ -108,5 +111,6 @@
"version": "npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"
},
"typings": "./index.d.ts",
"version": "0.19.2"
"unpkg": "dist/axios.min.js",
"version": "0.21.1"
}

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2013-2015 Petka Antonov
Copyright (c) 2013-2018 Petka Antonov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

@ -2,8 +2,10 @@
<img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
title="Promises/A+ 1.1 compliant" align="right" />
</a>
[![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird)
[![coverage-98%](http://img.shields.io/badge/coverage-98%-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
[![coverage-98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html)
**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises)
@ -15,6 +17,10 @@ See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html)
For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
### Note
Promises in Node.js 10 are significantly faster than before. Bluebird still includes a lot of features like cancellation, iteration methods and warnings that native promises don't. If you are using Bluebird for performance rather than for those - please consider giving native promises a shot and running the benchmarks yourself.
# Questions and issues
The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`.
@ -29,7 +35,7 @@ Thanks to BrowserStack for providing us with a free account which lets us suppor
The MIT License (MIT)
Copyright (c) 2013-2016 Petka Antonov
Copyright (c) 2013-2019 Petka Antonov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

@ -1,7 +1,7 @@
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 Petka Antonov
* Copyright (c) 2013-2018 Petka Antonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
@ -23,7 +23,7 @@
*
*/
/**
* bluebird build version 3.4.7
* bluebird build version 3.7.2
* Features enabled: core
* Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/
@ -33,7 +33,6 @@ var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = _dereq_("./schedule");
var Queue = _dereq_("./queue");
var util = _dereq_("./util");
function Async() {
this._customScheduler = false;
@ -41,7 +40,6 @@ function Async() {
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
@ -60,16 +58,6 @@ Async.prototype.hasCustomScheduler = function() {
return this._customScheduler;
};
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
@ -118,62 +106,33 @@ function AsyncSettlePromises(promise) {
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
function _drainQueue(queue) {
while (queue.length() > 0) {
_drainQueueStep(queue);
}
}
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
function _drainQueueStep(queue) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
} else {
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
}
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
_drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
_drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
@ -190,7 +149,7 @@ Async.prototype._reset = function () {
module.exports = Async;
module.exports.firstLineError = firstLineError;
},{"./queue":17,"./schedule":18,"./util":21}],2:[function(_dereq_,module,exports){
},{"./queue":17,"./schedule":18}],2:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
@ -520,11 +479,12 @@ return Context;
},{}],7:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
module.exports = function(Promise, Context,
enableAsyncHooks, disableAsyncHooks) {
var async = Promise._async;
var Warning = _dereq_("./errors").Warning;
var util = _dereq_("./util");
var es5 = _dereq_("./es5");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
@ -550,6 +510,34 @@ var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
var deferUnhandledRejectionCheck;
(function() {
var promises = [];
function unhandledRejectionCheck() {
for (var i = 0; i < promises.length; ++i) {
promises[i]._notifyUnhandledRejection();
}
unhandledRejectionClear();
}
function unhandledRejectionClear() {
promises.length = 0;
}
deferUnhandledRejectionCheck = function(promise) {
promises.push(promise);
setTimeout(unhandledRejectionCheck, 1);
};
es5.defineProperty(Promise, "_unhandledRejectionCheck", {
value: unhandledRejectionCheck
});
es5.defineProperty(Promise, "_unhandledRejectionClear", {
value: unhandledRejectionClear
});
})();
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
@ -559,7 +547,7 @@ Promise.prototype.suppressUnhandledRejections = function() {
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
deferUnhandledRejectionCheck(this);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
@ -617,19 +605,13 @@ Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
var context = Promise._getContext();
possiblyUnhandledRejection = util.contextBind(context, fn);
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
var context = Promise._getContext();
unhandledRejectionHandled = util.contextBind(context, fn);
};
var disableLongStackTraces = function() {};
@ -640,6 +622,7 @@ Promise.longStackTraces = function () {
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
@ -647,14 +630,14 @@ Promise.longStackTraces = function () {
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
@ -662,37 +645,85 @@ Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var legacyHandlers = {
unhandledrejection: {
before: function() {
var ret = util.global.onunhandledrejection;
util.global.onunhandledrejection = null;
return ret;
},
after: function(fn) {
util.global.onunhandledrejection = fn;
}
},
rejectionhandled: {
before: function() {
var ret = util.global.onrejectionhandled;
util.global.onrejectionhandled = null;
return ret;
},
after: function(fn) {
util.global.onrejectionhandled = fn;
}
}
};
var fireDomEvent = (function() {
var dispatch = function(legacy, e) {
if (legacy) {
var fn;
try {
fn = legacy.before();
return !util.global.dispatchEvent(e);
} finally {
legacy.after(fn);
}
} else {
return !util.global.dispatchEvent(e);
}
};
try {
if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new CustomEvent(name.toLowerCase(), {
name = name.toLowerCase();
var eventData = {
detail: event,
cancelable: true
});
return !util.global.dispatchEvent(domEvent);
};
var domEvent = new CustomEvent(name, eventData);
es5.defineProperty(
domEvent, "promise", {value: event.promise});
es5.defineProperty(
domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
};
} else if (typeof Event === "function") {
var event = new Event("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new Event(name.toLowerCase(), {
name = name.toLowerCase();
var domEvent = new Event(name, {
cancelable: true
});
domEvent.detail = event;
return !util.global.dispatchEvent(domEvent);
es5.defineProperty(domEvent, "promise", {value: event.promise});
es5.defineProperty(domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
};
} else {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function(name, event) {
name = name.toLowerCase();
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true,
domEvent.initCustomEvent(name, false, true,
event);
return !util.global.dispatchEvent(domEvent);
return dispatch(legacyHandlers[name], domEvent);
};
}
} catch (e) {}
@ -810,6 +841,18 @@ Promise.config = function(opts) {
Promise.prototype._fireEvent = defaultFireEvent;
}
}
if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
var prev = config.asyncHooks;
var cur = !!opts.asyncHooks;
if (prev !== cur) {
config.asyncHooks = cur;
if (cur) {
enableAsyncHooks();
} else {
disableAsyncHooks();
}
}
}
return Promise;
};
@ -830,6 +873,7 @@ Promise.prototype._attachCancellationCallback = function(onCancel) {
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._dereferenceTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
@ -935,6 +979,10 @@ function longStackTracesAttachExtraTrace(error, ignoreSelf) {
}
}
function longStackTracesDereferenceTrace() {
this._trace = undefined;
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) {
if (returnValue === undefined && promiseCreated !== null &&
@ -1192,8 +1240,8 @@ function parseLineInfo(line) {
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstStackLines = (firstLineError.stack || "").split("\n");
var lastStackLines = (lastLineError.stack || "").split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
@ -1402,12 +1450,16 @@ var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
monitoring: false,
asyncHooks: false
};
if (longStackTraces) Promise.longStackTraces();
return {
asyncHooks: function() {
return config.asyncHooks;
},
longStackTraces: function() {
return config.longStackTraces;
},
@ -1436,7 +1488,7 @@ return {
};
};
},{"./errors":9,"./util":21}],8:[function(_dereq_,module,exports){
},{"./errors":9,"./es5":10,"./util":21}],8:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function returner() {
@ -1686,10 +1738,11 @@ if (isES5) {
},{}],11:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, tryConvertToPromise) {
module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
var util = _dereq_("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
@ -1741,7 +1794,9 @@ function finallyHandler(reasonOrValue) {
var ret = this.isFinallyHandler()
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret !== undefined) {
if (ret === NEXT_FILTER) {
return ret;
} else if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
@ -1790,18 +1845,49 @@ Promise.prototype["finally"] = function (handler) {
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
Promise.prototype.tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if(len === 1) {
return this._passThrough(handlerOrPredicate,
1,
undefined,
finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError(
"tapCatch statement predicate: "
+ "expecting an object but got " + util.classString(item)
));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this),
1,
undefined,
finallyHandler);
}
};
return PassThroughHandlerContext;
};
},{"./util":21}],12:[function(_dereq_,module,exports){
},{"./catch_filter":5,"./util":21}],12:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) {
var util = _dereq_("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
@ -1947,10 +2033,8 @@ Promise.join = function () {
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
var context = Promise._getContext();
holder.fn = util.contextBind(context, holder.fn);
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
@ -2092,20 +2176,42 @@ var apiRejection = function(msg) {
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = _dereq_("./util");
util.setReflectHandler(reflectHandler);
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
var getDomain = function() {
var domain = process.domain;
if (domain === undefined) {
return null;
}
return domain;
};
var getContextDefault = function() {
return null;
};
var getContextDomain = function() {
return {
domain: getDomain(),
async: null
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
};
var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ?
_dereq_("async_hooks").AsyncResource : null;
var getContextAsyncHooks = function() {
return {
domain: getDomain(),
async: new AsyncResource("Bluebird::Promise")
};
};
var getContext = util.isNode ? getContextDomain : getContextDefault;
util.notEnumerableProp(Promise, "_getContext", getContext);
var enableAsyncHooks = function() {
getContext = getContextAsyncHooks;
util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks);
};
var disableAsyncHooks = function() {
getContext = getContextDomain;
util.notEnumerableProp(Promise, "_getContext", getContextDomain);
};
var es5 = _dereq_("./es5");
var Async = _dereq_("./async");
@ -2129,33 +2235,36 @@ var PromiseArray =
var Context = _dereq_("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = _dereq_("./debuggability")(Promise, Context);
var debug = _dereq_("./debuggability")(Promise, Context,
enableAsyncHooks, disableAsyncHooks);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
_dereq_("./finally")(Promise, tryConvertToPromise);
_dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = _dereq_("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
}
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
if (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
@ -2174,12 +2283,17 @@ Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("expecting an object but got " +
"A catch statement predicate " + util.classString(item));
return apiRejection("Catch statement predicate: " +
"expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
if (typeof fn !== "function") {
throw new TypeError("The last argument to .catch() " +
"must be a function, got " + util.toString(fn));
}
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
@ -2320,7 +2434,7 @@ Promise.prototype._then = function (
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
var context = getContext();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
@ -2338,15 +2452,14 @@ Promise.prototype._then = function (
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
handler: util.contextBind(context, handler),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
target._addCallbacks(didFulfill, didReject, promise,
receiver, context);
}
return promise;
@ -2407,7 +2520,15 @@ Promise.prototype._setWillBeCancelled = function() {
Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
var bitField = this._bitField;
this._bitField = bitField |
(((bitField & 536870912) >> 2) ^
134217728);
};
Promise.prototype._setNoAsyncGuarantee = function() {
this._bitField = (this._bitField | 536870912) &
(~134217728);
};
Promise.prototype._receiverAt = function (index) {
@ -2462,7 +2583,7 @@ Promise.prototype._addCallbacks = function (
reject,
promise,
receiver,
domain
context
) {
var index = this._length();
@ -2475,12 +2596,10 @@ Promise.prototype._addCallbacks = function (
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
this._fulfillmentHandler0 = util.contextBind(context, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
this._rejectionHandler0 = util.contextBind(context, reject);
}
} else {
var base = index * 4 - 4;
@ -2488,11 +2607,11 @@ Promise.prototype._addCallbacks = function (
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : util.domainBind(domain, fulfill);
util.contextBind(context, fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : util.domainBind(domain, reject);
util.contextBind(context, reject);
}
}
this._setLength(index + 1);
@ -2512,6 +2631,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
@ -2528,7 +2648,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
this._setFollowee(maybePromise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
@ -2554,6 +2674,7 @@ function(reason, synchronous, ignoreNonErrorWarnings) {
};
Promise.prototype._resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this;
this._captureStackTrace();
this._pushContext();
@ -2717,6 +2838,7 @@ Promise.prototype._fulfill = function (value) {
} else {
async.settlePromises(this);
}
this._dereferenceTrace();
}
};
@ -2785,6 +2907,14 @@ Promise.prototype._settledValue = function() {
}
};
if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
get: function () {
return "Object";
}
});
}
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
@ -2809,9 +2939,9 @@ _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
_dereq_("./direct_resolve")(Promise);
_dereq_("./synchronous_inspection")(Promise);
_dereq_("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async);
Promise.Promise = Promise;
Promise.version = "3.4.7";
Promise.version = "3.7.2";
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
@ -2837,7 +2967,7 @@ Promise.version = "3.4.7";
};
},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(_dereq_,module,exports){
},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21,"async_hooks":undefined}],16:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) {
@ -2848,6 +2978,7 @@ function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
case -6: return new Map();
}
}
@ -2855,6 +2986,7 @@ function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
values.suppressUnhandledRejections();
}
promise._setOnCancel(this);
this._values = values;
@ -3121,7 +3253,8 @@ if (util.isNode && typeof MutationObserver === "undefined") {
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
(window.navigator.standalone || window.cordova))) {
(window.navigator.standalone || window.cordova)) &&
("classList" in document.documentElement)) {
schedule = (function() {
var div = document.createElement("div");
var opts = {attributes: true};
@ -3135,11 +3268,11 @@ if (util.isNode && typeof MutationObserver === "undefined") {
var scheduleToggle = function() {
if (toggleScheduled) return;
toggleScheduled = true;
div2.classList.toggle("foo");
};
toggleScheduled = true;
div2.classList.toggle("foo");
};
return function schedule(fn) {
return function schedule(fn) {
var o = new MutationObserver(function() {
o.disconnect();
fn();
@ -3552,8 +3685,12 @@ function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) new FakeConstructor();
var receiver = new FakeConstructor();
function ic() {
return typeof receiver.foo;
}
ic();
ic();
return obj;
eval(obj);
}
@ -3580,10 +3717,11 @@ function safeToString(obj) {
}
function isError(obj) {
return obj !== null &&
return obj instanceof Error ||
(obj !== null &&
typeof obj === "object" &&
typeof obj.message === "string" &&
typeof obj.name === "string";
typeof obj.name === "string");
}
function markAsOriginatingFromRejection(e) {
@ -3678,18 +3816,42 @@ function getNativePromise() {
if (typeof Promise === "function") {
try {
var promise = new Promise(function(){});
if ({}.toString.call(promise) === "[object Promise]") {
if (classString(promise) === "[object Promise]") {
return Promise;
}
} catch (e) {}
}
}
function domainBind(self, cb) {
return self.bind(cb);
var reflectHandler;
function contextBind(ctx, cb) {
if (ctx === null ||
typeof cb !== "function" ||
cb === reflectHandler) {
return cb;
}
if (ctx.domain !== null) {
cb = ctx.domain.bind(cb);
}
var async = ctx.async;
if (async !== null) {
var old = cb;
cb = function() {
var args = (new Array(2)).concat([].slice.call(arguments));;
args[0] = old;
args[1] = this;
return async.runInAsyncScope.apply(async, args);
};
}
return cb;
}
var ret = {
setReflectHandler: function(fn) {
reflectHandler = fn;
},
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
@ -3716,24 +3878,37 @@ var ret = {
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode,
hasEnvVariables: hasEnvVariables,
env: env,
global: globalObject,
getNativePromise: getNativePromise,
domainBind: domainBind
contextBind: contextBind
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
var version;
if (process.versions && process.versions.node) {
version = process.versions.node.split(".").map(Number);
} else if (process.version) {
version = process.version.split(".").map(Number);
}
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
ret.nodeSupportsAsyncResource = ret.isNode && (function() {
var supportsAsync = false;
try {
var res = _dereq_("async_hooks").AsyncResource;
supportsAsync = typeof res.prototype.runInAsyncScope === "function";
} catch (e) {
supportsAsync = false;
}
return supportsAsync;
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
},{"./es5":10}]},{},[3])(3)
},{"./es5":10,"async_hooks":undefined}]},{},[3])(3)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -3,7 +3,6 @@ var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = require("./schedule");
var Queue = require("./queue");
var util = require("./util");
function Async() {
this._customScheduler = false;
@ -11,7 +10,6 @@ function Async() {
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
@ -30,16 +28,6 @@ Async.prototype.hasCustomScheduler = function() {
return this._customScheduler;
};
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
@ -88,62 +76,33 @@ function AsyncSettlePromises(promise) {
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
function _drainQueue(queue) {
while (queue.length() > 0) {
_drainQueueStep(queue);
}
}
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
function _drainQueueStep(queue) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
} else {
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
}
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
_drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
_drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {

@ -1,9 +1,10 @@
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
module.exports = function(Promise, Context,
enableAsyncHooks, disableAsyncHooks) {
var async = Promise._async;
var Warning = require("./errors").Warning;
var util = require("./util");
var es5 = require("./es5");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
@ -29,6 +30,34 @@ var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
var deferUnhandledRejectionCheck;
(function() {
var promises = [];
function unhandledRejectionCheck() {
for (var i = 0; i < promises.length; ++i) {
promises[i]._notifyUnhandledRejection();
}
unhandledRejectionClear();
}
function unhandledRejectionClear() {
promises.length = 0;
}
deferUnhandledRejectionCheck = function(promise) {
promises.push(promise);
setTimeout(unhandledRejectionCheck, 1);
};
es5.defineProperty(Promise, "_unhandledRejectionCheck", {
value: unhandledRejectionCheck
});
es5.defineProperty(Promise, "_unhandledRejectionClear", {
value: unhandledRejectionClear
});
})();
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
@ -38,7 +67,7 @@ Promise.prototype.suppressUnhandledRejections = function() {
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
deferUnhandledRejectionCheck(this);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
@ -96,19 +125,13 @@ Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
var context = Promise._getContext();
possiblyUnhandledRejection = util.contextBind(context, fn);
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
var context = Promise._getContext();
unhandledRejectionHandled = util.contextBind(context, fn);
};
var disableLongStackTraces = function() {};
@ -119,6 +142,7 @@ Promise.longStackTraces = function () {
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
@ -126,14 +150,14 @@ Promise.longStackTraces = function () {
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
@ -141,37 +165,85 @@ Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var legacyHandlers = {
unhandledrejection: {
before: function() {
var ret = util.global.onunhandledrejection;
util.global.onunhandledrejection = null;
return ret;
},
after: function(fn) {
util.global.onunhandledrejection = fn;
}
},
rejectionhandled: {
before: function() {
var ret = util.global.onrejectionhandled;
util.global.onrejectionhandled = null;
return ret;
},
after: function(fn) {
util.global.onrejectionhandled = fn;
}
}
};
var fireDomEvent = (function() {
var dispatch = function(legacy, e) {
if (legacy) {
var fn;
try {
fn = legacy.before();
return !util.global.dispatchEvent(e);
} finally {
legacy.after(fn);
}
} else {
return !util.global.dispatchEvent(e);
}
};
try {
if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new CustomEvent(name.toLowerCase(), {
name = name.toLowerCase();
var eventData = {
detail: event,
cancelable: true
});
return !util.global.dispatchEvent(domEvent);
};
var domEvent = new CustomEvent(name, eventData);
es5.defineProperty(
domEvent, "promise", {value: event.promise});
es5.defineProperty(
domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
};
} else if (typeof Event === "function") {
var event = new Event("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new Event(name.toLowerCase(), {
name = name.toLowerCase();
var domEvent = new Event(name, {
cancelable: true
});
domEvent.detail = event;
return !util.global.dispatchEvent(domEvent);
es5.defineProperty(domEvent, "promise", {value: event.promise});
es5.defineProperty(domEvent, "reason", {value: event.reason});
return dispatch(legacyHandlers[name], domEvent);
};
} else {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function(name, event) {
name = name.toLowerCase();
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true,
domEvent.initCustomEvent(name, false, true,
event);
return !util.global.dispatchEvent(domEvent);
return dispatch(legacyHandlers[name], domEvent);
};
}
} catch (e) {}
@ -289,6 +361,18 @@ Promise.config = function(opts) {
Promise.prototype._fireEvent = defaultFireEvent;
}
}
if ("asyncHooks" in opts && util.nodeSupportsAsyncResource) {
var prev = config.asyncHooks;
var cur = !!opts.asyncHooks;
if (prev !== cur) {
config.asyncHooks = cur;
if (cur) {
enableAsyncHooks();
} else {
disableAsyncHooks();
}
}
}
return Promise;
};
@ -309,6 +393,7 @@ Promise.prototype._attachCancellationCallback = function(onCancel) {
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._dereferenceTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
@ -414,6 +499,10 @@ function longStackTracesAttachExtraTrace(error, ignoreSelf) {
}
}
function longStackTracesDereferenceTrace() {
this._trace = undefined;
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) {
if (returnValue === undefined && promiseCreated !== null &&
@ -671,8 +760,8 @@ function parseLineInfo(line) {
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstStackLines = (firstLineError.stack || "").split("\n");
var lastStackLines = (lastLineError.stack || "").split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
@ -881,12 +970,16 @@ var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
monitoring: false,
asyncHooks: false
};
if (longStackTraces) Promise.longStackTraces();
return {
asyncHooks: function() {
return config.asyncHooks;
},
longStackTraces: function() {
return config.longStackTraces;
},

@ -1,8 +1,9 @@
"use strict";
module.exports = function(Promise, tryConvertToPromise) {
module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
var util = require("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
var catchFilter = require("./catch_filter")(NEXT_FILTER);
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
@ -54,7 +55,9 @@ function finallyHandler(reasonOrValue) {
var ret = this.isFinallyHandler()
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret !== undefined) {
if (ret === NEXT_FILTER) {
return ret;
} else if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
@ -103,9 +106,41 @@ Promise.prototype["finally"] = function (handler) {
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
Promise.prototype.tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if(len === 1) {
return this._passThrough(handlerOrPredicate,
1,
undefined,
finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError(
"tapCatch statement predicate: "
+ "expecting an object but got " + util.classString(item)
));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this),
1,
undefined,
finallyHandler);
}
};
return PassThroughHandlerContext;
};

@ -157,7 +157,7 @@ PromiseSpawn.prototype._continue = function (result) {
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)

@ -1,7 +1,6 @@
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
@ -147,10 +146,8 @@ Promise.join = function () {
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
var context = Promise._getContext();
holder.fn = util.contextBind(context, holder.fn);
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
@ -159,7 +156,7 @@ Promise.join = function () {
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len ; ++$_i) {args[$_i] = arguments[$_i ];};
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;

@ -5,7 +5,6 @@ module.exports = function(Promise,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
@ -14,8 +13,8 @@ var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : util.domainBind(domain, fn);
var context = Promise._getContext();
this._callback = util.contextBind(context, fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
@ -23,6 +22,14 @@ function MappingPromiseArray(promises, fn, limit, _filter) {
this._inFlight = 0;
this._queue = [];
async.invoke(this._asyncInit, this, undefined);
if (util.isArray(promises)) {
for (var i = 0; i < promises.length; ++i) {
var maybePromise = promises[i];
if (maybePromise instanceof Promise) {
maybePromise.suppressUnhandledRejections();
}
}
}
}
util.inherits(MappingPromiseArray, PromiseArray);

@ -12,20 +12,42 @@ var apiRejection = function(msg) {
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = require("./util");
util.setReflectHandler(reflectHandler);
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
var getDomain = function() {
var domain = process.domain;
if (domain === undefined) {
return null;
}
return domain;
};
var getContextDefault = function() {
return null;
};
var getContextDomain = function() {
return {
domain: getDomain(),
async: null
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
};
var AsyncResource = util.isNode && util.nodeSupportsAsyncResource ?
require("async_hooks").AsyncResource : null;
var getContextAsyncHooks = function() {
return {
domain: getDomain(),
async: new AsyncResource("Bluebird::Promise")
};
};
var getContext = util.isNode ? getContextDomain : getContextDefault;
util.notEnumerableProp(Promise, "_getContext", getContext);
var enableAsyncHooks = function() {
getContext = getContextAsyncHooks;
util.notEnumerableProp(Promise, "_getContext", getContextAsyncHooks);
};
var disableAsyncHooks = function() {
getContext = getContextDomain;
util.notEnumerableProp(Promise, "_getContext", getContextDomain);
};
var es5 = require("./es5");
var Async = require("./async");
@ -49,33 +71,36 @@ var PromiseArray =
var Context = require("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var debug = require("./debuggability")(Promise, Context,
enableAsyncHooks, disableAsyncHooks);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
require("./finally")(Promise, tryConvertToPromise);
require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
}
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
if (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
@ -94,12 +119,17 @@ Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("expecting an object but got " +
"A catch statement predicate " + util.classString(item));
return apiRejection("Catch statement predicate: " +
"expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
if (typeof fn !== "function") {
throw new TypeError("The last argument to .catch() " +
"must be a function, got " + util.toString(fn));
}
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
@ -240,7 +270,7 @@ Promise.prototype._then = function (
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
var context = getContext();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
@ -258,15 +288,14 @@ Promise.prototype._then = function (
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
handler: util.contextBind(context, handler),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
target._addCallbacks(didFulfill, didReject, promise,
receiver, context);
}
return promise;
@ -327,7 +356,15 @@ Promise.prototype._setWillBeCancelled = function() {
Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
var bitField = this._bitField;
this._bitField = bitField |
(((bitField & 536870912) >> 2) ^
134217728);
};
Promise.prototype._setNoAsyncGuarantee = function() {
this._bitField = (this._bitField | 536870912) &
(~134217728);
};
Promise.prototype._receiverAt = function (index) {
@ -382,7 +419,7 @@ Promise.prototype._addCallbacks = function (
reject,
promise,
receiver,
domain
context
) {
var index = this._length();
@ -395,12 +432,10 @@ Promise.prototype._addCallbacks = function (
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
this._fulfillmentHandler0 = util.contextBind(context, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
this._rejectionHandler0 = util.contextBind(context, reject);
}
} else {
var base = index * 4 - 4;
@ -408,11 +443,11 @@ Promise.prototype._addCallbacks = function (
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : util.domainBind(domain, fulfill);
util.contextBind(context, fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : util.domainBind(domain, reject);
util.contextBind(context, reject);
}
}
this._setLength(index + 1);
@ -432,6 +467,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
@ -448,7 +484,7 @@ Promise.prototype._resolveCallback = function(value, shouldBind) {
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
this._setFollowee(maybePromise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
@ -474,6 +510,7 @@ function(reason, synchronous, ignoreNonErrorWarnings) {
};
Promise.prototype._resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this;
this._captureStackTrace();
this._pushContext();
@ -637,6 +674,7 @@ Promise.prototype._fulfill = function (value) {
} else {
async.settlePromises(this);
}
this._dereferenceTrace();
}
};
@ -705,6 +743,14 @@ Promise.prototype._settledValue = function() {
}
};
if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
get: function () {
return "Object";
}
});
}
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
@ -729,14 +775,12 @@ require("./cancel")(Promise, PromiseArray, apiRejection, debug);
require("./direct_resolve")(Promise);
require("./synchronous_inspection")(Promise);
require("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async);
Promise.Promise = Promise;
Promise.version = "3.4.7";
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
Promise.version = "3.7.2";
require('./call_get.js')(Promise);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL, debug);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./nodeify.js')(Promise);
require('./promisify.js')(Promise, INTERNAL);
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
@ -744,9 +788,11 @@ require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./settle.js')(Promise, PromiseArray, debug);
require('./some.js')(Promise, PromiseArray, apiRejection);
require('./filter.js')(Promise, INTERNAL);
require('./each.js')(Promise, INTERNAL);
require('./timers.js')(Promise, INTERNAL, debug);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./any.js')(Promise);
require('./each.js')(Promise, INTERNAL);
require('./filter.js')(Promise, INTERNAL);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);

@ -8,6 +8,7 @@ function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
case -6: return new Map();
}
}
@ -15,6 +16,7 @@ function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
values.suppressUnhandledRejections();
}
promise._setOnCancel(this);
this._values = values;

@ -55,7 +55,7 @@ function PropertiesPromiseArray(obj) {
}
this.constructor$(entries);
this._isMap = isMap;
this._init$(undefined, -3);
this._init$(undefined, isMap ? -6 : -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save