-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenv.ts
More file actions
305 lines (285 loc) · 8.99 KB
/
env.ts
File metadata and controls
305 lines (285 loc) · 8.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/**
* @fileoverview Environment variable parsing and conversion utilities.
* Provides type-safe conversion functions for boolean, number, and string values.
*/
const NumberCtor = Number
// IMPORTANT: Do not use destructuring here - use direct assignment instead.
// tsgo has a bug that incorrectly transpiles destructured exports, resulting in
// `exports.SomeName = void 0;` which causes runtime errors.
// See: https://github.com/SocketDev/socket-packageurl-js/issues/3
const NumberIsFinite = Number.isFinite
const NumberParseInt = Number.parseInt
const StringCtor = String
// Common environment variables that have case sensitivity issues on Windows.
// These are checked with case-insensitive matching when exact matches fail.
const caseInsensitiveKeys = new Set([
'APPDATA',
'COMSPEC',
'HOME',
'LOCALAPPDATA',
'PATH',
'PATHEXT',
'PROGRAMFILES',
'SYSTEMROOT',
'TEMP',
'TMP',
'USERPROFILE',
'WINDIR',
])
/**
* Create a case-insensitive environment variable Proxy for Windows compatibility.
* On Windows, environment variables are case-insensitive (PATH vs Path vs path).
* This Proxy provides consistent access regardless of case, with priority given
* to exact matches, then case-insensitive matches for known vars.
*
* **Use Cases:**
* - Cross-platform test environments needing consistent env var access
* - Windows compatibility when passing env to child processes
* - Merging environment overrides while preserving case-insensitive lookups
*
* **Performance Note:**
* Proxy operations have runtime overhead. Only use when Windows case-insensitive
* access is required. For most use cases, process.env directly is sufficient.
*
* @param base - Base environment object (usually process.env)
* @param overrides - Optional overrides to merge
* @returns Proxy that handles case-insensitive env var access
*
* @example
* // Create a Proxy with overrides
* const env = createEnvProxy(process.env, { NODE_ENV: 'test' })
* console.log(env.PATH) // Works with any case: PATH, Path, path
* console.log(env.NODE_ENV) // 'test'
*
* @example
* // Pass to child process spawn
* import { createEnvProxy } from '@socketsecurity/lib/env'
* import { spawn } from '@socketsecurity/lib/spawn'
*
* spawn('node', ['script.js'], {
* env: createEnvProxy(process.env, { NODE_ENV: 'test' })
* })
*/
export function createEnvProxy(
base: NodeJS.ProcessEnv,
overrides?: Record<string, string | undefined>,
): NodeJS.ProcessEnv {
return new Proxy(
{},
{
get(_target, prop) {
if (typeof prop !== 'string') {
return undefined
}
// Priority 1: Check overrides for exact match.
if (overrides && prop in overrides) {
return overrides[prop]
}
// Priority 2: Check base for exact match.
if (prop in base) {
return base[prop]
}
// Priority 3: Case-insensitive lookup for known keys.
const upperProp = prop.toUpperCase()
if (caseInsensitiveKeys.has(upperProp)) {
// Check overrides with case variations.
if (overrides) {
const key = findCaseInsensitiveEnvKey(overrides, upperProp)
if (key !== undefined) {
return overrides[key]
}
}
// Check base with case variations.
const key = findCaseInsensitiveEnvKey(base, upperProp)
if (key !== undefined) {
return base[key]
}
}
return undefined
},
ownKeys(_target) {
const keys = new Set<string>([
...Object.keys(base),
...(overrides ? Object.keys(overrides) : []),
])
return [...keys]
},
getOwnPropertyDescriptor(_target, prop) {
if (typeof prop !== 'string') {
return undefined
}
// Use the same lookup logic as get().
const value = this.get?.(_target, prop, _target)
return value !== undefined
? {
enumerable: true,
configurable: true,
writable: true,
value,
}
: undefined
},
has(_target, prop) {
if (typeof prop !== 'string') {
return false
}
// Check overrides.
if (overrides && prop in overrides) {
return true
}
// Check base.
if (prop in base) {
return true
}
// Case-insensitive check.
const upperProp = prop.toUpperCase()
if (caseInsensitiveKeys.has(upperProp)) {
if (
overrides &&
findCaseInsensitiveEnvKey(overrides, upperProp) !== undefined
) {
return true
}
if (findCaseInsensitiveEnvKey(base, upperProp) !== undefined) {
return true
}
}
return false
},
set(_target, prop, value) {
if (typeof prop === 'string' && overrides) {
overrides[prop] = value
return true
}
return false
},
},
) as NodeJS.ProcessEnv
}
/**
* Convert an environment variable value to a boolean.
*
* @param value - The value to convert
* @param defaultValue - Default when value is null/undefined (default: `false`)
* @returns `true` if value is '1' or 'true' (case-insensitive), `false` otherwise
*
* @example
* ```typescript
* import { envAsBoolean } from '@socketsecurity/lib/env'
*
* envAsBoolean('true') // true
* envAsBoolean('1') // true
* envAsBoolean('false') // false
* envAsBoolean(undefined) // false
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function envAsBoolean(value: unknown, defaultValue = false): boolean {
if (typeof value === 'string') {
const trimmed = value.trim()
return trimmed === '1' || trimmed.toLowerCase() === 'true'
}
if (value === null || value === undefined) {
return !!defaultValue
}
return !!value
}
/**
* Convert an environment variable value to a number.
*
* @param value - The value to convert
* @param defaultValue - Default when value is not a finite number (default: `0`)
* @returns The parsed integer, or the default value if parsing fails
*
* @example
* ```typescript
* import { envAsNumber } from '@socketsecurity/lib/env'
*
* envAsNumber('3000') // 3000
* envAsNumber('abc') // 0
* envAsNumber(undefined) // 0
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function envAsNumber(value: unknown, defaultValue = 0): number {
const numOrNaN = NumberParseInt(String(value), 10)
const numMayBeNegZero = NumberIsFinite(numOrNaN)
? numOrNaN
: NumberCtor(defaultValue)
// Ensure -0 is treated as 0.
return numMayBeNegZero || 0
}
/**
* Convert an environment variable value to a trimmed string.
*
* @param value - The value to convert
* @param defaultValue - Default when value is null/undefined (default: `''`)
* @returns The trimmed string value, or the default value
*
* @example
* ```typescript
* import { envAsString } from '@socketsecurity/lib/env'
*
* envAsString(' hello ') // 'hello'
* envAsString(undefined) // ''
* envAsString(null, 'n/a') // 'n/a'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function envAsString(value: unknown, defaultValue = ''): string {
if (typeof value === 'string') {
return value.trim()
}
if (value === null || value === undefined) {
return defaultValue === '' ? defaultValue : StringCtor(defaultValue).trim()
}
return StringCtor(value).trim()
}
/**
* Find a case-insensitive environment variable key match.
* Searches for an environment variable key that matches the given uppercase name,
* using optimized fast-path checks to minimize expensive toUpperCase() calls.
*
* **Use Cases:**
* - Finding PATH when env object has "Path" or "path"
* - Cross-platform env var access where case may vary
* - Custom case-insensitive env lookups
*
* **Performance:**
* - Fast path: Checks length first (O(1)) before toUpperCase (expensive)
* - Only converts to uppercase when length matches
* - Early exit on first match
*
* @param env - Environment object or env-like record to search
* @param upperEnvVarName - Uppercase environment variable name to find (e.g., 'PATH')
* @returns The actual key from env that matches (e.g., 'Path'), or undefined
*
* @example
* // Find PATH regardless of case
* const envObj = { Path: 'C:\\Windows', NODE_ENV: 'test' }
* const key = findCaseInsensitiveEnvKey(envObj, 'PATH')
* console.log(key) // 'Path'
* console.log(envObj[key]) // 'C:\\Windows'
*
* @example
* // Not found returns undefined
* const key = findCaseInsensitiveEnvKey({}, 'MISSING')
* console.log(key) // undefined
*/
export function findCaseInsensitiveEnvKey(
env: Record<string, string | undefined>,
upperEnvVarName: string,
): string | undefined {
const targetLength = upperEnvVarName.length
for (const key of Object.keys(env)) {
// Fast path: bail early if lengths don't match.
if (key.length !== targetLength) {
continue
}
// Only call toUpperCase if length matches.
if (key.toUpperCase() === upperEnvVarName) {
return key
}
}
return undefined
}