@vite-hub/env 0.0.2 → 0.0.4
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/LICENSE +201 -0
- package/README.md +119 -24
- package/dist/{declarations-Cy5XamUA.js → declarations-CoMmvRqH.js} +16 -1
- package/dist/{declarations-BIBfEwer.d.ts → declarations-U6P3rvxC.d.ts} +2 -1
- package/dist/{errors-RUmAFDJn.js → errors-C4Xcs6Fi.js} +13 -4
- package/dist/index.d.ts +11 -6
- package/dist/index.js +4 -3
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/provider.d.ts +6 -0
- package/dist/provider.js +7 -0
- package/dist/secret-C2191nAa.d.ts +11 -0
- package/dist/secret.d.ts +1 -10
- package/dist/server-C16sFc1E.js +303 -0
- package/dist/server.d.ts +5 -3
- package/dist/server.js +2 -2
- package/dist/{types-FcnPKias.d.ts → types-CsB6DTGE.d.ts} +40 -3
- package/dist/virtual-module.d.ts +30 -0
- package/dist/virtual.d.ts +2 -15
- package/dist/vite.d.ts +14 -4
- package/dist/vite.js +296 -96
- package/package.json +6 -2
- package/dist/server-B2Dp8Nc0.js +0 -59
package/dist/vite.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { n as env, r as isDefaultStringEnvVariable, t as defaultStringSchema } from "./declarations-
|
|
1
|
+
import { n as env, r as isDefaultStringEnvVariable, t as defaultStringSchema } from "./declarations-CoMmvRqH.js";
|
|
2
2
|
import { parseSchema } from "./schema.js";
|
|
3
|
-
import { a as
|
|
3
|
+
import { a as isAbortError, n as envSourceFailed, o as missingRequiredEnv, r as invalidEnvDeclaration } from "./errors-C4Xcs6Fi.js";
|
|
4
4
|
import { isViteHubError } from "@vite-hub/runtime";
|
|
5
|
-
import { mkdir, readFile,
|
|
6
|
-
import { basename, dirname, relative, resolve } from "node:path";
|
|
5
|
+
import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
6
|
+
import { basename, dirname, isAbsolute, parse, relative, resolve, win32 } from "node:path";
|
|
7
7
|
import { statSync } from "node:fs";
|
|
8
|
+
import { tmpdir } from "node:os";
|
|
8
9
|
import { loadEnv } from "vite";
|
|
9
10
|
import { execFile } from "node:child_process";
|
|
10
11
|
import { promisify } from "node:util";
|
|
@@ -27,10 +28,10 @@ const resolve$1 = function(...arguments_) {
|
|
|
27
28
|
const path = index >= 0 ? arguments_[index] : cwd();
|
|
28
29
|
if (!path || path.length === 0) continue;
|
|
29
30
|
resolvedPath = `${path}/${resolvedPath}`;
|
|
30
|
-
resolvedAbsolute = isAbsolute(path);
|
|
31
|
+
resolvedAbsolute = isAbsolute$1(path);
|
|
31
32
|
}
|
|
32
33
|
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
|
|
33
|
-
if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
|
|
34
|
+
if (resolvedAbsolute && !isAbsolute$1(resolvedPath)) return `/${resolvedPath}`;
|
|
34
35
|
return resolvedPath.length > 0 ? resolvedPath : ".";
|
|
35
36
|
};
|
|
36
37
|
function normalizeString(path, allowAboveRoot) {
|
|
@@ -83,7 +84,7 @@ function normalizeString(path, allowAboveRoot) {
|
|
|
83
84
|
}
|
|
84
85
|
return res;
|
|
85
86
|
}
|
|
86
|
-
const isAbsolute = function(p) {
|
|
87
|
+
const isAbsolute$1 = function(p) {
|
|
87
88
|
return _IS_ABSOLUTE_RE.test(p);
|
|
88
89
|
};
|
|
89
90
|
//#endregion
|
|
@@ -97,30 +98,27 @@ async function writeFileIfChanged(file, contents) {
|
|
|
97
98
|
//#region ../internal/src/build/vite.ts
|
|
98
99
|
const projectRootDirectoryMarkers = [
|
|
99
100
|
["server", "agents"],
|
|
101
|
+
["server", "channels"],
|
|
102
|
+
["server", "browsers"],
|
|
103
|
+
["server", "emails"],
|
|
100
104
|
["server", "schedules"],
|
|
101
|
-
["server", "templates"],
|
|
102
105
|
["server", "workspaces"]
|
|
103
106
|
];
|
|
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
107
|
const projectRootFileMarkers = [["package.json"]];
|
|
113
108
|
const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
|
|
114
109
|
const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
|
|
115
110
|
function resolveViteHubProjectRoot(root, options = {}) {
|
|
116
111
|
const resolvedRoot = resolve(root);
|
|
112
|
+
const temporaryRoot = resolve(tmpdir());
|
|
113
|
+
const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
|
|
117
114
|
if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
|
|
118
115
|
if (basename(resolvedRoot) === "app") {
|
|
119
116
|
const parent = dirname(resolvedRoot);
|
|
120
|
-
if (
|
|
117
|
+
if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
|
|
121
118
|
}
|
|
122
119
|
let current = resolvedRoot;
|
|
123
120
|
while (true) {
|
|
121
|
+
if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
|
|
124
122
|
if (hasProjectRootMarker(current)) return current;
|
|
125
123
|
const parent = dirname(current);
|
|
126
124
|
if (parent === current) return resolvedRoot;
|
|
@@ -137,7 +135,6 @@ function hasProjectRootDirectoryMarker(root) {
|
|
|
137
135
|
}
|
|
138
136
|
function hasProjectRootMarker(root) {
|
|
139
137
|
if (hasProjectRootDirectoryMarker(root)) return true;
|
|
140
|
-
if (hasProjectRootDefinitionFileMarker(root)) return true;
|
|
141
138
|
for (const marker of projectRootFileMarkers) try {
|
|
142
139
|
if (statSync(resolve(root, ...marker)).isFile()) return true;
|
|
143
140
|
} catch (error) {
|
|
@@ -145,14 +142,6 @@ function hasProjectRootMarker(root) {
|
|
|
145
142
|
}
|
|
146
143
|
return false;
|
|
147
144
|
}
|
|
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
145
|
function viteHubEnvAmbientTypesPath(root) {
|
|
157
146
|
return resolve(root, ".vitehub", "types", "env.d.ts");
|
|
158
147
|
}
|
|
@@ -339,7 +328,7 @@ async function resolveEnvEntries(declarations, input) {
|
|
|
339
328
|
};
|
|
340
329
|
}
|
|
341
330
|
function createRuntimeRegistry(declarations, options = {}) {
|
|
342
|
-
return buildRegistry(declarations, "env", options.prefix);
|
|
331
|
+
return buildRegistry(declarations, options.path ?? "env", options.prefix);
|
|
343
332
|
}
|
|
344
333
|
async function resolveBuildConfigValue(declaration, path, input) {
|
|
345
334
|
if (isEnvVariableDeclaration(declaration)) {
|
|
@@ -411,7 +400,7 @@ function buildRegistry(declarations, path, prefix) {
|
|
|
411
400
|
}
|
|
412
401
|
if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
|
|
413
402
|
const source = resolveEnvSource(value, valuePath, prefix);
|
|
414
|
-
if (source.kind !== "env") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source()
|
|
403
|
+
if (source.kind !== "env" && source.kind !== "provider") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() or env.provider().`);
|
|
415
404
|
if (!isDefaultStringEnvVariable(value)) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema, but runtime schemas cannot be serialized in v1.`);
|
|
416
405
|
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
406
|
return [key, {
|
|
@@ -484,6 +473,7 @@ async function resolveSourceValue(source, context) {
|
|
|
484
473
|
label: source.label,
|
|
485
474
|
value: readPath(await resolveBuiltInSource(source.label, () => context.packageJson()), source.path)
|
|
486
475
|
};
|
|
476
|
+
case "provider": throw invalidEnvDeclaration("env", "env.provider() is available only to Server Env at runtime.");
|
|
487
477
|
}
|
|
488
478
|
}
|
|
489
479
|
async function resolveBuiltInSource(source, resolveSource) {
|
|
@@ -551,7 +541,9 @@ function isBuildStaticValue(value) {
|
|
|
551
541
|
}
|
|
552
542
|
}
|
|
553
543
|
async function readPackageJson(rootDir) {
|
|
554
|
-
|
|
544
|
+
const value = JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
|
|
545
|
+
if (!isPlainRecord(value)) throw new TypeError("package.json must contain an object.");
|
|
546
|
+
return value;
|
|
555
547
|
}
|
|
556
548
|
async function gitOutput(rootDir, args) {
|
|
557
549
|
const { stdout } = await execFileAsync("git", args, { cwd: rootDir });
|
|
@@ -574,6 +566,7 @@ const defaultRuntimeImports = {
|
|
|
574
566
|
secret: "@vite-hub/env/secret",
|
|
575
567
|
server: "@vite-hub/env/server"
|
|
576
568
|
};
|
|
569
|
+
let envVitePluginSequence = 0;
|
|
577
570
|
function createEnvImportAliases(options = {}) {
|
|
578
571
|
return createViteHubEnvImportAliases(resolveEnvProjectRoot(options));
|
|
579
572
|
}
|
|
@@ -588,59 +581,141 @@ function createEnvTypeScriptPaths(options = {}) {
|
|
|
588
581
|
function hubEnv(options = {}) {
|
|
589
582
|
let buildPublicConfig = {};
|
|
590
583
|
let serverRegistry = {};
|
|
591
|
-
|
|
584
|
+
const resolvedStates = /* @__PURE__ */ new Map();
|
|
585
|
+
const generatedStateWrites = /* @__PURE__ */ new Map();
|
|
586
|
+
const resolvedConfigStates = /* @__PURE__ */ new WeakMap();
|
|
587
|
+
const pendingConfigStates = /* @__PURE__ */ new Map();
|
|
588
|
+
const configStateKey = `__vitehubEnvState${++envVitePluginSequence}`;
|
|
589
|
+
const environmentStateKey = `${configStateKey}Resolved`;
|
|
590
|
+
let configStateSequence = 0;
|
|
591
|
+
const serverRegistryHandlers = /* @__PURE__ */ new Set();
|
|
592
592
|
const getPublicEnv = () => buildPublicConfig;
|
|
593
593
|
const getServerEnvRegistry = () => serverRegistry;
|
|
594
|
+
const createServerEnvRegistry = (declarations) => createRuntimeRegistry(declarations, { prefix: options.prefix });
|
|
595
|
+
const resolveProjectRoot = (viteRoot) => resolveViteHubProjectRoot(resolve(viteRoot), { projectRoot: options.projectRoot });
|
|
594
596
|
const runtimeImports = resolveRuntimeImports(options.runtimeImports);
|
|
597
|
+
const prepareTypes = async (config, viteRoot) => {
|
|
598
|
+
const root = resolveProjectRoot(viteRoot);
|
|
599
|
+
const packageRoot = await resolvePackageRoot(viteRoot, root);
|
|
600
|
+
const registry = createRuntimeRegistry(config?.server, { prefix: options.prefix });
|
|
601
|
+
assertConfiguredProviders(registry, resolveProviderModules(options.providers, root));
|
|
602
|
+
await prepareEnvGeneratedTypes(root, packageRoot, config?.public, registry, runtimeImports);
|
|
603
|
+
};
|
|
604
|
+
const resolveState = async (config, mode) => {
|
|
605
|
+
const envConfig = config.env;
|
|
606
|
+
validateEnvConfigShape(envConfig, "vite");
|
|
607
|
+
const projectRoot = resolveProjectRoot(config.root || process.cwd());
|
|
608
|
+
const providerModules = resolveProviderModules(options.providers, projectRoot);
|
|
609
|
+
if (!envConfig) return {
|
|
610
|
+
defineValues: {},
|
|
611
|
+
projectRoot,
|
|
612
|
+
state: {
|
|
613
|
+
diagnosticsText: void 0,
|
|
614
|
+
projectRoot,
|
|
615
|
+
providerModules,
|
|
616
|
+
publicConfig: {},
|
|
617
|
+
serverRegistry: {}
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
const context = createSourceContext({
|
|
621
|
+
env: {
|
|
622
|
+
...loadEnv(mode, projectRoot, ""),
|
|
623
|
+
...process.env
|
|
624
|
+
},
|
|
625
|
+
mode: "build",
|
|
626
|
+
rootDir: projectRoot
|
|
627
|
+
});
|
|
628
|
+
const publicResult = await resolveEnvEntries(envConfig.public, {
|
|
629
|
+
context,
|
|
630
|
+
exposure: "build public",
|
|
631
|
+
prefix: options.prefix,
|
|
632
|
+
section: "env.public",
|
|
633
|
+
timing: "Vite config/dev/build"
|
|
634
|
+
});
|
|
635
|
+
const defineResult = await resolveBuildConfig(envConfig.define, {
|
|
636
|
+
context,
|
|
637
|
+
exposure: "compile-time replacement",
|
|
638
|
+
prefix: options.prefix,
|
|
639
|
+
section: "env.define",
|
|
640
|
+
timing: "Vite transform/build"
|
|
641
|
+
});
|
|
642
|
+
const publicConfig = Object.fromEntries(publicResult.entries.map((entry) => [entry.key, entry.value]));
|
|
643
|
+
const registry = createServerEnvRegistry(envConfig.server);
|
|
644
|
+
assertConfiguredProviders(registry, providerModules);
|
|
645
|
+
return {
|
|
646
|
+
defineValues: defineResult.values,
|
|
647
|
+
projectRoot,
|
|
648
|
+
state: {
|
|
649
|
+
diagnosticsText: formatDiagnostics([...publicResult.diagnostics, ...defineResult.diagnostics], options.diagnostics),
|
|
650
|
+
projectRoot,
|
|
651
|
+
providerModules,
|
|
652
|
+
publicConfig,
|
|
653
|
+
serverRegistry: registry
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
};
|
|
595
657
|
return {
|
|
596
658
|
name: ENV_VITE_PLUGIN_NAME,
|
|
597
659
|
api: {
|
|
660
|
+
createServerEnvRegistry,
|
|
598
661
|
getPublicEnv,
|
|
599
|
-
getServerEnvRegistry
|
|
662
|
+
getServerEnvRegistry,
|
|
663
|
+
onServerEnvRegistry: (handler) => serverRegistryHandlers.add(handler),
|
|
664
|
+
prepareTypes,
|
|
665
|
+
resolveProjectRoot
|
|
600
666
|
},
|
|
601
667
|
async config(config, env) {
|
|
602
668
|
const envConfig = config.env;
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
const
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
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
|
-
} };
|
|
669
|
+
const { defineValues, state } = await resolveState(config, env.mode);
|
|
670
|
+
buildPublicConfig = state.publicConfig;
|
|
671
|
+
serverRegistry = state.serverRegistry;
|
|
672
|
+
const configStateId = String(++configStateSequence);
|
|
673
|
+
pendingConfigStates.set(configStateId, state);
|
|
674
|
+
for (const handler of serverRegistryHandlers) handler(serverRegistry, config);
|
|
675
|
+
if (!envConfig) return { [configStateKey]: configStateId };
|
|
676
|
+
return {
|
|
677
|
+
[configStateKey]: configStateId,
|
|
678
|
+
define: {
|
|
679
|
+
...Object.fromEntries(Object.entries(defineValues).map(([key, value]) => [key, JSON.stringify(value)])),
|
|
680
|
+
...config.define
|
|
681
|
+
}
|
|
682
|
+
};
|
|
635
683
|
},
|
|
636
684
|
async configResolved(config) {
|
|
637
|
-
|
|
638
|
-
const
|
|
639
|
-
|
|
685
|
+
const projectRoot = resolveProjectRoot(config.root);
|
|
686
|
+
const configStateId = String(Object.getOwnPropertyDescriptor(config, configStateKey)?.value ?? "");
|
|
687
|
+
const state = pendingConfigStates.get(configStateId) ?? resolvedStates.get(projectRoot);
|
|
688
|
+
if (!state) throw new Error(`Missing resolved Env state for ${projectRoot}`);
|
|
689
|
+
pendingConfigStates.delete(configStateId);
|
|
690
|
+
resolvedConfigStates.set(config, state);
|
|
691
|
+
for (const environmentConfig of Object.values(config.environments || {})) {
|
|
692
|
+
resolvedConfigStates.set(environmentConfig, state);
|
|
693
|
+
Reflect.defineProperty(environmentConfig, environmentStateKey, {
|
|
694
|
+
configurable: true,
|
|
695
|
+
value: state
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
Reflect.deleteProperty(config, configStateKey);
|
|
699
|
+
resolvedStates.set(projectRoot, state);
|
|
700
|
+
if (state.diagnosticsText) config.logger.info(state.diagnosticsText);
|
|
701
|
+
const generatedStateWrite = (generatedStateWrites.get(projectRoot) ?? Promise.resolve()).catch(() => void 0).then(async () => {
|
|
702
|
+
await refreshEnvGeneratedFiles(projectRoot, await resolvePackageRoot(config.root, projectRoot), state.publicConfig, state.serverRegistry, runtimeImports, state.providerModules);
|
|
703
|
+
});
|
|
704
|
+
generatedStateWrites.set(projectRoot, generatedStateWrite);
|
|
705
|
+
try {
|
|
706
|
+
await generatedStateWrite;
|
|
707
|
+
} finally {
|
|
708
|
+
if (generatedStateWrites.get(projectRoot) === generatedStateWrite) generatedStateWrites.delete(projectRoot);
|
|
709
|
+
}
|
|
640
710
|
},
|
|
641
711
|
load(id) {
|
|
642
|
-
|
|
643
|
-
|
|
712
|
+
const viteConfig = this?.environment?.config;
|
|
713
|
+
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);
|
|
714
|
+
const publicConfig = state?.publicConfig ?? buildPublicConfig;
|
|
715
|
+
const registry = state?.serverRegistry ?? serverRegistry;
|
|
716
|
+
const providerModules = state?.providerModules ?? {};
|
|
717
|
+
if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(publicConfig);
|
|
718
|
+
if (id === RESOLVED_SERVER_ID) return createServerEnvModule(registry, runtimeImports, providerModules);
|
|
644
719
|
},
|
|
645
720
|
resolveId: {
|
|
646
721
|
order: "pre",
|
|
@@ -655,6 +730,19 @@ function hubEnv(options = {}) {
|
|
|
655
730
|
}
|
|
656
731
|
};
|
|
657
732
|
}
|
|
733
|
+
async function prepareEnvGeneratedTypes(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
|
|
734
|
+
const publicTypes = createPreparedPublicTypeEntries(publicConfig);
|
|
735
|
+
await Promise.all([
|
|
736
|
+
...packageRoot && packageRoot !== root ? [
|
|
737
|
+
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(packageRoot), createPublicEnvModuleTypes(publicTypes)),
|
|
738
|
+
writeFileIfChanged(viteHubEnvServerModuleTypesPath(packageRoot), createServerEnvModuleTypes(serverRegistry, runtimeImports)),
|
|
739
|
+
writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))
|
|
740
|
+
] : [],
|
|
741
|
+
writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
|
|
742
|
+
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
|
|
743
|
+
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
|
|
744
|
+
]);
|
|
745
|
+
}
|
|
658
746
|
function resolveEnvProjectRoot(options) {
|
|
659
747
|
return resolveViteHubProjectRoot(process.cwd(), { projectRoot: options.projectRoot });
|
|
660
748
|
}
|
|
@@ -667,18 +755,38 @@ function resolveRuntimeImports(imports) {
|
|
|
667
755
|
server: imports?.server ?? defaultRuntimeImports.server
|
|
668
756
|
};
|
|
669
757
|
}
|
|
670
|
-
function
|
|
671
|
-
|
|
758
|
+
function resolveProviderModules(providers, root) {
|
|
759
|
+
const output = {};
|
|
760
|
+
for (const [name, specifier] of Object.entries(providers || {})) {
|
|
761
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(name)) throw new TypeError("[vitehub] Env provider names must start with a letter and contain only letters, numbers, underscores, or hyphens.");
|
|
762
|
+
if (typeof specifier !== "string" || !specifier.trim()) throw new TypeError(`[vitehub] Env provider ${JSON.stringify(name)} requires a non-empty module specifier.`);
|
|
763
|
+
const normalized = specifier.trim();
|
|
764
|
+
if (/^(?:\\\\[?.]\\|\/\/[?.]\/)/.test(normalized)) throw new TypeError(`[vitehub] Env provider ${JSON.stringify(name)} uses an unsupported namespaced Windows module path.`);
|
|
765
|
+
output[name] = normalized.startsWith(".") ? resolve(root, normalized) : normalized;
|
|
766
|
+
}
|
|
767
|
+
return output;
|
|
768
|
+
}
|
|
769
|
+
function assertConfiguredProviders(registry, providers) {
|
|
770
|
+
const visit = (value, path) => {
|
|
771
|
+
if (!isRecord(value)) return;
|
|
772
|
+
if (isProviderEntry(value)) {
|
|
773
|
+
if (!Object.hasOwn(providers, value.source.provider)) throw new TypeError(`[vitehub] ${path} references Env provider ${JSON.stringify(value.source.provider)}, but hubEnv({ providers }) does not configure it.`);
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
if (isLiteralEntry(value) || isEnvEntry(value)) return;
|
|
777
|
+
for (const [key, child] of Object.entries(value)) visit(child, `${path}.${key}`);
|
|
778
|
+
};
|
|
779
|
+
for (const [key, value] of Object.entries(registry)) visit(value, `env.server.${key}`);
|
|
672
780
|
}
|
|
673
|
-
async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
|
|
781
|
+
async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules) {
|
|
782
|
+
const publicTypes = createPublicTypeEntries(publicConfig);
|
|
674
783
|
await Promise.all([
|
|
675
|
-
...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, serverRegistry, runtimeImports), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
|
|
676
|
-
writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(
|
|
784
|
+
...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
|
|
785
|
+
writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
|
|
677
786
|
writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
|
|
678
|
-
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(
|
|
679
|
-
writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports)),
|
|
680
|
-
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
|
|
681
|
-
...legacyEnvAmbientTypesPaths(root).map((path) => rm(path, { force: true }))
|
|
787
|
+
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
|
|
788
|
+
writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
|
|
789
|
+
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
|
|
682
790
|
]);
|
|
683
791
|
}
|
|
684
792
|
function createAmbientTypesReference(packageRoot, projectRoot) {
|
|
@@ -686,11 +794,12 @@ function createAmbientTypesReference(packageRoot, projectRoot) {
|
|
|
686
794
|
const specifier = target.startsWith(".") ? target : `./${target}`;
|
|
687
795
|
return `/// <reference path=${JSON.stringify(specifier)} />\n`;
|
|
688
796
|
}
|
|
689
|
-
function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports) {
|
|
797
|
+
function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports, providerModules) {
|
|
798
|
+
const publicTypes = createPublicTypeEntries(publicConfig);
|
|
690
799
|
return [
|
|
691
800
|
writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
|
|
692
|
-
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(
|
|
693
|
-
writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports)),
|
|
801
|
+
writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
|
|
802
|
+
writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
|
|
694
803
|
writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
|
|
695
804
|
];
|
|
696
805
|
}
|
|
@@ -721,59 +830,145 @@ function createPublicEnvModule(publicConfig) {
|
|
|
721
830
|
""
|
|
722
831
|
].join("\n");
|
|
723
832
|
}
|
|
724
|
-
function createPublicEnvModuleTypes(
|
|
833
|
+
function createPublicEnvModuleTypes(publicTypes) {
|
|
725
834
|
return [
|
|
726
835
|
"export interface PublicEnv {",
|
|
727
|
-
...createPublicTypeFields(
|
|
836
|
+
...createPublicTypeFields(publicTypes, 2),
|
|
728
837
|
"}",
|
|
729
838
|
"export const publicEnv: PublicEnv",
|
|
730
839
|
"export function usePublicEnv(): PublicEnv",
|
|
731
840
|
""
|
|
732
841
|
].join("\n");
|
|
733
842
|
}
|
|
734
|
-
function createServerEnvModule(serverRegistry, runtimeImports) {
|
|
843
|
+
function createServerEnvModule(serverRegistry, runtimeImports, providerModules, outputPath) {
|
|
844
|
+
const referenced = referencedProviderNames(serverRegistry);
|
|
845
|
+
const providers = Object.entries(providerModules).filter(([name]) => referenced.has(name));
|
|
735
846
|
return [
|
|
736
|
-
`import { resolveServerEnv } from ${JSON.stringify(runtimeImports.server)};`,
|
|
737
|
-
`
|
|
847
|
+
`import { inspectServerEnv as inspectRegistry, loadServerEnv as loadRegistry, resolveServerEnv } from ${JSON.stringify(runtimeImports.server)};`,
|
|
848
|
+
...providers.map(([, specifier], index) => `import envProvider${index} from ${JSON.stringify(providerImportSpecifier(specifier, outputPath))};`),
|
|
849
|
+
`const registry = JSON.parse(${JSON.stringify(JSON.stringify(serverRegistry))});`,
|
|
850
|
+
`const providers = Object.fromEntries([${providers.map(([name], index) => `[${JSON.stringify(name)}, envProvider${index}]`).join(", ")}]);`,
|
|
738
851
|
"export function useServerEnv(event) { return resolveServerEnv(registry, event); }",
|
|
739
|
-
"export async function
|
|
852
|
+
"export async function loadServerEnv(event, options) { return await loadRegistry(registry, event, { ...options, providers }); }",
|
|
853
|
+
"export async function inspectServerEnv(event, options) { return await inspectRegistry(registry, event, { ...options, providers }); }",
|
|
854
|
+
"export async function runWithServerEnv(event, callback, options) { return await callback(await loadServerEnv(event, options)); }",
|
|
740
855
|
""
|
|
741
856
|
].join("\n");
|
|
742
857
|
}
|
|
858
|
+
function providerImportSpecifier(specifier, outputPath) {
|
|
859
|
+
const windowsAbsolute = win32.isAbsolute(specifier);
|
|
860
|
+
if (!isAbsolute(specifier) && !windowsAbsolute) return specifier;
|
|
861
|
+
if (!outputPath) {
|
|
862
|
+
const normalized = specifier.replace(/\\/g, "/");
|
|
863
|
+
if (normalized.startsWith("//")) return `/@fs/${encodeModulePath(normalized)}`;
|
|
864
|
+
return /^[A-Za-z]:\//.test(normalized) ? `/${normalized}` : normalized;
|
|
865
|
+
}
|
|
866
|
+
if (windowsAbsolute !== win32.isAbsolute(outputPath)) return absoluteProviderImportSpecifier(specifier);
|
|
867
|
+
const target = windowsAbsolute ? win32.relative(win32.dirname(outputPath), specifier) : relative(dirname(outputPath), specifier);
|
|
868
|
+
if (isAbsolute(target) || win32.isAbsolute(target)) return absoluteProviderImportSpecifier(target);
|
|
869
|
+
const encodedTarget = encodeModulePath(target.replace(/\\/g, "/"));
|
|
870
|
+
return encodedTarget.startsWith(".") ? encodedTarget : `./${encodedTarget}`;
|
|
871
|
+
}
|
|
872
|
+
function absoluteProviderImportSpecifier(path) {
|
|
873
|
+
const normalized = path.replace(/\\/g, "/");
|
|
874
|
+
const encoded = encodeModulePath(normalized);
|
|
875
|
+
return /^[A-Za-z]:\//.test(normalized) ? `/${encoded}` : encoded;
|
|
876
|
+
}
|
|
877
|
+
function encodeModulePath(path) {
|
|
878
|
+
return path.split("/").map((segment) => /^[A-Za-z]:$/.test(segment) ? segment : encodeURIComponent(segment)).join("/");
|
|
879
|
+
}
|
|
880
|
+
function referencedProviderNames(registry) {
|
|
881
|
+
const names = /* @__PURE__ */ new Set();
|
|
882
|
+
const visit = (value) => {
|
|
883
|
+
if (!isRecord(value)) return;
|
|
884
|
+
if (isProviderEntry(value)) {
|
|
885
|
+
names.add(value.source.provider);
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
if (isLiteralEntry(value) || isEnvEntry(value)) return;
|
|
889
|
+
for (const child of Object.values(value)) visit(child);
|
|
890
|
+
};
|
|
891
|
+
for (const value of Object.values(registry)) visit(value);
|
|
892
|
+
return names;
|
|
893
|
+
}
|
|
743
894
|
function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
|
|
744
895
|
return [
|
|
745
896
|
`import type { SecretEnv } from ${JSON.stringify(runtimeImports.secret)}`,
|
|
746
897
|
"",
|
|
898
|
+
...createServerEnvInspectionTypes(0),
|
|
747
899
|
"export interface ServerEnv {",
|
|
748
900
|
...createServerTypeFields(serverRegistry, 2),
|
|
749
901
|
"}",
|
|
750
902
|
"export function useServerEnv(event?: unknown): ServerEnv",
|
|
751
|
-
|
|
903
|
+
...createReadonlyServerEnvTypes(0, "SecretEnv"),
|
|
904
|
+
"export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ReadonlyServerEnv>",
|
|
905
|
+
"export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ServerEnvInspection>",
|
|
906
|
+
"export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal }): Promise<T>",
|
|
752
907
|
""
|
|
753
908
|
].join("\n");
|
|
754
909
|
}
|
|
755
|
-
function createViteTypes(
|
|
910
|
+
function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
|
|
756
911
|
return [
|
|
757
912
|
"declare module \"#vitehub/env/public\" {",
|
|
758
913
|
" export interface PublicEnv {",
|
|
759
|
-
...createPublicTypeFields(
|
|
914
|
+
...createPublicTypeFields(publicTypes, 4),
|
|
760
915
|
" }",
|
|
761
916
|
" export const publicEnv: PublicEnv",
|
|
762
917
|
" export function usePublicEnv(): PublicEnv",
|
|
763
918
|
"}",
|
|
764
919
|
"declare module \"#vitehub/env/server\" {",
|
|
920
|
+
...createServerEnvInspectionTypes(2),
|
|
765
921
|
" export interface ServerEnv {",
|
|
766
922
|
...createServerTypeFields(serverRegistry, 4, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
|
|
767
923
|
" }",
|
|
768
924
|
" export function useServerEnv(event?: unknown): ServerEnv",
|
|
769
|
-
|
|
925
|
+
...createReadonlyServerEnvTypes(2, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
|
|
926
|
+
" export function loadServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ReadonlyServerEnv>",
|
|
927
|
+
" export function inspectServerEnv(event?: unknown, options?: { signal?: AbortSignal }): Promise<ServerEnvInspection>",
|
|
928
|
+
" export function runWithServerEnv<T>(event: unknown, callback: (env: ReadonlyServerEnv) => T | Promise<T>, options?: { signal?: AbortSignal }): Promise<T>",
|
|
770
929
|
"}",
|
|
771
930
|
""
|
|
772
931
|
].join("\n");
|
|
773
932
|
}
|
|
774
|
-
function
|
|
933
|
+
function createServerEnvInspectionTypes(indent) {
|
|
934
|
+
const prefix = " ".repeat(indent);
|
|
935
|
+
return [
|
|
936
|
+
`${prefix}export interface ServerEnvInspectionEntry {`,
|
|
937
|
+
`${prefix} masked: boolean`,
|
|
938
|
+
`${prefix} path?: string`,
|
|
939
|
+
`${prefix} source: "env" | "literal" | "provider"`,
|
|
940
|
+
`${prefix} status: "available" | "defaulted" | "error" | "invalid" | "missing"`,
|
|
941
|
+
`${prefix}}`,
|
|
942
|
+
`${prefix}export interface ServerEnvInspection {`,
|
|
943
|
+
`${prefix} entries: readonly ServerEnvInspectionEntry[]`,
|
|
944
|
+
`${prefix}}`
|
|
945
|
+
];
|
|
946
|
+
}
|
|
947
|
+
function createReadonlyServerEnvTypes(indent, secretType) {
|
|
775
948
|
const prefix = " ".repeat(indent);
|
|
776
|
-
return
|
|
949
|
+
return [
|
|
950
|
+
`${prefix}export type ReadonlyServerEnv = DeepReadonly<ServerEnv>`,
|
|
951
|
+
`${prefix}type DeepReadonly<T> = T extends ${secretType}<unknown>`,
|
|
952
|
+
`${prefix} ? T`,
|
|
953
|
+
`${prefix} : T extends (...args: infer TArguments) => infer TResult`,
|
|
954
|
+
`${prefix} ? (...args: TArguments) => TResult`,
|
|
955
|
+
`${prefix} : T extends object`,
|
|
956
|
+
`${prefix} ? { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> }`,
|
|
957
|
+
`${prefix} : T`
|
|
958
|
+
];
|
|
959
|
+
}
|
|
960
|
+
function createPublicTypeEntries(publicConfig) {
|
|
961
|
+
return Object.fromEntries(Object.entries(publicConfig).map(([key, value]) => [key, typeof value]));
|
|
962
|
+
}
|
|
963
|
+
function createPreparedPublicTypeEntries(publicConfig) {
|
|
964
|
+
return Object.fromEntries(Object.entries(publicConfig ?? {}).map(([key, declaration]) => {
|
|
965
|
+
const parsedDefault = typeof declaration.default === "undefined" ? void 0 : parseSchema(declaration.schema, declaration.default, `env.public.${key}`);
|
|
966
|
+
return [key, `${declaration.type ?? (isDefaultStringEnvVariable(declaration) ? "string" : void 0) ?? (parsedDefault === null ? "null" : typeof parsedDefault === "undefined" ? "unknown" : typeof parsedDefault)}${!declaration.required && typeof declaration.default === "undefined" ? " | undefined" : ""}`];
|
|
967
|
+
}));
|
|
968
|
+
}
|
|
969
|
+
function createPublicTypeFields(publicTypes, indent) {
|
|
970
|
+
const prefix = " ".repeat(indent);
|
|
971
|
+
return Object.entries(publicTypes).map(([key, type]) => `${prefix}${JSON.stringify(key)}: ${type}`);
|
|
777
972
|
}
|
|
778
973
|
function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
|
|
779
974
|
const prefix = " ".repeat(indent);
|
|
@@ -784,14 +979,14 @@ function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
|
|
|
784
979
|
}
|
|
785
980
|
function serverTypeFor(value, indent, secretType) {
|
|
786
981
|
if (isLiteralEntry(value)) return literalType(value.value);
|
|
787
|
-
if (isEnvEntry(value)) return value.secret ? `${secretType}<string>` : "string";
|
|
982
|
+
if (isEnvEntry(value) || isProviderEntry(value)) return value.secret ? `${secretType}<string>` : "string";
|
|
788
983
|
const fields = createServerTypeFields(value, indent + 2, secretType);
|
|
789
984
|
if (!fields.length) return "Record<string, never>";
|
|
790
985
|
const prefix = " ".repeat(indent);
|
|
791
986
|
return `{\n${fields.join("\n")}\n${prefix}}`;
|
|
792
987
|
}
|
|
793
988
|
function isOptionalServerValue(value) {
|
|
794
|
-
return isEnvEntry(value) && !value.required && typeof value.default === "undefined";
|
|
989
|
+
return (isEnvEntry(value) || isProviderEntry(value)) && !value.required && typeof value.default === "undefined";
|
|
795
990
|
}
|
|
796
991
|
function literalType(value) {
|
|
797
992
|
if (value === null) return "null";
|
|
@@ -810,10 +1005,15 @@ function isLiteralEntry(value) {
|
|
|
810
1005
|
function isEnvEntry(value) {
|
|
811
1006
|
if (!isRecord(value)) return false;
|
|
812
1007
|
const record = value;
|
|
813
|
-
return isRecord(record.source) && typeof record.required === "boolean" && typeof record.secret === "boolean";
|
|
1008
|
+
return isRecord(record.source) && record.source.kind === "env" && typeof record.required === "boolean" && typeof record.secret === "boolean";
|
|
1009
|
+
}
|
|
1010
|
+
function isProviderEntry(value) {
|
|
1011
|
+
if (!isRecord(value)) return false;
|
|
1012
|
+
const record = value;
|
|
1013
|
+
return isRecord(record.source) && record.source.kind === "provider" && typeof record.source.provider === "string";
|
|
814
1014
|
}
|
|
815
1015
|
function isRecord(value) {
|
|
816
1016
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
817
1017
|
}
|
|
818
1018
|
//#endregion
|
|
819
|
-
export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, env, hubEnv };
|
|
1019
|
+
export { ENV_PUBLIC_ID, ENV_SERVER_ID, ENV_VITE_PLUGIN_NAME, createEnvImportAliases, createEnvTypeScriptPaths, createRuntimeRegistry as createRuntimeEnvRegistry, env, hubEnv };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vite-hub/env",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.4",
|
|
4
4
|
"description": "Safe build and runtime environment variables for ViteHub.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"env",
|
|
@@ -34,6 +34,10 @@
|
|
|
34
34
|
"types": "./dist/presets.d.ts",
|
|
35
35
|
"import": "./dist/presets.js"
|
|
36
36
|
},
|
|
37
|
+
"./provider": {
|
|
38
|
+
"types": "./dist/provider.d.ts",
|
|
39
|
+
"import": "./dist/provider.js"
|
|
40
|
+
},
|
|
37
41
|
"./schema": {
|
|
38
42
|
"types": "./dist/schema.d.ts",
|
|
39
43
|
"import": "./dist/schema.js"
|
|
@@ -57,7 +61,7 @@
|
|
|
57
61
|
"./package.json": "./package.json"
|
|
58
62
|
},
|
|
59
63
|
"dependencies": {
|
|
60
|
-
"@vite-hub/runtime": "0.0.
|
|
64
|
+
"@vite-hub/runtime": "0.0.4"
|
|
61
65
|
},
|
|
62
66
|
"devDependencies": {
|
|
63
67
|
"publint": "^0.3.21",
|