@vite-hub/env 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +125 -5
  2. package/dist/access-B3qzBHye.js +54 -0
  3. package/dist/auth.d.ts +32 -0
  4. package/dist/auth.js +44 -0
  5. package/dist/bridge-CdNdTN1V.d.ts +374 -0
  6. package/dist/bridge-error-CFuU5zIz.js +65 -0
  7. package/dist/bridge.d.ts +2 -0
  8. package/dist/bridge.js +192 -0
  9. package/dist/cli-CMQPQbii.js +487 -0
  10. package/dist/cli-DEwcUIe0.d.ts +81 -0
  11. package/dist/cli.d.ts +41 -0
  12. package/dist/cli.js +2 -0
  13. package/dist/database.d.ts +21 -0
  14. package/dist/database.js +183 -0
  15. package/dist/declarations-CiRdb1qP.d.ts +32 -0
  16. package/dist/declarations-DAVgctKD.js +236 -0
  17. package/dist/error-diagnostics-CrxjYNYr.js +43 -0
  18. package/dist/http.d.ts +2 -0
  19. package/dist/http.js +122 -0
  20. package/dist/index.d.ts +6 -6
  21. package/dist/index.js +4 -4
  22. package/dist/internal/agent.d.ts +5 -0
  23. package/dist/internal/agent.js +22 -0
  24. package/dist/internal/connections.d.ts +18 -0
  25. package/dist/internal/connections.js +31 -0
  26. package/dist/presets.d.ts +15 -6
  27. package/dist/presets.js +21 -2
  28. package/dist/provider.d.ts +3 -4
  29. package/dist/provider.js +2 -1
  30. package/dist/schema.d.ts +5 -6
  31. package/dist/schema.js +26 -8
  32. package/dist/seal.d.ts +14 -0
  33. package/dist/seal.js +49 -0
  34. package/dist/server-DufVswRJ.js +670 -0
  35. package/dist/server.d.ts +23 -6
  36. package/dist/server.js +2 -3
  37. package/dist/values-D_r6V774.js +148 -0
  38. package/dist/virtual-module.d.ts +7 -3
  39. package/dist/virtual.d.ts +1 -1
  40. package/dist/vite.d.ts +27 -14
  41. package/dist/vite.js +840 -273
  42. package/package.json +81 -17
  43. package/dist/declarations-CoMmvRqH.js +0 -159
  44. package/dist/declarations-U6P3rvxC.d.ts +0 -24
  45. package/dist/errors-C4Xcs6Fi.js +0 -121
  46. package/dist/server-C16sFc1E.js +0 -303
  47. package/dist/types-CsB6DTGE.d.ts +0 -190
@@ -0,0 +1,183 @@
1
+ import { t as envBridgeError } from "./bridge-error-CFuU5zIz.js";
2
+ import { importSealKey, seal, sealedPayloadPattern, unseal } from "./seal.js";
3
+ import * as v from "valibot";
4
+ import { sql } from "drizzle-orm";
5
+ //#region src/database.ts
6
+ const identifier = v.pipe(v.string(), v.minLength(1), v.maxLength(512), v.regex(/^[^\u0000-\u001f]+$/));
7
+ const actor = v.object({
8
+ id: identifier,
9
+ kind: v.picklist([
10
+ "user",
11
+ "agent",
12
+ "service"
13
+ ])
14
+ });
15
+ const permission = v.picklist([
16
+ "inspect",
17
+ "preview",
18
+ "replace",
19
+ "use"
20
+ ]);
21
+ const timestamp = v.pipe(v.string(), v.isoTimestamp());
22
+ const activity = v.object({
23
+ id: identifier,
24
+ operationId: identifier,
25
+ timestamp,
26
+ actor,
27
+ key: identifier,
28
+ action: v.picklist([
29
+ "inspect",
30
+ "preview",
31
+ "replace",
32
+ "resolve",
33
+ "use",
34
+ "grant",
35
+ "revoke"
36
+ ]),
37
+ outcome: v.picklist([
38
+ "started",
39
+ "succeeded",
40
+ "failed",
41
+ "denied"
42
+ ]),
43
+ revision: v.optional(identifier),
44
+ operation: v.optional(identifier),
45
+ target: v.optional(actor),
46
+ permissions: v.optional(v.array(permission)),
47
+ traceId: v.optional(v.string()),
48
+ invocationId: v.optional(v.string())
49
+ });
50
+ const grant = v.object({
51
+ actor,
52
+ key: identifier,
53
+ permissions: v.pipe(v.array(permission), v.minLength(1))
54
+ });
55
+ const secretRow = v.object({
56
+ payload: v.pipe(v.string(), v.regex(sealedPayloadPattern)),
57
+ revision: identifier,
58
+ updated_at: timestamp,
59
+ preview: v.nullable(v.string())
60
+ });
61
+ const activityRow = v.object({
62
+ payload: v.string(),
63
+ id: identifier
64
+ });
65
+ const grantRow = v.object({
66
+ payload: v.string(),
67
+ actor_kind: v.picklist([
68
+ "user",
69
+ "agent",
70
+ "service"
71
+ ]),
72
+ actor_id: identifier
73
+ });
74
+ const revisionRow = v.object({ revision: identifier });
75
+ function parseStoredJson(payload) {
76
+ try {
77
+ return JSON.parse(payload);
78
+ } catch {
79
+ throw envBridgeError("invalid");
80
+ }
81
+ }
82
+ /** Persistent encrypted values, activity, and grants on a ViteHub SQLite/Drizzle database. */
83
+ function createDatabaseEnvStore(options) {
84
+ if (options.encryptionKey.byteLength !== 32) throw envBridgeError("invalid");
85
+ const namespace = options.namespace ?? "default";
86
+ const encryptionKey = importSealKey(options.encryptionKey);
87
+ let ready;
88
+ const initialize = () => ready ??= (async () => {
89
+ await options.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))`);
90
+ await options.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)`);
91
+ await options.db.run(sql`CREATE INDEX IF NOT EXISTS vitehub_env_activity_key ON vitehub_env_activity (namespace, key, sequence)`);
92
+ await options.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))`);
93
+ })().catch((error) => {
94
+ ready = void 0;
95
+ throw error;
96
+ });
97
+ async function row(key) {
98
+ await initialize();
99
+ const stored = (await options.db.all(sql`SELECT payload, revision, updated_at, preview FROM vitehub_env_secrets WHERE namespace = ${namespace} AND key = ${key}`))[0];
100
+ return stored === void 0 ? void 0 : v.parse(secretRow, stored);
101
+ }
102
+ function aad(key, revision) {
103
+ return new TextEncoder().encode(JSON.stringify([
104
+ namespace,
105
+ key,
106
+ revision
107
+ ]));
108
+ }
109
+ return {
110
+ async revisionCondition(key, revision) {
111
+ await initialize();
112
+ 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})`;
113
+ },
114
+ secrets: {
115
+ async inspect(key) {
116
+ const stored = await row(key);
117
+ return stored ? {
118
+ revision: stored.revision,
119
+ updatedAt: stored.updated_at,
120
+ ...stored.preview ? { preview: stored.preview } : {}
121
+ } : void 0;
122
+ },
123
+ async read(key) {
124
+ const stored = await row(key);
125
+ if (!stored) return;
126
+ return {
127
+ value: await unseal(await encryptionKey, aad(key, stored.revision), stored.payload),
128
+ revision: stored.revision
129
+ };
130
+ },
131
+ async replace({ key, value, expectedRevision }) {
132
+ await initialize();
133
+ const revision = crypto.randomUUID();
134
+ const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
135
+ const payload = await seal(await encryptionKey, aad(key, revision), value);
136
+ const preview = options.previews && value.length > 12 && /^[A-Za-z0-9_.-]+$/.test(value) ? `${value.slice(0, 4)}••••${value.slice(-4)}` : null;
137
+ 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`);
138
+ if (!written.length) throw envBridgeError("conflict");
139
+ if (written.length !== 1 || v.parse(revisionRow, written[0]).revision !== revision) throw envBridgeError("invalid");
140
+ return {
141
+ revision,
142
+ updatedAt,
143
+ activation: "next-resolution",
144
+ ...preview ? { preview } : {}
145
+ };
146
+ }
147
+ },
148
+ access: {
149
+ async append(event) {
150
+ await initialize();
151
+ await options.db.run(sql`INSERT INTO vitehub_env_activity (namespace, key, id, payload) VALUES (${namespace}, ${event.key}, ${event.id}, ${JSON.stringify(event)})`);
152
+ },
153
+ async activity({ key, before, limit }) {
154
+ await initialize();
155
+ 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) => {
156
+ const stored = v.parse(activityRow, row);
157
+ const event = v.parse(activity, parseStoredJson(stored.payload));
158
+ if (event.key !== key || event.id !== stored.id) throw envBridgeError("invalid");
159
+ return event;
160
+ });
161
+ },
162
+ async grants(key) {
163
+ await initialize();
164
+ 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) => {
165
+ const stored = v.parse(grantRow, row);
166
+ const access = v.parse(grant, parseStoredJson(stored.payload));
167
+ if (access.key !== key || access.actor.kind !== stored.actor_kind || access.actor.id !== stored.actor_id) throw envBridgeError("invalid");
168
+ return access;
169
+ });
170
+ },
171
+ async setGrant(grant) {
172
+ await initialize();
173
+ 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`);
174
+ },
175
+ async revokeGrant(actor, key) {
176
+ await initialize();
177
+ 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}`);
178
+ }
179
+ }
180
+ };
181
+ }
182
+ //#endregion
183
+ export { createDatabaseEnvStore };
@@ -0,0 +1,32 @@
1
+ import { E as EnvSource, M as EnvVariableOptions, O as EnvSourceResolver, j as EnvVariableDeclaration, k as EnvTypedVariableOptions } from "./bridge-CdNdTN1V.js";
2
+ //#region src/core/declarations.d.ts
3
+ interface EnvNamespace {
4
+ (options?: EnvVariableOptions): EnvVariableDeclaration;
5
+ /** Parse `true`, `false`, `1`, or `0` into a boolean. */
6
+ boolean: (options?: EnvTypedVariableOptions<boolean>) => EnvVariableDeclaration;
7
+ buildTimestamp: () => EnvSource;
8
+ custom: (label: string, resolver: EnvSourceResolver) => EnvSource;
9
+ /** Accept only the listed strings. The values are public metadata, so an enum cannot be secret. */
10
+ enum: <const TValues extends readonly [string, ...string[]]>(values: TValues, options?: Omit<EnvTypedVariableOptions<TValues[number]>, "secret">) => EnvVariableDeclaration;
11
+ gitBranch: () => EnvSource;
12
+ gitCommit: (options?: {
13
+ short?: boolean;
14
+ }) => EnvSource;
15
+ gitRef: () => EnvSource;
16
+ gitSha: (options?: {
17
+ short?: boolean;
18
+ }) => EnvSource;
19
+ gitTag: () => EnvSource;
20
+ /** Parse a finite number. */
21
+ number: (options?: EnvTypedVariableOptions<number>) => EnvVariableDeclaration;
22
+ packageJson: (path: string) => EnvSource;
23
+ provider: (provider: string, key: string) => EnvSource;
24
+ source: (name: string | string[], options?: {
25
+ canonical?: boolean;
26
+ skipEmpty?: boolean;
27
+ }) => EnvSource;
28
+ variable: (options?: EnvVariableOptions) => EnvVariableDeclaration;
29
+ }
30
+ declare const env: EnvNamespace;
31
+ //#endregion
32
+ export { env as t };
@@ -0,0 +1,236 @@
1
+ import { t as envErrorDiagnostics } from "./error-diagnostics-CrxjYNYr.js";
2
+ import { i as stringValueSchema, n as parseEnvValue, o as hasRuntimeType, s as isRuntimeRecord, t as envValueTypeName } from "./values-D_r6V774.js";
3
+ //#region src/core/declarations.ts
4
+ const runtimeSchemaProperty = "__vitehubRuntimeSchema";
5
+ const runtimeSchemaToken = getRuntimeSchemaToken();
6
+ const runtimeSchemaParsers = /* @__PURE__ */ new WeakMap();
7
+ const runtimeSchemas = /* @__PURE__ */ new WeakMap();
8
+ function createRuntimeValueSchema(valueSchema) {
9
+ const safeParse = (input) => {
10
+ const result = parseEnvValue(valueSchema, input);
11
+ return result.success ? result : {
12
+ error: envErrorDiagnostics.ENV_R0001({ message: result.message }),
13
+ success: false
14
+ };
15
+ };
16
+ runtimeSchemaParsers.set(safeParse, valueSchema);
17
+ return {
18
+ [runtimeSchemaProperty]: runtimeSchemaToken,
19
+ safeParse
20
+ };
21
+ }
22
+ const defaultStringSchema = createRuntimeValueSchema(stringValueSchema);
23
+ const booleanSchema = createRuntimeValueSchema(Object.freeze({ kind: "boolean" }));
24
+ const numberSchema = createRuntimeValueSchema(Object.freeze({ kind: "number" }));
25
+ function source(name, options = {}) {
26
+ const names = Array.isArray(name) ? name : [name];
27
+ if (!names.length || names.some((value) => typeof value !== "string" || !value.trim())) throw envErrorDiagnostics.ENV_R0002({ message: "env.source() requires one or more non-empty env variable names." });
28
+ const normalized = names.map((value) => value.trim());
29
+ return {
30
+ kind: "env",
31
+ label: `env:${normalized.join("|")}`,
32
+ name: normalized[0],
33
+ ...options.canonical === false ? { canonical: false } : {},
34
+ ...normalized.length > 1 ? { names: normalized } : {},
35
+ ...options.skipEmpty ? { skipEmpty: true } : {},
36
+ serializable: true
37
+ };
38
+ }
39
+ function custom(label, resolver) {
40
+ return {
41
+ kind: "custom",
42
+ label,
43
+ resolver,
44
+ serializable: false
45
+ };
46
+ }
47
+ function gitBranch() {
48
+ return {
49
+ kind: "git-branch",
50
+ label: "git:branch",
51
+ serializable: true
52
+ };
53
+ }
54
+ function gitCommit(options = {}) {
55
+ return {
56
+ kind: "git-commit",
57
+ label: "git:commit",
58
+ serializable: true,
59
+ short: options.short
60
+ };
61
+ }
62
+ function gitRef() {
63
+ return {
64
+ kind: "git-ref",
65
+ label: "git:ref",
66
+ serializable: true
67
+ };
68
+ }
69
+ function gitSha(options = {}) {
70
+ return {
71
+ kind: "git-sha",
72
+ label: "git:sha",
73
+ serializable: true,
74
+ short: options.short
75
+ };
76
+ }
77
+ function gitTag() {
78
+ return {
79
+ kind: "git-tag",
80
+ label: "git:tag",
81
+ serializable: true
82
+ };
83
+ }
84
+ function buildTimestamp() {
85
+ return {
86
+ kind: "build-timestamp",
87
+ label: "build:timestamp",
88
+ serializable: true
89
+ };
90
+ }
91
+ function packageJson(path) {
92
+ return {
93
+ kind: "package-json",
94
+ label: `package.json:${path}`,
95
+ path,
96
+ serializable: true
97
+ };
98
+ }
99
+ function provider(provider, key) {
100
+ if (typeof provider !== "string" || !/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(provider.trim())) throw envErrorDiagnostics.ENV_R0003({ message: "env.provider() requires a provider name that starts with a letter and contains only letters, numbers, underscores, or hyphens." });
101
+ if (typeof key !== "string" || !key.trim() || key.length > 512) throw envErrorDiagnostics.ENV_R0004({ message: "env.provider() requires a non-empty provider key." });
102
+ return {
103
+ key: key.trim(),
104
+ kind: "provider",
105
+ label: "provider",
106
+ provider: provider.trim(),
107
+ serializable: true
108
+ };
109
+ }
110
+ function variable(options = {}) {
111
+ options = readDeclarationOptions(options);
112
+ return createDeclaration(options, options.schema ?? defaultStringSchema, options.type);
113
+ }
114
+ function typedVariable(schema, options) {
115
+ options = readDeclarationOptions(options);
116
+ const valueSchema = runtimeSchemaParsers.get(schema.safeParse);
117
+ return createDeclaration(options, schema, valueSchema && envValueTypeName(valueSchema));
118
+ }
119
+ /** Create an internal built-in declaration whose parser survives runtime serialization. */
120
+ function descriptorVariable(valueSchema, options) {
121
+ return typedVariable(createRuntimeValueSchema(valueSchema), options);
122
+ }
123
+ function booleanVariable(options = {}) {
124
+ return typedVariable(booleanSchema, options);
125
+ }
126
+ function numberVariable(options = {}) {
127
+ return typedVariable(numberSchema, options);
128
+ }
129
+ function enumVariable(values, options = {}) {
130
+ if (!Array.isArray(values) || !values.length || values.some((value) => !hasRuntimeType(value, "string") || !value) || new Set(values).size !== values.length) throw envErrorDiagnostics.ENV_R0022({ message: "env.enum() requires one or more unique non-empty strings." });
131
+ return typedVariable(createRuntimeValueSchema(Object.freeze({
132
+ kind: "enum",
133
+ values: Object.freeze([...values])
134
+ })), options);
135
+ }
136
+ function isInspectableRecord(value) {
137
+ try {
138
+ if (!isRuntimeRecord(value)) return false;
139
+ Reflect.ownKeys(value);
140
+ return true;
141
+ } catch {
142
+ return false;
143
+ }
144
+ }
145
+ function readDeclarationOptions(options) {
146
+ if (!isInspectableRecord(options)) throw envErrorDiagnostics.ENV_R0005({ message: "env() only accepts a single options object." });
147
+ let snapshot;
148
+ try {
149
+ snapshot = {
150
+ default: options.default,
151
+ mode: options.mode,
152
+ optional: options.optional,
153
+ required: options.required,
154
+ schema: options.schema,
155
+ secret: options.secret,
156
+ source: options.source,
157
+ type: options.type
158
+ };
159
+ } catch {
160
+ throw envErrorDiagnostics.ENV_R0005({ message: "env() only accepts a single options object." });
161
+ }
162
+ if (snapshot.optional && snapshot.required !== void 0) throw envErrorDiagnostics.ENV_R0006({ message: "env() cannot use both optional and required." });
163
+ return snapshot;
164
+ }
165
+ function createDeclaration(options, schema, type) {
166
+ const required = options.optional ? false : options.required ?? true;
167
+ const source = typeof options.source === "function" ? custom("custom", options.source) : options.source;
168
+ const declaration = {
169
+ default: options.default,
170
+ kind: "env-variable",
171
+ mode: options.mode ?? "runtime",
172
+ required,
173
+ schema,
174
+ secret: options.secret ?? false,
175
+ source,
176
+ type
177
+ };
178
+ if (isRuntimeValueSchema(schema)) {
179
+ runtimeSchemas.set(declaration, schema);
180
+ Object.defineProperty(declaration, runtimeSchemaProperty, {
181
+ enumerable: true,
182
+ value: runtimeSchemaToken
183
+ });
184
+ }
185
+ return declaration;
186
+ }
187
+ const env = Object.assign(variable, {
188
+ boolean: booleanVariable,
189
+ buildTimestamp,
190
+ custom,
191
+ enum: enumVariable,
192
+ gitBranch,
193
+ gitCommit,
194
+ gitRef,
195
+ gitSha,
196
+ gitTag,
197
+ number: numberVariable,
198
+ packageJson,
199
+ provider,
200
+ source,
201
+ variable
202
+ });
203
+ /** Return the serializable value schema of a declaration created by `env()`, `env.boolean()`, `env.number()`, or `env.enum()`. */
204
+ function runtimeValueSchema(declaration) {
205
+ const schema = declaration.schema;
206
+ if (runtimeSchemas.get(declaration) === schema && isRuntimeValueSchema(schema)) return runtimeSchemaParsers.get(schema.safeParse);
207
+ try {
208
+ if (Object.getOwnPropertyDescriptor(declaration, runtimeSchemaProperty)?.value !== runtimeSchemaToken || !isRuntimeRecord(schema)) return void 0;
209
+ if (Object.getOwnPropertyDescriptor(schema, runtimeSchemaProperty)?.value !== runtimeSchemaToken || !hasOnlyRuntimeSchemaKeys(schema)) return void 0;
210
+ const safeParse = Object.getOwnPropertyDescriptor(schema, "safeParse")?.value;
211
+ return hasRuntimeType(safeParse, "function") ? runtimeSchemaParsers.get(safeParse) : void 0;
212
+ } catch {
213
+ return;
214
+ }
215
+ }
216
+ function isRuntimeValueSchema(schema) {
217
+ try {
218
+ return isRuntimeRecord(schema) && hasRuntimeType(schema.safeParse, "function") && runtimeSchemaParsers.has(schema.safeParse);
219
+ } catch {
220
+ return false;
221
+ }
222
+ }
223
+ function getRuntimeSchemaToken() {
224
+ const tokenKey = Symbol.for("vitehub.env.runtimeSchemaToken");
225
+ const globalScope = globalThis;
226
+ globalScope[tokenKey] ??= `schema:${Math.random().toString(36).slice(2)}`;
227
+ return globalScope[tokenKey];
228
+ }
229
+ function hasOnlyRuntimeSchemaKeys(schema) {
230
+ if ("~standard" in schema || "parse" in schema) return false;
231
+ const keys = Reflect.ownKeys(schema);
232
+ const safeParse = Object.getOwnPropertyDescriptor(schema, "safeParse");
233
+ return keys.length === 2 && keys.includes(runtimeSchemaProperty) && keys.includes("safeParse") && hasRuntimeType(safeParse?.value, "function");
234
+ }
235
+ //#endregion
236
+ export { env as n, runtimeValueSchema as r, descriptorVariable as t };
@@ -0,0 +1,43 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const envErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ ENV_R0001: dynamicError,
8
+ ENV_R0002: dynamicError,
9
+ ENV_R0003: dynamicError,
10
+ ENV_R0004: dynamicError,
11
+ ENV_R0005: dynamicError,
12
+ ENV_R0006: dynamicError,
13
+ ENV_R0007: dynamicError,
14
+ ENV_R0008: dynamicError,
15
+ ENV_R0009: dynamicError,
16
+ ENV_R0010: dynamicError,
17
+ ENV_R0011: dynamicError,
18
+ ENV_R0012: dynamicError,
19
+ ENV_R0013: dynamicError,
20
+ ENV_R0014: dynamicError,
21
+ ENV_R0015: dynamicError,
22
+ ENV_R0016: dynamicError,
23
+ ENV_R0017: dynamicError,
24
+ ENV_R0018: dynamicError,
25
+ ENV_R0019: dynamicError,
26
+ ENV_R0020: dynamicError,
27
+ ENV_R0021: dynamicError,
28
+ ENV_R0022: dynamicError,
29
+ ENV_R0023: dynamicError,
30
+ ENV_R0024: dynamicError,
31
+ ENV_R0025: dynamicError,
32
+ ENV_R0026: dynamicError,
33
+ ENV_R0027: dynamicError,
34
+ ENV_R0028: dynamicError,
35
+ ENV_B0001: dynamicError,
36
+ ENV_B0002: dynamicError,
37
+ ENV_B0003: dynamicError,
38
+ ENV_B0004: dynamicError,
39
+ ENV_B0005: dynamicError
40
+ }
41
+ });
42
+ //#endregion
43
+ export { envErrorDiagnostics as t };
package/dist/http.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { G as createEnvBridgeHandler, U as EnvManagement, W as EnvManagementResolver } from "./bridge-CdNdTN1V.js";
2
+ export { EnvManagement, EnvManagementResolver, createEnvBridgeHandler };
package/dist/http.js ADDED
@@ -0,0 +1,122 @@
1
+ import { n as envBridgeErrorBody, r as sanitizeEnvBridgeError, t as envBridgeError } from "./bridge-error-CFuU5zIz.js";
2
+ //#region src/http.ts
3
+ function record(value) {
4
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5
+ }
6
+ function actor(value) {
7
+ if (!record(value) || typeof value.id !== "string" || value.kind !== "user" && value.kind !== "agent" && value.kind !== "service") throw envBridgeError("invalid");
8
+ return {
9
+ id: value.id,
10
+ kind: value.kind
11
+ };
12
+ }
13
+ const permissions = [
14
+ "inspect",
15
+ "preview",
16
+ "replace",
17
+ "use"
18
+ ];
19
+ async function body(request) {
20
+ const reader = request.body?.getReader();
21
+ if (!reader) throw envBridgeError("invalid");
22
+ const decoder = new TextDecoder();
23
+ let size = 0;
24
+ let text = "";
25
+ try {
26
+ while (true) {
27
+ const chunk = await reader.read();
28
+ if (chunk.done) break;
29
+ size += chunk.value.byteLength;
30
+ if (size > 65536) {
31
+ await reader.cancel();
32
+ throw envBridgeError("invalid");
33
+ }
34
+ text += decoder.decode(chunk.value, { stream: true });
35
+ }
36
+ const value = JSON.parse(text + decoder.decode());
37
+ if (!record(value)) throw envBridgeError("invalid");
38
+ return value;
39
+ } catch {
40
+ throw envBridgeError("invalid");
41
+ } finally {
42
+ reader.releaseLock();
43
+ }
44
+ }
45
+ function response(value, status = 200) {
46
+ return Response.json(value, {
47
+ status,
48
+ headers: {
49
+ "cache-control": "no-store",
50
+ "x-content-type-options": "nosniff",
51
+ "x-robots-tag": "noindex, nofollow"
52
+ }
53
+ });
54
+ }
55
+ /** Mount only on a server route. resolve selects declared credentials, never arbitrary store keys. */
56
+ function createEnvBridgeHandler(resolve) {
57
+ return async (request) => {
58
+ if (request.method !== "POST") return response({ message: "Method not allowed." }, 405);
59
+ const origin = request.headers.get("origin");
60
+ if (origin ? origin !== new URL(request.url).origin : !/^Bearer\s+\S+$/i.test(request.headers.get("authorization") ?? "")) return response({ message: "Request origin is not allowed." }, 403);
61
+ try {
62
+ const input = await body(request);
63
+ if (typeof input.path !== "string" || input.path.length > 256) throw envBridgeError("invalid");
64
+ const target = resolve(input.path);
65
+ if (!target) return response({ message: "This variable is not managed." }, 404);
66
+ const context = await target.management.authenticate(request);
67
+ if (!context) return response({ message: "Authentication required." }, 401);
68
+ const { bridge } = target.management;
69
+ const key = target.key;
70
+ switch (input.action) {
71
+ case "permissions": return response({
72
+ permissions: await bridge.permissions(context, key),
73
+ admin: Boolean(context.admin && !context.scope)
74
+ });
75
+ case "inspect": return response({
76
+ metadata: await bridge.inspect(context, key) ?? null,
77
+ permissions: await bridge.permissions(context, key),
78
+ admin: Boolean(context.admin && !context.scope)
79
+ });
80
+ case "preview": {
81
+ const metadata = await bridge.preview(context, key);
82
+ return response({ metadata: metadata ? { preview: metadata.preview } : null });
83
+ }
84
+ case "replace": {
85
+ if (typeof input.value !== "string" || !(input.expectedRevision === null || typeof input.expectedRevision === "string")) throw envBridgeError("invalid");
86
+ const result = await bridge.replace(context, {
87
+ key,
88
+ value: input.value,
89
+ expectedRevision: input.expectedRevision
90
+ });
91
+ return response({
92
+ revision: result.revision,
93
+ updatedAt: result.updatedAt,
94
+ activation: result.activation
95
+ });
96
+ }
97
+ case "activity":
98
+ if (input.before !== void 0 && typeof input.before !== "string") throw envBridgeError("invalid");
99
+ return response({ events: await bridge.activity(context, key, input.before) });
100
+ case "grants": return response({ grants: await bridge.grants(context, key) });
101
+ case "grant":
102
+ if (!Array.isArray(input.permissions) || input.permissions.some((value) => !permissions.includes(value))) throw envBridgeError("invalid");
103
+ await bridge.grant(context, {
104
+ actor: actor(input.actor),
105
+ key,
106
+ permissions: input.permissions
107
+ });
108
+ return response({ ok: true });
109
+ case "revoke":
110
+ await bridge.revoke(context, actor(input.actor), key);
111
+ return response({ ok: true });
112
+ default: throw envBridgeError("invalid");
113
+ }
114
+ } catch (error) {
115
+ const safe = sanitizeEnvBridgeError(error);
116
+ const status = safe.code === "ENV_BRIDGE_DENIED" ? 403 : safe.code === "ENV_BRIDGE_CONFLICT" ? 409 : safe.code === "ENV_BRIDGE_INVALID" ? 400 : 503;
117
+ return response(envBridgeErrorBody(safe), status);
118
+ }
119
+ };
120
+ }
121
+ //#endregion
122
+ export { createEnvBridgeHandler };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,11 @@
1
+ import { A as EnvValueSchema, B as ServerEnvInspection, C as EnvProviders, D as EnvSourceContext, E as EnvSource, F as LoadServerEnvOptions, H as ServerEnvInspectionStatus, I as PublicEnv, L as ServerEnv, M as EnvVariableOptions, N as EnvViteConfigOptions, O as EnvSourceResolver, P as EnvViteUserConfig, R as ServerEnvDescription, S as EnvProviderValues, T as EnvRuntimeRegistry, V as ServerEnvInspectionEntry, _ as EnvDiagnostics, b as EnvProvider, g as EnvDiagnosticEntry, h as EnvConfigOptions, j as EnvVariableDeclaration, k as EnvTypedVariableOptions, m as DeepReadonly, v as EnvIntegrationOptions, w as EnvRuntimeConfigOptions, x as EnvProviderContext, y as EnvMode, z as ServerEnvDescriptionEntry } from "./bridge-CdNdTN1V.js";
1
2
  import { t as SecretEnv } from "./secret-C2191nAa.js";
2
- import { C as ServerEnvInspection, S as ServerEnv, T as ServerEnvInspectionStatus, _ as EnvVariableOptions, a as EnvIntegrationOptions, b as LoadServerEnvOptions, c as EnvProviderContext, d as EnvRuntimeConfigOptions, f as EnvRuntimeRegistry, g as EnvVariableDeclaration, h as EnvSourceResolver, i as EnvDiagnostics, l as EnvProviderValues, m as EnvSourceContext, n as EnvConfigOptions, o as EnvMode, p as EnvSource, r as EnvDiagnosticEntry, s as EnvProvider, t as DeepReadonly, u as EnvProviders, v as EnvViteConfigOptions, w as ServerEnvInspectionEntry, x as PublicEnv, y as EnvViteUserConfig } from "./types-CsB6DTGE.js";
3
- import { t as env } from "./declarations-U6P3rvxC.js";
4
- import { openWorkflowEnv } from "./presets.js";
3
+ import { t as env } from "./declarations-CiRdb1qP.js";
4
+ import { openWorkflowEnv, typesafeEnv } from "./presets.js";
5
5
  import { StandardSchemaV1, parseSchema } from "./schema.js";
6
6
  import { defineEnvProvider } from "./provider.js";
7
- import { inspectServerEnv, loadServerEnv, resolveServerEnv } from "./server.js";
7
+ import { describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv } from "./server.js";
8
8
  import { ViteHubError } from "@vite-hub/runtime";
9
-
10
9
  //#region src/core/errors.d.ts
11
10
  declare const envErrorMessages: {
12
11
  readonly ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.";
@@ -30,6 +29,7 @@ interface EnvErrorDetailsByCode {
30
29
  source?: EnvSourceIdentifier;
31
30
  };
32
31
  ENV_RUNTIME_VALUE_INVALID: {
32
+ path?: string;
33
33
  source?: EnvSourceIdentifier;
34
34
  };
35
35
  ENV_SOURCE_FAILED: {
@@ -38,4 +38,4 @@ interface EnvErrorDetailsByCode {
38
38
  }
39
39
  type EnvErrorDetails<TCode extends EnvErrorCode = EnvErrorCode> = EnvErrorDetailsByCode[TCode];
40
40
  //#endregion
41
- export { type DeepReadonly, type EnvConfigOptions, type EnvDiagnosticEntry, type EnvDiagnostics, type EnvErrorCode, type EnvErrorDetails, type EnvIntegrationOptions, type EnvMode, type EnvProvider, type EnvProviderContext, type EnvProviderValues, type EnvProviders, type EnvRuntimeConfigOptions, type EnvRuntimeRegistry, type EnvSource, type EnvSourceContext, type EnvSourceIdentifier, type EnvSourceResolver, type EnvVariableDeclaration, type EnvVariableOptions, type EnvViteConfigOptions, type EnvViteUserConfig, type LoadServerEnvOptions, type PublicEnv, SecretEnv, type ServerEnv, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type StandardSchemaV1, defineEnvProvider, env, inspectServerEnv, loadServerEnv, openWorkflowEnv, parseSchema, resolveServerEnv };
41
+ export { type DeepReadonly, type EnvConfigOptions, type EnvDiagnosticEntry, type EnvDiagnostics, type EnvErrorCode, type EnvErrorDetails, type EnvIntegrationOptions, type EnvMode, type EnvProvider, type EnvProviderContext, type EnvProviderValues, type EnvProviders, type EnvRuntimeConfigOptions, type EnvRuntimeRegistry, type EnvSource, type EnvSourceContext, type EnvSourceIdentifier, type EnvSourceResolver, type EnvTypedVariableOptions, type EnvValueSchema, type EnvVariableDeclaration, type EnvVariableOptions, type EnvViteConfigOptions, type EnvViteUserConfig, type LoadServerEnvOptions, type PublicEnv, SecretEnv, type ServerEnv, type ServerEnvDescription, type ServerEnvDescriptionEntry, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type StandardSchemaV1, defineEnvProvider, describeServerEnv, env, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, openWorkflowEnv, parseSchema, resolveServerEnv, typesafeEnv };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { n as env } from "./declarations-CoMmvRqH.js";
2
- import { openWorkflowEnv } from "./presets.js";
1
+ import { n as env } from "./declarations-DAVgctKD.js";
2
+ import { openWorkflowEnv, typesafeEnv } from "./presets.js";
3
3
  import { parseSchema } from "./schema.js";
4
4
  import { SecretEnv } from "./secret.js";
5
5
  import { defineEnvProvider } from "./provider.js";
6
- import { n as loadServerEnv, r as resolveServerEnv, t as inspectServerEnv } from "./server-C16sFc1E.js";
7
- export { SecretEnv, defineEnvProvider, env, inspectServerEnv, loadServerEnv, openWorkflowEnv, parseSchema, resolveServerEnv };
6
+ import { a as isBlockingServerEnvEntry, i as inspectServerEnv, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv } from "./server-DufVswRJ.js";
7
+ export { SecretEnv, defineEnvProvider, describeServerEnv, env, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, openWorkflowEnv, parseSchema, resolveServerEnv, typesafeEnv };
@@ -0,0 +1,5 @@
1
+ import { K as EnvAttribution, t as EnvAccessContext } from "../bridge-CdNdTN1V.js";
2
+ //#region src/internal/agent.d.ts
3
+ /** Mint only for an identity registered by Agent Definition resolution. Names and copies are untrusted. */
4
+ export declare function agentEnvAccess(agent: unknown, attribution?: EnvAttribution): EnvAccessContext;
5
+ //#endregion