From e57349992f230b6b13e80613eb84302560aa5ba8 Mon Sep 17 00:00:00 2001 From: Yueming Gao <92220633+Jye10032@users.noreply.github.com> Date: Sat, 2 May 2026 00:20:18 +0800 Subject: [PATCH] fix(fetch): defer global access in fetch adapter (#7260) --- lib/adapters/fetch.js | 15 +++++++-------- tests/unit/adapters/fetch.test.js | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/lib/adapters/fetch.js b/lib/adapters/fetch.js index df47fd71..324be7aa 100644 --- a/lib/adapters/fetch.js +++ b/lib/adapters/fetch.js @@ -18,13 +18,6 @@ const DEFAULT_CHUNK_SIZE = 64 * 1024; const { isFunction } = utils; -const globalFetchAPI = (({ Request, Response }) => ({ - Request, - Response, -}))(utils.global); - -const { ReadableStream, TextEncoder } = utils.global; - const test = (fn, ...args) => { try { return !!fn(...args); @@ -34,11 +27,17 @@ const test = (fn, ...args) => { }; const factory = (env) => { + const globalObject = utils.global ?? globalThis; + const { ReadableStream, TextEncoder } = globalObject; + env = utils.merge.call( { skipUndefined: true, }, - globalFetchAPI, + { + Request: globalObject.Request, + Response: globalObject.Response, + }, env ); diff --git a/tests/unit/adapters/fetch.test.js b/tests/unit/adapters/fetch.test.js index b964ba5c..f7d4664d 100644 --- a/tests/unit/adapters/fetch.test.js +++ b/tests/unit/adapters/fetch.test.js @@ -9,6 +9,7 @@ import { makeEchoStream, } from '../../setup/server.js'; import axios from '../../../index.js'; +import utils from '../../../lib/utils.js'; import { getFetch } from '../../../lib/adapters/fetch.js'; import stream from 'stream'; import { AbortController } from 'abortcontroller-polyfill/dist/cjs-ponyfill.js'; @@ -814,6 +815,24 @@ describe.runIf(typeof fetch === 'function')('supports fetch with nodejs', () => }); describe('env config', () => { + it('should fallback to globalThis when utils.global is temporarily undefined', () => { + const originalGlobal = utils.global; + + try { + utils.global = undefined; + + assert.doesNotThrow(() => + getFetch({ + env: { + fetch() {}, + }, + }) + ); + } finally { + utils.global = originalGlobal; + } + }); + it('should respect env fetch API configuration', async () => { const { data, headers } = await fetchAxios.get('/', { env: {