@vite-hub/env 0.0.3 → 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/dist/vite.js CHANGED
@@ -1,10 +1,11 @@
1
- import { n as env, r as isDefaultStringEnvVariable, t as defaultStringSchema } from "./declarations-Cy5XamUA.js";
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 missingRequiredEnv, i as isAbortError, n as invalidEnvDeclaration, t as envSourceFailed } from "./errors-RUmAFDJn.js";
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, rm, stat, writeFile } from "node:fs/promises";
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,31 +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"],
100
102
  ["server", "browsers"],
103
+ ["server", "emails"],
101
104
  ["server", "schedules"],
102
- ["server", "templates"],
103
105
  ["server", "workspaces"]
104
106
  ];
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
107
  const projectRootFileMarkers = [["package.json"]];
114
108
  const VITEHUB_ENV_PUBLIC_ID = "#vitehub/env/public";
115
109
  const VITEHUB_ENV_SERVER_ID = "#vitehub/env/server";
116
110
  function resolveViteHubProjectRoot(root, options = {}) {
117
111
  const resolvedRoot = resolve(root);
112
+ const temporaryRoot = resolve(tmpdir());
113
+ const sharedTemporaryRoot = dirname(temporaryRoot) === parse(temporaryRoot).root ? temporaryRoot : void 0;
118
114
  if (options.projectRoot) return resolve(resolvedRoot, options.projectRoot);
119
115
  if (basename(resolvedRoot) === "app") {
120
116
  const parent = dirname(resolvedRoot);
121
- if (hasProjectRootDirectoryMarker(parent) || hasProjectRootDefinitionFileMarker(parent)) return parent;
117
+ if (parent !== sharedTemporaryRoot && hasProjectRootDirectoryMarker(parent)) return parent;
122
118
  }
123
119
  let current = resolvedRoot;
124
120
  while (true) {
121
+ if (current === sharedTemporaryRoot && resolvedRoot !== current) return resolvedRoot;
125
122
  if (hasProjectRootMarker(current)) return current;
126
123
  const parent = dirname(current);
127
124
  if (parent === current) return resolvedRoot;
@@ -138,7 +135,6 @@ function hasProjectRootDirectoryMarker(root) {
138
135
  }
139
136
  function hasProjectRootMarker(root) {
140
137
  if (hasProjectRootDirectoryMarker(root)) return true;
141
- if (hasProjectRootDefinitionFileMarker(root)) return true;
142
138
  for (const marker of projectRootFileMarkers) try {
143
139
  if (statSync(resolve(root, ...marker)).isFile()) return true;
144
140
  } catch (error) {
@@ -146,14 +142,6 @@ function hasProjectRootMarker(root) {
146
142
  }
147
143
  return false;
148
144
  }
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
145
  function viteHubEnvAmbientTypesPath(root) {
158
146
  return resolve(root, ".vitehub", "types", "env.d.ts");
159
147
  }
@@ -340,7 +328,7 @@ async function resolveEnvEntries(declarations, input) {
340
328
  };
341
329
  }
342
330
  function createRuntimeRegistry(declarations, options = {}) {
343
- return buildRegistry(declarations, "env", options.prefix);
331
+ return buildRegistry(declarations, options.path ?? "env", options.prefix);
344
332
  }
345
333
  async function resolveBuildConfigValue(declaration, path, input) {
346
334
  if (isEnvVariableDeclaration(declaration)) {
@@ -412,7 +400,7 @@ function buildRegistry(declarations, path, prefix) {
412
400
  }
413
401
  if (value.mode !== "runtime") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use mode: "runtime".`);
414
402
  const source = resolveEnvSource(value, valuePath, prefix);
415
- if (source.kind !== "env") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() in v1.`);
403
+ if (source.kind !== "env" && source.kind !== "provider") throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} must use env.source() or env.provider().`);
416
404
  if (!isDefaultStringEnvVariable(value)) throw invalidEnvDeclaration(valuePath, `Runtime declaration ${valuePath} uses a custom schema, but runtime schemas cannot be serialized in v1.`);
417
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.`);
418
406
  return [key, {
@@ -485,6 +473,7 @@ async function resolveSourceValue(source, context) {
485
473
  label: source.label,
486
474
  value: readPath(await resolveBuiltInSource(source.label, () => context.packageJson()), source.path)
487
475
  };
476
+ case "provider": throw invalidEnvDeclaration("env", "env.provider() is available only to Server Env at runtime.");
488
477
  }
489
478
  }
490
479
  async function resolveBuiltInSource(source, resolveSource) {
@@ -552,7 +541,9 @@ function isBuildStaticValue(value) {
552
541
  }
553
542
  }
554
543
  async function readPackageJson(rootDir) {
555
- return JSON.parse(await readFile(resolve(rootDir, "package.json"), "utf8"));
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;
556
547
  }
557
548
  async function gitOutput(rootDir, args) {
558
549
  const { stdout } = await execFileAsync("git", args, { cwd: rootDir });
@@ -575,6 +566,7 @@ const defaultRuntimeImports = {
575
566
  secret: "@vite-hub/env/secret",
576
567
  server: "@vite-hub/env/server"
577
568
  };
569
+ let envVitePluginSequence = 0;
578
570
  function createEnvImportAliases(options = {}) {
579
571
  return createViteHubEnvImportAliases(resolveEnvProjectRoot(options));
580
572
  }
@@ -589,59 +581,141 @@ function createEnvTypeScriptPaths(options = {}) {
589
581
  function hubEnv(options = {}) {
590
582
  let buildPublicConfig = {};
591
583
  let serverRegistry = {};
592
- let diagnosticsText;
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();
593
592
  const getPublicEnv = () => buildPublicConfig;
594
593
  const getServerEnvRegistry = () => serverRegistry;
594
+ const createServerEnvRegistry = (declarations) => createRuntimeRegistry(declarations, { prefix: options.prefix });
595
+ const resolveProjectRoot = (viteRoot) => resolveViteHubProjectRoot(resolve(viteRoot), { projectRoot: options.projectRoot });
595
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
+ };
596
657
  return {
597
658
  name: ENV_VITE_PLUGIN_NAME,
598
659
  api: {
660
+ createServerEnvRegistry,
599
661
  getPublicEnv,
600
- getServerEnvRegistry
662
+ getServerEnvRegistry,
663
+ onServerEnvRegistry: (handler) => serverRegistryHandlers.add(handler),
664
+ prepareTypes,
665
+ resolveProjectRoot
601
666
  },
602
667
  async config(config, env) {
603
668
  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
614
- });
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"
621
- });
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"
628
- });
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
- } };
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
+ };
636
683
  },
637
684
  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);
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
+ }
641
710
  },
642
711
  load(id) {
643
- if (id === RESOLVED_PUBLIC_ID) return createPublicEnvModule(buildPublicConfig);
644
- if (id === RESOLVED_SERVER_ID) return createServerEnvModule(serverRegistry, runtimeImports);
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);
645
719
  },
646
720
  resolveId: {
647
721
  order: "pre",
@@ -656,6 +730,19 @@ function hubEnv(options = {}) {
656
730
  }
657
731
  };
658
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
+ }
659
746
  function resolveEnvProjectRoot(options) {
660
747
  return resolveViteHubProjectRoot(process.cwd(), { projectRoot: options.projectRoot });
661
748
  }
@@ -668,18 +755,38 @@ function resolveRuntimeImports(imports) {
668
755
  server: imports?.server ?? defaultRuntimeImports.server
669
756
  };
670
757
  }
671
- function legacyEnvAmbientTypesPaths(root) {
672
- return [resolve(root, ".vitehub", "env", "vite.d.ts")];
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}`);
673
780
  }
674
- async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports) {
781
+ async function refreshEnvGeneratedFiles(root, packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules) {
782
+ const publicTypes = createPublicTypeEntries(publicConfig);
675
783
  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)),
784
+ ...packageRoot && packageRoot !== root ? [...packageEnvModuleWrites(packageRoot, publicConfig, serverRegistry, runtimeImports, providerModules), writeFileIfChanged(viteHubEnvAmbientTypesPath(packageRoot), createAmbientTypesReference(packageRoot, root))] : [],
785
+ writeFileIfChanged(viteHubEnvAmbientTypesPath(root), createViteTypes(publicTypes, serverRegistry, runtimeImports)),
678
786
  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 }))
787
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
788
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
789
+ writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
683
790
  ]);
684
791
  }
685
792
  function createAmbientTypesReference(packageRoot, projectRoot) {
@@ -687,11 +794,12 @@ function createAmbientTypesReference(packageRoot, projectRoot) {
687
794
  const specifier = target.startsWith(".") ? target : `./${target}`;
688
795
  return `/// <reference path=${JSON.stringify(specifier)} />\n`;
689
796
  }
690
- function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports) {
797
+ function packageEnvModuleWrites(root, publicConfig, serverRegistry, runtimeImports, providerModules) {
798
+ const publicTypes = createPublicTypeEntries(publicConfig);
691
799
  return [
692
800
  writeFileIfChanged(viteHubEnvPublicModulePath(root), createPublicEnvModule(publicConfig)),
693
- writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicConfig)),
694
- writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports)),
801
+ writeFileIfChanged(viteHubEnvPublicModuleTypesPath(root), createPublicEnvModuleTypes(publicTypes)),
802
+ writeFileIfChanged(viteHubEnvServerModulePath(root), createServerEnvModule(serverRegistry, runtimeImports, providerModules, viteHubEnvServerModulePath(root))),
695
803
  writeFileIfChanged(viteHubEnvServerModuleTypesPath(root), createServerEnvModuleTypes(serverRegistry, runtimeImports))
696
804
  ];
697
805
  }
@@ -722,59 +830,145 @@ function createPublicEnvModule(publicConfig) {
722
830
  ""
723
831
  ].join("\n");
724
832
  }
725
- function createPublicEnvModuleTypes(publicConfig) {
833
+ function createPublicEnvModuleTypes(publicTypes) {
726
834
  return [
727
835
  "export interface PublicEnv {",
728
- ...createPublicTypeFields(publicConfig, 2),
836
+ ...createPublicTypeFields(publicTypes, 2),
729
837
  "}",
730
838
  "export const publicEnv: PublicEnv",
731
839
  "export function usePublicEnv(): PublicEnv",
732
840
  ""
733
841
  ].join("\n");
734
842
  }
735
- 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));
736
846
  return [
737
- `import { resolveServerEnv } from ${JSON.stringify(runtimeImports.server)};`,
738
- `const registry = ${JSON.stringify(serverRegistry, null, 2)};`,
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(", ")}]);`,
739
851
  "export function useServerEnv(event) { return resolveServerEnv(registry, event); }",
740
- "export async function runWithServerEnv(event, callback) { return await callback(useServerEnv(event)); }",
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)); }",
741
855
  ""
742
856
  ].join("\n");
743
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
+ }
744
894
  function createServerEnvModuleTypes(serverRegistry, runtimeImports) {
745
895
  return [
746
896
  `import type { SecretEnv } from ${JSON.stringify(runtimeImports.secret)}`,
747
897
  "",
898
+ ...createServerEnvInspectionTypes(0),
748
899
  "export interface ServerEnv {",
749
900
  ...createServerTypeFields(serverRegistry, 2),
750
901
  "}",
751
902
  "export function useServerEnv(event?: unknown): ServerEnv",
752
- "export function runWithServerEnv<T>(event: unknown, callback: (env: ServerEnv) => T | Promise<T>): Promise<T>",
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>",
753
907
  ""
754
908
  ].join("\n");
755
909
  }
756
- function createViteTypes(publicConfig, serverRegistry, runtimeImports) {
910
+ function createViteTypes(publicTypes, serverRegistry, runtimeImports) {
757
911
  return [
758
912
  "declare module \"#vitehub/env/public\" {",
759
913
  " export interface PublicEnv {",
760
- ...createPublicTypeFields(publicConfig, 4),
914
+ ...createPublicTypeFields(publicTypes, 4),
761
915
  " }",
762
916
  " export const publicEnv: PublicEnv",
763
917
  " export function usePublicEnv(): PublicEnv",
764
918
  "}",
765
919
  "declare module \"#vitehub/env/server\" {",
920
+ ...createServerEnvInspectionTypes(2),
766
921
  " export interface ServerEnv {",
767
922
  ...createServerTypeFields(serverRegistry, 4, `import(${JSON.stringify(runtimeImports.secret)}).SecretEnv`),
768
923
  " }",
769
924
  " export function useServerEnv(event?: unknown): ServerEnv",
770
- " export function runWithServerEnv<T>(event: unknown, callback: (env: ServerEnv) => T | Promise<T>): Promise<T>",
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>",
771
929
  "}",
772
930
  ""
773
931
  ].join("\n");
774
932
  }
775
- function createPublicTypeFields(publicConfig, indent) {
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) {
776
948
  const prefix = " ".repeat(indent);
777
- return Object.entries(publicConfig).map(([key, value]) => `${prefix}${JSON.stringify(key)}: ${typeof value}`);
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}`);
778
972
  }
779
973
  function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
780
974
  const prefix = " ".repeat(indent);
@@ -785,14 +979,14 @@ function createServerTypeFields(registry, indent, secretType = "SecretEnv") {
785
979
  }
786
980
  function serverTypeFor(value, indent, secretType) {
787
981
  if (isLiteralEntry(value)) return literalType(value.value);
788
- if (isEnvEntry(value)) return value.secret ? `${secretType}<string>` : "string";
982
+ if (isEnvEntry(value) || isProviderEntry(value)) return value.secret ? `${secretType}<string>` : "string";
789
983
  const fields = createServerTypeFields(value, indent + 2, secretType);
790
984
  if (!fields.length) return "Record<string, never>";
791
985
  const prefix = " ".repeat(indent);
792
986
  return `{\n${fields.join("\n")}\n${prefix}}`;
793
987
  }
794
988
  function isOptionalServerValue(value) {
795
- return isEnvEntry(value) && !value.required && typeof value.default === "undefined";
989
+ return (isEnvEntry(value) || isProviderEntry(value)) && !value.required && typeof value.default === "undefined";
796
990
  }
797
991
  function literalType(value) {
798
992
  if (value === null) return "null";
@@ -811,10 +1005,15 @@ function isLiteralEntry(value) {
811
1005
  function isEnvEntry(value) {
812
1006
  if (!isRecord(value)) return false;
813
1007
  const record = value;
814
- 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";
815
1014
  }
816
1015
  function isRecord(value) {
817
1016
  return typeof value === "object" && value !== null && !Array.isArray(value);
818
1017
  }
819
1018
  //#endregion
820
- 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",
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.3"
64
+ "@vite-hub/runtime": "0.0.4"
61
65
  },
62
66
  "devDependencies": {
63
67
  "publint": "^0.3.21",