UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

68 lines (67 loc) • 2.57 kB
import { t as bindAbortRelay } from "./fetch-timeout-CNI8mjv-.mjs"; import { r as normalizeRequestInitHeadersForFetch } from "./fetch-headers-DD03wtQj.mjs"; //#region src/infra/fetch.ts const wrapFetchWithAbortSignalMarker = Symbol.for("openclaw.fetch.abort-signal-wrapped"); function withDuplex(init, input) { const hasInitBody = init?.body != null; const hasRequestBody = !hasInitBody && typeof Request !== "undefined" && input instanceof Request && input.body != null; if (!hasInitBody && !hasRequestBody) return init; if (init && "duplex" in init) return init; return { ...init, duplex: "half" }; } /** * Wraps fetch so Node-compatible duplex bodies, normalized headers, and foreign * AbortSignal implementations work against runtimes expecting native signals. */ function wrapFetchWithAbortSignal(fetchImpl) { if (fetchImpl[wrapFetchWithAbortSignalMarker]) return fetchImpl; const wrapped = ((input, init) => { const patchedInit = normalizeRequestInitHeadersForFetch(withDuplex(init, input)); const signal = patchedInit?.signal; if (!signal || typeof AbortSignal !== "undefined" && signal instanceof AbortSignal || typeof AbortController === "undefined" || typeof signal.addEventListener !== "function") return fetchImpl(input, patchedInit); const controller = new AbortController(); const onAbort = bindAbortRelay(controller); let listenerAttached = false; if (signal.aborted) controller.abort(); else { signal.addEventListener("abort", onAbort, { once: true }); listenerAttached = true; } const cleanup = () => { if (!listenerAttached || typeof signal.removeEventListener !== "function") return; listenerAttached = false; try { signal.removeEventListener("abort", onAbort); } catch {} }; try { return fetchImpl(input, { ...patchedInit, signal: controller.signal }).finally(cleanup); } catch (error) { cleanup(); throw error; } }); const wrappedFetch = Object.assign(wrapped, fetchImpl); const fetchWithPreconnect = fetchImpl; wrappedFetch.preconnect = typeof fetchWithPreconnect.preconnect === "function" ? fetchWithPreconnect.preconnect.bind(fetchWithPreconnect) : () => {}; Object.defineProperty(wrappedFetch, wrapFetchWithAbortSignalMarker, { value: true, enumerable: false, configurable: false, writable: false }); return wrappedFetch; } function resolveFetch(fetchImpl) { const resolved = fetchImpl ?? globalThis.fetch; if (!resolved) return; return wrapFetchWithAbortSignal(resolved); } //#endregion export { wrapFetchWithAbortSignal as n, resolveFetch as t };