From 83c9f578a94005c3682d655ab3a79eb18962e2c9 Mon Sep 17 00:00:00 2001 From: Zephyr Lykos Date: Sat, 10 Feb 2024 01:41:56 +0800 Subject: [PATCH] chore: refine esbuild & node detection (#2677) 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 | 5 ++++- 2 files changed, 6 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 8f05732ab93..936c71785a2 100644 --- a/lib/fetch/index.js +++ b/lib/fetch/index.js @@ -67,6 +67,9 @@ const { STATUS_CODES } = require('node:http') const GET_OR_HEAD = ['GET', 'HEAD'] const channels = require('../core/diagnostics.js').channels +const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined' + ? 'node' + : 'undici' /** @type {import('buffer').resolveObjectURL} */ let resolveObjectURL @@ -1553,7 +1556,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