@vite-hub/env 0.0.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +288 -23
  2. package/dist/access-B8lSDip4.js +54 -0
  3. package/dist/bridge-Cs9YfQWk.d.ts +447 -0
  4. package/dist/bridge-error-BhJ77age.js +66 -0
  5. package/dist/bridge.d.ts +2 -0
  6. package/dist/bridge.js +354 -0
  7. package/dist/cli-BPp7rdcA.d.ts +159 -0
  8. package/dist/cli-DLpY0QAo.js +669 -0
  9. package/dist/cli.d.ts +41 -0
  10. package/dist/cli.js +2 -0
  11. package/dist/database.d.ts +47 -0
  12. package/dist/database.js +274 -0
  13. package/dist/declarations-C5XR3aKw.d.ts +58 -0
  14. package/dist/error-diagnostics-B8RFjQ1V.js +56 -0
  15. package/dist/index.d.ts +146 -11
  16. package/dist/index.js +240 -7
  17. package/dist/internal/agent.d.ts +5 -0
  18. package/dist/internal/agent.js +22 -0
  19. package/dist/internal/connections.d.ts +18 -0
  20. package/dist/internal/connections.js +31 -0
  21. package/dist/internal/server.d.ts +3 -0
  22. package/dist/internal/server.js +2 -0
  23. package/dist/object-_dlsZ4lP.js +276 -0
  24. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  25. package/dist/operations-X1w--wds.js +30 -0
  26. package/dist/operations.d.ts +37 -0
  27. package/dist/operations.js +833 -0
  28. package/dist/runtime/public-env.d.ts +5 -0
  29. package/dist/runtime/public-env.js +8 -0
  30. package/dist/runtime/server-env.d.ts +22 -0
  31. package/dist/runtime/server-env.js +35 -0
  32. package/dist/schema-DMZ1_yhY.js +360 -0
  33. package/dist/seal.d.ts +17 -0
  34. package/dist/seal.js +52 -0
  35. package/dist/{secret.js → secret-DJd-fy5T.js} +1 -1
  36. package/dist/server-ChNL_Xc3.js +1279 -0
  37. package/dist/server-Dd8bjIKd.d.ts +145 -0
  38. package/dist/server.d.ts +3 -8
  39. package/dist/server.js +2 -3
  40. package/dist/virtual-module.d.ts +9 -5
  41. package/dist/virtual.d.ts +1 -1
  42. package/dist/vite.d.ts +79 -21
  43. package/dist/vite.js +1095 -339
  44. package/package.json +81 -28
  45. package/dist/declarations-CoMmvRqH.js +0 -159
  46. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  47. package/dist/errors-C4Xcs6Fi.js +0 -121
  48. package/dist/presets.d.ts +0 -11
  49. package/dist/presets.js +0 -25
  50. package/dist/provider.d.ts +0 -6
  51. package/dist/provider.js +0 -7
  52. package/dist/schema.d.ts +0 -16
  53. package/dist/schema.js +0 -37
  54. package/dist/secret-C2191nAa.d.ts +0 -11
  55. package/dist/secret.d.ts +0 -2
  56. package/dist/server-C16sFc1E.js +0 -303
  57. package/dist/types-CsB6DTGE.d.ts +0 -190
package/dist/cli.d.ts ADDED
@@ -0,0 +1,41 @@
1
+ import { G as ServerEnvInspection, K as ServerEnvInspectionEntry } from "./bridge-Cs9YfQWk.js";
2
+ import { n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-BPp7rdcA.js";
3
+ //#region src/secret-cli.d.ts
4
+ interface SecretCliContext {
5
+ env: Readonly<Record<string, string | undefined>>;
6
+ stderr: {
7
+ write: (chunk: string) => unknown;
8
+ };
9
+ stdout: {
10
+ write: (chunk: string) => unknown;
11
+ };
12
+ }
13
+ interface SecretCliFeature {
14
+ description: string;
15
+ name: string;
16
+ run: (args: string[], context: SecretCliContext) => Promise<number>;
17
+ usage: string;
18
+ }
19
+ /** `vitehub secret` features. They read only the process env and never load the project. */
20
+ export declare const secretCliFeatures: SecretCliFeature[];
21
+ //#endregion
22
+ //#region src/cli.d.ts
23
+ export interface EnvCliInspectInput {
24
+ applicationRoot?: string;
25
+ env: NodeJS.ProcessEnv;
26
+ rootDir: string;
27
+ stderr: ViteHubCliContext["stderr"];
28
+ stage: string;
29
+ }
30
+ export interface EnvCliOptions {
31
+ /** Replaces stage loading in tests. */
32
+ inspect?: (input: EnvCliInspectInput) => Promise<ServerEnvInspection>;
33
+ resolveProjectRoot: (viteRoot: string) => string;
34
+ }
35
+ export interface EnvCliReport {
36
+ entries: readonly ServerEnvInspectionEntry[];
37
+ ok: boolean;
38
+ stage: string;
39
+ }
40
+ export declare function createEnvCliContributor(options: EnvCliOptions): ViteHubCliContributor;
41
+ //#endregion
package/dist/cli.js ADDED
@@ -0,0 +1,2 @@
1
+ import { n as secretCliFeatures, t as createEnvCliContributor } from "./cli-DLpY0QAo.js";
2
+ export { createEnvCliContributor, secretCliFeatures };
@@ -0,0 +1,47 @@
1
+ import { d as EnvSecretMetadata, f as EnvSecretStore, r as EnvAccessStore } from "./bridge-Cs9YfQWk.js";
2
+ import { SQL } from "drizzle-orm";
3
+ //#region src/database.d.ts
4
+ export interface EnvDatabase {
5
+ run(query: SQL): unknown;
6
+ all(query: SQL): unknown[] | PromiseLike<unknown[]>;
7
+ }
8
+ export interface DatabaseEnvStore {
9
+ /** SQL predicate for atomically updating related records at a secret revision. */
10
+ revisionCondition(key: string, revision: string | null): Promise<SQL>;
11
+ /** The keys of the namespace with their metadata, by key. It never reads a value. */
12
+ list(): Promise<(EnvSecretMetadata & {
13
+ key: string;
14
+ })[]>;
15
+ /** Delete a key. Returns `false` when the namespace has no such key. Activity and grants stay. */
16
+ remove(key: string): Promise<boolean>;
17
+ /**
18
+ * Re-encrypts every value of the namespace that another key sealed with the current key, the first of
19
+ * `encryptionKeys`. Revisions stay the same. A value that a write replaces during the rotation keeps the new write.
20
+ */
21
+ rotate(): Promise<EnvStoreRotation>;
22
+ secrets: EnvSecretStore;
23
+ access: EnvAccessStore;
24
+ }
25
+ /** The result of `DatabaseEnvStore.rotate()`. */
26
+ export interface EnvStoreRotation {
27
+ /** Values re-encrypted with the current key. */
28
+ rotated: number;
29
+ /** Values that the current key already sealed, or that a concurrent write replaced. */
30
+ skipped: number;
31
+ }
32
+ /**
33
+ * The namespaces that start with `prefix` and hold at least one key, in text order. A Console that keeps one namespace
34
+ * for each project and stage, such as `<project>:production`, finds the stages of a project with it.
35
+ */
36
+ export declare function listDatabaseEnvNamespaces(db: EnvDatabase, prefix: string): Promise<string[]>;
37
+ /**
38
+ * Persistent encrypted values, activity, and grants on a ViteHub SQLite/Drizzle database.
39
+ * `encryptionKeys` is the keyring: the current 32-byte key first, then previous keys that still decrypt older values.
40
+ */
41
+ export declare function createDatabaseEnvStore(options: {
42
+ db: EnvDatabase;
43
+ encryptionKeys: readonly Uint8Array[];
44
+ namespace?: string;
45
+ previews?: boolean;
46
+ }): DatabaseEnvStore;
47
+ //#endregion
@@ -0,0 +1,274 @@
1
+ import { t as envBridgeError } from "./bridge-error-BhJ77age.js";
2
+ import { importSealKey, sealKeyId, sealWithKey, sealedPayloadPattern, unsealWithKey } from "./seal.js";
3
+ import { ViteHubError } from "@vite-hub/runtime";
4
+ import * as v from "valibot";
5
+ import { sql } from "drizzle-orm";
6
+ //#region src/database.ts
7
+ /** A stored value: `v2:<keyId>:<iv>:<ciphertext>`, or a legacy `<iv>:<ciphertext>` without a key id. */
8
+ const storedPayloadPattern = new RegExp(`^(?:v2:[a-f0-9]{16}:)?${sealedPayloadPattern.source.slice(1, -1)}$`);
9
+ const identifier = v.pipe(v.string(), v.minLength(1), v.maxLength(512), v.regex(/^[^\u0000-\u001f]+$/));
10
+ const actor = v.object({
11
+ id: identifier,
12
+ kind: v.picklist([
13
+ "user",
14
+ "agent",
15
+ "service"
16
+ ])
17
+ });
18
+ const permission = v.picklist([
19
+ "inspect",
20
+ "preview",
21
+ "replace",
22
+ "use"
23
+ ]);
24
+ const timestamp = v.pipe(v.string(), v.isoTimestamp());
25
+ const activity = v.object({
26
+ id: identifier,
27
+ operationId: identifier,
28
+ timestamp,
29
+ actor,
30
+ key: identifier,
31
+ action: v.picklist([
32
+ "inspect",
33
+ "preview",
34
+ "replace",
35
+ "remove",
36
+ "resolve",
37
+ "use",
38
+ "grant",
39
+ "revoke"
40
+ ]),
41
+ outcome: v.picklist([
42
+ "started",
43
+ "succeeded",
44
+ "failed",
45
+ "denied"
46
+ ]),
47
+ revision: v.optional(identifier),
48
+ operation: v.optional(identifier),
49
+ target: v.optional(actor),
50
+ permissions: v.optional(v.array(permission)),
51
+ traceId: v.optional(v.string()),
52
+ invocationId: v.optional(v.string())
53
+ });
54
+ const grant = v.object({
55
+ actor,
56
+ key: identifier,
57
+ permissions: v.pipe(v.array(permission), v.minLength(1))
58
+ });
59
+ const secretRow = v.object({
60
+ payload: v.pipe(v.string(), v.regex(storedPayloadPattern)),
61
+ revision: identifier,
62
+ updated_at: timestamp,
63
+ preview: v.nullable(v.string())
64
+ });
65
+ const activityRow = v.object({
66
+ payload: v.string(),
67
+ id: identifier
68
+ });
69
+ const grantRow = v.object({
70
+ payload: v.string(),
71
+ actor_kind: v.picklist([
72
+ "user",
73
+ "agent",
74
+ "service"
75
+ ]),
76
+ actor_id: identifier
77
+ });
78
+ const revisionRow = v.object({ revision: identifier });
79
+ const listRow = v.object({
80
+ key: identifier,
81
+ revision: identifier,
82
+ updated_at: timestamp,
83
+ preview: v.nullable(v.string())
84
+ });
85
+ const namespaceRow = v.object({ namespace: v.string() });
86
+ /** Create the Env tables when they are missing. Each store and `listDatabaseEnvNamespaces()` calls it first. */
87
+ async function createEnvTables(db) {
88
+ await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_secrets (namespace TEXT NOT NULL, key TEXT NOT NULL, payload TEXT NOT NULL, revision TEXT NOT NULL, updated_at TEXT NOT NULL, preview TEXT, PRIMARY KEY (namespace, key))`);
89
+ await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_activity (sequence INTEGER PRIMARY KEY AUTOINCREMENT, namespace TEXT NOT NULL, key TEXT NOT NULL, id TEXT NOT NULL UNIQUE, payload TEXT NOT NULL)`);
90
+ await db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_env_activity_key ON vitehub_env_activity (namespace, key, sequence)`);
91
+ await db.run(sql`CREATE TABLE IF NOT EXISTS vitehub_env_grants (namespace TEXT NOT NULL, key TEXT NOT NULL, actor_kind TEXT NOT NULL, actor_id TEXT NOT NULL, payload TEXT NOT NULL, PRIMARY KEY (namespace, key, actor_kind, actor_id))`);
92
+ }
93
+ /**
94
+ * The namespaces that start with `prefix` and hold at least one key, in text order. A Console that keeps one namespace
95
+ * for each project and stage, such as `<project>:production`, finds the stages of a project with it.
96
+ */
97
+ async function listDatabaseEnvNamespaces(db, prefix) {
98
+ await createEnvTables(db);
99
+ return (await db.all(sql`SELECT DISTINCT namespace FROM vitehub_env_secrets WHERE substr(namespace, 1, ${prefix.length}) = ${prefix} ORDER BY namespace`)).map((row) => v.parse(namespaceRow, row).namespace);
100
+ }
101
+ const rotationRow = v.object({
102
+ key: identifier,
103
+ payload: v.pipe(v.string(), v.regex(storedPayloadPattern)),
104
+ revision: identifier
105
+ });
106
+ function parseStoredJson(payload) {
107
+ try {
108
+ return JSON.parse(payload);
109
+ } catch {
110
+ throw envBridgeError("invalid");
111
+ }
112
+ }
113
+ /**
114
+ * Persistent encrypted values, activity, and grants on a ViteHub SQLite/Drizzle database.
115
+ * `encryptionKeys` is the keyring: the current 32-byte key first, then previous keys that still decrypt older values.
116
+ */
117
+ function createDatabaseEnvStore(options) {
118
+ if (!options.encryptionKeys.length || options.encryptionKeys.some((key) => key.byteLength !== 32)) throw envBridgeError("invalid");
119
+ const namespace = options.namespace ?? "default";
120
+ let keyring;
121
+ const keys = () => keyring ??= Promise.all(options.encryptionKeys.map(async (key) => ({
122
+ id: await sealKeyId(key),
123
+ key: await importSealKey(key)
124
+ })));
125
+ async function seal(key, revision, value) {
126
+ const [current] = await keys();
127
+ return `v2:${current.id}:${await sealWithKey(current.key, aad(key, revision), value)}`;
128
+ }
129
+ async function unseal(key, revision, payload) {
130
+ const additionalData = aad(key, revision);
131
+ if (payload.startsWith("v2:")) {
132
+ const id = payload.slice(3, 19);
133
+ const match = (await keys()).find((candidate) => candidate.id === id);
134
+ if (!match) throw new ViteHubError("SEAL_INVALID", `No configured encryption key has the key id ${id}. Add the key that sealed this value to the keyring.`);
135
+ return await unsealWithKey(match.key, additionalData, payload.slice(20));
136
+ }
137
+ let failure;
138
+ for (const candidate of await keys()) try {
139
+ return await unsealWithKey(candidate.key, additionalData, payload);
140
+ } catch (error) {
141
+ failure ??= error;
142
+ }
143
+ throw failure;
144
+ }
145
+ let ready;
146
+ const initialize = () => ready ??= createEnvTables(options.db).catch((error) => {
147
+ ready = void 0;
148
+ throw error;
149
+ });
150
+ async function row(key) {
151
+ await initialize();
152
+ const stored = (await options.db.all(sql`SELECT payload, revision, updated_at, preview FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key}`))[0];
153
+ return stored === void 0 ? void 0 : v.parse(secretRow, stored);
154
+ }
155
+ function aad(key, revision) {
156
+ return new TextEncoder().encode(JSON.stringify([
157
+ namespace,
158
+ key,
159
+ revision
160
+ ]));
161
+ }
162
+ return {
163
+ async rotate() {
164
+ await initialize();
165
+ const [current] = await keys();
166
+ const rows = await options.db.all(sql`SELECT key, payload, revision FROM vitehub_env_secrets WHERE namespace = ${namespace} ORDER BY key`);
167
+ let rotated = 0;
168
+ let skipped = 0;
169
+ for (const row of rows) {
170
+ const stored = v.parse(rotationRow, row);
171
+ if (stored.payload.startsWith(`v2:${current.id}:`)) {
172
+ skipped++;
173
+ continue;
174
+ }
175
+ const value = await unseal(stored.key, stored.revision, stored.payload);
176
+ const payload = await seal(stored.key, stored.revision, value);
177
+ if ((await options.db.all(sql`UPDATE vitehub_env_secrets SET payload = ${payload} WHERE namespace = ${namespace} AND key = ${stored.key} AND revision = ${stored.revision} AND payload = ${stored.payload} RETURNING key`)).length) rotated++;
178
+ else skipped++;
179
+ }
180
+ return {
181
+ rotated,
182
+ skipped
183
+ };
184
+ },
185
+ async revisionCondition(key, revision) {
186
+ await initialize();
187
+ return revision === null ? sql`NOT EXISTS (SELECT 1 FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key})` : sql`EXISTS (SELECT 1 FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key} AND revision = ${revision})`;
188
+ },
189
+ async list() {
190
+ await initialize();
191
+ return (await options.db.all(sql`SELECT key, revision, updated_at, preview FROM vitehub_env_secrets WHERE namespace = ${namespace} ORDER BY key`)).map((row) => {
192
+ const stored = v.parse(listRow, row);
193
+ return {
194
+ key: stored.key,
195
+ revision: stored.revision,
196
+ updatedAt: stored.updated_at,
197
+ ...stored.preview ? { preview: stored.preview } : {}
198
+ };
199
+ });
200
+ },
201
+ async remove(key) {
202
+ await initialize();
203
+ return (await options.db.all(sql`DELETE FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key} RETURNING revision`)).length > 0;
204
+ },
205
+ secrets: {
206
+ async inspect(key) {
207
+ const stored = await row(key);
208
+ return stored ? {
209
+ revision: stored.revision,
210
+ updatedAt: stored.updated_at,
211
+ ...stored.preview ? { preview: stored.preview } : {}
212
+ } : void 0;
213
+ },
214
+ async read(key) {
215
+ const stored = await row(key);
216
+ if (!stored) return;
217
+ return {
218
+ value: await unseal(key, stored.revision, stored.payload),
219
+ revision: stored.revision
220
+ };
221
+ },
222
+ async replace({ key, value, expectedRevision }) {
223
+ await initialize();
224
+ const revision = crypto.randomUUID();
225
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
226
+ const payload = await seal(key, revision, value);
227
+ const preview = options.previews && value.length > 12 && /^[A-Za-z0-9_.-]+$/.test(value) ? `${value.slice(0, 4)}••••${value.slice(-4)}` : null;
228
+ const written = expectedRevision === null ? await options.db.all(sql`INSERT INTO vitehub_env_secrets (namespace, key, payload, revision, updated_at, preview) VALUES (${namespace}, ${key}, ${payload}, ${revision}, ${updatedAt}, ${preview}) ON CONFLICT (namespace, key) DO NOTHING RETURNING revision`) : await options.db.all(sql`UPDATE vitehub_env_secrets SET payload = ${payload}, revision = ${revision}, updated_at = ${updatedAt}, preview = ${preview} WHERE namespace = ${namespace} AND key = ${key} AND revision = ${expectedRevision} RETURNING revision`);
229
+ if (!written.length) throw envBridgeError("conflict");
230
+ if (written.length !== 1 || v.parse(revisionRow, written[0]).revision !== revision) throw envBridgeError("invalid");
231
+ return {
232
+ revision,
233
+ updatedAt,
234
+ activation: "next-resolution",
235
+ ...preview ? { preview } : {}
236
+ };
237
+ }
238
+ },
239
+ access: {
240
+ async append(event) {
241
+ await initialize();
242
+ await options.db.run(sql`INSERT INTO vitehub_env_activity (namespace, key, id, payload) VALUES (${namespace}, ${event.key}, ${event.id}, ${JSON.stringify(event)})`);
243
+ },
244
+ async activity({ key, before, limit }) {
245
+ await initialize();
246
+ return (await options.db.all(sql`SELECT payload, id FROM vitehub_env_activity WHERE namespace = ${namespace} AND key = ${key} ${before ? sql`AND sequence < (SELECT sequence FROM vitehub_env_activity WHERE id = ${before} AND namespace = ${namespace} AND key = ${key})` : sql``} ORDER BY sequence DESC LIMIT ${Math.min(Math.max(limit, 1), 100)}`)).map((row) => {
247
+ const stored = v.parse(activityRow, row);
248
+ const event = v.parse(activity, parseStoredJson(stored.payload));
249
+ if (event.key !== key || event.id !== stored.id) throw envBridgeError("invalid");
250
+ return event;
251
+ });
252
+ },
253
+ async grants(key) {
254
+ await initialize();
255
+ return (await options.db.all(sql`SELECT payload, actor_kind, actor_id FROM vitehub_env_grants WHERE namespace = ${namespace} AND key = ${key} ORDER BY actor_kind, actor_id`)).map((row) => {
256
+ const stored = v.parse(grantRow, row);
257
+ const access = v.parse(grant, parseStoredJson(stored.payload));
258
+ if (access.key !== key || access.actor.kind !== stored.actor_kind || access.actor.id !== stored.actor_id) throw envBridgeError("invalid");
259
+ return access;
260
+ });
261
+ },
262
+ async setGrant(grant) {
263
+ await initialize();
264
+ await options.db.run(sql`INSERT INTO vitehub_env_grants (namespace, key, actor_kind, actor_id, payload) VALUES (${namespace}, ${grant.key}, ${grant.actor.kind}, ${grant.actor.id}, ${JSON.stringify(grant)}) ON CONFLICT (namespace, key, actor_kind, actor_id) DO UPDATE SET payload = excluded.payload`);
265
+ },
266
+ async revokeGrant(actor, key) {
267
+ await initialize();
268
+ await options.db.run(sql`DELETE FROM vitehub_env_grants WHERE namespace = ${namespace} AND key = ${key} AND actor_kind = ${actor.kind} AND actor_id = ${actor.id}`);
269
+ }
270
+ }
271
+ };
272
+ }
273
+ //#endregion
274
+ export { createDatabaseEnvStore, listDatabaseEnvNamespaces };
@@ -0,0 +1,58 @@
1
+ import { F as EnvTypedVariableOptions, L as EnvVariableDeclaration, M as EnvSource, P as EnvSourceResolver, R as EnvVariableOptions, j as EnvSchemaModuleReference } from "./bridge-Cs9YfQWk.js";
2
+ //#region src/core/declarations.d.ts
3
+ type EnvListItem = boolean | number | string;
4
+ interface StandardSchemaLike {
5
+ "~standard": {
6
+ validate: (value: unknown) => unknown;
7
+ };
8
+ }
9
+ interface EnvNamespace {
10
+ (options?: EnvVariableOptions): EnvVariableDeclaration;
11
+ /** Parse `true`, `false`, `1`, or `0` into a boolean. */
12
+ boolean: (options?: EnvTypedVariableOptions<boolean>) => EnvVariableDeclaration;
13
+ buildTimestamp: () => EnvSource;
14
+ custom: (label: string, resolver: EnvSourceResolver) => EnvSource;
15
+ /** Accept only the listed strings. The values are public metadata, so an enum cannot be secret. */
16
+ enum: <const TValues extends readonly [string, ...string[]]>(values: TValues, options?: EnvTypedVariableOptions<TValues[number]> & {
17
+ secret?: never;
18
+ }) => EnvVariableDeclaration;
19
+ /** The current branch: `GIT_BRANCH`, then `GITHUB_HEAD_REF`, then `GITHUB_REF_NAME` on a GitHub branch ref, then local Git. */
20
+ gitBranch: () => EnvSource;
21
+ /** The current commit SHA: `GIT_SHA`, then `GITHUB_SHA`, then local Git. `short` keeps 7 characters of a CI value. */
22
+ gitCommit: (options?: {
23
+ short?: boolean;
24
+ }) => EnvSource;
25
+ /** The current tag, or `undefined`: `GIT_TAG`, then `GITHUB_REF_NAME` on a GitHub tag ref, then local Git. */
26
+ gitTag: () => EnvSource;
27
+ /**
28
+ * Parse a JSON value. In `env.server`, validate it with `env.json(env.schemaFrom(module, exportName))`.
29
+ * With `mode: "build"`, pass the Standard Schema itself. Without a schema, the value is `unknown`.
30
+ */
31
+ json: {
32
+ (options?: EnvTypedVariableOptions<unknown>): EnvVariableDeclaration;
33
+ (schema: EnvSchemaModuleReference | StandardSchemaLike, options?: EnvTypedVariableOptions<unknown>): EnvVariableDeclaration;
34
+ };
35
+ /**
36
+ * Parse a list separated by commas or line breaks. Items are trimmed and empty items are dropped. Pass `env.number()`, `env.boolean()`,
37
+ * or `env.enum()` to parse each item, for example `env.list(env.number())`.
38
+ */
39
+ list: {
40
+ (options?: EnvTypedVariableOptions<readonly EnvListItem[]>): EnvVariableDeclaration;
41
+ (item: EnvVariableDeclaration, options?: EnvTypedVariableOptions<readonly EnvListItem[]>): EnvVariableDeclaration;
42
+ };
43
+ /** Parse a finite number. */
44
+ number: (options?: EnvTypedVariableOptions<number>) => EnvVariableDeclaration;
45
+ packageJson: (path: string) => EnvSource;
46
+ provider: (provider: string, key: string) => EnvSource;
47
+ /**
48
+ * Validate a Server Env value with a Standard Schema exported by a module, for example `env.schemaFrom("./server/env.schema.ts", "apiUrl")`.
49
+ * The server build imports the module, so refinements and transforms run on every resolution.
50
+ */
51
+ schemaFrom: (module: string, exportName?: string) => EnvSchemaModuleReference;
52
+ source: (name: string | string[], options?: {
53
+ canonical?: boolean;
54
+ }) => EnvSource;
55
+ }
56
+ declare const env: EnvNamespace;
57
+ //#endregion
58
+ export { env as t };
@@ -0,0 +1,56 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ /** A code whose call site passes the message as `why`. Pass the fix as a string literal: the docs catalog reads only literals. */
5
+ const withFix = (fix) => ({
6
+ ...dynamicError,
7
+ fix
8
+ });
9
+ const envErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
10
+ docsBase: "https://vitehub.dev/docs/env/diagnostics",
11
+ codes: {
12
+ ENV_R0001: withFix("Change the value so that it matches the type of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
13
+ ENV_R0002: withFix("Pass one or more variable names, for example `env.source('DATABASE_URL')`."),
14
+ ENV_R0003: withFix("Use a key of `vitehub({ env: { providers } })` or `hubEnv({ providers })` as the provider name, for example `env.provider('vault', 'db/password')`."),
15
+ ENV_R0004: withFix("Pass the key that the provider reads as the second argument, for example `env.provider('vault', 'db/password')`."),
16
+ ENV_R0005: withFix("Pass one plain options object, for example `env({ secret: true })`."),
17
+ ENV_R0006: withFix("Remove `required`: a value is required by default. Set `optional: true` for a value that can be missing, or a `default` for a fallback value, not both."),
18
+ ENV_R0008: withFix("Change the Env declaration at the path in the error details, as the message says."),
19
+ ENV_R0009: withFix("Load Server Env with `await loadServerEnv()`, or run the code in `runWithServerEnv()`. A provider value cannot be read without `await`."),
20
+ ENV_R0010: withFix("Give the variable a value at its source: set it in `.env` or in the host environment, or return it from the provider or the custom source. Or set `optional: true` on the declaration, or a `default` if the variable is not secret. Run `vitehub env check` to list the missing variables."),
21
+ ENV_R0011: withFix("Change the value at its source, or the `default` of the declaration, so that it matches the type of the variable. The message names each issue. If the message names a provider, make its `read()` return a plain object with a value for each key, not a getter."),
22
+ ENV_R0012: withFix("Make package.json contain one JSON object."),
23
+ ENV_R0013: withFix("Pass an object with a `read({ env, keys, signal })` method to `defineEnvProvider()`."),
24
+ ENV_R0014: withFix("Use a schema that validates without a Promise for this variable."),
25
+ ENV_R0015: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
26
+ ENV_R0016: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
27
+ ENV_R0017: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
28
+ ENV_R0018: withFix("Change the value so that it matches the schema of the variable. The value comes from `.env`, the host environment, a source, a provider, or the `default` of the declaration. The message names each issue."),
29
+ ENV_R0019: withFix("Make the provider module default-export `defineEnvProvider({ read })`, and list it in `vitehub({ env: { providers } })` or `hubEnv({ providers })`. If you call `loadServerEnv()` directly, pass the provider in `options.providers`."),
30
+ ENV_R0020: withFix("The caller aborted the load. Load Server Env again with a signal that is not aborted."),
31
+ ENV_R0021: withFix("This is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message and your Vite config."),
32
+ ENV_R0022: withFix("Pass unique, non-empty strings, for example `env.enum(['development', 'production'])`."),
33
+ ENV_R0023: withFix("Change the `default` so that it matches the schema, for example a number for `env.number()`."),
34
+ ENV_R0025: withFix("Put a stage name after `--stage`, for example `vitehub env check --stage production`."),
35
+ ENV_R0026: withFix("Remove the option. `vitehub env <command> --help` lists the options."),
36
+ ENV_R0027: withFix("Add `vitehub()` or `hubEnv()` to the Vite plugins of the selected stage."),
37
+ ENV_R0028: withFix("This is a ViteHub bug. Report it at https://github.com/vite-hub/vitehub/issues with the message and your Vite config."),
38
+ ENV_R0029: withFix("Pass a non-empty module specifier and an export name that is a JavaScript identifier, for example `env.schemaFrom('./server/env.schema.ts', 'apiUrl')`. Use `env.schemaFrom()` only in `env.server`. Elsewhere, pass the schema object itself."),
39
+ ENV_R0030: withFix("Configure Vite's SSR environment with a RunnableDevEnvironment so Env can import its server module."),
40
+ ENV_B0001: withFix("Add `vitehub()` or `hubEnv()` to the Vite plugins once. If it is there, report a ViteHub bug at https://github.com/vite-hub/vitehub/issues with your Vite config."),
41
+ ENV_B0002: withFix("Rename the key in `vitehub({ env: { providers } })` or `hubEnv({ providers })`, for example `vault` or `aws_secrets`. Use at most 64 characters."),
42
+ ENV_B0003: withFix("Set the provider to a module specifier, for example `'./server/env-provider.ts'` or a package name."),
43
+ ENV_B0004: withFix("Use a relative path, a normal absolute path, or a package name for the provider module."),
44
+ ENV_B0005: withFix("Add the provider to `vitehub({ env: { providers } })` or `hubEnv({ providers })`, or use a configured provider name in `env.provider()`."),
45
+ ENV_B0006: withFix("Change the env-spec schema file at the file and line that the message names, so that it follows the env-spec format."),
46
+ ENV_B0007: withFix("Stop other Vite processes of this project. If none runs, delete `.vitehub/env/secret.lock` and run the command again."),
47
+ ENV_JSON_SCHEMA_INVALID: withFix("In `env.server`, export the Standard Schema from a module and pass `env.json(env.schemaFrom('./server/env.schema.ts', 'settings'))`. With `mode: 'build'`, pass the schema object itself. Without a schema, call `env.json()` or `env.json({ default: {} })`."),
48
+ ENV_LIST_ITEM_INVALID: withFix("Pass the item parser without options, for example `env.list(env.number())` or `env.list(env.enum(['a', 'b']))`, and put `default`, `secret`, `source`, or `optional` on the list: `env.list(env.number(), { default: [1] })`."),
49
+ ENV_NOT_GENERATED: {
50
+ why: ({ accessor }) => `\`${accessor}()\` ran outside a Vite build, so ViteHub did not generate the Env registry that it reads.`,
51
+ fix: "Run the code through `vite dev`, `vite build`, or a framework that uses them, with `vitehub()` and Env on. A test that calls it needs the Vite plugin too."
52
+ }
53
+ }
54
+ });
55
+ //#endregion
56
+ export { envErrorDiagnostics as t };