Skip to content

Commit faf1f47

Browse files
vrugtehagelsxzz
andauthored
fix: fallbacks for when env variables are disallowed (#5)
Co-authored-by: Kevin Deng <[email protected]>
1 parent 6508a03 commit faf1f47

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

‎src/node.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,15 @@ import {
1010
import { humanize, selectColor } from './utils.ts'
1111
import type { Debugger, DebugOptions, InspectOptions } from './types.ts'
1212

13+
let env: Record<string, string | undefined> = {}
14+
try {
15+
// eslint-disable-next-line no-void -- Access process.env here because it may throw in restricted environments.
16+
void process.env.DEBUG
17+
env = process.env
18+
} catch {}
19+
1320
const colors: number[] =
14-
process.stderr.getColorDepth && process.stderr.getColorDepth() > 2
21+
process.stderr.getColorDepth && process.stderr.getColorDepth(env) > 2
1522
? [
1623
20, 21, 26, 27, 32, 33, 38, 39, 40, 41, 42, 43, 44, 45, 56, 57, 62, 63,
1724
68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 92, 93, 98, 99, 112, 113, 128,
@@ -21,7 +28,7 @@ const colors: number[] =
2128
]
2229
: [6, 2, 3, 4, 5, 1]
2330

24-
const inspectOpts: InspectOptions = Object.keys(process.env)
31+
const inspectOpts: InspectOptions = Object.keys(env)
2532
.filter((key) => /^debug_/i.test(key))
2633
.reduce<Record<string, any>>((obj, key) => {
2734
// Camel-case
@@ -31,7 +38,7 @@ const inspectOpts: InspectOptions = Object.keys(process.env)
3138
.replace(/_([a-z])/g, (_, k) => k.toUpperCase())
3239

3340
// Coerce string value into JS value
34-
let value: any = process.env[key]
41+
let value: any = env[key]
3542
const lowerCase = typeof value === 'string' && value.toLowerCase()
3643
if (value === 'null') {
3744
value = null
@@ -142,11 +149,11 @@ export function createDebug(
142149

143150
function save(namespaces: string): void {
144151
if (namespaces) {
145-
process.env.DEBUG = namespaces
152+
env.DEBUG = namespaces
146153
} else {
147154
// If you set a process.env field to null or undefined, it gets cast to the
148155
// string 'null' or 'undefined'. Just delete instead.
149-
delete process.env.DEBUG
156+
delete env.DEBUG
150157
}
151158
}
152159

@@ -160,7 +167,7 @@ function enable(namespaces: string): void {
160167
}
161168

162169
// side-effect
163-
_enable(process.env.DEBUG || '')
170+
_enable(env.DEBUG || '')
164171

165172
export type * from './types.ts'
166173
export { disable, enable, enabled, namespaces }

0 commit comments

Comments
 (0)