rekwest 5.0.3 → 5.2.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.
package/README.md CHANGED
@@ -1,241 +1,244 @@
1
- The robust request library that humanity deserves 🌐
2
- ---
3
- This package provides highly likely functional and **easy-to-use** abstraction atop of
4
- native [http(s).request](https://nodejs.org/api/https.html#httpsrequesturl-options-callback)
5
- and [http2.request](https://nodejs.org/api/http2.html#clienthttp2sessionrequestheaders-options).
6
-
7
- ## Abstract
8
-
9
- * Fetch-alike
10
- * Cool-beans 🫐 config options (with defaults)
11
- * Automatic HTTP/2 support (ALPN negotiation)
12
- * Automatic or opt-in body parse (with non-UTF-8 charset decoding)
13
- * Automatic and simplistic `Cookies` treatment (with built-in **jar** & **ttl**)
14
- * Automatic decompression (with opt-in body compression)
15
- * Built-in streamable `FormData` interface
16
- * Support redirects & retries with fine-grained tune-ups
17
- * Support all legit request body types (include blobs & streams)
18
- * Support both CJS and ESM module systems
19
- * Fully promise-able and pipe-able
20
- * Zero dependencies
21
-
22
- ## Prerequisites
23
-
24
- * Node.js `>= 18.13.0`
25
-
26
- ## Installation
27
-
28
- ```bash
29
- npm install rekwest --save
30
- ```
31
-
32
- ### Usage
33
-
34
- ```javascript
35
- import rekwest, { constants } from 'rekwest';
36
-
37
- const {
38
- HTTP2_HEADER_AUTHORIZATION,
39
- HTTP2_HEADER_CONTENT_ENCODING,
40
- HTTP2_METHOD_POST,
41
- HTTP_STATUS_OK,
42
- } = constants;
43
-
44
- const url = 'https://somewhe.re/somewhat/endpoint';
45
-
46
- const res = await rekwest(url, {
47
- body: { celestial: 'payload' },
48
- headers: {
49
- [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
50
- [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
51
- /** [HTTP2_HEADER_CONTENT_TYPE]
52
- * is undue for
53
- * Array/Blob/File/FormData/Object/URLSearchParams body types
54
- * and will be set automatically, with an option to override it here
55
- */
56
- },
57
- method: HTTP2_METHOD_POST,
58
- });
59
-
60
- console.assert(res.statusCode === HTTP_STATUS_OK);
61
- console.info(res.headers);
62
- console.log(res.body);
63
- ```
64
-
65
- ---
66
-
67
- ```javascript
68
- import { Readable } from 'node:stream';
69
- import rekwest, {
70
- constants,
71
- Blob,
72
- File,
73
- FormData,
74
- } from 'rekwest';
75
-
76
- const {
77
- HTTP2_HEADER_AUTHORIZATION,
78
- HTTP2_HEADER_CONTENT_ENCODING,
79
- HTTP2_METHOD_POST,
80
- HTTP_STATUS_OK,
81
- } = constants;
82
-
83
- const blob = new Blob(['bits']);
84
- const file = new File(['bits'], 'file.dab');
85
- const readable = Readable.from('bits');
86
-
87
- const fd = new FormData({
88
- aux: Date.now(), // either [[key, value]] or kv sequenceable
89
- });
90
-
91
- fd.append('celestial', 'payload');
92
- fd.append('blob', blob, 'blob.dab');
93
- fd.append('file', file);
94
- fd.append('readable', readable, 'readable.dab');
95
-
96
- const url = 'https://somewhe.re/somewhat/endpoint';
97
-
98
- const res = await rekwest(url, {
99
- body: fd,
100
- headers: {
101
- [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
102
- [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
103
- },
104
- method: HTTP2_METHOD_POST,
105
- });
106
-
107
- console.assert(res.statusCode === HTTP_STATUS_OK);
108
- console.info(res.headers);
109
- console.log(res.body);
110
- ```
111
-
112
- ### API
113
-
114
- #### `rekwest(url[, options])`
115
-
116
- * `url` **{string | URL}** The URL to send the request to
117
- * `options` **{Object}**
118
- Extends [http(s).RequestOptions](https://nodejs.org/api/https.html#httpsrequesturl-options-callback) along with
119
- extra [http2.ClientSessionOptions](https://nodejs.org/api/http2.html#http2connectauthority-options-listener)
120
- & [http2.ClientSessionRequestOptions](https://nodejs.org/api/http2.html#clienthttp2sessionrequestheaders-options)
121
- and [tls.ConnectionOptions](https://nodejs.org/api/tls.html#tlsconnectoptions-callback)
122
- for HTTP/2 attunes
123
- * `baseURL` **{string | URL}** The base URL to use in cases where `url` is a relative URL
124
- * `body` **{string | Array | ArrayBuffer | ArrayBufferView | AsyncIterator | Blob | Buffer | DataView | File |
125
- FormData | Iterator | Object | Readable | ReadableStream | SharedArrayBuffer | URLSearchParams}** The body to send
126
- with the request
127
- * `cookies` **{boolean | Array<[k, v]> | Array<string\> | Cookies | Object | URLSearchParams}** `Default: true` The
128
- cookies to add to
129
- the request
130
- * `cookiesTTL` **{boolean}** `Default: false` Controls enablement of TTL for the cookies cache
131
- * `credentials` **{include | omit | same-origin}** `Default: same-origin` Controls credentials in case of cross-origin
132
- redirects
133
- * `digest` **{boolean}** `Default: true` Controls whether to read the response stream or simply add a mixin
134
- * `follow` **{number}** `Default: 20` The number of redirects to follow
135
- * `h2` **{boolean}** `Default: false` Forces the use of HTTP/2 protocol
136
- * `headers` **{Object}** The headers to add to the request
137
- * `maxRetryAfter` **{number}** The upper limit of `retry-after` header. If unset, it will use `timeout` value
138
- * `parse` **{boolean}** `Default: true` Controls whether to parse response body or simply return a buffer
139
- * `redirect` **{error | follow | manual}** `Default: follow` Controls the redirect flows
140
- * `retry` **{Object}** Represents the retry options
141
- * `attempts` **{number}** `Default: 0` The number of retry attempts
142
- * `backoffStrategy` **{string}** `Default: interval * Math.log(Math.random() * (Math.E * Math.E - Math.E) + Math.E)`
143
- The backoff strategy algorithm that increases logarithmically. To fixate set value to `interval * 1`
144
- * `interval` **{number}** `Default: 1e3` The initial retry interval
145
- * `retryAfter` **{boolean}** `Default: true` Controls `retry-after` header receptiveness
146
- * `statusCodes` **{number[]}** `Default: [429, 503]` The list of status codes to retry on
147
- * `stripTrailingSlash` **{boolean}** `Default: false` Controls whether to strip trailing slash at the end of the URL
148
- * `thenable` **{boolean}** `Default: false` Controls the promise resolutions
149
- * `timeout` **{number}** `Default: 3e5` The number of milliseconds a request can take before termination
150
- * `trimTrailingSlashes` **{boolean}** `Default: false` Controls whether to trim trailing slashes within the URL
151
- * **Returns:** Promise that resolves to
152
- extended [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage)
153
- or [http2.ClientHttp2Stream](https://nodejs.org/api/http2.html#class-clienthttp2stream) which is respectively
154
- readable and duplex streams
155
- * if `digest: true` & `parse: true`
156
- * `body` **{string | Array | Buffer | Object}** The body based on its content type
157
- * if `digest: false`
158
- * `arrayBuffer` **{AsyncFunction}** Reads the response and returns **ArrayBuffer**
159
- * `blob` **{AsyncFunction}** Reads the response and returns **Blob**
160
- * `body` **{AsyncFunction}** Reads the response and returns **Buffer** if `parse: false`
161
- * `json` **{AsyncFunction}** Reads the response and returns **Object**
162
- * `text` **{AsyncFunction}** Reads the response and returns **String**
163
- * `bodyUsed` **{boolean}** Indicates whether the response were read or not
164
- * `cookies` **{undefined | Cookies}** The cookies sent and received with the response
165
- * `headers` **{Object}** The headers received with the response
166
- * `httpVersion` **{string}** Indicates protocol version negotiated with the server
167
- * `ok` **{boolean}** Indicates if the response was successful (statusCode: **200-299**)
168
- * `redirected` **{boolean}** Indicates if the response is the result of a redirect
169
- * `statusCode` **{number}** Indicates the status code of the response
170
- * `trailers` **{undefined | Object}** The trailer headers received with the response
171
-
172
- ---
173
-
174
- #### `rekwest.defaults`
175
-
176
- The object to fulfill with default [options](#rekwesturl-options).
177
-
178
- ---
179
-
180
- #### `rekwest.extend(options)`
181
-
182
- The method to extend default [options](#rekwesturl-options) per instance.
183
-
184
- ```javascript
185
- import rekwest, { constants } from 'rekwest';
186
-
187
- const {
188
- HTTP_STATUS_OK,
189
- } = constants;
190
-
191
- const rk = rekwest.extend({
192
- baseURL: 'https://somewhe.re',
193
- });
194
-
195
- const signal = AbortSignal.timeout(1e4);
196
- const url = '/somewhat/endpoint';
197
-
198
- const res = await rk(url, {
199
- signal,
200
- });
201
-
202
- console.assert(res.statusCode === HTTP_STATUS_OK);
203
- console.info(res.headers);
204
- console.log(res.body);
205
- ```
206
-
207
- ---
208
-
209
- #### `rekwest.stream(url[, options])`
210
-
211
- The method with limited functionality to use with streams and/or pipes.
212
-
213
- * No automata (redirects & retries)
214
- * Pass `h2: true` in options to use HTTP/2 protocol
215
- * Use `ackn({ url: URL })` method in advance to check the available protocols
216
-
217
- ```javascript
218
- import fs from 'node:fs';
219
- import { pipeline } from 'node:stream/promises';
220
- import rekwest, {
221
- ackn,
222
- constants,
223
- } from 'rekwest';
224
-
225
- const {
226
- HTTP2_METHOD_POST,
227
- } = constants;
228
-
229
- const url = new URL('https://somewhe.re/somewhat/endpoint');
230
- const options = await ackn({ url });
231
-
232
- await pipeline(
233
- fs.createReadStream('/var/tmp/vent/inlet.xyz'),
234
- rekwest.stream(url, { ...options, method: HTTP2_METHOD_POST }),
235
- fs.createWriteStream('/var/tmp/vent/outlet.xyz'),
236
- );
237
- ```
238
-
239
- ---
240
-
241
- For more details, please check tests (coverage: **>97%**) in the repository.
1
+ The robust request library that humanity deserves 🌐
2
+ ---
3
+ This package provides highly likely functional and **easy-to-use** abstraction atop of
4
+ native [http(s).request](https://nodejs.org/api/https.html#httpsrequesturl-options-callback)
5
+ and [http2.request](https://nodejs.org/api/http2.html#clienthttp2sessionrequestheaders-options).
6
+
7
+ ## Abstract
8
+
9
+ * Fetch-alike
10
+ * Cool-beans 🫐 config options (with defaults)
11
+ * Automatic HTTP/2 support (ALPN negotiation)
12
+ * Automatic or opt-in body parse (with non-UTF-8 charset decoding)
13
+ * Automatic and simplistic `Cookies` treatment (with built-in **jar** & **ttl**)
14
+ * Automatic decompression (with opt-in body compression)
15
+ * Built-in streamable `FormData` interface
16
+ * Support redirects & retries with fine-grained tune-ups
17
+ * Support all legit request body types (include blobs & streams)
18
+ * Support both CJS and ESM module systems
19
+ * Fully promise-able and pipe-able
20
+ * Zero dependencies
21
+
22
+ ## Prerequisites
23
+
24
+ * Node.js `>= 18.13.0`
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ npm install rekwest --save
30
+ ```
31
+
32
+ ### Usage
33
+
34
+ ```javascript
35
+ import rekwest, { constants } from 'rekwest';
36
+
37
+ const {
38
+ HTTP2_HEADER_AUTHORIZATION,
39
+ HTTP2_HEADER_CONTENT_ENCODING,
40
+ HTTP2_METHOD_POST,
41
+ HTTP_STATUS_OK,
42
+ } = constants;
43
+
44
+ const url = 'https://somewhe.re/somewhat/endpoint';
45
+
46
+ const res = await rekwest(url, {
47
+ body: { celestial: 'payload' },
48
+ headers: {
49
+ [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
50
+ [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
51
+ /** [HTTP2_HEADER_CONTENT_TYPE]
52
+ * is undue for
53
+ * Array/Blob/File/FormData/Object/URLSearchParams body types
54
+ * and will be set automatically, with an option to override it here
55
+ */
56
+ },
57
+ method: HTTP2_METHOD_POST,
58
+ });
59
+
60
+ console.assert(res.statusCode === HTTP_STATUS_OK);
61
+ console.info(res.headers);
62
+ console.log(res.body);
63
+ ```
64
+
65
+ ---
66
+
67
+ ```javascript
68
+ import { Readable } from 'node:stream';
69
+ import rekwest, {
70
+ constants,
71
+ Blob,
72
+ File,
73
+ FormData,
74
+ } from 'rekwest';
75
+
76
+ const {
77
+ HTTP2_HEADER_AUTHORIZATION,
78
+ HTTP2_HEADER_CONTENT_ENCODING,
79
+ HTTP2_METHOD_POST,
80
+ HTTP_STATUS_OK,
81
+ } = constants;
82
+
83
+ const blob = new Blob(['bits']);
84
+ const file = new File(['bits'], 'file.dab');
85
+ const readable = Readable.from('bits');
86
+
87
+ const fd = new FormData({
88
+ aux: Date.now(), // either [[key, value]] or kv sequenceable
89
+ });
90
+
91
+ fd.append('celestial', 'payload');
92
+ fd.append('blob', blob, 'blob.dab');
93
+ fd.append('file', file);
94
+ fd.append('readable', readable, 'readable.dab');
95
+
96
+ const url = 'https://somewhe.re/somewhat/endpoint';
97
+
98
+ const res = await rekwest(url, {
99
+ body: fd,
100
+ headers: {
101
+ [HTTP2_HEADER_AUTHORIZATION]: 'Bearer [token]',
102
+ [HTTP2_HEADER_CONTENT_ENCODING]: 'br', // enables: body compression
103
+ },
104
+ method: HTTP2_METHOD_POST,
105
+ });
106
+
107
+ console.assert(res.statusCode === HTTP_STATUS_OK);
108
+ console.info(res.headers);
109
+ console.log(res.body);
110
+ ```
111
+
112
+ ### API
113
+
114
+ #### `rekwest(url[, options])`
115
+
116
+ * `url` **{string | URL}** The URL to send the request to
117
+ * `options` **{Object}**
118
+ Extends [http(s).RequestOptions](https://nodejs.org/api/https.html#httpsrequesturl-options-callback) along with
119
+ extra [http2.ClientSessionOptions](https://nodejs.org/api/http2.html#http2connectauthority-options-listener)
120
+ & [http2.ClientSessionRequestOptions](https://nodejs.org/api/http2.html#clienthttp2sessionrequestheaders-options)
121
+ and [tls.ConnectionOptions](https://nodejs.org/api/tls.html#tlsconnectoptions-callback)
122
+ for HTTP/2 attunes
123
+ * `baseURL` **{string | URL}** The base URL to use in cases where `url` is a relative URL
124
+ * `body` **{string | Array | ArrayBuffer | ArrayBufferView | AsyncIterator | Blob | Buffer | DataView | File |
125
+ FormData | Iterator | Object | Readable | ReadableStream | SharedArrayBuffer | URLSearchParams}** The body to send
126
+ with the request
127
+ * `cookies` **{boolean | Array<[k, v]> | Array<string\> | Cookies | Object | URLSearchParams}** `Default: true` The
128
+ cookies to add to
129
+ the request
130
+ * `cookiesTTL` **{boolean}** `Default: false` Controls enablement of TTL for the cookies cache
131
+ * `credentials` **{include | omit | same-origin}** `Default: same-origin` Controls credentials in case of cross-origin
132
+ redirects
133
+ * `digest` **{boolean}** `Default: true` Controls whether to read the response stream or simply add a mixin
134
+ * `follow` **{number}** `Default: 20` The number of redirects to follow
135
+ * `h2` **{boolean}** `Default: false` Forces the use of HTTP/2 protocol
136
+ * `headers` **{Object}** The headers to add to the request
137
+ * `maxRetryAfter` **{number}** The upper limit of `retry-after` header. If unset, it will use `timeout` value
138
+ * `parse` **{boolean}** `Default: true` Controls whether to parse response body or simply return a buffer
139
+ * `redirect` **{error | follow | manual}** `Default: follow` Controls the redirect flows
140
+ * `retry` **{Object}** Represents the retry options
141
+ * `attempts` **{number}** `Default: 0` The number of retry attempts
142
+ * `backoffStrategy` **{string}** `Default: interval * Math.log(Math.random() * (Math.E * Math.E - Math.E) + Math.E)`
143
+ The backoff strategy algorithm that increases logarithmically. To fixate set value to `interval * 1`
144
+ * `errorCodes` **{string[]}**
145
+ `Default: ['EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTDOWN', 'EHOSTUNREACH', 'ENETDOWN', 'ENETUNREACH', 'ENOTFOUND', 'EPIPE', 'ERR_HTTP2_STREAM_ERROR']`
146
+ The list of error codes to retry on
147
+ * `interval` **{number}** `Default: 1e3` The initial retry interval
148
+ * `retryAfter` **{boolean}** `Default: true` Controls `retry-after` header receptiveness
149
+ * `statusCodes` **{number[]}** `Default: [429, 500, 502, 503, 504]` The list of status codes to retry on
150
+ * `stripTrailingSlash` **{boolean}** `Default: false` Controls whether to strip trailing slash at the end of the URL
151
+ * `thenable` **{boolean}** `Default: false` Controls the promise resolutions
152
+ * `timeout` **{number}** `Default: 3e5` The number of milliseconds a request can take before termination
153
+ * `trimTrailingSlashes` **{boolean}** `Default: false` Controls whether to trim trailing slashes within the URL
154
+ * **Returns:** Promise that resolves to
155
+ extended [http.IncomingMessage](https://nodejs.org/api/http.html#class-httpincomingmessage)
156
+ or [http2.ClientHttp2Stream](https://nodejs.org/api/http2.html#class-clienthttp2stream) which is respectively
157
+ readable and duplex streams
158
+ * if `digest: true` & `parse: true`
159
+ * `body` **{string | Array | Buffer | Object}** The body based on its content type
160
+ * if `digest: false`
161
+ * `arrayBuffer` **{AsyncFunction}** Reads the response and returns **ArrayBuffer**
162
+ * `blob` **{AsyncFunction}** Reads the response and returns **Blob**
163
+ * `body` **{AsyncFunction}** Reads the response and returns **Buffer** if `parse: false`
164
+ * `json` **{AsyncFunction}** Reads the response and returns **Object**
165
+ * `text` **{AsyncFunction}** Reads the response and returns **String**
166
+ * `bodyUsed` **{boolean}** Indicates whether the response were read or not
167
+ * `cookies` **{undefined | Cookies}** The cookies sent and received with the response
168
+ * `headers` **{Object}** The headers received with the response
169
+ * `httpVersion` **{string}** Indicates protocol version negotiated with the server
170
+ * `ok` **{boolean}** Indicates if the response was successful (statusCode: **200-299**)
171
+ * `redirected` **{boolean}** Indicates if the response is the result of a redirect
172
+ * `statusCode` **{number}** Indicates the status code of the response
173
+ * `trailers` **{undefined | Object}** The trailer headers received with the response
174
+
175
+ ---
176
+
177
+ #### `rekwest.defaults`
178
+
179
+ The object to fulfill with default [options](#rekwesturl-options).
180
+
181
+ ---
182
+
183
+ #### `rekwest.extend(options)`
184
+
185
+ The method to extend default [options](#rekwesturl-options) per instance.
186
+
187
+ ```javascript
188
+ import rekwest, { constants } from 'rekwest';
189
+
190
+ const {
191
+ HTTP_STATUS_OK,
192
+ } = constants;
193
+
194
+ const rk = rekwest.extend({
195
+ baseURL: 'https://somewhe.re',
196
+ });
197
+
198
+ const signal = AbortSignal.timeout(1e4);
199
+ const url = '/somewhat/endpoint';
200
+
201
+ const res = await rk(url, {
202
+ signal,
203
+ });
204
+
205
+ console.assert(res.statusCode === HTTP_STATUS_OK);
206
+ console.info(res.headers);
207
+ console.log(res.body);
208
+ ```
209
+
210
+ ---
211
+
212
+ #### `rekwest.stream(url[, options])`
213
+
214
+ The method with limited functionality to use with streams and/or pipes.
215
+
216
+ * No automata (redirects & retries)
217
+ * Pass `h2: true` in options to use HTTP/2 protocol
218
+ * Use `ackn({ url: URL })` method in advance to check the available protocols
219
+
220
+ ```javascript
221
+ import fs from 'node:fs';
222
+ import { pipeline } from 'node:stream/promises';
223
+ import rekwest, {
224
+ ackn,
225
+ constants,
226
+ } from 'rekwest';
227
+
228
+ const {
229
+ HTTP2_METHOD_POST,
230
+ } = constants;
231
+
232
+ const url = new URL('https://somewhe.re/somewhat/endpoint');
233
+ const options = await ackn({ url });
234
+
235
+ await pipeline(
236
+ fs.createReadStream('/path/to/read/inlet.xyz'),
237
+ rekwest.stream(url, { ...options, method: HTTP2_METHOD_POST }),
238
+ fs.createWriteStream('/path/to/write/outlet.xyz'),
239
+ );
240
+ ```
241
+
242
+ ---
243
+
244
+ For more details, please check tests (coverage: **>97%**) in the repository.
package/dist/cookies.js CHANGED
@@ -5,6 +5,8 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.Cookies = void 0;
7
7
  var _utils = require("./utils");
8
+ const lifetimeCap = 3456e7; // 400 days
9
+
8
10
  class Cookies extends URLSearchParams {
9
11
  static #finalizers = new Set();
10
12
  static jar = new Map();
@@ -35,7 +37,8 @@ class Cookies extends URLSearchParams {
35
37
  for (const val of attrs) {
36
38
  if (/(?:Expires|Max-Age)=/i.test(val)) {
37
39
  const [key, value] = val.toLowerCase().split('=');
38
- ttl[(0, _utils.toCamelCase)(key)] = !Number.isNaN(Number(value)) ? value * 1e3 : Date.parse(value) - Date.now();
40
+ const ms = Number.isFinite(Number(value)) ? value * 1e3 : Date.parse(value) - Date.now();
41
+ ttl[(0, _utils.toCamelCase)(key)] = Math.min(ms, lifetimeCap);
39
42
  }
40
43
  }
41
44
  return [cookie.replace(/\u0022/g, ''), Object.keys(ttl).length ? ttl : null];
package/dist/defaults.js CHANGED
@@ -10,6 +10,9 @@ var _utils = require("./utils");
10
10
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
11
11
  const {
12
12
  HTTP2_METHOD_GET,
13
+ HTTP_STATUS_BAD_GATEWAY,
14
+ HTTP_STATUS_GATEWAY_TIMEOUT,
15
+ HTTP_STATUS_INTERNAL_SERVER_ERROR,
13
16
  HTTP_STATUS_SERVICE_UNAVAILABLE,
14
17
  HTTP_STATUS_TOO_MANY_REQUESTS
15
18
  } = _nodeHttp.default.constants;
@@ -32,9 +35,10 @@ const stash = {
32
35
  retry: {
33
36
  attempts: 0,
34
37
  backoffStrategy: 'interval * Math.log(Math.random() * (Math.E * Math.E - Math.E) + Math.E)',
38
+ errorCodes: ['EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'EHOSTDOWN', 'EHOSTUNREACH', 'ENETDOWN', 'ENETUNREACH', 'ENOTFOUND', 'EPIPE', 'ERR_HTTP2_STREAM_ERROR'],
35
39
  interval: 1e3,
36
40
  retryAfter: true,
37
- statusCodes: [HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_SERVICE_UNAVAILABLE]
41
+ statusCodes: [HTTP_STATUS_TOO_MANY_REQUESTS, HTTP_STATUS_INTERNAL_SERVER_ERROR, HTTP_STATUS_BAD_GATEWAY, HTTP_STATUS_SERVICE_UNAVAILABLE, HTTP_STATUS_GATEWAY_TIMEOUT]
38
42
  },
39
43
  stripTrailingSlash: false,
40
44
  thenable: false,
@@ -98,7 +98,7 @@ const postflight = (req, res, options, {
98
98
  options.url = location;
99
99
  if (statusCode === HTTP_STATUS_MOVED_PERMANENTLY && res.headers[HTTP2_HEADER_RETRY_AFTER]) {
100
100
  let interval = res.headers[HTTP2_HEADER_RETRY_AFTER];
101
- interval = Number(interval) * 1000 || new Date(interval) - Date.now();
101
+ interval = Number(interval) * 1e3 || new Date(interval) - Date.now();
102
102
  if (interval > options.maxRetryAfter) {
103
103
  return res.emit('error', (0, _utils.maxRetryAfterError)(interval, {
104
104
  cause: (0, _mixin.mixin)(res, options)
package/dist/transfer.js CHANGED
@@ -57,6 +57,7 @@ const transfer = async (options, overact) => {
57
57
  req = request(url, options);
58
58
  }
59
59
  (0, _utils.affix)(client, req, options);
60
+ req.once('aborted', reject);
60
61
  req.once('error', reject);
61
62
  req.once('frameError', reject);
62
63
  req.once('goaway', reject);
@@ -77,24 +78,26 @@ const transfer = async (options, overact) => {
77
78
  maxRetryAfter,
78
79
  retry
79
80
  } = options;
80
- if (retry?.attempts && retry?.statusCodes.includes(ex.statusCode)) {
81
- let {
82
- interval
83
- } = retry;
84
- if (retry.retryAfter && ex.headers[HTTP2_HEADER_RETRY_AFTER]) {
85
- interval = ex.headers[HTTP2_HEADER_RETRY_AFTER];
86
- interval = Number(interval) * 1000 || new Date(interval) - Date.now();
87
- if (interval > maxRetryAfter) {
88
- throw (0, _utils.maxRetryAfterError)(interval, {
89
- cause: ex
90
- });
81
+ if (retry?.attempts > 0) {
82
+ if (retry.errorCodes?.includes(ex.code) || retry.statusCodes?.includes(ex.statusCode)) {
83
+ let {
84
+ interval
85
+ } = retry;
86
+ if (retry.retryAfter && ex.headers?.[HTTP2_HEADER_RETRY_AFTER]) {
87
+ interval = ex.headers[HTTP2_HEADER_RETRY_AFTER];
88
+ interval = Number(interval) * 1e3 || new Date(interval) - Date.now();
89
+ if (interval > maxRetryAfter) {
90
+ throw (0, _utils.maxRetryAfterError)(interval, {
91
+ cause: ex
92
+ });
93
+ }
94
+ } else {
95
+ interval = new Function('interval', `return Math.ceil(${retry.backoffStrategy});`)(interval);
91
96
  }
92
- } else {
93
- interval = new Function('interval', `return Math.ceil(${retry.backoffStrategy});`)(interval);
97
+ retry.attempts--;
98
+ retry.interval = interval;
99
+ return (0, _promises.setTimeout)(interval).then(() => overact(url, options));
94
100
  }
95
- retry.attempts--;
96
- retry.interval = interval;
97
- return (0, _promises.setTimeout)(interval).then(() => overact(url, options));
98
101
  }
99
102
  if (digest && !redirected && ex.body) {
100
103
  ex.body = await ex.body();
package/dist/utils.js CHANGED
@@ -46,6 +46,7 @@ const admix = (res, headers, options) => {
46
46
  };
47
47
  exports.admix = admix;
48
48
  const affix = (client, req, options) => {
49
+ req.once('close', () => client?.close());
49
50
  req.once('end', () => client?.close());
50
51
  req.once('timeout', () => req.destroy(new _errors.TimeoutError(`Timed out after ${options.timeout} ms.`)));
51
52
  req.once('trailers', trailers => {
package/package.json CHANGED
@@ -8,15 +8,15 @@
8
8
  "url": "https://github.com/bricss/rekwest/issues"
9
9
  },
10
10
  "devDependencies": {
11
- "@babel/cli": "^7.23.0",
12
- "@babel/core": "^7.23.3",
13
- "@babel/eslint-parser": "^7.23.3",
14
- "@babel/preset-env": "^7.23.3",
15
- "@stylistic/eslint-plugin-js": "^1.1.0",
16
- "c8": "^8.0.1",
17
- "eslint": "^8.53.0",
18
- "eslint-config-ultra-refined": "^2.19.1",
19
- "mocha": "^10.2.0"
11
+ "@babel/cli": "^7.23.9",
12
+ "@babel/core": "^7.24.0",
13
+ "@babel/eslint-parser": "^7.23.10",
14
+ "@babel/preset-env": "^7.24.0",
15
+ "@stylistic/eslint-plugin-js": "^1.6.3",
16
+ "c8": "^9.1.0",
17
+ "eslint": "^8.57.0",
18
+ "eslint-config-ultra-refined": "^2.20.0",
19
+ "mocha": "^10.3.0"
20
20
  },
21
21
  "description": "The robust request library that humanity deserves 🌐",
22
22
  "engines": {
@@ -70,5 +70,5 @@
70
70
  "test:bail": "mocha --bail",
71
71
  "test:cover": "c8 --include=src --reporter=lcov --reporter=text npm test"
72
72
  },
73
- "version": "5.0.3"
73
+ "version": "5.2.0"
74
74
  }