From 904bfc219ff13a726a7d73984b385f7f9cefe27a Mon Sep 17 00:00:00 2001 From: Zephyr Lykos Date: Wed, 31 Jan 2024 15:26:16 +0800 Subject: [PATCH] chore: refine esbuild & node detection When using the loader for external builtins, `esbuildDetection` is undefined. This commit defines `__UNDICI_IS_NODE__` on `globalThis` in the loader and deletes it after loading Undici. `esbuildDetection` has also been extracted as a variable at the top level of the module, to support deleting `__UNDICI_IS_NODE__` on `globalThis` to avoid polluting the global namespace. --- build/wasm.js | 2 ++ lib/fetch/index.js | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/build/wasm.js b/build/wasm.js index 3fb8f103117..ca89ec7d4cf 100644 --- a/build/wasm.js +++ b/build/wasm.js @@ -101,6 +101,8 @@ if (EXTERNAL_PATH) { writeFileSync(join(ROOT, 'loader.js'), ` 'use strict' +globalThis.__UNDICI_IS_NODE__ = true module.exports = require('node:module').createRequire('${EXTERNAL_PATH}/loader.js')('./index-fetch.js') +delete globalThis.__UNDICI_IS_NODE__ `) } diff --git a/lib/fetch/index.js b/lib/fetch/index.js index 9693782552f..857baa72840 100644 --- a/lib/fetch/index.js +++ b/lib/fetch/index.js @@ -66,6 +66,10 @@ const { webidl } = require('./webidl') const { STATUS_CODES } = require('node:http') const GET_OR_HEAD = ['GET', 'HEAD'] +const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' + ? 'node' + : 'undici' + /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL @@ -1473,7 +1477,7 @@ async function httpNetworkOrCacheFetch ( // user agents should append `User-Agent`/default `User-Agent` value to // httpRequest’s header list. if (!httpRequest.headersList.contains('user-agent', true)) { - httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node', true) + httpRequest.headersList.append('user-agent', defaultUserAgent) } // 15. If httpRequest’s cache mode is "default" and httpRequest’s header