Commit 31761388e94 for nodejs
commit 31761388e94d289f87c60ece599451c51c6afd37
Author: Node.js GitHub Bot <github-bot@iojs.org>
Date: Mon Nov 23 19:45:02 2026 -0500
deps: update undici to 8.13.1
PR-URL: https://github.com/nodejs/node/pull/67692
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
diff --git a/deps/undici/src/SECURITY.md b/deps/undici/src/SECURITY.md
index 6fed3847fba..2f9e4ea37fb 100644
--- a/deps/undici/src/SECURITY.md
+++ b/deps/undici/src/SECURITY.md
@@ -36,6 +36,29 @@ issue.
Undici is an HTTP client library for Node.js. Its threat model is derived from
and aligned with the [Node.js threat model](https://github.com/nodejs/node/blob/HEAD/SECURITY.md#the-nodejs-threat-model).
+The Node.js policy is authoritative for the copy of undici bundled with
+Node.js. This section applies the same boundaries to the standalone undici
+package.
+
+### Security triage dispositions
+
+Security reports are classified using the same dispositions as Node.js:
+
+* **Vulnerability**: An undici defect that is exploitable across an
+ undici-owned security boundary and meets the criteria under
+ [What constitutes a vulnerability](#what-constitutes-a-vulnerability),
+ including any applicable DoS criteria.
+* **Security-interest bug**: A real undici defect, or an API behavior likely to
+ cause security bugs in applications, that is not itself a vulnerability
+ under this threat model. These are fixed as regular bugs and do not
+ automatically receive a CVE, but should still be reported privately first
+ when they affect a common security control such as protocol interpretation,
+ certificate validation, or TLS decisions.
+* **Common bug**: A correctness, robustness, or crash issue without an
+ undici-owned security boundary or a realistic cross-boundary attacker
+ benefit.
+* **Invalid / out of scope**: A report that cannot be reproduced, is not an
+ undici defect, or concerns behavior excluded by this policy.
### What constitutes a vulnerability
@@ -53,27 +76,40 @@ For a behavior to be considered a DoS vulnerability, the proof of concept must
meet the following criteria:
* The API is being correctly used.
-* The API is public and documented.
-* The behavior is significant enough to cause a denial of service quickly
- or in a context not controlled by the application developer (for example,
- HTTP parsing).
+* The API does not have a warning against its use in production.
+* The API is public and documented. For standards-based APIs, the behavior
+ must be well-defined by the applicable specification.
+* The API is stable. For APIs bundled in Node.js, it must have stable (2.0)
+ status.
+* The behavior is significant enough to cause a denial of service quickly or
+ in a context not controlled by the application developer, such as protocol
+ parsing.
* The behavior is directly exploitable by an untrusted source without requiring
application mistakes.
* The behavior cannot be reasonably mitigated through standard operational
- practices (like process recycling).
+ practices, such as process recycling.
+* The behavior occurs deterministically under normal usage patterns rather than
+ only in edge cases.
+* The behavior occurs at a rate that would cause practical resource exhaustion
+ within a practical timeframe under typical workloads.
* The attack demonstrates
[asymmetric resource consumption](https://cwe.mitre.org/data/definitions/405.html),
- where the attacker expends significantly fewer resources than what is required
- by the client to process the attack.
+ where the attacker expends significantly fewer resources than the client
+ must expend to process the attack. Attacks requiring comparable resources on
+ the attacker's side, which can be mitigated through practices such as rate
+ limiting, may not qualify.
**Undici does NOT trust**:
-* Data received from the remote end of HTTP connections (both inbound responses
- and server-sent data) that is parsed or transformed by undici before being
- passed to the application. This includes:
+* Data received from the remote end of outbound network connections created
+ through undici APIs and transformed or validated by undici before being
+ passed to the application, **except with respect to payload length**. Undici
+ trusts applications to make connections and requests that avoid payload
+ sizes that would result in a denial of service. Subject to that exception,
+ untrusted data includes:
* HTTP response headers and status lines.
- * HTTP response bodies when processed by undici (e.g., chunked transfer
- decoding, content-encoding).
+ * HTTP response bodies processed by undici, such as chunked transfer decoding
+ and content-encoding.
* WebSocket frames received from a server.
* Server-Sent Events (EventSource) data received from a server.
* TLS certificate validation performed by undici on behalf of the application.
@@ -81,7 +117,8 @@ meet the following criteria:
**Undici trusts**:
* The application code that uses its APIs, including all configuration,
- options, callbacks, and decisions about which body-consuming APIs to call.
+ options, callbacks, connection and request decisions, and decisions about
+ which body-consuming APIs to call.
* The operating system and its network stack.
* The Node.js runtime undici is running on.
* Dependencies installed by the application.
@@ -99,19 +136,19 @@ meet the following criteria:
bypass organizational, regulatory, or legal controls. Untrusted proxies are
outside the supported threat model.
-In other words, if untrusted data passing through undici to the application
-can trigger actions other than those documented for the APIs, there is likely
-a security vulnerability. Examples of unwanted actions are polluting globals,
-causing an unrecoverable crash, or any other unexpected side effects that can
-lead to a loss of confidentiality, integrity, or availability.
+In other words, if untrusted data passing through undici to the application can
+trigger actions other than those documented for the APIs, there is likely a
+security vulnerability. Examples include polluting globals, causing an
+unrecoverable crash, or other unexpected side effects that can lead to a loss
+of confidentiality, integrity, or availability.
### Examples of vulnerabilities
#### Improper Certificate Validation (CWE-295)
* Undici provides TLS connections to HTTPS endpoints. If certificates can be
- crafted that result in incorrect validation by undici, that is considered
- a vulnerability.
+ crafted that result in incorrect validation by undici, that is considered a
+ vulnerability.
#### Inconsistent Interpretation of HTTP Responses (CWE-444)
@@ -127,12 +164,19 @@ lead to a loss of confidentiality, integrity, or availability.
#### CRLF Injection in Request Headers (CWE-93)
-* If untrusted input passed to undici APIs (such as header values or URLs)
- can inject additional headers or corrupt the HTTP request stream, that is
+* If untrusted input passed to undici APIs, such as header values or URLs, can
+ inject additional headers or corrupt the HTTP request stream, that is
considered a vulnerability.
### Examples of non-vulnerabilities
+#### Defense-in-depth issues
+
+* Bugs whose fixes only improve resilience after another security boundary has
+ already failed, or reduce the impact of behavior outside this threat model,
+ are defense-in-depth issues. They are fixed as regular bugs and do not
+ receive CVEs.
+
#### Malicious Third-Party Modules (CWE-1357)
* Application code and its dependencies are trusted by undici. Any scenario
@@ -141,17 +185,17 @@ lead to a loss of confidentiality, integrity, or availability.
#### Prototype Pollution Attacks (CWE-1321)
-* Undici trusts the inputs provided to it by application code. It is up to the
- application to sanitize appropriately. Any scenario that requires control
- over user input passed directly by the application is not considered a
- vulnerability in undici.
+* Undici trusts inputs provided by application code. The application must
+ sanitize them appropriately. A scenario that requires control over user input
+ passed directly by the application is not a vulnerability in undici.
#### Uncontrolled Resource Consumption on Outbound Connections (CWE-400)
-* If undici is asked to connect to a remote site and the response payload is
- large enough to impact performance or cause the runtime to run out of
- resources, that is not considered a vulnerability. Applications are
- responsible for setting appropriate limits on response sizes.
+* If undici is asked to connect to a remote site and return an artifact, it is
+ not a vulnerability if the size of that artifact is large enough to impact
+ performance or cause the runtime to run out of resources. Applications are
+ responsible for choosing suitable response-processing APIs and enforcing
+ limits appropriate for their workloads.
#### Calling body-consuming methods on untrusted responses
@@ -188,9 +232,9 @@ lead to a loss of confidentiality, integrity, or availability.
#### Application Misconfiguration
-* Issues arising from incorrect or insecure use of undici APIs (such as
+* Issues arising from incorrect or insecure use of undici APIs, such as
disabling TLS verification, ignoring errors, or passing unsanitized user
- input to request options) are the application's responsibility, not
+ input to request options, are the application's responsibility and not
vulnerabilities in undici.
#### Unauthorized or untrusted proxy use
diff --git a/deps/undici/src/docs/docs/api/CacheStore.md b/deps/undici/src/docs/docs/api/CacheStore.md
index 45c202d8987..dd4facac2f0 100644
--- a/deps/undici/src/docs/docs/api/CacheStore.md
+++ b/deps/undici/src/docs/docs/api/CacheStore.md
@@ -203,6 +203,16 @@ added: v7.0.0
integers; a `TypeError` is thrown otherwise, or if `maxEntrySize` is greater
than 2 GB.
+The database is not encrypted, and nothing in it is hashed. The request URL
+(including the query string), the response headers and body, and the values of
+any request headers named in the response's `Vary` header (for example
+`Authorization` or `Cookie`) are written as plain text to `location`. Protect
+that file like any other sensitive data, or use `':memory:'`. A response to a
+request that carries `Authorization` is only stored when the response allows it
+with `public`, `s-maxage`, or `must-revalidate` (see [RFC 9111, Section 3.5][]);
+servers can send `Cache-Control: no-store` to keep a response out of the cache
+entirely.
+
### `sqliteCacheStore.close()`
<!-- YAML
@@ -372,4 +382,5 @@ The value returned by `get`. It contains every field of
body. (optional)
[RFC 9111]: https://www.rfc-editor.org/rfc/rfc9111.html
+[RFC 9111, Section 3.5]: https://www.rfc-editor.org/rfc/rfc9111.html#section-3.5
[`node:sqlite`]: https://nodejs.org/api/sqlite.html
diff --git a/deps/undici/src/docs/docs/api/Client.md b/deps/undici/src/docs/docs/api/Client.md
index b81aef5559b..402e050351d 100644
--- a/deps/undici/src/docs/docs/api/Client.md
+++ b/deps/undici/src/docs/docs/api/Client.md
@@ -137,7 +137,9 @@ added: v1.0.0
positive integer. **Default:** `524288`.
* `pingInterval` {number} The time interval, in milliseconds, between HTTP/2
PING frames. Set to `0` to disable PING frames. Applies only to HTTP/2
- connections and emits a `ping` event on the client. **Default:** `60e3`.
+ connections and emits a `ping` event on the client. A connection whose
+ PING is still unacknowledged when the next one is due is closed, and new
+ requests go to a new connection. **Default:** `60e3`.
* `settings` {object} `SETTINGS` frame options. For full reference, take a
look to [HTTP/2#Settings Object](https://nodejs.org/api/http2.html#settings-object)
* `webSocket` {Object} (optional) WebSocket-specific configuration.
@@ -217,7 +219,7 @@ import { Client, buildConnector } from 'undici'
const connector = buildConnector({ rejectUnauthorized: false })
const client = new Client('https://localhost:3000', {
connect (opts, cb) {
- connector(opts, (err, socket) => {
+ return connector(opts, (err, socket) => {
if (err) {
cb(err)
} else {
diff --git a/deps/undici/src/docs/docs/api/Connector.md b/deps/undici/src/docs/docs/api/Connector.md
index 8e21f1713f0..724c480b7ed 100644
--- a/deps/undici/src/docs/docs/api/Connector.md
+++ b/deps/undici/src/docs/docs/api/Connector.md
@@ -78,7 +78,7 @@ const connector = buildConnector({ rejectUnauthorized: false })
const client = new Client('https://localhost:3000', {
connect (opts, cb) {
- connector(opts, (err, socket) => {
+ return connector(opts, (err, socket) => {
if (err) {
cb(err)
} else if (/* assertion */ false) {
@@ -124,6 +124,13 @@ targets or a [`tls.TLSSocket`][] for `https:` targets, applies TCP keep-alive an
the connect timeout, and invokes `callback` once the socket connects or errors.
The socket is also returned synchronously.
+undici uses the returned socket to cancel a connection attempt that no request
+needs any more: once every request waiting for it is aborted, the socket is
+destroyed and the next request opens a new connection instead of waiting for
+it. A connector that wraps another one should return the socket it gets back,
+as the examples on this page do. If it returns nothing, the attempt runs until
+it connects or fails.
+
When connecting over TLS, established sessions are cached (subject to
`maxCachedSessions`) and reused for subsequent connections to the same
`servername` or `hostname`.
@@ -141,7 +148,7 @@ const connector = buildConnector({ rejectUnauthorized: false })
const client = new Client('https://localhost:3000', {
connect (opts, cb) {
- connector(opts, (err, socket) => {
+ return connector(opts, (err, socket) => {
if (err) {
cb(err)
} else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) {
diff --git a/deps/undici/src/docs/docs/api/Dispatcher.md b/deps/undici/src/docs/docs/api/Dispatcher.md
index 61c0d64f53d..8265bee52d6 100644
--- a/deps/undici/src/docs/docs/api/Dispatcher.md
+++ b/deps/undici/src/docs/docs/api/Dispatcher.md
@@ -705,6 +705,26 @@ The order of the interceptors matters: the last interceptor in the chain is the
first to be called. Forking the chain of interceptors can lead to unexpected
results.
+Because interceptors wrap each other, ordering is the end-user's responsibility.
+Certain built-in interceptors are order-sensitive and will throw an
+`InvalidArgumentError` if composed in an unsafe order. In particular, the
+`cache` interceptor must be composed **after** the `redirect` interceptor. When
+`cache` is composed before `redirect`, the cache handler is wrapped *above* the
+redirect handler, so it never observes the redirect history and its
+cross-origin / credential-bearing redirect guards are silently disabled.
+This allows an attacker-controlled or cross-principal redirect response to be
+stored under the trusted origin's cache key and replayed to unrelated callers
+(see GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26 and
+GHSA-7XG3-FPHP-28HG).
+
+```js
+// Correct: cache is composed after redirect.
+new Agent().compose(interceptors.redirect({ maxRedirections: 5 }), interceptors.cache({}))
+
+// Throws an InvalidArgumentError: cache composed before redirect.
+new Agent().compose(interceptors.cache({}), interceptors.redirect({ maxRedirections: 5 }))
+```
+
```text
compose([interceptor1, interceptor2, interceptor3])
diff --git a/deps/undici/src/docs/docs/api/Interceptors.md b/deps/undici/src/docs/docs/api/Interceptors.md
index fd4b8d59aa1..3d3ae902fb0 100644
--- a/deps/undici/src/docs/docs/api/Interceptors.md
+++ b/deps/undici/src/docs/docs/api/Interceptors.md
@@ -204,9 +204,6 @@ and `x-compress`, is left untouched, matching `fetch()`. As required by
[RFC 9659](https://www.rfc-editor.org/rfc/rfc9659.html), a `zstd` frame that
requires a window size larger than 8 MB fails to decode.
-> **Experimental:** This interceptor is experimental and subject to change.
-> A one-time `ExperimentalWarning` is emitted on first use.
-
**Parameters**
* `opts` {Object} (optional)
@@ -359,12 +356,25 @@ backing store.
**Returns:** {Dispatcher.DispatcherComposeInterceptor}
+> **Ordering:** the `cache` interceptor must be composed **after** the
+> `redirect` interceptor. When `cache` is composed before `redirect`, the cache
+> handler is wrapped above the redirect handler, so it never observes the
+> redirect history and its cross-origin / credential-bearing redirect guards are
+> silently disabled, which lets an attacker-controlled or cross-principal
+> redirect response be stored under the trusted origin's cache key and replayed
+> to unrelated callers (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32,
+> GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG). `compose()` throws an
+> `InvalidArgumentError` for this unsafe order. The `deduplicate` interceptor
+> participates in the same redirect-history contract and may be placed before or
+> after `redirect`, as long as `cache` follows `redirect`.
+
**Example**
```js
import { Agent, interceptors, cacheStores } from 'undici'
const agent = new Agent().compose(
+ interceptors.redirect({ maxRedirections: 5 }),
interceptors.cache({ store: new cacheStores.MemoryCacheStore() })
)
```
diff --git a/deps/undici/src/docs/docs/best-practices/mocking-request.md b/deps/undici/src/docs/docs/best-practices/mocking-request.md
index 86ebca94f7a..d097ce68272 100644
--- a/deps/undici/src/docs/docs/best-practices/mocking-request.md
+++ b/deps/undici/src/docs/docs/best-practices/mocking-request.md
@@ -61,7 +61,7 @@ const success = await bankTransfer('1234567890', '100')
assert.deepEqual(success, { message: 'transaction processed' })
-// if you dont want to check whether the body or the headers contain the same value
+// if you don't want to check whether the body or the headers contain the same value
// just remove it from interceptor
mockPool.intercept({
path: '/bank-transfer',
diff --git a/deps/undici/src/lib/api/abort-signal.js b/deps/undici/src/lib/api/abort-signal.js
index 608170b4316..d4c1c93c7a2 100644
--- a/deps/undici/src/lib/api/abort-signal.js
+++ b/deps/undici/src/lib/api/abort-signal.js
@@ -2,15 +2,17 @@
const { addAbortListener } = require('../core/util')
const { RequestAbortedError } = require('../core/errors')
+const { kQueuedAbort } = require('../core/symbols')
const kListener = Symbol('kListener')
const kSignal = Symbol('kSignal')
function abort (self) {
+ // Keep the reason even when abort is set: a queued request that cannot be
+ // taken out of its queue is aborted once it starts.
+ self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
if (self.abort) {
- self.abort(self[kSignal]?.reason)
- } else {
- self.reason = self[kSignal]?.reason ?? new RequestAbortedError()
+ self.abort(self.reason)
}
removeSignal(self)
}
@@ -26,7 +28,7 @@ function addSignal (self, signal) {
}
if (signal.aborted) {
- abort(self)
+ self.reason = signal.reason ?? new RequestAbortedError()
return
}
@@ -53,7 +55,55 @@ function removeSignal (self) {
self[kListener] = null
}
+// Dispatchers call the kQueuedAbort hook while a request waits for a
+// connection, with a function that takes it out of their queue. Until the
+// request starts, the handler's abort calls that function.
+//
+// A retry or a redirect dispatches the same handler again after an earlier
+// attempt started. The handler's abort then also calls the controller of that
+// attempt: it does nothing once the attempt is over, and still reaches a
+// response that a retry resumes.
+function queuedAbortHook (handler) {
+ // The abort set by onRequestStart, and the one this hook installed last.
+ let started = null
+ let installed = null
+ return (cancel) => {
+ if (handler.reason) {
+ cancel(handler.reason)
+ return
+ }
+
+ if (handler.abort !== installed) {
+ started = handler.abort
+ }
+
+ if (started === null) {
+ installed = cancel
+ } else {
+ const abortStarted = started
+ installed = (reason) => {
+ abortStarted(reason)
+ cancel(reason)
+ }
+ }
+ handler.abort = installed
+ }
+}
+
+// Dispatches a request whose options carry a signal. Requests without a signal
+// are dispatched directly and never reach this function.
+function dispatchWithSignal (dispatcher, opts, handler) {
+ if (handler.reason) {
+ // Already aborted: fail without dispatching, so no connection is opened.
+ handler.onResponseError(null, handler.reason)
+ return
+ }
+
+ dispatcher.dispatch({ ...opts, [kQueuedAbort]: queuedAbortHook(handler) }, handler)
+}
+
module.exports = {
addSignal,
- removeSignal
+ removeSignal,
+ dispatchWithSignal
}
diff --git a/deps/undici/src/lib/api/api-connect.js b/deps/undici/src/lib/api/api-connect.js
index f449c787d61..9811b076cb9 100644
--- a/deps/undici/src/lib/api/api-connect.js
+++ b/deps/undici/src/lib/api/api-connect.js
@@ -4,7 +4,7 @@ const assert = require('node:assert')
const { AsyncResource } = require('node:async_hooks')
const { InvalidArgumentError, SocketError } = require('../core/errors')
const util = require('../core/util')
-const { addSignal, removeSignal } = require('./abort-signal')
+const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
class ConnectHandler extends AsyncResource {
constructor (opts, callback) {
@@ -99,7 +99,11 @@ function connect (opts, callback) {
try {
const connectHandler = new ConnectHandler(opts, callback)
const connectOptions = { ...opts, method: 'CONNECT' }
- this.dispatch(connectOptions, connectHandler)
+ if (opts.signal == null) {
+ this.dispatch(connectOptions, connectHandler)
+ } else {
+ dispatchWithSignal(this, connectOptions, connectHandler)
+ }
} catch (err) {
if (typeof callback !== 'function') {
throw err
diff --git a/deps/undici/src/lib/api/api-pipeline.js b/deps/undici/src/lib/api/api-pipeline.js
index 6af3913440a..fe7c729413a 100644
--- a/deps/undici/src/lib/api/api-pipeline.js
+++ b/deps/undici/src/lib/api/api-pipeline.js
@@ -14,7 +14,7 @@ const {
} = require('../core/errors')
const util = require('../core/util')
const { kBodyUsed } = require('../core/symbols')
-const { addSignal, removeSignal } = require('./abort-signal')
+const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
function noop () {}
@@ -126,7 +126,7 @@ class PipelineHandler extends AsyncResource {
err = new RequestAbortedError()
}
- if (abort && err) {
+ if (abort && (err || !res?.readableEnded)) {
abort()
}
@@ -255,7 +255,12 @@ class PipelineHandler extends AsyncResource {
function pipeline (opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler)
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
+ const pipelineOpts = { ...opts, body: pipelineHandler.req }
+ if (opts.signal == null) {
+ this.dispatch(pipelineOpts, pipelineHandler)
+ } else {
+ dispatchWithSignal(this, pipelineOpts, pipelineHandler)
+ }
return pipelineHandler.ret
} catch (err) {
return new PassThrough().destroy(err)
diff --git a/deps/undici/src/lib/api/api-request.js b/deps/undici/src/lib/api/api-request.js
index e9f72a428b2..c857e213d3f 100644
--- a/deps/undici/src/lib/api/api-request.js
+++ b/deps/undici/src/lib/api/api-request.js
@@ -5,6 +5,7 @@ const { AsyncResource } = require('node:async_hooks')
const { Readable } = require('./readable')
const { InvalidArgumentError, RequestAbortedError } = require('../core/errors')
const util = require('../core/util')
+const { dispatchWithSignal } = require('./abort-signal')
function noop () {}
@@ -37,6 +38,11 @@ class RequestHandler extends AsyncResource {
throw new InvalidArgumentError('invalid onInfo callback')
}
+ // Reject before dispatching: onRequestStart only runs once a connection is established.
+ if (signal?.aborted) {
+ throw signal.reason ?? new RequestAbortedError()
+ }
+
super('UNDICI_REQUEST')
} catch (err) {
if (util.isStream(body)) {
@@ -60,9 +66,7 @@ class RequestHandler extends AsyncResource {
this.reason = null
this.removeAbortListener = null
- if (signal?.aborted) {
- this.reason = signal.reason ?? new RequestAbortedError()
- } else if (signal) {
+ if (signal) {
this.removeAbortListener = util.addAbortListener(signal, () => {
this.reason = signal.reason ?? new RequestAbortedError()
if (this.res) {
@@ -103,7 +107,7 @@ class RequestHandler extends AsyncResource {
if (statusCode < 200) {
if (this.onInfo) {
- this.onInfo({ statusCode, headers: responseHeaderData })
+ this.runInAsyncScope(this.onInfo, null, { statusCode, headers: responseHeaderData })
}
return
}
@@ -230,7 +234,11 @@ function request (opts, callback) {
try {
const handler = new RequestHandler(opts, callback)
- this.dispatch(opts, handler)
+ if (opts.signal == null) {
+ this.dispatch(opts, handler)
+ } else {
+ dispatchWithSignal(this, opts, handler)
+ }
} catch (err) {
if (typeof callback !== 'function') {
throw err
diff --git a/deps/undici/src/lib/api/api-stream.js b/deps/undici/src/lib/api/api-stream.js
index f111d70efc1..a5e1b3ef472 100644
--- a/deps/undici/src/lib/api/api-stream.js
+++ b/deps/undici/src/lib/api/api-stream.js
@@ -4,7 +4,7 @@ const assert = require('node:assert')
const { AsyncResource } = require('node:async_hooks')
const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors')
const util = require('../core/util')
-const { addSignal, removeSignal } = require('./abort-signal')
+const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
function noop () {}
@@ -257,7 +257,11 @@ function stream (opts, factory, callback) {
try {
const handler = new StreamHandler(opts, factory, callback)
- this.dispatch(opts, handler)
+ if (opts.signal == null) {
+ this.dispatch(opts, handler)
+ } else {
+ dispatchWithSignal(this, opts, handler)
+ }
} catch (err) {
if (typeof callback !== 'function') {
throw err
diff --git a/deps/undici/src/lib/api/api-upgrade.js b/deps/undici/src/lib/api/api-upgrade.js
index 42cb29ed3ce..29eece8d0be 100644
--- a/deps/undici/src/lib/api/api-upgrade.js
+++ b/deps/undici/src/lib/api/api-upgrade.js
@@ -5,7 +5,7 @@ const { AsyncResource } = require('node:async_hooks')
const assert = require('node:assert')
const util = require('../core/util')
const { kHTTP2Stream } = require('../core/symbols')
-const { addSignal, removeSignal } = require('./abort-signal')
+const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal')
class UpgradeHandler extends AsyncResource {
constructor (opts, callback) {
@@ -108,7 +108,11 @@ function upgrade (opts, callback) {
method: opts.method || 'GET',
upgrade: opts.protocol || 'Websocket'
}
- this.dispatch(upgradeOpts, upgradeHandler)
+ if (opts.signal == null) {
+ this.dispatch(upgradeOpts, upgradeHandler)
+ } else {
+ dispatchWithSignal(this, upgradeOpts, upgradeHandler)
+ }
} catch (err) {
if (typeof callback !== 'function') {
throw err
diff --git a/deps/undici/src/lib/core/request.js b/deps/undici/src/lib/core/request.js
index efa391b8edf..039dbd7a08e 100644
--- a/deps/undici/src/lib/core/request.js
+++ b/deps/undici/src/lib/core/request.js
@@ -47,6 +47,8 @@ const kHandler = Symbol('handler')
const kController = Symbol('controller')
const kResume = Symbol('resume')
+function noop () {}
+
class RequestController {
#paused = false
#reason = null
@@ -463,12 +465,26 @@ class Request {
}
}
+ // Fails a request that was aborted before it reached a connection. The
+ // handler gets an aborted controller, so wrappers such as RetryHandler can
+ // tell a caller abort apart from a retryable connection failure.
+ onQueuedAbort (reason) {
+ this[kController] = createAbortedController(reason)
+ return this.onResponseError(reason)
+ }
+
addHeader (key, value) {
processHeader(this, key, value)
return this
}
}
+function createAbortedController (reason) {
+ const controller = new RequestController(noop)
+ controller.abort(reason)
+ return controller
+}
+
function processHeader (request, key, val) {
if (val && (typeof val === 'object' && !Array.isArray(val))) {
throw new InvalidArgumentError(`invalid ${key} header`)
@@ -580,3 +596,4 @@ function isUndiciFormData (body) {
}
module.exports = Request
+module.exports.createAbortedController = createAbortedController
diff --git a/deps/undici/src/lib/core/symbols.js b/deps/undici/src/lib/core/symbols.js
index 62163ebe2d6..842669bc6d7 100644
--- a/deps/undici/src/lib/core/symbols.js
+++ b/deps/undici/src/lib/core/symbols.js
@@ -60,6 +60,7 @@ module.exports = {
kMaxResponseSize: Symbol('max response size'),
kHTTP2Session: Symbol('http2Session'),
kHTTP2Options: Symbol('http2 options'),
+ kQueuedAbort: Symbol('queued abort'),
kHTTP2SessionState: Symbol('http2Session state'),
kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
kConstruct: Symbol('constructable'),
@@ -77,5 +78,6 @@ module.exports = {
kNoProxyAgent: Symbol('no proxy agent'),
kHttpProxyAgent: Symbol('http proxy agent'),
kHttpsProxyAgent: Symbol('https proxy agent'),
- kSocks5ProxyAgent: Symbol('socks5 proxy agent')
+ kSocks5ProxyAgent: Symbol('socks5 proxy agent'),
+ kInterceptorKind: Symbol('interceptor kind')
}
diff --git a/deps/undici/src/lib/dispatcher/agent.js b/deps/undici/src/lib/dispatcher/agent.js
index 7f95e308700..a73ba2e0541 100644
--- a/deps/undici/src/lib/dispatcher/agent.js
+++ b/deps/undici/src/lib/dispatcher/agent.js
@@ -96,7 +96,7 @@ class Agent extends DispatcherBase {
? { ...this[kOptions], allowH2: false }
: this[kOptions])
- const closeClientIfUnused = () => {
+ const closeClientIfUnused = (deferred = false) => {
if (this[kClients].get(key) !== dispatcher) {
return
}
@@ -106,7 +106,16 @@ class Agent extends DispatcherBase {
// no connected clients and is not busy, but it still has pending work.
// Closing it here lets the replacement Client finish those requests
// and then destroys that new connection with ClientDestroyedError.
- if (dispatcher[kConnected] > 0 || dispatcher[kBusy] || dispatcher[kPending] > 0) {
+ if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
+ return
+ }
+
+ if (dispatcher[kPending] > 0) {
+ if (!deferred) {
+ queueMicrotask(() => {
+ closeClientIfUnused(true)
+ })
+ }
return
}
diff --git a/deps/undici/src/lib/dispatcher/client-h1.js b/deps/undici/src/lib/dispatcher/client-h1.js
index a26b9c014e8..13bc66f9372 100644
--- a/deps/undici/src/lib/dispatcher/client-h1.js
+++ b/deps/undici/src/lib/dispatcher/client-h1.js
@@ -67,6 +67,7 @@ const removeAllListeners = util.removeAllListeners
const kIdleSocketValidation = Symbol('kIdleSocketValidation')
const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout')
const kSocketUsed = Symbol('kSocketUsed')
+const kIdleSince = Symbol('kIdleSince')
const kTypeOfService = Symbol('kTypeOfService')
let extractBody
@@ -1107,6 +1108,19 @@ function scheduleIdleSocketValidation (client, socket) {
})
}
+/**
+ * kIdleSince is recorded when the keep-alive timer is armed, so this never
+ * expires a socket before that timer is due.
+ * @param {import('net').Socket} socket
+ * @returns {boolean}
+ */
+function isIdleSocketExpired (socket) {
+ const parser = socket[kParser]
+ return parser.timeoutType === TIMEOUT_KEEP_ALIVE &&
+ parser.timeoutValue > 0 &&
+ performance.now() - socket[kIdleSince] >= parser.timeoutValue
+}
+
/**
* @param {import('./client.js')} client
*/
@@ -1124,6 +1138,15 @@ function resumeH1 (client) {
socket[kNoRef] = false
}
+ // The keep-alive timer cannot fire while the event loop is blocked, and a
+ // request dispatched from the poll phase passes the idle socket validation
+ // below before that timer or a FIN received during the block is processed.
+ // Check the clock so that an expired socket is not reused.
+ if (client[kRunning] === 0 && client[kPending] > 0 && isIdleSocketExpired(socket)) {
+ util.destroy(socket, new InformationalError('socket idle timeout'))
+ return
+ }
+
if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
if (socket[kIdleSocketValidation] === 0) {
scheduleIdleSocketValidation(client, socket)
@@ -1152,6 +1175,7 @@ function resumeH1 (client) {
if (client[kSize] === 0) {
if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
+ socket[kIdleSince] = performance.now()
socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)
}
} else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
diff --git a/deps/undici/src/lib/dispatcher/client-h2.js b/deps/undici/src/lib/dispatcher/client-h2.js
index 9857b80b1e2..418ef37e922 100644
--- a/deps/undici/src/lib/dispatcher/client-h2.js
+++ b/deps/undici/src/lib/dispatcher/client-h2.js
@@ -91,6 +91,7 @@ const {
HTTP2_HEADER_STATUS,
HTTP2_HEADER_PROTOCOL,
NGHTTP2_NO_ERROR,
+ NGHTTP2_PROTOCOL_ERROR,
NGHTTP2_REFUSED_STREAM
}
} = http2
@@ -300,7 +301,9 @@ function connectH2 (client, socket) {
// refH2Session/unrefH2Session.
refed: true,
ping: {
- interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref()
+ interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref(),
+ // Set while a periodic PING waits for its ack.
+ pending: false
}
}
session[kReceivedGoAway] = false
@@ -565,6 +568,10 @@ function onHttp2ProbeTimeout (session) {
return
}
+ resetUnresponsiveHttp2Session(session)
+}
+
+function resetUnresponsiveHttp2Session (session) {
const err = new SocketError('HTTP/2: connection unresponsive', util.getSocketInfo(session[kSocket]))
session[kError] = err
resetHttp2Session(session, err)
@@ -658,16 +665,27 @@ function onHttp2SendPing (session) {
return
}
- // If no ping sent, do nothing
+ // An unacked PING never calls back, so a connection that silently died
+ // (dropped by a NAT or load balancer, a hung peer) would be kept forever when
+ // no stream times out on it, e.g. when every request is aborted first.
+ if (state.ping.pending) {
+ resetUnresponsiveHttp2Session(session)
+ return
+ }
+
+ state.ping.pending = true
session.ping(onPing.bind(session))
function onPing (err, duration) {
+ state.ping.pending = false
+
const client = this[kClient]
const socket = this[kSocket]
if (err != null) {
const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`)
- socket[kError] = error
+ // Keep the reason the session was torn down if that is what cancelled the PING.
+ socket[kError] ??= error
client[kOnError](error)
} else {
client.emit('ping', duration)
@@ -1684,11 +1702,16 @@ function onError (err) {
// noop error sink so that re-delivery cannot go unhandled.
stream.on('error', noop)
- // Node's HTTP/2 implementation can turn an incomplete Content-Length body
- // into a protocol stream error instead of emitting 'end'. Prefer the
- // content-length mismatch error when the received byte count proves it.
- if (state.responseContentLength != null && state.bytesRead !== state.responseContentLength) {
- err = new ResponseContentLengthMismatchError()
+ // Node may report Content-Length violations as protocol errors.
+ if (
+ (err.code === 'ERR_HTTP2_ERROR' ||
+ (err.code === 'ERR_HTTP2_STREAM_ERROR' && stream.rstCode === NGHTTP2_PROTOCOL_ERROR)) &&
+ state.responseContentLength != null &&
+ state.bytesRead !== state.responseContentLength
+ ) {
+ const mismatch = new ResponseContentLengthMismatchError()
+ mismatch.cause = err
+ err = mismatch
}
if (typeof stream.rstCode === 'number' && stream.rstCode !== NGHTTP2_NO_ERROR) {
diff --git a/deps/undici/src/lib/dispatcher/client.js b/deps/undici/src/lib/dispatcher/client.js
index 05288a5991b..bc55e15bd31 100644
--- a/deps/undici/src/lib/dispatcher/client.js
+++ b/deps/undici/src/lib/dispatcher/client.js
@@ -55,12 +55,14 @@ const {
kHostAuthority,
kResume,
kHTTP2Options,
- kUseMilo
+ kUseMilo,
+ kQueuedAbort
} = require('../core/symbols.js')
const connectH1 = require('./client-h1.js')
const connectH2 = require('./client-h2.js')
const kClosedResolve = Symbol('kClosedResolve')
+const kCancelConnect = Symbol('kCancelConnect')
const getDefaultNodeMaxHeaderSize = http &&
http.maxHeaderSize &&
@@ -322,6 +324,7 @@ class Client extends DispatcherBase {
this[kClosedResolve] = null
this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
this[kHTTPContext] = null
+ this[kCancelConnect] = null
// h2
this[kHTTP2Options] = {
pingInterval: h2Options?.pingInterval ?? pingInterval ?? 60e3,
@@ -402,6 +405,8 @@ class Client extends DispatcherBase {
[kConnect] (cb) {
connect(this)
+ // Asked for explicitly: keep it even if no request waits for it.
+ this[kCancelConnect] = null
this.once('connect', cb)
}
@@ -419,6 +424,15 @@ class Client extends DispatcherBase {
this[kResume](true)
}
+ if (request.abort === null && !request.aborted) {
+ // The request is still waiting for a connection: if its handler listens
+ // to a signal, give it a way to take the request out of the queue.
+ const onQueued = opts[kQueuedAbort]
+ if (onQueued !== undefined) {
+ onQueued((reason) => abortPendingRequest(this, request, reason))
+ }
+ }
+
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
this[kNeedDrain] = 2
}
@@ -469,6 +483,56 @@ class Client extends DispatcherBase {
}
}
+function failQueuedRequest (client, request, reason) {
+ try {
+ request.onQueuedAbort(reason)
+ assert(request.aborted)
+ } catch (err) {
+ client.emit('error', err)
+ }
+}
+
+function abortPendingRequest (client, request, reason) {
+ // The request already settled, or it started and its handler owns the abort.
+ if (request.aborted || request.abort !== null) {
+ return
+ }
+
+ const queue = client[kQueue]
+ const idx = queue.indexOf(request, client[kPendingIdx])
+ if (idx === -1) {
+ return
+ }
+
+ // _resume() may be handing this request to the connection right now, before
+ // onRequestStart runs. Leave it there: the handler aborts it once it starts.
+ if (idx === client[kPendingIdx] && client[kResuming] === 2) {
+ return
+ }
+
+ queue.splice(idx, 1)
+ failQueuedRequest(client, request, reason)
+
+ // The client may no longer be busy: emit 'drain' so a Pool can use it again.
+ client[kResume](true)
+
+ if (client[kCancelConnect] !== null && client[kSize] === 0) {
+ // The drain is emitted in a microtask: check once a Pool had the chance to
+ // hand this client the requests it queued.
+ queueMicrotask(() => cancelUnusedConnect(client))
+ }
+}
+
+// A connection attempt that no request waits for only holds a connection slot,
+// until it connects or times out. Destroy it, so the next request starts a new
+// one instead of waiting for it.
+function cancelUnusedConnect (client) {
+ const cancel = client[kCancelConnect]
+ if (cancel !== null && client[kSize] === 0) {
+ cancel(new InformationalError('no request waits for this connection'))
+ }
+}
+
function onError (client, err) {
if (
client[kRunning] === 0 &&
@@ -515,6 +579,38 @@ function connect (client) {
client[kConnecting] = true
+ // The name this attempt verifies the server's certificate for. While it
+ // connects, its requests can be aborted and _resume() can switch
+ // client[kServerName] to the name of the next queued request.
+ const servername = client[kServerName]
+
+ let calledBack = false
+ let cancelled = false
+
+ // Ends this attempt without a 'connectionError': no request failed, and a
+ // Pool would retire this client.
+ const abandon = (socket, err) => {
+ client[kConnecting] = false
+
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername,
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ })
+ }
+
+ util.destroy(socket.on('error', noop), err)
+ }
+
if (channels.beforeConnect.hasSubscribers) {
channels.beforeConnect.publish({
connectParams: {
@@ -523,7 +619,7 @@ function connect (client) {
protocol,
port,
version: client[kHTTPContext]?.version,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
},
connector: client[kConnector]
@@ -531,16 +627,27 @@ function connect (client) {
}
try {
- client[kConnector]({
+ const connecting = client[kConnector]({
host,
hostname,
protocol,
port,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
}, (err, socket) => {
+ calledBack = true
+
+ if (cancelled) {
+ if (socket) {
+ util.destroy(socket.on('error', noop))
+ }
+ return
+ }
+
+ client[kCancelConnect] = null
+
if (err) {
- handleConnectError(client, err, { host, hostname, protocol, port })
+ handleConnectError(client, err, { host, hostname, protocol, port, servername })
client[kResume]()
return
}
@@ -553,13 +660,21 @@ function connect (client) {
assert(socket)
+ if (client[kServerName] !== servername) {
+ // The server proved its identity for another name than the one the
+ // queued requests are for: never send them on this connection.
+ abandon(socket, new InformationalError('servername changed'))
+ client[kResume]()
+ return
+ }
+
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 })
+ handleConnectError(client, err, { host, hostname, protocol, port, servername })
client[kResume]()
return
}
@@ -579,7 +694,7 @@ function connect (client) {
protocol,
port,
version: client[kHTTPContext]?.version,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
@@ -590,13 +705,23 @@ function connect (client) {
client.emit('connect', client[kUrl], [client])
client[kResume]()
})
+
+ // The attempt can only be cancelled through the socket the connector
+ // returns. The built-in connector returns it; custom connectors may not.
+ if (!calledBack && util.isStream(connecting)) {
+ client[kCancelConnect] = (err) => {
+ cancelled = true
+ client[kCancelConnect] = null
+ abandon(connecting, err)
+ }
+ }
} catch (err) {
- handleConnectError(client, err, { host, hostname, protocol, port })
+ handleConnectError(client, err, { host, hostname, protocol, port, servername })
client[kResume]()
}
}
-function handleConnectError (client, err, { host, hostname, protocol, port }) {
+function handleConnectError (client, err, { host, hostname, protocol, port, servername }) {
if (client.destroyed) {
return
}
@@ -611,7 +736,7 @@ function handleConnectError (client, err, { host, hostname, protocol, port }) {
protocol,
port,
version: client[kHTTPContext]?.version,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
@@ -627,7 +752,8 @@ function handleConnectError (client, err, { host, hostname, protocol, port }) {
util.errorRequest(client, running[i], err)
}
- while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
+ // Only the requests for the name the certificate failed for.
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === servername) {
const request = client[kQueue].splice(client[kPendingIdx], 1)[0]
util.errorRequest(client, request, err)
}
@@ -718,6 +844,9 @@ function _resume (client, sync) {
client[kHTTPContext] = null
resume(client)
})
+ // A pending attempt verifies the server for the previous name, and its
+ // connection is discarded once it connects: do not wait for it.
+ client[kCancelConnect]?.(new InformationalError('servername changed'))
}
if (client[kConnecting]) {
diff --git a/deps/undici/src/lib/dispatcher/dispatcher-base.js b/deps/undici/src/lib/dispatcher/dispatcher-base.js
index 97a4db6e321..7261fd17a90 100644
--- a/deps/undici/src/lib/dispatcher/dispatcher-base.js
+++ b/deps/undici/src/lib/dispatcher/dispatcher-base.js
@@ -190,7 +190,12 @@ class DispatcherBase extends Dispatcher {
handler.onResponseError(null, err)
- return false
+ // The request failed synchronously: no work was queued on this
+ // dispatcher, no capacity was consumed and no 'drain' event will
+ // ever follow. Returning false would make callers (e.g. Pool)
+ // mark this dispatcher as busy waiting for a drain that never
+ // comes, permanently taking it out of rotation.
+ return true
}
}
}
diff --git a/deps/undici/src/lib/dispatcher/dispatcher.js b/deps/undici/src/lib/dispatcher/dispatcher.js
index 11a7ab2b447..ed45263b27c 100644
--- a/deps/undici/src/lib/dispatcher/dispatcher.js
+++ b/deps/undici/src/lib/dispatcher/dispatcher.js
@@ -1,6 +1,7 @@
'use strict'
const EventEmitter = require('node:events')
-const { kOriginless, kUrl } = require('../core/symbols')
+const { InvalidArgumentError } = require('../core/errors')
+const { kOriginless, kUrl, kInterceptorKind } = require('../core/symbols')
class Dispatcher extends EventEmitter {
dispatch () {
@@ -24,6 +25,8 @@ class Dispatcher extends EventEmitter {
: this[kUrl]?.origin
let dispatch = this.dispatch.bind(this)
+ const orderSensitiveKinds = []
+
for (const interceptor of interceptors) {
if (interceptor == null) {
continue
@@ -33,6 +36,10 @@ class Dispatcher extends EventEmitter {
throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`)
}
+ if (interceptor[kInterceptorKind] != null) {
+ orderSensitiveKinds.push(interceptor[kInterceptorKind])
+ }
+
dispatch = interceptor(dispatch, interceptorOrigin)
if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) {
@@ -40,6 +47,20 @@ class Dispatcher extends EventEmitter {
}
}
+ // Several shipped interceptors are order-sensitive: they cooperate through
+ // the redirect history threaded on the request context, and the cache
+ // handler only receives it when the redirect interceptor is composed before
+ // the cache interceptor. Composing `cache` before `redirect` silently
+ // disables the cache's redirect-origin guards (cross-origin cache
+ // poisoning, credential-bearing redirect replay), so fail fast instead of
+ // storing an attacker-controlled or cross-principal response under a key
+ // the application trusts.
+ const cacheIndex = orderSensitiveKinds.indexOf('cache')
+ const redirectIndex = orderSensitiveKinds.indexOf('redirect')
+ if (cacheIndex !== -1 && redirectIndex !== -1 && cacheIndex < redirectIndex) {
+ throw new InvalidArgumentError('the cache interceptor must be composed after the redirect interceptor; composing the cache before the redirect disables the cache\'s cross-origin and credential redirect guards (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG)')
+ }
+
const originalDispatch = dispatch
const self = this
dispatch = function (opts, handler) {
diff --git a/deps/undici/src/lib/dispatcher/pool-base.js b/deps/undici/src/lib/dispatcher/pool-base.js
index ebd3a52784b..5453fd29c33 100644
--- a/deps/undici/src/lib/dispatcher/pool-base.js
+++ b/deps/undici/src/lib/dispatcher/pool-base.js
@@ -4,7 +4,8 @@ const { AsyncResource } = require('node:async_hooks')
const { PoolStats } = require('../util/stats.js')
const DispatcherBase = require('./dispatcher-base')
const FixedQueue = require('./fixed-queue')
-const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('../core/symbols')
+const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require('../core/symbols')
+const { createAbortedController } = require('../core/request')
const kClients = Symbol('clients')
const kNeedDrain = Symbol('needDrain')
@@ -23,6 +24,8 @@ const kAddClient = Symbol('add client')
const kRemoveClient = Symbol('remove client')
const kRetireClient = Symbol('retire client')
const kRetiring = Symbol('retiring clients')
+const kShiftQueue = Symbol('shift queue')
+const kAbortQueued = Symbol('abort queued')
// Closes every live client, including clients that have been
// taken out of rotation but are still finishing their own
@@ -36,6 +39,8 @@ class QueuedRequest extends AsyncResource {
super('UNDICI_POOL_QUEUED_REQUEST')
this.opts = opts
this.handler = handler
+ // Cleared once the request leaves the queue, so a late abort is ignored.
+ this.queued = true
}
dispatch (dispatcher) {
@@ -75,17 +80,15 @@ class PoolBase extends DispatcherBase {
return
}
- const queue = this[kQueue]
let needDrain = false
this[kOnClientDrain](client)
while (!needDrain) {
- const item = queue.shift()
+ const item = this[kShiftQueue]()
if (!item) {
break
}
- this[kQueued]--
needDrain = !item.dispatch(client)
}
@@ -98,7 +101,7 @@ class PoolBase extends DispatcherBase {
// negotiated and hit maxConcurrentStreams. Hand the rest to other
// clients, creating new ones up to the connection limit, instead of
// leaving them for this client to drain one batch at a time.
- if (!queue.isEmpty()) {
+ if (this[kQueued] > 0) {
return this[kDrainQueue](origin, targets)
}
}
@@ -108,7 +111,7 @@ class PoolBase extends DispatcherBase {
this.emit('drain', origin, [this, ...targets])
}
- if (this[kClosedResolve] && queue.isEmpty()) {
+ if (this[kClosedResolve] && this[kQueued] === 0) {
return closeClients(this).then(this[kClosedResolve])
}
}
@@ -118,23 +121,31 @@ class PoolBase extends DispatcherBase {
[kOnClientDrain] () {}
[kDrainQueue] (origin, targets) {
- const queue = this[kQueue]
let hasDispatcher = true
- while (!queue.isEmpty()) {
- const dispatcher = this[kGetDispatcher]()
+ while (this[kQueued] > 0) {
+ let dispatcher
+ try {
+ dispatcher = this[kGetDispatcher]()
+ } catch (err) {
+ // Selection failed before a dispatcher took ownership of this item.
+ const item = this[kShiftQueue]()
+ item.runInAsyncScope(item.handler.onResponseError, item.handler, null, err)
+ // The error handler may synchronously dispatch and consume capacity.
+ hasDispatcher = !this.destroyed && this[kHasDispatcher](false)
+ continue
+ }
if (!dispatcher) {
hasDispatcher = false
break
}
- const item = queue.shift()
- this[kQueued]--
+ const item = this[kShiftQueue]()
if (!item.dispatch(dispatcher)) {
dispatcher[kNeedDrain] = true
this[kOnClientBusy](dispatcher)
- hasDispatcher = this[kHasDispatcher]()
+ hasDispatcher = this[kHasDispatcher](false)
if (!hasDispatcher) {
break
}
@@ -146,11 +157,48 @@ class PoolBase extends DispatcherBase {
this.emit('drain', origin, [this, ...targets])
}
- if (this[kClosedResolve] && queue.isEmpty()) {
+ if (this[kClosedResolve] && this[kQueued] === 0) {
return closeClients(this).then(this[kClosedResolve])
}
}
+ // Aborted requests stay in the queue as tombstones (queued === false) and
+ // are skipped here; kQueued only counts the live ones.
+ [kShiftQueue] () {
+ const queue = this[kQueue]
+ let item = queue.shift()
+ while (item !== null && item.queued === false) {
+ item = queue.shift()
+ }
+
+ if (item !== null) {
+ this[kQueued]--
+ item.queued = false
+ }
+
+ return item
+ }
+
+ // Called through the handler's kQueuedAbort hook when a queued request is
+ // aborted.
+ [kAbortQueued] (item, reason) {
+ if (!item.queued) {
+ return
+ }
+
+ const { handler } = item
+ item.queued = false
+ item.opts = null
+ item.handler = null
+ this[kQueued]--
+
+ item.runInAsyncScope(handler.onResponseError, handler, createAbortedController(reason), reason)
+
+ if (this[kClosedResolve] && this[kQueued] === 0) {
+ closeClients(this).then(this[kClosedResolve])
+ }
+ }
+
[kOnConnect] = (origin, targets) => {
this.emit('connect', origin, [this, ...targets])
};
@@ -212,7 +260,7 @@ class PoolBase extends DispatcherBase {
}
[kClose] () {
- if (this[kQueue].isEmpty()) {
+ if (this[kQueued] === 0) {
return closeClients(this)
} else {
return new Promise((resolve) => {
@@ -223,7 +271,7 @@ class PoolBase extends DispatcherBase {
[kDestroy] (err) {
while (true) {
- const item = this[kQueue].shift()
+ const item = this[kShiftQueue]()
if (!item) {
break
}
@@ -244,9 +292,17 @@ class PoolBase extends DispatcherBase {
const dispatcher = this[kGetDispatcher]()
if (!dispatcher) {
+ const item = new QueuedRequest(opts, handler)
this[kNeedDrain] = true
- this[kQueue].push(new QueuedRequest(opts, handler))
+ this[kQueue].push(item)
this[kQueued]++
+
+ const onQueued = opts[kQueuedAbort]
+ if (onQueued !== undefined) {
+ // Give the handler a way to remove the request from the queue as soon
+ // as it is aborted.
+ onQueued((reason) => this[kAbortQueued](item, reason))
+ }
} else if (!dispatcher.dispatch(opts, handler)) {
dispatcher[kNeedDrain] = true
this[kOnClientBusy](dispatcher)
diff --git a/deps/undici/src/lib/dispatcher/pool.js b/deps/undici/src/lib/dispatcher/pool.js
index e44ac84b94f..3e731b6bea4 100644
--- a/deps/undici/src/lib/dispatcher/pool.js
+++ b/deps/undici/src/lib/dispatcher/pool.js
@@ -18,7 +18,7 @@ const {
InvalidArgumentError
} = require('../core/errors')
const util = require('../core/util')
-const { kConnecting, kHTTPContext, kUrl, kQueued } = require('../core/symbols')
+const { kConnecting, kHTTPContext, kHTTP2Session, kRemoteSettings, kUrl, kQueued } = require('../core/symbols')
const buildConnector = require('../core/connect')
const kOptions = Symbol('options')
@@ -116,12 +116,25 @@ class Pool extends PoolBase {
}
if (client === this[kProtocolProbe]) {
- // An h2 Client's drain event releases the requests accumulated during
- // negotiation onto that Client. If ALPN selected h1, release the probe
- // immediately and restore normal Pool fan-out instead.
- if (this[kProtocol] !== 'h2') {
- this[kProtocolProbe] = null
- this[kDrainQueue](origin, targets.slice(1))
+ const releaseProbe = () => {
+ if (client === this[kProtocolProbe]) {
+ this[kProtocolProbe] = null
+ // An empty queue must not release backpressure when this client
+ // is still saturated and the connection limit prevents fan-out.
+ // Check capacity without invoking a factory for unused capacity.
+ if (!this.destroyed && (this[kQueued] > 0 || (!this.closed && this[kHasDispatcher](false)))) {
+ this[kDrainQueue](origin, targets.slice(1))
+ }
+ }
+ }
+ const session = client[kHTTP2Session]
+ // A peer's stream limit can keep the probe busy indefinitely. Once
+ // SETTINGS arrive, queued work may need another connection without
+ // waiting for this client's drain event.
+ if (this[kProtocol] !== 'h2' || session[kRemoteSettings]) {
+ releaseProbe()
+ } else {
+ session.once('remoteSettings', releaseProbe)
}
}
})
@@ -200,7 +213,7 @@ class Pool extends PoolBase {
}
}
- [kHasDispatcher] () {
+ [kHasDispatcher] (create = true) {
const clientTtlOption = this[kOptions].clientTtl
for (let i = 0; i < this[kClients].length; i++) {
const client = this[kClients][i]
@@ -218,7 +231,7 @@ class Pool extends PoolBase {
}
if (!this[kConnections] || this[kClients].length < this[kConnections]) {
- createClient(this)
+ if (create) createClient(this)
return true
}
diff --git a/deps/undici/src/lib/dispatcher/proxy-agent.js b/deps/undici/src/lib/dispatcher/proxy-agent.js
index 19319ff8d10..d90ff5930c1 100644
--- a/deps/undici/src/lib/dispatcher/proxy-agent.js
+++ b/deps/undici/src/lib/dispatcher/proxy-agent.js
@@ -159,8 +159,10 @@ class ProxyAgent extends DispatcherBase {
headers: this[kProxyHeaders],
connect,
factory: agentFactory,
- username: opts.username || username,
- password: opts.password || password,
+ // Socks5ProxyAgent decodes the credentials embedded in the URI;
+ // the URL getters return them still percent-encoded.
+ username: opts.username,
+ password: opts.password,
connectTimeout,
proxyTls: opts.proxyTls,
requestTls: opts.requestTls
diff --git a/deps/undici/src/lib/handler/cache-handler.js b/deps/undici/src/lib/handler/cache-handler.js
index 20c96def267..d139853ec59 100644
--- a/deps/undici/src/lib/handler/cache-handler.js
+++ b/deps/undici/src/lib/handler/cache-handler.js
@@ -412,7 +412,7 @@ class CacheHandler {
deleteCachedValue(this.#store, this.#cacheKey)
}
- // Don't have anything to tell us this response is cachable and we're not
+ // Don't have anything to tell us this response is cacheable and we're not
// caching by default
return downstreamOnHeaders()
}
diff --git a/deps/undici/src/lib/handler/retry-handler.js b/deps/undici/src/lib/handler/retry-handler.js
index b7c458b0ea5..19d2585f519 100644
--- a/deps/undici/src/lib/handler/retry-handler.js
+++ b/deps/undici/src/lib/handler/retry-handler.js
@@ -1,7 +1,7 @@
'use strict'
const assert = require('node:assert')
-const { kRetryHandlerDefaultRetry } = require('../core/symbols')
+const { kRetryHandlerDefaultRetry, kQueuedAbort } = require('../core/symbols')
const { RequestRetryError, RequestAbortedError } = require('../core/errors')
const {
hasSafeIterator,
@@ -98,6 +98,11 @@ class RetryController {
}
class RetryHandler {
+ // Takes the retry that waits for a connection out of its queue.
+ #queuedCancel = null
+ // Whether retries are dispatched with a hook that sets #queuedCancel.
+ #tracksQueuedRetry = false
+
constructor (opts, { dispatch, handler }) {
const { retryOptions, ...dispatchOpts } = opts
const {
@@ -561,6 +566,18 @@ class RetryHandler {
}
}
+ if (!this.#tracksQueuedRetry) {
+ // The consumer's controller still targets the earlier attempt, so an
+ // abort would not reach a retry that waits for a connection. Keep the
+ // function that takes it out of its queue; the caller's hook still runs.
+ this.#tracksQueuedRetry = true
+ const onQueued = this.opts[kQueuedAbort]
+ this.opts[kQueuedAbort] = (cancel) => {
+ this.#queuedCancel = cancel
+ onQueued?.(cancel)
+ }
+ }
+
try {
this.retryCountCheckpoint = this.retryCount
this.dispatch(this.opts, this)
@@ -622,6 +639,15 @@ class RetryHandler {
}
#onAbort (reason) {
+ // A retry that waits for a connection is taken out of its queue: its
+ // dispatcher fails it with an aborted controller, so onResponseError passes
+ // the abort on instead of retrying. Once the retry started, this does nothing.
+ const cancel = this.#queuedCancel
+ if (cancel !== null) {
+ this.#queuedCancel = null
+ cancel(reason ?? new RequestAbortedError())
+ }
+
// A consumer abort lands on the controller proxy. If the retry policy is
// still deciding (typically holding a backoff timer), cancel the wait and
// surface the abort immediately instead of letting the request hang until
diff --git a/deps/undici/src/lib/interceptor/cache.js b/deps/undici/src/lib/interceptor/cache.js
index 60d2522d1ff..eb71c531c57 100644
--- a/deps/undici/src/lib/interceptor/cache.js
+++ b/deps/undici/src/lib/interceptor/cache.js
@@ -18,7 +18,9 @@ const {
isEtagUsable
} = require('../util/cache.js')
const { AbortError } = require('../core/errors.js')
+const { kQueuedAbort } = require('../core/symbols.js')
const { parseHttpDate } = require('../util/date.js')
+const { kInterceptorKind } = require('../core/symbols.js')
/**
* @param {(string | RegExp)[] | undefined} origins
@@ -541,7 +543,10 @@ function handleResult (
dispatch(
{
...opts,
- headers
+ headers,
+ // The revalidation is not the caller's request: aborting the
+ // caller must not cancel it while it waits for a connection.
+ [kQueuedAbort]: undefined
},
new CacheHandler(globalOpts, cacheKey, {
// Silent handler that just updates the cache
@@ -665,7 +670,7 @@ module.exports = (opts = {}) => {
}
}
- return (dispatch, interceptorOrigin) => {
+ const interceptor = (dispatch, interceptorOrigin) => {
return (opts, handler) => {
const requestOrigin = getInterceptorOrigin(opts, interceptorOrigin)
if (!requestOrigin || arrayIncludes(safeMethodsToNotCache, opts.method)) {
@@ -768,4 +773,6 @@ module.exports = (opts = {}) => {
}
}
}
+ interceptor[kInterceptorKind] = 'cache'
+ return interceptor
}
diff --git a/deps/undici/src/lib/interceptor/decompress.js b/deps/undici/src/lib/interceptor/decompress.js
index 0b6d2bcc0cf..835c9fa7794 100644
--- a/deps/undici/src/lib/interceptor/decompress.js
+++ b/deps/undici/src/lib/interceptor/decompress.js
@@ -105,8 +105,6 @@ function createMaxSizeLimiter (maxSize) {
})
}
-let warningEmitted = /** @type {boolean} */ (false)
-
/**
* @typedef {Object} DecompressHandlerOptions
* @property {number[]|Readonly<number[]>} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for
@@ -550,15 +548,6 @@ class DecompressHandler extends DecoratorHandler {
* @returns {Function} - Interceptor function
*/
function createDecompressInterceptor (options = {}) {
- // Emit experimental warning only once
- if (!warningEmitted) {
- process.emitWarning(
- 'DecompressInterceptor is experimental and subject to change',
- 'ExperimentalWarning'
- )
- warningEmitted = true
- }
-
return (dispatch) => {
return (opts, handler) => {
if (opts.method === 'HEAD') {
diff --git a/deps/undici/src/lib/interceptor/deduplicate.js b/deps/undici/src/lib/interceptor/deduplicate.js
index 12598130e8f..c8e5b934c5a 100644
--- a/deps/undici/src/lib/interceptor/deduplicate.js
+++ b/deps/undici/src/lib/interceptor/deduplicate.js
@@ -4,6 +4,7 @@ const diagnosticsChannel = require('node:diagnostics_channel')
const util = require('../core/util')
const DeduplicationHandler = require('../handler/deduplication-handler')
const { getInterceptorOrigin, normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require('../util/cache.js')
+const { kInterceptorKind } = require('../core/symbols.js')
const pendingRequestsChannel = diagnosticsChannel.channel('undici:request:pending-requests')
@@ -57,7 +58,7 @@ module.exports = (opts = {}) => {
*/
const pendingRequests = new Map()
- return (dispatch, interceptorOrigin) => {
+ const interceptor = (dispatch, interceptorOrigin) => {
return (opts, handler) => {
const requestOrigin = getInterceptorOrigin(opts, interceptorOrigin)
if (!requestOrigin || opts.upgrade || methods.includes(opts.method) === false) {
@@ -115,4 +116,6 @@ module.exports = (opts = {}) => {
return dispatch(opts, deduplicationHandler)
}
}
+ interceptor[kInterceptorKind] = 'deduplicate'
+ return interceptor
}
diff --git a/deps/undici/src/lib/interceptor/redirect.js b/deps/undici/src/lib/interceptor/redirect.js
index 34e9b321197..d772100be9a 100644
--- a/deps/undici/src/lib/interceptor/redirect.js
+++ b/deps/undici/src/lib/interceptor/redirect.js
@@ -1,9 +1,10 @@
'use strict'
const RedirectHandler = require('../handler/redirect-handler')
+const { kInterceptorKind } = require('../core/symbols.js')
function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections, throwOnMaxRedirect: defaultThrowOnMaxRedirect, stripHeadersOnRedirect: defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect: defaultStripHeadersOnCrossOriginRedirect } = {}) {
- return (dispatch) => {
+ const interceptor = (dispatch) => {
return function Intercept (opts, handler) {
const { maxRedirections = defaultMaxRedirections, throwOnMaxRedirect = defaultThrowOnMaxRedirect, stripHeadersOnRedirect = defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect = defaultStripHeadersOnCrossOriginRedirect, ...rest } = opts
@@ -16,6 +17,8 @@ function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections, t
return dispatch(dispatchOpts, redirectHandler)
}
}
+ interceptor[kInterceptorKind] = 'redirect'
+ return interceptor
}
module.exports = createRedirectInterceptor
diff --git a/deps/undici/src/lib/util/cache.js b/deps/undici/src/lib/util/cache.js
index 12f29e9181f..9aabf188d55 100644
--- a/deps/undici/src/lib/util/cache.js
+++ b/deps/undici/src/lib/util/cache.js
@@ -650,7 +650,7 @@ function isInvalidOrWildcardVaryHeader (varyHeader) {
/**
* Note: this deviates from the spec a little. Empty etags ("", W/"") are valid,
- * however, including them in cached resposnes serves little to no purpose.
+ * however, including them in cached responses serves little to no purpose.
*
* @see https://www.rfc-editor.org/rfc/rfc9110.html#name-etag
*
diff --git a/deps/undici/src/lib/util/timers.js b/deps/undici/src/lib/util/timers.js
index 14984d42ef2..11ac022995d 100644
--- a/deps/undici/src/lib/util/timers.js
+++ b/deps/undici/src/lib/util/timers.js
@@ -194,7 +194,7 @@ function refreshTimeout () {
// method (e.g. mocked timers in tests).
if (fastNowTimeout?.refresh) {
fastNowTimeout.refresh()
- // fastNowTimeout is not instantiated yet or refresh is not availabe,
+ // fastNowTimeout is not instantiated yet or refresh is not available,
// create a new Timer.
} else {
clearTimeout(fastNowTimeout)
diff --git a/deps/undici/src/lib/web/fetch/formdata.js b/deps/undici/src/lib/web/fetch/formdata.js
index e7b8c4c3fb2..c42deafe2d7 100644
--- a/deps/undici/src/lib/web/fetch/formdata.js
+++ b/deps/undici/src/lib/web/fetch/formdata.js
@@ -163,19 +163,12 @@ class FormData {
}
[nodeUtil.inspect.custom] (depth, options) {
- const state = this.#state.reduce((a, b) => {
- if (a[b.name]) {
- if (Array.isArray(a[b.name])) {
- a[b.name].push(b.value)
- } else {
- a[b.name] = [a[b.name], b.value]
- }
- } else {
- a[b.name] = b.value
- }
-
- return a
- }, { __proto__: null })
+ const state = Object.groupBy(this.#state, ({ name }) => name)
+ for (const [name, entries] of Object.entries(state)) {
+ state[name] = entries.length === 1
+ ? entries[0].value
+ : entries.map(({ value }) => value)
+ }
options.depth ??= depth
options.colors ??= true
diff --git a/deps/undici/src/lib/web/fetch/index.js b/deps/undici/src/lib/web/fetch/index.js
index b90f6c8d866..f65afa1f9cb 100644
--- a/deps/undici/src/lib/web/fetch/index.js
+++ b/deps/undici/src/lib/web/fetch/index.js
@@ -59,7 +59,7 @@ const {
const EE = require('node:events')
const { Readable, pipeline, finished, isErrored, isReadable } = require('node:stream')
const { addAbortListener, bufferToLowerCasedHeaderName } = require('../../core/util')
-const { SocketError } = require('../../core/errors')
+const { SocketError, InformationalError } = require('../../core/errors')
const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url')
const { getGlobalDispatcher } = require('../../global')
const { webidl } = require('../webidl')
@@ -2333,6 +2333,10 @@ async function httpNetworkFetch (
}
}
+ // The response will be exposed without a body, so any content the
+ // server sends is disregarded (see main fetch step 19).
+ this.nullBodyStatus = nullBodyStatus.includes(status)
+
this.body = new Readable({ read: () => controller.resume() })
const onError = (err) => this.onResponseError(controller, err)
@@ -2352,6 +2356,14 @@ async function httpNetworkFetch (
},
onResponseData (controller, chunk) {
+ if (this.nullBodyStatus) {
+ // The server sent content in a response that must not have any.
+ // Nobody can read it, so close the connection instead of waiting
+ // for the server to finish sending it.
+ controller.abort(new InformationalError('response with null body status has content'))
+ return
+ }
+
if (fetchParams.controller.dump) {
return
}
@@ -2391,6 +2403,13 @@ async function httpNetworkFetch (
fetchParams.controller.off('terminated', this.abort)
}
+ if (this.nullBodyStatus) {
+ // The response has no body, so a failure while receiving the
+ // disregarded content must not turn it into a network error.
+ this.body?.destroy()
+ return
+ }
+
if (
request.mode === 'websocket' &&
allowH2 !== false &&
diff --git a/deps/undici/src/lib/web/fetch/util.js b/deps/undici/src/lib/web/fetch/util.js
index c51c89d2fb4..46c50d43939 100644
--- a/deps/undici/src/lib/web/fetch/util.js
+++ b/deps/undici/src/lib/web/fetch/util.js
@@ -560,7 +560,7 @@ function stripURLForReferrer (url, originOnly = false) {
return url
}
-const isPotentialleTrustworthyIPv4 = RegExp.prototype.test
+const isPotentiallyTrustworthyIPv4 = RegExp.prototype.test
.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/)
const isPotentiallyTrustworthyIPv6 = RegExp.prototype.test
@@ -583,7 +583,7 @@ function isOriginIPPotentiallyTrustworthy (origin) {
}
// IPv4
- return isPotentialleTrustworthyIPv4(origin)
+ return isPotentiallyTrustworthyIPv4(origin)
}
/**
diff --git a/deps/undici/src/package-lock.json b/deps/undici/src/package-lock.json
index 63b2cd1746a..f2c4547fb1a 100644
--- a/deps/undici/src/package-lock.json
+++ b/deps/undici/src/package-lock.json
@@ -1,15 +1,15 @@
{
"name": "undici",
- "version": "8.12.4",
+ "version": "8.13.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "undici",
- "version": "8.12.4",
+ "version": "8.13.1",
"license": "MIT",
"devDependencies": {
- "@fastify/busboy": "3.2.4",
+ "@fastify/busboy": "3.2.5",
"@matteo.collina/tspl": "^0.2.0",
"@metcoder95/https-pem": "^1.0.0",
"@sinonjs/fake-timers": "^12.0.0",
@@ -1131,20 +1131,37 @@
}
},
"node_modules/@eslint/config-array": {
- "version": "0.23.5",
- "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
- "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",
+ "version": "0.23.6",
+ "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz",
+ "integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@eslint/object-schema": "^3.0.5",
"debug": "^4.3.1",
- "minimatch": "^10.2.4"
+ "minimatch": "^11.0.5"
},
"engines": {
"node": "^20.19.0 || ^22.13.0 || >=24"
}
},
+ "node_modules/@eslint/config-array/node_modules/minimatch": {
+ "version": "11.0.8",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz",
+ "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/@eslint/config-helpers": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",
@@ -1196,9 +1213,9 @@
}
},
"node_modules/@fastify/busboy": {
- "version": "3.2.4",
- "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.4.tgz",
- "integrity": "sha512-lQS8xcXT54rdJb+wlG/Q7SMSdtkZEpLPHooSDUZyyZm9LJD7X1kONPhVoPaHq+dsPtWUGGLIz9gBNhs9qKbylw==",
+ "version": "3.2.5",
+ "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.5.tgz",
+ "integrity": "sha512-y8MTAeBlEQUNVnskmZQwpseZN3EgCksQNOULlfxWY6o6VEqh01+oExMgbM7gN6YLQ8pNDYeweNPKJRt8jQm2ZQ==",
"dev": true,
"license": "MIT"
},
@@ -1297,6 +1314,13 @@
"node": ">=12"
}
},
+ "node_modules/@isaacs/nonrecursive-glob-match": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
+ "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0"
+ },
"node_modules/@istanbuljs/load-nyc-config": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz",
@@ -4557,9 +4581,9 @@
}
},
"node_modules/eslint": {
- "version": "10.13.0",
- "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.13.0.tgz",
- "integrity": "sha512-UohDjD4zSzEwhf58M3O7vc/ycc8O1I7dNlhtD0WxE8Px8EHNJKtUwzBqrzeGhisRuv2ag4sAYswszCJRgKXYUg==",
+ "version": "10.15.0",
+ "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz",
+ "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==",
"dev": true,
"license": "MIT",
"workspaces": [
@@ -4568,11 +4592,11 @@
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.2",
- "@eslint/config-array": "^0.23.5",
+ "@eslint/config-array": "^0.23.6",
"@eslint/config-helpers": "^0.7.0",
"@eslint/core": "^1.2.1",
"@eslint/plugin-kit": "^0.7.3",
- "@humanfs/node": "^0.16.6",
+ "@humanfs/node": "^0.16.8",
"@humanwhocodes/module-importer": "^1.0.1",
"@humanwhocodes/retry": "^0.4.2",
"@types/estree": "^1.0.6",
@@ -4593,7 +4617,7 @@
"imurmurhash": "^0.1.4",
"is-glob": "^4.0.0",
"json-stable-stringify-without-jsonify": "^1.0.1",
- "minimatch": "^10.2.5",
+ "minimatch": "^11.0.5",
"natural-compare": "^1.4.0",
"optionator": "^0.9.3"
},
@@ -4942,6 +4966,23 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/eslint/node_modules/minimatch": {
+ "version": "11.0.8",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz",
+ "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/nonrecursive-glob-match": "^1.1.0",
+ "brace-expansion": "^5.0.12"
+ },
+ "engines": {
+ "node": "20 || >=22"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
"node_modules/eslint/node_modules/p-locate": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
@@ -7195,9 +7236,9 @@
"license": "MIT"
},
"node_modules/node-forge": {
- "version": "1.4.2",
- "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.2.tgz",
- "integrity": "sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==",
+ "version": "1.4.3",
+ "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz",
+ "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==",
"dev": true,
"license": "(BSD-3-Clause OR GPL-2.0)",
"engines": {
@@ -9032,9 +9073,9 @@
}
},
"node_modules/ws": {
- "version": "8.22.0",
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz",
- "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==",
+ "version": "8.23.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
+ "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
"dev": true,
"license": "MIT",
"engines": {
diff --git a/deps/undici/src/package.json b/deps/undici/src/package.json
index d05d075a005..ba9f11bd61e 100644
--- a/deps/undici/src/package.json
+++ b/deps/undici/src/package.json
@@ -1,6 +1,6 @@
{
"name": "undici",
- "version": "8.12.4",
+ "version": "8.13.1",
"description": "An HTTP/1.1 client, written from scratch for Node.js",
"homepage": "https://undici.nodejs.org",
"bugs": {
@@ -93,7 +93,7 @@
"test:node-test": "borp --timeout 180000 -p \"test/node-test/**/*.js\"",
"test:tdd": "borp --timeout 180000 --expose-gc -p \"test/*.js\"",
"test:tdd:node-test": "borp --timeout 180000 -p \"test/node-test/**/*.js\" -w",
- "test:typescript": "tsd && tsc test/imports/undici-import.ts --typeRoots ./types --noEmit && tsc ./types/*.d.ts --noEmit --typeRoots ./types",
+ "test:typescript": "tsd && tsc test/imports/undici-import.ts --typeRoots ./types --noEmit && tsc -p tsconfig.types.json",
"test:webidl": "borp --timeout 180000 -p \"test/webidl/*.js\"",
"test:websocket": "borp --timeout 180000 -p \"test/websocket/**/*.js\"",
"test:websocket:autobahn": "node test/autobahn/client.js",
@@ -111,7 +111,7 @@
"prepare": "husky && node ./scripts/platform-shell.js"
},
"devDependencies": {
- "@fastify/busboy": "3.2.4",
+ "@fastify/busboy": "3.2.5",
"@matteo.collina/tspl": "^0.2.0",
"@metcoder95/https-pem": "^1.0.0",
"@sinonjs/fake-timers": "^12.0.0",
diff --git a/deps/undici/src/tsconfig.types.json b/deps/undici/src/tsconfig.types.json
new file mode 100644
index 00000000000..8ae81f8b261
--- /dev/null
+++ b/deps/undici/src/tsconfig.types.json
@@ -0,0 +1,7 @@
+{
+ "compilerOptions": {
+ "noEmit": true,
+ "typeRoots": ["./types"]
+ },
+ "include": ["types/**/*.d.ts"]
+}
diff --git a/deps/undici/src/types/retry-handler.d.ts b/deps/undici/src/types/retry-handler.d.ts
index 180cde92166..ccb73c86282 100644
--- a/deps/undici/src/types/retry-handler.d.ts
+++ b/deps/undici/src/types/retry-handler.d.ts
@@ -78,7 +78,7 @@ declare namespace RetryHandler {
*/
minTimeout?: number;
/**
- * Factior to multiply the timeout factor between retries.
+ * Factor to multiply the timeout factor between retries.
*
* @type {number}
* @memberof RetryOptions
diff --git a/deps/undici/undici.js b/deps/undici/undici.js
index 552dafce800..f2aca61248b 100644
--- a/deps/undici/undici.js
+++ b/deps/undici/undici.js
@@ -615,6 +615,7 @@ var require_symbols = __commonJS({
kMaxResponseSize: /* @__PURE__ */ Symbol("max response size"),
kHTTP2Session: /* @__PURE__ */ Symbol("http2Session"),
kHTTP2Options: /* @__PURE__ */ Symbol("http2 options"),
+ kQueuedAbort: /* @__PURE__ */ Symbol("queued abort"),
kHTTP2SessionState: /* @__PURE__ */ Symbol("http2Session state"),
kRetryHandlerDefaultRetry: /* @__PURE__ */ Symbol("retry agent default retry"),
kConstruct: /* @__PURE__ */ Symbol("constructable"),
@@ -632,7 +633,8 @@ var require_symbols = __commonJS({
kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"),
kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"),
kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"),
- kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent")
+ kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent"),
+ kInterceptorKind: /* @__PURE__ */ Symbol("interceptor kind")
};
}
});
@@ -642,7 +644,8 @@ var require_dispatcher = __commonJS({
"lib/dispatcher/dispatcher.js"(exports2, module2) {
"use strict";
var EventEmitter = require("node:events");
- var { kOriginless, kUrl } = require_symbols();
+ var { InvalidArgumentError } = require_errors();
+ var { kOriginless, kUrl, kInterceptorKind } = require_symbols();
var Dispatcher2 = class extends EventEmitter {
static {
__name(this, "Dispatcher");
@@ -660,6 +663,7 @@ var require_dispatcher = __commonJS({
const interceptors = Array.isArray(args[0]) ? args[0] : args;
const interceptorOrigin = this[kOriginless] === true ? null : this[kUrl]?.origin;
let dispatch = this.dispatch.bind(this);
+ const orderSensitiveKinds = [];
for (const interceptor of interceptors) {
if (interceptor == null) {
continue;
@@ -667,11 +671,19 @@ var require_dispatcher = __commonJS({
if (typeof interceptor !== "function") {
throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`);
}
+ if (interceptor[kInterceptorKind] != null) {
+ orderSensitiveKinds.push(interceptor[kInterceptorKind]);
+ }
dispatch = interceptor(dispatch, interceptorOrigin);
if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) {
throw new TypeError("invalid interceptor");
}
}
+ const cacheIndex = orderSensitiveKinds.indexOf("cache");
+ const redirectIndex = orderSensitiveKinds.indexOf("redirect");
+ if (cacheIndex !== -1 && redirectIndex !== -1 && cacheIndex < redirectIndex) {
+ throw new InvalidArgumentError("the cache interceptor must be composed after the redirect interceptor; composing the cache before the redirect disables the cache's cross-origin and credential redirect guards (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG)");
+ }
const originalDispatch = dispatch;
const self = this;
dispatch = /* @__PURE__ */ __name(function(opts, handler) {
@@ -970,7 +982,7 @@ var require_dispatcher_base = __commonJS({
throw err;
}
handler.onResponseError(null, err);
- return false;
+ return true;
}
}
};
@@ -1095,747 +1107,464 @@ var require_fixed_queue = __commonJS({
}
});
-// lib/dispatcher/pool-base.js
-var require_pool_base = __commonJS({
- "lib/dispatcher/pool-base.js"(exports2, module2) {
+// lib/util/timers.js
+var require_timers = __commonJS({
+ "lib/util/timers.js"(exports2, module2) {
"use strict";
- var { AsyncResource } = require("node:async_hooks");
- var { PoolStats } = require_stats();
- var DispatcherBase = require_dispatcher_base();
- var FixedQueue = require_fixed_queue();
- var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols();
- var kClients = /* @__PURE__ */ Symbol("clients");
- var kNeedDrain = /* @__PURE__ */ Symbol("needDrain");
- var kQueue = /* @__PURE__ */ Symbol("queue");
- var kClosedResolve = /* @__PURE__ */ Symbol("closed resolve");
- var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
- var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
- var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
- var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
- var kOnClientBusy = /* @__PURE__ */ Symbol("on client busy");
- var kOnClientDrain = /* @__PURE__ */ Symbol("on client drain");
- var kDrainQueue = /* @__PURE__ */ Symbol("drain queue");
- var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher");
- var kHasDispatcher = /* @__PURE__ */ Symbol("has dispatcher");
- var kAddClient = /* @__PURE__ */ Symbol("add client");
- var kRemoveClient = /* @__PURE__ */ Symbol("remove client");
- var kRetireClient = /* @__PURE__ */ Symbol("retire client");
- var kRetiring = /* @__PURE__ */ Symbol("retiring clients");
- var QueuedRequest = class extends AsyncResource {
- static {
- __name(this, "QueuedRequest");
- }
- constructor(opts, handler) {
- super("UNDICI_POOL_QUEUED_REQUEST");
- this.opts = opts;
- this.handler = handler;
- }
- dispatch(dispatcher) {
- return this.runInAsyncScope(dispatcher.dispatch, dispatcher, this.opts, this.handler);
- }
- };
- function closeClients(pool) {
- const closeAll = [];
- for (let i = 0; i < pool[kClients].length; i++) {
- const client = pool[kClients][i];
- if (!client.destroyed) {
- closeAll.push(client.close());
- }
- }
- for (const closed of pool[kRetiring].values()) {
- closeAll.push(closed);
- }
- return Promise.all(closeAll);
- }
- __name(closeClients, "closeClients");
- var PoolBase = class extends DispatcherBase {
- static {
- __name(this, "PoolBase");
- }
- [kQueue] = new FixedQueue();
- [kQueued] = 0;
- [kClients] = [];
- // Clients removed from kClients that have not finished closing,
- // mapped to a promise that settles once they have.
- [kRetiring] = /* @__PURE__ */ new Map();
- [kNeedDrain] = false;
- [kOnDrain](client, origin, targets) {
- if (client.closed || client.destroyed) {
- return;
- }
- const queue = this[kQueue];
- let needDrain = false;
- this[kOnClientDrain](client);
- while (!needDrain) {
- const item = queue.shift();
- if (!item) {
- break;
- }
- this[kQueued]--;
- needDrain = !item.dispatch(client);
+ var fastNow = 0;
+ var RESOLUTION_MS = 1e3;
+ var TICK_MS = (RESOLUTION_MS >> 1) - 1;
+ var fastNowTimeout;
+ var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer");
+ var fastTimers = [];
+ var NOT_IN_LIST = -2;
+ var TO_BE_CLEARED = -1;
+ var PENDING = 0;
+ var ACTIVE = 1;
+ function onTick() {
+ fastNow += TICK_MS;
+ let idx = 0;
+ let len = fastTimers.length;
+ while (idx < len) {
+ const timer = fastTimers[idx];
+ if (timer._state === PENDING) {
+ timer._idleStart = fastNow - TICK_MS;
+ timer._state = ACTIVE;
+ } else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) {
+ timer._state = TO_BE_CLEARED;
+ timer._idleStart = -1;
+ timer._onTimeout(timer._timerArg);
}
- client[kNeedDrain] = needDrain;
- if (needDrain) {
- this[kOnClientBusy](client);
- if (!queue.isEmpty()) {
- return this[kDrainQueue](origin, targets);
+ if (timer._state === TO_BE_CLEARED) {
+ timer._state = NOT_IN_LIST;
+ if (--len !== 0) {
+ fastTimers[idx] = fastTimers[len];
}
- }
- if (!needDrain && this[kNeedDrain]) {
- this[kNeedDrain] = false;
- this.emit("drain", origin, [this, ...targets]);
- }
- if (this[kClosedResolve] && queue.isEmpty()) {
- return closeClients(this).then(this[kClosedResolve]);
+ } else {
+ ++idx;
}
}
- [kOnClientBusy]() {
+ fastTimers.length = len;
+ if (fastTimers.length !== 0) {
+ refreshTimeout();
}
- [kOnClientDrain]() {
+ }
+ __name(onTick, "onTick");
+ function refreshTimeout() {
+ if (fastNowTimeout?.refresh) {
+ fastNowTimeout.refresh();
+ } else {
+ clearTimeout(fastNowTimeout);
+ fastNowTimeout = setTimeout(onTick, TICK_MS);
+ fastNowTimeout?.unref();
}
- [kDrainQueue](origin, targets) {
- const queue = this[kQueue];
- let hasDispatcher = true;
- while (!queue.isEmpty()) {
- const dispatcher = this[kGetDispatcher]();
- if (!dispatcher) {
- hasDispatcher = false;
- break;
- }
- const item = queue.shift();
- this[kQueued]--;
- if (!item.dispatch(dispatcher)) {
- dispatcher[kNeedDrain] = true;
- this[kOnClientBusy](dispatcher);
- hasDispatcher = this[kHasDispatcher]();
- if (!hasDispatcher) {
- break;
- }
- }
- }
- if (hasDispatcher && this[kNeedDrain]) {
- this[kNeedDrain] = false;
- this.emit("drain", origin, [this, ...targets]);
- }
- if (this[kClosedResolve] && queue.isEmpty()) {
- return closeClients(this).then(this[kClosedResolve]);
- }
+ }
+ __name(refreshTimeout, "refreshTimeout");
+ var FastTimer = class {
+ static {
+ __name(this, "FastTimer");
}
- [kOnConnect] = (origin, targets) => {
- this.emit("connect", origin, [this, ...targets]);
- };
- [kOnDisconnect] = (origin, targets, err) => {
- this.emit("disconnect", origin, [this, ...targets], err);
- };
- [kOnConnectionError] = (origin, targets, err) => {
- this.emit("connectionError", origin, [this, ...targets], err);
- };
- get [kBusy]() {
- return this[kNeedDrain];
+ [kFastTimer] = true;
+ /**
+ * The state of the timer, which can be one of the following:
+ * - NOT_IN_LIST (-2)
+ * - TO_BE_CLEARED (-1)
+ * - PENDING (0)
+ * - ACTIVE (1)
+ *
+ * @type {-2|-1|0|1}
+ * @private
+ */
+ _state = NOT_IN_LIST;
+ /**
+ * The number of milliseconds to wait before calling the callback.
+ *
+ * @type {number}
+ * @private
+ */
+ _idleTimeout = -1;
+ /**
+ * The time in milliseconds when the timer was started. This value is used to
+ * calculate when the timer should expire.
+ *
+ * @type {number}
+ * @default -1
+ * @private
+ */
+ _idleStart = -1;
+ /**
+ * The function to be executed when the timer expires.
+ * @type {Function}
+ * @private
+ */
+ _onTimeout;
+ /**
+ * The argument to be passed to the callback when the timer expires.
+ *
+ * @type {*}
+ * @private
+ */
+ _timerArg;
+ /**
+ * @constructor
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should wait
+ * before the specified function or code is executed.
+ * @param {*} arg
+ */
+ constructor(callback, delay, arg) {
+ this._onTimeout = callback;
+ this._idleTimeout = delay;
+ this._timerArg = arg;
+ this.refresh();
}
- get [kConnected]() {
- let ret = 0;
- for (const { [kConnected]: connected } of this[kClients]) {
- ret += connected;
+ /**
+ * Sets the timer's start time to the current time, and reschedules the timer
+ * to call its callback at the previously specified duration adjusted to the
+ * current time.
+ * Using this on a timer that has already called its callback will reactivate
+ * the timer.
+ *
+ * @returns {void}
+ */
+ refresh() {
+ if (this._state === NOT_IN_LIST) {
+ fastTimers.push(this);
}
- return ret;
- }
- get [kFree]() {
- let ret = 0;
- for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) {
- ret += connected && !needDrain;
+ if (!fastNowTimeout || fastTimers.length === 1) {
+ refreshTimeout();
}
- return ret;
+ this._state = PENDING;
}
- get [kPending]() {
- let ret = this[kQueued];
- for (const { [kPending]: pending } of this[kClients]) {
- ret += pending;
- }
- return ret;
+ /**
+ * The `clear` method cancels the timer, preventing it from executing.
+ *
+ * @returns {void}
+ * @private
+ */
+ clear() {
+ this._state = TO_BE_CLEARED;
+ this._idleStart = -1;
}
- get [kRunning]() {
- let ret = 0;
- for (const { [kRunning]: running } of this[kClients]) {
- ret += running;
+ };
+ module2.exports = {
+ /**
+ * The setTimeout() method sets a timer which executes a function once the
+ * timer expires.
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should
+ * wait before the specified function or code is executed.
+ * @param {*} [arg] An optional argument to be passed to the callback function
+ * when the timer expires.
+ * @returns {NodeJS.Timeout|FastTimer}
+ */
+ setTimeout(callback, delay, arg) {
+ return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg);
+ },
+ /**
+ * The clearTimeout method cancels an instantiated Timer previously created
+ * by calling setTimeout.
+ *
+ * @param {NodeJS.Timeout|FastTimer} timeout
+ */
+ clearTimeout(timeout) {
+ if (timeout[kFastTimer]) {
+ timeout.clear();
+ } else {
+ clearTimeout(timeout);
}
- return ret;
+ },
+ /**
+ * The setFastTimeout() method sets a fastTimer which executes a function once
+ * the timer expires.
+ * @param {Function} callback A function to be executed after the timer
+ * expires.
+ * @param {number} delay The time, in milliseconds that the timer should
+ * wait before the specified function or code is executed.
+ * @param {*} [arg] An optional argument to be passed to the callback function
+ * when the timer expires.
+ * @returns {FastTimer}
+ */
+ setFastTimeout(callback, delay, arg) {
+ return new FastTimer(callback, delay, arg);
+ },
+ /**
+ * The clearTimeout method cancels an instantiated FastTimer previously
+ * created by calling setFastTimeout.
+ *
+ * @param {FastTimer} timeout
+ */
+ clearFastTimeout(timeout) {
+ timeout.clear();
+ },
+ /**
+ * The now method returns the value of the internal fast timer clock.
+ *
+ * @returns {number}
+ */
+ now() {
+ return fastNow;
+ },
+ /**
+ * Trigger the onTick function to process the fastTimers array.
+ * Exported for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ * @param {number} [delay=0] The delay in milliseconds to add to the now value.
+ */
+ tick(delay = 0) {
+ fastNow += delay - RESOLUTION_MS + 1;
+ onTick();
+ onTick();
+ },
+ /**
+ * Reset FastTimers.
+ * Exported for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ */
+ reset() {
+ fastNow = 0;
+ fastTimers.length = 0;
+ clearTimeout(fastNowTimeout);
+ fastNowTimeout = null;
+ },
+ /**
+ * Exporting for testing purposes only.
+ * Marking as deprecated to discourage any use outside of testing.
+ * @deprecated
+ */
+ kFastTimer
+ };
+ }
+});
+
+// lib/core/tree.js
+var require_tree = __commonJS({
+ "lib/core/tree.js"(exports2, module2) {
+ "use strict";
+ var {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord
+ } = require_constants();
+ var TstNode = class _TstNode {
+ static {
+ __name(this, "TstNode");
}
- get [kSize]() {
- let ret = this[kQueued];
- for (const { [kSize]: size } of this[kClients]) {
- ret += size;
+ /** @type {any} */
+ value = null;
+ /** @type {null | TstNode} */
+ left = null;
+ /** @type {null | TstNode} */
+ middle = null;
+ /** @type {null | TstNode} */
+ right = null;
+ /** @type {number} */
+ code;
+ /**
+ * @param {string} key
+ * @param {any} value
+ * @param {number} index
+ */
+ constructor(key, value, index) {
+ if (index === void 0 || index >= key.length) {
+ throw new TypeError("Unreachable");
}
- return ret;
- }
- get stats() {
- return new PoolStats(this);
- }
- [kClose]() {
- if (this[kQueue].isEmpty()) {
- return closeClients(this);
+ const code = this.code = key.charCodeAt(index);
+ if (code > 127) {
+ throw new TypeError("key must be ascii string");
+ }
+ if (key.length !== ++index) {
+ this.middle = new _TstNode(key, value, index);
} else {
- return new Promise((resolve) => {
- this[kClosedResolve] = resolve;
- });
+ this.value = value;
}
}
- [kDestroy](err) {
+ /**
+ * @param {string} key
+ * @param {any} value
+ * @returns {void}
+ */
+ add(key, value) {
+ const length = key.length;
+ if (length === 0) {
+ throw new TypeError("Unreachable");
+ }
+ let index = 0;
+ let node = this;
while (true) {
- const item = this[kQueue].shift();
- if (!item) {
+ const code = key.charCodeAt(index);
+ if (code > 127) {
+ throw new TypeError("key must be ascii string");
+ }
+ if (node.code === code) {
+ if (length === ++index) {
+ node.value = value;
+ break;
+ } else if (node.middle !== null) {
+ node = node.middle;
+ } else {
+ node.middle = new _TstNode(key, value, index);
+ break;
+ }
+ } else if (node.code < code) {
+ if (node.left !== null) {
+ node = node.left;
+ } else {
+ node.left = new _TstNode(key, value, index);
+ break;
+ }
+ } else if (node.right !== null) {
+ node = node.right;
+ } else {
+ node.right = new _TstNode(key, value, index);
break;
}
- item.handler.onResponseError(null, err);
- }
- const destroyAll = new Array(this[kClients].length);
- for (let i = 0; i < this[kClients].length; i++) {
- destroyAll[i] = this[kClients][i].destroy(err);
- }
- for (const client of this[kRetiring].keys()) {
- destroyAll.push(client.destroy(err));
- }
- return Promise.all(destroyAll);
- }
- [kDispatch](opts, handler) {
- const dispatcher = this[kGetDispatcher]();
- if (!dispatcher) {
- this[kNeedDrain] = true;
- this[kQueue].push(new QueuedRequest(opts, handler));
- this[kQueued]++;
- } else if (!dispatcher.dispatch(opts, handler)) {
- dispatcher[kNeedDrain] = true;
- this[kOnClientBusy](dispatcher);
- this[kNeedDrain] = !this[kHasDispatcher]();
}
- return !this[kNeedDrain];
}
- [kHasDispatcher]() {
- for (let i = 0; i < this[kClients].length; i++) {
- const dispatcher = this[kClients][i];
- if (!dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true) {
- return true;
+ /**
+ * @param {Uint8Array} key
+ * @returns {TstNode | null}
+ */
+ search(key) {
+ const keylength = key.length;
+ let index = 0;
+ let node = this;
+ while (node !== null && index < keylength) {
+ let code = key[index];
+ if (code <= 90 && code >= 65) {
+ code |= 32;
+ }
+ while (node !== null) {
+ if (code === node.code) {
+ if (keylength === ++index) {
+ return node;
+ }
+ node = node.middle;
+ break;
+ }
+ node = node.code < code ? node.left : node.right;
}
}
- return false;
+ return null;
}
- [kAddClient](client) {
- client.on("drain", this[kOnDrain].bind(this, client)).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
- this[kClients].push(client);
- if (this[kNeedDrain]) {
- queueMicrotask(() => {
- if (this[kNeedDrain] && !client[kNeedDrain]) {
- this[kOnDrain](client, client[kUrl], [client, this]);
- }
- });
- }
- return this;
+ };
+ var TernarySearchTree = class {
+ static {
+ __name(this, "TernarySearchTree");
}
- // Takes a client out of rotation. A closed client no longer takes requests
- // from the pool queue (see kOnDrain), but it finishes the requests it
- // already has. Until it has, pool.close() waits for it and pool.destroy()
- // destroys it.
- [kRetireClient](client) {
- const idx = this[kClients].indexOf(client);
- if (idx !== -1) {
- this[kClients].splice(idx, 1);
- }
- if (client.destroyed || this[kRetiring].has(client)) {
- return;
+ /** @type {TstNode | null} */
+ node = null;
+ /**
+ * @param {string} key
+ * @param {any} value
+ * @returns {void}
+ * */
+ insert(key, value) {
+ if (this.node === null) {
+ this.node = new TstNode(key, value, 0);
+ } else {
+ this.node.add(key, value);
}
- let done = false;
- let resolveClosed;
- const closed = new Promise((resolve) => {
- resolveClosed = resolve;
- });
- this[kRetiring].set(client, closed);
- client.close(() => {
- if (!done) {
- done = true;
- this[kRetiring].delete(client);
- resolveClosed();
- }
- });
}
- [kRemoveClient](client) {
- this[kRetireClient](client);
- this[kNeedDrain] = !this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
+ /**
+ * @param {Uint8Array} key
+ * @returns {any}
+ */
+ lookup(key) {
+ return this.node?.search(key)?.value ?? null;
}
};
+ var tree = new TernarySearchTree();
+ for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]];
+ tree.insert(key, key);
+ }
module2.exports = {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kRetireClient,
- kDrainQueue,
- kOnClientBusy,
- kOnClientDrain,
- kGetDispatcher,
- kHasDispatcher
+ TernarySearchTree,
+ tree
};
}
});
-// lib/util/timers.js
-var require_timers = __commonJS({
- "lib/util/timers.js"(exports2, module2) {
+// lib/core/util.js
+var require_util = __commonJS({
+ "lib/core/util.js"(exports2, module2) {
"use strict";
- var fastNow = 0;
- var RESOLUTION_MS = 1e3;
- var TICK_MS = (RESOLUTION_MS >> 1) - 1;
- var fastNowTimeout;
- var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer");
- var fastTimers = [];
- var NOT_IN_LIST = -2;
- var TO_BE_CLEARED = -1;
- var PENDING = 0;
- var ACTIVE = 1;
- function onTick() {
- fastNow += TICK_MS;
- let idx = 0;
- let len = fastTimers.length;
- while (idx < len) {
- const timer = fastTimers[idx];
- if (timer._state === PENDING) {
- timer._idleStart = fastNow - TICK_MS;
- timer._state = ACTIVE;
- } else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) {
- timer._state = TO_BE_CLEARED;
- timer._idleStart = -1;
- timer._onTimeout(timer._timerArg);
- }
- if (timer._state === TO_BE_CLEARED) {
- timer._state = NOT_IN_LIST;
- if (--len !== 0) {
- fastTimers[idx] = fastTimers[len];
- }
- } else {
- ++idx;
- }
+ var assert = require("node:assert");
+ var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
+ var { IncomingMessage } = require("node:http");
+ var stream = require("node:stream");
+ var net = require("node:net");
+ var { stringify } = require("node:querystring");
+ var { EventEmitter: EE, addAbortListener: addAbortListenerNative } = require("node:events");
+ var timers = require_timers();
+ var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
+ var { headerNameLowerCasedRecord } = require_constants();
+ var { tree } = require_tree();
+ var BodyAsyncIterable = class {
+ static {
+ __name(this, "BodyAsyncIterable");
}
- fastTimers.length = len;
- if (fastTimers.length !== 0) {
- refreshTimeout();
+ constructor(body) {
+ this[kBody] = body;
+ this[kBodyUsed] = false;
+ }
+ async *[Symbol.asyncIterator]() {
+ assert(!this[kBodyUsed], "disturbed");
+ this[kBodyUsed] = true;
+ yield* this[kBody];
}
+ };
+ function noop() {
}
- __name(onTick, "onTick");
- function refreshTimeout() {
- if (fastNowTimeout?.refresh) {
- fastNowTimeout.refresh();
+ __name(noop, "noop");
+ function wrapRequestBody(body) {
+ if (isStream(body)) {
+ if (bodyLength(body) === 0) {
+ body.on("data", function() {
+ assert(false);
+ });
+ }
+ if (typeof body.readableDidRead !== "boolean") {
+ body[kBodyUsed] = false;
+ EE.prototype.on.call(body, "data", function() {
+ this[kBodyUsed] = true;
+ });
+ }
+ return body;
+ } else if (body && typeof body.pipeTo === "function") {
+ return new BodyAsyncIterable(body);
+ } else if (body && isFormDataLike(body)) {
+ return body;
+ } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
+ return new BodyAsyncIterable(body);
} else {
- clearTimeout(fastNowTimeout);
- fastNowTimeout = setTimeout(onTick, TICK_MS);
- fastNowTimeout?.unref();
+ return body;
}
}
- __name(refreshTimeout, "refreshTimeout");
- var FastTimer = class {
- static {
- __name(this, "FastTimer");
+ __name(wrapRequestBody, "wrapRequestBody");
+ function isStream(obj) {
+ return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
+ }
+ __name(isStream, "isStream");
+ function isBlobLike(object) {
+ return object instanceof Blob;
+ }
+ __name(isBlobLike, "isBlobLike");
+ function pathHasQueryOrFragment(url) {
+ return url.includes("?") || url.includes("#");
+ }
+ __name(pathHasQueryOrFragment, "pathHasQueryOrFragment");
+ function serializePathWithQuery(url, queryParams) {
+ if (pathHasQueryOrFragment(url)) {
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".');
}
- [kFastTimer] = true;
- /**
- * The state of the timer, which can be one of the following:
- * - NOT_IN_LIST (-2)
- * - TO_BE_CLEARED (-1)
- * - PENDING (0)
- * - ACTIVE (1)
- *
- * @type {-2|-1|0|1}
- * @private
- */
- _state = NOT_IN_LIST;
- /**
- * The number of milliseconds to wait before calling the callback.
- *
- * @type {number}
- * @private
- */
- _idleTimeout = -1;
- /**
- * The time in milliseconds when the timer was started. This value is used to
- * calculate when the timer should expire.
- *
- * @type {number}
- * @default -1
- * @private
- */
- _idleStart = -1;
- /**
- * The function to be executed when the timer expires.
- * @type {Function}
- * @private
- */
- _onTimeout;
- /**
- * The argument to be passed to the callback when the timer expires.
- *
- * @type {*}
- * @private
- */
- _timerArg;
- /**
- * @constructor
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should wait
- * before the specified function or code is executed.
- * @param {*} arg
- */
- constructor(callback, delay, arg) {
- this._onTimeout = callback;
- this._idleTimeout = delay;
- this._timerArg = arg;
- this.refresh();
- }
- /**
- * Sets the timer's start time to the current time, and reschedules the timer
- * to call its callback at the previously specified duration adjusted to the
- * current time.
- * Using this on a timer that has already called its callback will reactivate
- * the timer.
- *
- * @returns {void}
- */
- refresh() {
- if (this._state === NOT_IN_LIST) {
- fastTimers.push(this);
- }
- if (!fastNowTimeout || fastTimers.length === 1) {
- refreshTimeout();
- }
- this._state = PENDING;
- }
- /**
- * The `clear` method cancels the timer, preventing it from executing.
- *
- * @returns {void}
- * @private
- */
- clear() {
- this._state = TO_BE_CLEARED;
- this._idleStart = -1;
- }
- };
- module2.exports = {
- /**
- * The setTimeout() method sets a timer which executes a function once the
- * timer expires.
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should
- * wait before the specified function or code is executed.
- * @param {*} [arg] An optional argument to be passed to the callback function
- * when the timer expires.
- * @returns {NodeJS.Timeout|FastTimer}
- */
- setTimeout(callback, delay, arg) {
- return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg);
- },
- /**
- * The clearTimeout method cancels an instantiated Timer previously created
- * by calling setTimeout.
- *
- * @param {NodeJS.Timeout|FastTimer} timeout
- */
- clearTimeout(timeout) {
- if (timeout[kFastTimer]) {
- timeout.clear();
- } else {
- clearTimeout(timeout);
- }
- },
- /**
- * The setFastTimeout() method sets a fastTimer which executes a function once
- * the timer expires.
- * @param {Function} callback A function to be executed after the timer
- * expires.
- * @param {number} delay The time, in milliseconds that the timer should
- * wait before the specified function or code is executed.
- * @param {*} [arg] An optional argument to be passed to the callback function
- * when the timer expires.
- * @returns {FastTimer}
- */
- setFastTimeout(callback, delay, arg) {
- return new FastTimer(callback, delay, arg);
- },
- /**
- * The clearTimeout method cancels an instantiated FastTimer previously
- * created by calling setFastTimeout.
- *
- * @param {FastTimer} timeout
- */
- clearFastTimeout(timeout) {
- timeout.clear();
- },
- /**
- * The now method returns the value of the internal fast timer clock.
- *
- * @returns {number}
- */
- now() {
- return fastNow;
- },
- /**
- * Trigger the onTick function to process the fastTimers array.
- * Exported for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- * @param {number} [delay=0] The delay in milliseconds to add to the now value.
- */
- tick(delay = 0) {
- fastNow += delay - RESOLUTION_MS + 1;
- onTick();
- onTick();
- },
- /**
- * Reset FastTimers.
- * Exported for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- */
- reset() {
- fastNow = 0;
- fastTimers.length = 0;
- clearTimeout(fastNowTimeout);
- fastNowTimeout = null;
- },
- /**
- * Exporting for testing purposes only.
- * Marking as deprecated to discourage any use outside of testing.
- * @deprecated
- */
- kFastTimer
- };
- }
-});
-
-// lib/core/tree.js
-var require_tree = __commonJS({
- "lib/core/tree.js"(exports2, module2) {
- "use strict";
- var {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
- } = require_constants();
- var TstNode = class _TstNode {
- static {
- __name(this, "TstNode");
- }
- /** @type {any} */
- value = null;
- /** @type {null | TstNode} */
- left = null;
- /** @type {null | TstNode} */
- middle = null;
- /** @type {null | TstNode} */
- right = null;
- /** @type {number} */
- code;
- /**
- * @param {string} key
- * @param {any} value
- * @param {number} index
- */
- constructor(key, value, index) {
- if (index === void 0 || index >= key.length) {
- throw new TypeError("Unreachable");
- }
- const code = this.code = key.charCodeAt(index);
- if (code > 127) {
- throw new TypeError("key must be ascii string");
- }
- if (key.length !== ++index) {
- this.middle = new _TstNode(key, value, index);
- } else {
- this.value = value;
- }
- }
- /**
- * @param {string} key
- * @param {any} value
- * @returns {void}
- */
- add(key, value) {
- const length = key.length;
- if (length === 0) {
- throw new TypeError("Unreachable");
- }
- let index = 0;
- let node = this;
- while (true) {
- const code = key.charCodeAt(index);
- if (code > 127) {
- throw new TypeError("key must be ascii string");
- }
- if (node.code === code) {
- if (length === ++index) {
- node.value = value;
- break;
- } else if (node.middle !== null) {
- node = node.middle;
- } else {
- node.middle = new _TstNode(key, value, index);
- break;
- }
- } else if (node.code < code) {
- if (node.left !== null) {
- node = node.left;
- } else {
- node.left = new _TstNode(key, value, index);
- break;
- }
- } else if (node.right !== null) {
- node = node.right;
- } else {
- node.right = new _TstNode(key, value, index);
- break;
- }
- }
- }
- /**
- * @param {Uint8Array} key
- * @returns {TstNode | null}
- */
- search(key) {
- const keylength = key.length;
- let index = 0;
- let node = this;
- while (node !== null && index < keylength) {
- let code = key[index];
- if (code <= 90 && code >= 65) {
- code |= 32;
- }
- while (node !== null) {
- if (code === node.code) {
- if (keylength === ++index) {
- return node;
- }
- node = node.middle;
- break;
- }
- node = node.code < code ? node.left : node.right;
- }
- }
- return null;
- }
- };
- var TernarySearchTree = class {
- static {
- __name(this, "TernarySearchTree");
- }
- /** @type {TstNode | null} */
- node = null;
- /**
- * @param {string} key
- * @param {any} value
- * @returns {void}
- * */
- insert(key, value) {
- if (this.node === null) {
- this.node = new TstNode(key, value, 0);
- } else {
- this.node.add(key, value);
- }
- }
- /**
- * @param {Uint8Array} key
- * @returns {any}
- */
- lookup(key) {
- return this.node?.search(key)?.value ?? null;
- }
- };
- var tree = new TernarySearchTree();
- for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]];
- tree.insert(key, key);
- }
- module2.exports = {
- TernarySearchTree,
- tree
- };
- }
-});
-
-// lib/core/util.js
-var require_util = __commonJS({
- "lib/core/util.js"(exports2, module2) {
- "use strict";
- var assert = require("node:assert");
- var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
- var { IncomingMessage } = require("node:http");
- var stream = require("node:stream");
- var net = require("node:net");
- var { stringify } = require("node:querystring");
- var { EventEmitter: EE, addAbortListener: addAbortListenerNative } = require("node:events");
- var timers = require_timers();
- var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
- var { headerNameLowerCasedRecord } = require_constants();
- var { tree } = require_tree();
- var BodyAsyncIterable = class {
- static {
- __name(this, "BodyAsyncIterable");
- }
- constructor(body) {
- this[kBody] = body;
- this[kBodyUsed] = false;
- }
- async *[Symbol.asyncIterator]() {
- assert(!this[kBodyUsed], "disturbed");
- this[kBodyUsed] = true;
- yield* this[kBody];
- }
- };
- function noop() {
- }
- __name(noop, "noop");
- function wrapRequestBody(body) {
- if (isStream(body)) {
- if (bodyLength(body) === 0) {
- body.on("data", function() {
- assert(false);
- });
- }
- if (typeof body.readableDidRead !== "boolean") {
- body[kBodyUsed] = false;
- EE.prototype.on.call(body, "data", function() {
- this[kBodyUsed] = true;
- });
- }
- return body;
- } else if (body && typeof body.pipeTo === "function") {
- return new BodyAsyncIterable(body);
- } else if (body && isFormDataLike(body)) {
- return body;
- } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) {
- return new BodyAsyncIterable(body);
- } else {
- return body;
- }
- }
- __name(wrapRequestBody, "wrapRequestBody");
- function isStream(obj) {
- return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function";
- }
- __name(isStream, "isStream");
- function isBlobLike(object) {
- return object instanceof Blob;
- }
- __name(isBlobLike, "isBlobLike");
- function pathHasQueryOrFragment(url) {
- return url.includes("?") || url.includes("#");
- }
- __name(pathHasQueryOrFragment, "pathHasQueryOrFragment");
- function serializePathWithQuery(url, queryParams) {
- if (pathHasQueryOrFragment(url)) {
- throw new Error('Query params cannot be passed when url already contains "?" or "#".');
- }
- const stringified = stringify(queryParams);
- if (stringified) {
- url += "?" + stringified;
+ const stringified = stringify(queryParams);
+ if (stringified) {
+ url += "?" + stringified;
}
return url;
}
@@ -4460,7 +4189,7 @@ var require_util2 = __commonJS({
return url;
}
__name(stripURLForReferrer, "stripURLForReferrer");
- var isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
+ var isPotentiallyTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/);
var isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/);
function isOriginIPPotentiallyTrustworthy(origin) {
if (origin.includes(":")) {
@@ -4469,7 +4198,7 @@ var require_util2 = __commonJS({
}
return isPotentiallyTrustworthyIPv6(origin);
}
- return isPotentialleTrustworthyIPv4(origin);
+ return isPotentiallyTrustworthyIPv4(origin);
}
__name(isOriginIPPotentiallyTrustworthy, "isOriginIPPotentiallyTrustworthy");
function isOriginPotentiallyTrustworthy(origin) {
@@ -5134,589 +4863,924 @@ var require_formdata = __commonJS({
if (idx === -1) {
return null;
}
- return this.#state[idx].value;
+ return this.#state[idx].value;
+ }
+ getAll(name) {
+ webidl.brandCheck(this, webidl.is.FormData);
+ const prefix = "FormData.getAll";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ name = webidl.converters.USVString(name);
+ return this.#state.filter((entry) => entry.name === name).map((entry) => entry.value);
+ }
+ has(name) {
+ webidl.brandCheck(this, webidl.is.FormData);
+ const prefix = "FormData.has";
+ webidl.argumentLengthCheck(arguments, 1, prefix);
+ name = webidl.converters.USVString(name);
+ return this.#state.findIndex((entry) => entry.name === name) !== -1;
+ }
+ set(name, value, filename = void 0) {
+ webidl.brandCheck(this, webidl.is.FormData);
+ const prefix = "FormData.set";
+ webidl.argumentLengthCheck(arguments, 2, prefix);
+ name = webidl.converters.USVString(name);
+ if (arguments.length === 3 || webidl.is.Blob(value)) {
+ value = webidl.converters.Blob(value, prefix, "value");
+ if (filename !== void 0) {
+ filename = webidl.converters.USVString(filename);
+ }
+ } else {
+ value = webidl.converters.USVString(value);
+ }
+ const entry = makeEntry(name, value, filename);
+ const idx = this.#state.findIndex((entry2) => entry2.name === name);
+ if (idx !== -1) {
+ this.#state = [
+ ...this.#state.slice(0, idx),
+ entry,
+ ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name)
+ ];
+ } else {
+ this.#state.push(entry);
+ }
+ }
+ [nodeUtil.inspect.custom](depth, options) {
+ const state = Object.groupBy(this.#state, ({ name }) => name);
+ for (const [name, entries] of Object.entries(state)) {
+ state[name] = entries.length === 1 ? entries[0].value : entries.map(({ value }) => value);
+ }
+ options.depth ??= depth;
+ options.colors ??= true;
+ const output = nodeUtil.formatWithOptions(options, state);
+ return `FormData ${output.slice(output.indexOf("]") + 2)}`;
+ }
+ static {
+ getFormDataState = /* @__PURE__ */ __name((formData) => formData.#state, "getFormDataState");
+ setFormDataState = /* @__PURE__ */ __name((formData, newState) => {
+ formData.#state = newState;
+ }, "setFormDataState");
+ getFormDataBoundary = /* @__PURE__ */ __name((formData) => {
+ return formData.#boundary ??= `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
+ }, "getFormDataBoundary");
+ webidl.is.FormData = (arg) => {
+ return arg != null && typeof arg === "object" && #state in arg;
+ };
+ }
+ };
+ iteratorMixin("FormData", FormData, getFormDataState, "name", "value", webidl.is.FormData);
+ Object.defineProperties(FormData.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ getAll: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: "FormData",
+ configurable: true
+ }
+ });
+ function makeEntry(name, value, filename) {
+ if (typeof value === "string") {
+ } else {
+ if (!webidl.is.File(value)) {
+ value = new File([value], "blob", { type: value.type });
+ }
+ if (filename !== void 0) {
+ const options = {
+ type: value.type,
+ lastModified: value.lastModified
+ };
+ value = new File([value], filename, options);
+ }
+ }
+ return { name, value };
+ }
+ __name(makeEntry, "makeEntry");
+ module2.exports = { FormData, makeEntry, setFormDataState, getFormDataBoundary };
+ }
+});
+
+// lib/core/request.js
+var require_request = __commonJS({
+ "lib/core/request.js"(exports2, module2) {
+ "use strict";
+ var {
+ InvalidArgumentError,
+ NotSupportedError
+ } = require_errors();
+ var assert = require("node:assert");
+ var {
+ isValidHTTPToken,
+ isValidHeaderValue,
+ isStream,
+ destroy,
+ isBuffer,
+ isFormDataLike,
+ isIterable,
+ hasSafeIterator,
+ isBlobLike,
+ serializePathWithQuery,
+ parseHeaders,
+ assertRequestHandler,
+ getServerName,
+ normalizedMethodRecords,
+ getProtocolFromUrlString
+ } = require_util();
+ var { channels } = require_diagnostics();
+ var { headerNameLowerCasedRecord } = require_constants();
+ var invalidPathRegex = /[^\u0021-\u00ff]/;
+ function isValidContentLengthHeaderValue(val) {
+ if (typeof val !== "string" || val.length === 0) {
+ return false;
+ }
+ for (let i = 0; i < val.length; i++) {
+ const charCode = val.charCodeAt(i);
+ if (charCode < 48 || charCode > 57) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isValidContentLengthHeaderValue, "isValidContentLengthHeaderValue");
+ var kHandler = /* @__PURE__ */ Symbol("handler");
+ var kController = /* @__PURE__ */ Symbol("controller");
+ var kResume = /* @__PURE__ */ Symbol("resume");
+ function noop() {
+ }
+ __name(noop, "noop");
+ var RequestController = class {
+ static {
+ __name(this, "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]?.();
+ }
}
- getAll(name) {
- webidl.brandCheck(this, webidl.is.FormData);
- const prefix = "FormData.getAll";
- webidl.argumentLengthCheck(arguments, 1, prefix);
- name = webidl.converters.USVString(name);
- return this.#state.filter((entry) => entry.name === name).map((entry) => entry.value);
+ abort(reason) {
+ if (!this.#aborted) {
+ this.#aborted = true;
+ this.#reason = reason;
+ this.#abort(reason);
+ }
}
- has(name) {
- webidl.brandCheck(this, webidl.is.FormData);
- const prefix = "FormData.has";
- webidl.argumentLengthCheck(arguments, 1, prefix);
- name = webidl.converters.USVString(name);
- return this.#state.findIndex((entry) => entry.name === name) !== -1;
+ get aborted() {
+ return this.#aborted;
}
- set(name, value, filename = void 0) {
- webidl.brandCheck(this, webidl.is.FormData);
- const prefix = "FormData.set";
- webidl.argumentLengthCheck(arguments, 2, prefix);
- name = webidl.converters.USVString(name);
- if (arguments.length === 3 || webidl.is.Blob(value)) {
- value = webidl.converters.Blob(value, prefix, "value");
- if (filename !== void 0) {
- filename = webidl.converters.USVString(filename);
- }
- } else {
- value = webidl.converters.USVString(value);
+ get reason() {
+ return this.#reason;
+ }
+ get paused() {
+ return this.#paused;
+ }
+ };
+ var Request = class {
+ static {
+ __name(this, "Request");
+ }
+ constructor(origin, {
+ path,
+ method,
+ body,
+ headers,
+ query,
+ idempotent,
+ blocking,
+ upgrade,
+ headersTimeout,
+ bodyTimeout,
+ reset,
+ expectContinue,
+ servername,
+ throwOnError,
+ maxRedirections,
+ typeOfService
+ }, handler) {
+ if (typeof path !== "string") {
+ throw new InvalidArgumentError("path must be a string");
+ } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://")) && method !== "CONNECT") {
+ throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
+ } else if (invalidPathRegex.test(path)) {
+ throw new InvalidArgumentError("invalid request path");
}
- const entry = makeEntry(name, value, filename);
- const idx = this.#state.findIndex((entry2) => entry2.name === name);
- if (idx !== -1) {
- this.#state = [
- ...this.#state.slice(0, idx),
- entry,
- ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name)
- ];
- } else {
- this.#state.push(entry);
+ if (typeof method !== "string") {
+ throw new InvalidArgumentError("method must be a string");
+ } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) {
+ throw new InvalidArgumentError("invalid request method");
}
- }
- [nodeUtil.inspect.custom](depth, options) {
- const state = this.#state.reduce((a, b) => {
- if (a[b.name]) {
- if (Array.isArray(a[b.name])) {
- a[b.name].push(b.value);
+ if (upgrade && typeof upgrade !== "string") {
+ throw new InvalidArgumentError("upgrade must be a string");
+ }
+ if (upgrade && !isValidHeaderValue(upgrade)) {
+ throw new InvalidArgumentError("invalid upgrade header");
+ }
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError("invalid headersTimeout");
+ }
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError("invalid bodyTimeout");
+ }
+ if (reset != null && typeof reset !== "boolean") {
+ throw new InvalidArgumentError("invalid reset");
+ }
+ if (expectContinue != null && typeof expectContinue !== "boolean") {
+ throw new InvalidArgumentError("invalid expectContinue");
+ }
+ if (throwOnError != null) {
+ throw new InvalidArgumentError("invalid throwOnError");
+ }
+ if (maxRedirections != null && maxRedirections !== 0) {
+ throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
+ }
+ if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
+ throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255");
+ }
+ this.headersTimeout = headersTimeout;
+ this.bodyTimeout = bodyTimeout;
+ this.method = method;
+ this.typeOfService = typeOfService;
+ this.abort = null;
+ if (body == null) {
+ this.body = null;
+ } else if (isStream(body)) {
+ this.body = body;
+ const rState = this.body._readableState;
+ if (!rState || !rState.autoDestroy) {
+ this.endHandler = /* @__PURE__ */ __name(function autoDestroy() {
+ destroy(this);
+ }, "autoDestroy");
+ this.body.on("end", this.endHandler);
+ }
+ this.errorHandler = (err) => {
+ if (this.abort) {
+ this.abort(err);
} else {
- a[b.name] = [a[b.name], b.value];
+ this.error = err;
+ }
+ };
+ this.body.on("error", this.errorHandler);
+ } else if (isBuffer(body)) {
+ this.body = body.byteLength ? body : null;
+ } else if (ArrayBuffer.isView(body)) {
+ this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
+ } else if (body instanceof ArrayBuffer) {
+ this.body = body.byteLength ? Buffer.from(body) : null;
+ } else if (typeof body === "string") {
+ this.body = body.length ? Buffer.from(body) : null;
+ } else if (isFormDataLike(body)) {
+ if (!isUndiciFormData(body)) {
+ throw new InvalidArgumentError("body must be a FormData created by this undici package instance; FormData from other sources, such as the built-in FormData provided by Node.js, is not supported");
+ }
+ this.body = body;
+ } else if (isIterable(body) || isBlobLike(body)) {
+ this.body = body;
+ } else {
+ throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
+ }
+ this.completed = false;
+ this.aborted = false;
+ this.upgrade = upgrade || null;
+ this.path = query ? serializePathWithQuery(path, query) : path;
+ this.origin = origin;
+ this.protocol = getProtocolFromUrlString(origin);
+ this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" || method === "QUERY" : idempotent;
+ this.blocking = blocking ?? this.method !== "HEAD";
+ this.reset = reset == null ? null : reset;
+ this.host = null;
+ this.contentLength = null;
+ this.contentType = null;
+ this.headers = [];
+ this.expectContinue = expectContinue != null ? expectContinue : false;
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError("headers array must be even");
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(this, headers[i], headers[i + 1]);
+ }
+ } else if (headers && typeof headers === "object") {
+ if (hasSafeIterator(headers)) {
+ for (const header of headers) {
+ if (!Array.isArray(header) || header.length !== 2) {
+ throw new InvalidArgumentError("headers must be in key-value pair format");
+ }
+ processHeader(this, header[0], header[1]);
}
} else {
- a[b.name] = b.value;
+ const keys = Object.keys(headers);
+ for (let i = 0; i < keys.length; ++i) {
+ processHeader(this, keys[i], headers[keys[i]]);
+ }
}
- return a;
- }, { __proto__: null });
- options.depth ??= depth;
- options.colors ??= true;
- const output = nodeUtil.formatWithOptions(options, state);
- return `FormData ${output.slice(output.indexOf("]") + 2)}`;
- }
- static {
- getFormDataState = /* @__PURE__ */ __name((formData) => formData.#state, "getFormDataState");
- setFormDataState = /* @__PURE__ */ __name((formData, newState) => {
- formData.#state = newState;
- }, "setFormDataState");
- getFormDataBoundary = /* @__PURE__ */ __name((formData) => {
- return formData.#boundary ??= `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`;
- }, "getFormDataBoundary");
- webidl.is.FormData = (arg) => {
- return arg != null && typeof arg === "object" && #state in arg;
- };
+ } else if (headers != null) {
+ throw new InvalidArgumentError("headers must be an object or an array");
+ }
+ assertRequestHandler(handler, method, upgrade);
+ this.servername = servername || getServerName(this.host) || null;
+ this[kHandler] = handler;
+ if (channels.create.hasSubscribers) {
+ channels.create.publish({ request: this });
+ }
}
- };
- iteratorMixin("FormData", FormData, getFormDataState, "name", "value", webidl.is.FormData);
- Object.defineProperties(FormData.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- getAll: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: "FormData",
- configurable: true
+ onBodySent(chunk) {
+ if (channels.bodyChunkSent.hasSubscribers) {
+ channels.bodyChunkSent.publish({ request: this, chunk });
+ }
+ if (this[kHandler].onBodySent) {
+ try {
+ return this[kHandler].onBodySent(chunk);
+ } catch (err) {
+ this.abort(err);
+ }
+ }
}
- });
- function makeEntry(name, value, filename) {
- if (typeof value === "string") {
- } else {
- if (!webidl.is.File(value)) {
- value = new File([value], "blob", { type: value.type });
+ onRequestSent() {
+ if (channels.bodySent.hasSubscribers) {
+ channels.bodySent.publish({ request: this });
}
- if (filename !== void 0) {
- const options = {
- type: value.type,
- lastModified: value.lastModified
- };
- value = new File([value], filename, options);
+ if (this[kHandler].onRequestSent) {
+ try {
+ return this[kHandler].onRequestSent();
+ } catch (err) {
+ this.abort(err);
+ }
+ }
+ }
+ onRequestStart(abort, context) {
+ assert(!this.aborted);
+ assert(!this.completed);
+ this[kController] = new RequestController(abort);
+ if (this.error) {
+ this[kController].abort(this.error);
+ return;
}
+ this.abort = abort;
+ return this[kHandler].onRequestStart(this[kController], context);
}
- return { name, value };
- }
- __name(makeEntry, "makeEntry");
- module2.exports = { FormData, makeEntry, setFormDataState, getFormDataBoundary };
- }
-});
-
-// lib/core/request.js
-var require_request = __commonJS({
- "lib/core/request.js"(exports2, module2) {
- "use strict";
- var {
- InvalidArgumentError,
- NotSupportedError
- } = require_errors();
- var assert = require("node:assert");
- var {
- isValidHTTPToken,
- isValidHeaderValue,
- isStream,
- destroy,
- isBuffer,
- isFormDataLike,
- isIterable,
- hasSafeIterator,
- isBlobLike,
- serializePathWithQuery,
- parseHeaders,
- assertRequestHandler,
- getServerName,
- normalizedMethodRecords,
- getProtocolFromUrlString
- } = require_util();
- var { channels } = require_diagnostics();
- var { headerNameLowerCasedRecord } = require_constants();
- var invalidPathRegex = /[^\u0021-\u00ff]/;
- function isValidContentLengthHeaderValue(val) {
- if (typeof val !== "string" || val.length === 0) {
- return false;
+ onResponseStarted() {
+ return this[kHandler].onResponseStarted?.();
}
- for (let i = 0; i < val.length; i++) {
- const charCode = val.charCodeAt(i);
- if (charCode < 48 || charCode > 57) {
+ onResponseStart(statusCode, headers, resume, statusText) {
+ assert(!this.aborted);
+ assert(!this.completed);
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
+ }
+ const controller = this[kController];
+ if (controller) {
+ controller[kResume] = resume;
+ controller.rawHeaders = headers;
+ }
+ const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
+ try {
+ this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText);
+ return !controller?.paused;
+ } catch (err) {
+ this.abort(err);
return false;
}
}
- return true;
- }
- __name(isValidContentLengthHeaderValue, "isValidContentLengthHeaderValue");
- var kHandler = /* @__PURE__ */ Symbol("handler");
- var kController = /* @__PURE__ */ Symbol("controller");
- var kResume = /* @__PURE__ */ Symbol("resume");
- var RequestController = class {
- static {
- __name(this, "RequestController");
- }
- #paused = false;
- #reason = null;
- #aborted = false;
- #abort;
- [kResume] = null;
- rawHeaders = null;
- rawTrailers = null;
- constructor(abort) {
- this.#abort = abort;
+ onResponseData(chunk) {
+ assert(!this.aborted);
+ assert(!this.completed);
+ 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;
+ }
}
- pause() {
- this.#paused = true;
+ /**
+ * @param {number} statusCode
+ * @param {Buffer[]|string[]|import('../../types/header.d.ts').IncomingHttpHeaders} headers
+ * @param {import('node:stream').Duplex} socket
+ * @param {string} [statusText]
+ */
+ onRequestUpgrade(statusCode, headers, socket, statusText = "") {
+ this.onFinally();
+ assert(!this.aborted);
+ assert(!this.completed);
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
+ }
+ const controller = this[kController];
+ if (controller) {
+ controller.rawHeaders = headers;
+ }
+ const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
+ const result = this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket);
+ if (!this.aborted) {
+ this.completed = true;
+ if (channels.trailers.hasSubscribers) {
+ channels.trailers.publish({ request: this, trailers: [] });
+ }
+ }
+ return result;
}
- resume() {
- if (this.#paused) {
- this.#paused = false;
- this[kResume]?.();
+ onResponseEnd(trailers) {
+ this.onFinally();
+ assert(!this.aborted);
+ assert(!this.completed);
+ this.completed = true;
+ if (channels.trailers.hasSubscribers) {
+ 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].onResponseEnd?.(controller, parsedTrailers);
+ } catch (err) {
+ this.onResponseError(err);
}
}
- abort(reason) {
- if (!this.#aborted) {
- this.#aborted = true;
- this.#reason = reason;
- this.#abort(reason);
+ onResponseError(error) {
+ this.onFinally();
+ if (channels.error.hasSubscribers) {
+ channels.error.publish({ request: this, error });
+ }
+ if (this.aborted) {
+ return;
}
+ this.aborted = true;
+ const controller = this[kController];
+ return this[kHandler].onResponseError?.(controller, error);
}
- get aborted() {
- return this.#aborted;
+ onFinally() {
+ if (this.errorHandler) {
+ this.body.off("error", this.errorHandler);
+ this.errorHandler = null;
+ }
+ if (this.endHandler) {
+ this.body.off("end", this.endHandler);
+ this.endHandler = null;
+ }
}
- get reason() {
- return this.#reason;
+ // Fails a request that was aborted before it reached a connection. The
+ // handler gets an aborted controller, so wrappers such as RetryHandler can
+ // tell a caller abort apart from a retryable connection failure.
+ onQueuedAbort(reason) {
+ this[kController] = createAbortedController(reason);
+ return this.onResponseError(reason);
}
- get paused() {
- return this.#paused;
+ addHeader(key, value) {
+ processHeader(this, key, value);
+ return this;
}
};
- var Request = class {
- static {
- __name(this, "Request");
+ function createAbortedController(reason) {
+ const controller = new RequestController(noop);
+ controller.abort(reason);
+ return controller;
+ }
+ __name(createAbortedController, "createAbortedController");
+ function processHeader(request, key, val) {
+ if (val && (typeof val === "object" && !Array.isArray(val))) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ } else if (val === void 0) {
+ return;
}
- constructor(origin, {
- path,
- method,
- body,
- headers,
- query,
- idempotent,
- blocking,
- upgrade,
- headersTimeout,
- bodyTimeout,
- reset,
- expectContinue,
- servername,
- throwOnError,
- maxRedirections,
- typeOfService
- }, handler) {
- if (typeof path !== "string") {
- throw new InvalidArgumentError("path must be a string");
- } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://")) && method !== "CONNECT") {
- throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
- } else if (invalidPathRegex.test(path)) {
- throw new InvalidArgumentError("invalid request path");
- }
- if (typeof method !== "string") {
- throw new InvalidArgumentError("method must be a string");
- } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) {
- throw new InvalidArgumentError("invalid request method");
- }
- if (upgrade && typeof upgrade !== "string") {
- throw new InvalidArgumentError("upgrade must be a string");
- }
- if (upgrade && !isValidHeaderValue(upgrade)) {
- throw new InvalidArgumentError("invalid upgrade header");
+ let headerName = headerNameLowerCasedRecord[key];
+ if (headerName === void 0) {
+ headerName = key.toLowerCase();
+ if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) {
+ throw new InvalidArgumentError("invalid header key");
}
- if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError("invalid headersTimeout");
+ }
+ if (Array.isArray(val)) {
+ const arr = [];
+ for (let i = 0; i < val.length; i++) {
+ if (typeof val[i] === "string") {
+ if (!isValidHeaderValue(val[i])) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ }
+ arr.push(val[i]);
+ } else if (val[i] === null) {
+ arr.push("");
+ } else if (typeof val[i] === "object") {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ } else {
+ const str = `${val[i]}`;
+ if (!isValidHeaderValue(str)) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
+ }
+ arr.push(str);
+ }
}
- if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError("invalid bodyTimeout");
+ val = arr;
+ } else if (typeof val === "string") {
+ if (!isValidHeaderValue(val)) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
}
- if (reset != null && typeof reset !== "boolean") {
- throw new InvalidArgumentError("invalid reset");
+ } else if (val === null) {
+ val = "";
+ } else {
+ val = `${val}`;
+ if (!isValidHeaderValue(val)) {
+ throw new InvalidArgumentError(`invalid ${key} header`);
}
- if (expectContinue != null && typeof expectContinue !== "boolean") {
- throw new InvalidArgumentError("invalid expectContinue");
+ }
+ if (headerName === "host") {
+ if (request.host !== null) {
+ throw new InvalidArgumentError("duplicate host header");
}
- if (throwOnError != null) {
- throw new InvalidArgumentError("invalid throwOnError");
+ if (typeof val !== "string") {
+ throw new InvalidArgumentError("invalid host header");
}
- if (maxRedirections != null && maxRedirections !== 0) {
- throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor");
+ request.host = val;
+ } else if (headerName === "content-length") {
+ if (request.contentLength !== null) {
+ throw new InvalidArgumentError("duplicate content-length header");
}
- if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) {
- throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255");
+ if (!isValidContentLengthHeaderValue(val)) {
+ throw new InvalidArgumentError("invalid content-length header");
}
- this.headersTimeout = headersTimeout;
- this.bodyTimeout = bodyTimeout;
- this.method = method;
- this.typeOfService = typeOfService;
- this.abort = null;
- if (body == null) {
- this.body = null;
- } else if (isStream(body)) {
- this.body = body;
- const rState = this.body._readableState;
- if (!rState || !rState.autoDestroy) {
- this.endHandler = /* @__PURE__ */ __name(function autoDestroy() {
- destroy(this);
- }, "autoDestroy");
- this.body.on("end", this.endHandler);
- }
- this.errorHandler = (err) => {
- if (this.abort) {
- this.abort(err);
- } else {
- this.error = err;
- }
- };
- this.body.on("error", this.errorHandler);
- } else if (isBuffer(body)) {
- this.body = body.byteLength ? body : null;
- } else if (ArrayBuffer.isView(body)) {
- this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null;
- } else if (body instanceof ArrayBuffer) {
- this.body = body.byteLength ? Buffer.from(body) : null;
- } else if (typeof body === "string") {
- this.body = body.length ? Buffer.from(body) : null;
- } else if (isFormDataLike(body)) {
- if (!isUndiciFormData(body)) {
- throw new InvalidArgumentError("body must be a FormData created by this undici package instance; FormData from other sources, such as the built-in FormData provided by Node.js, is not supported");
- }
- this.body = body;
- } else if (isIterable(body) || isBlobLike(body)) {
- this.body = body;
- } else {
- throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable");
+ request.contentLength = parseInt(val, 10);
+ } else if (request.contentType === null && headerName === "content-type") {
+ request.contentType = val;
+ request.headers.push(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 : null;
+ if (value === null) {
+ throw new InvalidArgumentError("invalid connection header");
}
- this.completed = false;
- this.aborted = false;
- this.upgrade = upgrade || null;
- this.path = query ? serializePathWithQuery(path, query) : path;
- this.origin = origin;
- this.protocol = getProtocolFromUrlString(origin);
- this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" || method === "QUERY" : idempotent;
- this.blocking = blocking ?? this.method !== "HEAD";
- this.reset = reset == null ? null : reset;
- this.host = null;
- this.contentLength = null;
- this.contentType = null;
- this.headers = [];
- this.expectContinue = expectContinue != null ? expectContinue : false;
- if (Array.isArray(headers)) {
- if (headers.length % 2 !== 0) {
- throw new InvalidArgumentError("headers array must be even");
- }
- for (let i = 0; i < headers.length; i += 2) {
- processHeader(this, headers[i], headers[i + 1]);
+ for (const token of value.toLowerCase().split(",")) {
+ const trimmed = token.trim();
+ if (!isValidHTTPToken(trimmed)) {
+ throw new InvalidArgumentError("invalid connection header");
}
- } else if (headers && typeof headers === "object") {
- if (hasSafeIterator(headers)) {
- for (const header of headers) {
- if (!Array.isArray(header) || header.length !== 2) {
- throw new InvalidArgumentError("headers must be in key-value pair format");
- }
- processHeader(this, header[0], header[1]);
- }
- } else {
- const keys = Object.keys(headers);
- for (let i = 0; i < keys.length; ++i) {
- processHeader(this, keys[i], headers[keys[i]]);
- }
+ if (trimmed === "close") {
+ request.reset = true;
}
- } else if (headers != null) {
- throw new InvalidArgumentError("headers must be an object or an array");
}
- assertRequestHandler(handler, method, upgrade);
- this.servername = servername || getServerName(this.host) || null;
- this[kHandler] = handler;
- if (channels.create.hasSubscribers) {
- channels.create.publish({ request: this });
+ } else if (headerName === "expect") {
+ throw new NotSupportedError("expect header not supported");
+ } else {
+ request.headers.push(key, val);
+ }
+ }
+ __name(processHeader, "processHeader");
+ var isFormData;
+ function isUndiciFormData(body) {
+ if (isFormData === void 0) {
+ require_formdata();
+ isFormData = require_webidl().webidl.is.FormData;
+ }
+ return isFormData(body);
+ }
+ __name(isUndiciFormData, "isUndiciFormData");
+ module2.exports = Request;
+ module2.exports.createAbortedController = createAbortedController;
+ }
+});
+
+// lib/dispatcher/pool-base.js
+var require_pool_base = __commonJS({
+ "lib/dispatcher/pool-base.js"(exports2, module2) {
+ "use strict";
+ var { AsyncResource } = require("node:async_hooks");
+ var { PoolStats } = require_stats();
+ var DispatcherBase = require_dispatcher_base();
+ var FixedQueue = require_fixed_queue();
+ var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require_symbols();
+ var { createAbortedController } = require_request();
+ var kClients = /* @__PURE__ */ Symbol("clients");
+ var kNeedDrain = /* @__PURE__ */ Symbol("needDrain");
+ var kQueue = /* @__PURE__ */ Symbol("queue");
+ var kClosedResolve = /* @__PURE__ */ Symbol("closed resolve");
+ var kOnDrain = /* @__PURE__ */ Symbol("onDrain");
+ var kOnConnect = /* @__PURE__ */ Symbol("onConnect");
+ var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect");
+ var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError");
+ var kOnClientBusy = /* @__PURE__ */ Symbol("on client busy");
+ var kOnClientDrain = /* @__PURE__ */ Symbol("on client drain");
+ var kDrainQueue = /* @__PURE__ */ Symbol("drain queue");
+ var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher");
+ var kHasDispatcher = /* @__PURE__ */ Symbol("has dispatcher");
+ var kAddClient = /* @__PURE__ */ Symbol("add client");
+ var kRemoveClient = /* @__PURE__ */ Symbol("remove client");
+ var kRetireClient = /* @__PURE__ */ Symbol("retire client");
+ var kRetiring = /* @__PURE__ */ Symbol("retiring clients");
+ var kShiftQueue = /* @__PURE__ */ Symbol("shift queue");
+ var kAbortQueued = /* @__PURE__ */ Symbol("abort queued");
+ var QueuedRequest = class extends AsyncResource {
+ static {
+ __name(this, "QueuedRequest");
+ }
+ constructor(opts, handler) {
+ super("UNDICI_POOL_QUEUED_REQUEST");
+ this.opts = opts;
+ this.handler = handler;
+ this.queued = true;
+ }
+ dispatch(dispatcher) {
+ return this.runInAsyncScope(dispatcher.dispatch, dispatcher, this.opts, this.handler);
+ }
+ };
+ function closeClients(pool) {
+ const closeAll = [];
+ for (let i = 0; i < pool[kClients].length; i++) {
+ const client = pool[kClients][i];
+ if (!client.destroyed) {
+ closeAll.push(client.close());
}
}
- onBodySent(chunk) {
- if (channels.bodyChunkSent.hasSubscribers) {
- channels.bodyChunkSent.publish({ request: this, chunk });
+ for (const closed of pool[kRetiring].values()) {
+ closeAll.push(closed);
+ }
+ return Promise.all(closeAll);
+ }
+ __name(closeClients, "closeClients");
+ var PoolBase = class extends DispatcherBase {
+ static {
+ __name(this, "PoolBase");
+ }
+ [kQueue] = new FixedQueue();
+ [kQueued] = 0;
+ [kClients] = [];
+ // Clients removed from kClients that have not finished closing,
+ // mapped to a promise that settles once they have.
+ [kRetiring] = /* @__PURE__ */ new Map();
+ [kNeedDrain] = false;
+ [kOnDrain](client, origin, targets) {
+ if (client.closed || client.destroyed) {
+ return;
}
- if (this[kHandler].onBodySent) {
- try {
- return this[kHandler].onBodySent(chunk);
- } catch (err) {
- this.abort(err);
+ let needDrain = false;
+ this[kOnClientDrain](client);
+ while (!needDrain) {
+ const item = this[kShiftQueue]();
+ if (!item) {
+ break;
}
+ needDrain = !item.dispatch(client);
}
- }
- onRequestSent() {
- if (channels.bodySent.hasSubscribers) {
- channels.bodySent.publish({ request: this });
- }
- if (this[kHandler].onRequestSent) {
- try {
- return this[kHandler].onRequestSent();
- } catch (err) {
- this.abort(err);
+ client[kNeedDrain] = needDrain;
+ if (needDrain) {
+ this[kOnClientBusy](client);
+ if (this[kQueued] > 0) {
+ return this[kDrainQueue](origin, targets);
}
}
- }
- onRequestStart(abort, context) {
- assert(!this.aborted);
- assert(!this.completed);
- this[kController] = new RequestController(abort);
- if (this.error) {
- this[kController].abort(this.error);
- return;
+ if (!needDrain && this[kNeedDrain]) {
+ this[kNeedDrain] = false;
+ this.emit("drain", origin, [this, ...targets]);
+ }
+ if (this[kClosedResolve] && this[kQueued] === 0) {
+ return closeClients(this).then(this[kClosedResolve]);
}
- this.abort = abort;
- return this[kHandler].onRequestStart(this[kController], context);
}
- onResponseStarted() {
- return this[kHandler].onResponseStarted?.();
+ [kOnClientBusy]() {
}
- onResponseStart(statusCode, headers, resume, statusText) {
- assert(!this.aborted);
- assert(!this.completed);
- if (channels.headers.hasSubscribers) {
- channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
+ [kOnClientDrain]() {
+ }
+ [kDrainQueue](origin, targets) {
+ let hasDispatcher = true;
+ while (this[kQueued] > 0) {
+ let dispatcher;
+ try {
+ dispatcher = this[kGetDispatcher]();
+ } catch (err) {
+ const item2 = this[kShiftQueue]();
+ item2.runInAsyncScope(item2.handler.onResponseError, item2.handler, null, err);
+ hasDispatcher = !this.destroyed && this[kHasDispatcher](false);
+ continue;
+ }
+ if (!dispatcher) {
+ hasDispatcher = false;
+ break;
+ }
+ const item = this[kShiftQueue]();
+ if (!item.dispatch(dispatcher)) {
+ dispatcher[kNeedDrain] = true;
+ this[kOnClientBusy](dispatcher);
+ hasDispatcher = this[kHasDispatcher](false);
+ if (!hasDispatcher) {
+ break;
+ }
+ }
}
- const controller = this[kController];
- if (controller) {
- controller[kResume] = resume;
- controller.rawHeaders = headers;
+ if (hasDispatcher && this[kNeedDrain]) {
+ this[kNeedDrain] = false;
+ this.emit("drain", origin, [this, ...targets]);
}
- const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
- try {
- this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText);
- return !controller?.paused;
- } catch (err) {
- this.abort(err);
- return false;
+ if (this[kClosedResolve] && this[kQueued] === 0) {
+ return closeClients(this).then(this[kClosedResolve]);
}
}
- onResponseData(chunk) {
- assert(!this.aborted);
- assert(!this.completed);
- if (channels.bodyChunkReceived.hasSubscribers) {
- channels.bodyChunkReceived.publish({ request: this, chunk });
+ // Aborted requests stay in the queue as tombstones (queued === false) and
+ // are skipped here; kQueued only counts the live ones.
+ [kShiftQueue]() {
+ const queue = this[kQueue];
+ let item = queue.shift();
+ while (item !== null && item.queued === false) {
+ item = queue.shift();
}
- const controller = this[kController];
- try {
- this[kHandler].onResponseData?.(controller, chunk);
- return !controller?.paused;
- } catch (err) {
- this.abort(err);
- return false;
+ if (item !== null) {
+ this[kQueued]--;
+ item.queued = false;
}
+ return item;
}
- /**
- * @param {number} statusCode
- * @param {Buffer[]|string[]|import('../../types/header.d.ts').IncomingHttpHeaders} headers
- * @param {import('node:stream').Duplex} socket
- * @param {string} [statusText]
- */
- onRequestUpgrade(statusCode, headers, socket, statusText = "") {
- this.onFinally();
- assert(!this.aborted);
- assert(!this.completed);
- if (channels.headers.hasSubscribers) {
- channels.headers.publish({ request: this, response: { statusCode, headers, statusText } });
- }
- const controller = this[kController];
- if (controller) {
- controller.rawHeaders = headers;
+ // Called through the handler's kQueuedAbort hook when a queued request is
+ // aborted.
+ [kAbortQueued](item, reason) {
+ if (!item.queued) {
+ return;
}
- const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers;
- const result = this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket);
- if (!this.aborted) {
- this.completed = true;
- if (channels.trailers.hasSubscribers) {
- channels.trailers.publish({ request: this, trailers: [] });
- }
+ const { handler } = item;
+ item.queued = false;
+ item.opts = null;
+ item.handler = null;
+ this[kQueued]--;
+ item.runInAsyncScope(handler.onResponseError, handler, createAbortedController(reason), reason);
+ if (this[kClosedResolve] && this[kQueued] === 0) {
+ closeClients(this).then(this[kClosedResolve]);
}
- return result;
}
- onResponseEnd(trailers) {
- this.onFinally();
- assert(!this.aborted);
- assert(!this.completed);
- this.completed = true;
- if (channels.trailers.hasSubscribers) {
- 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].onResponseEnd?.(controller, parsedTrailers);
- } catch (err) {
- this.onResponseError(err);
- }
+ [kOnConnect] = (origin, targets) => {
+ this.emit("connect", origin, [this, ...targets]);
+ };
+ [kOnDisconnect] = (origin, targets, err) => {
+ this.emit("disconnect", origin, [this, ...targets], err);
+ };
+ [kOnConnectionError] = (origin, targets, err) => {
+ this.emit("connectionError", origin, [this, ...targets], err);
+ };
+ get [kBusy]() {
+ return this[kNeedDrain];
}
- onResponseError(error) {
- this.onFinally();
- if (channels.error.hasSubscribers) {
- channels.error.publish({ request: this, error });
+ get [kConnected]() {
+ let ret = 0;
+ for (const { [kConnected]: connected } of this[kClients]) {
+ ret += connected;
}
- if (this.aborted) {
- return;
+ return ret;
+ }
+ get [kFree]() {
+ let ret = 0;
+ for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) {
+ ret += connected && !needDrain;
}
- this.aborted = true;
- const controller = this[kController];
- return this[kHandler].onResponseError?.(controller, error);
+ return ret;
}
- onFinally() {
- if (this.errorHandler) {
- this.body.off("error", this.errorHandler);
- this.errorHandler = null;
+ get [kPending]() {
+ let ret = this[kQueued];
+ for (const { [kPending]: pending } of this[kClients]) {
+ ret += pending;
}
- if (this.endHandler) {
- this.body.off("end", this.endHandler);
- this.endHandler = null;
+ return ret;
+ }
+ get [kRunning]() {
+ let ret = 0;
+ for (const { [kRunning]: running } of this[kClients]) {
+ ret += running;
}
+ return ret;
}
- addHeader(key, value) {
- processHeader(this, key, value);
- return this;
+ get [kSize]() {
+ let ret = this[kQueued];
+ for (const { [kSize]: size } of this[kClients]) {
+ ret += size;
+ }
+ return ret;
}
- };
- function processHeader(request, key, val) {
- if (val && (typeof val === "object" && !Array.isArray(val))) {
- throw new InvalidArgumentError(`invalid ${key} header`);
- } else if (val === void 0) {
- return;
+ get stats() {
+ return new PoolStats(this);
}
- let headerName = headerNameLowerCasedRecord[key];
- if (headerName === void 0) {
- headerName = key.toLowerCase();
- if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) {
- throw new InvalidArgumentError("invalid header key");
+ [kClose]() {
+ if (this[kQueued] === 0) {
+ return closeClients(this);
+ } else {
+ return new Promise((resolve) => {
+ this[kClosedResolve] = resolve;
+ });
}
}
- if (Array.isArray(val)) {
- const arr = [];
- for (let i = 0; i < val.length; i++) {
- if (typeof val[i] === "string") {
- if (!isValidHeaderValue(val[i])) {
- throw new InvalidArgumentError(`invalid ${key} header`);
- }
- arr.push(val[i]);
- } else if (val[i] === null) {
- arr.push("");
- } else if (typeof val[i] === "object") {
- throw new InvalidArgumentError(`invalid ${key} header`);
- } else {
- const str = `${val[i]}`;
- if (!isValidHeaderValue(str)) {
- throw new InvalidArgumentError(`invalid ${key} header`);
- }
- arr.push(str);
+ [kDestroy](err) {
+ while (true) {
+ const item = this[kShiftQueue]();
+ if (!item) {
+ break;
}
+ item.handler.onResponseError(null, err);
}
- val = arr;
- } else if (typeof val === "string") {
- if (!isValidHeaderValue(val)) {
- throw new InvalidArgumentError(`invalid ${key} header`);
+ const destroyAll = new Array(this[kClients].length);
+ for (let i = 0; i < this[kClients].length; i++) {
+ destroyAll[i] = this[kClients][i].destroy(err);
}
- } else if (val === null) {
- val = "";
- } else {
- val = `${val}`;
- if (!isValidHeaderValue(val)) {
- throw new InvalidArgumentError(`invalid ${key} header`);
+ for (const client of this[kRetiring].keys()) {
+ destroyAll.push(client.destroy(err));
}
+ return Promise.all(destroyAll);
}
- if (headerName === "host") {
- if (request.host !== null) {
- throw new InvalidArgumentError("duplicate host header");
+ [kDispatch](opts, handler) {
+ const dispatcher = this[kGetDispatcher]();
+ if (!dispatcher) {
+ const item = new QueuedRequest(opts, handler);
+ this[kNeedDrain] = true;
+ this[kQueue].push(item);
+ this[kQueued]++;
+ const onQueued = opts[kQueuedAbort];
+ if (onQueued !== void 0) {
+ onQueued((reason) => this[kAbortQueued](item, reason));
+ }
+ } else if (!dispatcher.dispatch(opts, handler)) {
+ dispatcher[kNeedDrain] = true;
+ this[kOnClientBusy](dispatcher);
+ this[kNeedDrain] = !this[kHasDispatcher]();
}
- if (typeof val !== "string") {
- throw new InvalidArgumentError("invalid host header");
+ return !this[kNeedDrain];
+ }
+ [kHasDispatcher]() {
+ for (let i = 0; i < this[kClients].length; i++) {
+ const dispatcher = this[kClients][i];
+ if (!dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true) {
+ return true;
+ }
}
- request.host = val;
- } else if (headerName === "content-length") {
- if (request.contentLength !== null) {
- throw new InvalidArgumentError("duplicate content-length header");
+ return false;
+ }
+ [kAddClient](client) {
+ client.on("drain", this[kOnDrain].bind(this, client)).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]);
+ this[kClients].push(client);
+ if (this[kNeedDrain]) {
+ queueMicrotask(() => {
+ if (this[kNeedDrain] && !client[kNeedDrain]) {
+ this[kOnDrain](client, client[kUrl], [client, this]);
+ }
+ });
}
- if (!isValidContentLengthHeaderValue(val)) {
- throw new InvalidArgumentError("invalid content-length header");
+ return this;
+ }
+ // Takes a client out of rotation. A closed client no longer takes requests
+ // from the pool queue (see kOnDrain), but it finishes the requests it
+ // already has. Until it has, pool.close() waits for it and pool.destroy()
+ // destroys it.
+ [kRetireClient](client) {
+ const idx = this[kClients].indexOf(client);
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1);
}
- request.contentLength = parseInt(val, 10);
- } else if (request.contentType === null && headerName === "content-type") {
- request.contentType = val;
- request.headers.push(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 : null;
- if (value === null) {
- throw new InvalidArgumentError("invalid connection header");
+ if (client.destroyed || this[kRetiring].has(client)) {
+ return;
}
- 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;
+ let done = false;
+ let resolveClosed;
+ const closed = new Promise((resolve) => {
+ resolveClosed = resolve;
+ });
+ this[kRetiring].set(client, closed);
+ client.close(() => {
+ if (!done) {
+ done = true;
+ this[kRetiring].delete(client);
+ resolveClosed();
}
- }
- } else if (headerName === "expect") {
- throw new NotSupportedError("expect header not supported");
- } else {
- request.headers.push(key, val);
+ });
}
- }
- __name(processHeader, "processHeader");
- var isFormData;
- function isUndiciFormData(body) {
- if (isFormData === void 0) {
- require_formdata();
- isFormData = require_webidl().webidl.is.FormData;
+ [kRemoveClient](client) {
+ this[kRetireClient](client);
+ this[kNeedDrain] = !this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true);
}
- return isFormData(body);
- }
- __name(isUndiciFormData, "isUndiciFormData");
- module2.exports = Request;
+ };
+ module2.exports = {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kRetireClient,
+ kDrainQueue,
+ kOnClientBusy,
+ kOnClientDrain,
+ kGetDispatcher,
+ kHasDispatcher
+ };
}
});
@@ -7304,6 +7368,7 @@ var require_client_h1 = __commonJS({
var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation");
var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout");
var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed");
+ var kIdleSince = /* @__PURE__ */ Symbol("kIdleSince");
var kTypeOfService = /* @__PURE__ */ Symbol("kTypeOfService");
var extractBody;
function lazyllhttp() {
@@ -8088,6 +8153,11 @@ var require_client_h1 = __commonJS({
});
}
__name(scheduleIdleSocketValidation, "scheduleIdleSocketValidation");
+ function isIdleSocketExpired(socket) {
+ const parser = socket[kParser];
+ return parser.timeoutType === TIMEOUT_KEEP_ALIVE && parser.timeoutValue > 0 && performance.now() - socket[kIdleSince] >= parser.timeoutValue;
+ }
+ __name(isIdleSocketExpired, "isIdleSocketExpired");
function resumeH1(client) {
const socket = client[kSocket];
if (socket && !socket.destroyed) {
@@ -8100,6 +8170,10 @@ var require_client_h1 = __commonJS({
socket.ref();
socket[kNoRef] = false;
}
+ if (client[kRunning] === 0 && client[kPending] > 0 && isIdleSocketExpired(socket)) {
+ util.destroy(socket, new InformationalError("socket idle timeout"));
+ return;
+ }
if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) {
if (socket[kIdleSocketValidation] === 0) {
scheduleIdleSocketValidation(client, socket);
@@ -8125,6 +8199,7 @@ var require_client_h1 = __commonJS({
}
if (client[kSize] === 0) {
if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {
+ socket[kIdleSince] = performance.now();
socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE);
}
} else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
@@ -8688,6 +8763,7 @@ var require_client_h2 = __commonJS({
HTTP2_HEADER_STATUS,
HTTP2_HEADER_PROTOCOL,
NGHTTP2_NO_ERROR,
+ NGHTTP2_PROTOCOL_ERROR,
NGHTTP2_REFUSED_STREAM
}
} = http2;
@@ -8853,7 +8929,9 @@ var require_client_h2 = __commonJS({
// refH2Session/unrefH2Session.
refed: true,
ping: {
- interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref()
+ interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref(),
+ // Set while a periodic PING waits for its ack.
+ pending: false
}
};
session[kReceivedGoAway] = false;
@@ -9044,11 +9122,15 @@ var require_client_h2 = __commonJS({
if (session.closed || session.destroyed) {
return;
}
+ resetUnresponsiveHttp2Session(session);
+ }
+ __name(onHttp2ProbeTimeout, "onHttp2ProbeTimeout");
+ function resetUnresponsiveHttp2Session(session) {
const err = new SocketError("HTTP/2: connection unresponsive", util.getSocketInfo(session[kSocket]));
session[kError] = err;
resetHttp2Session(session, err);
}
- __name(onHttp2ProbeTimeout, "onHttp2ProbeTimeout");
+ __name(resetUnresponsiveHttp2Session, "resetUnresponsiveHttp2Session");
function clearHttp2IdleTimeout(session) {
const state = session[kHTTP2SessionState];
if (state?.idleTimeout != null) {
@@ -9117,13 +9199,19 @@ var require_client_h2 = __commonJS({
state.ping.interval = null;
return;
}
+ if (state.ping.pending) {
+ resetUnresponsiveHttp2Session(session);
+ return;
+ }
+ state.ping.pending = true;
session.ping(onPing.bind(session));
function onPing(err, duration) {
+ state.ping.pending = false;
const client = this[kClient];
const socket = this[kSocket];
if (err != null) {
const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`);
- socket[kError] = error;
+ socket[kError] ??= error;
client[kOnError](error);
} else {
client.emit("ping", duration);
@@ -9813,8 +9901,10 @@ var require_client_h2 = __commonJS({
}
stream.off("error", onError);
stream.on("error", noop);
- if (state.responseContentLength != null && state.bytesRead !== state.responseContentLength) {
- err = new ResponseContentLengthMismatchError();
+ if ((err.code === "ERR_HTTP2_ERROR" || err.code === "ERR_HTTP2_STREAM_ERROR" && stream.rstCode === NGHTTP2_PROTOCOL_ERROR) && state.responseContentLength != null && state.bytesRead !== state.responseContentLength) {
+ const mismatch = new ResponseContentLengthMismatchError();
+ mismatch.cause = err;
+ err = mismatch;
}
if (typeof stream.rstCode === "number" && stream.rstCode !== NGHTTP2_NO_ERROR) {
err.http2ErrorCode = stream.rstCode;
@@ -10122,11 +10212,13 @@ var require_client = __commonJS({
kHostAuthority,
kResume,
kHTTP2Options,
- kUseMilo
+ kUseMilo,
+ kQueuedAbort
} = require_symbols();
var connectH1 = require_client_h1();
var connectH2 = require_client_h2();
var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve");
+ var kCancelConnect = /* @__PURE__ */ Symbol("kCancelConnect");
var getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => {
throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid");
};
@@ -10340,6 +10432,7 @@ var require_client = __commonJS({
this[kClosedResolve] = null;
this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1;
this[kHTTPContext] = null;
+ this[kCancelConnect] = null;
this[kHTTP2Options] = {
pingInterval: h2Options?.pingInterval ?? pingInterval ?? 6e4,
connectionWindowSize: h2Options?.connectionWindowSize ?? connectionWindowSize ?? 524288,
@@ -10392,6 +10485,7 @@ var require_client = __commonJS({
}
[kConnect](cb) {
connect(this);
+ this[kCancelConnect] = null;
this.once("connect", cb);
}
[kDispatch](opts, handler) {
@@ -10404,6 +10498,12 @@ var require_client = __commonJS({
} else {
this[kResume](true);
}
+ if (request.abort === null && !request.aborted) {
+ const onQueued = opts[kQueuedAbort];
+ if (onQueued !== void 0) {
+ onQueued((reason) => abortPendingRequest(this, request, reason));
+ }
+ }
if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
this[kNeedDrain] = 2;
}
@@ -10444,6 +10544,42 @@ var require_client = __commonJS({
});
}
};
+ function failQueuedRequest(client, request, reason) {
+ try {
+ request.onQueuedAbort(reason);
+ assert(request.aborted);
+ } catch (err) {
+ client.emit("error", err);
+ }
+ }
+ __name(failQueuedRequest, "failQueuedRequest");
+ function abortPendingRequest(client, request, reason) {
+ if (request.aborted || request.abort !== null) {
+ return;
+ }
+ const queue = client[kQueue];
+ const idx = queue.indexOf(request, client[kPendingIdx]);
+ if (idx === -1) {
+ return;
+ }
+ if (idx === client[kPendingIdx] && client[kResuming] === 2) {
+ return;
+ }
+ queue.splice(idx, 1);
+ failQueuedRequest(client, request, reason);
+ client[kResume](true);
+ if (client[kCancelConnect] !== null && client[kSize] === 0) {
+ queueMicrotask(() => cancelUnusedConnect(client));
+ }
+ }
+ __name(abortPendingRequest, "abortPendingRequest");
+ function cancelUnusedConnect(client) {
+ const cancel = client[kCancelConnect];
+ if (cancel !== null && client[kSize] === 0) {
+ cancel(new InformationalError("no request waits for this connection"));
+ }
+ }
+ __name(cancelUnusedConnect, "cancelUnusedConnect");
function onError(client, err) {
if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") {
assert(client[kPendingIdx] === client[kRunningIdx]);
@@ -10470,6 +10606,28 @@ var require_client = __commonJS({
hostname = ip;
}
client[kConnecting] = true;
+ const servername = client[kServerName];
+ let calledBack = false;
+ let cancelled = false;
+ const abandon = /* @__PURE__ */ __name((socket, err) => {
+ client[kConnecting] = false;
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ version: client[kHTTPContext]?.version,
+ servername,
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ });
+ }
+ util.destroy(socket.on("error", noop), err);
+ }, "abandon");
if (channels.beforeConnect.hasSubscribers) {
channels.beforeConnect.publish({
connectParams: {
@@ -10478,23 +10636,31 @@ var require_client = __commonJS({
protocol,
port,
version: client[kHTTPContext]?.version,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
},
connector: client[kConnector]
});
}
try {
- client[kConnector]({
+ const connecting = client[kConnector]({
host,
hostname,
protocol,
port,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
}, (err, socket) => {
+ calledBack = true;
+ if (cancelled) {
+ if (socket) {
+ util.destroy(socket.on("error", noop));
+ }
+ return;
+ }
+ client[kCancelConnect] = null;
if (err) {
- handleConnectError(client, err, { host, hostname, protocol, port });
+ handleConnectError(client, err, { host, hostname, protocol, port, servername });
client[kResume]();
return;
}
@@ -10504,11 +10670,16 @@ var require_client = __commonJS({
return;
}
assert(socket);
+ if (client[kServerName] !== servername) {
+ abandon(socket, new InformationalError("servername changed"));
+ client[kResume]();
+ return;
+ }
try {
client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket);
} catch (err2) {
socket.destroy().on("error", noop);
- handleConnectError(client, err2, { host, hostname, protocol, port });
+ handleConnectError(client, err2, { host, hostname, protocol, port, servername });
client[kResume]();
return;
}
@@ -10525,7 +10696,7 @@ var require_client = __commonJS({
protocol,
port,
version: client[kHTTPContext]?.version,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
@@ -10535,13 +10706,20 @@ var require_client = __commonJS({
client.emit("connect", client[kUrl], [client]);
client[kResume]();
});
+ if (!calledBack && util.isStream(connecting)) {
+ client[kCancelConnect] = (err) => {
+ cancelled = true;
+ client[kCancelConnect] = null;
+ abandon(connecting, err);
+ };
+ }
} catch (err) {
- handleConnectError(client, err, { host, hostname, protocol, port });
+ handleConnectError(client, err, { host, hostname, protocol, port, servername });
client[kResume]();
}
}
__name(connect, "connect");
- function handleConnectError(client, err, { host, hostname, protocol, port }) {
+ function handleConnectError(client, err, { host, hostname, protocol, port, servername }) {
if (client.destroyed) {
return;
}
@@ -10554,7 +10732,7 @@ var require_client = __commonJS({
protocol,
port,
version: client[kHTTPContext]?.version,
- servername: client[kServerName],
+ servername,
localAddress: client[kLocalAddress]
},
connector: client[kConnector],
@@ -10567,7 +10745,7 @@ var require_client = __commonJS({
for (let i = 0; i < running.length; i++) {
util.errorRequest(client, running[i], err);
}
- while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === servername) {
const request = client[kQueue].splice(client[kPendingIdx], 1)[0];
util.errorRequest(client, request, err);
}
@@ -10644,6 +10822,7 @@ var require_client = __commonJS({
client[kHTTPContext] = null;
resume(client);
});
+ client[kCancelConnect]?.(new InformationalError("servername changed"));
}
if (client[kConnecting]) {
return;
@@ -10693,7 +10872,7 @@ var require_pool = __commonJS({
InvalidArgumentError
} = require_errors();
var util = require_util();
- var { kConnecting, kHTTPContext, kUrl, kQueued } = require_symbols();
+ var { kConnecting, kHTTPContext, kHTTP2Session, kRemoteSettings, kUrl, kQueued } = require_symbols();
var buildConnector = require_connect();
var kOptions = /* @__PURE__ */ Symbol("options");
var kConnections = /* @__PURE__ */ Symbol("connections");
@@ -10775,9 +10954,19 @@ var require_pool = __commonJS({
this[kProtocol] = client[kHTTPContext]?.version;
}
if (client === this[kProtocolProbe]) {
- if (this[kProtocol] !== "h2") {
- this[kProtocolProbe] = null;
- this[kDrainQueue](origin2, targets.slice(1));
+ const releaseProbe = /* @__PURE__ */ __name(() => {
+ if (client === this[kProtocolProbe]) {
+ this[kProtocolProbe] = null;
+ if (!this.destroyed && (this[kQueued] > 0 || !this.closed && this[kHasDispatcher](false))) {
+ this[kDrainQueue](origin2, targets.slice(1));
+ }
+ }
+ }, "releaseProbe");
+ const session = client[kHTTP2Session];
+ if (this[kProtocol] !== "h2" || session[kRemoteSettings]) {
+ releaseProbe();
+ } else {
+ session.once("remoteSettings", releaseProbe);
}
}
});
@@ -10831,7 +11020,7 @@ var require_pool = __commonJS({
return createClient(this);
}
}
- [kHasDispatcher]() {
+ [kHasDispatcher](create = true) {
const clientTtlOption = this[kOptions].clientTtl;
for (let i = 0; i < this[kClients].length; i++) {
const client = this[kClients][i];
@@ -10846,7 +11035,7 @@ var require_pool = __commonJS({
return false;
}
if (!this[kConnections] || this[kClients].length < this[kConnections]) {
- createClient(this);
+ if (create) createClient(this);
return true;
}
return false;
@@ -10937,11 +11126,19 @@ var require_agent = __commonJS({
let dispatcher = this[kClients].get(key);
if (!dispatcher) {
dispatcher = this[kFactory](opts.origin, allowH2 === false ? { ...this[kOptions], allowH2: false } : this[kOptions]);
- const closeClientIfUnused = /* @__PURE__ */ __name(() => {
+ const closeClientIfUnused = /* @__PURE__ */ __name((deferred = false) => {
if (this[kClients].get(key) !== dispatcher) {
return;
}
- if (dispatcher[kConnected] > 0 || dispatcher[kBusy] || dispatcher[kPending] > 0) {
+ if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) {
+ return;
+ }
+ if (dispatcher[kPending] > 0) {
+ if (!deferred) {
+ queueMicrotask(() => {
+ closeClientIfUnused(true);
+ });
+ }
return;
}
this[kClients].delete(key);
@@ -12094,8 +12291,10 @@ var require_proxy_agent = __commonJS({
headers: this[kProxyHeaders],
connect,
factory: agentFactory,
- username: opts.username || username,
- password: opts.password || password,
+ // Socks5ProxyAgent decodes the credentials embedded in the URI;
+ // the URL getters return them still percent-encoded.
+ username: opts.username,
+ password: opts.password,
connectTimeout,
proxyTls: opts.proxyTls,
requestTls: opts.requestTls
@@ -14274,7 +14473,7 @@ var require_fetch = __commonJS({
var EE = require("node:events");
var { Readable, pipeline, finished, isErrored, isReadable } = require("node:stream");
var { addAbortListener, bufferToLowerCasedHeaderName } = require_util();
- var { SocketError } = require_errors();
+ var { SocketError, InformationalError } = require_errors();
var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
var { getGlobalDispatcher: getGlobalDispatcher2 } = require_global2();
var { webidl } = require_webidl();
@@ -15312,6 +15511,7 @@ var require_fetch = __commonJS({
}
}
}
+ this.nullBodyStatus = nullBodyStatus.includes(status);
this.body = new Readable({ read: /* @__PURE__ */ __name(() => controller.resume(), "read") });
const onError = /* @__PURE__ */ __name((err) => this.onResponseError(controller, err), "onError");
resolve({
@@ -15326,6 +15526,10 @@ var require_fetch = __commonJS({
});
},
onResponseData(controller, chunk) {
+ if (this.nullBodyStatus) {
+ controller.abort(new InformationalError("response with null body status has content"));
+ return;
+ }
if (fetchParams.controller.dump) {
return;
}
@@ -15346,6 +15550,10 @@ var require_fetch = __commonJS({
if (this.abort) {
fetchParams.controller.off("terminated", this.abort);
}
+ if (this.nullBodyStatus) {
+ this.body?.destroy();
+ return;
+ }
if (request.mode === "websocket" && allowH2 !== false && error?.code === "UND_ERR_INFO" && error?.message === "HTTP/2: Extended CONNECT protocol not supported by server") {
resolve(dispatchWithProtocolPreference(body2, false));
return;
@@ -18488,6 +18696,94 @@ var require_readable = __commonJS({
}
});
+// lib/api/abort-signal.js
+var require_abort_signal = __commonJS({
+ "lib/api/abort-signal.js"(exports2, module2) {
+ "use strict";
+ var { addAbortListener } = require_util();
+ var { RequestAbortedError } = require_errors();
+ var { kQueuedAbort } = require_symbols();
+ var kListener = /* @__PURE__ */ Symbol("kListener");
+ var kSignal = /* @__PURE__ */ Symbol("kSignal");
+ function abort(self) {
+ self.reason = self[kSignal]?.reason ?? new RequestAbortedError();
+ if (self.abort) {
+ self.abort(self.reason);
+ }
+ removeSignal(self);
+ }
+ __name(abort, "abort");
+ function addSignal(self, signal) {
+ self.reason = null;
+ self[kSignal] = null;
+ self[kListener] = null;
+ if (!signal) {
+ return;
+ }
+ if (signal.aborted) {
+ self.reason = signal.reason ?? new RequestAbortedError();
+ return;
+ }
+ self[kSignal] = signal;
+ self[kListener] = () => {
+ abort(self);
+ };
+ addAbortListener(self[kSignal], self[kListener]);
+ }
+ __name(addSignal, "addSignal");
+ function removeSignal(self) {
+ if (!self[kSignal]) {
+ return;
+ }
+ if ("removeEventListener" in self[kSignal]) {
+ self[kSignal].removeEventListener("abort", self[kListener]);
+ } else {
+ self[kSignal].removeListener("abort", self[kListener]);
+ }
+ self[kSignal] = null;
+ self[kListener] = null;
+ }
+ __name(removeSignal, "removeSignal");
+ function queuedAbortHook(handler) {
+ let started = null;
+ let installed = null;
+ return (cancel) => {
+ if (handler.reason) {
+ cancel(handler.reason);
+ return;
+ }
+ if (handler.abort !== installed) {
+ started = handler.abort;
+ }
+ if (started === null) {
+ installed = cancel;
+ } else {
+ const abortStarted = started;
+ installed = /* @__PURE__ */ __name((reason) => {
+ abortStarted(reason);
+ cancel(reason);
+ }, "installed");
+ }
+ handler.abort = installed;
+ };
+ }
+ __name(queuedAbortHook, "queuedAbortHook");
+ function dispatchWithSignal(dispatcher, opts, handler) {
+ if (handler.reason) {
+ handler.onResponseError(null, handler.reason);
+ return;
+ }
+ dispatcher.dispatch({ ...opts, [kQueuedAbort]: queuedAbortHook(handler) }, handler);
+ }
+ __name(dispatchWithSignal, "dispatchWithSignal");
+ module2.exports = {
+ addSignal,
+ removeSignal,
+ dispatchWithSignal
+ };
+ }
+});
+
// lib/api/api-request.js
var require_api_request = __commonJS({
"lib/api/api-request.js"(exports2, module2) {
@@ -18497,6 +18793,7 @@ var require_api_request = __commonJS({
var { Readable } = require_readable();
var { InvalidArgumentError, RequestAbortedError } = require_errors();
var util = require_util();
+ var { dispatchWithSignal } = require_abort_signal();
function noop() {
}
__name(noop, "noop");
@@ -18525,6 +18822,9 @@ var require_api_request = __commonJS({
if (onInfo && typeof onInfo !== "function") {
throw new InvalidArgumentError("invalid onInfo callback");
}
+ if (signal?.aborted) {
+ throw signal.reason ?? new RequestAbortedError();
+ }
super("UNDICI_REQUEST");
} catch (err) {
if (util.isStream(body)) {
@@ -18546,9 +18846,7 @@ var require_api_request = __commonJS({
this.highWaterMark = highWaterMark;
this.reason = null;
this.removeAbortListener = null;
- if (signal?.aborted) {
- this.reason = signal.reason ?? new RequestAbortedError();
- } else if (signal) {
+ if (signal) {
this.removeAbortListener = util.addAbortListener(signal, () => {
this.reason = signal.reason ?? new RequestAbortedError();
if (this.res) {
@@ -18577,7 +18875,7 @@ var require_api_request = __commonJS({
const responseHeaderData = responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers;
if (statusCode < 200) {
if (this.onInfo) {
- this.onInfo({ statusCode, headers: responseHeaderData });
+ this.runInAsyncScope(this.onInfo, null, { statusCode, headers: responseHeaderData });
}
return;
}
@@ -18679,7 +18977,11 @@ var require_api_request = __commonJS({
}
try {
const handler = new RequestHandler(opts, callback);
- this.dispatch(opts, handler);
+ if (opts.signal == null) {
+ this.dispatch(opts, handler);
+ } else {
+ dispatchWithSignal(this, opts, handler);
+ }
} catch (err) {
if (typeof callback !== "function") {
throw err;
@@ -18694,61 +18996,6 @@ var require_api_request = __commonJS({
}
});
-// lib/api/abort-signal.js
-var require_abort_signal = __commonJS({
- "lib/api/abort-signal.js"(exports2, module2) {
- "use strict";
- var { addAbortListener } = require_util();
- var { RequestAbortedError } = require_errors();
- var kListener = /* @__PURE__ */ Symbol("kListener");
- var kSignal = /* @__PURE__ */ Symbol("kSignal");
- function abort(self) {
- if (self.abort) {
- self.abort(self[kSignal]?.reason);
- } else {
- self.reason = self[kSignal]?.reason ?? new RequestAbortedError();
- }
- removeSignal(self);
- }
- __name(abort, "abort");
- function addSignal(self, signal) {
- self.reason = null;
- self[kSignal] = null;
- self[kListener] = null;
- if (!signal) {
- return;
- }
- if (signal.aborted) {
- abort(self);
- return;
- }
- self[kSignal] = signal;
- self[kListener] = () => {
- abort(self);
- };
- addAbortListener(self[kSignal], self[kListener]);
- }
- __name(addSignal, "addSignal");
- function removeSignal(self) {
- if (!self[kSignal]) {
- return;
- }
- if ("removeEventListener" in self[kSignal]) {
- self[kSignal].removeEventListener("abort", self[kListener]);
- } else {
- self[kSignal].removeListener("abort", self[kListener]);
- }
- self[kSignal] = null;
- self[kListener] = null;
- }
- __name(removeSignal, "removeSignal");
- module2.exports = {
- addSignal,
- removeSignal
- };
- }
-});
-
// lib/api/api-stream.js
var require_api_stream = __commonJS({
"lib/api/api-stream.js"(exports2, module2) {
@@ -18757,7 +19004,7 @@ var require_api_stream = __commonJS({
var { AsyncResource } = require("node:async_hooks");
var { InvalidArgumentError, InvalidReturnValueError } = require_errors();
var util = require_util();
- var { addSignal, removeSignal } = require_abort_signal();
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
function noop() {
}
__name(noop, "noop");
@@ -18953,7 +19200,11 @@ var require_api_stream = __commonJS({
}
try {
const handler = new StreamHandler(opts, factory, callback);
- this.dispatch(opts, handler);
+ if (opts.signal == null) {
+ this.dispatch(opts, handler);
+ } else {
+ dispatchWithSignal(this, opts, handler);
+ }
} catch (err) {
if (typeof callback !== "function") {
throw err;
@@ -18985,7 +19236,7 @@ var require_api_pipeline = __commonJS({
} = require_errors();
var util = require_util();
var { kBodyUsed } = require_symbols();
- var { addSignal, removeSignal } = require_abort_signal();
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
function noop() {
}
__name(noop, "noop");
@@ -19080,7 +19331,7 @@ var require_api_pipeline = __commonJS({
if (!err && !ret._readableState.endEmitted) {
err = new RequestAbortedError();
}
- if (abort && err) {
+ if (abort && (err || !res?.readableEnded)) {
abort();
}
util.destroy(body, err);
@@ -19174,7 +19425,12 @@ var require_api_pipeline = __commonJS({
function pipeline(opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler);
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
+ const pipelineOpts = { ...opts, body: pipelineHandler.req };
+ if (opts.signal == null) {
+ this.dispatch(pipelineOpts, pipelineHandler);
+ } else {
+ dispatchWithSignal(this, pipelineOpts, pipelineHandler);
+ }
return pipelineHandler.ret;
} catch (err) {
return new PassThrough().destroy(err);
@@ -19194,7 +19450,7 @@ var require_api_upgrade = __commonJS({
var assert = require("node:assert");
var util = require_util();
var { kHTTP2Stream } = require_symbols();
- var { addSignal, removeSignal } = require_abort_signal();
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
var UpgradeHandler = class extends AsyncResource {
static {
__name(this, "UpgradeHandler");
@@ -19275,7 +19531,11 @@ var require_api_upgrade = __commonJS({
method: opts.method || "GET",
upgrade: opts.protocol || "Websocket"
};
- this.dispatch(upgradeOpts, upgradeHandler);
+ if (opts.signal == null) {
+ this.dispatch(upgradeOpts, upgradeHandler);
+ } else {
+ dispatchWithSignal(this, upgradeOpts, upgradeHandler);
+ }
} catch (err) {
if (typeof callback !== "function") {
throw err;
@@ -19297,7 +19557,7 @@ var require_api_connect = __commonJS({
var { AsyncResource } = require("node:async_hooks");
var { InvalidArgumentError, SocketError } = require_errors();
var util = require_util();
- var { addSignal, removeSignal } = require_abort_signal();
+ var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal();
var ConnectHandler = class extends AsyncResource {
static {
__name(this, "ConnectHandler");
@@ -19371,7 +19631,11 @@ var require_api_connect = __commonJS({
try {
const connectHandler = new ConnectHandler(opts, callback);
const connectOptions = { ...opts, method: "CONNECT" };
- this.dispatch(connectOptions, connectHandler);
+ if (opts.signal == null) {
+ this.dispatch(connectOptions, connectHandler);
+ } else {
+ dispatchWithSignal(this, connectOptions, connectHandler);
+ }
} catch (err) {
if (typeof callback !== "function") {
throw err;
diff --git a/src/undici_version.h b/src/undici_version.h
index e0a4578df6c..81bfc11bb62 100644
--- a/src/undici_version.h
+++ b/src/undici_version.h
@@ -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 "8.12.4"
+#define UNDICI_VERSION "8.13.1"
#endif // SRC_UNDICI_VERSION_H_