Skip to content

Commit

Permalink
chore: refine esbuild & node detection (nodejs#2677)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mochaaP authored and crysmags committed Feb 27, 2024
1 parent 010924b commit fd0f87f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 2 additions & 0 deletions build/wasm.js
Original file line number Diff line number Diff line change
Expand Up @@ -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__
`)
}
6 changes: 5 additions & 1 deletion lib/fetch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -1478,7 +1482,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
Expand Down

0 comments on commit fd0f87f

Please sign in to comment.