@vite-hub/env 0.0.0 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.js ADDED
@@ -0,0 +1,819 @@
1
+ import { n as env, r as isDefaultStringEnvVariable, t as defaultStringSchema } from "./declarations-Cy5XamUA.js";
2
+ import { parseSchema } from "./schema.js";
3
+ import { a as missingRequiredEnv, i as isAbortError, n as invalidEnvDeclaration, t as envSourceFailed } from "./errors-RUmAFDJn.js";
4
+ 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";
8
+ import { loadEnv } from "vite";
9
+ import { execFile } from "node:child_process";
10
+ import { promisify } from "node:util";
11
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
12
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
13
+ function normalizeWindowsPath(input = "") {
14
+ if (!input) return input;
15
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
16
+ }
17
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
18
+ function cwd() {
19
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
20
+ return "/";
21
+ }
22
+ const resolve$1 = function(...arguments_) {
23
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
24
+ let resolvedPath = "";
25
+ let resolvedAbsolute = false;
26
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
27
+ const path = index >= 0 ? arguments_[index] : cwd();
28
+ if (!path || path.length === 0) continue;
29
+ resolvedPath = `${path}/${resolvedPath}`;
30
+ resolvedAbsolute = isAbsolute(path);
31
+ }
32
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
33
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
34
+ return resolvedPath.length > 0 ? resolvedPath : ".";
35
+ };
36
+ function normalizeString(path, allowAboveRoot) {
37
+ let res = "";
38
+ let lastSegmentLength = 0;
39
+ let lastSlash = -1;
40
+ let dots = 0;
41
+ let char = null;
42
+ for (let index = 0; index <= path.length; ++index) {
43
+ if (index < path.length) char = path[index];
44
+ else if (char === "/") break;
45
+ else char = "/";
46
+ if (char === "/") {
47
+ if (lastSlash === index - 1 || dots === 1);
48
+ else if (dots === 2) {
49
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
50
+ if (res.length > 2) {
51
+ const lastSlashIndex = res.lastIndexOf("/");
52
+ if (lastSlashIndex === -1) {
53
+ res = "";
54
+ lastSegmentLength = 0;
55
+ } else {
56
+ res = res.slice(0, lastSlashIndex);
57
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
58
+ }
59
+ lastSlash = index;
60
+ dots = 0;
61
+ continue;
62
+ } else if (res.length > 0) {
63
+ res = "";
64
+ lastSegmentLength = 0;
65
+ lastSlash = index;
66
+ dots = 0;
67
+ continue;
68
+ }
69
+ }
70
+ if (allowAboveRoot) {
71
+ res += res.length > 0 ? "/.." : "..";
72
+ lastSegmentLength = 2;
73
+ }
74
+ } else {
75
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
76
+ else res = path.slice(lastSlash + 1, index);
77
+ lastSegmentLength = index - lastSlash - 1;
78
+ }
79
+ lastSlash = index;
80
+ dots = 0;
81
+ } else if (char === "." && dots !== -1) ++dots;
82
+ else dots = -1;
83
+ }
84
+ return res;
85
+ }
86
+ const isAbsolute = function(p) {
87
+ return _IS_ABSOLUTE_RE.test(p);
88
+ };
89
+ //#endregion
90
+ //#region ../internal/src/definition-catalog.ts
91
+ async function writeFileIfChanged(file, contents) {
92
+ if (await readFile(file, "utf8").catch(() => void 0) === contents) return;
93
+ await mkdir(resolve$1(file, ".."), { recursive: true });
94
+ await writeFile(file, contents, "utf8");
95
+ }
96
+ //#endregion
97
+ //#region ../internal/src/build/vite.ts
98
+ const projectRootDirectoryMarkers = [
99
+ ["server", "agents"],
100
+ ["server", "schedules"],
101
+ ["server", "templates"],
102
+ ["server", "workspaces"]
103
+ ];
104
+ const projectRootDefinitionFileMarkers = [
105
+ ".ts",
106
+ ".mts",
107
+ ".cts",
108
+ ".js",
109
+ ".mjs",
110
+ ".cjs"
111
+ ].flatMap((extension) => [["server", `email${extension}`], [`server.email${extension}`]]);
112
+ const projectRootFileMarkers = [["package.json"]];
113
+ const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
114
+ const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
115
+ function resolveViteHubProjectRoot(root, options = {}) {
116
+ const resolvedRoot = resolve(root);
117
+ if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
118
+ if (basename(resolvedRoot) === "app") {
119
+ const parent = dirname(resolvedRoot);
120
+ if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
121
+ }
122
+ let current = resolvedRoot;
123
+ while (true) {
124
+ if (hasProjectRootMarker(current)) return current;
125
+ const parent = dirname(current);
126
+ if (parent === current) return resolvedRoot;
127
+ current = parent;
128
+ }
129
+ }
130
+ function hasProjectRootDirectoryMarker(root) {
131
+ for (const marker of projectRootDirectoryMarkers) try {
132
+ if (statSync(resolve(root, ...marker)).isDirectory()) return true;
133
+ } catch (error) {
134
+ if (error.code !== "ENOENT") throw error;
135
+ }
136
+ return false;
137
+ }
138
+ function hasProjectRootMarker(root) {
139
+ if (hasProjectRootDirectoryMarker(root)) return true;
140
+ if (hasProjectRootDefinitionFileMarker(root)) return true;
141
+ for (const marker of projectRootFileMarkers) try {
142
+ if (statSync(resolve(root, ...marker)).isFile()) return true;
143
+ } catch (error) {
144
+ if (error.code !== "ENOENT") throw error;
145
+ }
146
+ return false;
147
+ }
148
+ function hasProjectRootDefinitionFileMarker(root) {
149
+ for (const marker of projectRootDefinitionFileMarkers) try {
150
+ if (statSync(resolve(root, ...marker)).isFile()) return true;
151
+ } catch (error) {
152
+ if (error.code !== "ENOENT") throw error;
153
+ }
154
+ return false;
155
+ }
156
+ function viteHubEnvAmbientTypesPath(root) {
157
+ return resolve(root, ".vitehub", "types", "env.d.ts");
158
+ }
159
+ function viteHubEnvPublicModulePath(root) {
160
+ return resolve(root, ".vitehub", "env", "public.mjs");
161
+ }
162
+ function viteHubEnvPublicModuleTypesPath(root) {
163
+ return resolve(root, ".vitehub", "env", "public.d.ts");
164
+ }
165
+ function viteHubEnvServerModulePath(root) {
166
+ return resolve(root, ".vitehub", "env", "server.mjs");
167
+ }
168
+ function viteHubEnvServerModuleTypesPath(root) {
169
+ return resolve(root, ".vitehub", "env", "server.d.ts");
170
+ }
171
+ function createViteHubEnvImportAliases(root) {
172
+ return {
173
+ [VITEHUB_ENV_PUBLIC_ID]: viteHubEnvPublicModulePath(root),
174
+ [VITEHUB_ENV_SERVER_ID]: viteHubEnvServerModulePath(root)
175
+ };
176
+ }
177
+ //#endregion
178
+ //#region src/core/diagnostics.ts
179
+ function shouldTraceDiagnostics(option) {
180
+ return option === "trace" || process.env.VITEHUB_ENV_TRACE === "true";
181
+ }
182
+ function formatDiagnostics(entries, option = "summary") {
183
+ if (option === "off" || entries.length === 0) return;
184
+ if (!shouldTraceDiagnostics(option)) return `@vite-hub/env validated ${entries.length} declaration${entries.length === 1 ? "" : "s"}.`;
185
+ return ["@vite-hub/env", ...entries.flatMap((entry) => [
186
+ entry.key,
187
+ ` source: ${entry.source}`,
188
+ ` mode: ${entry.mode}`,
189
+ ` timing: ${entry.timing}`,
190
+ ` exposed: ${entry.exposed}`,
191
+ ` status: ${entry.status}`,
192
+ entry.type ? ` type: ${entry.type}` : void 0,
193
+ entry.masked ? " value: ********" : void 0
194
+ ].filter(Boolean))].join("\n");
195
+ }
196
+ //#endregion
197
+ //#region src/core/resolve.ts
198
+ const execFileAsync = promisify(execFile);
199
+ function validateEnvConfigShape(config, _target) {
200
+ if (!config) return;
201
+ const viteConfig = config;
202
+ for (const key of Object.keys(viteConfig)) if (key !== "define" && key !== "public" && key !== "server") {
203
+ const path = `env.${key}`;
204
+ throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Vite env config only supports env.public, env.define, and env.server.`);
205
+ }
206
+ for (const [key, declaration] of Object.entries(viteConfig.public || {})) {
207
+ assertEnvVariableDeclaration(`env.public.${key}`, declaration);
208
+ if (declaration.mode !== "build") {
209
+ const path = `env.public.${key}`;
210
+ throw invalidEnvDeclaration(path, `${path} must use mode: "build" in Vite config.`);
211
+ }
212
+ if (declaration.secret) {
213
+ const path = `env.public.${key}`;
214
+ throw invalidEnvDeclaration(path, `${path} cannot be marked secret.`);
215
+ }
216
+ }
217
+ validateBuildDeclarations(viteConfig.define, "env.define");
218
+ }
219
+ function createSourceContext(input) {
220
+ return {
221
+ build: { timestamp: () => (/* @__PURE__ */ new Date()).toISOString() },
222
+ env: input.env,
223
+ git: {
224
+ branch: () => gitOutput(input.rootDir, [
225
+ "rev-parse",
226
+ "--abbrev-ref",
227
+ "HEAD"
228
+ ]),
229
+ commit: (options) => gitOutput(input.rootDir, options?.short ? [
230
+ "rev-parse",
231
+ "--short",
232
+ "HEAD"
233
+ ] : ["rev-parse", "HEAD"]),
234
+ ref: async () => envValue(input.env, ["GIT_REF_NAME", "GITHUB_REF_NAME"]) ?? await gitOutput(input.rootDir, [
235
+ "rev-parse",
236
+ "--abbrev-ref",
237
+ "HEAD"
238
+ ]),
239
+ sha: async (options) => {
240
+ const value = envValue(input.env, ["GIT_SHA", "GITHUB_SHA"]);
241
+ if (value) return options?.short ? value.slice(0, 7) : value;
242
+ return gitOutput(input.rootDir, options?.short ? [
243
+ "rev-parse",
244
+ "--short",
245
+ "HEAD"
246
+ ] : ["rev-parse", "HEAD"]);
247
+ },
248
+ tag: async () => {
249
+ const tag = envValue(input.env, ["GIT_TAG"]);
250
+ if (tag) return tag;
251
+ if (input.env.GITHUB_REF_TYPE === "tag") return envValue(input.env, ["GITHUB_REF_NAME"]);
252
+ return await gitOutput(input.rootDir, [
253
+ "describe",
254
+ "--tags",
255
+ "--exact-match",
256
+ "HEAD"
257
+ ]).catch(() => void 0);
258
+ }
259
+ },
260
+ mode: input.mode,
261
+ packageJson: () => readPackageJson(input.rootDir),
262
+ rootDir: input.rootDir
263
+ };
264
+ }
265
+ function envValue(env, names) {
266
+ for (const name of names) {
267
+ const value = env[name];
268
+ if (value) return value;
269
+ }
270
+ }
271
+ async function resolveBuildConfig(declarations, input) {
272
+ const diagnostics = [];
273
+ const values = {};
274
+ for (const [key, declaration] of Object.entries(declarations || {})) {
275
+ const result = await resolveBuildConfigValue(declaration, `${input.section}.${key}`, input);
276
+ values[key] = result.value;
277
+ diagnostics.push(...result.diagnostics);
278
+ }
279
+ return {
280
+ diagnostics,
281
+ values
282
+ };
283
+ }
284
+ async function resolveEnvEntries(declarations, input) {
285
+ const entries = [];
286
+ const diagnostics = [];
287
+ for (const [key, declaration] of Object.entries(declarations || {})) {
288
+ const source = resolveEnvSource(declaration, `${input.section}.${key}`, input.prefix);
289
+ const resolvedSource = await resolveSourceValue(source, input.context);
290
+ const defaulted = typeof resolvedSource.value === "undefined";
291
+ const valueForSchema = defaulted ? declaration.default : resolvedSource.value;
292
+ if (typeof valueForSchema === "undefined") {
293
+ if (declaration.required) {
294
+ const path = `${input.section}.${key}`;
295
+ throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
296
+ }
297
+ entries.push({
298
+ key,
299
+ masked: declaration.secret,
300
+ source: resolvedSource.label,
301
+ type: declaration.type ?? "undefined",
302
+ value: void 0
303
+ });
304
+ diagnostics.push({
305
+ exposed: declaration.secret ? `${input.exposure}, masked` : input.exposure,
306
+ key: `${input.section}.${key}`,
307
+ masked: declaration.secret,
308
+ mode: declaration.mode,
309
+ source: resolvedSource.label,
310
+ status: "missing",
311
+ timing: input.timing,
312
+ type: declaration.type ?? "undefined"
313
+ });
314
+ continue;
315
+ }
316
+ const value = parseSchema(declaration.schema, valueForSchema, `${input.section}.${key}`);
317
+ const type = declaration.type ?? inferTypeName(value);
318
+ entries.push({
319
+ key,
320
+ masked: declaration.secret,
321
+ source: resolvedSource.label,
322
+ type,
323
+ value
324
+ });
325
+ diagnostics.push({
326
+ exposed: declaration.secret ? `${input.exposure}, masked` : input.exposure,
327
+ key: `${input.section}.${key}`,
328
+ masked: declaration.secret,
329
+ mode: declaration.mode,
330
+ source: defaulted ? "default" : resolvedSource.label,
331
+ status: defaulted ? "defaulted" : "valid",
332
+ timing: input.timing,
333
+ type
334
+ });
335
+ }
336
+ return {
337
+ diagnostics,
338
+ entries
339
+ };
340
+ }
341
+ function createRuntimeRegistry(declarations, options = {}) {
342
+ return buildRegistry(declarations, "env", options.prefix);
343
+ }
344
+ async function resolveBuildConfigValue(declaration, path, input) {
345
+ if (isEnvVariableDeclaration(declaration)) {
346
+ const source = resolveEnvSource(declaration, path, input.prefix);
347
+ const resolvedSource = await resolveSourceValue(source, input.context);
348
+ const defaulted = typeof resolvedSource.value === "undefined";
349
+ const valueForSchema = defaulted ? declaration.default : resolvedSource.value;
350
+ if (typeof valueForSchema === "undefined") {
351
+ if (declaration.required) throw missingRequiredEnv(source.kind === "custom" ? "custom" : source.label, `Missing ${path} from ${source.label}.`, path);
352
+ return {
353
+ diagnostics: [{
354
+ exposed: input.exposure,
355
+ key: path,
356
+ masked: false,
357
+ mode: declaration.mode,
358
+ source: resolvedSource.label,
359
+ status: "missing",
360
+ timing: input.timing,
361
+ type: declaration.type ?? "undefined"
362
+ }],
363
+ value: void 0
364
+ };
365
+ }
366
+ const value = parseSchema(declaration.schema, valueForSchema, path);
367
+ const type = declaration.type ?? inferTypeName(value);
368
+ return {
369
+ diagnostics: [{
370
+ exposed: input.exposure,
371
+ key: path,
372
+ masked: false,
373
+ mode: declaration.mode,
374
+ source: defaulted ? "default" : resolvedSource.label,
375
+ status: defaulted ? "defaulted" : "valid",
376
+ timing: input.timing,
377
+ type
378
+ }],
379
+ value
380
+ };
381
+ }
382
+ if (isBuildStaticValue(declaration)) return {
383
+ diagnostics: [],
384
+ value: declaration
385
+ };
386
+ if (!isPlainRecord(declaration)) throw invalidEnvDeclaration(path, `Invalid build declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
387
+ const value = {};
388
+ const diagnostics = [];
389
+ for (const [key, child] of Object.entries(declaration)) {
390
+ const result = await resolveBuildConfigValue(child, `${path}.${key}`, input);
391
+ value[key] = result.value;
392
+ diagnostics.push(...result.diagnostics);
393
+ }
394
+ return {
395
+ diagnostics,
396
+ value
397
+ };
398
+ }
399
+ function buildRegistry(declarations, path, prefix) {
400
+ if (typeof declarations === "undefined") return {};
401
+ if (!isPlainRecord(declarations)) throw invalidEnvDeclaration(path, `Invalid runtime declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
402
+ return Object.fromEntries(Object.entries(declarations).map(([key, value]) => {
403
+ const valuePath = `${path}.${key}`;
404
+ if (!isEnvVariableDeclaration(value)) {
405
+ if (isRuntimeStaticValue(value)) return [key, {
406
+ kind: "literal",
407
+ value
408
+ }];
409
+ if (!isPlainRecord(value)) throw invalidEnvDeclaration(valuePath, `Invalid runtime declaration at ${valuePath}. Use env(), a serializable static value, or a nested object.`);
410
+ return [key, buildRegistry(value, valuePath, prefix)];
411
+ }
412
+ if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
413
+ const source = resolveEnvSource(value, valuePath, prefix);
414
+ if (source.kind !== "env") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() in v1.`);
415
+ if (!isDefaultStringEnvVariable(value)) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema, but runtime schemas cannot be serialized in v1.`);
416
+ 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.`);
417
+ return [key, {
418
+ default: typeof value.default === "undefined" ? void 0 : parseSchema(defaultStringSchema, value.default, valuePath),
419
+ required: value.required,
420
+ schema: { kind: "string" },
421
+ secret: value.secret,
422
+ source,
423
+ type: value.type
424
+ }];
425
+ }));
426
+ }
427
+ function resolveEnvSource(declaration, path, prefix = "") {
428
+ return declaration.source ?? inferEnvSource(path, prefix);
429
+ }
430
+ function inferTypeName(value) {
431
+ if (Array.isArray(value)) return "unknown[]";
432
+ switch (typeof value) {
433
+ case "boolean":
434
+ case "number":
435
+ case "string": return typeof value;
436
+ case "object": return value === null ? "null" : "Record<string, unknown>";
437
+ case "undefined": return "undefined";
438
+ default: return "unknown";
439
+ }
440
+ }
441
+ async function resolveSourceValue(source, context) {
442
+ switch (source.kind) {
443
+ case "custom": return {
444
+ label: source.label,
445
+ value: await source.resolver(context)
446
+ };
447
+ case "env":
448
+ for (const name of source.names || [source.name]) {
449
+ const value = context.env[name];
450
+ if (typeof value !== "undefined") return {
451
+ label: `env:${name}`,
452
+ value
453
+ };
454
+ }
455
+ return {
456
+ label: source.label,
457
+ value: void 0
458
+ };
459
+ case "git-branch": return {
460
+ label: source.label,
461
+ value: await resolveBuiltInSource(source.label, () => context.git.branch())
462
+ };
463
+ case "git-commit": return {
464
+ label: source.label,
465
+ value: await resolveBuiltInSource(source.label, () => context.git.commit({ short: source.short }))
466
+ };
467
+ case "git-ref": return {
468
+ label: source.label,
469
+ value: await resolveBuiltInSource(source.label, () => context.git.ref())
470
+ };
471
+ case "git-sha": return {
472
+ label: source.label,
473
+ value: await resolveBuiltInSource(source.label, () => context.git.sha({ short: source.short }))
474
+ };
475
+ case "git-tag": return {
476
+ label: source.label,
477
+ value: await resolveBuiltInSource(source.label, () => context.git.tag())
478
+ };
479
+ case "build-timestamp": return {
480
+ label: source.label,
481
+ value: context.build.timestamp()
482
+ };
483
+ case "package-json": return {
484
+ label: source.label,
485
+ value: readPath(await resolveBuiltInSource(source.label, () => context.packageJson()), source.path)
486
+ };
487
+ }
488
+ }
489
+ async function resolveBuiltInSource(source, resolveSource) {
490
+ try {
491
+ return await resolveSource();
492
+ } catch (cause) {
493
+ if (isAbortError(cause) || isViteHubError(cause)) throw cause;
494
+ throw envSourceFailed(source, cause);
495
+ }
496
+ }
497
+ function validateBuildDeclarations(declarations, path) {
498
+ if (typeof declarations === "undefined") return;
499
+ if (!isPlainRecord(declarations)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Use env(), a serializable static value, or a nested object.`);
500
+ for (const [key, declaration] of Object.entries(declarations)) {
501
+ const valuePath = `${path}.${key}`;
502
+ if (isEnvVariableDeclaration(declaration)) {
503
+ if (declaration.mode !== "build") throw invalidEnvDeclaration(valuePath, `${valuePath} must use mode: "build".`);
504
+ if (declaration.secret) throw invalidEnvDeclaration(valuePath, `${valuePath} cannot be marked secret because Vite define values are bundled.`);
505
+ continue;
506
+ }
507
+ if (isBuildStaticValue(declaration)) continue;
508
+ validateBuildDeclarations(declaration, valuePath);
509
+ }
510
+ }
511
+ function assertEnvVariableDeclaration(path, declaration) {
512
+ if (!isEnvVariableDeclaration(declaration)) throw invalidEnvDeclaration(path, `Invalid declaration at ${path}. Use env().`);
513
+ }
514
+ function inferEnvSource(path, prefix) {
515
+ const name = `${prefix}${pathToEnvName(path)}`;
516
+ return {
517
+ kind: "env",
518
+ label: `env:${name}`,
519
+ name,
520
+ serializable: true
521
+ };
522
+ }
523
+ function pathToEnvName(path) {
524
+ return path.split(".").slice(1).flatMap((segment) => segmentToEnvParts(segment)).filter(Boolean).join("_");
525
+ }
526
+ function segmentToEnvParts(segment) {
527
+ 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);
528
+ }
529
+ function isEnvVariableDeclaration(value) {
530
+ return isPlainRecord(value) && value.kind === "env-variable";
531
+ }
532
+ function isPlainRecord(value) {
533
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
534
+ const prototype = Object.getPrototypeOf(value);
535
+ return prototype === null || prototype === Object.prototype;
536
+ }
537
+ function isRuntimeStaticValue(value) {
538
+ return isBuildStaticValue(value);
539
+ }
540
+ function isBuildStaticValue(value) {
541
+ if (value === null) return true;
542
+ switch (typeof value) {
543
+ case "boolean":
544
+ case "string": return true;
545
+ case "number": return Number.isFinite(value);
546
+ case "object":
547
+ if (!Array.isArray(value)) return false;
548
+ for (let index = 0; index < value.length; index += 1) if (!(index in value) || !isBuildStaticValue(value[index])) return false;
549
+ return true;
550
+ default: return false;
551
+ }
552
+ }
553
+ async function readPackageJson(rootDir) {
554
+ return JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
555
+ }
556
+ async function gitOutput(rootDir, args) {
557
+ const { stdout } = await execFileAsync("git", args, { cwd: rootDir });
558
+ return stdout.trim();
559
+ }
560
+ function readPath(value, path) {
561
+ return path.split(".").reduce((current, segment) => {
562
+ if (typeof current !== "object" || current === null) return;
563
+ return current[segment];
564
+ }, value);
565
+ }
566
+ //#endregion
567
+ //#region src/vite.ts
568
+ const ENV_VITE_PLUGIN_NAME = "@vite-hub/env/vite";
569
+ const ENV_PUBLIC_ID = VITEHUB_ENV_PUBLIC_ID;
570
+ const ENV_SERVER_ID = VITEHUB_ENV_SERVER_ID;
571
+ const RESOLVED_PUBLIC_ID = `\0${ENV_PUBLIC_ID}`;
572
+ const RESOLVED_SERVER_ID = `\0${ENV_SERVER_ID}`;
573
+ const defaultRuntimeImports = {
574
+ secret: "@vite-hub/env/secret",
575
+ server: "@vite-hub/env/server"
576
+ };
577
+ function createEnvImportAliases(options = {}) {
578
+ return createViteHubEnvImportAliases(resolveEnvProjectRoot(options));
579
+ }
580
+ function createEnvTypeScriptPaths(options = {}) {
581
+ const root = resolveEnvProjectRoot(options);
582
+ const toTypeScriptPath = (path) => stripModuleExtension(options.relativeTo ? relative(resolve(options.relativeTo), path) : path);
583
+ return {
584
+ [ENV_PUBLIC_ID]: [toTypeScriptPath(viteHubEnvPublicModulePath(root))],
585
+ [ENV_SERVER_ID]: [toTypeScriptPath(viteHubEnvServerModulePath(root))]
586
+ };
587
+ }
588
+ function hubEnv(options = {}) {
589
+ let buildPublicConfig = {};
590
+ let serverRegistry = {};
591
+ let diagnosticsText;
592
+ const getPublicEnv = () => buildPublicConfig;
593
+ const getServerEnvRegistry = () => serverRegistry;
594
+ const runtimeImports = resolveRuntimeImports(options.runtimeImports);
595
+ return {
596
+ name: ENV_VITE_PLUGIN_NAME,
597
+ api: {
598
+ getPublicEnv,
599
+ getServerEnvRegistry
600
+ },
601
+ async config(config, env) {
602
+ const envConfig = config.env;
603
+ validateEnvConfigShape(envConfig, "vite");
604
+ if (!envConfig) return;
605
+ const root = resolveViteHubProjectRoot(resolve(config.root || process.cwd()), { projectRoot: options.projectRoot });
606
+ const context = createSourceContext({
607
+ env: {
608
+ ...loadEnv(env.mode, root, ""),
609
+ ...process.env
610
+ },
611
+ mode: "build",
612
+ rootDir: root
613
+ });
614
+ const publicResult = await resolveEnvEntries(envConfig.public, {
615
+ context,
616
+ exposure: "build public",
617
+ prefix: options.prefix,
618
+ section: "env.public",
619
+ timing: "Vite config/dev/build"
620
+ });
621
+ const defineResult = await resolveBuildConfig(envConfig.define, {
622
+ context,
623
+ exposure: "compile-time replacement",
624
+ prefix: options.prefix,
625
+ section: "env.define",
626
+ timing: "Vite transform/build"
627
+ });
628
+ buildPublicConfig = Object.fromEntries(publicResult.entries.map((entry) => [entry.key, entry.value]));
629
+ serverRegistry = createRuntimeRegistry(envConfig.server, { prefix: options.prefix });
630
+ diagnosticsText = formatDiagnostics([...publicResult.diagnostics, ...defineResult.diagnostics], options.diagnostics);
631
+ return { define: {
632
+ ...Object.fromEntries(Object.entries(defineResult.values).map(([key, value]) => [key, JSON.stringify(value)])),
633
+ ...config.define
634
+ } };
635
+ },
636
+ async configResolved(config) {
637
+ if (diagnosticsText) config.logger.info(diagnosticsText);
638
+ const projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: options.projectRoot });
639
+ await refreshEnvGeneratedFiles(projectRoot, await resolvePackageRoot(config.root, projectRoot), buildPublicConfig, serverRegistry, runtimeImports);
640
+ },
641
+ load(id) {
642
+ if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(buildPublicConfig);
643
+ if (id === RESOLVED_SERVER_ID) return createServerEnvModule(serverRegistry, runtimeImports);
644
+ },
645
+ resolveId: {
646
+ order: "pre",
647
+ handler(id) {
648
+ if (id === ENV_PUBLIC_ID) return RESOLVED_PUBLIC_ID;
649
+ if (id === ENV_SERVER_ID) return RESOLVED_SERVER_ID;
650
+ }
651
+ },
652
+ transform(code) {
653
+ if (!code.includes("/* @vitehub-env */") || !code.includes(ENV_SERVER_ID)) return;
654
+ return code.replace(/\/\* @vite-ignore \*\/\s*\/\* @vitehub-env \*\/\s*[\w$]+/g, JSON.stringify(ENV_SERVER_ID));
655
+ }
656
+ };
657
+ }
658
+ function resolveEnvProjectRoot(options) {
659
+ return resolveViteHubProjectRoot(process.cwd(), { projectRoot: options.projectRoot });
660
+ }
661
+ function stripModuleExtension(path) {
662
+ return path.replace(/\.mjs$/, "");
663
+ }
664
+ function resolveRuntimeImports(imports) {
665
+ return {
666
+ secret: imports?.secret ?? defaultRuntimeImports.secret,
667
+ server: imports?.server ?? defaultRuntimeImports.server
668
+ };
669
+ }
670
+ function legacyEnvAmbientTypesPaths(root) {
671
+ return [resolve(root, ".vitehub", "env", "vite.d.ts")];
672
+ }
673
+ async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
674
+ await Promise.all([
675
+ ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, serverRegistry, runtimeImports), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
676
+ writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicConfig, serverRegistry, runtimeImports)),
677
+ writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
678
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicConfig)),
679
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports)),
680
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports)),
681
+ ...legacyEnvAmbientTypesPaths(root).map((path) => rm(path, { force: true }))
682
+ ]);
683
+ }
684
+ function createAmbientTypesReference(packageRoot, projectRoot) {
685
+ const target = relative(dirname(viteHubEnvAmbientTypesPath(packageRoot)), viteHubEnvAmbientTypesPath(projectRoot)).replace(/\\/g, "/");
686
+ const specifier = target.startsWith(".") ? target : `./${target}`;
687
+ return `/// <reference path=${JSON.stringify(specifier)} />\n`;
688
+ }
689
+ function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports) {
690
+ return [
691
+ writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
692
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicConfig)),
693
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports)),
694
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
695
+ ];
696
+ }
697
+ async function resolvePackageRoot(viteRoot, projectRoot) {
698
+ const stop = resolve(projectRoot);
699
+ let current = resolve(viteRoot);
700
+ while (true) {
701
+ if (await hasPackageManifest(current)) return current;
702
+ if (current === stop) return void 0;
703
+ const parent = dirname(current);
704
+ if (parent === current) return void 0;
705
+ current = parent;
706
+ }
707
+ }
708
+ async function hasPackageManifest(root) {
709
+ try {
710
+ return (await stat(resolve(root, "package.json"))).isFile();
711
+ } catch (error) {
712
+ if (error.code === "ENOENT") return false;
713
+ throw error;
714
+ }
715
+ }
716
+ function createPublicEnvModule(publicConfig) {
717
+ return [
718
+ `const publicEnv = ${JSON.stringify(publicConfig, null, 2)};`,
719
+ "export function usePublicEnv() { return publicEnv; }",
720
+ "export { publicEnv };",
721
+ ""
722
+ ].join("\n");
723
+ }
724
+ function createPublicEnvModuleTypes(publicConfig) {
725
+ return [
726
+ "export interface PublicEnv {",
727
+ ...createPublicTypeFields(publicConfig, 2),
728
+ "}",
729
+ "export const publicEnv: PublicEnv",
730
+ "export function usePublicEnv(): PublicEnv",
731
+ ""
732
+ ].join("\n");
733
+ }
734
+ function createServerEnvModule(serverRegistry, runtimeImports) {
735
+ return [
736
+ `import { resolveServerEnv } from ${JSON.stringify(runtimeImports.server)};`,
737
+ `const registry = ${JSON.stringify(serverRegistry, null, 2)};`,
738
+ "export function useServerEnv(event) { return resolveServerEnv(registry, event); }",
739
+ "export async function runWithServerEnv(event, callback) { return await callback(useServerEnv(event)); }",
740
+ ""
741
+ ].join("\n");
742
+ }
743
+ function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
744
+ return [
745
+ `import type { SecretEnv } from ${JSON.stringify(runtimeImports.secret)}`,
746
+ "",
747
+ "export interface ServerEnv {",
748
+ ...createServerTypeFields(serverRegistry, 2),
749
+ "}",
750
+ "export function useServerEnv(event?: unknown): ServerEnv",
751
+ "export function runWithServerEnv<T>(event: unknown, callback: (env: ServerEnv) => T | Promise<T>): Promise<T>",
752
+ ""
753
+ ].join("\n");
754
+ }
755
+ function createViteTypes(publicConfig, serverRegistry, runtimeImports) {
756
+ return [
757
+ "declare module \"#vitehub/env/public\" {",
758
+ " export interface PublicEnv {",
759
+ ...createPublicTypeFields(publicConfig, 4),
760
+ " }",
761
+ " export const publicEnv: PublicEnv",
762
+ " export function usePublicEnv(): PublicEnv",
763
+ "}",
764
+ "declare module \"#vitehub/env/server\" {",
765
+ " export interface ServerEnv {",
766
+ ...createServerTypeFields(serverRegistry, 4, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
767
+ " }",
768
+ " export function useServerEnv(event?: unknown): ServerEnv",
769
+ " export function runWithServerEnv<T>(event: unknown, callback: (env: ServerEnv) => T | Promise<T>): Promise<T>",
770
+ "}",
771
+ ""
772
+ ].join("\n");
773
+ }
774
+ function createPublicTypeFields(publicConfig, indent) {
775
+ const prefix = " ".repeat(indent);
776
+ return Object.entries(publicConfig).map(([key, value]) => `${prefix}${JSON.stringify(key)}: ${typeof value}`);
777
+ }
778
+ function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
779
+ const prefix = " ".repeat(indent);
780
+ return Object.entries(registry).map(([key, value]) => {
781
+ const optional = isOptionalServerValue(value) ? "?" : "";
782
+ return `${prefix}${JSON.stringify(key)}${optional}: ${serverTypeFor(value, indent, secretType)}`;
783
+ });
784
+ }
785
+ function serverTypeFor(value, indent, secretType) {
786
+ if (isLiteralEntry(value)) return literalType(value.value);
787
+ if (isEnvEntry(value)) return value.secret ? `${secretType}<string>` : "string";
788
+ const fields = createServerTypeFields(value, indent + 2, secretType);
789
+ if (!fields.length) return "Record<string, never>";
790
+ const prefix = " ".repeat(indent);
791
+ return `{\n${fields.join("\n")}\n${prefix}}`;
792
+ }
793
+ function isOptionalServerValue(value) {
794
+ return isEnvEntry(value) && !value.required && typeof value.default === "undefined";
795
+ }
796
+ function literalType(value) {
797
+ if (value === null) return "null";
798
+ if (Array.isArray(value)) return `readonly [${value.map((item) => literalType(item)).join(", ")}]`;
799
+ switch (typeof value) {
800
+ case "boolean":
801
+ case "number":
802
+ case "string": return JSON.stringify(value);
803
+ default: return "unknown";
804
+ }
805
+ }
806
+ function isLiteralEntry(value) {
807
+ if (!isRecord(value)) return false;
808
+ return value.kind === "literal";
809
+ }
810
+ function isEnvEntry(value) {
811
+ if (!isRecord(value)) return false;
812
+ const record = value;
813
+ return isRecord(record.source) && typeof record.required === "boolean" && typeof record.secret === "boolean";
814
+ }
815
+ function isRecord(value) {
816
+ return typeof value === "object" && value !== null && !Array.isArray(value);
817
+ }
818
+ //#endregion
819
+ export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, env, hubEnv };