@tschk/moonshine-astro 0.4.4 → 0.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/env.ts ADDED
@@ -0,0 +1,361 @@
1
+ /** Independent host-free Astro typed environment schema helpers (`astro:env`). */
2
+
3
+ export type EnvContext = "client" | "server";
4
+ export type EnvAccess = "public" | "secret";
5
+
6
+ export interface EnvFieldBaseOptions<T> {
7
+ context: EnvContext;
8
+ access: EnvAccess;
9
+ optional?: boolean;
10
+ default?: T;
11
+ }
12
+
13
+ export interface StringEnvFieldOptions extends EnvFieldBaseOptions<string> {
14
+ min?: number;
15
+ max?: number;
16
+ length?: number;
17
+ url?: boolean;
18
+ includes?: string;
19
+ startsWith?: string;
20
+ endsWith?: string;
21
+ }
22
+
23
+ export interface NumberEnvFieldOptions extends EnvFieldBaseOptions<number> {
24
+ min?: number;
25
+ max?: number;
26
+ gt?: number;
27
+ lt?: number;
28
+ int?: boolean;
29
+ }
30
+
31
+ export type BooleanEnvFieldOptions = EnvFieldBaseOptions<boolean>;
32
+
33
+ export interface EnumEnvFieldOptions<
34
+ Values extends readonly [string, ...string[]],
35
+ > extends EnvFieldBaseOptions<Values[number]> {
36
+ values: Values;
37
+ }
38
+
39
+ export interface EnvFieldDefinition<
40
+ T = unknown,
41
+ Context extends EnvContext = EnvContext,
42
+ Access extends EnvAccess = EnvAccess,
43
+ > {
44
+ readonly type: "string" | "number" | "boolean" | "enum";
45
+ readonly context: Context;
46
+ readonly access: Access;
47
+ readonly optional: boolean;
48
+ readonly default?: T;
49
+ readonly options: EnvFieldBaseOptions<any>;
50
+ parse(rawValue: string | undefined, key: string): T;
51
+ }
52
+
53
+ export interface AstroEnvIssue {
54
+ key: string;
55
+ message: string;
56
+ }
57
+
58
+ export class AstroEnvError extends Error {
59
+ readonly issues: AstroEnvIssue[];
60
+
61
+ constructor(issues: AstroEnvIssue[]) {
62
+ const summary = issues.map((i) => `${i.key}: ${i.message}`).join("; ");
63
+ super(`Invalid environment variables: ${summary}`);
64
+ this.name = "AstroEnvError";
65
+ this.issues = issues;
66
+ }
67
+ }
68
+
69
+ type ResolvedFieldType<
70
+ Base,
71
+ Opts extends { optional?: boolean; default?: Base },
72
+ > = Opts["optional"] extends true
73
+ ? Opts["default"] extends Base
74
+ ? Base
75
+ : Base | undefined
76
+ : Base;
77
+
78
+ function createStringField<Opts extends StringEnvFieldOptions>(
79
+ options: Opts,
80
+ ): EnvFieldDefinition<
81
+ ResolvedFieldType<string, Opts>,
82
+ Opts["context"],
83
+ Opts["access"]
84
+ > {
85
+ if (options.context === "client" && options.access === "secret") {
86
+ throw new AstroEnvError([
87
+ {
88
+ key: "envField.string",
89
+ message: 'Client environment variables cannot have access "secret".',
90
+ },
91
+ ]);
92
+ }
93
+ return {
94
+ type: "string",
95
+ context: options.context,
96
+ access: options.access,
97
+ optional: Boolean(options.optional),
98
+ default: options.default as ResolvedFieldType<string, Opts>,
99
+ options: { ...options },
100
+ parse(rawValue: string | undefined, key: string) {
101
+ const value =
102
+ rawValue === undefined || rawValue === "" ? options.default : rawValue;
103
+ if (value === undefined) {
104
+ if (options.optional) {
105
+ return undefined as ResolvedFieldType<string, Opts>;
106
+ }
107
+ throw new Error(`Required environment variable "${key}" is missing.`);
108
+ }
109
+ if (options.length !== undefined && value.length !== options.length) {
110
+ throw new Error(
111
+ `Expected "${key}" to have length ${options.length}, got ${value.length}.`,
112
+ );
113
+ }
114
+ if (options.min !== undefined && value.length < options.min) {
115
+ throw new Error(
116
+ `Expected "${key}" to have minimum length ${options.min}, got ${value.length}.`,
117
+ );
118
+ }
119
+ if (options.max !== undefined && value.length > options.max) {
120
+ throw new Error(
121
+ `Expected "${key}" to have maximum length ${options.max}, got ${value.length}.`,
122
+ );
123
+ }
124
+ if (options.url && !URL.canParse(value)) {
125
+ throw new Error(`Expected "${key}" to be a valid URL.`);
126
+ }
127
+ if (options.includes !== undefined && !value.includes(options.includes)) {
128
+ throw new Error(`Expected "${key}" to include "${options.includes}".`);
129
+ }
130
+ if (
131
+ options.startsWith !== undefined &&
132
+ !value.startsWith(options.startsWith)
133
+ ) {
134
+ throw new Error(
135
+ `Expected "${key}" to start with "${options.startsWith}".`,
136
+ );
137
+ }
138
+ if (options.endsWith !== undefined && !value.endsWith(options.endsWith)) {
139
+ throw new Error(`Expected "${key}" to end with "${options.endsWith}".`);
140
+ }
141
+ return value as ResolvedFieldType<string, Opts>;
142
+ },
143
+ };
144
+ }
145
+
146
+ function createNumberField<Opts extends NumberEnvFieldOptions>(
147
+ options: Opts,
148
+ ): EnvFieldDefinition<
149
+ ResolvedFieldType<number, Opts>,
150
+ Opts["context"],
151
+ Opts["access"]
152
+ > {
153
+ if (options.context === "client" && options.access === "secret") {
154
+ throw new AstroEnvError([
155
+ {
156
+ key: "envField.number",
157
+ message: 'Client environment variables cannot have access "secret".',
158
+ },
159
+ ]);
160
+ }
161
+ return {
162
+ type: "number",
163
+ context: options.context,
164
+ access: options.access,
165
+ optional: Boolean(options.optional),
166
+ default: options.default as ResolvedFieldType<number, Opts>,
167
+ options: { ...options },
168
+ parse(rawValue: string | undefined, key: string) {
169
+ if (rawValue === undefined || rawValue === "") {
170
+ if (options.default !== undefined) {
171
+ return options.default as ResolvedFieldType<number, Opts>;
172
+ }
173
+ if (options.optional) {
174
+ return undefined as ResolvedFieldType<number, Opts>;
175
+ }
176
+ throw new Error(`Required environment variable "${key}" is missing.`);
177
+ }
178
+ const num = Number(rawValue);
179
+ if (Number.isNaN(num)) {
180
+ throw new Error(`Expected "${key}" to be a valid number.`);
181
+ }
182
+ if (options.int && !Number.isInteger(num)) {
183
+ throw new Error(`Expected "${key}" to be an integer.`);
184
+ }
185
+ if (options.min !== undefined && num < options.min) {
186
+ throw new Error(`Expected "${key}" to be >= ${options.min}.`);
187
+ }
188
+ if (options.max !== undefined && num > options.max) {
189
+ throw new Error(`Expected "${key}" to be <= ${options.max}.`);
190
+ }
191
+ if (options.gt !== undefined && num <= options.gt) {
192
+ throw new Error(`Expected "${key}" to be > ${options.gt}.`);
193
+ }
194
+ if (options.lt !== undefined && num >= options.lt) {
195
+ throw new Error(`Expected "${key}" to be < ${options.lt}.`);
196
+ }
197
+ return num as ResolvedFieldType<number, Opts>;
198
+ },
199
+ };
200
+ }
201
+
202
+ function createBooleanField<Opts extends BooleanEnvFieldOptions>(
203
+ options: Opts,
204
+ ): EnvFieldDefinition<
205
+ ResolvedFieldType<boolean, Opts>,
206
+ Opts["context"],
207
+ Opts["access"]
208
+ > {
209
+ if (options.context === "client" && options.access === "secret") {
210
+ throw new AstroEnvError([
211
+ {
212
+ key: "envField.boolean",
213
+ message: 'Client environment variables cannot have access "secret".',
214
+ },
215
+ ]);
216
+ }
217
+ return {
218
+ type: "boolean",
219
+ context: options.context,
220
+ access: options.access,
221
+ optional: Boolean(options.optional),
222
+ default: options.default as ResolvedFieldType<boolean, Opts>,
223
+ options: { ...options },
224
+ parse(rawValue: string | undefined, key: string) {
225
+ if (rawValue === undefined || rawValue === "") {
226
+ if (options.default !== undefined) {
227
+ return options.default as ResolvedFieldType<boolean, Opts>;
228
+ }
229
+ if (options.optional) {
230
+ return undefined as ResolvedFieldType<boolean, Opts>;
231
+ }
232
+ throw new Error(`Required environment variable "${key}" is missing.`);
233
+ }
234
+ if (rawValue === "true" || rawValue === "1") {
235
+ return true as ResolvedFieldType<boolean, Opts>;
236
+ }
237
+ if (rawValue === "false" || rawValue === "0") {
238
+ return false as ResolvedFieldType<boolean, Opts>;
239
+ }
240
+ throw new Error(
241
+ `Expected "${key}" to be a boolean ("true", "false", "1", or "0").`,
242
+ );
243
+ },
244
+ };
245
+ }
246
+
247
+ function createEnumField<
248
+ const Values extends readonly [string, ...string[]],
249
+ Opts extends EnumEnvFieldOptions<Values>,
250
+ >(
251
+ options: Opts,
252
+ ): EnvFieldDefinition<
253
+ ResolvedFieldType<Values[number], Opts>,
254
+ Opts["context"],
255
+ Opts["access"]
256
+ > {
257
+ if (options.context === "client" && options.access === "secret") {
258
+ throw new AstroEnvError([
259
+ {
260
+ key: "envField.enum",
261
+ message: 'Client environment variables cannot have access "secret".',
262
+ },
263
+ ]);
264
+ }
265
+ return {
266
+ type: "enum",
267
+ context: options.context,
268
+ access: options.access,
269
+ optional: Boolean(options.optional),
270
+ default: options.default as ResolvedFieldType<Values[number], Opts>,
271
+ options: { ...options },
272
+ parse(rawValue: string | undefined, key: string) {
273
+ const value =
274
+ rawValue === undefined || rawValue === "" ? options.default : rawValue;
275
+ if (value === undefined) {
276
+ if (options.optional) {
277
+ return undefined as ResolvedFieldType<Values[number], Opts>;
278
+ }
279
+ throw new Error(`Required environment variable "${key}" is missing.`);
280
+ }
281
+ if (!options.values.includes(value as Values[number])) {
282
+ throw new Error(
283
+ `Expected "${key}" to be one of [${options.values.join(", ")}], got "${value}".`,
284
+ );
285
+ }
286
+ return value as ResolvedFieldType<Values[number], Opts>;
287
+ },
288
+ };
289
+ }
290
+
291
+ export const envField = {
292
+ string: createStringField,
293
+ number: createNumberField,
294
+ boolean: createBooleanField,
295
+ enum: createEnumField,
296
+ };
297
+
298
+ export type InferEnvField<F> =
299
+ F extends EnvFieldDefinition<infer T, any, any> ? T : never;
300
+
301
+ export type InferEnvSchema<S extends Record<string, EnvFieldDefinition<any>>> =
302
+ {
303
+ [K in keyof S]: InferEnvField<S[K]>;
304
+ };
305
+
306
+ let customEnvSource: Record<string, string | undefined> | undefined;
307
+
308
+ export function setEnvSource(source: Record<string, string | undefined>): void {
309
+ customEnvSource = { ...source };
310
+ }
311
+
312
+ export function getEnvSource(): Record<string, string | undefined> {
313
+ if (customEnvSource) {
314
+ return customEnvSource;
315
+ }
316
+ if (typeof process !== "undefined" && process.env) {
317
+ return process.env as Record<string, string | undefined>;
318
+ }
319
+ return {};
320
+ }
321
+
322
+ export function resetEnvSource(): void {
323
+ customEnvSource = undefined;
324
+ }
325
+
326
+ export function getSecret(key: string): string | undefined {
327
+ const source = getEnvSource();
328
+ return source[key];
329
+ }
330
+
331
+ export function validateEnv<S extends Record<string, EnvFieldDefinition<any>>>(
332
+ schema: S,
333
+ env: Record<string, string | undefined> = getEnvSource(),
334
+ filter?: { context?: EnvContext; access?: EnvAccess },
335
+ ): InferEnvSchema<S> {
336
+ const result: Record<string, unknown> = {};
337
+ const issues: AstroEnvIssue[] = [];
338
+
339
+ for (const [key, field] of Object.entries(schema)) {
340
+ if (filter?.context && field.context !== filter.context) {
341
+ continue;
342
+ }
343
+ if (filter?.access && field.access !== filter.access) {
344
+ continue;
345
+ }
346
+ try {
347
+ result[key] = field.parse(env[key], key);
348
+ } catch (err) {
349
+ issues.push({
350
+ key,
351
+ message: err instanceof Error ? err.message : String(err),
352
+ });
353
+ }
354
+ }
355
+
356
+ if (issues.length > 0) {
357
+ throw new AstroEnvError(issues);
358
+ }
359
+
360
+ return result as InferEnvSchema<S>;
361
+ }