-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrewire.ts
More file actions
270 lines (250 loc) · 7.77 KB
/
rewire.ts
File metadata and controls
270 lines (250 loc) · 7.77 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
/**
* @fileoverview Environment variable rewiring utilities for testing.
* Uses AsyncLocalStorage for context-isolated overrides that work with concurrent tests.
*
* Features:
* - Context-isolated overrides via withEnv() for advanced use cases
* - Test-friendly setEnv/clearEnv/resetEnv that work in beforeEach/afterEach
* - Compatible with vi.stubEnv() - reads from process.env as final fallback
* - Thread-safe for concurrent test execution
*/
import process from 'node:process'
import { hasOwn } from '../objects'
import { envAsBoolean } from './helpers'
import { MapCtor, ObjectEntries } from '../primordials'
let _async_hooks: typeof import('node:async_hooks') | undefined
/**
* Lazily load the async_hooks module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getAsyncHooks() {
if (_async_hooks === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_async_hooks = /*@__PURE__*/ require('node:async_hooks')
}
return _async_hooks as typeof import('node:async_hooks')
}
type EnvOverrides = Map<string, string | undefined>
// Isolated execution context storage for nested overrides (withEnv/withEnvSync)
// AsyncLocalStorage creates isolated contexts that don't leak between concurrent code
const { AsyncLocalStorage } = getAsyncHooks()
const isolatedOverridesStorage = new AsyncLocalStorage<EnvOverrides>()
// Shared test hook overrides (setEnv/clearEnv/resetEnv in beforeEach/afterEach)
// IMPORTANT: Use globalThis to ensure singleton across duplicate module instances
// In coverage mode, both src and dist versions of this module may be loaded,
// but they must share the same Map for rewiring to work.
// Only initialize in test environment to avoid polluting production runtime
// Vitest automatically sets VITEST=true when running tests
const sharedOverridesSymbol = Symbol.for(
'@socketsecurity/lib/env/rewire/test-overrides',
)
const _globalThis = globalThis as Record<symbol, unknown>
const isVitestEnv = envAsBoolean(process.env['VITEST'])
if (isVitestEnv && !_globalThis[sharedOverridesSymbol]) {
_globalThis[sharedOverridesSymbol] = new MapCtor<string, string | undefined>()
}
const sharedOverrides: Map<string, string | undefined> | undefined =
_globalThis[sharedOverridesSymbol] as
| Map<string, string | undefined>
| undefined
/**
* Clear a specific environment variable override.
*
* @param key - The environment variable name to clear
*
* @example
* ```typescript
* import { setEnv, clearEnv } from '@socketsecurity/lib/env/rewire'
*
* setEnv('CI', '1')
* clearEnv('CI')
* ```
*/
export function clearEnv(key: string): void {
sharedOverrides?.delete(key)
}
/**
* Get an environment variable value, checking overrides first.
*
* Resolution order:
* 1. Isolated overrides (temporary - set via withEnv/withEnvSync)
* 2. Shared overrides (persistent - set via setEnv in beforeEach)
* 3. process.env (including vi.stubEnv modifications)
*
* @internal Used by env getters to support test rewiring
*
* @example
* ```typescript
* import { getEnvValue } from '@socketsecurity/lib/env/rewire'
*
* const value = getEnvValue('NODE_ENV')
* // e.g. 'production' or undefined
* ```
*/
export function getEnvValue(key: string): string | undefined {
// Check isolated overrides first (highest priority - temporary via withEnv)
const isolatedOverrides = isolatedOverridesStorage.getStore()
if (isolatedOverrides?.has(key)) {
return isolatedOverrides.get(key)
}
// Check shared overrides (persistent via setEnv in beforeEach)
if (sharedOverrides?.has(key)) {
return sharedOverrides.get(key)
}
// Fall back to process.env (works with vi.stubEnv)
return process.env[key]
}
/**
* Check if an environment variable has been overridden.
*
* @param key - The environment variable name to check
* @returns `true` if the variable has been overridden, `false` otherwise
*
* @example
* ```typescript
* import { setEnv, hasOverride } from '@socketsecurity/lib/env/rewire'
*
* hasOverride('CI') // false
* setEnv('CI', '1')
* hasOverride('CI') // true
* ```
*/
export function hasOverride(key: string): boolean {
const isolatedOverrides = isolatedOverridesStorage.getStore()
return !!(isolatedOverrides?.has(key) || sharedOverrides?.has(key))
}
/**
* Check if an environment variable exists (has a key), checking overrides first.
*
* Resolution order:
* 1. Isolated overrides (temporary - set via withEnv/withEnvSync)
* 2. Shared overrides (persistent - set via setEnv in beforeEach)
* 3. process.env (including vi.stubEnv modifications)
*
* @internal Used by env getters to check for key presence (not value truthiness)
*
* @example
* ```typescript
* import { isInEnv } from '@socketsecurity/lib/env/rewire'
*
* isInEnv('PATH') // true (usually set)
* isInEnv('MISSING') // false
* ```
*/
export function isInEnv(key: string): boolean {
// Check isolated overrides first (highest priority - temporary via withEnv)
const isolatedOverrides = isolatedOverridesStorage.getStore()
if (isolatedOverrides?.has(key)) {
return true
}
// Check shared overrides (persistent via setEnv in beforeEach)
if (sharedOverrides?.has(key)) {
return true
}
// Fall back to process.env (works with vi.stubEnv)
return hasOwn(process.env, key)
}
/**
* Clear all environment variable overrides.
* Useful in afterEach hooks to ensure clean test state.
*
* @example
* ```typescript
* import { resetEnv } from './rewire'
*
* afterEach(() => {
* resetEnv()
* })
* ```
*/
export function resetEnv(): void {
sharedOverrides?.clear()
}
/**
* Set an environment variable override for testing.
* This does not modify process.env, only affects env getters.
*
* Works in test hooks (beforeEach) without needing AsyncLocalStorage context.
* Vitest's module isolation ensures each test file has independent overrides.
*
* @example
* ```typescript
* import { setEnv, resetEnv } from './rewire'
* import { getCI } from './ci'
*
* beforeEach(() => {
* setEnv('CI', '1')
* })
*
* afterEach(() => {
* resetEnv()
* })
*
* it('should detect CI environment', () => {
* expect(getCI()).toBe(true)
* })
* ```
*/
export function setEnv(key: string, value: string | undefined): void {
sharedOverrides?.set(key, value)
}
/**
* Run code with environment overrides in an isolated AsyncLocalStorage context.
* Creates true context isolation - overrides don't leak to concurrent code.
*
* Useful for tests that need temporary overrides without affecting other tests
* or for nested override scenarios.
*
* @example
* ```typescript
* import { withEnv } from './rewire'
* import { getCI } from './ci'
*
* // Temporary override in isolated context
* await withEnv({ CI: '1' }, async () => {
* expect(getCI()).toBe(true)
* })
* expect(getCI()).toBe(false) // Override is gone
* ```
*
* @example
* ```typescript
* // Nested overrides work correctly
* setEnv('CI', '1') // Shared override (persistent)
*
* await withEnv({ CI: '0' }, async () => {
* expect(getCI()).toBe(false) // Isolated override takes precedence
* })
*
* expect(getCI()).toBe(true) // Back to shared override
* ```
*/
export async function withEnv<T>(
overrides: Record<string, string | undefined>,
fn: () => T | Promise<T>,
): Promise<T> {
const map = new MapCtor(ObjectEntries(overrides))
return await isolatedOverridesStorage.run(map, fn)
}
/**
* Synchronous version of withEnv for non-async code.
*
* @example
* ```typescript
* import { withEnvSync } from './rewire'
* import { getCI } from './ci'
*
* const result = withEnvSync({ CI: '1' }, () => {
* return getCI()
* })
* expect(result).toBe(true)
* ```
*/
export function withEnvSync<T>(
overrides: Record<string, string | undefined>,
fn: () => T,
): T {
const map = new MapCtor(ObjectEntries(overrides))
return isolatedOverridesStorage.run(map, fn)
}