@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
package/dist/vite.js CHANGED
@@ -1,13 +1,20 @@
1
- import { n as env, r as isDefaultStringEnvVariable, t as defaultStringSchema } from "./declarations-Cy5XamUA.js";
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-CrxjYNYr.js";
2
+ import { a as isEnvSchemaValue, i as stringValueSchema, n as parseEnvValue, o as hasRuntimeType, r as schemaContainsEnum, t as envValueTypeName } from "./values-D_r6V774.js";
3
+ import { n as env, r as runtimeValueSchema, t as descriptorVariable } from "./declarations-DAVgctKD.js";
2
4
  import { parseSchema } from "./schema.js";
3
- import { a as missingRequiredEnv, i as isAbortError, n as invalidEnvDeclaration, t as envSourceFailed } from "./errors-RUmAFDJn.js";
5
+ import { _ as readViteHubSecret, c as isRuntimeEnvEntry, d as runtimeRegistryEntries, f as envSourceFailed, h as missingRequiredEnv, l as isRuntimeLiteralEntry, m as isAbortError, p as invalidEnvDeclaration, r as describeServerEnv, u as isRuntimeProviderEntry } from "./server-DufVswRJ.js";
6
+ import { a as createViteHubEnvImportAliases, c as viteHubEnvDescriptionModulePath, d as viteHubEnvServerModulePath, f as viteHubEnvServerModuleTypesPath, i as VITEHUB_ENV_SERVER_ID, l as viteHubEnvPublicModulePath, o as resolveViteHubProjectRoot, r as VITEHUB_ENV_PUBLIC_ID, s as viteHubEnvAmbientTypesPath, t as createEnvCliContributor, u as viteHubEnvPublicModuleTypesPath } from "./cli-CMQPQbii.js";
7
+ import { Diagnostic } from "nostics";
4
8
  import { isViteHubError } from "@vite-hub/runtime";
5
- import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
6
- import { basename, dirname, relative, resolve } from "node:path";
7
- import { statSync } from "node:fs";
9
+ import { readFileSync } from "node:fs";
10
+ import { dirname, isAbsolute, relative, resolve, win32 } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { createHash, randomBytes } from "node:crypto";
13
+ import { chmod, mkdir, open, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
8
14
  import { loadEnv } from "vite";
9
15
  import { execFile } from "node:child_process";
10
16
  import { promisify } from "node:util";
17
+ import { ParsedEnvSpecFunctionCall, ParsedEnvSpecKeyValuePair, ParsedEnvSpecStaticValue, parseEnvSpecDotEnvFile } from "@env-spec/parser";
11
18
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
12
19
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
13
20
  function normalizeWindowsPath(input = "") {
@@ -27,10 +34,10 @@ const resolve$1 = function(...arguments_) {
27
34
  const path = index >= 0 ? arguments_[index] : cwd();
28
35
  if (!path || path.length === 0) continue;
29
36
  resolvedPath = `${path}/${resolvedPath}`;
30
- resolvedAbsolute = isAbsolute(path);
37
+ resolvedAbsolute = isAbsolute$1(path);
31
38
  }
32
39
  resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
33
- if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
40
+ if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
34
41
  return resolvedPath.length > 0 ? resolvedPath : ".";
35
42
  };
36
43
  function normalizeString(path, allowAboveRoot) {
@@ -83,7 +90,7 @@ function normalizeString(path, allowAboveRoot) {
83
90
  }
84
91
  return res;
85
92
  }
86
- const isAbsolute = function(p) {
93
+ const isAbsolute$1 = function(p) {
87
94
  return _IS_ABSOLUTE_RE.test(p);
88
95
  };
89
96
  //#endregion
@@ -94,88 +101,6 @@ async function writeFileIfChanged(file, contents) {
94
101
  await writeFile(file, contents, "utf8");
95
102
  }
96
103
  //#endregion
97
- //#region ../internal/src/build/vite.ts
98
- const projectRootDirectoryMarkers = [
99
- ["server", "agents"],
100
- ["server", "browsers"],
101
- ["server", "schedules"],
102
- ["server", "templates"],
103
- ["server", "workspaces"]
104
- ];
105
- const projectRootDefinitionFileMarkers = [
106
- ".ts",
107
- ".mts",
108
- ".cts",
109
- ".js",
110
- ".mjs",
111
- ".cjs"
112
- ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
113
- const projectRootFileMarkers = [["package.json"]];
114
- const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
115
- const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
116
- function resolveViteHubProjectRoot(root, options = {}) {
117
- const resolvedRoot = resolve(root);
118
- if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
119
- if (basename(resolvedRoot) === "app") {
120
- const parent = dirname(resolvedRoot);
121
- if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
122
- }
123
- let current = resolvedRoot;
124
- while (true) {
125
- if (hasProjectRootMarker(current)) return current;
126
- const parent = dirname(current);
127
- if (parent === current) return resolvedRoot;
128
- current = parent;
129
- }
130
- }
131
- function hasProjectRootDirectoryMarker(root) {
132
- for (const marker of projectRootDirectoryMarkers) try {
133
- if (statSync(resolve(root, ...marker)).isDirectory()) return true;
134
- } catch (error) {
135
- if (error.code !== "ENOENT") throw error;
136
- }
137
- return false;
138
- }
139
- function hasProjectRootMarker(root) {
140
- if (hasProjectRootDirectoryMarker(root)) return true;
141
- if (hasProjectRootDefinitionFileMarker(root)) return true;
142
- for (const marker of projectRootFileMarkers) try {
143
- if (statSync(resolve(root, ...marker)).isFile()) return true;
144
- } catch (error) {
145
- if (error.code !== "ENOENT") throw error;
146
- }
147
- return false;
148
- }
149
- function hasProjectRootDefinitionFileMarker(root) {
150
- for (const marker of projectRootDefinitionFileMarkers) try {
151
- if (statSync(resolve(root, ...marker)).isFile()) return true;
152
- } catch (error) {
153
- if (error.code !== "ENOENT") throw error;
154
- }
155
- return false;
156
- }
157
- function viteHubEnvAmbientTypesPath(root) {
158
- return resolve(root, ".vitehub", "types", "env.d.ts");
159
- }
160
- function viteHubEnvPublicModulePath(root) {
161
- return resolve(root, ".vitehub", "env", "public.mjs");
162
- }
163
- function viteHubEnvPublicModuleTypesPath(root) {
164
- return resolve(root, ".vitehub", "env", "public.d.ts");
165
- }
166
- function viteHubEnvServerModulePath(root) {
167
- return resolve(root, ".vitehub", "env", "server.mjs");
168
- }
169
- function viteHubEnvServerModuleTypesPath(root) {
170
- return resolve(root, ".vitehub", "env", "server.d.ts");
171
- }
172
- function createViteHubEnvImportAliases(root) {
173
- return {
174
- [VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
175
- [VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root)
176
- };
177
- }
178
- //#endregion
179
104
  //#region src/core/diagnostics.ts
180
105
  function shouldTraceDiagnostics(option) {
181
106
  return option === "trace" || process.env.VITEHUB_ENV_TRACE === "true";
@@ -249,7 +174,7 @@ function createSourceContext(input) {
249
174
  tag: async () => {
250
175
  const tag = envValue(input.env, ["GIT_TAG"]);
251
176
  if (tag) return tag;
252
- if (input.env.GITHUB_REF_TYPE === "tag") return envValue(input.env, ["GITHUB_REF_NAME"]);
177
+ if (Object.hasOwn(input.env, "GITHUB_REF_TYPE") && input.env.GITHUB_REF_TYPE === "tag") return envValue(input.env, ["GITHUB_REF_NAME"]);
253
178
  return await gitOutput(input.rootDir, [
254
179
  "describe",
255
180
  "--tags",
@@ -265,16 +190,20 @@ function createSourceContext(input) {
265
190
  }
266
191
  function envValue(env, names) {
267
192
  for (const name of names) {
268
- const value = env[name];
193
+ const value = Object.hasOwn(env, name) ? env[name] : void 0;
269
194
  if (value) return value;
270
195
  }
271
196
  }
272
197
  async function resolveBuildConfig(declarations, input) {
198
+ assertUniqueBuildCanonicalNames(declarations, input.section, input.prefix);
273
199
  const diagnostics = [];
274
200
  const values = {};
275
201
  for (const [key, declaration] of Object.entries(declarations || {})) {
276
- const result = await resolveBuildConfigValue(declaration, `${input.section}.${key}`, input);
277
- values[key] = result.value;
202
+ const result = await resolveBuildConfigValue(declaration, `${input.section}.${key}`, {
203
+ ...input,
204
+ prefix: canonicalKey.test(key) ? input.prefix : false
205
+ });
206
+ setOwnValue(values, key, result.value);
278
207
  diagnostics.push(...result.diagnostics);
279
208
  }
280
209
  return {
@@ -283,55 +212,27 @@ async function resolveBuildConfig(declarations, input) {
283
212
  };
284
213
  }
285
214
  async function resolveEnvEntries(declarations, input) {
215
+ assertUniqueBuildCanonicalNames(declarations, input.section, input.prefix);
286
216
  const entries = [];
287
217
  const diagnostics = [];
288
218
  for (const [key, declaration] of Object.entries(declarations || {})) {
289
- const source = resolveEnvSource(declaration, `${input.section}.${key}`, input.prefix);
290
- const resolvedSource = await resolveSourceValue(source, input.context);
291
- const defaulted = typeof resolvedSource.value === "undefined";
292
- const valueForSchema = defaulted ? declaration.default : resolvedSource.value;
293
- if (typeof valueForSchema === "undefined") {
294
- if (declaration.required) {
295
- const path = `${input.section}.${key}`;
296
- throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
297
- }
298
- entries.push({
299
- key,
300
- masked: declaration.secret,
301
- source: resolvedSource.label,
302
- type: declaration.type ?? "undefined",
303
- value: void 0
304
- });
305
- diagnostics.push({
306
- exposed: declaration.secret ? `${input.exposure}, masked` : input.exposure,
307
- key: `${input.section}.${key}`,
308
- masked: declaration.secret,
309
- mode: declaration.mode,
310
- source: resolvedSource.label,
311
- status: "missing",
312
- timing: input.timing,
313
- type: declaration.type ?? "undefined"
314
- });
315
- continue;
316
- }
317
- const value = parseSchema(declaration.schema, valueForSchema, `${input.section}.${key}`);
318
- const type = declaration.type ?? inferTypeName(value);
219
+ const result = await resolveBuildDeclaration(declaration, `${input.section}.${key}`, input, canonicalKey.test(key));
319
220
  entries.push({
320
221
  key,
321
222
  masked: declaration.secret,
322
- source: resolvedSource.label,
323
- type,
324
- value
223
+ source: result.source,
224
+ type: result.type ?? declaration.type ?? "undefined",
225
+ value: result.value
325
226
  });
326
227
  diagnostics.push({
327
228
  exposed: declaration.secret ? `${input.exposure}, masked` : input.exposure,
328
229
  key: `${input.section}.${key}`,
329
230
  masked: declaration.secret,
330
231
  mode: declaration.mode,
331
- source: defaulted ? "default" : resolvedSource.label,
332
- status: defaulted ? "defaulted" : "valid",
232
+ source: result.status === "defaulted" ? "default" : result.source,
233
+ status: result.status,
333
234
  timing: input.timing,
334
- type
235
+ type: result.type ?? declaration.type ?? "undefined"
335
236
  });
336
237
  }
337
238
  return {
@@ -340,44 +241,66 @@ async function resolveEnvEntries(declarations, input) {
340
241
  };
341
242
  }
342
243
  function createRuntimeRegistry(declarations, options = {}) {
343
- return buildRegistry(declarations, "env", options.prefix);
244
+ const path = options.path ?? "env";
245
+ try {
246
+ const registry = buildRegistry(declarations, path, options.prefix);
247
+ assertUniqueCanonicalNames(registry, path);
248
+ return registry;
249
+ } catch (error) {
250
+ if (isClassifiedError(error)) throw error;
251
+ throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
252
+ }
253
+ }
254
+ const canonicalKey = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
255
+ function claimCanonicalName(owners, canonical, path) {
256
+ if (canonical === void 0) return;
257
+ const owner = owners.get(canonical);
258
+ if (owner !== void 0) throw invalidEnvDeclaration(path, `${path} and ${owner} share the canonical variable name ${canonical}. Rename one, or set hubEnv({ prefix: false }).`);
259
+ owners.set(canonical, path);
260
+ }
261
+ function assertUniqueBuildCanonicalNames(declarations, path, prefix) {
262
+ const owners = /* @__PURE__ */ new Map();
263
+ const visit = (value, valuePath, valuePrefix) => {
264
+ if (isEnvVariableDeclaration(value)) {
265
+ const source = resolveEnvSource(value, valuePath, valuePrefix);
266
+ if (source.kind === "env" && source.canonical !== false) claimCanonicalName(owners, source.canonical, valuePath);
267
+ return;
268
+ }
269
+ if (!isPlainRecord(value)) return;
270
+ for (const [key, child] of Object.entries(value)) visit(child, `${valuePath}.${key}`, canonicalKey.test(key) ? valuePrefix : false);
271
+ };
272
+ visit(declarations, path, prefix);
273
+ }
274
+ function assertUniqueCanonicalNames(registry, path) {
275
+ const owners = /* @__PURE__ */ new Map();
276
+ const visit = (value, valuePath) => {
277
+ if (!isPlainRecord(value)) return;
278
+ const source = value.source;
279
+ if (isPlainRecord(source) && source.kind === "env") {
280
+ if (typeof source.canonical !== "string") return;
281
+ claimCanonicalName(owners, source.canonical, valuePath);
282
+ return;
283
+ }
284
+ if (value.kind === "literal" || isPlainRecord(source)) return;
285
+ for (const [key, child] of Object.entries(value)) visit(child, `${valuePath}.${key}`);
286
+ };
287
+ visit(registry, path);
344
288
  }
345
289
  async function resolveBuildConfigValue(declaration, path, input) {
346
290
  if (isEnvVariableDeclaration(declaration)) {
347
- const source = resolveEnvSource(declaration, path, input.prefix);
348
- const resolvedSource = await resolveSourceValue(source, input.context);
349
- const defaulted = typeof resolvedSource.value === "undefined";
350
- const valueForSchema = defaulted ? declaration.default : resolvedSource.value;
351
- if (typeof valueForSchema === "undefined") {
352
- if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
353
- return {
354
- diagnostics: [{
355
- exposed: input.exposure,
356
- key: path,
357
- masked: false,
358
- mode: declaration.mode,
359
- source: resolvedSource.label,
360
- status: "missing",
361
- timing: input.timing,
362
- type: declaration.type ?? "undefined"
363
- }],
364
- value: void 0
365
- };
366
- }
367
- const value = parseSchema(declaration.schema, valueForSchema, path);
368
- const type = declaration.type ?? inferTypeName(value);
291
+ const result = await resolveBuildDeclaration(declaration, path, input);
369
292
  return {
370
293
  diagnostics: [{
371
294
  exposed: input.exposure,
372
295
  key: path,
373
296
  masked: false,
374
297
  mode: declaration.mode,
375
- source: defaulted ? "default" : resolvedSource.label,
376
- status: defaulted ? "defaulted" : "valid",
298
+ source: result.status === "defaulted" ? "default" : result.source,
299
+ status: result.status,
377
300
  timing: input.timing,
378
- type
301
+ type: result.type ?? declaration.type ?? "undefined"
379
302
  }],
380
- value
303
+ value: result.value
381
304
  };
382
305
  }
383
306
  if (isBuildStaticValue(declaration)) return {
@@ -388,8 +311,11 @@ async function resolveBuildConfigValue(declaration, path, input) {
388
311
  const value = {};
389
312
  const diagnostics = [];
390
313
  for (const [key, child] of Object.entries(declaration)) {
391
- const result = await resolveBuildConfigValue(child, `${path}.${key}`, input);
392
- value[key] = result.value;
314
+ const result = await resolveBuildConfigValue(child, `${path}.${key}`, {
315
+ ...input,
316
+ prefix: canonicalKey.test(key) ? input.prefix : false
317
+ });
318
+ setOwnValue(value, key, result.value);
393
319
  diagnostics.push(...result.diagnostics);
394
320
  }
395
321
  return {
@@ -397,36 +323,114 @@ async function resolveBuildConfigValue(declaration, path, input) {
397
323
  value
398
324
  };
399
325
  }
326
+ async function resolveBuildDeclaration(declaration, path, input, canonical = true) {
327
+ const defaultValue = parseDeclarationDefault(declaration, path);
328
+ const source = resolveEnvSource(declaration, path, canonical ? input.prefix : false);
329
+ const resolvedSource = await resolveSourceValue(source, input.context);
330
+ const defaulted = typeof resolvedSource.value === "undefined";
331
+ const valueForSchema = defaulted ? defaultValue : resolvedSource.value;
332
+ if (typeof valueForSchema === "undefined") {
333
+ if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
334
+ return {
335
+ source: resolvedSource.label,
336
+ status: "missing",
337
+ value: void 0
338
+ };
339
+ }
340
+ const value = parseSchema(declaration.schema, valueForSchema, path);
341
+ const type = declaration.type ?? inferTypeName(value);
342
+ return {
343
+ source: resolvedSource.label,
344
+ status: defaulted ? "defaulted" : "valid",
345
+ type,
346
+ value
347
+ };
348
+ }
349
+ function parseDeclarationDefault(declaration, path) {
350
+ const schema = runtimeValueSchema(declaration);
351
+ return schema && declaration.default !== void 0 ? parseRuntimeDefault(schema, declaration.default, path) : declaration.default;
352
+ }
400
353
  function buildRegistry(declarations, path, prefix) {
401
354
  if (typeof declarations === "undefined") return {};
402
355
  if (!isPlainRecord(declarations)) throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
403
- return Object.fromEntries(Object.entries(declarations).map(([key, value]) => {
404
- const valuePath = `${path}.${key}`;
405
- if (!isEnvVariableDeclaration(value)) {
406
- if (isRuntimeStaticValue(value)) return [key, {
407
- kind: "literal",
408
- value
356
+ try {
357
+ return Object.fromEntries(Object.entries(declarations).map(([key, value]) => {
358
+ const valuePath = `${path}.${key}`;
359
+ if (!isEnvVariableDeclaration(value)) {
360
+ if (isRuntimeStaticValue(value)) return [key, {
361
+ kind: "literal",
362
+ value
363
+ }];
364
+ if (!isPlainRecord(value)) throw invalidEnvDeclaration(valuePath, `Invalid runtime declaration at ${valuePath}. Use env(), a serializable static value, or a nested object.`);
365
+ return [key, buildRegistry(value, valuePath, canonicalKey.test(key) ? prefix : false)];
366
+ }
367
+ if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
368
+ const source = resolveEnvSource(value, valuePath, canonicalKey.test(key) ? prefix : false);
369
+ if (source.kind !== "env" && source.kind !== "provider") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() or env.provider().`);
370
+ const schema = runtimeValueSchema(value);
371
+ if (!schema) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema. Server Env accepts env(), env.boolean(), env.number(), and env.enum() because runtime parsers must be serializable.`);
372
+ if (schemaContainsEnum(schema) && value.secret) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} cannot be a secret enum: generated types, the Console, and errors show its allowed values. Use env({ secret: true }) and check the value in server code.`);
373
+ const type = envValueTypeName(schema);
374
+ if (value.type && value.type !== type) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses type ${JSON.stringify(value.type)}, but its parser produces ${type}. Use env.boolean(), env.number(), or env.enum() to parse other types.`);
375
+ return [key, {
376
+ default: typeof value.default === "undefined" ? void 0 : parseRuntimeDefault(schema, value.default, valuePath),
377
+ required: value.required,
378
+ schema,
379
+ secret: value.secret,
380
+ source
409
381
  }];
410
- if (!isPlainRecord(value)) throw invalidEnvDeclaration(valuePath, `Invalid runtime declaration at ${valuePath}. Use env(), a serializable static value, or a nested object.`);
411
- return [key, buildRegistry(value, valuePath, prefix)];
412
- }
413
- if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
414
- const source = resolveEnvSource(value, valuePath, prefix);
415
- if (source.kind !== "env") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() in v1.`);
416
- if (!isDefaultStringEnvVariable(value)) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema, but runtime schemas cannot be serialized in v1.`);
417
- if (value.type && value.type !== "string") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses type ${JSON.stringify(value.type)}, but runtime values are strings in v1.`);
418
- return [key, {
419
- default: typeof value.default === "undefined" ? void 0 : parseSchema(defaultStringSchema, value.default, valuePath),
420
- required: value.required,
421
- schema: { kind: "string" },
422
- secret: value.secret,
423
- source,
424
- type: value.type
425
- }];
426
- }));
382
+ }));
383
+ } catch (error) {
384
+ if (isClassifiedError(error)) throw error;
385
+ throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
386
+ }
387
+ }
388
+ function isClassifiedError(error) {
389
+ return isViteHubError(error) || error instanceof Diagnostic;
427
390
  }
428
- function resolveEnvSource(declaration, path, prefix = "") {
429
- return declaration.source ?? inferEnvSource(path, prefix);
391
+ function setOwnValue(record, key, value) {
392
+ Object.defineProperty(record, key, {
393
+ configurable: true,
394
+ enumerable: true,
395
+ value,
396
+ writable: true
397
+ });
398
+ }
399
+ function parseRuntimeDefault(schema, value, path) {
400
+ const result = (schema.kind === "boolean" || schema.kind === "number" ? hasRuntimeType(value, schema.kind) : true) ? parseEnvValue(schema, value) : {
401
+ message: `Expected a ${schema.kind} default.`,
402
+ success: false
403
+ };
404
+ if (!result.success) throw envErrorDiagnostics.ENV_R0023({ message: `[vitehub] Invalid default for ${path}: ${result.message}` });
405
+ return result.data;
406
+ }
407
+ /** The default prefix of canonical variable names. */
408
+ const defaultEnvPrefix = "VITEHUB_";
409
+ /**
410
+ * The canonical variable name of a declaration path: the prefix plus the path in upper snake case.
411
+ * `env.server.cliproxy.apiKey` becomes `VITEHUB_CLIPROXY_API_KEY`. `false` disables canonical names.
412
+ */
413
+ function canonicalEnvName(path, prefix = defaultEnvPrefix) {
414
+ return prefix === false ? void 0 : `${prefix}${pathToEnvName(path)}`;
415
+ }
416
+ /**
417
+ * Resolve the source of a declaration. An env source reads the canonical name first, then its
418
+ * conventional names: the explicit `env.source()` names, or the unprefixed path name.
419
+ */
420
+ function resolveEnvSource(declaration, path, prefix = defaultEnvPrefix) {
421
+ const source = declaration.source ?? inferEnvSource(path);
422
+ const canonical = canonicalEnvName(path, prefix);
423
+ if (source.kind !== "env" || canonical === void 0 || source.canonical === false) return source;
424
+ const names = [.../* @__PURE__ */ new Set([canonical, ...source.names ?? [source.name]])];
425
+ return names.length === 1 ? {
426
+ ...source,
427
+ canonical
428
+ } : {
429
+ ...source,
430
+ canonical,
431
+ label: `env:${names.join("|")}`,
432
+ names
433
+ };
430
434
  }
431
435
  function inferTypeName(value) {
432
436
  if (Array.isArray(value)) return "unknown[]";
@@ -447,8 +451,8 @@ async function resolveSourceValue(source, context) {
447
451
  };
448
452
  case "env":
449
453
  for (const name of source.names || [source.name]) {
450
- const value = context.env[name];
451
- if (typeof value !== "undefined") return {
454
+ const value = Object.hasOwn(context.env, name) ? context.env[name] : void 0;
455
+ if (typeof value !== "undefined" && !(source.skipEmpty && value === "")) return {
452
456
  label: `env:${name}`,
453
457
  value
454
458
  };
@@ -485,6 +489,7 @@ async function resolveSourceValue(source, context) {
485
489
  label: source.label,
486
490
  value: readPath(await resolveBuiltInSource(source.label, () => context.packageJson()), source.path)
487
491
  };
492
+ case "provider": throw invalidEnvDeclaration("env", "env.provider() is available only to Server Env at runtime.");
488
493
  }
489
494
  }
490
495
  async function resolveBuiltInSource(source, resolveSource) {
@@ -495,25 +500,31 @@ async function resolveBuiltInSource(source, resolveSource) {
495
500
  throw envSourceFailed(source, cause);
496
501
  }
497
502
  }
498
- function validateBuildDeclarations(declarations, path) {
503
+ function validateBuildDeclarations(declarations, path, ancestors = /* @__PURE__ */ new Set()) {
499
504
  if (typeof declarations === "undefined") return;
500
505
  if (!isPlainRecord(declarations)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
501
- for (const [key, declaration] of Object.entries(declarations)) {
502
- const valuePath = `${path}.${key}`;
503
- if (isEnvVariableDeclaration(declaration)) {
504
- if (declaration.mode !== "build") throw invalidEnvDeclaration(valuePath, `${valuePath} must use mode: "build".`);
505
- if (declaration.secret) throw invalidEnvDeclaration(valuePath, `${valuePath} cannot be marked secret because Vite define values are bundled.`);
506
- continue;
506
+ if (ancestors.has(declarations)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Nested environment declarations cannot contain cycles.`);
507
+ ancestors.add(declarations);
508
+ try {
509
+ for (const [key, declaration] of Object.entries(declarations)) {
510
+ const valuePath = `${path}.${key}`;
511
+ if (isEnvVariableDeclaration(declaration)) {
512
+ if (declaration.mode !== "build") throw invalidEnvDeclaration(valuePath, `${valuePath} must use mode: "build".`);
513
+ if (declaration.secret) throw invalidEnvDeclaration(valuePath, `${valuePath} cannot be marked secret because Vite define values are bundled.`);
514
+ continue;
515
+ }
516
+ if (isBuildStaticValue(declaration)) continue;
517
+ validateBuildDeclarations(declaration, valuePath, ancestors);
507
518
  }
508
- if (isBuildStaticValue(declaration)) continue;
509
- validateBuildDeclarations(declaration, valuePath);
519
+ } finally {
520
+ ancestors.delete(declarations);
510
521
  }
511
522
  }
512
523
  function assertEnvVariableDeclaration(path, declaration) {
513
524
  if (!isEnvVariableDeclaration(declaration)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Use env().`);
514
525
  }
515
- function inferEnvSource(path, prefix) {
516
- const name = `${prefix}${pathToEnvName(path)}`;
526
+ function inferEnvSource(path) {
527
+ const name = pathToEnvName(path);
517
528
  return {
518
529
  kind: "env",
519
530
  label: `env:${name}`,
@@ -528,31 +539,51 @@ function segmentToEnvParts(segment) {
528
539
  return segment.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").split("_").map((part) => part.toUpperCase()).filter(Boolean);
529
540
  }
530
541
  function isEnvVariableDeclaration(value) {
531
- return isPlainRecord(value) && value.kind === "env-variable";
542
+ try {
543
+ return isPlainRecord(value) && value.kind === "env-variable";
544
+ } catch {
545
+ return false;
546
+ }
532
547
  }
533
548
  function isPlainRecord(value) {
534
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
535
- const prototype = Object.getPrototypeOf(value);
536
- return prototype === null || prototype === Object.prototype;
549
+ try {
550
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
551
+ const prototype = Object.getPrototypeOf(value);
552
+ return prototype === null || prototype === Object.prototype;
553
+ } catch {
554
+ return false;
555
+ }
537
556
  }
538
557
  function isRuntimeStaticValue(value) {
539
558
  return isBuildStaticValue(value);
540
559
  }
541
- function isBuildStaticValue(value) {
542
- if (value === null) return true;
543
- switch (typeof value) {
544
- case "boolean":
545
- case "string": return true;
546
- case "number": return Number.isFinite(value);
547
- case "object":
548
- if (!Array.isArray(value)) return false;
549
- for (let index = 0; index < value.length; index += 1) if (!(index in value) || !isBuildStaticValue(value[index])) return false;
550
- return true;
551
- default: return false;
560
+ function isBuildStaticValue(value, ancestors = /* @__PURE__ */ new Set()) {
561
+ try {
562
+ if (value === null) return true;
563
+ switch (typeof value) {
564
+ case "boolean":
565
+ case "string": return true;
566
+ case "number": return Number.isFinite(value);
567
+ case "object":
568
+ if (!Array.isArray(value)) return false;
569
+ if (ancestors.has(value)) return false;
570
+ ancestors.add(value);
571
+ try {
572
+ for (let index = 0; index < value.length; index += 1) if (!Object.hasOwn(value, index) || !isBuildStaticValue(value[index], ancestors)) return false;
573
+ return true;
574
+ } finally {
575
+ ancestors.delete(value);
576
+ }
577
+ default: return false;
578
+ }
579
+ } catch {
580
+ return false;
552
581
  }
553
582
  }
554
583
  async function readPackageJson(rootDir) {
555
- return JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
584
+ const value = JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
585
+ if (!isPlainRecord(value)) throw envErrorDiagnostics.ENV_R0012({ message: "package.json must contain an object." });
586
+ return value;
556
587
  }
557
588
  async function gitOutput(rootDir, args) {
558
589
  const { stdout } = await execFileAsync("git", args, { cwd: rootDir });
@@ -561,20 +592,443 @@ async function gitOutput(rootDir, args) {
561
592
  function readPath(value, path) {
562
593
  return path.split(".").reduce((current, segment) => {
563
594
  if (typeof current !== "object" || current === null) return;
595
+ if (!Object.hasOwn(current, segment)) return void 0;
564
596
  return current[segment];
565
597
  }, value);
566
598
  }
567
599
  //#endregion
600
+ //#region src/env-schema/profile.ts
601
+ function fail$1(context, reason) {
602
+ throw new Error(`${context.file}:${context.line}${context.key ? ` (${context.key})` : ""}: ${reason}`);
603
+ }
604
+ function locationLine(location, end = false) {
605
+ if (typeof location !== "object" || location === null) return 1;
606
+ const point = end && "end" in location ? location.end : "start" in location ? location.start : void 0;
607
+ if (typeof point === "object" && point !== null && "line" in point && typeof point.line === "number" && Number.isInteger(point.line) && point.line > 0) return point.line;
608
+ return 1;
609
+ }
610
+ function staticValue(node, context) {
611
+ if (!(node instanceof ParsedEnvSpecStaticValue)) fail$1(context, "Only static values are supported");
612
+ const value = node.unescapedValue;
613
+ if (value === void 0 || typeof value === "string" || typeof value === "boolean" || typeof value === "number") return value;
614
+ return fail$1(context, "Unsupported static value");
615
+ }
616
+ function booleanDecorator(decorator, context) {
617
+ const value = staticValue(decorator.value, context);
618
+ if (typeof value !== "boolean") fail$1(context, "Decorator requires a static boolean");
619
+ return value;
620
+ }
621
+ function decorators(nodes, allowed, context) {
622
+ const result = /* @__PURE__ */ new Map();
623
+ for (const node of nodes) {
624
+ const here = {
625
+ ...context,
626
+ line: locationLine(node.data._location)
627
+ };
628
+ if (node.hasInvalidName || !allowed.includes(node.name) || node.strayText || node.isBareFnCall) fail$1(here, "Unsupported or malformed decorator");
629
+ if (result.has(node.name)) fail$1(here, "Duplicate decorator");
630
+ result.set(node.name, node);
631
+ }
632
+ return result;
633
+ }
634
+ function typeArguments(call, allowed, context) {
635
+ const args = /* @__PURE__ */ new Map();
636
+ for (const arg of call.data.args.values) {
637
+ if (!(arg instanceof ParsedEnvSpecKeyValuePair) || !allowed.includes(arg.key)) fail$1(context, "Unsupported type argument");
638
+ if (args.has(arg.key)) fail$1(context, "Duplicate type argument");
639
+ args.set(arg.key, staticValue(arg.value, context));
640
+ }
641
+ return args;
642
+ }
643
+ function numericArgument(args, name, context, length = false) {
644
+ if (!args.has(name)) return void 0;
645
+ const value = args.get(name);
646
+ if (typeof value !== "number" || !Number.isFinite(value) || length && (!Number.isSafeInteger(value) || value < 0)) fail$1(context, "Invalid numeric type argument");
647
+ return value;
648
+ }
649
+ function parseType(decorator, context) {
650
+ if (!decorator) return { kind: "string" };
651
+ return parseTypeNode(decorator.value, context);
652
+ }
653
+ function parseTypeNode(node, context, depth = 0) {
654
+ if (depth > 16) fail$1(context, "Type nesting exceeds 16 levels");
655
+ const name = node instanceof ParsedEnvSpecFunctionCall ? node.name : staticValue(node, context);
656
+ if (name === "array") {
657
+ const args = node instanceof ParsedEnvSpecFunctionCall ? node.data.args.values : [];
658
+ if (args.length > 1 || args[0] instanceof ParsedEnvSpecKeyValuePair) fail$1(context, "Array requires at most one item type");
659
+ return {
660
+ kind: "array",
661
+ ...args.length && { items: parseTypeNode(args[0], context, depth + 1) }
662
+ };
663
+ }
664
+ if (name === "object") {
665
+ if (!(node instanceof ParsedEnvSpecFunctionCall)) return { kind: "object" };
666
+ const entries = /* @__PURE__ */ new Map();
667
+ for (const arg of node.data.args.values) {
668
+ if (!(arg instanceof ParsedEnvSpecKeyValuePair) || !/^[A-Z_$][\w$]*$/i.test(arg.key) || [
669
+ "__proto__",
670
+ "prototype",
671
+ "constructor",
672
+ "__envSchemaUnset"
673
+ ].includes(arg.key)) fail$1(context, "Object requires safe named property types");
674
+ if (entries.has(arg.key)) fail$1(context, "Duplicate object property");
675
+ entries.set(arg.key, parseTypeNode(arg.value, context, depth + 1));
676
+ }
677
+ return {
678
+ kind: "object",
679
+ properties: Object.fromEntries(entries)
680
+ };
681
+ }
682
+ if (name === "enum") {
683
+ if (!(node instanceof ParsedEnvSpecFunctionCall) || node.data.args.values.length === 0) fail$1(context, "Enum requires string choices");
684
+ const values = node.data.args.values.map((arg) => {
685
+ const value = staticValue(arg, context);
686
+ if (typeof value !== "string" || value === "") fail$1(context, "Enum requires nonempty string choices");
687
+ return value;
688
+ });
689
+ if (new Set(values).size !== values.length) fail$1(context, "Duplicate enum choice");
690
+ return {
691
+ kind: "enum",
692
+ values
693
+ };
694
+ }
695
+ if (name === "string") {
696
+ const args = node instanceof ParsedEnvSpecFunctionCall ? typeArguments(node, ["minLength", "maxLength"], context) : /* @__PURE__ */ new Map();
697
+ const minLength = numericArgument(args, "minLength", context, true);
698
+ const maxLength = numericArgument(args, "maxLength", context, true);
699
+ if (minLength !== void 0 && maxLength !== void 0 && minLength > maxLength) fail$1(context, "Minimum length exceeds maximum length");
700
+ return {
701
+ kind: "string",
702
+ ...minLength !== void 0 && { minLength },
703
+ ...maxLength !== void 0 && { maxLength }
704
+ };
705
+ }
706
+ if (name === "number") {
707
+ const args = node instanceof ParsedEnvSpecFunctionCall ? typeArguments(node, [
708
+ "min",
709
+ "max",
710
+ "isInt"
711
+ ], context) : /* @__PURE__ */ new Map();
712
+ const min = numericArgument(args, "min", context);
713
+ const max = numericArgument(args, "max", context);
714
+ const isInt = args.get("isInt");
715
+ if (args.has("isInt") && typeof isInt !== "boolean") fail$1(context, "Integer constraint requires a static boolean");
716
+ if (min !== void 0 && max !== void 0 && min > max) fail$1(context, "Minimum exceeds maximum");
717
+ return {
718
+ kind: "number",
719
+ ...min !== void 0 && { min },
720
+ ...max !== void 0 && { max },
721
+ ...typeof isInt === "boolean" && { isInt }
722
+ };
723
+ }
724
+ if (name === "boolean" || name === "url") {
725
+ if (node instanceof ParsedEnvSpecFunctionCall) typeArguments(node, [], context);
726
+ return { kind: name };
727
+ }
728
+ return fail$1(context, "Unsupported type");
729
+ }
730
+ function lexicalValue(node, context) {
731
+ if (node.data.quote) {
732
+ const value = staticValue(node, context);
733
+ if (typeof value !== "string") fail$1(context, "Invalid quoted default");
734
+ return value;
735
+ }
736
+ const raw = node.data.rawValue;
737
+ if (raw === void 0) return void 0;
738
+ if (typeof raw !== "string") fail$1(context, "Invalid default");
739
+ const value = raw.trim();
740
+ if (!value) return void 0;
741
+ if (/^["'`[{]/.test(value) || /^[A-Z]\w*\(/i.test(value)) fail$1(context, "Unsupported or malformed default expression");
742
+ const decoded = staticValue(node, context);
743
+ return typeof decoded === "string" ? decoded : value;
744
+ }
745
+ function validUrl(value) {
746
+ try {
747
+ return !!new URL(value).protocol;
748
+ } catch {
749
+ return false;
750
+ }
751
+ }
752
+ function matchesStructuredType(value, type) {
753
+ switch (type.kind) {
754
+ case "array": {
755
+ const items = type.items;
756
+ return Array.isArray(value) && (!items || value.every((item) => matchesStructuredType(item, items)));
757
+ }
758
+ case "object": {
759
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
760
+ const properties = type.properties;
761
+ return !properties || Object.keys(value).length === Object.keys(properties).length && Object.entries(properties).every(([key, property]) => {
762
+ const item = value[key];
763
+ return Object.hasOwn(value, key) && item !== void 0 && matchesStructuredType(item, property);
764
+ });
765
+ }
766
+ case "string": return typeof value === "string" && (type.minLength === void 0 || value.length >= type.minLength) && (type.maxLength === void 0 || value.length <= type.maxLength);
767
+ case "number": return typeof value === "number" && (!type.isInt || Number.isSafeInteger(value)) && (type.min === void 0 || value >= type.min) && (type.max === void 0 || value <= type.max);
768
+ case "boolean": return typeof value === "boolean";
769
+ case "enum": return typeof value === "string" && type.values.includes(value);
770
+ case "url": return typeof value === "string" && validUrl(value);
771
+ }
772
+ }
773
+ function parseDefault(value, type, required, context) {
774
+ if (value === void 0) return void 0;
775
+ if (value === "") {
776
+ if (required) fail$1(context, "Required default cannot be empty");
777
+ if (type.kind !== "string") return void 0;
778
+ }
779
+ switch (type.kind) {
780
+ case "array":
781
+ case "object": {
782
+ let parsed;
783
+ try {
784
+ parsed = JSON.parse(value);
785
+ } catch {
786
+ fail$1(context, "Default must be valid JSON");
787
+ }
788
+ if (!isEnvSchemaValue(parsed) || !matchesStructuredType(parsed, type)) fail$1(context, "Default does not match the declared JSON type");
789
+ return parsed;
790
+ }
791
+ case "string":
792
+ if (type.minLength !== void 0 && value.length < type.minLength || type.maxLength !== void 0 && value.length > type.maxLength) fail$1(context, "Default violates string length constraints");
793
+ return value;
794
+ case "number": {
795
+ const text = value.trim();
796
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(text)) fail$1(context, "Default must be a finite decimal number");
797
+ const number = Number(text);
798
+ if (!Number.isFinite(number) || type.isInt && !Number.isSafeInteger(number) || type.min !== void 0 && number < type.min || type.max !== void 0 && number > type.max) fail$1(context, "Default violates number constraints");
799
+ return number;
800
+ }
801
+ case "boolean":
802
+ if (value.trim() === "true" || value.trim() === "1") return true;
803
+ if (value.trim() === "false" || value.trim() === "0") return false;
804
+ return fail$1(context, "Default must be a boolean");
805
+ case "enum":
806
+ if (!type.values.includes(value)) fail$1(context, "Default is not an enum choice");
807
+ return value;
808
+ case "url":
809
+ if (!validUrl(value)) fail$1(context, "Default must be an absolute URL");
810
+ return value;
811
+ }
812
+ }
813
+ function parseEnvSchema(source, filename) {
814
+ let parsed;
815
+ try {
816
+ parsed = parseEnvSpecDotEnvFile(source);
817
+ } catch (error) {
818
+ return fail$1({
819
+ file: filename,
820
+ line: locationLine(typeof error === "object" && error !== null && "location" in error ? error.location : void 0)
821
+ }, "Invalid env-spec syntax");
822
+ }
823
+ const rootContext = {
824
+ file: filename,
825
+ line: 1
826
+ };
827
+ for (const block of parsed.headerBlocks) if (block.decoratorsArray.length && !block.divider) fail$1({
828
+ file: filename,
829
+ line: locationLine(block.data._location)
830
+ }, "Root decorators require a header divider");
831
+ for (const block of parsed.orphanCommentBlocks) if (block.decoratorsArray.length) fail$1({
832
+ file: filename,
833
+ line: locationLine(block.data._location)
834
+ }, "Decorator is not attached to a declaration");
835
+ const root = decorators(parsed.decoratorsArray, ["defaultRequired", "defaultSensitive"], rootContext);
836
+ const defaultRequired = root.get("defaultRequired");
837
+ const defaultSensitive = root.get("defaultSensitive");
838
+ const required = defaultRequired ? booleanDecorator(defaultRequired, rootContext) : true;
839
+ const sensitive = defaultSensitive ? booleanDecorator(defaultSensitive, rootContext) : true;
840
+ const keys = /* @__PURE__ */ new Set();
841
+ return parsed.configItems.map((item) => {
842
+ const line = Math.max(locationLine(item.data._location), ...item.data.preComments.map((comment) => locationLine(comment.data._location, true) + 1));
843
+ const context = {
844
+ file: filename,
845
+ line
846
+ };
847
+ if (!/^[A-Z_]\w*$/i.test(item.key) || item.key.length > 256 || [
848
+ "__proto__",
849
+ "prototype",
850
+ "constructor"
851
+ ].includes(item.key.toLowerCase())) fail$1(context, "Invalid or reserved environment key");
852
+ context.key = item.key;
853
+ if (keys.has(item.key)) fail$1(context, "Duplicate environment key");
854
+ keys.add(item.key);
855
+ const metadata = decorators(item.decoratorsArray, [
856
+ "type",
857
+ "required",
858
+ "optional",
859
+ "sensitive",
860
+ "public",
861
+ "example"
862
+ ], context);
863
+ if (metadata.has("required") && metadata.has("optional")) fail$1(context, "Cannot combine required and optional");
864
+ if (metadata.has("sensitive") && metadata.has("public")) fail$1(context, "Cannot combine sensitive and public");
865
+ const field = {
866
+ key: item.key,
867
+ type: parseType(metadata.get("type"), context),
868
+ required,
869
+ sensitive,
870
+ description: item.description,
871
+ docs: [],
872
+ source: {
873
+ file: filename,
874
+ line
875
+ }
876
+ };
877
+ for (const [name, node] of metadata) if (name === "required") field.required = booleanDecorator(node, context);
878
+ else if (name === "optional") field.required = !booleanDecorator(node, context);
879
+ else if (name === "sensitive") field.sensitive = booleanDecorator(node, context);
880
+ else if (name === "public") field.sensitive = !booleanDecorator(node, context);
881
+ else if (name === "example") {
882
+ const example = staticValue(node.value, context);
883
+ if (typeof example !== "string") fail$1(context, "Example must be a string");
884
+ field.example = example;
885
+ }
886
+ if (item.value !== void 0 && !(item.value instanceof ParsedEnvSpecStaticValue)) fail$1(context, "Dynamic or structured defaults are unsupported");
887
+ const checkedDefault = parseDefault(item.value ? lexicalValue(item.value, context) : void 0, field.type, field.required, context);
888
+ if (checkedDefault !== void 0) field.default = checkedDefault;
889
+ return field;
890
+ });
891
+ }
892
+ //#endregion
893
+ //#region src/env-schema/importer.ts
894
+ function fail(field, reason) {
895
+ const path = field ? `${field.source.file}:${field.source.line} (${field.key})` : "envSchema";
896
+ throw invalidEnvDeclaration(path, `${path}: ${reason}`);
897
+ }
898
+ function outputName(name) {
899
+ return name.split("_").filter(Boolean).map((word, index) => {
900
+ const normalized = word === word.toUpperCase() ? word.toLowerCase() : word;
901
+ return index === 0 ? normalized.charAt(0).toLowerCase() + normalized.slice(1) : normalized.charAt(0).toUpperCase() + normalized.slice(1);
902
+ }).join("");
903
+ }
904
+ function safePath(path, field, publicField) {
905
+ const segments = path.split(".");
906
+ if (!segments.length || publicField && segments.length !== 1 || segments.length > 16 || segments.some((segment) => !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(segment) || [
907
+ "__proto__",
908
+ "prototype",
909
+ "constructor"
910
+ ].includes(segment.toLowerCase()))) fail(field, "Output path must contain safe identifiers; Public Env paths must be flat");
911
+ if ([
912
+ "public",
913
+ "define",
914
+ "server"
915
+ ].includes(segments[0] || "")) fail(field, "Output paths cannot select an Env visibility section");
916
+ return segments;
917
+ }
918
+ function descriptor(field) {
919
+ const type = field.type;
920
+ if (type.kind === "string") return {
921
+ ...type,
922
+ minLength: Math.max(type.minLength ?? 0, field.required ? 1 : 0)
923
+ };
924
+ if (type.kind === "number") return {
925
+ ...type,
926
+ decimal: true
927
+ };
928
+ return type;
929
+ }
930
+ function add(tree, segments, declaration, field) {
931
+ const [head, ...rest] = segments;
932
+ if (!head) return fail(field, "Output path cannot be empty");
933
+ const existing = tree.get(head);
934
+ if (!rest.length) {
935
+ if (existing) fail(field, "Output path collides with another declaration");
936
+ tree.set(head, {
937
+ kind: "field",
938
+ declaration
939
+ });
940
+ return;
941
+ }
942
+ if (existing?.kind === "field") fail(field, "Output path collides with another declaration");
943
+ const children = existing?.children ?? /* @__PURE__ */ new Map();
944
+ tree.set(head, {
945
+ kind: "branch",
946
+ children
947
+ });
948
+ add(children, rest, declaration, field);
949
+ }
950
+ function serverConfig(tree) {
951
+ const result = {};
952
+ for (const [key, node] of tree) Object.defineProperty(result, key, {
953
+ enumerable: true,
954
+ configurable: true,
955
+ writable: true,
956
+ value: node.kind === "field" ? node.declaration : serverConfig(node.children)
957
+ });
958
+ return result;
959
+ }
960
+ /** Import a committed env-spec-v1 contract. Reads schema metadata, never developer env files. */
961
+ function envSchema(file, options = {}) {
962
+ const filename = file instanceof URL ? fileURLToPath(file) : resolve(file);
963
+ const prefix = options.prefix ?? "VITEHUB_";
964
+ if (prefix && (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(prefix) || prefix.length > 128)) fail(void 0, "Prefix must be a portable environment name prefix");
965
+ let source;
966
+ try {
967
+ source = readFileSync(filename, "utf8");
968
+ } catch {
969
+ throw invalidEnvDeclaration(filename, `${filename}: Cannot read environment schema file`);
970
+ }
971
+ let fields;
972
+ try {
973
+ fields = parseEnvSchema(source, filename);
974
+ } catch (error) {
975
+ throw invalidEnvDeclaration(filename, error instanceof Error ? error.message : `${filename}: Invalid environment schema file`);
976
+ }
977
+ const knownKeys = new Set(fields.map((field) => field.key));
978
+ for (const key of Object.keys(options.paths ?? {})) if (!knownKeys.has(key)) fail(void 0, "Path mapping refers to an undeclared schema key");
979
+ const server = /* @__PURE__ */ new Map();
980
+ const publicConfig = {};
981
+ const publicNames = /* @__PURE__ */ new Set();
982
+ for (const field of fields) {
983
+ const publicPrefix = `${prefix}PUBLIC_`;
984
+ const publicField = field.key.startsWith(publicPrefix);
985
+ if (publicField && field.sensitive) fail(field, "A Public Env declaration cannot be sensitive; mark it @public or @sensitive=false");
986
+ if (schemaContainsEnum(field.type) && field.sensitive) fail(field, "A secret enum would expose its allowed values; use a string instead");
987
+ const name = publicField ? field.key.slice(publicPrefix.length) : prefix && field.key.startsWith(prefix) ? field.key.slice(prefix.length) : field.key;
988
+ const mapped = options.paths && Object.hasOwn(options.paths, field.key) ? options.paths[field.key] : outputName(name);
989
+ if (typeof mapped !== "string") fail(field, "Output path must be a string");
990
+ const segments = safePath(mapped, field, publicField);
991
+ const declaration = descriptorVariable(descriptor(field), {
992
+ ...field.default !== void 0 ? { default: field.default } : {},
993
+ mode: publicField ? "build" : "runtime",
994
+ required: field.required,
995
+ secret: field.sensitive,
996
+ source: env.source(field.key, {
997
+ canonical: false,
998
+ skipEmpty: !field.required && field.type.kind !== "string"
999
+ })
1000
+ });
1001
+ if (publicField) {
1002
+ if (publicNames.has(mapped)) fail(field, "Output path collides with another declaration");
1003
+ publicNames.add(mapped);
1004
+ Object.defineProperty(publicConfig, mapped, {
1005
+ enumerable: true,
1006
+ configurable: true,
1007
+ writable: true,
1008
+ value: declaration
1009
+ });
1010
+ } else add(server, segments, declaration, field);
1011
+ }
1012
+ return {
1013
+ public: publicConfig,
1014
+ server: serverConfig(server)
1015
+ };
1016
+ }
1017
+ //#endregion
568
1018
  //#region src/vite.ts
569
1019
  const ENV_VITE_PLUGIN_NAME = "@vite-hub/env/vite";
570
1020
  const ENV_PUBLIC_ID = VITEHUB_ENV_PUBLIC_ID;
571
1021
  const ENV_SERVER_ID = VITEHUB_ENV_SERVER_ID;
1022
+ const ENV_DESCRIPTION_ID = "#vitehub/env/description";
1023
+ const RESOLVED_DESCRIPTION_ID = `\0${ENV_DESCRIPTION_ID}`;
572
1024
  const RESOLVED_PUBLIC_ID = `\0${ENV_PUBLIC_ID}`;
573
1025
  const RESOLVED_SERVER_ID = `\0${ENV_SERVER_ID}`;
574
1026
  const defaultRuntimeImports = {
575
1027
  secret: "@vite-hub/env/secret",
576
1028
  server: "@vite-hub/env/server"
577
1029
  };
1030
+ let envVitePluginSequence = 0;
1031
+ const developmentSecretLocks = /* @__PURE__ */ new Map();
578
1032
  function createEnvImportAliases(options = {}) {
579
1033
  return createViteHubEnvImportAliases(resolveEnvProjectRoot(options));
580
1034
  }
@@ -589,63 +1043,187 @@ function createEnvTypeScriptPaths(options = {}) {
589
1043
  function hubEnv(options = {}) {
590
1044
  let buildPublicConfig = {};
591
1045
  let serverRegistry = {};
592
- let diagnosticsText;
1046
+ const resolvedStates = /* @__PURE__ */ new Map();
1047
+ const generatedStateWrites = /* @__PURE__ */ new Map();
1048
+ const resolvedConfigStates = /* @__PURE__ */ new WeakMap();
1049
+ const pendingConfigStates = /* @__PURE__ */ new Map();
1050
+ const configStateKey = `__vitehubEnvState${++envVitePluginSequence}`;
1051
+ const environmentStateKey = `${configStateKey}Resolved`;
1052
+ let configStateSequence = 0;
1053
+ const serverRegistryHandlers = /* @__PURE__ */ new Set();
593
1054
  const getPublicEnv = () => buildPublicConfig;
594
1055
  const getServerEnvRegistry = () => serverRegistry;
1056
+ const createServerEnvRegistry = (declarations) => createRuntimeRegistry(declarations, { prefix: options.prefix });
1057
+ const resolveProjectRoot = (viteRoot) => resolveViteHubProjectRoot(resolve(viteRoot), { projectRoot: options.projectRoot });
595
1058
  const runtimeImports = resolveRuntimeImports(options.runtimeImports);
1059
+ const prepareTypes = async (config, viteRoot) => {
1060
+ const root = resolveProjectRoot(viteRoot);
1061
+ const packageRoot = await resolvePackageRoot(viteRoot, root);
1062
+ const registry = createRuntimeRegistry(config?.server, { prefix: options.prefix });
1063
+ assertConfiguredProviders(registry, resolveProviderModules(options.providers, root));
1064
+ await prepareEnvGeneratedTypes(root, packageRoot, config?.public, registry, runtimeImports);
1065
+ };
1066
+ const resolveState = async (config, mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey) => {
1067
+ const envConfig = config.env;
1068
+ validateEnvConfigShape(envConfig, "vite");
1069
+ const projectRoot = resolveProjectRoot(config.root || process.cwd());
1070
+ const providerModules = resolveProviderModules(options.providers, projectRoot);
1071
+ if (!envConfig) return {
1072
+ defineValues: {},
1073
+ projectRoot,
1074
+ state: {
1075
+ diagnosticsText: void 0,
1076
+ projectRoot,
1077
+ providerModules,
1078
+ publicConfig: {},
1079
+ publicTypes: {},
1080
+ serverRegistry: {},
1081
+ developmentSecret,
1082
+ developmentSecretGenerated,
1083
+ developmentSecretEnvKey
1084
+ }
1085
+ };
1086
+ const context = createSourceContext({
1087
+ env: {
1088
+ ...loadEnv(mode, projectRoot, ""),
1089
+ ...process.env
1090
+ },
1091
+ mode: "build",
1092
+ rootDir: projectRoot
1093
+ });
1094
+ const publicResult = await resolveEnvEntries(envConfig.public, {
1095
+ context,
1096
+ exposure: "build public",
1097
+ prefix: options.prefix,
1098
+ section: "env.public",
1099
+ timing: "Vite config/dev/build"
1100
+ });
1101
+ const defineResult = await resolveBuildConfig(envConfig.define, {
1102
+ context,
1103
+ exposure: "compile-time replacement",
1104
+ prefix: options.prefix,
1105
+ section: "env.define",
1106
+ timing: "Vite transform/build"
1107
+ });
1108
+ const publicConfig = Object.fromEntries(publicResult.entries.map((entry) => [entry.key, entry.value]));
1109
+ const registry = createServerEnvRegistry(envConfig.server);
1110
+ assertConfiguredProviders(registry, providerModules);
1111
+ return {
1112
+ defineValues: defineResult.values,
1113
+ projectRoot,
1114
+ state: {
1115
+ diagnosticsText: formatDiagnostics([...publicResult.diagnostics, ...defineResult.diagnostics], options.diagnostics),
1116
+ projectRoot,
1117
+ providerModules,
1118
+ publicConfig,
1119
+ publicTypes: createPublicTypeEntries(envConfig.public, publicConfig),
1120
+ serverRegistry: registry,
1121
+ developmentSecret,
1122
+ developmentSecretGenerated,
1123
+ developmentSecretEnvKey
1124
+ }
1125
+ };
1126
+ };
596
1127
  return {
597
1128
  name: ENV_VITE_PLUGIN_NAME,
598
1129
  api: {
1130
+ createServerEnvRegistry,
599
1131
  getPublicEnv,
600
- getServerEnvRegistry
1132
+ getServerEnvRegistry,
1133
+ onServerEnvRegistry: (handler) => serverRegistryHandlers.add(handler),
1134
+ prepareTypes,
1135
+ resolveProjectRoot
601
1136
  },
1137
+ vitehub: { cli: () => createEnvCliContributor({ resolveProjectRoot }) },
602
1138
  async config(config, env) {
1139
+ let developmentSecret;
1140
+ let developmentSecretGenerated = false;
1141
+ let developmentSecretEnvKey;
1142
+ if (env.command === "serve") {
1143
+ const projectRoot = resolveProjectRoot(config.root || process.cwd());
1144
+ const resolvedSecret = await resolveDevelopmentSecret(projectRoot, loadEnv(env.mode, projectRoot, ""));
1145
+ developmentSecret = resolvedSecret.secret;
1146
+ developmentSecretGenerated = resolvedSecret.generated;
1147
+ developmentSecretEnvKey = resolvedSecret.envKey;
1148
+ if (developmentSecretEnvKey) process.env[developmentSecretEnvKey] = developmentSecret;
1149
+ }
603
1150
  const envConfig = config.env;
604
- validateEnvConfigShape(envConfig, "vite");
605
- if (!envConfig) return;
606
- const root = resolveViteHubProjectRoot(resolve(config.root || process.cwd()), { projectRoot: options.projectRoot });
607
- const context = createSourceContext({
608
- env: {
609
- ...loadEnv(env.mode, root, ""),
610
- ...process.env
611
- },
612
- mode: "build",
613
- rootDir: root
1151
+ const { defineValues, state } = await resolveState(config, env.mode, developmentSecret, developmentSecretGenerated, developmentSecretEnvKey);
1152
+ buildPublicConfig = state.publicConfig;
1153
+ serverRegistry = state.serverRegistry;
1154
+ const configStateId = String(++configStateSequence);
1155
+ pendingConfigStates.set(configStateId, state);
1156
+ for (const handler of serverRegistryHandlers) handler(serverRegistry, config);
1157
+ if (!envConfig) return {
1158
+ [configStateKey]: configStateId,
1159
+ __vitehubEnvDevelopmentSecret: developmentSecret,
1160
+ __vitehubEnvDevelopmentSecretEnvKey: developmentSecretEnvKey
1161
+ };
1162
+ return {
1163
+ [configStateKey]: configStateId,
1164
+ __vitehubEnvDevelopmentSecret: developmentSecret,
1165
+ __vitehubEnvDevelopmentSecretEnvKey: developmentSecretEnvKey,
1166
+ define: {
1167
+ ...Object.fromEntries(Object.entries(defineValues).map(([key, value]) => [key, JSON.stringify(value)])),
1168
+ ...config.define
1169
+ }
1170
+ };
1171
+ },
1172
+ async configResolved(config) {
1173
+ const projectRoot = resolveProjectRoot(config.root);
1174
+ const configStateId = String(Object.getOwnPropertyDescriptor(config, configStateKey)?.value ?? "");
1175
+ const state = pendingConfigStates.get(configStateId) ?? resolvedStates.get(projectRoot);
1176
+ if (!state) throw envErrorDiagnostics.ENV_B0001({ message: `Missing resolved Env state for ${projectRoot}` });
1177
+ pendingConfigStates.delete(configStateId);
1178
+ resolvedConfigStates.set(config, state);
1179
+ Reflect.defineProperty(config, "__vitehubEnvDevelopmentSecretEnvKey", {
1180
+ configurable: true,
1181
+ value: state.developmentSecretEnvKey
614
1182
  });
615
- const publicResult = await resolveEnvEntries(envConfig.public, {
616
- context,
617
- exposure: "build public",
618
- prefix: options.prefix,
619
- section: "env.public",
620
- timing: "Vite config/dev/build"
1183
+ Reflect.defineProperty(config, "__vitehubEnvDevelopmentSecret", {
1184
+ configurable: true,
1185
+ value: state.developmentSecret
621
1186
  });
622
- const defineResult = await resolveBuildConfig(envConfig.define, {
623
- context,
624
- exposure: "compile-time replacement",
625
- prefix: options.prefix,
626
- section: "env.define",
627
- timing: "Vite transform/build"
1187
+ const onResolved = config.__vitehubEnvOnResolved;
1188
+ if (onResolved?.length) {
1189
+ await Promise.all(onResolved.map((callback) => callback(state.developmentSecretEnvKey)));
1190
+ onResolved.length = 0;
1191
+ }
1192
+ for (const environmentConfig of Object.values(config.environments || {})) {
1193
+ resolvedConfigStates.set(environmentConfig, state);
1194
+ Reflect.defineProperty(environmentConfig, environmentStateKey, {
1195
+ configurable: true,
1196
+ value: state
1197
+ });
1198
+ }
1199
+ Reflect.deleteProperty(config, configStateKey);
1200
+ resolvedStates.set(projectRoot, state);
1201
+ if (state.diagnosticsText) config.logger.info(state.diagnosticsText);
1202
+ const generatedStateWrite = (generatedStateWrites.get(projectRoot) ?? Promise.resolve()).catch(() => void 0).then(async () => {
1203
+ const packageRoot = await resolvePackageRoot(config.root, projectRoot);
1204
+ await refreshEnvGeneratedFiles(projectRoot, packageRoot, state.publicConfig, state.publicTypes, state.serverRegistry, runtimeImports, state.providerModules, state.developmentSecretEnvKey, state.developmentSecretGenerated);
628
1205
  });
629
- buildPublicConfig = Object.fromEntries(publicResult.entries.map((entry) => [entry.key, entry.value]));
630
- serverRegistry = createRuntimeRegistry(envConfig.server, { prefix: options.prefix });
631
- diagnosticsText = formatDiagnostics([...publicResult.diagnostics, ...defineResult.diagnostics], options.diagnostics);
632
- return { define: {
633
- ...Object.fromEntries(Object.entries(defineResult.values).map(([key, value]) => [key, JSON.stringify(value)])),
634
- ...config.define
635
- } };
636
- },
637
- async configResolved(config) {
638
- if (diagnosticsText) config.logger.info(diagnosticsText);
639
- const projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: options.projectRoot });
640
- await refreshEnvGeneratedFiles(projectRoot, await resolvePackageRoot(config.root, projectRoot), buildPublicConfig, serverRegistry, runtimeImports);
1206
+ generatedStateWrites.set(projectRoot, generatedStateWrite);
1207
+ try {
1208
+ await generatedStateWrite;
1209
+ } finally {
1210
+ if (generatedStateWrites.get(projectRoot) === generatedStateWrite) generatedStateWrites.delete(projectRoot);
1211
+ }
641
1212
  },
642
1213
  load(id) {
643
- if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(buildPublicConfig);
644
- if (id === RESOLVED_SERVER_ID) return createServerEnvModule(serverRegistry, runtimeImports);
1214
+ const viteConfig = this?.environment?.config;
1215
+ const state = (viteConfig ? Reflect.get(viteConfig, environmentStateKey) : void 0) ?? (viteConfig ? resolvedConfigStates.get(viteConfig) : void 0) ?? (viteConfig?.root ? resolvedStates.get(resolveProjectRoot(viteConfig.root)) : void 0) ?? (viteConfig?.root ? Array.from(pendingConfigStates.values()).findLast((state) => state.projectRoot === resolveProjectRoot(viteConfig.root)) : void 0) ?? Array.from(resolvedStates.values()).at(-1) ?? Array.from(pendingConfigStates.values()).at(-1);
1216
+ const publicConfig = state?.publicConfig ?? buildPublicConfig;
1217
+ const registry = state?.serverRegistry ?? serverRegistry;
1218
+ const providerModules = state?.providerModules ?? {};
1219
+ if (id === RESOLVED_DESCRIPTION_ID) return createServerEnvDescriptionModule(registry);
1220
+ if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(publicConfig);
1221
+ if (id === RESOLVED_SERVER_ID) return createServerEnvModule(registry, runtimeImports, providerModules, void 0, state?.developmentSecretEnvKey, state?.developmentSecretGenerated);
645
1222
  },
646
1223
  resolveId: {
647
1224
  order: "pre",
648
1225
  handler(id) {
1226
+ if (id === ENV_DESCRIPTION_ID) return RESOLVED_DESCRIPTION_ID;
649
1227
  if (id === ENV_PUBLIC_ID) return RESOLVED_PUBLIC_ID;
650
1228
  if (id === ENV_SERVER_ID) return RESOLVED_SERVER_ID;
651
1229
  }
@@ -656,6 +1234,20 @@ function hubEnv(options = {}) {
656
1234
  }
657
1235
  };
658
1236
  }
1237
+ async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
1238
+ const publicTypes = createPublicTypeEntries(publicConfig);
1239
+ await Promise.all([
1240
+ ...packageRoot && packageRoot !== root ? [
1241
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(packageRoot), createPublicEnvModuleTypes(publicTypes)),
1242
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(packageRoot), createServerEnvModuleTypes(serverRegistry, runtimeImports)),
1243
+ writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))
1244
+ ] : [],
1245
+ writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
1246
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
1247
+ writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
1248
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
1249
+ ]);
1250
+ }
659
1251
  function resolveEnvProjectRoot(options) {
660
1252
  return resolveViteHubProjectRoot(process.cwd(), { projectRoot: options.projectRoot });
661
1253
  }
@@ -668,18 +1260,109 @@ function resolveRuntimeImports(imports) {
668
1260
  server: imports?.server ?? defaultRuntimeImports.server
669
1261
  };
670
1262
  }
671
- function legacyEnvAmbientTypesPaths(root) {
672
- return [resolve(root, ".vitehub", "env", "vite.d.ts")];
1263
+ function resolveProviderModules(providers, root) {
1264
+ const output = {};
1265
+ for (const [name, specifier] of Object.entries(providers || {})) {
1266
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(name)) throw envErrorDiagnostics.ENV_B0002({ message: "[vitehub] Env provider names must start with a letter and contain only letters, numbers, underscores, or hyphens." });
1267
+ if (typeof specifier !== "string" || !specifier.trim()) throw envErrorDiagnostics.ENV_B0003({ message: `[vitehub] Env provider ${JSON.stringify(name)} requires a non-empty module specifier.` });
1268
+ const normalized = specifier.trim();
1269
+ if (/^(?:\\\\[?.]\\|\/\/[?.]\/)/.test(normalized)) throw envErrorDiagnostics.ENV_B0004({ message: `[vitehub] Env provider ${JSON.stringify(name)} uses an unsupported namespaced Windows module path.` });
1270
+ output[name] = normalized.startsWith(".") ? resolve(root, normalized) : normalized;
1271
+ }
1272
+ return output;
1273
+ }
1274
+ function assertConfiguredProviders(registry, providers) {
1275
+ for (const { entry, path } of runtimeRegistryEntries(registry)) if (isRuntimeProviderEntry(entry) && !Object.hasOwn(providers, entry.source.provider)) throw envErrorDiagnostics.ENV_B0005({ message: `[vitehub] ${path} references Env provider ${JSON.stringify(entry.source.provider)}, but hubEnv({ providers }) does not configure it.` });
1276
+ }
1277
+ const generatedSecretPattern = /^[0-9a-f]{64}$/;
1278
+ /**
1279
+ * Give the development server a root secret when none is configured, so `deriveSecret()` works without setup.
1280
+ * The secret is kept in `.vitehub/env/secret` with mode 0600 and survives restarts. Builds never generate one.
1281
+ */
1282
+ async function resolveDevelopmentSecret(projectRoot, loadedEnv) {
1283
+ const existing = developmentSecretLocks.get(projectRoot);
1284
+ if (existing) return existing;
1285
+ const pending = resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv);
1286
+ developmentSecretLocks.set(projectRoot, pending);
1287
+ try {
1288
+ return await pending;
1289
+ } finally {
1290
+ if (developmentSecretLocks.get(projectRoot) === pending) developmentSecretLocks.delete(projectRoot);
1291
+ }
673
1292
  }
674
- async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
1293
+ async function resolveDevelopmentSecretUnlocked(projectRoot, loadedEnv) {
1294
+ const configured = readViteHubSecret(loadedEnv);
1295
+ const envKey = `VITEHUB_SECRET_${createHash("sha256").update(resolve(projectRoot)).digest("hex").slice(0, 16)}`;
1296
+ if (configured) return {
1297
+ generated: false,
1298
+ secret: configured,
1299
+ envKey
1300
+ };
1301
+ const secretPath = resolve(projectRoot, ".vitehub", "env", "secret");
1302
+ let secret = await readFile(secretPath, "utf8").then((value) => value.trim(), () => "");
1303
+ if (!generatedSecretPattern.test(secret)) {
1304
+ await mkdir(dirname(secretPath), { recursive: true });
1305
+ const lockPath = `${secretPath}.lock`;
1306
+ let lock;
1307
+ for (let attempt = 0; attempt < 120 && !lock; attempt++) try {
1308
+ lock = await open(lockPath, "wx", 384);
1309
+ await lock.writeFile(`${process.pid}\n`);
1310
+ } catch (error) {
1311
+ if (error.code !== "EEXIST") throw error;
1312
+ try {
1313
+ const lockStat = await stat(lockPath);
1314
+ const owner = await readFile(lockPath, "utf8").catch(() => "");
1315
+ let ownerAlive = false;
1316
+ const ownerPid = Number.parseInt(owner, 10);
1317
+ if (Number.isInteger(ownerPid) && ownerPid > 0) try {
1318
+ process.kill(ownerPid, 0);
1319
+ ownerAlive = true;
1320
+ } catch (error) {
1321
+ ownerAlive = error.code !== "ESRCH";
1322
+ }
1323
+ if (!ownerAlive && Date.now() - lockStat.mtimeMs > 3e4) {
1324
+ const stalePath = `${lockPath}.${process.pid}.${Date.now()}.stale`;
1325
+ await rename(lockPath, stalePath).catch(() => {});
1326
+ await unlink(stalePath).catch(() => {});
1327
+ }
1328
+ } catch {}
1329
+ await new Promise((resolve) => setTimeout(resolve, 5));
1330
+ }
1331
+ if (!lock) throw new Error(`Timed out waiting for generated secret lock: ${secretPath}`);
1332
+ const replacementPath = `${secretPath}.${process.pid}.${Date.now()}.tmp`;
1333
+ try {
1334
+ secret = await readFile(secretPath, "utf8").then((value) => value.trim(), () => "");
1335
+ if (!generatedSecretPattern.test(secret)) {
1336
+ secret = randomBytes(32).toString("hex");
1337
+ await writeFile(replacementPath, secret, {
1338
+ flag: "wx",
1339
+ mode: 384
1340
+ });
1341
+ await rename(replacementPath, secretPath);
1342
+ }
1343
+ } finally {
1344
+ const owned = await lock.stat().then((lockStat) => stat(lockPath).then((pathStat) => lockStat.dev === pathStat.dev && lockStat.ino === pathStat.ino, () => false));
1345
+ await lock.close();
1346
+ if (owned) await unlink(lockPath).catch(() => {});
1347
+ await unlink(replacementPath).catch(() => {});
1348
+ }
1349
+ }
1350
+ await chmod(secretPath, 384);
1351
+ return {
1352
+ generated: true,
1353
+ secret,
1354
+ envKey
1355
+ };
1356
+ }
1357
+ async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated) {
675
1358
  await Promise.all([
676
- ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, serverRegistry, runtimeImports), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
677
- writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicConfig, serverRegistry, runtimeImports)),
1359
+ ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
1360
+ writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
678
1361
  writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
679
- writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicConfig)),
680
- writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports)),
681
- writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports)),
682
- ...legacyEnvAmbientTypesPaths(root).map((path) => rm(path, { force: true }))
1362
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
1363
+ writeFileIfChanged(viteHubEnvDescriptionModulePath(root), createServerEnvDescriptionModule(serverRegistry)),
1364
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
1365
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
683
1366
  ]);
684
1367
  }
685
1368
  function createAmbientTypesReference(packageRoot, projectRoot) {
@@ -687,11 +1370,11 @@ function createAmbientTypesReference(packageRoot, projectRoot) {
687
1370
  const specifier = target.startsWith(".") ? target : `./${target}`;
688
1371
  return `/// <reference path=${JSON.stringify(specifier)} />\n`;
689
1372
  }
690
- function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports) {
1373
+ function packageEnvModuleWrites(root, publicConfig, publicTypes, serverRegistry, runtimeImports, providerModules, developmentSecretEnvKey, developmentSecretGenerated) {
691
1374
  return [
692
1375
  writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
693
- writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicConfig)),
694
- writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports)),
1376
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
1377
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root), developmentSecretEnvKey, developmentSecretGenerated)),
695
1378
  writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
696
1379
  ];
697
1380
  }
@@ -722,59 +1405,151 @@ function createPublicEnvModule(publicConfig) {
722
1405
  ""
723
1406
  ].join("\n");
724
1407
  }
725
- function createPublicEnvModuleTypes(publicConfig) {
1408
+ function createPublicEnvModuleTypes(publicTypes) {
726
1409
  return [
727
1410
  "export interface PublicEnv {",
728
- ...createPublicTypeFields(publicConfig, 2),
1411
+ ...createPublicTypeFields(publicTypes, 2),
729
1412
  "}",
730
1413
  "export const publicEnv: PublicEnv",
731
1414
  "export function usePublicEnv(): PublicEnv",
732
1415
  ""
733
1416
  ].join("\n");
734
1417
  }
735
- function createServerEnvModule(serverRegistry, runtimeImports) {
1418
+ function createServerEnvModule(serverRegistry, runtimeImports, providerModules, outputPath, developmentSecretEnvKey, developmentSecretGenerated) {
1419
+ const referenced = referencedProviderNames(serverRegistry);
1420
+ const providers = Object.entries(providerModules).filter(([name]) => referenced.has(name));
736
1421
  return [
737
- `import { resolveServerEnv } from ${JSON.stringify(runtimeImports.server)};`,
738
- `const registry = ${JSON.stringify(serverRegistry, null, 2)};`,
739
- "export function useServerEnv(event) { return resolveServerEnv(registry, event); }",
740
- "export async function runWithServerEnv(event, callback) { return await callback(useServerEnv(event)); }",
1422
+ `import * as envRuntime from ${JSON.stringify(runtimeImports.server)};`,
1423
+ ...providers.map(([, specifier], index) => `import envProvider${index} from ${JSON.stringify(providerImportSpecifier(specifier, outputPath))};`),
1424
+ `const registry = JSON.parse(${JSON.stringify(JSON.stringify(serverRegistry))});`,
1425
+ `const providers = Object.fromEntries([${providers.map(([name], index) => `[${JSON.stringify(name)}, envProvider${index}]`).join(", ")}]);`,
1426
+ createServerEnvDescriptionModule(serverRegistry).trimEnd(),
1427
+ "export const manageServerEnv = envRuntime.createServerEnvManagement?.(registry, providers) ?? (async () => Response.json({ message: \"Env management is unavailable.\" }, { status: 503 }));",
1428
+ "export function useServerEnv(event) { return envRuntime.resolveServerEnv(registry, event); }",
1429
+ `export async function deriveSecret(purpose, event) { return await envRuntime.deriveSecret(purpose, event, undefined, ${JSON.stringify(developmentSecretGenerated)}, ${JSON.stringify(developmentSecretEnvKey)}); }`,
1430
+ "export async function loadServerEnv(event, options) { return await envRuntime.loadServerEnv(registry, event, { ...options, providers }); }",
1431
+ "export async function inspectServerEnv(event, options) { return await envRuntime.inspectServerEnv(registry, event, { ...options, providers }); }",
1432
+ "export async function runWithServerEnv(event, callback, options) { return await callback(await loadServerEnv(event, options)); }",
741
1433
  ""
742
1434
  ].join("\n");
743
1435
  }
1436
+ function createServerEnvDescriptionModule(serverRegistry) {
1437
+ return `export function describeServerEnv() { return JSON.parse(${JSON.stringify(JSON.stringify(describeServerEnv(serverRegistry)))}); }\n`;
1438
+ }
1439
+ function providerImportSpecifier(specifier, outputPath) {
1440
+ const windowsAbsolute = win32.isAbsolute(specifier);
1441
+ if (!isAbsolute(specifier) && !windowsAbsolute) return specifier;
1442
+ if (!outputPath) {
1443
+ const normalized = specifier.replace(/\\/g, "/");
1444
+ if (normalized.startsWith("//")) return `/@fs/${encodeModulePath(normalized)}`;
1445
+ return /^[A-Za-z]:\//.test(normalized) ? `/${normalized}` : normalized;
1446
+ }
1447
+ if (windowsAbsolute !== win32.isAbsolute(outputPath)) return absoluteProviderImportSpecifier(specifier);
1448
+ const target = windowsAbsolute ? win32.relative(win32.dirname(outputPath), specifier) : relative(dirname(outputPath), specifier);
1449
+ if (isAbsolute(target) || win32.isAbsolute(target)) return absoluteProviderImportSpecifier(target);
1450
+ const encodedTarget = encodeModulePath(target.replace(/\\/g, "/"));
1451
+ return encodedTarget.startsWith(".") ? encodedTarget : `./${encodedTarget}`;
1452
+ }
1453
+ function absoluteProviderImportSpecifier(path) {
1454
+ const normalized = path.replace(/\\/g, "/");
1455
+ const encoded = encodeModulePath(normalized);
1456
+ return /^[A-Za-z]:\//.test(normalized) ? `/${encoded}` : encoded;
1457
+ }
1458
+ function encodeModulePath(path) {
1459
+ return path.split("/").map((segment) => /^[A-Za-z]:$/.test(segment) ? segment : encodeURIComponent(segment)).join("/");
1460
+ }
1461
+ function referencedProviderNames(registry) {
1462
+ const names = /* @__PURE__ */ new Set();
1463
+ for (const { entry } of runtimeRegistryEntries(registry)) if (isRuntimeProviderEntry(entry)) names.add(entry.source.provider);
1464
+ return names;
1465
+ }
744
1466
  function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
745
1467
  return [
746
1468
  `import type { SecretEnv } from ${JSON.stringify(runtimeImports.secret)}`,
747
1469
  "",
1470
+ ...createServerEnvInspectionTypes(0),
748
1471
  "export interface ServerEnv {",
749
1472
  ...createServerTypeFields(serverRegistry, 2),
750
1473
  "}",
751
1474
  "export function useServerEnv(event?: unknown): ServerEnv",
752
- "export function runWithServerEnv<T>(event: unknown, callback: (env: ServerEnv) => T | Promise<T>): Promise<T>",
1475
+ "export function deriveSecret(purpose: string, event?: unknown): Promise<string>",
1476
+ ...createReadonlyServerEnvTypes(0, "SecretEnv"),
1477
+ `export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ReadonlyServerEnv>`,
1478
+ `export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ServerEnvInspection>`,
1479
+ `export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<T>`,
753
1480
  ""
754
1481
  ].join("\n");
755
1482
  }
756
- function createViteTypes(publicConfig, serverRegistry, runtimeImports) {
1483
+ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
757
1484
  return [
758
1485
  "declare module \"#vitehub/env/public\" {",
759
1486
  " export interface PublicEnv {",
760
- ...createPublicTypeFields(publicConfig, 4),
1487
+ ...createPublicTypeFields(publicTypes, 4),
761
1488
  " }",
762
1489
  " export const publicEnv: PublicEnv",
763
1490
  " export function usePublicEnv(): PublicEnv",
764
1491
  "}",
765
1492
  "declare module \"#vitehub/env/server\" {",
1493
+ ...createServerEnvInspectionTypes(2),
766
1494
  " export interface ServerEnv {",
767
1495
  ...createServerTypeFields(serverRegistry, 4, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
768
1496
  " }",
769
1497
  " export function useServerEnv(event?: unknown): ServerEnv",
770
- " export function runWithServerEnv<T>(event: unknown, callback: (env: ServerEnv) => T | Promise<T>): Promise<T>",
1498
+ " export function deriveSecret(purpose: string, event?: unknown): Promise<string>",
1499
+ ...createReadonlyServerEnvTypes(2, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
1500
+ ` export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ReadonlyServerEnv>`,
1501
+ ` export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<ServerEnvInspection>`,
1502
+ ` export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal; access?: import(${JSON.stringify(runtimeImports.server)}).EnvAccessContext }): Promise<T>`,
771
1503
  "}",
772
1504
  ""
773
1505
  ].join("\n");
774
1506
  }
775
- function createPublicTypeFields(publicConfig, indent) {
1507
+ function createServerEnvInspectionTypes(indent) {
776
1508
  const prefix = " ".repeat(indent);
777
- return Object.entries(publicConfig).map(([key, value]) => `${prefix}${JSON.stringify(key)}: ${typeof value}`);
1509
+ return [
1510
+ `${prefix}export interface ServerEnvDescriptionEntry { path?: string; canonicalName?: string; source: "env" | "literal" | "provider"; provider?: string; secret: boolean; required: boolean; hasDefault: boolean; type?: string }`,
1511
+ `${prefix}export interface ServerEnvDescription { entries: readonly ServerEnvDescriptionEntry[] }`,
1512
+ `${prefix}export function describeServerEnv(): ServerEnvDescription`,
1513
+ `${prefix}export function manageServerEnv(request: Request): Promise<Response>`,
1514
+ `${prefix}export interface ServerEnvInspectionEntry {`,
1515
+ `${prefix} masked: boolean`,
1516
+ `${prefix} path?: string`,
1517
+ `${prefix} provider?: string`,
1518
+ `${prefix} required: boolean`,
1519
+ `${prefix} source: "env" | "literal" | "provider"`,
1520
+ `${prefix} status: "available" | "defaulted" | "error" | "invalid" | "missing"`,
1521
+ `${prefix} via?: "canonical" | "conventional"`,
1522
+ `${prefix} conflict?: true`,
1523
+ `${prefix}}`,
1524
+ `${prefix}export interface ServerEnvInspection {`,
1525
+ `${prefix} entries: readonly ServerEnvInspectionEntry[]`,
1526
+ `${prefix}}`
1527
+ ];
1528
+ }
1529
+ function createReadonlyServerEnvTypes(indent, secretType) {
1530
+ const prefix = " ".repeat(indent);
1531
+ return [
1532
+ `${prefix}export type ReadonlyServerEnv = DeepReadonly<ServerEnv>`,
1533
+ `${prefix}type DeepReadonly<T> = T extends ${secretType}<unknown>`,
1534
+ `${prefix} ? T`,
1535
+ `${prefix} : T extends (...args: infer TArguments) => infer TResult`,
1536
+ `${prefix} ? (...args: TArguments) => TResult`,
1537
+ `${prefix} : T extends object`,
1538
+ `${prefix} ? { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> }`,
1539
+ `${prefix} : T`
1540
+ ];
1541
+ }
1542
+ function createPublicTypeEntries(publicConfig, resolvedValues) {
1543
+ return Object.fromEntries(Object.entries(publicConfig ?? {}).map(([key, declaration]) => {
1544
+ const valueSchema = runtimeValueSchema(declaration);
1545
+ const fallbackValue = resolvedValues ? resolvedValues[key] : typeof declaration.default === "undefined" ? void 0 : parseSchema(declaration.schema, declaration.default, `env.public.${key}`);
1546
+ const fallbackType = fallbackValue === null ? "null" : fallbackValue === void 0 ? "unknown" : typeof fallbackValue;
1547
+ return [key, `${declaration.type ?? (valueSchema ? envValueTypeName(valueSchema) : void 0) ?? fallbackType}${!declaration.required && typeof declaration.default === "undefined" ? " | undefined" : ""}`];
1548
+ }));
1549
+ }
1550
+ function createPublicTypeFields(publicTypes, indent) {
1551
+ const prefix = " ".repeat(indent);
1552
+ return Object.entries(publicTypes).map(([key, type]) => `${prefix}${JSON.stringify(key)}: ${type}`);
778
1553
  }
779
1554
  function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
780
1555
  const prefix = " ".repeat(indent);
@@ -784,15 +1559,18 @@ function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
784
1559
  });
785
1560
  }
786
1561
  function serverTypeFor(value, indent, secretType) {
787
- if (isLiteralEntry(value)) return literalType(value.value);
788
- if (isEnvEntry(value)) return value.secret ? `${secretType}<string>` : "string";
1562
+ if (isRuntimeLiteralEntry(value)) return literalType(value.value);
1563
+ if (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) {
1564
+ const type = envValueTypeName(value.schema ?? stringValueSchema);
1565
+ return value.secret ? `${secretType}<${type}>` : type;
1566
+ }
789
1567
  const fields = createServerTypeFields(value, indent + 2, secretType);
790
1568
  if (!fields.length) return "Record<string, never>";
791
1569
  const prefix = " ".repeat(indent);
792
1570
  return `{\n${fields.join("\n")}\n${prefix}}`;
793
1571
  }
794
1572
  function isOptionalServerValue(value) {
795
- return isEnvEntry(value) && !value.required && typeof value.default === "undefined";
1573
+ return (isRuntimeEnvEntry(value) || isRuntimeProviderEntry(value)) && !value.required && typeof value.default === "undefined";
796
1574
  }
797
1575
  function literalType(value) {
798
1576
  if (value === null) return "null";
@@ -804,17 +1582,5 @@ function literalType(value) {
804
1582
  default: return "unknown";
805
1583
  }
806
1584
  }
807
- function isLiteralEntry(value) {
808
- if (!isRecord(value)) return false;
809
- return value.kind === "literal";
810
- }
811
- function isEnvEntry(value) {
812
- if (!isRecord(value)) return false;
813
- const record = value;
814
- return isRecord(record.source) && typeof record.required === "boolean" && typeof record.secret === "boolean";
815
- }
816
- function isRecord(value) {
817
- return typeof value === "object" && value !== null && !Array.isArray(value);
818
- }
819
1585
  //#endregion
820
- export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, env, hubEnv };
1586
+ export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createRuntimeRegistry as createRuntimeEnvRegistry, env, envSchema, hubEnv };