got 11.4.0 → 11.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/source/as-promise/index.d.ts +1 -3
  2. package/dist/source/as-promise/index.js +56 -117
  3. package/dist/source/as-promise/normalize-arguments.d.ts +3 -0
  4. package/dist/source/as-promise/normalize-arguments.js +78 -0
  5. package/dist/source/as-promise/parse-body.d.ts +3 -0
  6. package/dist/source/as-promise/parse-body.js +25 -0
  7. package/dist/source/as-promise/types.d.ts +235 -58
  8. package/dist/source/as-promise/types.js +29 -16
  9. package/dist/source/{as-promise → core}/calculate-retry-delay.d.ts +2 -1
  10. package/dist/source/core/calculate-retry-delay.js +29 -0
  11. package/dist/source/core/index.d.ts +851 -28
  12. package/dist/source/core/index.js +291 -55
  13. package/dist/source/core/utils/dns-ip-version.js +1 -0
  14. package/dist/source/core/utils/get-body-size.d.ts +2 -4
  15. package/dist/source/core/utils/is-form-data.d.ts +2 -2
  16. package/dist/source/core/utils/is-response-ok.d.ts +2 -0
  17. package/dist/source/core/utils/is-response-ok.js +8 -0
  18. package/dist/source/core/utils/options-to-url.d.ts +0 -1
  19. package/dist/source/core/utils/timed-out.js +1 -0
  20. package/dist/source/core/utils/url-to-options.d.ts +0 -1
  21. package/dist/source/core/utils/weakable-map.d.ts +1 -1
  22. package/dist/source/create.js +42 -13
  23. package/dist/source/index.js +16 -6
  24. package/dist/source/types.d.ts +245 -8
  25. package/dist/source/utils/deep-freeze.d.ts +1 -1
  26. package/dist/source/utils/deprecation-warning.js +1 -1
  27. package/package.json +30 -29
  28. package/readme.md +171 -35
  29. package/dist/source/as-promise/calculate-retry-delay.js +0 -38
  30. package/dist/source/as-promise/core.d.ts +0 -13
  31. package/dist/source/as-promise/core.js +0 -124
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "got",
3
- "version": "11.4.0",
3
+ "version": "11.6.0",
4
4
  "description": "Human-friendly and powerful HTTP request library for Node.js",
5
5
  "license": "MIT",
6
6
  "repository": "sindresorhus/got",
@@ -10,7 +10,7 @@
10
10
  "node": ">=10.19.0"
11
11
  },
12
12
  "scripts": {
13
- "test": "xo && tsc --noEmit && nyc --reporter=html --reporter=text ava",
13
+ "test": "xo && npm run build && nyc --reporter=html --reporter=text ava",
14
14
  "release": "np",
15
15
  "build": "del-cli dist && tsc",
16
16
  "prepare": "npm run build"
@@ -43,14 +43,14 @@
43
43
  "ky"
44
44
  ],
45
45
  "dependencies": {
46
- "@sindresorhus/is": "^2.1.1",
46
+ "@sindresorhus/is": "^3.1.1",
47
47
  "@szmarczak/http-timer": "^4.0.5",
48
48
  "@types/cacheable-request": "^6.0.1",
49
49
  "@types/responselike": "^1.0.0",
50
50
  "cacheable-lookup": "^5.0.3",
51
51
  "cacheable-request": "^7.0.1",
52
52
  "decompress-response": "^6.0.0",
53
- "http2-wrapper": "^1.0.0-beta.4.5",
53
+ "http2-wrapper": "^1.0.0-beta.5.2",
54
54
  "lowercase-keys": "^2.0.0",
55
55
  "p-cancelable": "^2.0.0",
56
56
  "responselike": "^2.0.0"
@@ -59,35 +59,39 @@
59
59
  "@ava/typescript": "^1.1.1",
60
60
  "@sindresorhus/tsconfig": "^0.7.0",
61
61
  "@sinonjs/fake-timers": "^6.0.1",
62
- "@types/benchmark": "^1.0.31",
63
- "@types/express": "^4.17.6",
64
- "@types/node": "^13.13.4",
65
- "@types/node-fetch": "^2.5.5",
66
- "@types/request": "^2.48.4",
67
- "@types/sinon": "^9.0.0",
62
+ "@types/benchmark": "^1.0.33",
63
+ "@types/express": "^4.17.7",
64
+ "@types/node": "^14.6.0",
65
+ "@types/node-fetch": "^2.5.7",
66
+ "@types/pem": "^1.9.5",
67
+ "@types/pify": "^3.0.2",
68
+ "@types/request": "^2.48.5",
69
+ "@types/sinon": "^9.0.5",
68
70
  "@types/tough-cookie": "^4.0.0",
69
- "ava": "^3.6.0",
70
- "axios": "^0.19.2",
71
+ "ava": "^3.11.1",
72
+ "axios": "^0.20.0",
71
73
  "benchmark": "^2.1.4",
72
- "coveralls": "^3.0.4",
74
+ "coveralls": "^3.1.0",
73
75
  "create-test-server": "^3.0.1",
74
- "del-cli": "^3.0.0",
75
- "delay": "^4.3.0",
76
+ "del-cli": "^3.0.1",
77
+ "delay": "^4.4.0",
76
78
  "express": "^4.17.1",
77
79
  "form-data": "^3.0.0",
78
- "get-stream": "^5.1.0",
79
- "nock": "^12.0.0",
80
+ "get-stream": "^6.0.0",
81
+ "nock": "^13.0.4",
80
82
  "node-fetch": "^2.6.0",
81
- "np": "^6.0.0",
82
- "nyc": "^15.0.1",
83
- "p-event": "^4.1.0",
84
- "sinon": "^9.0.2",
83
+ "np": "^6.4.0",
84
+ "nyc": "^15.1.0",
85
+ "p-event": "^4.2.0",
86
+ "pem": "^1.14.4",
87
+ "pify": "^5.0.0",
88
+ "sinon": "^9.0.3",
85
89
  "slow-stream": "0.0.4",
86
- "tempy": "^0.5.0",
90
+ "tempy": "^0.6.0",
87
91
  "to-readable-stream": "^2.1.0",
88
92
  "tough-cookie": "^4.0.0",
89
- "typescript": "3.8.3",
90
- "xo": "^0.30.0"
93
+ "typescript": "^4.0.2",
94
+ "xo": "^0.33.0"
91
95
  },
92
96
  "types": "dist/source",
93
97
  "sideEffects": false,
@@ -116,13 +120,10 @@
116
120
  ],
117
121
  "rules": {
118
122
  "@typescript-eslint/no-empty-function": "off",
119
- "@typescript-eslint/no-base-to-string": "off",
120
123
  "node/prefer-global/url": "off",
121
124
  "node/prefer-global/url-search-params": "off",
122
- "@typescript-eslint/prefer-readonly-parameter-types": "off",
123
- "@typescript-eslint/no-floating-promises": "off",
124
- "@typescript-eslint/method-signature-style": "off",
125
- "unicorn/no-fn-reference-in-iterator": "off"
125
+ "import/no-anonymous-default-export": "off",
126
+ "@typescript-eslint/no-invalid-void-type": "off"
126
127
  }
127
128
  },
128
129
  "runkitExampleFilename": "./documentation/examples/runkit-example.js"
package/readme.md CHANGED
@@ -40,7 +40,7 @@ For browser usage, we recommend [Ky](https://github.com/sindresorhus/ky) by the
40
40
  - [Errors with metadata](#errors)
41
41
  - [JSON mode](#json-mode)
42
42
  - [WHATWG URL support](#url)
43
- - [HTTPS API](#https)
43
+ - [HTTPS API](#advanced-https-api)
44
44
  - [Hooks](#hooks)
45
45
  - [Instances with custom defaults](#instances)
46
46
  - [Types](#types)
@@ -120,6 +120,8 @@ const pipeline = promisify(stream.pipeline);
120
120
 
121
121
  **Tip:** `from.pipe(to)` doesn't forward errors. Instead, use [`stream.pipeline(from, ..., to, callback)`](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback).
122
122
 
123
+ **Note:** While `got.post('https://example.com')` resolves, `got.stream.post('https://example.com')` will hang indefinitely until a body is provided. If there's no body on purpose, remember to `.end()` the stream or set the [`body`](#body) option to an empty string.
124
+
123
125
  ### API
124
126
 
125
127
  It's a `GET` request by default, but can be changed by using different methods or via [`options.method`](#method).
@@ -508,12 +510,10 @@ Default:
508
510
 
509
511
  An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
510
512
 
511
- **Note:** When using streams, this option is ignored. If the connection is reset when downloading, you need to catch the error and clear the file you were writing into to prevent duplicated content.
512
-
513
513
  If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.\
514
514
  If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
515
515
 
516
- Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
516
+ Delays between retries counts with function `1000 * Math.pow(2, retry - 1) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
517
517
 
518
518
  The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
519
519
 
@@ -527,6 +527,36 @@ By default, it retries *only* on the specified methods, status codes, and on the
527
527
  - `ENETUNREACH`: No internet connection.
528
528
  - `EAI_AGAIN`: DNS lookup timed out.
529
529
 
530
+ <a name="retry-stream"></a>
531
+
532
+ You can retry Got streams too. The implementation looks like this:
533
+
534
+ ```js
535
+ const got = require('got');
536
+ const fs = require('fs');
537
+
538
+ let writeStream;
539
+
540
+ const fn = (retryCount = 0) => {
541
+ const stream = got.stream('https://example.com');
542
+ stream.retryCount = retryCount;
543
+
544
+ if (writeStream) {
545
+ writeStream.destroy();
546
+ }
547
+
548
+ writeStream = fs.createWriteStream('example.com');
549
+
550
+ stream.pipe(writeStream);
551
+
552
+ // If you don't attach the listener, it will NOT make a retry.
553
+ // It automatically checks the listener count so it knows whether to retry or not :)
554
+ stream.once('retry', fn);
555
+ };
556
+
557
+ fn();
558
+ ```
559
+
530
560
  ###### followRedirect
531
561
 
532
562
  Type: `boolean`\
@@ -577,6 +607,13 @@ Default: `false`
577
607
 
578
608
  [Cache adapter instance](#cache-adapters) for storing cached response data.
579
609
 
610
+ ###### cacheOptions
611
+
612
+ Type: `object | undefined`\
613
+ Default: `{}`
614
+
615
+ [Cache options](https://github.com/kornelski/http-cache-semantics#constructor-options) used for the specified request.
616
+
580
617
  ###### dnsCache
581
618
 
582
619
  Type: `CacheableLookup | false`\
@@ -697,7 +734,7 @@ Default: `[]`
697
734
 
698
735
  Called with [normalized](source/core/index.ts) [request options](#options). Got will make no further changes to the request before it is sent. This is especially useful in conjunction with [`got.extend()`](#instances) when you want to create an API client that, for example, uses HMAC-signing.
699
736
 
700
- See the [AWS section](#aws) for an example.
737
+ **Tip:** You can override the `request` function by returning a [`ClientRequest`-like](https://nodejs.org/api/http.html#http_class_http_clientrequest) instance or a [`IncomingMessage`-like](https://nodejs.org/api/http.html#http_class_http_incomingmessage) instance. This is very useful when creating a custom cache mechanism.
701
738
 
702
739
  ###### hooks.beforeRedirect
703
740
 
@@ -908,6 +945,13 @@ Default: `Infinity`
908
945
 
909
946
  The maximum amount of items that should be emitted.
910
947
 
948
+ ###### pagination.backoff
949
+
950
+ Type: `number`\
951
+ Default: `0`
952
+
953
+ Milliseconds to wait before the next request is triggered.
954
+
911
955
  ###### pagination.requestLimit
912
956
 
913
957
  Type: `number`\
@@ -1241,6 +1285,13 @@ If the `content-length` header is missing, `total` will be `undefined`.
1241
1285
  })();
1242
1286
  ```
1243
1287
 
1288
+ ##### .once('retry', retryCount, error)
1289
+
1290
+ To enable retrying on a Got stream, it is required to have a `retry` handler attached.\
1291
+ When this event is emitted, you should reset the stream you were writing to and prepare the body again.
1292
+
1293
+ See the [`retry`](#retry-stream) option for an example implementation.
1294
+
1244
1295
  ##### .ip
1245
1296
 
1246
1297
  Type: `string`
@@ -1563,13 +1614,13 @@ const addAccessToken = (accessToken: string): BeforeRequestHook => options => {
1563
1614
  Each error contains an `options` property which are the options Got used to create a request - just to make debugging easier.\
1564
1615
  Additionaly, the errors may have `request` (Got Stream) and `response` (Got Response) properties depending on which phase of the request failed.
1565
1616
 
1566
- #### got.CacheError
1617
+ #### got.RequestError
1567
1618
 
1568
- When a cache method fails, for example, if the database goes down or there's a filesystem error.
1619
+ When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. All the errors below inherit this one.
1569
1620
 
1570
- #### got.RequestError
1621
+ #### got.CacheError
1571
1622
 
1572
- When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
1623
+ When a cache method fails, for example, if the database goes down or there's a filesystem error.
1573
1624
 
1574
1625
  #### got.ReadError
1575
1626
 
@@ -1579,6 +1630,10 @@ When reading from response stream fails.
1579
1630
 
1580
1631
  When server response code is 2xx, and parsing body fails. Includes a `response` property.
1581
1632
 
1633
+ #### got.UploadError
1634
+
1635
+ When the request body is a stream and an error occurs while reading from that stream.
1636
+
1582
1637
  #### got.HTTPError
1583
1638
 
1584
1639
  When the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304. Includes a `response` property.
@@ -1591,14 +1646,14 @@ When the server redirects you more than ten times. Includes a `response` propert
1591
1646
 
1592
1647
  When given an unsupported protocol.
1593
1648
 
1594
- #### got.CancelError
1595
-
1596
- When the request is aborted with `.cancel()`.
1597
-
1598
1649
  #### got.TimeoutError
1599
1650
 
1600
1651
  When the request is aborted due to a [timeout](#timeout). Includes an `event` and `timings` property.
1601
1652
 
1653
+ #### got.CancelError
1654
+
1655
+ When the request is aborted with `.cancel()`.
1656
+
1602
1657
  ## Aborting the request
1603
1658
 
1604
1659
  The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which when called, aborts the request.
@@ -1726,7 +1781,7 @@ const tunnel = require('tunnel');
1726
1781
 
1727
1782
  got('https://sindresorhus.com', {
1728
1783
  agent: {
1729
- https: tunnel.httpOverHttp({
1784
+ https: tunnel.httpsOverHttp({
1730
1785
  proxy: {
1731
1786
  host: 'localhost'
1732
1787
  }
@@ -1735,8 +1790,30 @@ got('https://sindresorhus.com', {
1735
1790
  });
1736
1791
  ```
1737
1792
 
1793
+ Otherwise, you can use the [`hpagent`](https://github.com/delvedor/hpagent) package, which keeps the internal sockets alive to be reused.
1794
+
1795
+ ```js
1796
+ const got = require('got');
1797
+ const {HttpsProxyAgent} = require('hpagent');
1798
+
1799
+ got('https://sindresorhus.com', {
1800
+ agent: {
1801
+ https: new HttpsProxyAgent({
1802
+ keepAlive: true,
1803
+ keepAliveMsecs: 1000,
1804
+ maxSockets: 256,
1805
+ maxFreeSockets: 256,
1806
+ scheduling: 'lifo',
1807
+ proxy: 'https://localhost:8080'
1808
+ })
1809
+ }
1810
+ });
1811
+ ```
1812
+
1738
1813
  Alternatively, use [`global-agent`](https://github.com/gajus/global-agent) to configure a global proxy for all HTTP/HTTPS traffic in your program.
1739
1814
 
1815
+ Read the [`http2-wrapper`](https://github.com/szmarczak/http2-wrapper/#proxy-support) docs to learn about proxying for HTTP/2.
1816
+
1740
1817
  ## Cookies
1741
1818
 
1742
1819
  You can use the [`tough-cookie`](https://github.com/salesforce/tough-cookie) package:
@@ -1823,29 +1900,14 @@ got('unix:/var/run/docker.sock:/containers/json');
1823
1900
 
1824
1901
  ## AWS
1825
1902
 
1826
- Requests to AWS services need to have their headers signed. This can be accomplished by using the [`aws4`](https://www.npmjs.com/package/aws4) package. This is an example for querying an ["API Gateway"](https://docs.aws.amazon.com/apigateway/api-reference/signing-requests/) with a signed request.
1903
+ Requests to AWS services need to have their headers signed. This can be accomplished by using the [`got4aws`](https://www.npmjs.com/package/got4aws) package. This is an example for querying an ["API Gateway"](https://docs.aws.amazon.com/apigateway/api-reference/signing-requests/) with a signed request.
1827
1904
 
1828
1905
  ```js
1829
- const got = require('got');
1830
- const AWS = require('aws-sdk');
1831
- const aws4 = require('aws4');
1906
+ const got4aws = require('got4aws');;
1832
1907
 
1833
- const chain = new AWS.CredentialProviderChain();
1908
+ const awsClient = got4aws();
1834
1909
 
1835
- // Create a Got instance to use relative paths and signed requests
1836
- const awsClient = got.extend({
1837
- prefixUrl: 'https://<api-id>.execute-api.<api-region>.amazonaws.com/<stage>/',
1838
- hooks: {
1839
- beforeRequest: [
1840
- async options => {
1841
- const credentials = await chain.resolvePromise();
1842
- aws4.sign(options, credentials);
1843
- }
1844
- ]
1845
- }
1846
- });
1847
-
1848
- const response = await awsClient('endpoint/path', {
1910
+ const response = await awsClient('https://<api-id>.execute-api.<api-region>.amazonaws.com/<stage>/endpoint/path', {
1849
1911
  // Request-specific options
1850
1912
  });
1851
1913
  ```
@@ -1869,6 +1931,32 @@ nock('https://sindresorhus.com')
1869
1931
  })();
1870
1932
  ```
1871
1933
 
1934
+ Bear in mind, that by default `nock` mocks only one request. Got will [retry](#retry) on failed requests by default, causing a `No match for request ...` error. The solution is to either disable retrying (set `options.retry` to `0`) or call `.persist()` on the mocked request.
1935
+
1936
+ ```js
1937
+ const got = require('got');
1938
+ const nock = require('nock');
1939
+
1940
+ const scope = nock('https://sindresorhus.com')
1941
+ .get('/')
1942
+ .reply(500, 'Internal server error')
1943
+ .persist();
1944
+
1945
+ (async () => {
1946
+ try {
1947
+ await got('https://sindresorhus.com')
1948
+ } catch (error) {
1949
+ console.log(error.response.body);
1950
+ //=> 'Internal server error'
1951
+
1952
+ console.log(error.response.retryCount);
1953
+ //=> 2
1954
+ }
1955
+
1956
+ scope.persist(false);
1957
+ })();
1958
+ ```
1959
+
1872
1960
  For real integration testing we recommend using [`ava`](https://github.com/avajs/ava) with [`create-test-server`](https://github.com/lukechilds/create-test-server). We're using a macro so we don't have to `server.listen()` and `server.close()` every test. Take a look at one of our tests:
1873
1961
 
1874
1962
  ```js
@@ -2019,11 +2107,14 @@ The Electron `net` module is not consistent with the Node.js `http` module. See
2019
2107
  | Bugs | [![][gbg]][g6] | [![][rbg]][r6] | [![][nbg]][n6] | [![][kbg]][k6] | [![][abg]][a6] | [![][sbg]][s6] |
2020
2108
  | Dependents | [![][gdp]][g7] | [![][rdp]][r7] | [![][ndp]][n7] | [![][kdp]][k7] | [![][adp]][a7] | [![][sdp]][s7] |
2021
2109
  | Install size | [![][gis]][g8] | [![][ris]][r8] | [![][nis]][n8] | [![][kis]][k8] | [![][ais]][a8] | [![][sis]][s8] |
2110
+ | GitHub stars | [![][gs]][g9] | [![][rs]][r9] | [![][ns]][n9] | [![][ks]][k9] | [![][as]][a9] | [![][ss]][s9] |
2111
+ | TypeScript support | [![][gts]][g10] | [![][rts]][r10] | [![][nts]][n10] | [![][kts]][k10] | [![][ats]][a10] | [![][sts]][s11] |
2112
+ | Last commit | [![][glc]][g11] | [![][rlc]][r11] | [![][nlc]][n11] | [![][klc]][k11] | [![][alc]][a11] | [![][slc]][s11] |
2022
2113
 
2023
2114
  \* It's almost API compatible with the browser `fetch` API.\
2024
2115
  \*\* Need to switch the protocol manually. Doesn't accept PUSH streams and doesn't reuse HTTP/2 sessions.\
2025
2116
  \*\*\* Currently, only `DownloadProgress` event is supported, `UploadProgress` event is not supported.\
2026
- :sparkle: Almost-stable feature, but the API may change. Don't hestitate to try it out!\
2117
+ :sparkle: Almost-stable feature, but the API may change. Don't hesitate to try it out!\
2027
2118
  :grey_question: Feature in early stage of development. Very experimental.
2028
2119
 
2029
2120
  <!-- GITHUB -->
@@ -2153,9 +2244,54 @@ The Electron `net` module is not consistent with the Node.js `http` module. See
2153
2244
  [a8]: https://packagephobia.now.sh/result?p=axios
2154
2245
  [s8]: https://packagephobia.now.sh/result?p=superagent
2155
2246
 
2247
+ <!-- GITHUB STARS -->
2248
+ [gs]: https://badgen.net/github/stars/sindresorhus/got?label
2249
+ [ks]: https://badgen.net/github/stars/sindresorhus/ky?label
2250
+ [rs]: https://badgen.net/github/stars/request/request?label
2251
+ [ns]: https://badgen.net/github/stars/bitinn/node-fetch?label
2252
+ [as]: https://badgen.net/github/stars/axios/axios?label
2253
+ [ss]: https://badgen.net/github/stars/visionmedia/superagent?label
2254
+
2255
+ [g9]: https://github.com/sindresorhus/got
2256
+ [k9]: https://github.com/sindresorhus/ky
2257
+ [r9]: https://github.com/request/request
2258
+ [n9]: https://github.com/node-fetch/node-fetch
2259
+ [a9]: https://github.com/axios/axios
2260
+ [s9]: https://github.com/visionmedia/superagent
2261
+
2262
+ <!-- TYPESCRIPT SUPPORT -->
2263
+ [gts]: https://badgen.net/npm/types/got?label
2264
+ [kts]: https://badgen.net/npm/types/ky?label
2265
+ [rts]: https://badgen.net/npm/types/request?label
2266
+ [nts]: https://badgen.net/npm/types/node-fetch?label
2267
+ [ats]: https://badgen.net/npm/types/axios?label
2268
+ [sts]: https://badgen.net/npm/types/superagent?label
2269
+
2270
+ [g10]: https://github.com/sindresorhus/got
2271
+ [k10]: https://github.com/sindresorhus/ky
2272
+ [r10]: https://github.com/request/request
2273
+ [n10]: https://github.com/node-fetch/node-fetch
2274
+ [a10]: https://github.com/axios/axios
2275
+ [s10]: https://github.com/visionmedia/superagent
2276
+
2277
+ <!-- LAST COMMIT -->
2278
+ [glc]: https://badgen.net/github/last-commit/sindresorhus/got?label
2279
+ [klc]: https://badgen.net/github/last-commit/sindresorhus/ky?label
2280
+ [rlc]: https://badgen.net/github/last-commit/request/request?label
2281
+ [nlc]: https://badgen.net/github/last-commit/bitinn/node-fetch?label
2282
+ [alc]: https://badgen.net/github/last-commit/axios/axios?label
2283
+ [slc]: https://badgen.net/github/last-commit/visionmedia/superagent?label
2284
+
2285
+ [g11]: https://github.com/sindresorhus/got/commits
2286
+ [k11]: https://github.com/sindresorhus/ky/commits
2287
+ [r11]: https://github.com/request/request/commits
2288
+ [n11]: https://github.com/node-fetch/node-fetch/commits
2289
+ [a11]: https://github.com/axios/axios/commits
2290
+ [s11]: https://github.com/visionmedia/superagent/commits
2291
+
2156
2292
  [Click here][InstallSizeOfTheDependencies] to see the install size of the Got dependencies.
2157
2293
 
2158
- [InstallSizeOfTheDependencies]: https://packagephobia.now.sh/result?p=@sindresorhus/is@1.0.0,@szmarczak/http-timer@3.1.0,@types/cacheable-request@6.0.1,cacheable-lookup@0.2.1,cacheable-request@7.0.0,decompress-response@5.0.0,duplexer3@0.1.4,get-stream@5.0.0,lowercase-keys@2.0.0,mimic-response@2.0.0,p-cancelable@2.0.0,responselike@2.0.0,to-readable-stream@2.0.0,type-fest@0.8.0
2294
+ [InstallSizeOfTheDependencies]: https://packagephobia.com/result?p=@sindresorhus/is@3.0.0,@szmarczak/http-timer@4.0.5,@types/cacheable-request@6.0.1,@types/responselike@1.0.0,cacheable-lookup@5.0.3,cacheable-request@7.0.1,decompress-response@6.0.0,http2-wrapper@1.0.0,lowercase-keys@2.0.0,p-cancelable@2.0.0,responselike@2.0.0
2159
2295
 
2160
2296
  ## Related
2161
2297
 
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const types_1 = require("./types");
4
- const retryAfterStatusCodes = new Set([413, 429, 503]);
5
- const isErrorWithResponse = (error) => (error instanceof types_1.HTTPError || error instanceof types_1.ParseError || error instanceof types_1.MaxRedirectsError);
6
- const calculateRetryDelay = ({ attemptCount, retryOptions, error }) => {
7
- if (attemptCount > retryOptions.limit) {
8
- return 0;
9
- }
10
- const hasMethod = retryOptions.methods.includes(error.options.method);
11
- const hasErrorCode = retryOptions.errorCodes.includes(error.code);
12
- const hasStatusCode = isErrorWithResponse(error) && retryOptions.statusCodes.includes(error.response.statusCode);
13
- if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {
14
- return 0;
15
- }
16
- if (isErrorWithResponse(error)) {
17
- const { response } = error;
18
- if (response && 'retry-after' in response.headers && retryAfterStatusCodes.has(response.statusCode)) {
19
- let after = Number(response.headers['retry-after']);
20
- if (Number.isNaN(after)) {
21
- after = Date.parse(response.headers['retry-after']) - Date.now();
22
- }
23
- else {
24
- after *= 1000;
25
- }
26
- if (retryOptions.maxRetryAfter === undefined || after > retryOptions.maxRetryAfter) {
27
- return 0;
28
- }
29
- return after;
30
- }
31
- if (response.statusCode === 413) {
32
- return 0;
33
- }
34
- }
35
- const noise = Math.random() * 100;
36
- return ((2 ** (attemptCount - 1)) * 1000) + noise;
37
- };
38
- exports.default = calculateRetryDelay;
@@ -1,13 +0,0 @@
1
- /// <reference types="node" />
2
- import { URL } from 'url';
3
- import { Options, NormalizedOptions, Defaults, ResponseType, Response } from './types';
4
- import Request, { ParseJsonFunction } from '../core';
5
- export declare const knownBodyTypes: string[];
6
- export declare const parseBody: (response: Response<unknown>, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: string | undefined) => unknown;
7
- export default class PromisableRequest extends Request {
8
- ['constructor']: typeof PromisableRequest;
9
- options: NormalizedOptions;
10
- static normalizeArguments(url?: string | URL, nonNormalizedOptions?: Options, defaults?: Defaults): NormalizedOptions;
11
- static mergeOptions(...sources: Options[]): NormalizedOptions;
12
- _beforeError(error: Error): Promise<void>;
13
- }
@@ -1,124 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const is_1 = require("@sindresorhus/is");
4
- const types_1 = require("./types");
5
- const core_1 = require("../core");
6
- if (!core_1.knownHookEvents.includes('beforeRetry')) {
7
- core_1.knownHookEvents.push('beforeRetry', 'afterResponse');
8
- }
9
- exports.knownBodyTypes = ['json', 'buffer', 'text'];
10
- // @ts-ignore The error is: Not all code paths return a value.
11
- exports.parseBody = (response, responseType, parseJson, encoding) => {
12
- const { rawBody } = response;
13
- try {
14
- if (responseType === 'text') {
15
- return rawBody.toString(encoding);
16
- }
17
- if (responseType === 'json') {
18
- return rawBody.length === 0 ? '' : parseJson(rawBody.toString());
19
- }
20
- if (responseType === 'buffer') {
21
- return Buffer.from(rawBody);
22
- }
23
- throw new types_1.ParseError({
24
- message: `Unknown body type '${responseType}'`,
25
- name: 'Error'
26
- }, response);
27
- }
28
- catch (error) {
29
- throw new types_1.ParseError(error, response);
30
- }
31
- };
32
- class PromisableRequest extends core_1.default {
33
- static normalizeArguments(url, nonNormalizedOptions, defaults) {
34
- const options = super.normalizeArguments(url, nonNormalizedOptions, defaults);
35
- if (is_1.default.null_(options.encoding)) {
36
- throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
37
- }
38
- is_1.assert.any([is_1.default.string, is_1.default.undefined], options.encoding);
39
- is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.resolveBodyOnly);
40
- is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.methodRewriting);
41
- is_1.assert.any([is_1.default.boolean, is_1.default.undefined], options.isStream);
42
- is_1.assert.any([is_1.default.string, is_1.default.undefined], options.responseType);
43
- // `options.responseType`
44
- if (options.responseType === undefined) {
45
- options.responseType = 'text';
46
- }
47
- // `options.retry`
48
- const { retry } = options;
49
- if (defaults) {
50
- options.retry = { ...defaults.retry };
51
- }
52
- else {
53
- options.retry = {
54
- calculateDelay: retryObject => retryObject.computedValue,
55
- limit: 0,
56
- methods: [],
57
- statusCodes: [],
58
- errorCodes: [],
59
- maxRetryAfter: undefined
60
- };
61
- }
62
- if (is_1.default.object(retry)) {
63
- options.retry = {
64
- ...options.retry,
65
- ...retry
66
- };
67
- options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))];
68
- options.retry.statusCodes = [...new Set(options.retry.statusCodes)];
69
- options.retry.errorCodes = [...new Set(options.retry.errorCodes)];
70
- }
71
- else if (is_1.default.number(retry)) {
72
- options.retry.limit = retry;
73
- }
74
- if (is_1.default.undefined(options.retry.maxRetryAfter)) {
75
- options.retry.maxRetryAfter = Math.min(...[options.timeout.request, options.timeout.connect].filter(is_1.default.number));
76
- }
77
- // `options.pagination`
78
- if (is_1.default.object(options.pagination)) {
79
- if (defaults) {
80
- options.pagination = {
81
- ...defaults.pagination,
82
- ...options.pagination
83
- };
84
- }
85
- const { pagination } = options;
86
- if (!is_1.default.function_(pagination.transform)) {
87
- throw new Error('`options.pagination.transform` must be implemented');
88
- }
89
- if (!is_1.default.function_(pagination.shouldContinue)) {
90
- throw new Error('`options.pagination.shouldContinue` must be implemented');
91
- }
92
- if (!is_1.default.function_(pagination.filter)) {
93
- throw new TypeError('`options.pagination.filter` must be implemented');
94
- }
95
- if (!is_1.default.function_(pagination.paginate)) {
96
- throw new Error('`options.pagination.paginate` must be implemented');
97
- }
98
- }
99
- // JSON mode
100
- if (options.responseType === 'json' && options.headers.accept === undefined) {
101
- options.headers.accept = 'application/json';
102
- }
103
- return options;
104
- }
105
- static mergeOptions(...sources) {
106
- let mergedOptions;
107
- for (const source of sources) {
108
- mergedOptions = PromisableRequest.normalizeArguments(undefined, source, mergedOptions);
109
- }
110
- return mergedOptions;
111
- }
112
- async _beforeError(error) {
113
- if (this.destroyed) {
114
- return;
115
- }
116
- if (!(error instanceof core_1.RequestError)) {
117
- error = new core_1.RequestError(error.message, error, this);
118
- }
119
- // Let the promise decide whether to abort or not
120
- // It is also responsible for the `beforeError` hook
121
- this.emit('error', error);
122
- }
123
- }
124
- exports.default = PromisableRequest;