-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
528 lines (488 loc) · 14.8 KB
/
index.ts
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
import { ZodCustomIssue, ZodError, ZodIssue, ZodObject, ZodType, z } from "zod";
type ErrorMessage<T extends string> = T;
type Simplify<T> = {
[P in keyof T]: T[P];
} & {};
type Impossible<T extends Record<string, any>> = Partial<
Record<keyof T, never>
>;
type ClientOptions<
TPrefix extends string,
TClient extends Record<string, ZodType>
> = {
clientPrefix: TPrefix;
client: Partial<{
[K in keyof TClient]: K extends `${TPrefix}${string}`
? TClient[K]
: ErrorMessage<`${K extends string
? K
: never} is not prefixed with ${TPrefix}.`>;
}>;
};
type ServerOptions<
TPrefix extends string,
TServer extends Record<string, ZodType>
> = {
server: Partial<{
[TKey in keyof TServer]: TPrefix extends ""
? TServer[TKey]
: TKey extends `${TPrefix}${string}`
? ErrorMessage<`${TKey extends `${TPrefix}${string}`
? TKey
: never} should not be prefixed with ${TPrefix}.`>
: TServer[TKey];
}>;
};
type TransformOptions<
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>,
TTransformOutput extends Record<string, unknown>
> = {
transform: (
envs: Simplify<
z.infer<ZodObject<TShared>> &
z.infer<ZodObject<TClient>> &
z.infer<ZodObject<TServer>>
>
) => TTransformOutput;
};
type FeatureFlagsOptions<
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>,
TTransformOutput extends Record<string, unknown>,
TFeatureFlags extends FeatureFlagsExtend<
TShared,
TClient,
TServer,
TTransformOutput
>
> = {
featureFlags: TFeatureFlags;
};
type SubType<Base, Condition> = Pick<
Base,
{
[Key in keyof Base]: Base[Key] extends Condition ? Key : never;
}[keyof Base]
>;
type FeatureFlagsExtend<
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>,
TTransformOutput extends Record<string, unknown>
> = {
[K in keyof SubType<
EnvBaseReturn<TShared, TClient, TServer, TTransformOutput>,
boolean
>]?: {
[X in Exclude<
keyof Simplify<
TTransformOutput &
z.infer<ZodObject<TShared>> &
z.infer<ZodObject<TClient>> &
z.infer<ZodObject<TServer>>
>,
K
>]?: true;
};
};
type EnvBaseReturn<
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>,
TTransformOutput extends Record<string, unknown>
> = Simplify<
TTransformOutput &
z.infer<ZodObject<TShared>> &
z.infer<ZodObject<TClient>> &
z.infer<ZodObject<TServer>>
>;
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
k: infer I
) => void
? I
: never;
type EnvReturnAux<
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>,
TTransformOutput extends Record<string, unknown>,
TFeatureFlags extends FeatureFlagsExtend<
TShared,
TClient,
TServer,
TTransformOutput
>
> = UnionToIntersection<
| {
[K in keyof TFeatureFlags]: {
__flags:
| ({
[D in keyof TFeatureFlags[K]]: D extends keyof EnvBaseReturn<
TShared,
TClient,
TServer,
TTransformOutput
>
? NonNullable<
EnvBaseReturn<
TShared,
TClient,
TServer,
TTransformOutput
>[D]
>
: never;
} & { [x in K]: true })
| ({ [x in K]: false } & {
[D in keyof TFeatureFlags[K]]: D extends keyof EnvBaseReturn<
TShared,
TClient,
TServer,
TTransformOutput
>
? EnvBaseReturn<TShared, TClient, TServer, TTransformOutput>[D]
: never;
});
};
}[keyof TFeatureFlags]
>;
type EnvReturn<
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>,
TTransformOutput extends Record<string, unknown>,
TFeatureFlags extends FeatureFlagsExtend<
TShared,
TClient,
TServer,
TTransformOutput
>
> = keyof EnvReturnAux<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
> extends never
? EnvBaseReturn<TShared, TClient, TServer, TTransformOutput>
: {
[K in keyof EnvReturnAux<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>]: EnvReturnAux<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>[K];
}[keyof EnvReturnAux<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>] &
EnvBaseReturn<TShared, TClient, TServer, TTransformOutput>;
type RuntimeOptions<
TPrefix extends string,
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>
> = {
runtimeEnv: Record<
TPrefix extends ""
?
| {
[TKey in keyof TShared]: TKey extends string ? TKey : never;
}[keyof TShared]
| {
[TKey in keyof TClient]: TKey extends string ? TKey : never;
}[keyof TClient]
| {
[TKey in keyof TServer]: TKey extends string ? TKey : never;
}[keyof TServer]
:
| {
[TKey in keyof TShared]: TKey extends string ? TKey : never;
}[keyof TShared]
| {
[TKey in keyof TClient]: TKey extends `${TPrefix}${string}`
? TKey
: never;
}[keyof TClient]
| {
[TKey in keyof TServer]: TKey extends `${TPrefix}${string}`
? never
: TKey;
}[keyof TServer],
string | boolean | number | undefined
>;
};
type CommonOptions<TShared extends Record<string, ZodType>> = {
/**
* How to determine whether the app is running on the server or the client.
* @default typeof window === "undefined"
*/
isServer?: boolean;
/**
* Shared variables, often those that are provided by build tools and is available to both client and server,
* but isn't prefixed and doesn't require to be manually supplied. For example `NODE_ENV`, `VERCEL_URL` etc.
*/
shared?: TShared;
/**
* Called when validation fails. By default the error is logged,
* and an error is thrown telling what environment variables are invalid.
*/
onValidationError?: (error: ZodError) => never;
/**
* Called when a server-side environment variable is accessed on the client.
* By default an error is thrown.
*/
onInvalidAccess?: (variable: string) => never;
/**
* Whether to skip validation of environment variables.
* @default false
*/
skipValidation?: boolean;
};
type EnvOptions<
TPrefix extends string,
TShared extends Record<string, ZodType>,
TClient extends Record<string, ZodType>,
TServer extends Record<string, ZodType>,
TTransformOutput extends Record<string, unknown>,
TFeatureFlags extends FeatureFlagsExtend<
TShared,
TClient,
TServer,
TTransformOutput
>
> = (
| (ClientOptions<TPrefix, TClient> &
ServerOptions<TPrefix, TServer> &
TransformOptions<TShared, TClient, TServer, TTransformOutput> &
FeatureFlagsOptions<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>)
| (ClientOptions<TPrefix, TClient> &
ServerOptions<TPrefix, TServer> &
TransformOptions<TShared, TClient, TServer, TTransformOutput> &
Impossible<FeatureFlagsOptions<never, never, never, never, never>>)
| (ClientOptions<TPrefix, TClient> &
ServerOptions<TPrefix, TServer> &
Impossible<TransformOptions<never, never, never, never>> &
FeatureFlagsOptions<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>)
| (ClientOptions<TPrefix, TClient> &
Impossible<ServerOptions<never, never>> &
TransformOptions<TShared, TClient, TServer, TTransformOutput> &
FeatureFlagsOptions<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>)
| (Impossible<ClientOptions<never, never>> &
ServerOptions<TPrefix, TServer> &
TransformOptions<TShared, TClient, TServer, TTransformOutput> &
FeatureFlagsOptions<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>)
| (ClientOptions<TPrefix, TClient> &
ServerOptions<TPrefix, TServer> &
Impossible<TransformOptions<never, never, never, never>> &
Impossible<FeatureFlagsOptions<never, never, never, never, never>>)
| (ClientOptions<TPrefix, TClient> &
Impossible<ServerOptions<never, never>> &
TransformOptions<TShared, TClient, TServer, TTransformOutput> &
Impossible<FeatureFlagsOptions<never, never, never, never, never>>)
| (Impossible<ClientOptions<never, never>> &
ServerOptions<TPrefix, TServer> &
TransformOptions<TShared, TClient, TServer, TTransformOutput> &
Impossible<FeatureFlagsOptions<never, never, never, never, never>>)
| (ClientOptions<TPrefix, TClient> &
Impossible<ServerOptions<never, never>> &
Impossible<TransformOptions<never, never, never, never>> &
FeatureFlagsOptions<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>)
| (Impossible<ClientOptions<never, never>> &
ServerOptions<TPrefix, TServer> &
Impossible<TransformOptions<never, never, never, never>> &
FeatureFlagsOptions<
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>)
| (ClientOptions<TPrefix, TClient> &
Impossible<ServerOptions<never, never>> &
Impossible<TransformOptions<never, never, never, never>> &
Impossible<FeatureFlagsOptions<never, never, never, never, never>>)
| (ServerOptions<TPrefix, TServer> &
Impossible<ClientOptions<never, never>> &
Impossible<TransformOptions<never, never, never, never>> &
Impossible<FeatureFlagsOptions<never, never, never, never, never>>)
) &
RuntimeOptions<TPrefix, TShared, TClient, TServer> &
CommonOptions<TShared>;
export function createEnv<
TPrefix extends string = "",
TShared extends Record<string, ZodType> = NonNullable<unknown>,
TClient extends Record<string, ZodType> = NonNullable<unknown>,
TServer extends Record<string, ZodType> = NonNullable<unknown>,
TTransformOutput extends Record<string, unknown> = NonNullable<unknown>,
TFeatureFlags extends FeatureFlagsExtend<
TShared,
TClient,
TServer,
TTransformOutput
> = FeatureFlagsExtend<
NonNullable<unknown>,
NonNullable<unknown>,
NonNullable<unknown>,
NonNullable<unknown>
>
>(
opts: EnvOptions<
TPrefix,
TShared,
TClient,
TServer,
TTransformOutput,
TFeatureFlags
>
): EnvReturn<TShared, TClient, TServer, TTransformOutput, TFeatureFlags> {
const runtimeEnv = opts.runtimeEnv ?? process.env;
const skip = !!opts.skipValidation;
if (skip) return runtimeEnv as any;
const _client = typeof opts.client === "object" ? opts.client : {};
const _server = typeof opts.server === "object" ? opts.server : {};
const _shared = typeof opts.shared === "object" ? opts.shared : {};
const client = z.object(_client);
const server = z.object(_server);
const shared = z.object(_shared);
const isServer = opts.isServer ?? typeof window === "undefined";
const allClient = client.merge(shared);
const allServer = server.merge(shared).merge(client);
const parsed = isServer
? allServer.safeParse(runtimeEnv) // on server we can validate all env vars
: allClient.safeParse(runtimeEnv); // on client we can only validate the ones that are exposed
const onValidationError =
opts.onValidationError ??
((error: ZodError) => {
console.error(
"❌ Invalid environment variables:",
error.flatten().fieldErrors
);
throw new Error("Invalid environment variables");
});
const onFlagError = (errors: ZodError[]) => {
console.error(
"❌ Invalid feature flags deps:",
errors.reduce((acc, e) => ({ ...acc, ...e.flatten().fieldErrors }), {})
);
throw new Error("Invalid feature flags");
};
if (!parsed.success) {
onValidationError(parsed.error);
}
const onInvalidAccess =
opts.onInvalidAccess ??
((_variable: string) => {
throw new Error(
"❌ Attempted to access a server-side environment variable on the client"
);
});
if (parsed.success === false) {
return onValidationError(parsed.error);
}
let data = parsed.data;
if (opts.transform) {
data = opts.transform(parsed.data as any) as any;
}
if (opts.featureFlags) {
const featureFlagsSafeParse = (featureFlags: {}, data: unknown) => {
let success = true;
let errors: ZodError[] = [];
Object.entries(featureFlags).forEach(([flag, def]) => {
const schema = z.discriminatedUnion(flag, [
z.object({
[flag]: z.literal(true),
...Object.keys(def as {}).reduce((acc, env) => {
if (!isServer && !env.startsWith(opts.clientPrefix ?? "")) {
return acc;
}
return {
...acc,
[env]: z.custom((val) => val !== undefined, {
message: `Expected non undefined value, received undefined`,
params: { env, flag },
fatal: true,
}),
};
}, {}),
}),
z.object({
[flag]: z.literal(false),
}),
z.object({
[flag]: z.undefined(),
}),
]);
const parsed = schema.safeParse(data);
if (!parsed.success) {
success = false;
errors.push(parsed.error);
}
});
return { success, errors };
};
const flagsParse = featureFlagsSafeParse(opts.featureFlags, data);
if (!flagsParse.success) {
onFlagError(flagsParse.errors);
}
}
const env = new Proxy(data, {
get(target, prop) {
if (typeof prop !== "string") return undefined;
if (
!isServer &&
opts.clientPrefix &&
!prop.startsWith(opts.clientPrefix) &&
shared.shape[prop as keyof typeof shared.shape] === undefined
) {
return onInvalidAccess(prop);
}
return target[prop as keyof typeof target];
},
});
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any
return env as any;
}