Skip to content

Commit

Permalink
refactor(helper/adapter): improve runtime detection (#2846)
Browse files Browse the repository at this point in the history
* refactor: improve runtime detection

detect runtime using navigator.userAgent when possible

* fix typescript types

* export knownUserAgents

* add return type for checkUserAgentEquals
  • Loading branch information
6km authored May 29, 2024
1 parent 7cbca60 commit a44d888
Showing 1 changed file with 31 additions and 8 deletions.
39 changes: 31 additions & 8 deletions src/helper/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,28 +35,51 @@ export const env = <T extends Record<string, unknown>, C extends Context = Conte
return runtimeEnvHandlers[runtime]()
}

export const knownUserAgents: Partial<Record<Runtime, string>> = {
deno: 'Deno',
bun: 'Bun',
workerd: 'Cloudflare-Workers',
node: 'Node.js',
}

export const getRuntimeKey = (): Runtime => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const global = globalThis as any

if (global?.Deno !== undefined) {
return 'deno'
}
if (global?.Bun !== undefined) {
return 'bun'
}
if (typeof global?.WebSocketPair === 'function') {
return 'workerd'
// check if the current runtime supports navigator.userAgent
const userAgentSupported =
typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string'

// if supported, check the user agent
if (userAgentSupported) {
for (const [runtimeKey, userAgent] of Object.entries(knownUserAgents)) {
if (checkUserAgentEquals(userAgent)) {
return runtimeKey as Runtime
}
}
}

// check if running on Edge Runtime
if (typeof global?.EdgeRuntime === 'string') {
return 'edge-light'
}

// check if running on Fastly
if (global?.fastly !== undefined) {
return 'fastly'
}

// userAgent isn't supported before Node v21.1.0; so fallback to the old way
if (global?.process?.release?.name === 'node') {
return 'node'
}

// couldn't detect the runtime
return 'other'
}

export const checkUserAgentEquals = (platform: string): boolean => {
const userAgent = navigator.userAgent

return userAgent.startsWith(platform)
}

0 comments on commit a44d888

Please sign in to comment.