undici 8.7.0 → 8.8.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 +5 -0
- package/docs/docs/api/Client.md +4 -0
- package/docs/docs/api/Dispatcher.md +6 -0
- package/docs/docs/api/Interceptors.md +59 -0
- package/docs/docs/api/MockAgent.md +27 -0
- package/docs/docs/api/MockPool.md +28 -1
- package/docs/docs/index.md +5 -0
- package/lib/core/request.js +1 -1
- package/lib/core/util.js +6 -1
- package/lib/dispatcher/agent.js +3 -3
- package/lib/dispatcher/client-h1.js +31 -6
- package/lib/dispatcher/client-h2.js +34 -43
- package/lib/handler/cache-handler.js +93 -5
- package/lib/handler/cache-revalidation-handler.js +10 -0
- package/lib/handler/redirect-handler.js +5 -2
- package/lib/handler/retry-handler.js +6 -4
- package/lib/interceptor/cache.js +21 -4
- package/lib/interceptor/decompress.js +4 -0
- package/lib/mock/mock-interceptor.js +25 -7
- package/lib/mock/mock-utils.js +39 -10
- package/lib/util/cache.js +49 -7
- package/lib/web/fetch/body.js +2 -1
- package/lib/web/fetch/response.js +1 -3
- package/package.json +2 -2
- package/types/client.d.ts +2 -2
- package/types/dispatcher.d.ts +3 -3
- package/types/mock-interceptor.d.ts +5 -1
package/README.md
CHANGED
|
@@ -408,6 +408,11 @@ For more information about their behavior, please reference the body mixin from
|
|
|
408
408
|
|
|
409
409
|
This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site.
|
|
410
410
|
|
|
411
|
+
For the top-level APIs below, the `url` argument supplies the request origin and
|
|
412
|
+
path. Do not pass `origin` or `path` in the second `options` argument. The linked
|
|
413
|
+
`Dispatcher` option types include those fields because dispatcher methods are
|
|
414
|
+
lower-level APIs that do not receive a separate `url` argument.
|
|
415
|
+
|
|
411
416
|
### `undici.request([url, options]): Promise`
|
|
412
417
|
|
|
413
418
|
Arguments:
|
package/docs/docs/api/Client.md
CHANGED
|
@@ -49,6 +49,10 @@ added: v1.0.0
|
|
|
49
49
|
* `headersTimeout` {number|null} The timeout, in milliseconds, the parser
|
|
50
50
|
waits to receive the complete HTTP headers before the request times out. Use
|
|
51
51
|
`0` to disable it entirely. **Default:** `300e3`.
|
|
52
|
+
HTTP/1.1 headers/body parser timeouts are not guaranteed to fire with exact
|
|
53
|
+
millisecond precision: delays up to 1000ms use native timers, while larger
|
|
54
|
+
delays use undici's lower-overhead fast timers with a target resolution
|
|
55
|
+
around 500ms.
|
|
52
56
|
* `connectTimeout` {number|null} The timeout, in milliseconds, for
|
|
53
57
|
establishing a socket connection. Use `0` to disable it entirely.
|
|
54
58
|
**Default:** `10e3`.
|
|
@@ -228,6 +228,10 @@ added: v4.0.0
|
|
|
228
228
|
* `bodyTimeout` {number|null} The time, in milliseconds, after which the request
|
|
229
229
|
times out while receiving body data. Monitors the time between body chunks.
|
|
230
230
|
Use `0` to disable it entirely. Defaults to 300 seconds.
|
|
231
|
+
HTTP/1.1 headers/body parser timeouts are not guaranteed to fire with exact
|
|
232
|
+
millisecond precision: delays up to 1000ms use native timers, while larger
|
|
233
|
+
delays use undici's lower-overhead fast timers with a target resolution
|
|
234
|
+
around 500ms.
|
|
231
235
|
* `reset` {boolean} Whether the request should establish a keep-alive
|
|
232
236
|
connection. **Default:** `false`.
|
|
233
237
|
* `expectContinue` {boolean} For HTTP/2, appends the `expect: 100-continue`
|
|
@@ -729,6 +733,8 @@ await client.request({ path: '/', method: 'GET' })
|
|
|
729
733
|
```
|
|
730
734
|
|
|
731
735
|
For the full list of built-in interceptors provided by undici, see [Interceptors](Interceptors.md).
|
|
736
|
+
For an example of a custom interceptor that wraps handler callbacks, see
|
|
737
|
+
[Custom interceptors](Interceptors.md#custom-interceptors).
|
|
732
738
|
|
|
733
739
|
### Event: `'connect'`
|
|
734
740
|
|
|
@@ -32,6 +32,65 @@ const client = new Client('https://example.com').compose(
|
|
|
32
32
|
|
|
33
33
|
---
|
|
34
34
|
|
|
35
|
+
## Custom interceptors
|
|
36
|
+
|
|
37
|
+
Custom interceptors use the same shape as
|
|
38
|
+
[`dispatcher.compose()`](./Dispatcher.md#dispatchercomposeinterceptors-interceptor):
|
|
39
|
+
an interceptor takes a `dispatch` function and returns another dispatch-like
|
|
40
|
+
function with the same `(options, handler)` signature.
|
|
41
|
+
|
|
42
|
+
When an interceptor wraps the handler, forward the callbacks that it does not
|
|
43
|
+
handle itself. The complete handler callback list is documented under
|
|
44
|
+
[`dispatcher.dispatch(options, handler)`](./Dispatcher.md#dispatcherdispatchoptions-handler).
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import { Agent } from 'undici'
|
|
48
|
+
|
|
49
|
+
const timingInterceptor = dispatch => {
|
|
50
|
+
return (options, handler) => {
|
|
51
|
+
const started = performance.now()
|
|
52
|
+
|
|
53
|
+
return dispatch(options, {
|
|
54
|
+
...handler,
|
|
55
|
+
onResponseStart (controller, statusCode, headers, statusMessage) {
|
|
56
|
+
const duration = Math.round(performance.now() - started)
|
|
57
|
+
const method = options.method ?? 'GET'
|
|
58
|
+
const origin = options.origin ?? ''
|
|
59
|
+
|
|
60
|
+
console.log(`${method} ${origin}${options.path} -> ${statusCode} in ${duration}ms`)
|
|
61
|
+
|
|
62
|
+
return handler.onResponseStart?.(
|
|
63
|
+
controller,
|
|
64
|
+
statusCode,
|
|
65
|
+
headers,
|
|
66
|
+
statusMessage
|
|
67
|
+
)
|
|
68
|
+
},
|
|
69
|
+
onResponseError (controller, error) {
|
|
70
|
+
const duration = Math.round(performance.now() - started)
|
|
71
|
+
|
|
72
|
+
console.error(`request failed after ${duration}ms`, error)
|
|
73
|
+
|
|
74
|
+
return handler.onResponseError?.(controller, error)
|
|
75
|
+
}
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const dispatcher = new Agent().compose(timingInterceptor)
|
|
81
|
+
|
|
82
|
+
const { body } = await dispatcher.request({
|
|
83
|
+
origin: 'https://example.com',
|
|
84
|
+
path: '/',
|
|
85
|
+
method: 'GET'
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
await body.dump()
|
|
89
|
+
await dispatcher.close()
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
35
94
|
## `interceptors.dump([opts])`
|
|
36
95
|
|
|
37
96
|
Reads and discards the response body up to a configurable size limit. Useful
|
|
@@ -17,6 +17,13 @@ registered on the {MockClient} or {MockPool} instances returned by
|
|
|
17
17
|
`MockAgent` is set as the dispatcher (for example through
|
|
18
18
|
[`setGlobalDispatcher()`][] or a per-request `dispatcher` option).
|
|
19
19
|
|
|
20
|
+
> [!NOTE]
|
|
21
|
+
> [`setGlobalDispatcher()`][] only affects undici APIs that use the global
|
|
22
|
+
> dispatcher, such as `request()` and `fetch()`. It does not replace or
|
|
23
|
+
> monkeypatch {Pool} or {Client} instances that were created separately. To test
|
|
24
|
+
> code that accepts or creates a pool/client directly, pass the {MockPool} or
|
|
25
|
+
> {MockClient} returned by [`mockAgent.get(origin)`][] into that code.
|
|
26
|
+
|
|
20
27
|
```mjs
|
|
21
28
|
import { MockAgent } from 'undici'
|
|
22
29
|
|
|
@@ -139,6 +146,26 @@ for await (const data of body) {
|
|
|
139
146
|
}
|
|
140
147
|
```
|
|
141
148
|
|
|
149
|
+
```mjs displayName="Testing code that accepts a pool"
|
|
150
|
+
import { MockAgent } from 'undici'
|
|
151
|
+
|
|
152
|
+
async function getStatus (pool) {
|
|
153
|
+
const { statusCode } = await pool.request({
|
|
154
|
+
path: '/foo',
|
|
155
|
+
method: 'GET'
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
return statusCode
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const mockAgent = new MockAgent()
|
|
162
|
+
const mockPool = mockAgent.get('http://localhost:3000')
|
|
163
|
+
|
|
164
|
+
mockPool.intercept({ path: '/foo', method: 'GET' }).reply(200)
|
|
165
|
+
|
|
166
|
+
console.log(await getStatus(mockPool)) // 200
|
|
167
|
+
```
|
|
168
|
+
|
|
142
169
|
```mjs displayName="Returning a MockClient"
|
|
143
170
|
import { MockAgent, request } from 'undici'
|
|
144
171
|
|
|
@@ -136,7 +136,8 @@ The reply behaviour of a matching request is defined through the returned
|
|
|
136
136
|
computing all reply options dynamically rather than just the body.
|
|
137
137
|
* `callback` {Function} A `(opts: MockResponseCallbackOptions) =>
|
|
138
138
|
{ statusCode, data, responseOptions }` function invoked with the incoming
|
|
139
|
-
request.
|
|
139
|
+
request. The callback may be asynchronous; a returned promise is awaited
|
|
140
|
+
and must resolve to the same shape.
|
|
140
141
|
* Returns: {MockScope}
|
|
141
142
|
* `replyWithError(error)` {Function} Defines an error for a matching request to
|
|
142
143
|
throw.
|
|
@@ -263,6 +264,32 @@ for await (const data of body) {
|
|
|
263
264
|
}
|
|
264
265
|
```
|
|
265
266
|
|
|
267
|
+
```mjs displayName="Reply with an asynchronous options callback"
|
|
268
|
+
import { readFile } from 'node:fs/promises'
|
|
269
|
+
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
|
270
|
+
|
|
271
|
+
const mockAgent = new MockAgent()
|
|
272
|
+
setGlobalDispatcher(mockAgent)
|
|
273
|
+
|
|
274
|
+
const mockPool = mockAgent.get('http://localhost:3000')
|
|
275
|
+
|
|
276
|
+
mockPool.intercept({
|
|
277
|
+
path: '/fixture',
|
|
278
|
+
method: 'GET'
|
|
279
|
+
}).reply(async ({ path }) => ({
|
|
280
|
+
statusCode: 200,
|
|
281
|
+
data: await readFile(new URL('./fixture.json', import.meta.url))
|
|
282
|
+
}))
|
|
283
|
+
|
|
284
|
+
const { statusCode, body } = await request('http://localhost:3000/fixture')
|
|
285
|
+
|
|
286
|
+
console.log('response received', statusCode) // response received 200
|
|
287
|
+
|
|
288
|
+
for await (const data of body) {
|
|
289
|
+
console.log('data', data.toString('utf8')) // contents of fixture.json
|
|
290
|
+
}
|
|
291
|
+
```
|
|
292
|
+
|
|
266
293
|
```mjs displayName="Multiple intercepts"
|
|
267
294
|
import { MockAgent, setGlobalDispatcher, request } from 'undici'
|
|
268
295
|
|
package/docs/docs/index.md
CHANGED
|
@@ -410,6 +410,11 @@ For more information about their behavior, please reference the body mixin from
|
|
|
410
410
|
|
|
411
411
|
This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site.
|
|
412
412
|
|
|
413
|
+
For the top-level APIs below, the `url` argument supplies the request origin and
|
|
414
|
+
path. Do not pass `origin` or `path` in the second `options` argument. The linked
|
|
415
|
+
`Dispatcher` option types include those fields because dispatcher methods are
|
|
416
|
+
lower-level APIs that do not receive a separate `url` argument.
|
|
417
|
+
|
|
413
418
|
### `undici.request([url, options])`
|
|
414
419
|
|
|
415
420
|
* `url` {string|URL|UrlObject}
|
package/lib/core/request.js
CHANGED
package/lib/core/util.js
CHANGED
|
@@ -370,7 +370,12 @@ function destroy (stream, err) {
|
|
|
370
370
|
stream.socket = null
|
|
371
371
|
}
|
|
372
372
|
|
|
373
|
-
|
|
373
|
+
try {
|
|
374
|
+
stream.destroy(err)
|
|
375
|
+
} catch {
|
|
376
|
+
// stream.destroy may throw on managed sockets (e.g., http2).
|
|
377
|
+
// Silently ignore — the socket lifecycle is handled by the subsystem.
|
|
378
|
+
}
|
|
374
379
|
} else if (err) {
|
|
375
380
|
queueMicrotask(() => {
|
|
376
381
|
stream.emit('error', err)
|
package/lib/dispatcher/agent.js
CHANGED
|
@@ -107,15 +107,15 @@ class Agent extends DispatcherBase {
|
|
|
107
107
|
}
|
|
108
108
|
|
|
109
109
|
let hasOrigin = false
|
|
110
|
-
for (const
|
|
111
|
-
if (
|
|
110
|
+
for (const k of this[kClients].keys()) {
|
|
111
|
+
if (k === origin || k === `${origin}#http1-only`) {
|
|
112
112
|
hasOrigin = true
|
|
113
113
|
break
|
|
114
114
|
}
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
if (!hasOrigin) {
|
|
118
|
-
this[kOrigins].delete(
|
|
118
|
+
this[kOrigins].delete(origin)
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
121
|
|
|
@@ -60,6 +60,7 @@ const removeAllListeners = util.removeAllListeners
|
|
|
60
60
|
const kIdleSocketValidation = Symbol('kIdleSocketValidation')
|
|
61
61
|
const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
|
|
62
62
|
const kSocketUsed = Symbol('kSocketUsed')
|
|
63
|
+
const kTypeOfService = Symbol('kTypeOfService')
|
|
63
64
|
|
|
64
65
|
let extractBody
|
|
65
66
|
|
|
@@ -1050,7 +1051,7 @@ function onSocketClose () {
|
|
|
1050
1051
|
|
|
1051
1052
|
function clearIdleSocketValidation (socket) {
|
|
1052
1053
|
if (socket[kIdleSocketValidationTimeout]) {
|
|
1053
|
-
|
|
1054
|
+
clearImmediate(socket[kIdleSocketValidationTimeout])
|
|
1054
1055
|
socket[kIdleSocketValidationTimeout] = null
|
|
1055
1056
|
}
|
|
1056
1057
|
|
|
@@ -1059,14 +1060,14 @@ function clearIdleSocketValidation (socket) {
|
|
|
1059
1060
|
|
|
1060
1061
|
function scheduleIdleSocketValidation (client, socket) {
|
|
1061
1062
|
socket[kIdleSocketValidation] = 1
|
|
1062
|
-
socket[kIdleSocketValidationTimeout] =
|
|
1063
|
+
socket[kIdleSocketValidationTimeout] = setImmediate(() => {
|
|
1063
1064
|
socket[kIdleSocketValidationTimeout] = null
|
|
1064
1065
|
socket[kIdleSocketValidation] = 2
|
|
1065
1066
|
|
|
1066
1067
|
if (client[kSocket] === socket && !socket.destroyed) {
|
|
1067
1068
|
client[kResume]()
|
|
1068
1069
|
}
|
|
1069
|
-
}
|
|
1070
|
+
})
|
|
1070
1071
|
socket[kIdleSocketValidationTimeout].unref?.()
|
|
1071
1072
|
}
|
|
1072
1073
|
|
|
@@ -1134,6 +1135,32 @@ function shouldSendContentLength (method) {
|
|
|
1134
1135
|
return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
|
|
1135
1136
|
}
|
|
1136
1137
|
|
|
1138
|
+
function setTypeOfService (socket, request) {
|
|
1139
|
+
if (typeof socket.setTypeOfService !== 'function') {
|
|
1140
|
+
return
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
const typeOfService = request.typeOfService
|
|
1144
|
+
|
|
1145
|
+
if (typeOfService === undefined) {
|
|
1146
|
+
return
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
const currentTypeOfService = socket[kTypeOfService]
|
|
1150
|
+
|
|
1151
|
+
if (currentTypeOfService === typeOfService) {
|
|
1152
|
+
return
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
try {
|
|
1156
|
+
socket.setTypeOfService(typeOfService)
|
|
1157
|
+
socket[kTypeOfService] = typeOfService
|
|
1158
|
+
} catch {
|
|
1159
|
+
// QoS marking is best-effort. setTypeOfService() can throw synchronously on
|
|
1160
|
+
// some platforms depending on socket state, but that must not abort the request.
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1137
1164
|
/**
|
|
1138
1165
|
* @param {import('./client.js')} client
|
|
1139
1166
|
* @param {import('../core/request.js')} request
|
|
@@ -1265,9 +1292,7 @@ function writeH1 (client, request) {
|
|
|
1265
1292
|
socket[kBlocking] = true
|
|
1266
1293
|
}
|
|
1267
1294
|
|
|
1268
|
-
|
|
1269
|
-
socket.setTypeOfService(request.typeOfService)
|
|
1270
|
-
}
|
|
1295
|
+
setTypeOfService(socket, request)
|
|
1271
1296
|
|
|
1272
1297
|
let header = `${method} ${path} HTTP/1.1\r\n`
|
|
1273
1298
|
|
|
@@ -157,9 +157,10 @@ function completeRequest (client, request, resetPendingIdx = false) {
|
|
|
157
157
|
const queue = client[kQueue]
|
|
158
158
|
const runningIdx = client[kRunningIdx]
|
|
159
159
|
|
|
160
|
-
// In-order completion:
|
|
161
|
-
// The client's resume loop compacts
|
|
160
|
+
// In-order completion: clear the request and advance without splicing.
|
|
161
|
+
// The client's resume loop compacts cleared slots once the index grows.
|
|
162
162
|
if (runningIdx < client[kPendingIdx] && queue[runningIdx] === request) {
|
|
163
|
+
queue[runningIdx] = null
|
|
163
164
|
client[kRunningIdx] = runningIdx + 1
|
|
164
165
|
return
|
|
165
166
|
}
|
|
@@ -246,7 +247,6 @@ function connectH2 (client, socket) {
|
|
|
246
247
|
|
|
247
248
|
util.addListener(session, 'error', onHttp2SessionError)
|
|
248
249
|
util.addListener(session, 'frameError', onHttp2FrameError)
|
|
249
|
-
util.addListener(session, 'end', onHttp2SessionEnd)
|
|
250
250
|
util.addListener(session, 'goaway', onHttp2SessionGoAway)
|
|
251
251
|
util.addListener(session, 'close', onHttp2SessionClose)
|
|
252
252
|
util.addListener(session, 'remoteSettings', onHttp2RemoteSettings)
|
|
@@ -322,16 +322,6 @@ function connectH2 (client, socket) {
|
|
|
322
322
|
// Don't dispatch an upgrade until all preceding requests have completed.
|
|
323
323
|
// Possibly, we do not have remote settings confirmed yet.
|
|
324
324
|
if ((request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false) return true
|
|
325
|
-
// Request with stream or iterator body can error while other requests
|
|
326
|
-
// are inflight and indirectly error those as well.
|
|
327
|
-
// Ensure this doesn't happen by waiting for inflight
|
|
328
|
-
// to complete before dispatching.
|
|
329
|
-
|
|
330
|
-
// Request with stream or iterator body cannot be retried.
|
|
331
|
-
// Ensure that no other requests are inflight and
|
|
332
|
-
// could cause failure.
|
|
333
|
-
if (util.bodyLength(request.body) !== 0 &&
|
|
334
|
-
(util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) return true
|
|
335
325
|
} else {
|
|
336
326
|
return (request.upgrade === 'websocket' || request.method === 'CONNECT') && session[kRemoteSettings] === false
|
|
337
327
|
}
|
|
@@ -505,12 +495,6 @@ function onHttp2FrameError (type, code, id) {
|
|
|
505
495
|
}
|
|
506
496
|
}
|
|
507
497
|
|
|
508
|
-
function onHttp2SessionEnd () {
|
|
509
|
-
const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))
|
|
510
|
-
this.destroy(err)
|
|
511
|
-
util.destroy(this[kSocket], err)
|
|
512
|
-
}
|
|
513
|
-
|
|
514
498
|
/**
|
|
515
499
|
* This is the root cause of #3011
|
|
516
500
|
* We need to handle GOAWAY frames properly, and trigger the session close
|
|
@@ -654,7 +638,7 @@ function onHttp2SocketError (err) {
|
|
|
654
638
|
return
|
|
655
639
|
}
|
|
656
640
|
|
|
657
|
-
this[kClient][kOnError](err)
|
|
641
|
+
this[kHTTP2Session]?.[kClient]?.[kOnError](err)
|
|
658
642
|
}
|
|
659
643
|
|
|
660
644
|
function onHttp2SocketEnd () {
|
|
@@ -688,20 +672,24 @@ function onUpgradeStreamClose () {
|
|
|
688
672
|
closeStreamSession(this)
|
|
689
673
|
}
|
|
690
674
|
|
|
691
|
-
|
|
675
|
+
// Idempotent terminal cleanup, called from both 'end' and 'close': the
|
|
676
|
+
// null-state guard no-ops the later call.
|
|
677
|
+
function completeRequestStream () {
|
|
692
678
|
const state = this[kRequestStreamState]
|
|
693
679
|
|
|
694
|
-
if (state) {
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
680
|
+
if (state == null) {
|
|
681
|
+
return
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// Release the stream first so request references are cleared,
|
|
685
|
+
// then complete the response with trailers if available.
|
|
686
|
+
releaseRequestStream(this)
|
|
698
687
|
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
finalizeRequest(state)
|
|
702
|
-
}
|
|
688
|
+
if (state.pendingEnd && !state.request.aborted && !state.request.completed) {
|
|
689
|
+
state.request.onResponseEnd(state.trailers || {})
|
|
703
690
|
}
|
|
704
691
|
|
|
692
|
+
finalizeRequest(state)
|
|
705
693
|
closeStreamSession(this)
|
|
706
694
|
this[kRequestStreamState] = null
|
|
707
695
|
}
|
|
@@ -943,14 +931,14 @@ function writeH2 (client, request) {
|
|
|
943
931
|
// close() alone leaves cleanup waiting on the 'close' event; on a busy,
|
|
944
932
|
// long-lived multiplexed session that event can fail to fire, leaving the
|
|
945
933
|
// native Http2Stream (and the whole request graph it pins) alive for the
|
|
946
|
-
// session's life. Destroy the stream to release the handle
|
|
947
|
-
// deterministically
|
|
948
|
-
//
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
}
|
|
934
|
+
// session's life. Destroy the stream synchronously to release the handle
|
|
935
|
+
// deterministically. Deferring the destroy (e.g. via setImmediate) leaks
|
|
936
|
+
// the same way when the event loop is stalled and the callback never runs
|
|
937
|
+
// under abort churn (#5558); close() has already queued the RST_STREAM
|
|
938
|
+
// frame on the native session, so a synchronous destroy still sends it.
|
|
939
|
+
if (!stream.destroyed) {
|
|
940
|
+
util.destroy(stream)
|
|
941
|
+
}
|
|
954
942
|
|
|
955
943
|
// We move the running index to the next request
|
|
956
944
|
client[kOnError](err)
|
|
@@ -1137,7 +1125,7 @@ function writeH2 (client, request) {
|
|
|
1137
1125
|
}
|
|
1138
1126
|
|
|
1139
1127
|
stream[kHTTP2Session] = session
|
|
1140
|
-
stream.on('close',
|
|
1128
|
+
stream.on('close', completeRequestStream)
|
|
1141
1129
|
|
|
1142
1130
|
bindRequestToStream(request, stream, releaseRequestStream)
|
|
1143
1131
|
if (expectContinue) {
|
|
@@ -1280,13 +1268,16 @@ function onEnd () {
|
|
|
1280
1268
|
|
|
1281
1269
|
stream.off('end', onEnd)
|
|
1282
1270
|
|
|
1283
|
-
//
|
|
1284
|
-
//
|
|
1285
|
-
// onTrailers (which may fire after 'end' on Windows) can
|
|
1286
|
-
// store trailers first.
|
|
1271
|
+
// onTrailers (which may fire after 'end' on Windows) has already stored
|
|
1272
|
+
// trailers on the state by now, so completing here still delivers them.
|
|
1287
1273
|
if (state.responseReceived) {
|
|
1288
1274
|
if (!request.aborted && !request.completed) {
|
|
1289
1275
|
state.pendingEnd = true
|
|
1276
|
+
|
|
1277
|
+
// Complete on 'end': a blocked event loop can keep the stream's 'close'
|
|
1278
|
+
// from firing, stranding its buffers until OOM. Idempotent, so a later
|
|
1279
|
+
// 'close' no-ops.
|
|
1280
|
+
completeRequestStream.call(stream)
|
|
1290
1281
|
}
|
|
1291
1282
|
} else {
|
|
1292
1283
|
// Stream ended without receiving a response - this is an error
|
|
@@ -1357,7 +1348,7 @@ function onTrailers (trailers) {
|
|
|
1357
1348
|
return
|
|
1358
1349
|
}
|
|
1359
1350
|
|
|
1360
|
-
// Store trailers for
|
|
1351
|
+
// Store trailers for completeRequestStream to use when completing
|
|
1361
1352
|
state.trailers = trailers
|
|
1362
1353
|
}
|
|
1363
1354
|
|
|
@@ -26,6 +26,10 @@ const NOT_UNDERSTOOD_STATUS_CODES = [
|
|
|
26
26
|
|
|
27
27
|
const MAX_RESPONSE_AGE = 2147483647000
|
|
28
28
|
|
|
29
|
+
// Retention for revalidation-only entries (zero freshness lifetime but a
|
|
30
|
+
// validator present); each successful revalidation re-stores the entry.
|
|
31
|
+
const REVALIDATION_ONLY_RETENTION = 86400000 // 24 hours
|
|
32
|
+
|
|
29
33
|
/**
|
|
30
34
|
* @typedef {import('../../types/dispatcher.d.ts').default.DispatchHandler} DispatchHandler
|
|
31
35
|
*
|
|
@@ -118,6 +122,7 @@ class CacheHandler {
|
|
|
118
122
|
} catch {
|
|
119
123
|
// Fail silently
|
|
120
124
|
}
|
|
125
|
+
this.#deleteLocationHeaderEntries(resHeaders)
|
|
121
126
|
return downstreamOnHeaders()
|
|
122
127
|
}
|
|
123
128
|
|
|
@@ -150,8 +155,12 @@ class CacheHandler {
|
|
|
150
155
|
? parseHttpDate(resHeaders.date)
|
|
151
156
|
: undefined
|
|
152
157
|
|
|
158
|
+
const hasValidator =
|
|
159
|
+
(typeof resHeaders.etag === 'string' && isEtagUsable(resHeaders.etag)) ||
|
|
160
|
+
typeof resHeaders['last-modified'] === 'string'
|
|
161
|
+
|
|
153
162
|
const staleAt =
|
|
154
|
-
determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives) ??
|
|
163
|
+
determineStaleAt(this.#cacheType, now, resAge, resHeaders, resDate, cacheControlDirectives, hasValidator) ??
|
|
155
164
|
this.#cacheByDefault
|
|
156
165
|
if (staleAt === undefined || (resAge && resAge > staleAt)) {
|
|
157
166
|
return downstreamOnHeaders()
|
|
@@ -159,7 +168,11 @@ class CacheHandler {
|
|
|
159
168
|
|
|
160
169
|
const baseTime = resDate ? resDate.getTime() : now
|
|
161
170
|
const absoluteStaleAt = staleAt + baseTime
|
|
162
|
-
|
|
171
|
+
// Zero freshness lifetime but a validator: stale from the start, yet still
|
|
172
|
+
// storable since each reuse is preceded by a revalidation request.
|
|
173
|
+
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.4
|
|
174
|
+
const revalidationOnly = staleAt === 0 && hasValidator
|
|
175
|
+
if (now >= absoluteStaleAt && !revalidationOnly) {
|
|
163
176
|
// Response is already stale
|
|
164
177
|
return downstreamOnHeaders()
|
|
165
178
|
}
|
|
@@ -314,6 +327,58 @@ class CacheHandler {
|
|
|
314
327
|
}
|
|
315
328
|
}
|
|
316
329
|
|
|
330
|
+
/**
|
|
331
|
+
* Deletes the cache entries for the URIs in the response's Location and
|
|
332
|
+
* Content-Location headers when they share the request URI's origin
|
|
333
|
+
* https://www.rfc-editor.org/rfc/rfc9111.html#section-4.4
|
|
334
|
+
*
|
|
335
|
+
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
|
|
336
|
+
*/
|
|
337
|
+
#deleteLocationHeaderEntries (resHeaders) {
|
|
338
|
+
let requestUrl
|
|
339
|
+
try {
|
|
340
|
+
requestUrl = new URL(this.#cacheKey.path, this.#cacheKey.origin)
|
|
341
|
+
} catch {
|
|
342
|
+
// Can't resolve the request URI, don't invalidate anything else
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const invalidatedPaths = new Set([this.#cacheKey.path])
|
|
347
|
+
|
|
348
|
+
for (const headerName of ['location', 'content-location']) {
|
|
349
|
+
const header = resHeaders[headerName]
|
|
350
|
+
const value = Array.isArray(header) ? header[0] : header
|
|
351
|
+
if (typeof value !== 'string' || value === '') {
|
|
352
|
+
continue
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
let url
|
|
356
|
+
try {
|
|
357
|
+
url = new URL(value, requestUrl)
|
|
358
|
+
} catch {
|
|
359
|
+
continue
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
if (url.origin !== requestUrl.origin) {
|
|
363
|
+
// Only invalidate URIs sharing the request URI's origin, invalidating
|
|
364
|
+
// cross-origin URIs could be used for cache poisoning
|
|
365
|
+
continue
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const path = `${url.pathname}${url.search}`
|
|
369
|
+
if (invalidatedPaths.has(path)) {
|
|
370
|
+
continue
|
|
371
|
+
}
|
|
372
|
+
invalidatedPaths.add(path)
|
|
373
|
+
|
|
374
|
+
try {
|
|
375
|
+
this.#store.delete({ ...this.#cacheKey, path })?.catch?.(noop)
|
|
376
|
+
} catch {
|
|
377
|
+
// Fail silently
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
317
382
|
onResponseData (controller, chunk) {
|
|
318
383
|
if (this.#writeStream?.write(chunk) === false) {
|
|
319
384
|
controller.pause()
|
|
@@ -422,23 +487,35 @@ function getAge (ageHeader) {
|
|
|
422
487
|
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
|
|
423
488
|
* @param {Date | undefined} responseDate
|
|
424
489
|
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
|
|
490
|
+
* @param {boolean} hasValidator whether the response has a validator (etag or
|
|
491
|
+
* last-modified) that revalidation requests can be made with
|
|
425
492
|
*
|
|
426
493
|
* @returns {number | undefined} time that the value is stale at in seconds or undefined if it shouldn't be cached
|
|
427
494
|
*/
|
|
428
|
-
function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheControlDirectives) {
|
|
495
|
+
function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheControlDirectives, hasValidator) {
|
|
429
496
|
if (cacheType === 'shared') {
|
|
430
497
|
// Prioritize s-maxage since we're a shared cache
|
|
431
498
|
// s-maxage > max-age > Expire
|
|
432
499
|
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.10-3
|
|
433
500
|
const sMaxAge = cacheControlDirectives['s-maxage']
|
|
434
501
|
if (sMaxAge !== undefined) {
|
|
435
|
-
|
|
502
|
+
if (sMaxAge > 0) {
|
|
503
|
+
return sMaxAge * 1000
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// Immediately stale, but storable if we can revalidate it before reuse.
|
|
507
|
+
return sMaxAge === 0 && hasValidator ? 0 : undefined
|
|
436
508
|
}
|
|
437
509
|
}
|
|
438
510
|
|
|
439
511
|
const maxAge = cacheControlDirectives['max-age']
|
|
440
512
|
if (maxAge !== undefined) {
|
|
441
|
-
|
|
513
|
+
if (maxAge > 0) {
|
|
514
|
+
return maxAge * 1000
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// Immediately stale, but storable if we can revalidate it before reuse.
|
|
518
|
+
return maxAge === 0 && hasValidator ? 0 : undefined
|
|
442
519
|
}
|
|
443
520
|
|
|
444
521
|
if (typeof resHeaders.expires === 'string') {
|
|
@@ -482,6 +559,12 @@ function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheC
|
|
|
482
559
|
return 31536000000
|
|
483
560
|
}
|
|
484
561
|
|
|
562
|
+
if (cacheControlDirectives['no-cache'] === true && hasValidator) {
|
|
563
|
+
// No freshness source, but a validator lets us revalidate before reuse.
|
|
564
|
+
// https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.4
|
|
565
|
+
return 0
|
|
566
|
+
}
|
|
567
|
+
|
|
485
568
|
return undefined
|
|
486
569
|
}
|
|
487
570
|
|
|
@@ -518,6 +601,11 @@ function determineDeleteAt (baseTime, cachedAt, cacheControlDirectives, staleAt)
|
|
|
518
601
|
// revalidated.
|
|
519
602
|
if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
|
|
520
603
|
const freshnessLifetime = staleAt - baseTime
|
|
604
|
+
if (freshnessLifetime <= 0) {
|
|
605
|
+
// Revalidation-only entry: no freshness lifetime to size the buffer on,
|
|
606
|
+
// so retain it for a bounded window instead.
|
|
607
|
+
return cachedAt + REVALIDATION_ONLY_RETENTION
|
|
608
|
+
}
|
|
521
609
|
const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1000)
|
|
522
610
|
return staleAt + freshnessLifetime + datePrecisionPadding
|
|
523
611
|
}
|
|
@@ -109,6 +109,16 @@ class CacheRevalidationHandler {
|
|
|
109
109
|
}
|
|
110
110
|
|
|
111
111
|
if (this.#callback) {
|
|
112
|
+
// Serve the stale cached response on a connection error, per stale-if-error:
|
|
113
|
+
// RFC 5861 counts an unreachable origin (a would-be 5xx) as an error.
|
|
114
|
+
// https://datatracker.ietf.org/doc/html/rfc5861#section-4
|
|
115
|
+
if (this.#allowErrorStatusCodes) {
|
|
116
|
+
this.#successful = true
|
|
117
|
+
this.#callback(true, this.#context)
|
|
118
|
+
this.#callback = null
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
|
|
112
122
|
this.#callback(false)
|
|
113
123
|
this.#callback = null
|
|
114
124
|
}
|
|
@@ -52,6 +52,8 @@ class RedirectHandler {
|
|
|
52
52
|
throw new Error('max redirects')
|
|
53
53
|
}
|
|
54
54
|
|
|
55
|
+
let removeContentHeaders = statusCode === 303
|
|
56
|
+
|
|
55
57
|
// https://tools.ietf.org/html/rfc7231#section-6.4.2
|
|
56
58
|
// https://fetch.spec.whatwg.org/#http-redirect-fetch
|
|
57
59
|
// In case of HTTP 301 or 302 with POST, change the method to GET
|
|
@@ -62,6 +64,7 @@ class RedirectHandler {
|
|
|
62
64
|
util.destroy(this.opts.body.on('error', noop))
|
|
63
65
|
}
|
|
64
66
|
this.opts.body = null
|
|
67
|
+
removeContentHeaders = true
|
|
65
68
|
}
|
|
66
69
|
|
|
67
70
|
// https://tools.ietf.org/html/rfc7231#section-6.4.4
|
|
@@ -101,9 +104,9 @@ class RedirectHandler {
|
|
|
101
104
|
}
|
|
102
105
|
|
|
103
106
|
// Remove headers referring to the original URL.
|
|
104
|
-
// By default it is Host only
|
|
107
|
+
// By default it is Host only. A 303 or a 301/302 POST-to-GET redirect also removes all Content-* headers.
|
|
105
108
|
// https://tools.ietf.org/html/rfc7231#section-6.4
|
|
106
|
-
this.opts.headers = cleanRequestHeaders(this.opts.headers,
|
|
109
|
+
this.opts.headers = cleanRequestHeaders(this.opts.headers, removeContentHeaders, this.opts.origin !== origin, this.stripHeadersOnRedirect, this.stripHeadersOnCrossOriginRedirect)
|
|
107
110
|
this.opts.path = path
|
|
108
111
|
this.opts.origin = origin
|
|
109
112
|
this.opts.query = null
|
|
@@ -11,7 +11,7 @@ const {
|
|
|
11
11
|
|
|
12
12
|
function calculateRetryAfterHeader (retryAfter) {
|
|
13
13
|
const retryTime = new Date(retryAfter).getTime()
|
|
14
|
-
return isNaN(retryTime) ?
|
|
14
|
+
return isNaN(retryTime) ? null : retryTime - Date.now()
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
// A stable controller handed to the downstream handler for the lifetime of the
|
|
@@ -211,9 +211,11 @@ class RetryHandler {
|
|
|
211
211
|
}
|
|
212
212
|
|
|
213
213
|
const retryTimeout =
|
|
214
|
-
retryAfterHeader
|
|
215
|
-
?
|
|
216
|
-
:
|
|
214
|
+
retryAfterHeader === 0
|
|
215
|
+
? 0
|
|
216
|
+
: retryAfterHeader > 0
|
|
217
|
+
? Math.min(retryAfterHeader, maxTimeout)
|
|
218
|
+
: Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout)
|
|
217
219
|
|
|
218
220
|
setTimeout(() => cb(null), retryTimeout)
|
|
219
221
|
}
|
package/lib/interceptor/cache.js
CHANGED
|
@@ -57,16 +57,33 @@ function needsRevalidation (result, cacheControlDirectives, { headers = {} }) {
|
|
|
57
57
|
return false
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/**
|
|
61
|
+
* must-revalidate (proxy-revalidate for shared caches) forbids serving a stale
|
|
62
|
+
* response without successful validation, overriding max-stale and stale-if-error.
|
|
63
|
+
* https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.2
|
|
64
|
+
* https://www.rfc-editor.org/rfc/rfc9111.html#section-5.2.2.8
|
|
65
|
+
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
|
|
66
|
+
* @param {'shared' | 'private'} cacheType
|
|
67
|
+
* @returns {boolean}
|
|
68
|
+
*/
|
|
69
|
+
function forbidsServingStale (result, cacheType) {
|
|
70
|
+
return Boolean(
|
|
71
|
+
result.cacheControlDirectives?.['must-revalidate'] ||
|
|
72
|
+
(cacheType === 'shared' && result.cacheControlDirectives?.['proxy-revalidate'])
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
|
|
60
76
|
/**
|
|
61
77
|
* @param {import('../../types/cache-interceptor.d.ts').default.GetResult} result
|
|
62
78
|
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives | undefined} cacheControlDirectives
|
|
79
|
+
* @param {'shared' | 'private'} cacheType
|
|
63
80
|
* @returns {boolean}
|
|
64
81
|
*/
|
|
65
|
-
function isStale (result, cacheControlDirectives) {
|
|
82
|
+
function isStale (result, cacheControlDirectives, cacheType) {
|
|
66
83
|
const now = Date.now()
|
|
67
84
|
if (now > result.staleAt) {
|
|
68
85
|
// Response is stale
|
|
69
|
-
if (cacheControlDirectives?.['max-stale']) {
|
|
86
|
+
if (cacheControlDirectives?.['max-stale'] && !forbidsServingStale(result, cacheType)) {
|
|
70
87
|
// There's a threshold where we can serve stale responses, let's see if
|
|
71
88
|
// we're in it
|
|
72
89
|
// https://www.rfc-editor.org/rfc/rfc9111.html#name-max-stale
|
|
@@ -286,7 +303,7 @@ function handleResult (
|
|
|
286
303
|
return dispatch(opts, handler)
|
|
287
304
|
}
|
|
288
305
|
|
|
289
|
-
const stale = isStale(result, reqCacheControl)
|
|
306
|
+
const stale = isStale(result, reqCacheControl, globalOpts.type)
|
|
290
307
|
const revalidate = needsRevalidation(result, reqCacheControl, opts)
|
|
291
308
|
|
|
292
309
|
// Check if the response is stale
|
|
@@ -345,7 +362,7 @@ function handleResult (
|
|
|
345
362
|
|
|
346
363
|
let withinStaleIfErrorThreshold = false
|
|
347
364
|
const staleIfErrorExpiry = result.cacheControlDirectives['stale-if-error'] ?? reqCacheControl?.['stale-if-error']
|
|
348
|
-
if (staleIfErrorExpiry) {
|
|
365
|
+
if (staleIfErrorExpiry && !forbidsServingStale(result, globalOpts.type)) {
|
|
349
366
|
withinStaleIfErrorThreshold = now < (result.staleAt + (staleIfErrorExpiry * 1000))
|
|
350
367
|
}
|
|
351
368
|
|
|
@@ -276,6 +276,10 @@ function createDecompressInterceptor (options = {}) {
|
|
|
276
276
|
|
|
277
277
|
return (dispatch) => {
|
|
278
278
|
return (opts, handler) => {
|
|
279
|
+
if (opts.method === 'HEAD') {
|
|
280
|
+
return dispatch(opts, handler)
|
|
281
|
+
}
|
|
282
|
+
|
|
279
283
|
const decompressHandler = new DecompressHandler(handler, options)
|
|
280
284
|
return dispatch(opts, decompressHandler)
|
|
281
285
|
}
|
|
@@ -12,6 +12,11 @@ const {
|
|
|
12
12
|
} = require('./mock-symbols')
|
|
13
13
|
const { InvalidArgumentError } = require('../core/errors')
|
|
14
14
|
const { serializePathWithQuery } = require('../core/util')
|
|
15
|
+
const {
|
|
16
|
+
types: {
|
|
17
|
+
isPromise
|
|
18
|
+
}
|
|
19
|
+
} = require('node:util')
|
|
15
20
|
|
|
16
21
|
/**
|
|
17
22
|
* Defines the scope API for an interceptor reply
|
|
@@ -117,13 +122,9 @@ class MockInterceptor {
|
|
|
117
122
|
// Values of reply aren't available right now as they
|
|
118
123
|
// can only be available when the reply callback is invoked.
|
|
119
124
|
if (typeof replyOptionsCallbackOrStatusCode === 'function') {
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
|
|
123
|
-
const wrappedDefaultsCallback = (opts) => {
|
|
124
|
-
// Our reply options callback contains the parameter for statusCode, data and options.
|
|
125
|
-
const resolvedData = replyOptionsCallbackOrStatusCode(opts)
|
|
126
|
-
|
|
125
|
+
// Resolves the data returned by a reply options callback into
|
|
126
|
+
// dispatch data, validating its format along the way.
|
|
127
|
+
const resolveReplyCallbackData = (resolvedData) => {
|
|
127
128
|
// Check if it is in the right format
|
|
128
129
|
if (typeof resolvedData !== 'object' || resolvedData === null) {
|
|
129
130
|
throw new InvalidArgumentError('reply options callback must return an object')
|
|
@@ -138,6 +139,23 @@ class MockInterceptor {
|
|
|
138
139
|
}
|
|
139
140
|
}
|
|
140
141
|
|
|
142
|
+
// We'll first wrap the provided callback in another function,
|
|
143
|
+
// this function will properly resolve the data from the callback
|
|
144
|
+
// when invoked.
|
|
145
|
+
const wrappedDefaultsCallback = (opts) => {
|
|
146
|
+
// Our reply options callback contains the parameter for statusCode, data and options.
|
|
147
|
+
const resolvedData = replyOptionsCallbackOrStatusCode(opts)
|
|
148
|
+
|
|
149
|
+
// An asynchronous reply options callback resolves to the reply
|
|
150
|
+
// parameters, so the dispatch data can only be resolved once the
|
|
151
|
+
// returned promise settles.
|
|
152
|
+
if (isPromise(resolvedData)) {
|
|
153
|
+
return resolvedData.then(resolveReplyCallbackData)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return resolveReplyCallbackData(resolvedData)
|
|
157
|
+
}
|
|
158
|
+
|
|
141
159
|
// Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
|
|
142
160
|
const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback, { ignoreTrailingSlash: this[kIgnoreTrailingSlash] })
|
|
143
161
|
return new MockScope(newMockDispatch)
|
package/lib/mock/mock-utils.js
CHANGED
|
@@ -292,25 +292,54 @@ function mockDispatch (opts, handler) {
|
|
|
292
292
|
// Get mock dispatch from built key
|
|
293
293
|
const key = buildKey(opts)
|
|
294
294
|
const mockDispatch = getMockDispatch(this[kDispatches], key)
|
|
295
|
+
const mockDispatches = this[kDispatches]
|
|
295
296
|
|
|
296
297
|
mockDispatch.timesInvoked++
|
|
297
298
|
|
|
299
|
+
const { timesInvoked, times } = mockDispatch
|
|
300
|
+
|
|
301
|
+
// If it's used up and not persistent, mark as consumed
|
|
302
|
+
mockDispatch.consumed = !mockDispatch.persist && timesInvoked >= times
|
|
303
|
+
mockDispatch.pending = timesInvoked < times
|
|
304
|
+
|
|
298
305
|
// Here's where we resolve a callback if a callback is present for the dispatch data.
|
|
299
306
|
if (mockDispatch.data.callback) {
|
|
300
|
-
|
|
307
|
+
const callbackResult = mockDispatch.data.callback(opts)
|
|
308
|
+
|
|
309
|
+
// An asynchronous reply options callback resolves to the reply data, so
|
|
310
|
+
// the dispatch can only continue once the returned promise settles.
|
|
311
|
+
// A rejection cannot be thrown synchronously from the dispatch at that
|
|
312
|
+
// point, so it is surfaced as a response error instead.
|
|
313
|
+
if (isPromise(callbackResult)) {
|
|
314
|
+
callbackResult.then(
|
|
315
|
+
(resolvedData) => {
|
|
316
|
+
mockDispatch.data = { ...mockDispatch.data, ...resolvedData }
|
|
317
|
+
dispatchMockReply(mockDispatches, mockDispatch, key, opts, handler)
|
|
318
|
+
},
|
|
319
|
+
(error) => {
|
|
320
|
+
deleteMockDispatch(mockDispatches, key)
|
|
321
|
+
handler.onResponseError(null, error)
|
|
322
|
+
}
|
|
323
|
+
)
|
|
324
|
+
return true
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
mockDispatch.data = { ...mockDispatch.data, ...callbackResult }
|
|
301
328
|
}
|
|
302
329
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
const { timesInvoked, times } = mockDispatch
|
|
330
|
+
return dispatchMockReply(mockDispatches, mockDispatch, key, opts, handler)
|
|
331
|
+
}
|
|
306
332
|
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
333
|
+
/**
|
|
334
|
+
* Replies to a request once the mock dispatch data is fully resolved
|
|
335
|
+
*/
|
|
336
|
+
function dispatchMockReply (mockDispatches, mockDispatch, key, opts, handler) {
|
|
337
|
+
// Parse mockDispatch data
|
|
338
|
+
const { data: { statusCode, data, headers, trailers, error }, delay } = mockDispatch
|
|
310
339
|
|
|
311
340
|
// If specified, trigger dispatch error
|
|
312
341
|
if (error !== null) {
|
|
313
|
-
deleteMockDispatch(
|
|
342
|
+
deleteMockDispatch(mockDispatches, key)
|
|
314
343
|
handler.onResponseError(null, error)
|
|
315
344
|
return true
|
|
316
345
|
}
|
|
@@ -353,10 +382,10 @@ function mockDispatch (opts, handler) {
|
|
|
353
382
|
if (typeof delay === 'number' && delay > 0) {
|
|
354
383
|
timer = setTimeout(() => {
|
|
355
384
|
timer = null
|
|
356
|
-
handleReply(
|
|
385
|
+
handleReply(mockDispatches)
|
|
357
386
|
}, delay)
|
|
358
387
|
} else {
|
|
359
|
-
handleReply(
|
|
388
|
+
handleReply(mockDispatches)
|
|
360
389
|
}
|
|
361
390
|
|
|
362
391
|
function handleReply (mockDispatches, _data = data) {
|
package/lib/util/cache.js
CHANGED
|
@@ -42,15 +42,57 @@ function normalizeHeaders (opts) {
|
|
|
42
42
|
headers = {}
|
|
43
43
|
|
|
44
44
|
if (hasSafeIterator(opts.headers)) {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
if (Array.isArray(opts.headers)) {
|
|
46
|
+
// Array format: could be flat alternating [k, v, k, v, ...]
|
|
47
|
+
// or array-of-pairs [[k, v], ...]
|
|
48
|
+
const first = opts.headers[0]
|
|
49
|
+
if (Array.isArray(first)) {
|
|
50
|
+
for (const x of opts.headers) {
|
|
51
|
+
if (!Array.isArray(x)) {
|
|
52
|
+
throw new Error('opts.headers is not a valid header map')
|
|
53
|
+
}
|
|
54
|
+
const [key, val] = x
|
|
55
|
+
if (typeof key !== 'string' || typeof val !== 'string') {
|
|
56
|
+
throw new Error('opts.headers is not a valid header map')
|
|
57
|
+
}
|
|
58
|
+
headers[key.toLowerCase()] = val
|
|
59
|
+
}
|
|
60
|
+
} else {
|
|
61
|
+
// Flat alternating array [k, v, k, v, ...]
|
|
62
|
+
const len = opts.headers.length
|
|
63
|
+
if (len % 2 !== 0) {
|
|
64
|
+
throw new Error('opts.headers is not a valid header map')
|
|
65
|
+
}
|
|
66
|
+
for (let i = 0; i < len; i += 2) {
|
|
67
|
+
const key = opts.headers[i]
|
|
68
|
+
const val = opts.headers[i + 1]
|
|
69
|
+
if (typeof key !== 'string' || (typeof val !== 'string' && !Array.isArray(val))) {
|
|
70
|
+
throw new Error('opts.headers is not a valid header map')
|
|
71
|
+
}
|
|
72
|
+
if (typeof val === 'string') {
|
|
73
|
+
headers[key.toLowerCase()] = val
|
|
74
|
+
} else {
|
|
75
|
+
const mapped = []
|
|
76
|
+
for (let j = 0; j < val.length; j++) {
|
|
77
|
+
const v = val[j]
|
|
78
|
+
mapped.push(typeof v === 'string' ? v : v.toString('latin1'))
|
|
79
|
+
}
|
|
80
|
+
headers[key.toLowerCase()] = mapped
|
|
81
|
+
}
|
|
82
|
+
}
|
|
48
83
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
84
|
+
} else {
|
|
85
|
+
// Non-array iterable (e.g. Map) — use original iteration logic
|
|
86
|
+
for (const x of opts.headers) {
|
|
87
|
+
if (!Array.isArray(x)) {
|
|
88
|
+
throw new Error('opts.headers is not a valid header map')
|
|
89
|
+
}
|
|
90
|
+
const [key, val] = x
|
|
91
|
+
if (typeof key !== 'string' || typeof val !== 'string') {
|
|
92
|
+
throw new Error('opts.headers is not a valid header map')
|
|
93
|
+
}
|
|
94
|
+
headers[key.toLowerCase()] = val
|
|
52
95
|
}
|
|
53
|
-
headers[key.toLowerCase()] = val
|
|
54
96
|
}
|
|
55
97
|
} else {
|
|
56
98
|
for (const key of Object.keys(opts.headers)) {
|
package/lib/web/fetch/body.js
CHANGED
|
@@ -16,6 +16,7 @@ const { serializeAMimeType } = require('./data-url')
|
|
|
16
16
|
const { multipartFormDataParser } = require('./formdata-parser')
|
|
17
17
|
const { parseJSONFromBytes } = require('../infra')
|
|
18
18
|
const { utf8DecodeBytes } = require('../../encoding')
|
|
19
|
+
const { ReadableStreamTee } = require('node:stream/web')
|
|
19
20
|
|
|
20
21
|
const textEncoder = new TextEncoder()
|
|
21
22
|
function noop () {}
|
|
@@ -279,7 +280,7 @@ function cloneBody (body) {
|
|
|
279
280
|
// https://fetch.spec.whatwg.org/#concept-body-clone
|
|
280
281
|
|
|
281
282
|
// 1. Let « out1, out2 » be the result of teeing body’s stream.
|
|
282
|
-
const { 0: out1, 1: out2 } = body.stream.tee()
|
|
283
|
+
const { 0: out1, 1: out2 } = ReadableStreamTee?.(body.stream, true) ?? body.stream.tee()
|
|
283
284
|
|
|
284
285
|
// 2. Set body’s stream to out1.
|
|
285
286
|
body.stream = out1
|
|
@@ -45,9 +45,7 @@ class Response {
|
|
|
45
45
|
static json (data, init = undefined) {
|
|
46
46
|
webidl.argumentLengthCheck(arguments, 1, 'Response.json')
|
|
47
47
|
|
|
48
|
-
|
|
49
|
-
init = webidl.converters.ResponseInit(init)
|
|
50
|
-
}
|
|
48
|
+
init = webidl.converters.ResponseInit(init)
|
|
51
49
|
|
|
52
50
|
// 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
|
|
53
51
|
const bytes = textEncoder.encode(
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "undici",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.8.0",
|
|
4
4
|
"description": "An HTTP/1.1 client, written from scratch for Node.js",
|
|
5
5
|
"homepage": "https://undici.nodejs.org",
|
|
6
6
|
"bugs": {
|
|
@@ -116,7 +116,7 @@
|
|
|
116
116
|
"@types/node": "^22.0.0",
|
|
117
117
|
"abort-controller": "^3.0.0",
|
|
118
118
|
"borp": "^1.0.0",
|
|
119
|
-
"c8": "^
|
|
119
|
+
"c8": "^12.0.0",
|
|
120
120
|
"cross-env": "^10.0.0",
|
|
121
121
|
"dns-packet": "^5.4.0",
|
|
122
122
|
"esbuild": "^0.28.0",
|
package/types/client.d.ts
CHANGED
|
@@ -33,7 +33,7 @@ export declare namespace Client {
|
|
|
33
33
|
export interface Options {
|
|
34
34
|
/** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */
|
|
35
35
|
maxHeaderSize?: number;
|
|
36
|
-
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */
|
|
36
|
+
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). HTTP/1.1 parser timeouts are not guaranteed to fire with exact millisecond precision: delays up to 1000ms use native timers, while larger delays use lower-overhead fast timers with a target resolution around 500ms. */
|
|
37
37
|
headersTimeout?: number;
|
|
38
38
|
/** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */
|
|
39
39
|
socketTimeout?: never;
|
|
@@ -41,7 +41,7 @@ export declare namespace Client {
|
|
|
41
41
|
requestTimeout?: never;
|
|
42
42
|
/** The timeout for establishing a socket connection, in milliseconds. Use `0` to disable it entirely. Default: `10e3` milliseconds (10s). */
|
|
43
43
|
connectTimeout?: number;
|
|
44
|
-
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */
|
|
44
|
+
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). HTTP/1.1 parser timeouts are not guaranteed to fire with exact millisecond precision: delays up to 1000ms use native timers, while larger delays use lower-overhead fast timers with a target resolution around 500ms. */
|
|
45
45
|
bodyTimeout?: number;
|
|
46
46
|
/** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */
|
|
47
47
|
idleTimeout?: never;
|
package/types/dispatcher.d.ts
CHANGED
|
@@ -111,13 +111,13 @@ declare namespace Dispatcher {
|
|
|
111
111
|
idempotent?: boolean;
|
|
112
112
|
/** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. Defaults to `method !== 'HEAD'`. */
|
|
113
113
|
blocking?: boolean;
|
|
114
|
-
/** The IP Type of Service (ToS) value for the request socket. Must be an integer between 0 and 255.
|
|
114
|
+
/** The IP Type of Service (ToS) value for the request socket. Must be an integer between 0 and 255. */
|
|
115
115
|
typeOfService?: number | null;
|
|
116
116
|
/** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */
|
|
117
117
|
upgrade?: boolean | string | null;
|
|
118
|
-
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */
|
|
118
|
+
/** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. HTTP/1.1 parser timeouts are not guaranteed to fire with exact millisecond precision: delays up to 1000ms use native timers, while larger delays use lower-overhead fast timers with a target resolution around 500ms. */
|
|
119
119
|
headersTimeout?: number | null;
|
|
120
|
-
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */
|
|
120
|
+
/** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. HTTP/1.1 parser timeouts are not guaranteed to fire with exact millisecond precision: delays up to 1000ms use native timers, while larger delays use lower-overhead fast timers with a target resolution around 500ms. */
|
|
121
121
|
bodyTimeout?: number | null;
|
|
122
122
|
/** Whether the request should stablish a keep-alive or not. Default `false` */
|
|
123
123
|
reset?: boolean;
|
|
@@ -75,9 +75,13 @@ declare namespace MockInterceptor {
|
|
|
75
75
|
opts: MockResponseCallbackOptions
|
|
76
76
|
) => TData | Buffer | string
|
|
77
77
|
|
|
78
|
+
export type MockReplyOptions<TData extends object = object> = {
|
|
79
|
+
statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions
|
|
80
|
+
}
|
|
81
|
+
|
|
78
82
|
export type MockReplyOptionsCallback<TData extends object = object> = (
|
|
79
83
|
opts: MockResponseCallbackOptions
|
|
80
|
-
) =>
|
|
84
|
+
) => MockReplyOptions<TData> | Promise<MockReplyOptions<TData>>
|
|
81
85
|
}
|
|
82
86
|
|
|
83
87
|
interface Interceptable extends Dispatcher {
|