deps: update undici to 8.0.2

PR-URL: https://github.com/nodejs/node/pull/62384
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Rafael Gonzaga <rafael.nunu@hotmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
Node.js GitHub Bot authored and RafaelGSS committed 2026-04-14 10:57:43 +01:00
1 parent 98907f560f
commit b81d2cbcae
61 files changed
+2787 -2142

No files matched your search

+2 -1
View File
@@ -93,8 +93,9 @@ test/request-timeout.10mb.bin
CLAUDE.md
.claude
# Ignore .pi
# Local tooling
.pi
AGENTS.md
# Ignore .githuman
.githuman
+4
View File
@@ -96,6 +96,10 @@ Create a commit which includes all of the updated files in lib/llhttp.
### Steps:
`npm run test:wpt` and `node test/web-platform-tests/wpt-runner.mjs setup` will initialize the WPT submodule automatically when it is missing.
If you want to prepare the checkout explicitly, run:
```bash
git submodule update --init --recursive
```
+62
View File
@@ -154,6 +154,57 @@ const { statusCode, body } = await request('https://api.example.com/data');
const data = await body.json();
```
### Keep `fetch` and `FormData` together
When you send a `FormData` body, keep `fetch` and `FormData` from the same
implementation.
Use one of these patterns:
```js
// Built-in globals
const body = new FormData()
body.set('name', 'some')
await fetch('https://example.com', {
method: 'POST',
body
})
```
```js
// undici module imports
import { fetch, FormData } from 'undici'
const body = new FormData()
body.set('name', 'some')
await fetch('https://example.com', {
method: 'POST',
body
})
```
If you want the installed `undici` package to provide the globals, call
`install()` first:
```js
import { install } from 'undici'
install()
const body = new FormData()
body.set('name', 'some')
await fetch('https://example.com', {
method: 'POST',
body
})
```
`install()` replaces the global `fetch`, `Headers`, `Response`, `Request`, and
`FormData` implementations with undici's versions, so they all match.
Avoid mixing a global `FormData` with `undici.fetch()`, or `undici.FormData`
with the built-in global `fetch()`.
### Version Compatibility
You can check which version of undici is bundled with your Node.js version:
@@ -263,6 +314,11 @@ The `install()` function adds the following classes to `globalThis`:
- `CloseEvent`, `ErrorEvent`, `MessageEvent` - WebSocket events
- `EventSource` - Server-sent events client
When you call `install()`, these globals come from the same undici
implementation. For example, global `fetch` and global `FormData` will both be
undici's versions, which is the recommended setup if you want to use undici
through globals.
This is useful for:
- Polyfilling environments that don't have fetch
- Ensuring consistent fetch behavior across different Node.js versions
@@ -563,6 +619,12 @@ See [Dispatcher.upgrade](./docs/docs/api/Dispatcher.md#dispatcherupgradeoptions-
Sets the global dispatcher used by Common API Methods. Global dispatcher is shared among compatible undici modules,
including undici that is bundled internally with node.js.
Undici stores this dispatcher under `Symbol.for('undici.globalDispatcher.2')`.
`setGlobalDispatcher()` also mirrors the configured dispatcher to
`Symbol.for('undici.globalDispatcher.1')` using `Dispatcher1Wrapper`, so Node.js built-in `fetch`
can keep using the legacy handler contract while Undici uses the new handler API.
### `undici.getGlobalDispatcher()`
Gets the global dispatcher used by Common API Methods.
+2 -2
View File
@@ -29,7 +29,7 @@ Returns: `Client`
* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. **Security Warning:** Disabling this option can expose your application to HTTP Request Smuggling attacks, where mismatched content-length headers cause servers and proxies to interpret request boundaries differently. This can lead to cache poisoning, credential hijacking, and bypassing security controls. Only disable this in controlled environments where you fully trust the request source.
* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version.
* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details.
* **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
* **allowH2**: `boolean` - Default: `true`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation.
* **useH2c**: `boolean` - Default: `false`. Enforces h2c for non-https connections.
* **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame.
* **initialWindowSize**: `number` (optional) - Default: `262144` (256KB). Sets the HTTP/2 stream-level flow-control window size (SETTINGS_INITIAL_WINDOW_SIZE). Must be a positive integer greater than 0. This default is higher than Node.js core's default (65535 bytes) to improve throughput, Node's choice is very conservative for current high-bandwith networks. See [RFC 7540 Section 6.9.2](https://datatracker.ietf.org/doc/html/rfc7540#section-6.9.2) for more details.
@@ -282,4 +282,4 @@ console.log('requests completed')
### Event: `'error'`
Invoked for users errors such as throwing in the `onError` handler.
Invoked for user errors such as throwing in the `onResponseError` handler.
+8 -6
View File
@@ -182,22 +182,24 @@ diagnosticsChannel.channel('undici:websocket:open').subscribe(({
console.log(websocket) // the WebSocket instance
// Handshake response details
console.log(handshakeResponse.status) // 101 for successful WebSocket upgrade
console.log(handshakeResponse.statusText) // 'Switching Protocols'
console.log(handshakeResponse.status) // 101 for HTTP/1.1, 200 for HTTP/2 extended CONNECT
console.log(handshakeResponse.statusText) // 'Switching Protocols' for HTTP/1.1, commonly 'OK' for HTTP/2 in Node.js
console.log(handshakeResponse.headers) // Object containing response headers
})
```
### Handshake Response Object
The `handshakeResponse` object contains the HTTP response that upgraded the connection to WebSocket:
The `handshakeResponse` object contains the HTTP response that established the WebSocket connection:
- `status` (number): The HTTP status code (101 for successful WebSocket upgrade)
- `statusText` (string): The HTTP status message ('Switching Protocols' for successful upgrade)
- `status` (number): The HTTP status code (`101` for HTTP/1.1 upgrade, `200` for HTTP/2 extended CONNECT)
- `statusText` (string): The HTTP status message (`'Switching Protocols'` for HTTP/1.1, commonly `'OK'` for HTTP/2 in Node.js)
- `headers` (object): The HTTP response headers from the server, including:
- `sec-websocket-accept` and other WebSocket-related headers
- `upgrade: 'websocket'`
- `connection: 'upgrade'`
- `sec-websocket-accept` and other WebSocket-related headers
The `upgrade` and `connection` headers are only present for HTTP/1.1 handshakes.
This information is particularly useful for debugging and monitoring WebSocket connections, as it provides access to the initial HTTP handshake response that established the WebSocket connection.
+62 -27
View File
@@ -212,6 +212,41 @@ Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls wo
* **onResponseEnd** `(controller: DispatchController, trailers: Record<string, string | string[]>) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests.
* **onResponseError** `(controller: DispatchController, error: Error) => void` - Invoked when an error has occurred. May not throw.
#### Migration from legacy handler API
If you were previously using `onConnect/onHeaders/onData/onComplete/onError`, switch to the new callbacks:
- `onConnect(abort)` → `onRequestStart(controller)` and call `controller.abort(reason)`
- `onHeaders(status, rawHeaders, resume, statusText)` → `onResponseStart(controller, status, headers, statusText)`
- `onData(chunk)` → `onResponseData(controller, chunk)`
- `onComplete(trailers)` → `onResponseEnd(controller, trailers)`
- `onError(err)` → `onResponseError(controller, err)`
- `onUpgrade(status, rawHeaders, socket)` → `onRequestUpgrade(controller, status, headers, socket)`
To access raw header arrays (for preserving duplicates/casing), read them from the controller:
- `controller.rawHeaders` for response headers
- `controller.rawTrailers` for trailers
Pause/resume now uses the controller:
- Call `controller.pause()` and `controller.resume()` instead of returning `false` from handlers.
#### Compatibility notes
Undici now stores the global dispatcher under `Symbol.for('undici.globalDispatcher.2')`.
This avoids conflicts with runtimes (such as Node.js built-in `fetch`) that still rely on the legacy dispatcher handler interface.
`setGlobalDispatcher()` also mirrors the configured dispatcher to `Symbol.for('undici.globalDispatcher.1')` using a `Dispatcher1Wrapper`, so Node's built-in `fetch` can keep using the legacy handler contract.
If you need to expose a new dispatcher/agent to legacy v1 handler consumers (`onConnect/onHeaders/onData/onComplete/onError/onUpgrade`), use `Dispatcher1Wrapper`:
```js
import { Agent, Dispatcher1Wrapper } from 'undici'
const legacyCompatibleDispatcher = new Dispatcher1Wrapper(new Agent())
```
#### Example 1 - Dispatch GET request
```js
@@ -236,21 +271,21 @@ client.dispatch({
'x-foo': 'bar'
}
}, {
onConnect: () => {
onRequestStart: () => {
console.log('Connected!')
},
onError: (error) => {
onResponseError: (_controller, error) => {
console.error(error)
},
onHeaders: (statusCode, headers) => {
console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`)
onResponseStart: (_controller, statusCode, headers) => {
console.log(`onResponseStart | statusCode: ${statusCode} | headers: ${JSON.stringify(headers)}`)
},
onData: (chunk) => {
console.log('onData: chunk received')
onResponseData: (_controller, chunk) => {
console.log('onResponseData: chunk received')
data.push(chunk)
},
onComplete: (trailers) => {
console.log(`onComplete | trailers: ${trailers}`)
onResponseEnd: (_controller, trailers) => {
console.log(`onResponseEnd | trailers: ${JSON.stringify(trailers)}`)
const res = Buffer.concat(data).toString('utf8')
console.log(`Data: ${res}`)
client.close()
@@ -288,15 +323,15 @@ client.dispatch({
method: 'GET',
upgrade: 'websocket'
}, {
onConnect: () => {
console.log('Undici Client - onConnect')
onRequestStart: () => {
console.log('Undici Client - onRequestStart')
},
onError: (error) => {
console.log('onError') // shouldn't print
onResponseError: () => {
console.log('onResponseError') // shouldn't print
},
onUpgrade: (statusCode, headers, socket) => {
console.log('Undici Client - onUpgrade')
console.log(`onUpgrade Headers: ${headers}`)
onRequestUpgrade: (_controller, statusCode, headers, socket) => {
console.log('Undici Client - onRequestUpgrade')
console.log(`onRequestUpgrade Headers: ${JSON.stringify(headers)}`)
socket.on('data', buffer => {
console.log(buffer.toString('utf8'))
})
@@ -339,21 +374,21 @@ client.dispatch({
},
body: JSON.stringify({ message: 'Hello' })
}, {
onConnect: () => {
onRequestStart: () => {
console.log('Connected!')
},
onError: (error) => {
onResponseError: (_controller, error) => {
console.error(error)
},
onHeaders: (statusCode, headers) => {
console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`)
onResponseStart: (_controller, statusCode, headers) => {
console.log(`onResponseStart | statusCode: ${statusCode} | headers: ${JSON.stringify(headers)}`)
},
onData: (chunk) => {
console.log('onData: chunk received')
onResponseData: (_controller, chunk) => {
console.log('onResponseData: chunk received')
data.push(chunk)
},
onComplete: (trailers) => {
console.log(`onComplete | trailers: ${trailers}`)
onResponseEnd: (_controller, trailers) => {
console.log(`onResponseEnd | trailers: ${JSON.stringify(trailers)}`)
const res = Buffer.concat(data).toString('utf8')
console.log(`Response Data: ${res}`)
client.close()
@@ -364,7 +399,7 @@ client.dispatch({
### `Dispatcher.pipeline(options, handler)`
For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response.
For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response.
Arguments:
@@ -963,7 +998,7 @@ const { Client, interceptors } = require("undici");
const { redirect } = interceptors;
const client = new Client("http://service.example").compose(
redirect({ maxRedirections: 3, throwOnMaxRedirects: true })
redirect({ maxRedirections: 3, throwOnMaxRedirect: true })
);
client.request({ path: "/" })
```
@@ -1036,10 +1071,10 @@ The `dns` interceptor enables you to cache DNS lookups for a given duration, per
- `dualStack` - Whether to resolve both IPv4 and IPv6 addresses. Default: `true`.
- It will also attempt a happy-eyeballs-like approach to connect to the available addresses in case of a connection failure.
- `affinity` - Whether to use IPv4 or IPv6 addresses. Default: `4`.
- It can be either `'4` or `6`.
- It can be either `4` or `6`.
- It will only take effect if `dualStack` is `false`.
- `lookup: (hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, addresses: DNSInterceptorRecord[]) => void) => void` - Custom lookup function. Default: `dns.lookup`.
- For more info see [dns.lookup](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback).
- For more info see [dns.lookup](https://nodejs.org/api/dns.html#dnslookuphostname-options-callback).
- `pick: (origin: URL, records: DNSInterceptorRecords, affinity: 4 | 6) => DNSInterceptorRecord` - Custom pick function. Default: `RoundRobin`.
- The function should return a single record from the records array.
- By default a simplified version of Round Robin is used.
+8
View File
@@ -10,6 +10,14 @@ This API is implemented as per the standard, you can find documentation on [MDN]
If any parameters are passed to the FormData constructor other than `undefined`, an error will be thrown. Other parameters are ignored.
When you use `FormData` as a request body, keep `fetch` and `FormData` from the
same implementation. Use the built-in global `FormData` with the built-in
global `fetch()`, and use `undici`'s `FormData` with `undici.fetch()`.
If you want the installed `undici` package to provide the globals, call
[`install()`](/docs/api/GlobalInstallation.md) so `fetch`, `Headers`,
`Response`, `Request`, and `FormData` are installed together as a matching set.
## Response
This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response)
+48
View File
@@ -43,6 +43,54 @@ The `install()` function adds the following classes to `globalThis`:
| `MessageEvent` | WebSocket message event |
| `EventSource` | Server-sent events client |
## Using `FormData` with `fetch`
If you send a `FormData` body, use matching implementations for `fetch` and
`FormData`.
These two patterns are safe:
```js
// Built-in globals from Node.js
const body = new FormData()
await fetch('https://example.com', {
method: 'POST',
body
})
```
```js
// Globals installed from the undici package
import { install } from 'undici'
install()
const body = new FormData()
await fetch('https://example.com', {
method: 'POST',
body
})
```
After `install()`, `fetch`, `Headers`, `Response`, `Request`, and `FormData`
all come from the installed `undici` package, so they work as a matching set.
If you do not want to install globals, import both from `undici` instead:
```js
import { fetch, FormData } from 'undici'
const body = new FormData()
await fetch('https://example.com', {
method: 'POST',
body
})
```
Avoid mixing a global `FormData` with `undici.fetch()`, or `undici.FormData`
with the built-in global `fetch()`. Keeping them paired avoids surprising
multipart behavior across Node.js and undici versions.
## Use Cases
Global installation is useful for:
+1 -1
View File
@@ -260,4 +260,4 @@ console.log("requests completed");
### Event: `'error'`
Invoked for users errors such as throwing in the `onError` handler.
Invoked for user errors such as throwing in the `onResponseError` handler.
+15 -13
View File
@@ -2,7 +2,7 @@
A class that handles redirection logic for HTTP requests.
## `new RedirectHandler(dispatch, maxRedirections, opts, handler, redirectionLimitReached)`
## `new RedirectHandler(dispatch, maxRedirections, opts, handler)`
Arguments:
@@ -10,7 +10,6 @@ Arguments:
- **maxRedirections** `number` - Maximum number of redirections allowed.
- **opts** `object` - Options for handling redirection.
- **handler** `object` - An object containing handlers for different stages of the request lifecycle.
- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior.
Returns: `RedirectHandler`
@@ -20,7 +19,6 @@ Returns: `RedirectHandler`
- **maxRedirections** `number` (required) - Maximum number of redirections allowed.
- **opts** `object` (required) - Options for handling redirection.
- **handler** `object` (required) - Handlers for different stages of the request lifecycle.
- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior.
### Properties
@@ -30,61 +28,65 @@ Returns: `RedirectHandler`
- **maxRedirections** `number` - Maximum number of redirections allowed.
- **handler** `object` - Handlers for different stages of the request lifecycle.
- **history** `Array` - An array representing the history of URLs during redirection.
- **redirectionLimitReached** `boolean` - Indicates whether the redirection limit has been reached.
### Methods
#### `onConnect(abort)`
#### `onRequestStart(controller, context)`
Called when the connection is established.
Called when the request starts.
Parameters:
- **abort** `function` - The abort function.
- **controller** `DispatchController` - The request controller.
- **context** `object` - The dispatch context.
#### `onUpgrade(statusCode, headers, socket)`
#### `onRequestUpgrade(controller, statusCode, headers, socket)`
Called when an upgrade is requested.
Parameters:
- **controller** `DispatchController` - The request controller.
- **statusCode** `number` - The HTTP status code.
- **headers** `object` - The headers received in the response.
- **socket** `object` - The socket object.
#### `onError(error)`
#### `onResponseError(controller, error)`
Called when an error occurs.
Parameters:
- **controller** `DispatchController` - The request controller.
- **error** `Error` - The error that occurred.
#### `onHeaders(statusCode, headers, resume, statusText)`
#### `onResponseStart(controller, statusCode, headers, statusText)`
Called when headers are received.
Parameters:
- **controller** `DispatchController` - The request controller.
- **statusCode** `number` - The HTTP status code.
- **headers** `object` - The headers received in the response.
- **resume** `function` - The resume function.
- **statusText** `string` - The status text.
#### `onData(chunk)`
#### `onResponseData(controller, chunk)`
Called when data is received.
Parameters:
- **controller** `DispatchController` - The request controller.
- **chunk** `Buffer` - The data chunk received.
#### `onComplete(trailers)`
#### `onResponseEnd(controller, trailers)`
Called when the request is complete.
Parameters:
- **controller** `DispatchController` - The request controller.
- **trailers** `object` - The trailers received.
#### `onBodySent(chunk)`
-1
View File
@@ -23,7 +23,6 @@ Returns: `ProxyAgent`
- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second)
- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2`
- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true`
-
- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']`
- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]`
- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']`
+12 -14
View File
@@ -26,7 +26,6 @@ Extends: [`Dispatch.DispatchOptions`](/docs/docs/api/Dispatcher.md#parameter-dis
- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second)
- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2`
- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true`
-
- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']`
- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]`
- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', 'UND_ERR_SOCKET']`
@@ -82,17 +81,16 @@ const handler = new RetryHandler(
return client.dispatch(...args);
},
handler: {
onConnect() {},
onBodySent() {},
onHeaders(status, _rawHeaders, resume, _statusMessage) {
onRequestStart() {},
onBodySent(chunk) {},
onResponseStart(_controller, status, headers) {
// do something with headers
},
onData(chunk) {
onResponseData(_controller, chunk) {
chunks.push(chunk);
return true;
},
onComplete() {},
onError() {
onResponseEnd() {},
onResponseError(_controller, err) {
// handle error properly
},
},
@@ -107,12 +105,12 @@ const client = new Client(`http://localhost:${server.address().port}`);
const handler = new RetryHandler(dispatchOptions, {
dispatch: client.dispatch.bind(client),
handler: {
onConnect() {},
onBodySent() {},
onHeaders(status, _rawHeaders, resume, _statusMessage) {},
onData(chunk) {},
onComplete() {},
onError(err) {},
onRequestStart() {},
onBodySent(chunk) {},
onResponseStart(_controller, status, headers) {},
onResponseData(_controller, chunk) {},
onResponseEnd() {},
onResponseError(_controller, err) {},
},
});
```
@@ -19,6 +19,93 @@ When you install undici from npm, you get the full library with all of its
additional APIs, and potentially a newer release than what your Node.js version
bundles.
## Keep `fetch` and `FormData` from the same implementation
When you send a `FormData` body, keep `fetch` and `FormData` together from the
same implementation.
Use one of these patterns:
### Built-in globals
```js
const body = new FormData()
body.set('name', 'some')
body.set('someOtherProperty', '8000')
await fetch('https://example.com', {
method: 'POST',
body
})
```
### `undici` module imports
```js
import { fetch, FormData } from 'undici'
const body = new FormData()
body.set('name', 'some')
body.set('someOtherProperty', '8000')
await fetch('https://example.com', {
method: 'POST',
body
})
```
### `undici.install()` globals
If you want the installed `undici` package to provide the globals, call
[`install()`](/docs/api/GlobalInstallation.md):
```js
import { install } from 'undici'
install()
const body = new FormData()
body.set('name', 'some')
body.set('someOtherProperty', '8000')
await fetch('https://example.com', {
method: 'POST',
body
})
```
`install()` replaces the global `fetch`, `Headers`, `Response`, `Request`, and
`FormData` implementations with undici's versions, and also installs undici's
`WebSocket`, `CloseEvent`, `ErrorEvent`, `MessageEvent`, and `EventSource`
globals.
Avoid mixing implementations in the same request, for example:
```js
import { fetch } from 'undici'
const body = new FormData()
await fetch('https://example.com', {
method: 'POST',
body
})
```
```js
import { FormData } from 'undici'
const body = new FormData()
await fetch('https://example.com', {
method: 'POST',
body
})
```
Those combinations may behave differently across Node.js and undici versions.
Using matching pairs keeps multipart handling predictable.
## When you do NOT need to install undici
If all of the following are true, you can rely on the built-in globals and skip
@@ -119,12 +206,12 @@ You can always check the exact bundled version at runtime with
`process.versions.undici`.
Installing undici from npm does not replace the built-in globals. If you want
your installed version to override the global `fetch`, use
[`setGlobalDispatcher`](/docs/api/GlobalInstallation.md) or import `fetch`
your installed version to replace the global `fetch` and related classes, use
[`install()`](/docs/api/GlobalInstallation.md). Otherwise, import `fetch`
directly from `'undici'`:
```js
import { fetch } from 'undici'; // uses your installed version, not the built-in
import { fetch } from 'undici' // uses your installed version, not the built-in
```
## Further reading
@@ -18,3 +18,46 @@ const agent = new Agent({
setGlobalDispatcher(agent)
```
## Guarding against unexpected disconnects
Undici's `Client` automatically reconnects after a socket error. This means
a test can silently disconnect, reconnect, and still pass. Unfortunately,
this could mask bugs like unexpected parser errors or protocol violations.
To catch these silent reconnections, add a disconnect guard after creating
a `Client`:
```js
const { Client } = require('undici')
const { test, after } = require('node:test')
const { tspl } = require('@matteo.collina/tspl')
test('example with disconnect guard', async (t) => {
t = tspl(t, { plan: 1 })
const client = new Client('http://localhost:3000')
after(() => client.close())
client.on('disconnect', () => {
if (!client.closed && !client.destroyed) {
t.fail('unexpected disconnect')
}
})
// ... test logic ...
})
```
`client.close()` and `client.destroy()` both emit `'disconnect'` events, but
those are expected. The guard only fails when a disconnect happens during the
active test (i.e., `!client.closed && !client.destroyed` is true).
Skip the guard for tests where a disconnect is expected behavior, such as:
- Signal aborts (`signal.emit('abort')`, `ac.abort()`)
- Server-side destruction (`res.destroy()`, `req.socket.destroy()`)
- Client-side body destruction mid-stream (`data.body.destroy()`)
- Timeout errors (`HeadersTimeoutError`, `BodyTimeoutError`)
- Successful upgrades (the socket is detached from the `Client`)
- Retry/reconnect tests where the disconnect triggers the retry
- HTTP parser errors from malformed responses (`HTTPParserError`)
+2
View File
@@ -6,6 +6,7 @@ const Pool = require('./lib/dispatcher/pool')
const BalancedPool = require('./lib/dispatcher/balanced-pool')
const RoundRobinPool = require('./lib/dispatcher/round-robin-pool')
const Agent = require('./lib/dispatcher/agent')
const Dispatcher1Wrapper = require('./lib/dispatcher/dispatcher1-wrapper')
const ProxyAgent = require('./lib/dispatcher/proxy-agent')
const Socks5ProxyAgent = require('./lib/dispatcher/socks5-proxy-agent')
const EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')
@@ -35,6 +36,7 @@ module.exports.Pool = Pool
module.exports.BalancedPool = BalancedPool
module.exports.RoundRobinPool = RoundRobinPool
module.exports.Agent = Agent
module.exports.Dispatcher1Wrapper = Dispatcher1Wrapper
module.exports.ProxyAgent = ProxyAgent
module.exports.Socks5ProxyAgent = Socks5ProxyAgent
module.exports.EnvHttpProxyAgent = EnvHttpProxyAgent
+13 -11
View File
@@ -32,45 +32,48 @@ class ConnectHandler extends AsyncResource {
addSignal(this, signal)
}
onConnect (abort, context) {
onRequestStart (controller, context) {
if (this.reason) {
abort(this.reason)
controller.abort(this.reason)
return
}
assert(this.callback)
this.abort = abort
this.abort = (reason) => controller.abort(reason)
this.context = context
}
onHeaders () {
onResponseStart () {
throw new SocketError('bad connect', null)
}
onUpgrade (statusCode, rawHeaders, socket) {
onRequestUpgrade (controller, statusCode, headers, socket) {
const { callback, opaque, context } = this
removeSignal(this)
this.callback = null
let headers = rawHeaders
let responseHeaders = headers
const rawHeaders = controller?.rawHeaders
// Indicates is an HTTP2Session
if (headers != null) {
headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
if (responseHeaders != null) {
responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
: headers
}
this.runInAsyncScope(callback, null, null, {
statusCode,
headers,
headers: responseHeaders,
socket,
opaque,
context
})
}
onError (err) {
onResponseError (_controller, err) {
const { callback, opaque } = this
removeSignal(this)
@@ -96,7 +99,6 @@ function connect (opts, callback) {
try {
const connectHandler = new ConnectHandler(opts, callback)
const connectOptions = { ...opts, method: 'CONNECT' }
this.dispatch(connectOptions, connectHandler)
} catch (err) {
if (typeof callback !== 'function') {
+22 -13
View File
@@ -146,40 +146,46 @@ class PipelineHandler extends AsyncResource {
addSignal(this, signal)
}
onConnect (abort, context) {
onRequestStart (controller, context) {
const { res } = this
if (this.reason) {
abort(this.reason)
controller.abort(this.reason)
return
}
assert(!res, 'pipeline cannot be retried')
this.abort = abort
this.abort = (reason) => controller.abort(reason)
this.context = context
}
onHeaders (statusCode, rawHeaders, resume) {
onResponseStart (controller, statusCode, headers, _statusMessage) {
const { opaque, handler, context } = this
if (statusCode < 200) {
if (this.onInfo) {
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
this.onInfo({ statusCode, headers })
const rawHeaders = controller?.rawHeaders
const responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
: headers
this.onInfo({ statusCode, headers: responseHeaders })
}
return
}
this.res = new PipelineResponse(resume)
this.res = new PipelineResponse(() => controller.resume())
let body
try {
this.handler = null
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
const rawHeaders = controller?.rawHeaders
const responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
: headers
body = this.runInAsyncScope(handler, null, {
statusCode,
headers,
headers: responseHeaders,
opaque,
body: this.res,
context
@@ -222,17 +228,20 @@ class PipelineHandler extends AsyncResource {
this.body = body
}
onData (chunk) {
onResponseData (controller, chunk) {
const { res } = this
return res.push(chunk)
if (res.push(chunk) === false) {
controller.pause()
}
}
onComplete (trailers) {
onResponseEnd (_controller, _trailers) {
const { res } = this
res.push(null)
}
onError (err) {
onResponseError (_controller, err) {
const { ret } = this
this.handler = null
util.destroy(ret, err)
+44 -20
View File
@@ -54,6 +54,7 @@ class RequestHandler extends AsyncResource {
this.body = body
this.trailers = {}
this.context = null
this.controller = null
this.onInfo = onInfo || null
this.highWaterMark = highWaterMark
this.reason = null
@@ -73,36 +74,40 @@ class RequestHandler extends AsyncResource {
}
}
onConnect (abort, context) {
onRequestStart (controller, context) {
if (this.reason) {
abort(this.reason)
controller.abort(this.reason)
return
}
assert(this.callback)
this.abort = abort
this.controller = controller
this.abort = (reason) => controller.abort(reason)
this.context = context
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
onResponseStart (controller, statusCode, headers, statusText) {
const { callback, opaque, context, responseHeaders, highWaterMark } = this
const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
const rawHeaders = controller?.rawHeaders
const responseHeaderData = responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
: headers
if (statusCode < 200) {
if (this.onInfo) {
this.onInfo({ statusCode, headers })
this.onInfo({ statusCode, headers: responseHeaderData })
}
return
}
const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
const contentType = parsedHeaders['content-type']
const contentLength = parsedHeaders['content-length']
const parsedHeaders = headers
const contentType = parsedHeaders?.['content-type']
const contentLength = parsedHeaders?.['content-length']
const res = new Readable({
resume,
abort,
resume: () => controller.resume(),
abort: (reason) => controller.abort(reason),
contentType,
contentLength: this.method !== 'HEAD' && contentLength
? Number(contentLength)
@@ -121,8 +126,8 @@ class RequestHandler extends AsyncResource {
try {
this.runInAsyncScope(callback, null, null, {
statusCode,
statusText: statusMessage,
headers,
statusText,
headers: responseHeaderData,
trailers: this.trailers,
opaque,
body: res,
@@ -144,16 +149,35 @@ class RequestHandler extends AsyncResource {
}
}
onData (chunk) {
return this.res.push(chunk)
onResponseData (controller, chunk) {
if (!this.res) {
return
}
if (this.res.push(chunk) === false) {
controller.pause()
}
}
onComplete (trailers) {
util.parseHeaders(trailers, this.trailers)
this.res.push(null)
onResponseEnd (_controller, trailers) {
if (trailers && typeof trailers === 'object') {
for (const key of Object.keys(trailers)) {
if (key === '__proto__') {
Object.defineProperty(this.trailers, key, {
value: trailers[key],
enumerable: true,
configurable: true,
writable: true
})
} else {
this.trailers[key] = trailers[key]
}
}
}
this.res?.push(null)
}
onError (err) {
onResponseError (_controller, err) {
const { res, callback, body, opaque } = this
if (callback) {
+30 -15
View File
@@ -53,39 +53,44 @@ class StreamHandler extends AsyncResource {
this.res = null
this.abort = null
this.context = null
this.controller = null
this.trailers = null
this.body = body
this.onInfo = onInfo || null
if (util.isStream(body)) {
body.on('error', (err) => {
this.onError(err)
this.onResponseError(this.controller, err)
})
}
addSignal(this, signal)
}
onConnect (abort, context) {
onRequestStart (controller, context) {
if (this.reason) {
abort(this.reason)
controller.abort(this.reason)
return
}
assert(this.callback)
this.abort = abort
this.controller = controller
this.abort = (reason) => controller.abort(reason)
this.context = context
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
onResponseStart (controller, statusCode, headers, _statusMessage) {
const { factory, opaque, context, responseHeaders } = this
const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
const rawHeaders = controller?.rawHeaders
const responseHeaderData = responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
: headers
if (statusCode < 200) {
if (this.onInfo) {
this.onInfo({ statusCode, headers })
this.onInfo({ statusCode, headers: responseHeaderData })
}
return
}
@@ -98,7 +103,7 @@ class StreamHandler extends AsyncResource {
const res = this.runInAsyncScope(factory, null, {
statusCode,
headers,
headers: responseHeaderData,
opaque,
context
})
@@ -129,7 +134,7 @@ class StreamHandler extends AsyncResource {
}
})
res.on('drain', resume)
res.on('drain', () => controller.resume())
this.res = res
@@ -137,16 +142,24 @@ class StreamHandler extends AsyncResource {
? res.writableNeedDrain
: res._writableState?.needDrain
return needDrain !== true
if (needDrain === true) {
controller.pause()
}
}
onData (chunk) {
onResponseData (controller, chunk) {
const { res } = this
return res ? res.write(chunk) : true
if (!res) {
return
}
if (res.write(chunk) === false) {
controller.pause()
}
}
onComplete (trailers) {
onResponseEnd (_controller, trailers) {
const { res } = this
removeSignal(this)
@@ -155,12 +168,14 @@ class StreamHandler extends AsyncResource {
return
}
this.trailers = util.parseHeaders(trailers)
if (trailers && typeof trailers === 'object') {
this.trailers = trailers
}
res.end()
}
onError (err) {
onResponseError (_controller, err) {
const { res, callback, opaque, body } = this
removeSignal(this)
+14 -10
View File
@@ -34,23 +34,23 @@ class UpgradeHandler extends AsyncResource {
addSignal(this, signal)
}
onConnect (abort, context) {
onRequestStart (controller, context) {
if (this.reason) {
abort(this.reason)
controller.abort(this.reason)
return
}
assert(this.callback)
this.abort = abort
this.context = null
this.abort = (reason) => controller.abort(reason)
this.context = context
}
onHeaders () {
onResponseStart () {
throw new SocketError('bad upgrade', null)
}
onUpgrade (statusCode, rawHeaders, socket) {
onRequestUpgrade (controller, statusCode, headers, socket) {
assert(socket[kHTTP2Stream] === true ? statusCode === 200 : statusCode === 101)
const { callback, opaque, context } = this
@@ -58,16 +58,21 @@ class UpgradeHandler extends AsyncResource {
removeSignal(this)
this.callback = null
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
const rawHeaders = controller?.rawHeaders
const responseHeaders = this.responseHeaders === 'raw'
? (Array.isArray(rawHeaders) ? util.parseRawHeaders(rawHeaders) : [])
: headers
this.runInAsyncScope(callback, null, null, {
headers,
headers: responseHeaders,
socket,
opaque,
context
})
}
onError (err) {
onResponseError (_controller, err) {
const { callback, opaque } = this
removeSignal(this)
@@ -97,7 +102,6 @@ function upgrade (opts, callback) {
method: opts.method || 'GET',
upgrade: opts.protocol || 'Websocket'
}
this.dispatch(upgradeOpts, upgradeHandler)
} catch (err) {
if (typeof callback !== 'function') {
+1 -1
View File
@@ -51,7 +51,7 @@ function buildConnector ({ allowH2, useH2c, maxCachedSessions, socketPath, timeo
const options = { path: socketPath, ...opts }
const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
timeout = timeout == null ? 10e3 : timeout
allowH2 = allowH2 != null ? allowH2 : false
allowH2 = allowH2 != null ? allowH2 : true
return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
let socket
if (protocol === 'https:') {
+6 -4
View File
@@ -177,10 +177,12 @@ function trackWebSocketEvents (debugLog = websocketDebuglog) {
diagnosticsChannel.subscribe('undici:websocket:open',
evt => {
const {
address: { address, port }
} = evt
debugLog('connection opened %s%s', address, port ? `:${port}` : '')
if (evt.address != null) {
const { address, port } = evt.address
debugLog('connection opened %s%s', address, port ? `:${port}` : '')
} else {
debugLog('connection opened')
}
})
diagnosticsChannel.subscribe('undici:websocket:close',
+119 -29
View File
@@ -16,6 +16,7 @@ const {
hasSafeIterator,
isBlobLike,
serializePathWithQuery,
parseHeaders,
assertRequestHandler,
getServerName,
normalizedMethodRecords,
@@ -28,6 +29,55 @@ const { headerNameLowerCasedRecord } = require('./constants')
const invalidPathRegex = /[^\u0021-\u00ff]/
const kHandler = Symbol('handler')
const kController = Symbol('controller')
const kResume = Symbol('resume')
class RequestController {
#paused = false
#reason = null
#aborted = false
#abort
[kResume] = null
rawHeaders = null
rawTrailers = null
constructor (abort) {
this.#abort = abort
}
pause () {
this.#paused = true
}
resume () {
if (this.#paused) {
this.#paused = false
this[kResume]?.()
}
}
abort (reason) {
if (!this.#aborted) {
this.#aborted = true
this.#reason = reason
this.#abort(reason)
}
}
get aborted () {
return this.#aborted
}
get reason () {
return this.#reason
}
get paused () {
return this.#paused
}
}
class Request {
constructor (origin, {
@@ -241,23 +291,26 @@ class Request {
}
}
onConnect (abort) {
onRequestStart (abort, context) {
assert(!this.aborted)
assert(!this.completed)
this[kController] = new RequestController(abort)
if (this.error) {
abort(this.error)
} else {
this.abort = abort
return this[kHandler].onConnect(abort)
this[kController].abort(this.error)
return
}
this.abort = abort
return this[kHandler].onRequestStart(this[kController], context)
}
onResponseStarted () {
return this[kHandler].onResponseStarted?.()
}
onHeaders (statusCode, headers, resume, statusText) {
onResponseStart (statusCode, headers, resume, statusText) {
assert(!this.aborted)
assert(!this.completed)
@@ -265,36 +318,56 @@ class Request {
channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
}
try {
return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
} catch (err) {
this.abort(err)
const controller = this[kController]
if (controller) {
controller[kResume] = resume
controller.rawHeaders = headers
}
}
onData (chunk) {
assert(!this.aborted)
assert(!this.completed)
const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers
if (channels.bodyChunkReceived.hasSubscribers) {
channels.bodyChunkReceived.publish({ request: this, chunk })
}
try {
return this[kHandler].onData(chunk)
this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText)
return !controller?.paused
} catch (err) {
this.abort(err)
return false
}
}
onUpgrade (statusCode, headers, socket) {
onResponseData (chunk) {
assert(!this.aborted)
assert(!this.completed)
return this[kHandler].onUpgrade(statusCode, headers, socket)
if (channels.bodyChunkReceived.hasSubscribers) {
channels.bodyChunkReceived.publish({ request: this, chunk })
}
const controller = this[kController]
try {
this[kHandler].onResponseData?.(controller, chunk)
return !controller?.paused
} catch (err) {
this.abort(err)
return false
}
}
onComplete (trailers) {
onRequestUpgrade (statusCode, headers, socket) {
assert(!this.aborted)
assert(!this.completed)
const controller = this[kController]
if (controller) {
controller.rawHeaders = headers
}
const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers
return this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket)
}
onResponseEnd (trailers) {
this.onFinally()
assert(!this.aborted)
@@ -305,15 +378,22 @@ class Request {
channels.trailers.publish({ request: this, trailers })
}
const controller = this[kController]
if (controller) {
controller.rawTrailers = trailers
}
const parsedTrailers = Array.isArray(trailers) ? parseHeaders(trailers) : trailers
try {
return this[kHandler].onComplete(trailers)
return this[kHandler].onResponseEnd?.(controller, parsedTrailers)
} catch (err) {
// TODO (fix): This might be a bad idea?
this.onError(err)
this.onResponseError(err)
}
}
onError (error) {
onResponseError (error) {
this.onFinally()
if (channels.error.hasSubscribers) {
@@ -325,7 +405,9 @@ class Request {
}
this.aborted = true
return this[kHandler].onError(error)
const controller = this[kController]
return this[kHandler].onResponseError?.(controller, error)
}
onFinally () {
@@ -412,13 +494,21 @@ function processHeader (request, key, val) {
} else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') {
throw new InvalidArgumentError(`invalid ${headerName} header`)
} else if (headerName === 'connection') {
const value = typeof val === 'string' ? val.toLowerCase() : null
if (value !== 'close' && value !== 'keep-alive') {
// Per RFC 7230 Section 6.1, Connection header can contain
// a comma-separated list of connection option tokens (header names)
const value = typeof val === 'string' ? val : null
if (value === null) {
throw new InvalidArgumentError('invalid connection header')
}
if (value === 'close') {
request.reset = true
for (const token of value.toLowerCase().split(',')) {
const trimmed = token.trim()
if (!isValidHTTPToken(trimmed)) {
throw new InvalidArgumentError('invalid connection header')
}
if (trimmed === 'close') {
request.reset = true
}
}
} else if (headerName === 'expect') {
throw new NotSupportedError('expect header not supported')
+70 -44
View File
@@ -85,23 +85,9 @@ function isStream (obj) {
/**
* @param {*} object
* @returns {object is Blob}
* based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
*/
function isBlobLike (object) {
if (object === null) {
return false
} else if (object instanceof Blob) {
return true
} else if (typeof object !== 'object') {
return false
} else {
const sTag = object[Symbol.toStringTag]
return (sTag === 'Blob' || sTag === 'File') && (
('stream' in object && typeof object.stream === 'function') ||
('arrayBuffer' in object && typeof object.arrayBuffer === 'function')
)
}
return object instanceof Blob
}
/**
@@ -440,19 +426,39 @@ function parseHeaders (headers, obj) {
const key = headerNameToString(headers[i])
let val = obj[key]
if (val) {
if (typeof val === 'string') {
val = [val]
obj[key] = val
}
val.push(headers[i + 1].toString('latin1'))
} else {
const headersValue = headers[i + 1]
if (typeof headersValue === 'string') {
obj[key] = headersValue
if (val !== undefined) {
if (!Object.hasOwn(obj, key)) {
const headersValue = typeof headers[i + 1] === 'string'
? headers[i + 1]
: Array.isArray(headers[i + 1])
? headers[i + 1].map(x => x.toString('latin1'))
: headers[i + 1].toString('latin1')
if (key === '__proto__') {
Object.defineProperty(obj, key, {
value: headersValue,
enumerable: true,
configurable: true,
writable: true
})
} else {
obj[key] = headersValue
}
} else {
obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('latin1')) : headersValue.toString('latin1')
if (typeof val === 'string') {
val = [val]
obj[key] = val
}
val.push(headers[i + 1].toString('latin1'))
}
} else {
const headersValue = typeof headers[i + 1] === 'string'
? headers[i + 1]
: Array.isArray(headers[i + 1])
? headers[i + 1].map(x => x.toString('latin1'))
: headers[i + 1].toString('latin1')
obj[key] = headersValue
}
}
@@ -487,6 +493,26 @@ function parseRawHeaders (headers) {
return ret
}
/**
* @param {Record<string, string | string[]>} headers
* @returns {Buffer[]}
*/
function toRawHeaders (headers) {
const rawHeaders = []
for (const [name, value] of Object.entries(headers)) {
if (Array.isArray(value)) {
for (const entry of value) {
rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${entry}`, 'latin1'))
}
} else {
rawHeaders.push(Buffer.from(name, 'latin1'), Buffer.from(`${value}`, 'latin1'))
}
}
return rawHeaders
}
/**
* @param {string[]} headers
* @param {Buffer[]} headers
@@ -520,38 +546,37 @@ function assertRequestHandler (handler, method, upgrade) {
throw new InvalidArgumentError('handler must be an object')
}
if (typeof handler.onRequestStart === 'function') {
// TODO (fix): More checks...
return
if (typeof handler.onRequestStart !== 'function') {
throw new InvalidArgumentError('invalid onRequestStart method')
}
if (typeof handler.onConnect !== 'function') {
throw new InvalidArgumentError('invalid onConnect method')
}
if (typeof handler.onError !== 'function') {
throw new InvalidArgumentError('invalid onError method')
if (typeof handler.onResponseError !== 'function') {
throw new InvalidArgumentError('invalid onResponseError method')
}
if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
throw new InvalidArgumentError('invalid onBodySent method')
}
if (typeof handler.onRequestSent !== 'function' && handler.onRequestSent !== undefined) {
throw new InvalidArgumentError('invalid onRequestSent method')
}
if (upgrade || method === 'CONNECT') {
if (typeof handler.onUpgrade !== 'function') {
throw new InvalidArgumentError('invalid onUpgrade method')
if (typeof handler.onRequestUpgrade !== 'function') {
throw new InvalidArgumentError('invalid onRequestUpgrade method')
}
} else {
if (typeof handler.onHeaders !== 'function') {
throw new InvalidArgumentError('invalid onHeaders method')
if (typeof handler.onResponseStart !== 'function') {
throw new InvalidArgumentError('invalid onResponseStart method')
}
if (typeof handler.onData !== 'function') {
throw new InvalidArgumentError('invalid onData method')
if (typeof handler.onResponseData !== 'function') {
throw new InvalidArgumentError('invalid onResponseData method')
}
if (typeof handler.onComplete !== 'function') {
throw new InvalidArgumentError('invalid onComplete method')
if (typeof handler.onResponseEnd !== 'function') {
throw new InvalidArgumentError('invalid onResponseEnd method')
}
}
}
@@ -792,7 +817,7 @@ function removeAllListeners (obj) {
*/
function errorRequest (client, request, err) {
try {
request.onError(err)
request.onResponseError(err)
assert(request.aborted)
} catch (err) {
client.emit('error', err)
@@ -941,6 +966,7 @@ module.exports = {
removeAllListeners,
errorRequest,
parseRawHeaders,
toRawHeaders,
encodeRawHeaders,
parseHeaders,
parseKeepAliveTimeout,
+23 -7
View File
@@ -72,14 +72,17 @@ class Agent extends DispatcherBase {
}
[kDispatch] (opts, handler) {
let key
let origin
if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
key = String(opts.origin)
origin = String(opts.origin)
} else {
throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
}
if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(key)) {
const allowH2 = opts.allowH2 ?? this[kOptions].allowH2
const key = allowH2 === false ? `${origin}#http1-only` : origin
if (this[kOrigins].size >= this[kOptions].maxOrigins && !this[kOrigins].has(origin)) {
throw new MaxOriginsReachedError()
}
@@ -96,10 +99,23 @@ class Agent extends DispatcherBase {
result.dispatcher.close()
}
}
this[kOrigins].delete(key)
let hasOrigin = false
for (const entry of this[kClients].values()) {
if (entry.origin === origin) {
hasOrigin = true
break
}
}
if (!hasOrigin) {
this[kOrigins].delete(origin)
}
}
}
dispatcher = this[kFactory](opts.origin, this[kOptions])
dispatcher = this[kFactory](opts.origin, allowH2 === false
? { ...this[kOptions], allowH2: false }
: this[kOptions])
.on('drain', this[kOnDrain])
.on('connect', (origin, targets) => {
const result = this[kClients].get(key)
@@ -117,8 +133,8 @@ class Agent extends DispatcherBase {
this[kOnConnectionError](origin, targets, err)
})
this[kClients].set(key, { count: 0, dispatcher })
this[kOrigins].add(key)
this[kClients].set(key, { count: 0, dispatcher, origin })
this[kOrigins].add(origin)
}
return dispatcher.dispatch(opts, handler)
+5 -5
View File
@@ -507,7 +507,7 @@ class Parser {
client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
try {
request.onUpgrade(statusCode, headers, socket)
request.onRequestUpgrade(statusCode, headers, socket)
} catch (err) {
util.destroy(socket, err)
}
@@ -605,7 +605,7 @@ class Parser {
socket[kReset] = true
}
const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
const pause = request.onResponseStart(statusCode, headers, this.resume, statusText) === false
if (request.aborted) {
return -1
@@ -657,7 +657,7 @@ class Parser {
this.bytesRead += buf.length
if (request.onData(buf) === false) {
if (request.onResponseData(buf) === false) {
return constants.ERROR.PAUSED
}
@@ -703,7 +703,7 @@ class Parser {
return -1
}
request.onComplete(headers)
request.onResponseEnd(headers)
client[kQueue][client[kRunningIdx]++] = null
@@ -1078,7 +1078,7 @@ function writeH1 (client, request) {
}
try {
request.onConnect(abort)
request.onRequestStart(abort, null)
} catch (err) {
util.errorRequest(client, request, err)
}
+7 -8
View File
@@ -494,7 +494,7 @@ function writeH2 (client, request) {
try {
// We are already connected, streams are pending.
// We can call on connect, and wait for abort
request.onConnect(abort)
request.onRequestStart(abort, null)
} catch (err) {
util.errorRequest(client, request, err)
}
@@ -534,7 +534,7 @@ function writeH2 (client, request) {
stream.once('response', (headers, _flags) => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream)
request.onRequestUpgrade(statusCode, parseH2Headers(realHeaders), stream)
++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
@@ -568,7 +568,7 @@ function writeH2 (client, request) {
stream.on('response', headers => {
const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
request.onUpgrade(statusCode, parseH2Headers(realHeaders), stream)
request.onRequestUpgrade(statusCode, parseH2Headers(realHeaders), stream)
++session[kOpenStreams]
client[kQueue][client[kRunningIdx]++] = null
})
@@ -697,7 +697,7 @@ function writeH2 (client, request) {
return
}
if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
if (request.onResponseStart(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {
stream.pause()
}
@@ -706,7 +706,7 @@ function writeH2 (client, request) {
return
}
if (request.onData(chunk) === false) {
if (request.onResponseData(chunk) === false) {
stream.pause()
}
})
@@ -717,7 +717,7 @@ function writeH2 (client, request) {
// If we received a response, this is a normal completion
if (responseReceived) {
if (!request.aborted && !request.completed) {
request.onComplete({})
request.onResponseEnd({})
}
client[kQueue][client[kRunningIdx]++] = null
@@ -771,8 +771,7 @@ function writeH2 (client, request) {
return
}
stream.removeAllListeners('data')
request.onComplete(trailers)
request.onResponseEnd(trailers)
})
return true
+68 -59
View File
@@ -235,9 +235,13 @@ class Client extends DispatcherBase {
...(typeof autoSelectFamily === 'boolean' ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
...connect
})
} else if (socketPath != null) {
} else {
const customConnect = connect
connect = (opts, callback) => customConnect({ ...opts, socketPath }, callback)
connect = (opts, callback) => customConnect({
...opts,
...(socketPath != null ? { socketPath } : null),
...(allowH2 != null ? { allowH2 } : null)
}, callback)
}
this[kUrl] = util.parseOrigin(url)
@@ -452,65 +456,70 @@ function connect (client) {
})
}
client[kConnector]({
host,
hostname,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
}, (err, socket) => {
if (err) {
handleConnectError(client, err, { host, hostname, protocol, port })
try {
client[kConnector]({
host,
hostname,
protocol,
port,
servername: client[kServerName],
localAddress: client[kLocalAddress]
}, (err, socket) => {
if (err) {
handleConnectError(client, err, { host, hostname, protocol, port })
client[kResume]()
return
}
if (client.destroyed) {
util.destroy(socket.on('error', noop), new ClientDestroyedError())
client[kResume]()
return
}
assert(socket)
try {
client[kHTTPContext] = socket.alpnProtocol === 'h2'
? connectH2(client, socket)
: connectH1(client, socket)
} catch (err) {
socket.destroy().on('error', noop)
handleConnectError(client, err, { host, hostname, protocol, port })
client[kResume]()
return
}
client[kConnecting] = false
socket[kCounter] = 0
socket[kMaxRequests] = client[kMaxRequests]
socket[kClient] = client
socket[kError] = null
if (channels.connected.hasSubscribers) {
channels.connected.publish({
connectParams: {
host,
hostname,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
socket
})
}
client.emit('connect', client[kUrl], [client])
client[kResume]()
return
}
if (client.destroyed) {
util.destroy(socket.on('error', noop), new ClientDestroyedError())
client[kResume]()
return
}
assert(socket)
try {
client[kHTTPContext] = socket.alpnProtocol === 'h2'
? connectH2(client, socket)
: connectH1(client, socket)
} catch (err) {
socket.destroy().on('error', noop)
handleConnectError(client, err, { host, hostname, protocol, port })
client[kResume]()
return
}
client[kConnecting] = false
socket[kCounter] = 0
socket[kMaxRequests] = client[kMaxRequests]
socket[kClient] = client
socket[kError] = null
if (channels.connected.hasSubscribers) {
channels.connected.publish({
connectParams: {
host,
hostname,
protocol,
port,
version: client[kHTTPContext]?.version,
servername: client[kServerName],
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
socket
})
}
client.emit('connect', client[kUrl], [client])
})
} catch (err) {
handleConnectError(client, err, { host, hostname, protocol, port })
client[kResume]()
})
}
}
function handleConnectError (client, err, { host, hostname, protocol, port }) {
+2 -5
View File
@@ -1,7 +1,6 @@
'use strict'
const Dispatcher = require('./dispatcher')
const UnwrapHandler = require('../handler/unwrap-handler')
const {
ClientDestroyedError,
ClientClosedError,
@@ -134,8 +133,6 @@ class DispatcherBase extends Dispatcher {
throw new InvalidArgumentError('handler must be an object')
}
handler = UnwrapHandler.unwrap(handler)
try {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('opts must be an object.')
@@ -151,11 +148,11 @@ class DispatcherBase extends Dispatcher {
return this[kDispatch](opts, handler)
} catch (err) {
if (typeof handler.onError !== 'function') {
if (typeof handler.onResponseError !== 'function') {
throw err
}
handler.onError(err)
handler.onResponseError(null, err)
return false
}
-4
View File
@@ -1,8 +1,5 @@
'use strict'
const EventEmitter = require('node:events')
const WrapHandler = require('../handler/wrap-handler')
const wrapInterceptor = (dispatch) => (opts, handler) => dispatch(opts, WrapHandler.wrap(handler))
class Dispatcher extends EventEmitter {
dispatch () {
@@ -32,7 +29,6 @@ class Dispatcher extends EventEmitter {
}
dispatch = interceptor(dispatch)
dispatch = wrapInterceptor(dispatch)
if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) {
throw new TypeError('invalid interceptor')
+101
View File
@@ -0,0 +1,101 @@
'use strict'
const Dispatcher = require('./dispatcher')
const { InvalidArgumentError } = require('../core/errors')
const { toRawHeaders } = require('../core/util')
class LegacyHandlerWrapper {
#handler
constructor (handler) {
this.#handler = handler
}
onRequestStart (controller, context) {
this.#handler.onConnect?.((reason) => controller.abort(reason), context)
}
onRequestUpgrade (controller, statusCode, headers, socket) {
const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {})
this.#handler.onUpgrade?.(statusCode, rawHeaders, socket)
}
onResponseStart (controller, statusCode, headers, statusMessage) {
const rawHeaders = controller?.rawHeaders ?? toRawHeaders(headers ?? {})
if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
controller.pause()
}
}
onResponseData (controller, chunk) {
if (this.#handler.onData?.(chunk) === false) {
controller.pause()
}
}
onResponseEnd (controller, trailers) {
const rawTrailers = controller?.rawTrailers ?? toRawHeaders(trailers ?? {})
this.#handler.onComplete?.(rawTrailers)
}
onResponseError (_controller, err) {
if (!this.#handler.onError) {
throw err
}
this.#handler.onError(err)
}
onBodySent (chunk) {
this.#handler.onBodySent?.(chunk)
}
onRequestSent () {
this.#handler.onRequestSent?.()
}
onResponseStarted () {
this.#handler.onResponseStarted?.()
}
}
class Dispatcher1Wrapper extends Dispatcher {
#dispatcher
constructor (dispatcher) {
super()
if (!dispatcher || typeof dispatcher.dispatch !== 'function') {
throw new InvalidArgumentError('Argument dispatcher must implement dispatch')
}
this.#dispatcher = dispatcher
}
static wrapHandler (handler) {
if (!handler || typeof handler !== 'object') {
throw new InvalidArgumentError('handler must be an object')
}
if (typeof handler.onRequestStart === 'function') {
return handler
}
return new LegacyHandlerWrapper(handler)
}
dispatch (opts, handler) {
return this.#dispatcher.dispatch(opts, Dispatcher1Wrapper.wrapHandler(handler))
}
close (...args) {
return this.#dispatcher.close(...args)
}
destroy (...args) {
return this.#dispatcher.destroy(...args)
}
}
module.exports = Dispatcher1Wrapper
+1 -1
View File
@@ -143,7 +143,7 @@ class PoolBase extends DispatcherBase {
if (!item) {
break
}
item.handler.onError(err)
item.handler.onResponseError(null, err)
}
const destroyAll = new Array(this[kClients].length)
+12 -6
View File
@@ -16,6 +16,7 @@ const kProxyHeaders = Symbol('proxy headers')
const kRequestTls = Symbol('request tls settings')
const kProxyTls = Symbol('proxy tls settings')
const kConnectEndpoint = Symbol('connect endpoint function')
const kConnectEndpointHTTP1 = Symbol('connect endpoint function (http/1.1 only)')
const kTunnelProxy = Symbol('tunnel proxy')
function defaultProtocolPort (protocol) {
@@ -54,15 +55,15 @@ class Http1ProxyWrapper extends DispatcherBase {
}
[kDispatch] (opts, handler) {
const onHeaders = handler.onHeaders
handler.onHeaders = function (statusCode, data, resume) {
const onResponseStart = handler.onResponseStart
handler.onResponseStart = function (controller, statusCode, data, statusMessage) {
if (statusCode === 407) {
if (typeof handler.onError === 'function') {
handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)'))
if (typeof handler.onResponseError === 'function') {
handler.onResponseError(controller, new InvalidArgumentError('Proxy Authentication Required (407)'))
}
return
}
if (onHeaders) onHeaders.call(this, statusCode, data, resume)
if (onResponseStart) onResponseStart.call(this, controller, statusCode, data, statusMessage)
}
// Rewrite request as an HTTP1 Proxy request, without tunneling.
@@ -129,6 +130,7 @@ class ProxyAgent extends DispatcherBase {
const connect = buildConnector({ ...opts.proxyTls })
this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
this[kConnectEndpointHTTP1] = buildConnector({ ...opts.requestTls, allowH2: false })
const agentFactory = opts.factory || defaultAgentFactory
const factory = (origin, options) => {
@@ -216,7 +218,11 @@ class ProxyAgent extends DispatcherBase {
} else {
servername = opts.servername
}
this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
const connectEndpoint = opts.allowH2 === false
? this[kConnectEndpointHTTP1]
: this[kConnectEndpoint]
connectEndpoint({ ...opts, servername, httpSocket: socket }, callback)
} catch (err) {
if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
// Throw a custom error to avoid loop in client.js#connect
+13 -1
View File
@@ -2,9 +2,11 @@
// We include a version number for the Dispatcher API. In case of breaking changes,
// this version number must be increased to avoid conflicts.
const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
const globalDispatcher = Symbol.for('undici.globalDispatcher.2')
const legacyGlobalDispatcher = Symbol.for('undici.globalDispatcher.1')
const { InvalidArgumentError } = require('./core/errors')
const Agent = require('./dispatcher/agent')
const Dispatcher1Wrapper = require('./dispatcher/dispatcher1-wrapper')
if (getGlobalDispatcher() === undefined) {
setGlobalDispatcher(new Agent())
@@ -14,12 +16,22 @@ function setGlobalDispatcher (agent) {
if (!agent || typeof agent.dispatch !== 'function') {
throw new InvalidArgumentError('Argument agent must implement Agent')
}
Object.defineProperty(globalThis, globalDispatcher, {
value: agent,
writable: true,
enumerable: false,
configurable: false
})
const legacyAgent = agent instanceof Dispatcher1Wrapper ? agent : new Dispatcher1Wrapper(agent)
Object.defineProperty(globalThis, legacyGlobalDispatcher, {
value: legacyAgent,
writable: true,
enumerable: false,
configurable: false
})
}
function getGlobalDispatcher () {
+35 -10
View File
@@ -135,7 +135,7 @@ class CacheHandler {
}
const cacheControlDirectives = cacheControlHeader ? parseCacheControlHeader(cacheControlHeader) : {}
if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives)) {
if (!canCacheResponse(this.#cacheType, statusCode, resHeaders, cacheControlDirectives, this.#cacheKey.headers)) {
return downstreamOnHeaders()
}
@@ -173,7 +173,8 @@ class CacheHandler {
}
}
const deleteAt = determineDeleteAt(baseTime, cacheControlDirectives, absoluteStaleAt)
const cachedAt = resAge ? now - resAge : now
const deleteAt = determineDeleteAt(baseTime, cachedAt, cacheControlDirectives, absoluteStaleAt)
const strippedHeaders = stripNecessaryHeaders(resHeaders, cacheControlDirectives)
/**
@@ -185,7 +186,7 @@ class CacheHandler {
headers: strippedHeaders,
vary: varyDirectives,
cacheControlDirectives,
cachedAt: resAge ? now - resAge : now,
cachedAt,
staleAt: absoluteStaleAt,
deleteAt
}
@@ -340,8 +341,9 @@ class CacheHandler {
* @param {number} statusCode
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} resHeaders
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {import('../../types/header.d.ts').IncomingHttpHeaders} [reqHeaders]
*/
function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirectives) {
function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirectives, reqHeaders) {
// Status code must be final and understood.
if (statusCode < 200 || NOT_UNDERSTOOD_STATUS_CODES.includes(statusCode)) {
return false
@@ -372,8 +374,16 @@ function canCacheResponse (cacheType, statusCode, resHeaders, cacheControlDirect
}
// https://www.rfc-editor.org/rfc/rfc9111.html#name-storing-responses-to-authen
if (resHeaders.authorization) {
if (!cacheControlDirectives.public || typeof resHeaders.authorization !== 'string') {
if (reqHeaders?.authorization) {
if (
!cacheControlDirectives.public &&
!cacheControlDirectives['s-maxage'] &&
!cacheControlDirectives['must-revalidate']
) {
return false
}
if (typeof reqHeaders.authorization !== 'string') {
return false
}
@@ -476,11 +486,12 @@ function determineStaleAt (cacheType, now, age, resHeaders, responseDate, cacheC
}
/**
* @param {number} now
* @param {number} baseTime
* @param {number} cachedAt
* @param {import('../../types/cache-interceptor.d.ts').default.CacheControlDirectives} cacheControlDirectives
* @param {number} staleAt
*/
function determineDeleteAt (now, cacheControlDirectives, staleAt) {
function determineDeleteAt (baseTime, cachedAt, cacheControlDirectives, staleAt) {
let staleWhileRevalidate = -Infinity
let staleIfError = -Infinity
let immutable = -Infinity
@@ -493,8 +504,22 @@ function determineDeleteAt (now, cacheControlDirectives, staleAt) {
staleIfError = staleAt + (cacheControlDirectives['stale-if-error'] * 1000)
}
if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
immutable = now + 31536000000
if (cacheControlDirectives.immutable && staleWhileRevalidate === -Infinity && staleIfError === -Infinity) {
immutable = cachedAt + 31536000000
}
// When no stale directives or immutable flag, add a revalidation buffer
// equal to the freshness lifetime so the entry survives past staleAt long
// enough to be revalidated instead of silently disappearing.
//
// Response Date headers only have second precision, so baseTime can trail the
// actual cache insertion time by up to ~1s. Pad the buffer by that bounded
// skew so short-lived entries do not disappear exactly when they should be
// revalidated.
if (staleWhileRevalidate === -Infinity && staleIfError === -Infinity && immutable === -Infinity) {
const freshnessLifetime = staleAt - baseTime
const datePrecisionPadding = Math.min(Math.max(cachedAt - baseTime, 0), 1000)
return staleAt + freshnessLifetime + datePrecisionPadding
}
return Math.max(staleAt, staleWhileRevalidate, staleIfError, immutable)
+1 -2
View File
@@ -1,7 +1,6 @@
'use strict'
const assert = require('node:assert')
const WrapHandler = require('./wrap-handler')
/**
* @deprecated
@@ -16,7 +15,7 @@ module.exports = class DecoratorHandler {
if (typeof handler !== 'object' || handler === null) {
throw new TypeError('handler must be an object')
}
this.#handler = WrapHandler.wrap(handler)
this.#handler = handler
}
onRequestStart (...args) {
+1 -2
View File
@@ -3,7 +3,6 @@ const assert = require('node:assert')
const { kRetryHandlerDefaultRetry } = require('../core/symbols')
const { RequestRetryError } = require('../core/errors')
const WrapHandler = require('./wrap-handler')
const {
isDisturbed,
parseRangeHeader,
@@ -35,7 +34,7 @@ class RetryHandler {
this.error = null
this.dispatch = dispatch
this.handler = WrapHandler.wrap(handler)
this.handler = handler
this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) }
this.retryOpts = {
throwOnError: throwOnError ?? true,
-100
View File
@@ -1,100 +0,0 @@
'use strict'
const { parseHeaders } = require('../core/util')
const { InvalidArgumentError } = require('../core/errors')
const kResume = Symbol('resume')
class UnwrapController {
#paused = false
#reason = null
#aborted = false
#abort
[kResume] = null
constructor (abort) {
this.#abort = abort
}
pause () {
this.#paused = true
}
resume () {
if (this.#paused) {
this.#paused = false
this[kResume]?.()
}
}
abort (reason) {
if (!this.#aborted) {
this.#aborted = true
this.#reason = reason
this.#abort(reason)
}
}
get aborted () {
return this.#aborted
}
get reason () {
return this.#reason
}
get paused () {
return this.#paused
}
}
module.exports = class UnwrapHandler {
#handler
#controller
constructor (handler) {
this.#handler = handler
}
static unwrap (handler) {
// TODO (fix): More checks...
return !handler.onRequestStart ? handler : new UnwrapHandler(handler)
}
onConnect (abort, context) {
this.#controller = new UnwrapController(abort)
this.#handler.onRequestStart?.(this.#controller, context)
}
onResponseStarted () {
return this.#handler.onResponseStarted?.()
}
onUpgrade (statusCode, rawHeaders, socket) {
this.#handler.onRequestUpgrade?.(this.#controller, statusCode, parseHeaders(rawHeaders), socket)
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
this.#controller[kResume] = resume
this.#handler.onResponseStart?.(this.#controller, statusCode, parseHeaders(rawHeaders), statusMessage)
return !this.#controller.paused
}
onData (data) {
this.#handler.onResponseData?.(this.#controller, data)
return !this.#controller.paused
}
onComplete (rawTrailers) {
this.#handler.onResponseEnd?.(this.#controller, parseHeaders(rawTrailers))
}
onError (err) {
if (!this.#handler.onResponseError) {
throw new InvalidArgumentError('invalid onError method')
}
this.#handler.onResponseError?.(this.#controller, err)
}
}
-105
View File
@@ -1,105 +0,0 @@
'use strict'
const { InvalidArgumentError } = require('../core/errors')
module.exports = class WrapHandler {
#handler
constructor (handler) {
this.#handler = handler
}
static wrap (handler) {
// TODO (fix): More checks...
return handler.onRequestStart ? handler : new WrapHandler(handler)
}
// Unwrap Interface
onConnect (abort, context) {
return this.#handler.onConnect?.(abort, context)
}
onResponseStarted () {
return this.#handler.onResponseStarted?.()
}
onHeaders (statusCode, rawHeaders, resume, statusMessage) {
return this.#handler.onHeaders?.(statusCode, rawHeaders, resume, statusMessage)
}
onUpgrade (statusCode, rawHeaders, socket) {
return this.#handler.onUpgrade?.(statusCode, rawHeaders, socket)
}
onData (data) {
return this.#handler.onData?.(data)
}
onComplete (trailers) {
return this.#handler.onComplete?.(trailers)
}
onError (err) {
if (!this.#handler.onError) {
throw err
}
return this.#handler.onError?.(err)
}
// Wrap Interface
onRequestStart (controller, context) {
this.#handler.onConnect?.((reason) => controller.abort(reason), context)
}
onRequestUpgrade (controller, statusCode, headers, socket) {
const rawHeaders = []
for (const [key, val] of Object.entries(headers)) {
rawHeaders.push(Buffer.from(key, 'latin1'), toRawHeaderValue(val))
}
this.#handler.onUpgrade?.(statusCode, rawHeaders, socket)
}
onResponseStart (controller, statusCode, headers, statusMessage) {
const rawHeaders = []
for (const [key, val] of Object.entries(headers)) {
rawHeaders.push(Buffer.from(key, 'latin1'), toRawHeaderValue(val))
}
if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
controller.pause()
}
}
onResponseData (controller, data) {
if (this.#handler.onData?.(data) === false) {
controller.pause()
}
}
onResponseEnd (controller, trailers) {
const rawTrailers = []
for (const [key, val] of Object.entries(trailers)) {
rawTrailers.push(Buffer.from(key, 'latin1'), toRawHeaderValue(val))
}
this.#handler.onComplete?.(rawTrailers)
}
onResponseError (controller, err) {
if (!this.#handler.onError) {
throw new InvalidArgumentError('invalid onError method')
}
this.#handler.onError?.(err)
}
}
function toRawHeaderValue (value) {
return Array.isArray(value)
? value.map((item) => Buffer.from(item, 'latin1'))
: Buffer.from(value, 'latin1')
}
+30 -17
View File
@@ -124,30 +124,39 @@ function handleUncachedResponse (
) {
if (reqCacheControl?.['only-if-cached']) {
let aborted = false
const controller = {
paused: false,
rawHeaders: [],
rawTrailers: [],
pause () {
this.paused = true
},
resume () {
this.paused = false
},
abort: (reason) => {
aborted = true
handler.onResponseError?.(controller, reason ?? new AbortError())
}
}
try {
if (typeof handler.onConnect === 'function') {
handler.onConnect(() => {
aborted = true
})
handler.onRequestStart?.(controller, null)
if (aborted) {
return
}
if (aborted) {
return
}
if (typeof handler.onHeaders === 'function') {
handler.onHeaders(504, [], nop, 'Gateway Timeout')
if (aborted) {
return
}
handler.onResponseStart?.(controller, 504, {}, 'Gateway Timeout')
if (aborted) {
return
}
if (typeof handler.onComplete === 'function') {
handler.onComplete([])
}
handler.onResponseEnd?.(controller, {})
} catch (err) {
if (typeof handler.onError === 'function') {
handler.onError(err)
if (typeof handler.onResponseError === 'function') {
handler.onResponseError(controller, err)
}
}
@@ -175,6 +184,8 @@ function sendCachedValue (handler, opts, result, age, context, isStale) {
assert(!stream.readableDidRead, 'stream should not be readableDidRead')
const controller = {
rawHeaders: [],
rawTrailers: [],
resume () {
stream.resume()
},
@@ -227,6 +238,8 @@ function sendCachedValue (handler, opts, result, age, context, isStale) {
headers.warning = '110 - "response is stale"'
}
controller.rawHeaders = util.toRawHeaders(headers)
handler.onResponseStart?.(controller, result.statusCode, headers, result.statusMessage)
if (opts.method === 'HEAD') {
+27
View File
@@ -181,6 +181,33 @@ class DecompressHandler extends DecoratorHandler {
// Remove compression headers since we're decompressing
const { 'content-encoding': _, 'content-length': __, ...newHeaders } = headers
if (controller?.rawHeaders) {
const rawHeaders = controller.rawHeaders
if (Array.isArray(rawHeaders)) {
const filteredHeaders = []
for (let i = 0; i < rawHeaders.length; i += 2) {
const headerName = rawHeaders[i]
const name = Buffer.isBuffer(headerName) ? headerName.toString('latin1') : `${headerName}`
const lowerName = name.toLowerCase()
if (lowerName === 'content-encoding' || lowerName === 'content-length') {
continue
}
filteredHeaders.push(rawHeaders[i], rawHeaders[i + 1])
}
controller.rawHeaders = filteredHeaders
} else if (typeof rawHeaders === 'object') {
for (const name of Object.keys(rawHeaders)) {
const lowerName = name.toLowerCase()
if (lowerName === 'content-encoding' || lowerName === 'content-length') {
delete rawHeaders[name]
}
}
}
}
if (this.#decompressors.length === 1) {
this.#setupSingleDecompressor(controller)
} else {
+1 -1
View File
@@ -1,5 +1,5 @@
> undici@7.24.4 build:wasm
> undici@8.0.2 build:wasm
> node build/wasm.js --docker
> docker run --rm --platform=linux/x86_64 --user 1001:1001 --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/lib/llhttp,target=/home/node/build/lib/llhttp --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/build,target=/home/node/build/build --mount type=bind,source=/home/runner/work/node/node/deps/undici/src/deps,target=/home/node/build/deps -t ghcr.io/nodejs/wasm-builder@sha256:975f391d907e42a75b8c72eb77c782181e941608687d4d8694c3e9df415a0970 node build/wasm.js
+2 -1
View File
@@ -27,5 +27,6 @@ module.exports = {
kMockAgentAddCallHistoryLog: Symbol('mock agent add call history log'),
kMockAgentIsCallHistoryEnabled: Symbol('mock agent is call history enabled'),
kMockAgentAcceptsNonStandardSearchParameters: Symbol('mock agent accepts non standard search parameters'),
kMockCallHistoryAddLog: Symbol('mock call history add log')
kMockCallHistoryAddLog: Symbol('mock call history add log'),
kTotalDispatchCount: Symbol('total dispatch count')
}
+43 -24
View File
@@ -6,9 +6,10 @@ const {
kMockAgent,
kOriginalDispatch,
kOrigin,
kGetNetConnect
kGetNetConnect,
kTotalDispatchCount
} = require('./mock-symbols')
const { serializePathWithQuery } = require('../core/util')
const { serializePathWithQuery, parseHeaders } = require('../core/util')
const { STATUS_CODES } = require('node:http')
const {
types: {
@@ -206,6 +207,8 @@ function addMockDispatch (mockDispatches, key, data, opts) {
const replyData = typeof data === 'function' ? { callback: data } : { ...data }
const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
mockDispatches.push(newMockDispatch)
// Track total number of intercepts ever registered for better error messages
mockDispatches[kTotalDispatchCount] = (mockDispatches[kTotalDispatchCount] || 0) + 1
return newMockDispatch
}
@@ -308,7 +311,7 @@ function mockDispatch (opts, handler) {
// If specified, trigger dispatch error
if (error !== null) {
deleteMockDispatch(this[kDispatches], key)
handler.onError(error)
handler.onResponseError(null, error)
return true
}
@@ -316,24 +319,35 @@ function mockDispatch (opts, handler) {
let aborted = false
let timer = null
function abort (err) {
if (aborted) {
return
}
aborted = true
// Create the controller early so abort can use it
const controller = {
paused: false,
rawHeaders: null,
rawTrailers: null,
pause () {
this.paused = true
},
resume () {
this.paused = false
},
abort: (reason) => {
if (aborted) {
return
}
aborted = true
// Clear the pending delayed response if any
if (timer !== null) {
clearTimeout(timer)
timer = null
}
// Clear the pending delayed response if any
if (timer !== null) {
clearTimeout(timer)
timer = null
}
// Notify the handler of the abort
handler.onError(err)
handler.onResponseError?.(controller, reason)
}
}
// Call onConnect to allow the handler to register the abort callback
handler.onConnect?.(abort, null)
// Call onRequestStart to allow the handler to receive the controller
handler.onRequestStart?.(controller, null)
// Handle the request with a delay if necessary
if (typeof delay === 'number' && delay > 0) {
@@ -378,14 +392,16 @@ function mockDispatch (opts, handler) {
const responseHeaders = generateKeyValues(headers)
const responseTrailers = generateKeyValues(trailers)
handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode))
handler.onData?.(Buffer.from(responseData))
handler.onComplete?.(responseTrailers)
// Update the controller with response data
controller.rawHeaders = responseHeaders
controller.rawTrailers = responseTrailers
handler.onResponseStart?.(controller, statusCode, parseHeaders(responseHeaders), getStatusText(statusCode))
handler.onResponseData?.(controller, Buffer.from(responseData))
handler.onResponseEnd?.(controller, parseHeaders(responseTrailers))
deleteMockDispatch(mockDispatches, key)
}
function resume () {}
return true
}
@@ -401,13 +417,16 @@ function buildMockDispatch () {
} catch (error) {
if (error.code === 'UND_MOCK_ERR_MOCK_NOT_MATCHED') {
const netConnect = agent[kGetNetConnect]()
const totalInterceptsCount = this[kDispatches][kTotalDispatchCount] || this[kDispatches].length
const pendingInterceptsCount = this[kDispatches].filter(({ consumed }) => !consumed).length
const interceptsMessage = `, ${pendingInterceptsCount} interceptor(s) remaining out of ${totalInterceptsCount} defined`
if (netConnect === false) {
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)${interceptsMessage}`)
}
if (checkNetConnect(netConnect, origin)) {
originalDispatch.call(this, opts, handler)
} else {
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)${interceptsMessage}`)
}
} else {
throw error
+14 -6
View File
@@ -3,8 +3,8 @@
const Agent = require('../dispatcher/agent')
const MockAgent = require('./mock-agent')
const { SnapshotRecorder } = require('./snapshot-recorder')
const WrapHandler = require('../handler/wrap-handler')
const { InvalidArgumentError, UndiciError } = require('../core/errors')
const util = require('../core/util')
const { validateSnapshotMode } = require('./snapshot-utils')
const kSnapshotRecorder = Symbol('kSnapshotRecorder')
@@ -79,7 +79,6 @@ class SnapshotAgent extends MockAgent {
}
dispatch (opts, handler) {
handler = WrapHandler.wrap(handler)
const mode = this[kSnapshotMode]
// Check if URL should be excluded (pass through without mocking/recording)
@@ -107,8 +106,8 @@ class SnapshotAgent extends MockAgent {
} else {
// Playback mode but no snapshot found
const error = new UndiciError(`No snapshot found for ${opts.method || 'GET'} ${opts.path}`)
if (handler.onError) {
handler.onError(error)
if (handler.onResponseError) {
handler.onResponseError(null, error)
return
}
throw error
@@ -173,6 +172,10 @@ class SnapshotAgent extends MockAgent {
})
.then(() => handler.onResponseEnd(controller, trailers))
.catch((error) => handler.onResponseError(controller, error))
},
onResponseError (controller, error) {
return handler.onResponseError(controller, error)
}
}
@@ -192,7 +195,12 @@ class SnapshotAgent extends MockAgent {
try {
const { response } = snapshot
const rawHeaders = response.headers ? util.toRawHeaders(response.headers) : []
const rawTrailers = response.trailers ? util.toRawHeaders(response.trailers) : []
const controller = {
rawHeaders,
rawTrailers,
pause () { },
resume () { },
abort (reason) {
@@ -206,7 +214,7 @@ class SnapshotAgent extends MockAgent {
handler.onRequestStart(controller)
handler.onResponseStart(controller, response.statusCode, response.headers)
handler.onResponseStart(controller, response.statusCode, response.headers, response.statusMessage)
// Body is always stored as base64 string
const body = Buffer.from(response.body, 'base64')
@@ -214,7 +222,7 @@ class SnapshotAgent extends MockAgent {
handler.onResponseEnd(controller, response.trailers)
} catch (error) {
handler.onError?.(error)
handler.onResponseError?.(null, error)
}
}
+2 -2
View File
@@ -6,10 +6,10 @@ const { makeEntry } = require('./formdata')
const { webidl } = require('../webidl')
const assert = require('node:assert')
const { isomorphicDecode } = require('../infra')
const { utf8DecodeBytes } = require('../../encoding')
const dd = Buffer.from('--')
const decoder = new TextDecoder()
const decoderIgnoreBOM = new TextDecoder('utf-8', { ignoreBOM: true })
/**
* @param {string} chars
@@ -188,7 +188,7 @@ function multipartFormDataParser (input, mimeType) {
// 5.11. Otherwise:
// 5.11.1. Let value be the UTF-8 decoding without BOM of body.
value = utf8DecodeBytes(Buffer.from(body))
value = decoderIgnoreBOM.decode(Buffer.from(body))
}
// 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object.
+227 -225
View File
@@ -2135,241 +2135,243 @@ async function httpNetworkFetch (
const path = url.pathname + url.search
const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === '?'
return new Promise((resolve, reject) => agent.dispatch(
{
path: hasTrailingQuestionMark ? `${path}?` : path,
origin: url.origin,
method: request.method,
body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
headers: request.headersList.entries,
maxRedirections: 0,
upgrade: request.mode === 'websocket' ? 'websocket' : undefined
},
{
body: null,
abort: null,
return dispatchWithProtocolPreference(body)
onConnect (abort) {
// TODO (fix): Do we need connection here?
const { connection } = fetchParams.controller
// Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
// connection timing info with connection’s timing info, timingInfo’s post-redirect start
// time, and fetchParams’s cross-origin isolated capability.
// TODO: implement connection timing
timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
if (connection.destroyed) {
abort(new DOMException('The operation was aborted.', 'AbortError'))
} else {
fetchParams.controller.on('terminated', abort)
this.abort = connection.abort = abort
}
// Set timingInfo’s final network-request start time to the coarsened shared current time given
// fetchParams’s cross-origin isolated capability.
timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
function dispatchWithProtocolPreference (body, allowH2) {
return new Promise((resolve, reject) => agent.dispatch(
{
path: hasTrailingQuestionMark ? `${path}?` : path,
origin: url.origin,
method: request.method,
body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
headers: request.headersList.entries,
maxRedirections: 0,
upgrade: request.mode === 'websocket' ? 'websocket' : undefined,
...(allowH2 === false ? { allowH2 } : null)
},
{
body: null,
abort: null,
onResponseStarted () {
// Set timingInfo’s final network-response start time to the coarsened shared current
// time given fetchParams’s cross-origin isolated capability, immediately after the
// user agent’s HTTP parser receives the first byte of the response (e.g., frame header
// bytes for HTTP/2 or response status line for HTTP/1.x).
timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
},
onRequestStart (controller) {
// TODO (fix): Do we need connection here?
const { connection } = fetchParams.controller
onHeaders (status, rawHeaders, resume, statusText) {
if (status < 200) {
return false
}
// Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
// connection timing info with connection’s timing info, timingInfo’s post-redirect start
// time, and fetchParams’s cross-origin isolated capability.
// TODO: implement connection timing
timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
const headersList = new HeadersList()
const abort = (reason) => controller.abort(reason)
for (let i = 0; i < rawHeaders.length; i += 2) {
headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
}
const location = headersList.get('location', true)
this.body = new Readable({ read: resume })
const willFollow = location && request.redirect === 'follow' &&
redirectStatusSet.has(status)
const decoders = []
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
const contentEncoding = headersList.get('content-encoding', true)
// "All content-coding values are case-insensitive..."
/** @type {string[]} */
const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []
// Limit the number of content-encodings to prevent resource exhaustion.
// CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
const maxContentEncodings = 5
if (codings.length > maxContentEncodings) {
reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
return true
}
for (let i = codings.length - 1; i >= 0; --i) {
const coding = codings[i].trim()
// https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
if (coding === 'x-gzip' || coding === 'gzip') {
decoders.push(zlib.createGunzip({
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}))
} else if (coding === 'deflate') {
decoders.push(createInflate({
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}))
} else if (coding === 'br') {
decoders.push(zlib.createBrotliDecompress({
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
}))
} else if (coding === 'zstd' && hasZstd) {
decoders.push(zlib.createZstdDecompress({
flush: zlib.constants.ZSTD_e_continue,
finishFlush: zlib.constants.ZSTD_e_end
}))
} else {
decoders.length = 0
break
}
}
}
const onError = this.onError.bind(this)
resolve({
status,
statusText,
headersList,
body: decoders.length
? pipeline(this.body, ...decoders, (err) => {
if (err) {
this.onError(err)
}
}).on('error', onError)
: this.body.on('error', onError)
})
return true
},
onData (chunk) {
if (fetchParams.controller.dump) {
return
}
// 1. If one or more bytes have been transmitted from response’s
// message body, then:
// 1. Let bytes be the transmitted bytes.
const bytes = chunk
// 2. Let codings be the result of extracting header list values
// given `Content-Encoding` and response’s header list.
// See pullAlgorithm.
// 3. Increase timingInfo’s encoded body size by bytes’s length.
timingInfo.encodedBodySize += bytes.byteLength
// 4. See pullAlgorithm...
return this.body.push(bytes)
},
onComplete () {
if (this.abort) {
fetchParams.controller.off('terminated', this.abort)
}
fetchParams.controller.ended = true
this.body.push(null)
},
onError (error) {
if (this.abort) {
fetchParams.controller.off('terminated', this.abort)
}
this.body?.destroy(error)
fetchParams.controller.terminate(error)
reject(error)
},
onRequestUpgrade (_controller, status, headers, socket) {
// We need to support 200 for websocket over h2 as per RFC-8441
// Absence of session means H1
if ((socket.session != null && status !== 200) || (socket.session == null && status !== 101)) {
return false
}
const headersList = new HeadersList()
for (const [name, value] of Object.entries(headers)) {
if (value == null) {
continue
}
const headerName = name.toLowerCase()
if (Array.isArray(value)) {
for (const entry of value) {
headersList.append(headerName, String(entry), true)
}
if (connection.destroyed) {
abort(new DOMException('The operation was aborted.', 'AbortError'))
} else {
headersList.append(headerName, String(value), true)
fetchParams.controller.on('terminated', abort)
this.abort = connection.abort = abort
}
// Set timingInfo’s final network-request start time to the coarsened shared current time given
// fetchParams’s cross-origin isolated capability.
timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
},
onResponseStarted () {
// Set timingInfo’s final network-response start time to the coarsened shared current
// time given fetchParams’s cross-origin isolated capability, immediately after the
// user agent’s HTTP parser receives the first byte of the response (e.g., frame header
// bytes for HTTP/2 or response status line for HTTP/1.x).
timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
},
onResponseStart (controller, status, _headers, statusText) {
if (status < 200) {
return
}
const rawHeaders = controller?.rawHeaders ?? []
const headersList = new HeadersList()
for (let i = 0; i < rawHeaders.length; i += 2) {
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i])
const value = rawHeaders[i + 1]
if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
for (const val of value) {
headersList.append(nameStr, val.toString('latin1'), true)
}
} else {
headersList.append(nameStr, value.toString('latin1'), true)
}
}
const location = headersList.get('location', true)
this.body = new Readable({ read: () => controller.resume() })
const willFollow = location && request.redirect === 'follow' &&
redirectStatusSet.has(status)
const decoders = []
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
// https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
const contentEncoding = headersList.get('content-encoding', true)
// "All content-coding values are case-insensitive..."
/** @type {string[]} */
const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []
// Limit the number of content-encodings to prevent resource exhaustion.
// CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).
const maxContentEncodings = 5
if (codings.length > maxContentEncodings) {
reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))
return
}
for (let i = codings.length - 1; i >= 0; --i) {
const coding = codings[i].trim()
// https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
if (coding === 'x-gzip' || coding === 'gzip') {
decoders.push(zlib.createGunzip({
// Be less strict when decoding compressed responses, since sometimes
// servers send slightly invalid responses that are still accepted
// by common browsers.
// Always using Z_SYNC_FLUSH is what cURL does.
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}))
} else if (coding === 'deflate') {
decoders.push(createInflate({
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
}))
} else if (coding === 'br') {
decoders.push(zlib.createBrotliDecompress({
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
}))
} else if (coding === 'zstd' && hasZstd) {
decoders.push(zlib.createZstdDecompress({
flush: zlib.constants.ZSTD_e_continue,
finishFlush: zlib.constants.ZSTD_e_end
}))
} else {
decoders.length = 0
break
}
}
}
const onError = (err) => this.onResponseError(controller, err)
resolve({
status,
statusText,
headersList,
body: decoders.length
? pipeline(this.body, ...decoders, (err) => {
if (err) {
this.onResponseError(controller, err)
}
}).on('error', onError)
: this.body.on('error', onError)
})
},
onResponseData (controller, chunk) {
if (fetchParams.controller.dump) {
return
}
// 1. If one or more bytes have been transmitted from response’s
// message body, then:
// 1. Let bytes be the transmitted bytes.
const bytes = chunk
// 2. Let codings be the result of extracting header list values
// given `Content-Encoding` and response’s header list.
// See pullAlgorithm.
// 3. Increase timingInfo’s encoded body size by bytes’s length.
timingInfo.encodedBodySize += bytes.byteLength
// 4. See pullAlgorithm...
if (this.body.push(bytes) === false) {
controller.pause()
}
},
onResponseEnd () {
if (this.abort) {
fetchParams.controller.off('terminated', this.abort)
}
fetchParams.controller.ended = true
this.body?.push(null)
},
onResponseError (_controller, error) {
if (this.abort) {
fetchParams.controller.off('terminated', this.abort)
}
if (
request.mode === 'websocket' &&
allowH2 !== false &&
error?.code === 'UND_ERR_INFO' &&
error?.message === 'HTTP/2: Extended CONNECT protocol not supported by server'
) {
// The origin negotiated H2, but RFC 8441 websocket support is unavailable.
// Retry the opening handshake on a fresh HTTP/1.1-only connection instead.
resolve(dispatchWithProtocolPreference(body, false))
return
}
this.body?.destroy(error)
fetchParams.controller.terminate(error)
reject(error)
},
onRequestUpgrade (controller, status, _headers, socket) {
// We need to support 200 for websocket over h2 as per RFC-8441
// Absence of session means H1
if ((socket.session != null && status !== 200) || (socket.session == null && status !== 101)) {
return false
}
const rawHeaders = controller?.rawHeaders ?? []
const headersList = new HeadersList()
for (let i = 0; i < rawHeaders.length; i += 2) {
const nameStr = bufferToLowerCasedHeaderName(rawHeaders[i])
const value = rawHeaders[i + 1]
if (Array.isArray(value) && !Buffer.isBuffer(rawHeaders[i + 1])) {
for (const val of value) {
headersList.append(nameStr, val.toString('latin1'), true)
}
} else {
headersList.append(nameStr, value.toString('latin1'), true)
}
}
resolve({
status,
statusText: STATUS_CODES[status],
headersList,
socket
})
return true
}
resolve({
status,
statusText: STATUS_CODES[status],
headersList,
socket
})
return true
},
onUpgrade (status, rawHeaders, socket) {
// We need to support 200 for websocket over h2 as per RFC-8441
// Absence of session means H1
if ((socket.session != null && status !== 200) || (socket.session == null && status !== 101)) {
return false
}
const headersList = new HeadersList()
for (let i = 0; i < rawHeaders.length; i += 2) {
headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
}
resolve({
status,
statusText: STATUS_CODES[status],
headersList,
socket
})
return true
}
}
))
))
}
}
}
@@ -284,12 +284,6 @@ class WebSocketStream {
start: (controller) => {
this.#readableStreamController = controller
},
pull (controller) {
let chunk
while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) {
controller.enqueue(chunk)
}
},
cancel: (reason) => this.#cancel(reason)
})
+13 -1
View File
@@ -25,6 +25,18 @@ const { SendQueue } = require('./sender')
const { WebsocketFrameSend } = require('./frame')
const { channels } = require('../../core/diagnostics')
function getSocketAddress (socket) {
if (typeof socket?.address === 'function') {
return socket.address()
}
if (typeof socket?.session?.socket?.address === 'function') {
return socket.session.socket.address()
}
return null
}
/**
* @typedef {object} Handler
* @property {(response: any, extensions?: string[]) => void} onConnectionEstablished
@@ -491,7 +503,7 @@ class WebSocket extends EventTarget {
// Convert headers to a plain object for the event
const headers = response.headersList.entries
channels.open.publish({
address: response.socket.address(),
address: getSocketAddress(response.socket),
protocol: this.#protocol,
extensions: this.#extensions,
websocket: this,
+299 -299
View File
File diff suppressed because it is too large. Load diff
+5 -5
View File
@@ -1,6 +1,6 @@
{
"name": "undici",
"version": "7.24.4",
"version": "8.0.2",
"description": "An HTTP/1.1 client, written from scratch for Node.js",
"homepage": "https://undici.nodejs.org",
"bugs": {
@@ -97,7 +97,7 @@
"test:websocket:autobahn": "node test/autobahn/client.js",
"test:websocket:autobahn:report": "node test/autobahn/report.js",
"test:wpt:setup": "node test/web-platform-tests/wpt-runner.mjs setup",
"test:wpt": "npm run test:wpt:setup && node test/web-platform-tests/wpt-runner.mjs run /fetch /mimesniff /xhr /websockets /serviceWorkers /eventsource",
"test:wpt": "npm run test:wpt:setup && node test/web-platform-tests/wpt-runner.mjs run /fetch /mimesniff /websockets /serviceWorkers /eventsource",
"test:cache-tests": "node test/cache-interceptor/cache-tests.mjs --ci",
"coverage": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report",
"coverage:ci": "npm run coverage:clean && cross-env NODE_V8_COVERAGE=./coverage/tmp npm run test:javascript && npm run coverage:report:ci",
@@ -113,7 +113,7 @@
"@matteo.collina/tspl": "^0.2.0",
"@metcoder95/https-pem": "^1.0.0",
"@sinonjs/fake-timers": "^12.0.0",
"@types/node": "^20.19.22",
"@types/node": "^22.0.0",
"abort-controller": "^3.0.0",
"borp": "^0.20.0",
"c8": "^10.0.0",
@@ -129,11 +129,11 @@
"node-forge": "^1.3.1",
"proxy": "^2.1.1",
"tsd": "^0.33.0",
"typescript": "^5.6.2",
"typescript": "^6.0.2",
"ws": "^8.11.0"
},
"engines": {
"node": ">=20.18.1"
"node": ">=22.19.0"
},
"tsd": {
"directory": "test/types",
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
set -euo pipefail
TIMEOUT_SECONDS=${TIMEOUT_SECONDS:-120}
TEST_GLOB=${TEST_GLOB:-"test/*.js"}
LOG_DIR=${LOG_DIR:-"/tmp/undici-test-hang"}
mkdir -p "$LOG_DIR"
failures=()
timeouts=()
while IFS= read -r test_file; do
echo "==> ${test_file}"
log_file="$LOG_DIR/$(basename "$test_file").log"
if timeout "$TIMEOUT_SECONDS" npx borp -p "$test_file" >"$log_file" 2>&1; then
echo "PASS ${test_file}"
else
exit_code=$?
if [[ $exit_code -eq 124 || $exit_code -eq 137 ]]; then
echo "TIMEOUT ${test_file}"
timeouts+=("$test_file")
else
echo "FAIL ${test_file} (exit $exit_code)"
failures+=("$test_file")
fi
fi
echo
sleep 0.2
done < <(ls $TEST_GLOB | sort)
echo "=== Summary ==="
if [[ ${#timeouts[@]} -gt 0 ]]; then
echo "Timeouts:"
printf ' - %s\n' "${timeouts[@]}"
else
echo "Timeouts: none"
fi
if [[ ${#failures[@]} -gt 0 ]]; then
echo "Failures:"
printf ' - %s\n' "${failures[@]}"
else
echo "Failures: none"
fi
echo "Logs: $LOG_DIR"
+15 -1
View File
@@ -2,13 +2,26 @@
// Called from .github/workflows
const getMajorTagPrefix = (versionTag) => {
const match = /^v(\d+)\./.exec(versionTag)
return match ? `v${match[1]}` : versionTag
}
const getPreviousRelease = ({ releases, versionTag }) => {
const majorTagPrefix = getMajorTagPrefix(versionTag)
return releases.find((release) => {
return release.tag_name !== versionTag && release.tag_name.startsWith(`${majorTagPrefix}.`)
})
}
const generateReleaseNotes = async ({ github, owner, repo, versionTag, commitHash }) => {
const { data: releases } = await github.rest.repos.listReleases({
owner,
repo
})
const previousRelease = releases.find((r) => r.tag_name.startsWith('v7'))
const previousRelease = getPreviousRelease({ releases, versionTag })
const { data: { body } } = await github.rest.repos.generateReleaseNotes({
owner,
@@ -69,5 +82,6 @@ const release = async ({ github, context, versionTag, commitHash }) => {
module.exports = {
generatePr,
getPreviousRelease,
release
}
+5 -27
View File
@@ -137,8 +137,6 @@ declare namespace Dispatcher {
signal?: AbortSignal | EventEmitter | null;
/** This argument parameter is passed through to `ConnectData` */
opaque?: TOpaque;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
responseHeaders?: 'raw' | null;
}
@@ -147,8 +145,6 @@ declare namespace Dispatcher {
opaque?: TOpaque;
/** Default: `null` */
signal?: AbortSignal | EventEmitter | null;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
onInfo?: (info: { statusCode: number, headers: Record<string, string | string[]> }) => void;
/** Default: `null` */
@@ -170,8 +166,6 @@ declare namespace Dispatcher {
protocol?: string;
/** Default: `null` */
signal?: AbortSignal | EventEmitter | null;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
responseHeaders?: 'raw' | null;
}
@@ -218,6 +212,8 @@ declare namespace Dispatcher {
get aborted(): boolean
get paused(): boolean
get reason(): Error | null
rawHeaders?: Buffer[] | string[] | null
rawTrailers?: Buffer[] | string[] | null
abort(reason: Error): void
pause(): void
resume(): void
@@ -231,30 +227,12 @@ declare namespace Dispatcher {
onResponseEnd?(controller: DispatchController, trailers: IncomingHttpHeaders): void;
onResponseError?(controller: DispatchController, error: Error): void;
/** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */
/** @deprecated */
onConnect?(abort: (err?: Error) => void): void;
/** Invoked when an error has occurred. */
/** @deprecated */
onError?(err: Error): void;
/** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */
/** @deprecated */
onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void;
/** Invoked when response is received, before headers have been read. **/
/** @deprecated */
onResponseStarted?(): void;
/** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */
/** @deprecated */
onHeaders?(statusCode: number, headers: Buffer[], resume: () => void, statusText: string): boolean;
/** Invoked when response payload data is received. */
/** @deprecated */
onData?(chunk: Buffer): boolean;
/** Invoked when response payload and trailers have been received and the request has completed. */
/** @deprecated */
onComplete?(trailers: string[] | null): void;
/** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */
/** @deprecated */
onBodySent?(chunkSize: number, totalBytesSent: number): void;
onBodySent?(chunk: Buffer): void;
/** Invoked after the request body is fully sent. */
onRequestSent?(): void;
}
export type PipelineHandler<TOpaque = null> = (data: PipelineHandlerData<TOpaque>) => Readable
export type HttpMethod = Autocomplete<'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'>
+7
View File
@@ -0,0 +1,7 @@
import Dispatcher from './dispatcher'
export default Dispatcher1Wrapper
declare class Dispatcher1Wrapper extends Dispatcher {
constructor (dispatcher: Dispatcher)
}
+24 -4
View File
@@ -60,12 +60,32 @@ export interface SpecIterator<T, TReturn = any, TNext = undefined> {
next(...args: [] | [TNext]): IteratorResult<T, TReturn>;
}
export interface SpecIterableIterator<T> extends SpecIterator<T> {
export interface SpecIteratorObject<T, TReturn = undefined, TNext = unknown> extends SpecIterator<T, TReturn, TNext> {
[Symbol.iterator](): SpecIteratorObject<T, TReturn, TNext>;
map<U>(callbackfn: (value: T, index: number) => U): SpecIteratorObject<U>;
filter<S extends T>(predicate: (value: T, index: number) => value is S): SpecIteratorObject<S>;
filter(predicate: (value: T, index: number) => unknown): SpecIteratorObject<T>;
take(limit: number): SpecIteratorObject<T>;
drop(count: number): SpecIteratorObject<T>;
flatMap<U>(callbackfn: (value: T, index: number) => Iterator<U> | Iterable<U>): SpecIteratorObject<U>;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T;
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U;
toArray(): T[];
forEach(callbackfn: (value: T, index: number) => void): void;
some(predicate: (value: T, index: number) => unknown): boolean;
every(predicate: (value: T, index: number) => unknown): boolean;
find<S extends T>(predicate: (value: T, index: number) => value is S): S | undefined;
find(predicate: (value: T, index: number) => unknown): T | undefined;
readonly [Symbol.toStringTag]: string;
}
export interface SpecIterableIterator<T> extends SpecIteratorObject<T> {
[Symbol.iterator](): SpecIterableIterator<T>;
}
export interface SpecIterable<T> {
[Symbol.iterator](): SpecIterator<T>;
[Symbol.iterator](): SpecIterableIterator<T>;
}
export type HeadersInit = [string, string][] | HeaderRecord | Headers
@@ -173,7 +193,7 @@ export declare class Request extends BodyMixin {
readonly signal: AbortSignal
readonly duplex: RequestDuplex
readonly clone: () => Request
public clone (): Request
}
export interface ResponseInit {
@@ -203,7 +223,7 @@ export declare class Response extends BodyMixin {
readonly url: string
readonly redirected: boolean
readonly clone: () => Response
public clone (): Response
static error (): Response
static json (data: any, init?: ResponseInit): Response
+6
View File
@@ -4,6 +4,12 @@
import { File } from 'node:buffer'
import { SpecIterableIterator } from './fetch'
declare module 'node:buffer' {
interface File {
readonly [Symbol.toStringTag]: string
}
}
/**
* A `string` or `File` that represents a single value from a set of `FormData` key-value pairs.
*/
+1 -2
View File
@@ -5,8 +5,7 @@ export declare class RedirectHandler implements Dispatcher.DispatchHandler {
dispatch: Dispatcher.Dispatch,
maxRedirections: number,
opts: Dispatcher.DispatchOptions,
handler: Dispatcher.DispatchHandler,
redirectionLimitReached: boolean
handler: Dispatcher.DispatchHandler
)
}
+3 -1
View File
@@ -11,6 +11,7 @@ import H2CClient from './h2c-client'
import buildConnector from './connector'
import errors from './errors'
import Agent from './agent'
import Dispatcher1Wrapper from './dispatcher1-wrapper'
import MockClient from './mock-client'
import MockPool from './mock-pool'
import MockAgent from './mock-agent'
@@ -44,7 +45,7 @@ export { Interceptable } from './mock-interceptor'
declare function globalThisInstall (): void
export { Dispatcher, BalancedPool, RoundRobinPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, cacheStores, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, Socks5ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install }
export { Dispatcher, BalancedPool, RoundRobinPool, Pool, Client, buildConnector, errors, Agent, Dispatcher1Wrapper, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, interceptors, cacheStores, MockClient, MockPool, MockAgent, SnapshotAgent, MockCallHistory, MockCallHistoryLog, mockErrors, ProxyAgent, Socks5ProxyAgent, EnvHttpProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler, RetryAgent, H2CClient, globalThisInstall as install }
export default Undici
declare namespace Undici {
@@ -60,6 +61,7 @@ declare namespace Undici {
const buildConnector: typeof import('./connector').default
const errors: typeof import('./errors').default
const Agent: typeof import('./agent').default
const Dispatcher1Wrapper: typeof import('./dispatcher1-wrapper').default
const setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher
const getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher
const request: typeof import('./api').request
+1068 -989
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -2,5 +2,5 @@
// Refer to tools/dep_updaters/update-undici.sh
#ifndef SRC_UNDICI_VERSION_H_
#define SRC_UNDICI_VERSION_H_
#define UNDICI_VERSION "7.24.4"
#define UNDICI_VERSION "8.0.2"
#endif // SRC_UNDICI_VERSION_H_