Skip to content

Commit 8f8117c

Browse files
authored
node: enhance detect runtime to include cf workers (#760)
1 parent 96d67b7 commit 8f8117c

File tree

4 files changed

+24
-5
lines changed

4 files changed

+24
-5
lines changed

packages/node/src/__tests__/http-integration.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,11 @@ describe('Method Smoke Tests', () => {
5151
ajs.identify({ userId: 'my_user_id', traits: { foo: 'bar' } })
5252
await resolveCtx(ajs, 'identify')
5353
expect(calls[0].batch[0]._metadata).toMatchInlineSnapshot(
54-
{ nodeVersion: expect.any(String), runtime: 'node' },
54+
{ nodeVersion: expect.any(String), jsRuntime: 'node' },
5555
`
5656
Object {
57+
"jsRuntime": "node",
5758
"nodeVersion": Any<String>,
58-
"runtime": "node",
5959
}
6060
`
6161
)

packages/node/src/lib/__tests__/env.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,13 @@ describe(detectRuntime, () => {
3131
process = { env: {} }
3232
expect(detectRuntime()).toEqual<RuntimeEnv>('node')
3333
})
34+
35+
it('should return cloudflare worker if correct env', () => {
36+
// @ts-ignore
37+
// eslint-disable-next-line
38+
delete process.env
39+
// @ts-ignore
40+
globalThis.WebSocketPair = {}
41+
expect(detectRuntime()).toEqual<RuntimeEnv>('cloudflare-worker')
42+
})
3443
})

packages/node/src/lib/env.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
export type RuntimeEnv = 'node' | 'browser' | 'web-worker' | 'unknown'
1+
export type RuntimeEnv =
2+
| 'node'
3+
| 'browser'
4+
| 'web-worker'
5+
| 'cloudflare-worker'
6+
| 'unknown'
27

38
export const detectRuntime = (): RuntimeEnv => {
49
if (typeof process === 'object' && process && process.env) {
@@ -9,9 +14,14 @@ export const detectRuntime = (): RuntimeEnv => {
914
return 'browser'
1015
}
1116

17+
// @ts-ignore
18+
if (typeof WebSocketPair !== 'undefined') {
19+
return 'cloudflare-worker'
20+
}
21+
1222
if (
1323
// @ts-ignore
14-
typeof WorkerGlobalScope !== 'undefined' && // this may sometimes be available in a CF worker, so check for importScripts
24+
typeof WorkerGlobalScope !== 'undefined' &&
1525
// @ts-ignore
1626
typeof importScripts === 'function'
1727
) {

packages/node/src/plugins/segmentio/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ function normalizeEvent(ctx: Context) {
1212
if (runtime === 'node') {
1313
ctx.updateEvent('_metadata.nodeVersion', process.versions.node)
1414
}
15-
ctx.updateEvent('_metadata.runtime', runtime)
15+
ctx.updateEvent('_metadata.jsRuntime', runtime)
1616
}
1717

1818
type DefinedPluginFields =

0 commit comments

Comments
 (0)