@vite-hub/env 0.0.3 → 0.1.0

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.
Files changed (50) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +243 -28
  3. package/dist/access-B3qzBHye.js +54 -0
  4. package/dist/auth.d.ts +32 -0
  5. package/dist/auth.js +44 -0
  6. package/dist/bridge-CdNdTN1V.d.ts +374 -0
  7. package/dist/bridge-error-CFuU5zIz.js +65 -0
  8. package/dist/bridge.d.ts +2 -0
  9. package/dist/bridge.js +192 -0
  10. package/dist/cli-CMQPQbii.js +487 -0
  11. package/dist/cli-DEwcUIe0.d.ts +81 -0
  12. package/dist/cli.d.ts +41 -0
  13. package/dist/cli.js +2 -0
  14. package/dist/database.d.ts +21 -0
  15. package/dist/database.js +183 -0
  16. package/dist/declarations-CiRdb1qP.d.ts +32 -0
  17. package/dist/declarations-DAVgctKD.js +236 -0
  18. package/dist/error-diagnostics-CrxjYNYr.js +43 -0
  19. package/dist/http.d.ts +2 -0
  20. package/dist/http.js +122 -0
  21. package/dist/index.d.ts +13 -8
  22. package/dist/index.js +5 -4
  23. package/dist/internal/agent.d.ts +5 -0
  24. package/dist/internal/agent.js +22 -0
  25. package/dist/internal/connections.d.ts +18 -0
  26. package/dist/internal/connections.js +31 -0
  27. package/dist/presets.d.ts +15 -6
  28. package/dist/presets.js +21 -2
  29. package/dist/provider.d.ts +5 -0
  30. package/dist/provider.js +8 -0
  31. package/dist/schema.d.ts +5 -6
  32. package/dist/schema.js +26 -8
  33. package/dist/seal.d.ts +14 -0
  34. package/dist/seal.js +49 -0
  35. package/dist/secret-C2191nAa.d.ts +11 -0
  36. package/dist/secret.d.ts +1 -10
  37. package/dist/server-DufVswRJ.js +670 -0
  38. package/dist/server.d.ts +23 -4
  39. package/dist/server.js +2 -3
  40. package/dist/values-D_r6V774.js +148 -0
  41. package/dist/virtual-module.d.ts +34 -0
  42. package/dist/virtual.d.ts +2 -15
  43. package/dist/vite.d.ts +37 -14
  44. package/dist/vite.js +1058 -292
  45. package/package.json +84 -16
  46. package/dist/declarations-BIBfEwer.d.ts +0 -23
  47. package/dist/declarations-Cy5XamUA.js +0 -144
  48. package/dist/errors-RUmAFDJn.js +0 -112
  49. package/dist/server-B2Dp8Nc0.js +0 -59
  50. package/dist/types-FcnPKias.d.ts +0 -153
@@ -0,0 +1,670 @@
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-CrxjYNYr.js";
2
+ import { i as stringValueSchema, n as parseEnvValue, t as envValueTypeName } from "./values-D_r6V774.js";
3
+ import { SecretEnv } from "./secret.js";
4
+ import { createEnvBridgeHandler } from "./http.js";
5
+ import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { ViteHubError, isViteHubError } from "@vite-hub/runtime";
7
+ import * as v from "valibot";
8
+ //#region ../internal/src/runtime/cloudflare-env.ts
9
+ let activeEnv;
10
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
11
+ const runtimeGlobal = globalThis;
12
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
13
+ function getActiveCloudflareEnv() {
14
+ const scoped = activeEnvStorage.getStore();
15
+ if (scoped) return scoped.env;
16
+ const host = globalThis;
17
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
18
+ }
19
+ function ownValue(value, key) {
20
+ if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
21
+ return Reflect.get(value, key);
22
+ }
23
+ function ownObject(value) {
24
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
25
+ }
26
+ /** The objects where H3 1, H3 2, and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
27
+ function cloudflareOwners(target) {
28
+ const context = ownObject(ownValue(target, "context"));
29
+ const platform = ownObject(ownValue(context, "_platform"));
30
+ const req = ownObject(ownValue(target, "req"));
31
+ const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
32
+ return [
33
+ ownObject(ownValue(context, "cloudflare")),
34
+ ownObject(ownValue(platform, "cloudflare")),
35
+ ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare")),
36
+ ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"))
37
+ ];
38
+ }
39
+ function getCloudflareEnv(event, options = {}) {
40
+ const target = ownObject(event);
41
+ for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
42
+ return options.fallback === false ? void 0 : getActiveCloudflareEnv();
43
+ }
44
+ //#endregion
45
+ //#region ../internal/src/secret.ts
46
+ const secretEncoder = new TextEncoder();
47
+ /** HKDF salt for every ViteHub-derived secret. A different salt than Nuxt's keeps both derivations apart for one shared root. */
48
+ const viteHubSecretSalt = "vitehub";
49
+ function hex(buffer) {
50
+ return [...new Uint8Array(buffer)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
51
+ }
52
+ /**
53
+ * Reads the root app secret from an env record: `VITEHUB_SECRET`, then `NUXT_APP_SECRET`, so a Nuxt app needs only one
54
+ * secret. Returns `undefined` when neither is a non-empty string.
55
+ */
56
+ function readViteHubSecret(env) {
57
+ for (const name of ["VITEHUB_SECRET", "NUXT_APP_SECRET"]) {
58
+ const value = env[name];
59
+ if (typeof value === "string" && value) return value;
60
+ }
61
+ }
62
+ /**
63
+ * Derives a 32-byte secret for one purpose from the root secret, hex-encoded. It uses HKDF-SHA256 with the salt
64
+ * `vitehub` and the purpose as `info`. The result is stable while the root is unchanged and distinct for every purpose.
65
+ * Throws a `TypeError` when the root is shorter than 32 characters or the purpose is empty. It uses no Node API.
66
+ */
67
+ async function deriveViteHubSecret(root, purpose) {
68
+ if (root.length < 32) throw new TypeError(`[vitehub] VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.`);
69
+ if (!purpose) throw new TypeError("[vitehub] A derived secret requires a purpose.");
70
+ const key = await globalThis.crypto.subtle.importKey("raw", secretEncoder.encode(root), "HKDF", false, ["deriveBits"]);
71
+ return hex(await globalThis.crypto.subtle.deriveBits({
72
+ hash: "SHA-256",
73
+ info: secretEncoder.encode(purpose),
74
+ name: "HKDF",
75
+ salt: secretEncoder.encode(viteHubSecretSalt)
76
+ }, key, 256));
77
+ }
78
+ //#endregion
79
+ //#region src/core/errors.ts
80
+ const envErrorMessages = {
81
+ ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.",
82
+ ENV_ASYNC_REQUIRED: "[vitehub] Server Env requires asynchronous loading.",
83
+ ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.",
84
+ ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.",
85
+ ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed."
86
+ };
87
+ const envSourceIdentifierSet = /* @__PURE__ */ new Set([
88
+ "custom",
89
+ "env",
90
+ "git:branch",
91
+ "git:commit",
92
+ "git:ref",
93
+ "git:sha",
94
+ "git:tag",
95
+ "package.json",
96
+ "provider"
97
+ ]);
98
+ function invalidOptions() {
99
+ throw envErrorDiagnostics.ENV_R0007({ message: "[vitehub] Invalid Env error options." });
100
+ }
101
+ function own(value, key) {
102
+ if (typeof value !== "object" || value === null || Array.isArray(value)) invalidOptions();
103
+ try {
104
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
105
+ if (descriptor === void 0) return void 0;
106
+ if (!("value" in descriptor)) invalidOptions();
107
+ return descriptor.value;
108
+ } catch {
109
+ invalidOptions();
110
+ }
111
+ }
112
+ function createEnvError(options) {
113
+ const code = own(options, "code");
114
+ if (typeof code !== "string" || !Object.hasOwn(envErrorMessages, code)) invalidOptions();
115
+ const cause = own(options, "cause");
116
+ const details = normalizeDetails(code, own(options, "details"));
117
+ return new ViteHubError(code, envErrorMessages[code], {
118
+ ...cause === void 0 ? {} : { cause },
119
+ ...details === void 0 ? {} : { details }
120
+ });
121
+ }
122
+ function invalidEnvDeclaration(path, diagnostic) {
123
+ return createEnvError({
124
+ cause: envErrorDiagnostics.ENV_R0008({ message: diagnostic }),
125
+ code: "ENV_DECLARATION_INVALID",
126
+ details: optionalPath(path)
127
+ });
128
+ }
129
+ function asyncServerEnvRequired(path) {
130
+ return createEnvError({
131
+ cause: envErrorDiagnostics.ENV_R0009({ message: `Server Env at ${path} uses env.provider(). Use loadServerEnv() or runWithServerEnv().` }),
132
+ code: "ENV_ASYNC_REQUIRED",
133
+ details: optionalPath(path)
134
+ });
135
+ }
136
+ function missingRequiredEnv(source, diagnostic, path) {
137
+ const pathDetails = optionalPath(path);
138
+ return createEnvError({
139
+ cause: envErrorDiagnostics.ENV_R0010({ message: diagnostic }),
140
+ code: "ENV_REQUIRED_MISSING",
141
+ details: {
142
+ ...pathDetails,
143
+ source: publicSourceIdentifier(source)
144
+ }
145
+ });
146
+ }
147
+ function invalidRuntimeEnvValue(source, diagnostic, path) {
148
+ return createEnvError({
149
+ cause: envErrorDiagnostics.ENV_R0011({ message: diagnostic }),
150
+ code: "ENV_RUNTIME_VALUE_INVALID",
151
+ details: {
152
+ ...optionalPath(path),
153
+ source: publicSourceIdentifier(source)
154
+ }
155
+ });
156
+ }
157
+ function envSourceFailed(source, cause) {
158
+ return createEnvError({
159
+ cause,
160
+ code: "ENV_SOURCE_FAILED",
161
+ details: { source: publicSourceIdentifier(source) }
162
+ });
163
+ }
164
+ function isAbortError(value) {
165
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
166
+ try {
167
+ return value.name === "AbortError";
168
+ } catch {
169
+ return false;
170
+ }
171
+ }
172
+ function publicSourceIdentifier(source) {
173
+ if (envSourceIdentifierSet.has(source)) return source;
174
+ if (source.startsWith("env:")) return "env";
175
+ if (source.startsWith("package.json:")) return "package.json";
176
+ return "custom";
177
+ }
178
+ function normalizeDetails(code, details) {
179
+ if (details === void 0) return void 0;
180
+ if (typeof details !== "object" || details === null || Array.isArray(details)) invalidOptions();
181
+ const normalized = {};
182
+ if (code === "ENV_ASYNC_REQUIRED" || code === "ENV_DECLARATION_INVALID" || code === "ENV_REQUIRED_MISSING" || code === "ENV_RUNTIME_VALUE_INVALID") {
183
+ const path = safePath(own(details, "path"));
184
+ if (path) normalized.path = path;
185
+ }
186
+ if (code !== "ENV_ASYNC_REQUIRED" && code !== "ENV_DECLARATION_INVALID") {
187
+ const source = own(details, "source");
188
+ if (envSourceIdentifierSet.has(source)) normalized.source = source;
189
+ }
190
+ return Object.keys(normalized).length ? normalized : void 0;
191
+ }
192
+ function optionalPath(path) {
193
+ const normalized = safePath(path);
194
+ return normalized ? { path: normalized } : {};
195
+ }
196
+ function safePath(path) {
197
+ if (typeof path !== "string" || path.length > 256) return void 0;
198
+ return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? path : void 0;
199
+ }
200
+ //#endregion
201
+ //#region src/core/registry.ts
202
+ const recordSchema = v.object({});
203
+ const envEntrySchema = v.object({
204
+ required: v.boolean(),
205
+ secret: v.boolean(),
206
+ source: v.object({
207
+ kind: v.literal("env"),
208
+ name: v.string()
209
+ })
210
+ });
211
+ const providerEntrySchema = v.object({
212
+ required: v.boolean(),
213
+ secret: v.boolean(),
214
+ source: v.object({
215
+ key: v.string(),
216
+ kind: v.literal("provider"),
217
+ provider: v.string()
218
+ })
219
+ });
220
+ function isRecord(value) {
221
+ return v.is(recordSchema, value) && !Array.isArray(value);
222
+ }
223
+ function isRuntimeLiteralEntry(value) {
224
+ return isRecord(value) && value.kind === "literal";
225
+ }
226
+ function isRuntimeEnvEntry(value) {
227
+ return isRecord(value) && isRecord(value.source) && v.is(envEntrySchema, value);
228
+ }
229
+ function isRuntimeProviderEntry(value) {
230
+ return isRecord(value) && isRecord(value.source) && v.is(providerEntrySchema, value);
231
+ }
232
+ /** Visits declarations once. Literal values and declaration metadata are opaque to traversal. */
233
+ function* runtimeRegistryEntries(value, path = "env.server") {
234
+ if (isRuntimeLiteralEntry(value) || isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) {
235
+ yield {
236
+ entry: value,
237
+ path
238
+ };
239
+ return;
240
+ }
241
+ if (!isRecord(value)) return;
242
+ for (const [key, child] of Object.entries(value)) yield* runtimeRegistryEntries(child, `${path}.${key.includes(".") ? "!" : ""}${key}`);
243
+ }
244
+ //#endregion
245
+ //#region src/server.ts
246
+ function processEnv() {
247
+ return typeof process === "object" && process && process.env ? process.env : {};
248
+ }
249
+ function runtimeEnv(event) {
250
+ return {
251
+ ...processEnv(),
252
+ ...getCloudflareEnv(event)
253
+ };
254
+ }
255
+ let warnedGeneratedSecret = false;
256
+ /**
257
+ * Derives a 32-byte hex secret for one purpose from the root app secret, `VITEHUB_SECRET` (or `NUXT_APP_SECRET`).
258
+ * It uses HKDF-SHA256, so the result is stable while the root is unchanged and distinct for every purpose.
259
+ * Namespace the purpose to its owner, such as `my-module:session`. ViteHub reserves the `vitehub:` prefix.
260
+ * Throws `ENV_REQUIRED_MISSING` when no root secret is set, and `ENV_RUNTIME_VALUE_INVALID` when it is shorter than 32 characters.
261
+ */
262
+ async function deriveSecret(purpose, event, rootOverride, generatedOverride = false, rootEnvKey) {
263
+ const env = runtimeEnv(event);
264
+ const root = rootOverride ?? readViteHubSecret(env) ?? (rootEnvKey ? env[rootEnvKey] : void 0);
265
+ if (!root) throw missingRequiredEnv("env", "deriveSecret() requires VITEHUB_SECRET. Generate one with `openssl rand -base64 32`.", "VITEHUB_SECRET");
266
+ if (root.length < 32) throw invalidRuntimeEnvValue("env", `VITEHUB_SECRET must be at least 32 characters. Generate one with \`openssl rand -base64 32\`.`, "VITEHUB_SECRET");
267
+ if ((generatedOverride || env.VITEHUB_SECRET_GENERATED === "1") && !warnedGeneratedSecret) {
268
+ warnedGeneratedSecret = true;
269
+ console.warn("[vitehub] A generated development VITEHUB_SECRET is in use. Set VITEHUB_SECRET for deployments: builds never generate one.");
270
+ }
271
+ return await deriveViteHubSecret(root, purpose);
272
+ }
273
+ function hasRuntimeName(entry, env, name) {
274
+ return Object.hasOwn(env, name) && env[name] !== void 0 && !(entry.source.skipEmpty && env[name] === "");
275
+ }
276
+ function readRuntimeSource(entry, env) {
277
+ for (const name of entry.source.names || [entry.source.name]) if (hasRuntimeName(entry, env, name)) return {
278
+ found: true,
279
+ name,
280
+ value: env[name]
281
+ };
282
+ return { found: false };
283
+ }
284
+ /** Report which kind of name supplied the value, and whether a shadowed conventional name holds another value. */
285
+ function runtimeSourceOrigin(entry, env, source) {
286
+ const canonical = entry.source.canonical;
287
+ if (!source.found || canonical === void 0 || canonical === false) return {};
288
+ if (source.name !== canonical) return { via: "conventional" };
289
+ return (entry.source.names || [entry.source.name]).some((name) => name !== canonical && hasRuntimeName(entry, env, name) && env[name] !== source.value) ? {
290
+ conflict: true,
291
+ via: "canonical"
292
+ } : { via: "canonical" };
293
+ }
294
+ function resolvedRuntimeValue(entry, value, found, path, snapshot = false) {
295
+ const resolved = found ? value : entry.default;
296
+ if (typeof resolved === "undefined") {
297
+ if (entry.required) throw missingRequiredEnv(entry.source.kind, `Missing Runtime Env from ${entry.source.kind}.`, path);
298
+ return;
299
+ }
300
+ const parsed = parseEnvValue(entry.schema ?? stringValueSchema, resolved);
301
+ if (!parsed.success) {
302
+ const message = entry.secret ? "The value does not match its declared type." : parsed.message;
303
+ throw invalidRuntimeEnvValue(entry.source.kind, `Invalid ${path} from ${entry.source.kind}. ${message}`, path);
304
+ }
305
+ const data = snapshot ? snapshotValue(parsed.data) : parsed.data;
306
+ return entry.secret ? new SecretEnv(data) : data;
307
+ }
308
+ function resolveRegistryValue(value, env, path) {
309
+ if (isRuntimeLiteralEntry(value)) return value.value;
310
+ if (isRuntimeEnvEntry(value)) {
311
+ const source = readRuntimeSource(value, env);
312
+ return resolvedRuntimeValue(value, source.value, source.found, path);
313
+ }
314
+ if (isRuntimeProviderEntry(value)) throw asyncServerEnvRequired(path);
315
+ if (!isRecord(value)) return void 0;
316
+ const output = Object.create(null);
317
+ for (const [key, child] of Object.entries(value)) {
318
+ const childPath = `${path}.${key}`;
319
+ if (isRuntimeProviderEntry(child)) Object.defineProperty(output, key, {
320
+ enumerable: true,
321
+ get() {
322
+ throw asyncServerEnvRequired(childPath);
323
+ }
324
+ });
325
+ else output[key] = resolveRegistryValue(child, env, childPath);
326
+ }
327
+ return output;
328
+ }
329
+ /**
330
+ * Copy the namespace records of a resolved registry, so a caller that changes its result does not change the cached
331
+ * one. resolveRegistryValue() creates each namespace without a prototype, and provider getters keep their descriptor.
332
+ */
333
+ function copyNamespaces(value) {
334
+ const descriptors = Object.getOwnPropertyDescriptors(value);
335
+ for (const descriptor of Object.values(descriptors)) if (isNamespace(descriptor.value)) descriptor.value = copyNamespaces(descriptor.value);
336
+ return Object.create(null, descriptors);
337
+ }
338
+ function isNamespace(value) {
339
+ return typeof value === "object" && value !== null && Object.getPrototypeOf(value) === null;
340
+ }
341
+ function providerFor(name, providers) {
342
+ let provider;
343
+ try {
344
+ const configured = providers && Object.hasOwn(providers, name) ? providers[name] : void 0;
345
+ if (configured && typeof configured === "object" && typeof configured.read === "function") {
346
+ const read = configured.read;
347
+ provider = { read: (input) => read.call(configured, input) };
348
+ }
349
+ } catch (cause) {
350
+ throw envSourceFailed("provider", cause);
351
+ }
352
+ if (!provider) throw envErrorDiagnostics.ENV_R0019({ message: "The configured Server Env provider is unavailable or invalid." });
353
+ return provider;
354
+ }
355
+ function abortReason(signal) {
356
+ return signal.reason === void 0 ? Object.assign(envErrorDiagnostics.ENV_R0020({ message: "Server Env loading was aborted." }), { name: "AbortError" }) : signal.reason;
357
+ }
358
+ async function withAbort(operation, signal) {
359
+ if (!signal) return await operation();
360
+ if (signal.aborted) throw abortReason(signal);
361
+ return await new Promise((resolve, reject) => {
362
+ const abort = () => reject(abortReason(signal));
363
+ signal.addEventListener("abort", abort, { once: true });
364
+ Promise.resolve().then(() => {
365
+ if (signal.aborted) throw abortReason(signal);
366
+ return operation();
367
+ }).then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
368
+ });
369
+ }
370
+ function isCancellation(error, signal) {
371
+ return Boolean(signal?.aborted && error === abortReason(signal));
372
+ }
373
+ async function readProvider(provider, input, signal) {
374
+ try {
375
+ return await withAbort(() => provider.read(input), signal);
376
+ } catch (cause) {
377
+ if (isCancellation(cause, signal)) throw cause;
378
+ throw envSourceFailed("provider", cause);
379
+ }
380
+ }
381
+ function collectProviderKeys(value) {
382
+ const requests = /* @__PURE__ */ new Map();
383
+ for (const { entry } of runtimeRegistryEntries(value)) {
384
+ if (!isRuntimeProviderEntry(entry)) continue;
385
+ let keys = requests.get(entry.source.provider);
386
+ if (!keys) {
387
+ keys = /* @__PURE__ */ new Set();
388
+ requests.set(entry.source.provider, keys);
389
+ }
390
+ keys.add(entry.source.key);
391
+ }
392
+ return requests;
393
+ }
394
+ function normalizeProviderValues(value, keys) {
395
+ let record;
396
+ try {
397
+ if (isRecord(value)) record = value;
398
+ } catch (cause) {
399
+ throw envSourceFailed("provider", cause);
400
+ }
401
+ if (!record) throw invalidRuntimeEnvValue("provider", "A Server Env provider must return a plain record.");
402
+ let prototype;
403
+ try {
404
+ prototype = Object.getPrototypeOf(record);
405
+ } catch (cause) {
406
+ throw envSourceFailed("provider", cause);
407
+ }
408
+ if (prototype !== null && prototype !== Object.prototype) throw invalidRuntimeEnvValue("provider", "A Server Env provider must return a plain record.");
409
+ const output = /* @__PURE__ */ new Map();
410
+ for (const key of keys) {
411
+ let descriptor;
412
+ try {
413
+ descriptor = Object.getOwnPropertyDescriptor(record, key);
414
+ } catch (cause) {
415
+ throw envSourceFailed("provider", cause);
416
+ }
417
+ if (!descriptor) {
418
+ output.set(key, void 0);
419
+ continue;
420
+ }
421
+ if (!("value" in descriptor)) throw invalidRuntimeEnvValue("provider", "A Server Env provider returned an accessor instead of a value.");
422
+ output.set(key, descriptor.value);
423
+ }
424
+ return output;
425
+ }
426
+ function createProviderLoads(registry, localEnv, options) {
427
+ if (options.signal?.aborted) throw abortReason(options.signal);
428
+ const loads = /* @__PURE__ */ new Map();
429
+ for (const [name, requested] of collectProviderKeys(registry)) {
430
+ const keys = Object.freeze([...requested]);
431
+ const load = Promise.resolve().then(() => providerFor(name, options.providers)).then((provider) => readProvider(provider, {
432
+ env: localEnv,
433
+ keys,
434
+ signal: options.signal,
435
+ ...options.access ? { access: options.access } : {}
436
+ }, options.signal)).then((value) => normalizeProviderValues(value, keys)).catch((cause) => {
437
+ if (options.signal?.aborted) throw abortReason(options.signal);
438
+ if (isCancellation(cause, options.signal) || isViteHubError(cause)) throw cause;
439
+ throw envSourceFailed("provider", cause);
440
+ });
441
+ loads.set(name, load);
442
+ }
443
+ return loads;
444
+ }
445
+ async function providerValue(entry, loads) {
446
+ const load = loads.get(entry.source.provider);
447
+ if (!load) throw envSourceFailed("provider", envErrorDiagnostics.ENV_R0021({ message: "The Server Env provider was not loaded." }));
448
+ return (await load).get(entry.source.key);
449
+ }
450
+ const skipProviderValue = Symbol("vitehub.env.skip-provider");
451
+ function localRegistryValue(value, env, tolerateInvalid, path) {
452
+ if (isRuntimeLiteralEntry(value)) return snapshotValue(value.value);
453
+ if (isRuntimeProviderEntry(value)) return skipProviderValue;
454
+ if (isRuntimeEnvEntry(value)) try {
455
+ const source = readRuntimeSource(value, env);
456
+ return resolvedRuntimeValue(value, source.value, source.found, path, true);
457
+ } catch (error) {
458
+ if (!tolerateInvalid) throw error;
459
+ return skipProviderValue;
460
+ }
461
+ if (!isRecord(value)) return skipProviderValue;
462
+ const output = Object.create(null);
463
+ for (const [key, child] of Object.entries(value)) {
464
+ const resolved = localRegistryValue(child, env, tolerateInvalid, `${path}.${key}`);
465
+ if (resolved !== skipProviderValue) output[key] = resolved;
466
+ }
467
+ return Object.freeze(output);
468
+ }
469
+ function createLocalEnv(registry, env, tolerateInvalid) {
470
+ return localRegistryValue(registry, env, tolerateInvalid, "env.server");
471
+ }
472
+ async function loadRegistryValue(value, env, loads, path) {
473
+ if (isRuntimeLiteralEntry(value)) return snapshotValue(value.value);
474
+ if (isRuntimeEnvEntry(value)) {
475
+ const source = readRuntimeSource(value, env);
476
+ return resolvedRuntimeValue(value, source.value, source.found, path, true);
477
+ }
478
+ if (isRuntimeProviderEntry(value)) {
479
+ const resolved = await providerValue(value, loads);
480
+ return resolvedRuntimeValue(value, resolved, typeof resolved !== "undefined", path, true);
481
+ }
482
+ if (!isRecord(value)) return void 0;
483
+ const output = Object.create(null);
484
+ for (const [key, child] of Object.entries(value)) output[key] = await loadRegistryValue(child, env, loads, `${path}.${key}`);
485
+ return Object.freeze(output);
486
+ }
487
+ function snapshotValue(value) {
488
+ if (Array.isArray(value)) return Object.freeze(value.map(snapshotValue));
489
+ if (isRecord(value) && Object.getPrototypeOf(value) === Object.prototype) return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, item]) => [key, snapshotValue(item)])));
490
+ return value;
491
+ }
492
+ function inspectionStatus(entry, value, found) {
493
+ if (!found && typeof entry.default !== "undefined") return "defaulted";
494
+ if (!found || typeof value === "undefined") return "missing";
495
+ return parseEnvValue(entry.schema ?? stringValueSchema, value).success ? "available" : "invalid";
496
+ }
497
+ function inspectionPath(path) {
498
+ if (path.length > 256) return {};
499
+ return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? { path } : {};
500
+ }
501
+ function inspectionProvider(entry) {
502
+ return /^[A-Za-z0-9_-]{1,64}$/.test(entry.source.provider) ? { provider: entry.source.provider } : {};
503
+ }
504
+ async function inspectRegistryEntry(value, env, options, loads, path, entries) {
505
+ if (isRuntimeLiteralEntry(value)) {
506
+ entries.push({
507
+ masked: false,
508
+ ...inspectionPath(path),
509
+ required: false,
510
+ source: "literal",
511
+ status: "available"
512
+ });
513
+ return;
514
+ }
515
+ if (isRuntimeEnvEntry(value)) {
516
+ const source = readRuntimeSource(value, env);
517
+ entries.push({
518
+ masked: value.secret,
519
+ ...inspectionPath(path),
520
+ required: value.required,
521
+ source: "env",
522
+ status: inspectionStatus(value, source.value, source.found),
523
+ ...runtimeSourceOrigin(value, env, source)
524
+ });
525
+ return;
526
+ }
527
+ if (isRuntimeProviderEntry(value)) {
528
+ try {
529
+ const resolved = await providerValue(value, loads);
530
+ entries.push({
531
+ masked: value.secret,
532
+ ...inspectionPath(path),
533
+ ...inspectionProvider(value),
534
+ required: value.required,
535
+ source: "provider",
536
+ status: inspectionStatus(value, resolved, typeof resolved !== "undefined")
537
+ });
538
+ } catch (error) {
539
+ if (isCancellation(error, options.signal)) throw error;
540
+ entries.push({
541
+ masked: value.secret,
542
+ ...inspectionPath(path),
543
+ ...inspectionProvider(value),
544
+ required: value.required,
545
+ source: "provider",
546
+ status: "error"
547
+ });
548
+ }
549
+ return;
550
+ }
551
+ }
552
+ const registryEnvNames = /* @__PURE__ */ new WeakMap();
553
+ const resolvedServerEnvs = /* @__PURE__ */ new WeakMap();
554
+ /** The env names a registry reads, or null when it declares an array or object, since each call returns its own copy. */
555
+ function reusableEnvNames(registry) {
556
+ const known = registryEnvNames.get(registry);
557
+ if (known !== void 0) return known;
558
+ let names = [];
559
+ for (const { entry } of runtimeRegistryEntries(registry)) {
560
+ if (!isRuntimeEnvEntry(entry)) continue;
561
+ if (entry.schema?.kind === "array" || entry.schema?.kind === "object") {
562
+ names = null;
563
+ break;
564
+ }
565
+ names.push(...entry.source.names || [entry.source.name]);
566
+ }
567
+ registryEnvNames.set(registry, names);
568
+ return names;
569
+ }
570
+ /** The values of every name the registry reads, as one string. Undefined when the result must not be reused. */
571
+ function serverEnvKey(registry, event) {
572
+ const names = reusableEnvNames(registry);
573
+ if (!names) return void 0;
574
+ const host = processEnv();
575
+ const cloudflare = getCloudflareEnv(event) ?? {};
576
+ let key = "";
577
+ for (const name of names) {
578
+ const value = Object.hasOwn(cloudflare, name) ? cloudflare[name] : Object.hasOwn(host, name) ? host[name] : void 0;
579
+ if (value === void 0) key += `${name}\0`;
580
+ else if (typeof value === "string") key += `${name}=s${value.length}:${value}\0`;
581
+ else if (typeof value === "number" || typeof value === "boolean") key += `${name}=${typeof value === "number" ? "n" : "b"}${String(value)}\0`;
582
+ else return void 0;
583
+ }
584
+ return key;
585
+ }
586
+ /**
587
+ * Apps call `useServerEnv()` on hot paths, often once per listed row. The result is reused while every name the
588
+ * registry reads holds the same value, so a call does not copy the whole env and parse each declaration again. Each
589
+ * call still gets its own records.
590
+ */
591
+ function resolveServerEnv(registry, event) {
592
+ const key = serverEnvKey(registry, event);
593
+ if (key === void 0) return resolveRegistryValue(registry, runtimeEnv(event), "env.server");
594
+ let cached = resolvedServerEnvs.get(registry);
595
+ if (cached?.key !== key) {
596
+ cached = {
597
+ key,
598
+ value: resolveRegistryValue(registry, runtimeEnv(event), "env.server")
599
+ };
600
+ resolvedServerEnvs.set(registry, cached);
601
+ }
602
+ return isNamespace(cached.value) ? copyNamespaces(cached.value) : cached.value;
603
+ }
604
+ async function loadServerEnv(registry, event, options = {}) {
605
+ if (options.signal?.aborted) throw abortReason(options.signal);
606
+ const env = runtimeEnv(event);
607
+ const loads = createProviderLoads(registry, createLocalEnv(registry, env, false), options);
608
+ await Promise.all(loads.values());
609
+ if (options.signal?.aborted) throw abortReason(options.signal);
610
+ const value = await loadRegistryValue(registry, env, loads, "env.server");
611
+ if (options.signal?.aborted) throw abortReason(options.signal);
612
+ return value;
613
+ }
614
+ /** Describe declarations without loading host values or calling providers. */
615
+ function describeServerEnv(registry) {
616
+ const entries = [];
617
+ for (const { entry: value, path } of runtimeRegistryEntries(registry)) {
618
+ if (isRuntimeLiteralEntry(value)) {
619
+ entries.push({
620
+ ...inspectionPath(path),
621
+ source: "literal",
622
+ secret: false,
623
+ required: false,
624
+ hasDefault: false
625
+ });
626
+ continue;
627
+ }
628
+ if (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) entries.push({
629
+ ...inspectionPath(path),
630
+ ...isRuntimeEnvEntry(value) && value.source.canonical && /^[A-Z_][A-Z0-9_]{0,127}$/.test(value.source.canonical) ? { canonicalName: value.source.canonical } : {},
631
+ source: value.source.kind,
632
+ ...isRuntimeProviderEntry(value) ? inspectionProvider(value) : {},
633
+ secret: value.secret,
634
+ required: value.required,
635
+ hasDefault: value.default !== void 0,
636
+ type: value.secret && value.schema?.kind === "enum" ? "enum" : envValueTypeName(value.schema ?? stringValueSchema)
637
+ });
638
+ }
639
+ return { entries };
640
+ }
641
+ /** Returns whether an inspection entry makes `loadServerEnv()` fail: invalid, provider error, or required and missing. */
642
+ function isBlockingServerEnvEntry(entry) {
643
+ return entry.status === "invalid" || entry.status === "error" || entry.required && entry.status === "missing";
644
+ }
645
+ async function inspectServerEnv(registry, event, options = {}) {
646
+ if (options.signal?.aborted) throw abortReason(options.signal);
647
+ const env = runtimeEnv(event);
648
+ const loads = createProviderLoads(registry, createLocalEnv(registry, env, true), options);
649
+ await Promise.allSettled(loads.values());
650
+ if (options.signal?.aborted) throw abortReason(options.signal);
651
+ const entries = [];
652
+ for (const { entry, path } of runtimeRegistryEntries(registry)) await inspectRegistryEntry(entry, env, options, loads, path, entries);
653
+ if (options.signal?.aborted) throw abortReason(options.signal);
654
+ return Object.freeze({ entries: Object.freeze(entries.map((entry) => Object.freeze(entry))) });
655
+ }
656
+ /** Limit management to safe, declared provider paths. Host variables stay read-only. */
657
+ function createServerEnvManagement(registry, providers) {
658
+ const targets = /* @__PURE__ */ new Map();
659
+ for (const { entry, path } of runtimeRegistryEntries(registry)) {
660
+ if (!isRuntimeProviderEntry(entry)) continue;
661
+ const management = Object.hasOwn(providers, entry.source.provider) ? providers[entry.source.provider]?.management : void 0;
662
+ if (inspectionPath(path).path && management) targets.set(path, {
663
+ key: entry.source.key,
664
+ management
665
+ });
666
+ }
667
+ return createEnvBridgeHandler((path) => targets.get(path));
668
+ }
669
+ //#endregion
670
+ export { readViteHubSecret as _, isBlockingServerEnvEntry as a, isRuntimeEnvEntry as c, runtimeRegistryEntries as d, envSourceFailed as f, deriveViteHubSecret as g, missingRequiredEnv as h, inspectServerEnv as i, isRuntimeLiteralEntry as l, isAbortError as m, deriveSecret as n, loadServerEnv as o, invalidEnvDeclaration as p, describeServerEnv as r, resolveServerEnv as s, createServerEnvManagement as t, isRuntimeProviderEntry as u };