@vite-hub/env 0.5.0 → 0.6.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 (42) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-C5sPO6C2.js → access-DIErLk3w.js} +2 -3
  3. package/dist/{bridge-Cs9YfQWk.d.ts → bridge-BWwIooe0.d.ts} +0 -12
  4. package/dist/{bridge-error-t9bc6xvE.js → bridge-error-DEqzARPJ.js} +1 -2
  5. package/dist/bridge.d.ts +1 -1
  6. package/dist/bridge.js +6 -9
  7. package/dist/{cli-DJtQF4Wi.d.ts → cli-B-LW6l_J.d.ts} +0 -6
  8. package/dist/{cli-BctSFldY.js → cli-BXzUIcnA.js} +19 -25
  9. package/dist/cli.d.ts +3 -6
  10. package/dist/cli.js +1 -2
  11. package/dist/database.d.ts +2 -4
  12. package/dist/database.js +2 -3
  13. package/dist/{declarations-BEL0yvEY.d.ts → declarations-DNjO52_s.d.ts} +1 -3
  14. package/dist/{schema-CnCp0Muw.js → declarations-meg4Rmgd.js} +6 -71
  15. package/dist/{object-DICxAEoH.js → error-diagnostics-5BceFRdD.js} +52 -13
  16. package/dist/{error-diagnostics-CwQGNVnK.js → error-diagnostics-BFzFaXcH.js} +1 -2
  17. package/dist/index.d.ts +3 -13
  18. package/dist/index.js +8 -12
  19. package/dist/internal/agent.d.ts +2 -4
  20. package/dist/internal/agent.js +3 -4
  21. package/dist/internal/connections.d.ts +2 -4
  22. package/dist/internal/connections.js +3 -4
  23. package/dist/internal/server.d.ts +2 -2
  24. package/dist/internal/server.js +1 -2
  25. package/dist/{operation-definition-CI2PJGqu.d.ts → operation-definition-CqZkx1Rm.d.ts} +0 -4
  26. package/dist/{operations-LVaCzpR0.js → operations-BftegDMd.js} +2 -3
  27. package/dist/operations.d.ts +2 -6
  28. package/dist/operations.js +6 -721
  29. package/dist/runtime/public-env.d.ts +2 -4
  30. package/dist/runtime/public-env.js +2 -3
  31. package/dist/runtime/server-env.d.ts +2 -3
  32. package/dist/runtime/server-env.js +2 -3
  33. package/dist/seal.d.ts +1 -3
  34. package/dist/seal.js +1 -2
  35. package/dist/{secret-DJd-fy5T.js → secret-VhbE53Vm.js} +1 -2
  36. package/dist/{server-OvARy_y9.d.ts → server-CPEywepM.d.ts} +1 -11
  37. package/dist/{server-Ct3uvhf9.js → server-pTqnkM7n.js} +209 -152
  38. package/dist/server.d.ts +2 -2
  39. package/dist/server.js +1 -2
  40. package/dist/vite.d.ts +4 -16
  41. package/dist/vite.js +20 -21
  42. package/package.json +12 -10
@@ -1,5 +1,3 @@
1
- import { B as PublicEnv } from "../bridge-Cs9YfQWk.js";
2
- //#region src/runtime/public-env.d.ts
1
+ import { B as PublicEnv } from "../bridge-BWwIooe0.js";
3
2
  /** Reads the declared Public Env. Its values are fixed when the app builds. */
4
- export declare function usePublicEnv(): PublicEnv;
5
- //#endregion
3
+ export declare function usePublicEnv(): PublicEnv;
@@ -1,8 +1,7 @@
1
- import { t as envErrorDiagnostics } from "../error-diagnostics-CwQGNVnK.js";
2
- //#region src/runtime/public-env.ts
1
+ import { t as envErrorDiagnostics } from "../error-diagnostics-BFzFaXcH.js";
2
+ // src/runtime/public-env.ts
3
3
  /** Reads the declared Public Env. Its values are fixed when the app builds. */
4
4
  function usePublicEnv() {
5
5
  throw envErrorDiagnostics.ENV_NOT_GENERATED({ accessor: "usePublicEnv" });
6
6
  }
7
- //#endregion
8
7
  export { usePublicEnv };
@@ -1,6 +1,5 @@
1
- import { G as ServerEnvInspection, H as ServerEnv, U as ServerEnvDescription, V as ReadonlyServerEnv, t as EnvAccessContext } from "../bridge-Cs9YfQWk.js";
1
+ import { G as ServerEnvInspection, H as ServerEnv, U as ServerEnvDescription, V as ReadonlyServerEnv, t as EnvAccessContext } from "../bridge-BWwIooe0.js";
2
2
  import { ViteHubContext } from "@vite-hub/runtime";
3
- //#region src/runtime/server-env.d.ts
4
3
  interface ServerEnvLoadOptions {
5
4
  access?: EnvAccessContext;
6
5
  signal?: AbortSignal;
@@ -19,4 +18,4 @@ export declare function describeServerEnv(): ServerEnvDescription;
19
18
  export declare function deriveSecret(_purpose: string, _event?: ViteHubContext): Promise<string>;
20
19
  /** Answers the Env bridge requests of the Console. */
21
20
  export declare function manageServerEnv(_request: Request): Promise<Response>;
22
- //#endregion
21
+ export {};
@@ -1,5 +1,5 @@
1
- import { t as envErrorDiagnostics } from "../error-diagnostics-CwQGNVnK.js";
2
- //#region src/runtime/server-env.ts
1
+ import { t as envErrorDiagnostics } from "../error-diagnostics-BFzFaXcH.js";
2
+ // src/runtime/server-env.ts
3
3
  function notGenerated(accessor) {
4
4
  throw envErrorDiagnostics.ENV_NOT_GENERATED({ accessor });
5
5
  }
@@ -31,5 +31,4 @@ async function deriveSecret(_purpose, _event) {
31
31
  async function manageServerEnv(_request) {
32
32
  return notGenerated("manageServerEnv");
33
33
  }
34
- //#endregion
35
34
  export { deriveSecret, describeServerEnv, inspectServerEnv, loadServerEnv, manageServerEnv, runWithServerEnv, useServerEnv };
package/dist/seal.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- //#region src/seal.d.ts
2
1
  /** Stored sealed value format: `hex(iv):hex(ciphertext)`. */
3
2
  export declare const sealedPayloadPattern: RegExp;
4
3
  /** An imported AES-GCM key. */
@@ -13,5 +12,4 @@ export declare function sealKeyId(key: Uint8Array): Promise<string>;
13
12
  */
14
13
  export declare function sealWithKey(key: SealKey, additionalData: Uint8Array<ArrayBuffer>, plaintext: string): Promise<string>;
15
14
  /** Decrypts a value from `sealWithKey`. Fails when the key or `additionalData` differs. */
16
- export declare function unsealWithKey(key: SealKey, additionalData: Uint8Array<ArrayBuffer>, payload: string): Promise<string>;
17
- //#endregion
15
+ export declare function unsealWithKey(key: SealKey, additionalData: Uint8Array<ArrayBuffer>, payload: string): Promise<string>;
package/dist/seal.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ViteHubError } from "@vite-hub/runtime";
2
- //#region src/seal.ts
2
+ // src/seal.ts
3
3
  /** Stored sealed value format: `hex(iv):hex(ciphertext)`. */
4
4
  const sealedPayloadPattern = /^[a-f0-9]{24}:(?:[a-f0-9]{2}){16,}$/;
5
5
  function sealError() {
@@ -48,5 +48,4 @@ async function unsealWithKey(key, additionalData, payload) {
48
48
  });
49
49
  return new TextDecoder("utf-8", { ignoreBOM: true }).decode(value);
50
50
  }
51
- //#endregion
52
51
  export { importSealKey, sealKeyId, sealWithKey, sealedPayloadPattern, unsealWithKey };
@@ -1,4 +1,4 @@
1
- //#region src/secret.ts
1
+ // src/secret.ts
2
2
  const redactedSecret = "<redacted>";
3
3
  var SecretEnv = class {
4
4
  #value;
@@ -22,5 +22,4 @@ var SecretEnv = class {
22
22
  Object.defineProperty(SecretEnv.prototype, Symbol.for("nodejs.util.inspect.custom"), { value() {
23
23
  return redactedSecret;
24
24
  } });
25
- //#endregion
26
25
  export { SecretEnv as t };
@@ -1,6 +1,5 @@
1
- import { A as EnvRuntimeRegistry, G as ServerEnvInspection, K as ServerEnvInspectionEntry, Q as SecretEnv, U as ServerEnvDescription, y as DeepReadonly, z as LoadServerEnvOptions } from "./bridge-Cs9YfQWk.js";
1
+ import { A as EnvRuntimeRegistry, G as ServerEnvInspection, K as ServerEnvInspectionEntry, Q as SecretEnv, U as ServerEnvDescription, y as DeepReadonly, z as LoadServerEnvOptions } from "./bridge-BWwIooe0.js";
2
2
  import { Duration, Result, ViteHubContext, ViteHubContext as ViteHubContext$1 } from "@vite-hub/runtime";
3
- //#region src/schema.d.ts
4
3
  interface StandardSchemaResultSuccess<T = unknown> {
5
4
  issues?: undefined;
6
5
  value: T;
@@ -14,8 +13,6 @@ interface StandardSchemaV1<T = unknown> {
14
13
  };
15
14
  }
16
15
  declare function parseSchema(schema: unknown, value: unknown, label: string): unknown;
17
- //#endregion
18
- //#region src/internal/runtime-env.d.ts
19
16
  type RuntimeEnv = Record<string, unknown>;
20
17
  /**
21
18
  * A request event: an H3 event, another event with Standard Context, or a web `Request`. An H3 event matches `{ req }`
@@ -24,8 +21,6 @@ type RuntimeEnv = Record<string, unknown>;
24
21
  type RequestEvent = Request | ViteHubContext | {
25
22
  readonly req: Request;
26
23
  };
27
- //#endregion
28
- //#region src/seal-uses.d.ts
29
24
  /**
30
25
  * A SQLite, libSQL, or D1 Drizzle database, such as `db` from `vite-hub/database`. The uses of a sealed value live
31
26
  * there, because every instance of the app must see the same count. KV cannot take a use atomically.
@@ -33,8 +28,6 @@ type RequestEvent = Request | ViteHubContext | {
33
28
  interface SealUsesDatabase {
34
29
  all: (query: string) => unknown[] | PromiseLike<unknown[]>;
35
30
  }
36
- //#endregion
37
- //#region src/seal-value.d.ts
38
31
  /** The codes that `unseal()` returns. */
39
32
  type UnsealErrorCode = "ENV_SEAL_EXPIRED" | "ENV_SEAL_INVALID" | "ENV_SEAL_SCHEMA_MISMATCH" | "ENV_SEAL_USED_UP" | "ENV_SEAL_WRONG_PURPOSE";
40
33
  interface UnsealOptions {
@@ -100,8 +93,6 @@ declare function seal(purpose: string, value: unknown, options?: SealOptions): P
100
93
  */
101
94
  declare function unseal<T>(purpose: string, sealed: string, options: UnsealSchemaOptions<T>): Promise<Result<T, UnsealErrorCode>>;
102
95
  declare function unseal(purpose: string, sealed: string, options?: UnsealOptions): Promise<Result<unknown, UnsealErrorCode>>;
103
- //#endregion
104
- //#region src/server.d.ts
105
96
  /**
106
97
  * Run `callback` with `env` as the active Cloudflare bindings. Server Env reads them when a call gets no request
107
98
  * event, such as for the module bindings of `cloudflare:workers` outside a request.
@@ -143,5 +134,4 @@ declare function describeServerEnv(registry: EnvRuntimeRegistry): ServerEnvDescr
143
134
  /** Returns whether an inspection entry makes `loadServerEnv()` fail: invalid, provider error, or required and missing. */
144
135
  declare function isBlockingServerEnvEntry(entry: ServerEnvInspectionEntry): boolean;
145
136
  declare function inspectServerEnv(registry: EnvRuntimeRegistry, event?: ViteHubContext, options?: LoadServerEnvOptions): Promise<ServerEnvInspection>;
146
- //#endregion
147
137
  export { parseSchema as C, StandardSchemaV1 as S, unseal as _, describeServerEnv as a, StandardSchemaResultFailure as b, loadServerEnv as c, SealOptions as d, UnsealErrorCode as f, seal as g, createSealing as h, deriveSecret as i, resolveServerEnv as l, UnsealSchemaOptions as m, ViteHubContext$1 as n, inspectServerEnv as o, UnsealOptions as p, bindServerEnvSchemas as r, isBlockingServerEnvEntry as s, DeriveSecretOptions as t, runWithCloudflareEnv as u, SealUsesDatabase as v, StandardSchemaResultSuccess as x, RequestEvent as y };
@@ -1,13 +1,196 @@
1
- import { t as envErrorDiagnostics } from "./error-diagnostics-CwQGNVnK.js";
2
- import { t as SecretEnv } from "./secret-DJd-fy5T.js";
3
- import { r as internalErrorDiagnostics, t as isRecord } from "./object-DICxAEoH.js";
1
+ import { a as isRecordOrFunction, i as isRecord, r as standardResultIssues, t as internalErrorDiagnostics } from "./error-diagnostics-5BceFRdD.js";
2
+ import { t as envErrorDiagnostics } from "./error-diagnostics-BFzFaXcH.js";
3
+ import { t as SecretEnv } from "./secret-VhbE53Vm.js";
4
4
  import { defineDiagnostics } from "nostics";
5
- import { AsyncLocalStorage } from "node:async_hooks";
6
5
  import { ViteHubError, defineErrors, isViteHubError, parseDuration } from "@vite-hub/runtime";
6
+ import { AsyncLocalStorage } from "node:async_hooks";
7
7
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
8
8
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
9
9
  import * as v from "valibot";
10
- //#region src/core/json-value.ts
10
+ // src/core/errors.ts
11
+ const envErrorMessages = {
12
+ ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.",
13
+ ENV_ASYNC_REQUIRED: "[vitehub] Server Env requires asynchronous loading.",
14
+ ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.",
15
+ ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.",
16
+ ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed."
17
+ };
18
+ const envSourceIdentifierSet = /* @__PURE__ */ new Set([
19
+ "custom",
20
+ "env",
21
+ "git:branch",
22
+ "git:commit",
23
+ "git:tag",
24
+ "package.json",
25
+ "provider"
26
+ ]);
27
+ function createEnvError(options, message = envErrorMessages[options.code]) {
28
+ const { code, cause, details } = options;
29
+ return new ViteHubError(code, message, {
30
+ ...cause === void 0 ? {} : { cause },
31
+ ...details === void 0 || Object.keys(details).length === 0 ? {} : { details }
32
+ });
33
+ }
34
+ function invalidEnvDeclaration(path, diagnostic, cause) {
35
+ return createEnvError({
36
+ cause: envErrorDiagnostics.ENV_R0008({
37
+ message: diagnostic,
38
+ ...cause === void 0 ? {} : { cause }
39
+ }),
40
+ code: "ENV_DECLARATION_INVALID",
41
+ details: optionalPath(path)
42
+ });
43
+ }
44
+ function asyncServerEnvRequired(path) {
45
+ return createEnvError({
46
+ cause: envErrorDiagnostics.ENV_R0009({ message: `Server Env at ${path} uses env.provider(). Use loadServerEnv() or runWithServerEnv().` }),
47
+ code: "ENV_ASYNC_REQUIRED",
48
+ details: optionalPath(path)
49
+ });
50
+ }
51
+ /**
52
+ * The message and details name the declaration path and the variables that can supply it, so the operator
53
+ * knows what to set. Names are not secret; the value never appears because there is none.
54
+ */
55
+ function missingRequiredEnv(source, diagnostic, path, names = []) {
56
+ const pathDetails = optionalPath(path);
57
+ const variables = names.filter(isEnvVariableName).slice(0, 8);
58
+ const subject = pathDetails.path ? `Required Env value ${pathDetails.path} is missing.` : "Required Env value is missing.";
59
+ const supply = variables.length ? ` Set ${variables.join(" or ")}.` : "";
60
+ return createEnvError({
61
+ cause: envErrorDiagnostics.ENV_R0010({ message: diagnostic }),
62
+ code: "ENV_REQUIRED_MISSING",
63
+ details: {
64
+ ...variables.length ? { names: variables } : {},
65
+ ...pathDetails,
66
+ source: publicSourceIdentifier(source)
67
+ }
68
+ }, `[vitehub] ${subject}${supply}`);
69
+ }
70
+ function isEnvVariableName(name) {
71
+ return /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name);
72
+ }
73
+ function invalidRuntimeEnvValue(source, diagnostic, path) {
74
+ return createEnvError({
75
+ cause: envErrorDiagnostics.ENV_R0011({ message: diagnostic }),
76
+ code: "ENV_RUNTIME_VALUE_INVALID",
77
+ details: {
78
+ ...optionalPath(path),
79
+ source: publicSourceIdentifier(source)
80
+ }
81
+ });
82
+ }
83
+ function envSourceFailed(source, cause) {
84
+ return createEnvError({
85
+ cause,
86
+ code: "ENV_SOURCE_FAILED",
87
+ details: { source: publicSourceIdentifier(source) }
88
+ });
89
+ }
90
+ function isAbortError(value) {
91
+ if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
92
+ try {
93
+ return value.name === "AbortError";
94
+ } catch {
95
+ return false;
96
+ }
97
+ }
98
+ function publicSourceIdentifier(source) {
99
+ if (envSourceIdentifierSet.has(source)) return source;
100
+ if (source.startsWith("env:")) return "env";
101
+ if (source.startsWith("package.json:")) return "package.json";
102
+ return "custom";
103
+ }
104
+ function optionalPath(path) {
105
+ const normalized = safePath(path);
106
+ return normalized ? { path: normalized } : {};
107
+ }
108
+ function safePath(path) {
109
+ if (typeof path !== "string" || path.length > 256) return void 0;
110
+ return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? path : void 0;
111
+ }
112
+ // src/schema.ts
113
+ function parseSchema(schema, value, label) {
114
+ if (isSchemaModuleReference(schema)) throw envErrorDiagnostics.ENV_R0029({ message: `[vitehub] ${label} uses env.schemaFrom(), which only env.server supports. Pass the schema object itself.` });
115
+ const validate = readStandardValidate(schema, label);
116
+ if (validate) {
117
+ const result = validate(value);
118
+ if (isPromiseLike$1(result)) throw envErrorDiagnostics.ENV_R0014({ message: `[vitehub] ${label} uses an async schema. Env validation currently requires sync schemas.` });
119
+ const issues = standardResultIssues(result);
120
+ if (issues) throw envErrorDiagnostics.ENV_R0015({ message: `[vitehub] Invalid ${label}: ${formatStandardIssues(issues)}` });
121
+ if (!hasResultValue(result)) throw envErrorDiagnostics.ENV_R0016({ message: `[vitehub] Invalid ${label}: the schema returned no value.` });
122
+ return result.value;
123
+ }
124
+ if (isZodLike(schema) && hasSchemaMethod(schema, "safeParse") && typeof schema.safeParse === "function") {
125
+ const result = schema.safeParse(value);
126
+ if (!result.success) throw envErrorDiagnostics.ENV_R0017({ message: `[vitehub] Invalid ${label}: ${formatIssues(result.error)}` });
127
+ return result.data;
128
+ }
129
+ if (isZodLike(schema) && hasSchemaMethod(schema, "parse") && typeof schema.parse === "function") try {
130
+ return schema.parse(value);
131
+ } catch (error) {
132
+ throw envErrorDiagnostics.ENV_R0018({ message: `[vitehub] Invalid ${label}: ${formatIssues(error)}` });
133
+ }
134
+ return value;
135
+ }
136
+ function readStandardValidate(schema, label) {
137
+ if (!isRecordOrFunction(schema)) return void 0;
138
+ try {
139
+ const standard = Reflect.get(schema, "~standard");
140
+ if (!isRecordOrFunction(standard)) return void 0;
141
+ const validate = Reflect.get(standard, "validate");
142
+ if (typeof validate !== "function") return void 0;
143
+ return (input) => Reflect.apply(validate, standard, [input]);
144
+ } catch (error) {
145
+ throw invalidEnvDeclaration(label, `${label} has a schema that threw while ViteHub read its \`~standard\` validator.`, error);
146
+ }
147
+ }
148
+ function isSchemaModuleReference(schema) {
149
+ return typeof schema === "object" && schema !== null && !Array.isArray(schema) && schema.kind === "schema-module";
150
+ }
151
+ function isPromiseLike$1(value) {
152
+ return isRecordOrFunction(value) && typeof value.then === "function";
153
+ }
154
+ function hasResultValue(result) {
155
+ return isRecordOrFunction(result) && "value" in result;
156
+ }
157
+ function formatStandardIssues(issues) {
158
+ return issues.map((issue) => {
159
+ if (typeof issue === "string") return issue;
160
+ const message = isRecordOrFunction(issue) && typeof issue.message === "string" ? issue.message : "Invalid value.";
161
+ const segments = isRecordOrFunction(issue) && Array.isArray(issue.path) ? Array.from(issue.path, issuePathKey).filter((segment) => typeof segment === "string" || typeof segment === "number") : [];
162
+ return segments.length ? `${segments.join(".")}: ${message}` : message;
163
+ }).join("; ");
164
+ }
165
+ function issuePathKey(segment) {
166
+ return isRecordOrFunction(segment) ? segment.key : segment;
167
+ }
168
+ function isZodLike(schema) {
169
+ return typeof schema === "object" && schema !== null;
170
+ }
171
+ function hasSchemaMethod(schema, method) {
172
+ return Object.hasOwn(schema, method) || isZodSchemaMethod(schema, method);
173
+ }
174
+ function isZodSchemaMethod(schema, method) {
175
+ if (!Object.hasOwn(schema, "_zod")) return false;
176
+ const metadata = schema._zod;
177
+ if (!metadata) return false;
178
+ const constructor = metadata?.constr;
179
+ return hasSetValue(metadata?.traits, "ZodType") && Object.hasOwn(metadata, "constr") && typeof constructor === "function" && Object.getPrototypeOf(schema) === constructor.prototype && Object.hasOwn(constructor.prototype, method);
180
+ }
181
+ function hasSetValue(value, entry) {
182
+ try {
183
+ return Set.prototype.has.call(value, entry);
184
+ } catch {
185
+ return false;
186
+ }
187
+ }
188
+ function formatIssues(issues) {
189
+ if (Array.isArray(issues)) return issues.map((issue) => typeof issue === "string" ? issue : JSON.stringify(issue)).join("; ");
190
+ if (issues instanceof Error) return issues.message;
191
+ return typeof issues === "string" ? issues : JSON.stringify(issues);
192
+ }
193
+ // src/core/json-value.ts
11
194
  /** JSON values accepted at the environment boundary, without prototype or internal keys. */
12
195
  function isEnvSchemaValue(value, depth = 0) {
13
196
  if (depth > 64) return false;
@@ -22,8 +205,7 @@ function isEnvSchemaValue(value, depth = 0) {
22
205
  "__envSchemaUnset"
23
206
  ].includes(key) && isEnvSchemaValue(item, depth + 1));
24
207
  }
25
- //#endregion
26
- //#region src/core/values.ts
208
+ // src/core/values.ts
27
209
  const stringValueSchema = Object.freeze({ kind: "string" });
28
210
  /** Parse one host, provider, or default value with a serializable Server Env value schema. */
29
211
  function parseEnvValue(schema, input) {
@@ -191,8 +373,7 @@ function schemaContainsEnum(schema) {
191
373
  default: return false;
192
374
  }
193
375
  }
194
- //#endregion
195
- //#region ../internal/src/runtime/cloudflare-env-lookup.ts
376
+ // ../internal/src/runtime/cloudflare-env-lookup.ts
196
377
  /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
197
378
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
198
379
  let activeEnv;
@@ -206,15 +387,13 @@ function getActiveCloudflareEnv() {
206
387
  const host = globalThis;
207
388
  return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
208
389
  }
209
- //#endregion
210
- //#region ../internal/src/runtime/cloudflare-env.ts
390
+ // ../internal/src/runtime/cloudflare-env.ts
211
391
  const runtimeGlobal = globalThis;
212
392
  const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
213
393
  function runWithActiveCloudflareEnv(env, callback) {
214
394
  return activeEnvStorage.run({ env }, callback);
215
395
  }
216
- //#endregion
217
- //#region ../internal/src/secret.ts
396
+ // ../internal/src/secret.ts
218
397
  const secretEncoder = new TextEncoder();
219
398
  /**
220
399
  * Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
@@ -336,111 +515,7 @@ async function verifyViteHubStripeSignature(secret, header, body, options = {})
336
515
  for (const signature of signatures) verified = isViteHubSecretEqual(signature, expected) || verified;
337
516
  return verified;
338
517
  }
339
- //#endregion
340
- //#region src/core/errors.ts
341
- const envErrorMessages = {
342
- ENV_DECLARATION_INVALID: "[vitehub] Env declaration is invalid.",
343
- ENV_ASYNC_REQUIRED: "[vitehub] Server Env requires asynchronous loading.",
344
- ENV_REQUIRED_MISSING: "[vitehub] Required Env value is missing.",
345
- ENV_RUNTIME_VALUE_INVALID: "[vitehub] Runtime Env value is invalid.",
346
- ENV_SOURCE_FAILED: "[vitehub] Env source resolution failed."
347
- };
348
- const envSourceIdentifierSet = /* @__PURE__ */ new Set([
349
- "custom",
350
- "env",
351
- "git:branch",
352
- "git:commit",
353
- "git:tag",
354
- "package.json",
355
- "provider"
356
- ]);
357
- function createEnvError(options, message = envErrorMessages[options.code]) {
358
- const { code, cause, details } = options;
359
- return new ViteHubError(code, message, {
360
- ...cause === void 0 ? {} : { cause },
361
- ...details === void 0 || Object.keys(details).length === 0 ? {} : { details }
362
- });
363
- }
364
- function invalidEnvDeclaration(path, diagnostic, cause) {
365
- return createEnvError({
366
- cause: envErrorDiagnostics.ENV_R0008({
367
- message: diagnostic,
368
- ...cause === void 0 ? {} : { cause }
369
- }),
370
- code: "ENV_DECLARATION_INVALID",
371
- details: optionalPath(path)
372
- });
373
- }
374
- function asyncServerEnvRequired(path) {
375
- return createEnvError({
376
- cause: envErrorDiagnostics.ENV_R0009({ message: `Server Env at ${path} uses env.provider(). Use loadServerEnv() or runWithServerEnv().` }),
377
- code: "ENV_ASYNC_REQUIRED",
378
- details: optionalPath(path)
379
- });
380
- }
381
- /**
382
- * The message and details name the declaration path and the variables that can supply it, so the operator
383
- * knows what to set. Names are not secret; the value never appears because there is none.
384
- */
385
- function missingRequiredEnv(source, diagnostic, path, names = []) {
386
- const pathDetails = optionalPath(path);
387
- const variables = names.filter(isEnvVariableName).slice(0, 8);
388
- const subject = pathDetails.path ? `Required Env value ${pathDetails.path} is missing.` : "Required Env value is missing.";
389
- const supply = variables.length ? ` Set ${variables.join(" or ")}.` : "";
390
- return createEnvError({
391
- cause: envErrorDiagnostics.ENV_R0010({ message: diagnostic }),
392
- code: "ENV_REQUIRED_MISSING",
393
- details: {
394
- ...variables.length ? { names: variables } : {},
395
- ...pathDetails,
396
- source: publicSourceIdentifier(source)
397
- }
398
- }, `[vitehub] ${subject}${supply}`);
399
- }
400
- function isEnvVariableName(name) {
401
- return /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name);
402
- }
403
- function invalidRuntimeEnvValue(source, diagnostic, path) {
404
- return createEnvError({
405
- cause: envErrorDiagnostics.ENV_R0011({ message: diagnostic }),
406
- code: "ENV_RUNTIME_VALUE_INVALID",
407
- details: {
408
- ...optionalPath(path),
409
- source: publicSourceIdentifier(source)
410
- }
411
- });
412
- }
413
- function envSourceFailed(source, cause) {
414
- return createEnvError({
415
- cause,
416
- code: "ENV_SOURCE_FAILED",
417
- details: { source: publicSourceIdentifier(source) }
418
- });
419
- }
420
- function isAbortError(value) {
421
- if ((typeof value !== "object" || value === null) && typeof value !== "function") return false;
422
- try {
423
- return value.name === "AbortError";
424
- } catch {
425
- return false;
426
- }
427
- }
428
- function publicSourceIdentifier(source) {
429
- if (envSourceIdentifierSet.has(source)) return source;
430
- if (source.startsWith("env:")) return "env";
431
- if (source.startsWith("package.json:")) return "package.json";
432
- return "custom";
433
- }
434
- function optionalPath(path) {
435
- const normalized = safePath(path);
436
- return normalized ? { path: normalized } : {};
437
- }
438
- function safePath(path) {
439
- if (typeof path !== "string" || path.length > 256) return void 0;
440
- return /^(?:env|runtime)(?:\.[A-Za-z_$][A-Za-z0-9_$-]{0,63}){0,8}$/.test(path) ? path : void 0;
441
- }
442
- //#endregion
443
- //#region src/internal/runtime-env.ts
518
+ // src/internal/runtime-env.ts
444
519
  function processEnv() {
445
520
  return typeof process === "object" && process && process.env ? process.env : {};
446
521
  }
@@ -473,8 +548,7 @@ function standardSource(event) {
473
548
  if ("~standard" in event) return event;
474
549
  return event instanceof Request ? event : event.req;
475
550
  }
476
- //#endregion
477
- //#region src/core/registry.ts
551
+ // src/core/registry.ts
478
552
  const envEntrySchema = v.object({
479
553
  required: v.boolean(),
480
554
  secret: v.boolean(),
@@ -513,8 +587,7 @@ function* runtimeRegistryEntries(value, path = "env.server") {
513
587
  if (!isRecord(value)) return;
514
588
  for (const [key, child] of Object.entries(value)) yield* runtimeRegistryEntries(child, `${path}.${key.includes(".") ? "!" : ""}${key}`);
515
589
  }
516
- //#endregion
517
- //#region ../internal/src/invariant.ts
590
+ // ../internal/src/invariant.ts
518
591
  const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
519
592
  docsBase: "https://vitehub.dev/docs/development/diagnostics",
520
593
  codes: { INTERNAL_INVARIANT_FAILED: {
@@ -533,8 +606,7 @@ function invariantError(what) {
533
606
  function invariant(condition, what) {
534
607
  if (!condition) throw invariantError(what);
535
608
  }
536
- //#endregion
537
- //#region src/seal-uses.ts
609
+ // src/seal-uses.ts
538
610
  function isSealUseCount(value) {
539
611
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
540
612
  }
@@ -576,8 +648,7 @@ async function deleteSealUses(db, id) {
576
648
  await initialize(db);
577
649
  await db.all(`DELETE FROM ${table} WHERE id = '${checkId(id)}'`);
578
650
  }
579
- //#endregion
580
- //#region src/seal-value.ts
651
+ // src/seal-value.ts
581
652
  const sealErrors = /*#__PURE__*/ defineErrors({
582
653
  docs: "https://vitehub.dev/docs/env/diagnostics",
583
654
  codes: {
@@ -788,8 +859,7 @@ function seal(purpose, value, options) {
788
859
  function unseal(purpose, sealed, options) {
789
860
  return sealing.unseal(purpose, sealed, options);
790
861
  }
791
- //#endregion
792
- //#region src/server.ts
862
+ // src/server.ts
793
863
  /**
794
864
  * Run `callback` with `env` as the active Cloudflare bindings. Server Env reads them when a call gets no request
795
865
  * event, such as for the module bindings of `cloudflare:workers` outside a request.
@@ -850,20 +920,15 @@ function bindServerEnvSchemas(registry, modules) {
850
920
  if (!(isRuntimeEnvEntry(entry) || isRuntimeProviderEntry(entry)) || !entry.schemaModule) continue;
851
921
  const reference = entry.schemaModule;
852
922
  const module = Object.hasOwn(modules, reference.module) ? modules[reference.module] : void 0;
853
- const schema = module && Object.hasOwn(module, reference.export) ? module[reference.export] : void 0;
854
- if (!isBoundStandardSchema(schema)) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(${JSON.stringify(reference.module)}, ${JSON.stringify(reference.export)}), but that export is not a Standard Schema.`);
855
- boundSchemas.set(entry, schema);
923
+ const validate = readStandardValidate(module && Object.hasOwn(module, reference.export) ? module[reference.export] : void 0, path);
924
+ if (!validate) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(${JSON.stringify(reference.module)}, ${JSON.stringify(reference.export)}), but that export is not a Standard Schema.`);
925
+ boundSchemas.set(entry, validate);
856
926
  }
857
927
  }
858
- function isBoundStandardSchema(value) {
859
- if (typeof value !== "object" && typeof value !== "function" || value === null) return false;
860
- const standard = value["~standard"];
861
- return typeof standard === "object" && standard !== null && typeof standard.validate === "function";
862
- }
863
928
  function parseRuntimeValue(entry, value, path) {
864
929
  if (!entry.schemaModule) return parseEnvValue(entry.schema ?? stringValueSchema, value);
865
- const schema = boundSchemas.get(entry);
866
- if (!schema) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(), but no schema module was loaded for it. Only env.server declarations of hubEnv() support env.schemaFrom().`);
930
+ const validate = boundSchemas.get(entry);
931
+ if (!validate) throw invalidEnvDeclaration(path, `${path} uses env.schemaFrom(), but no schema module was loaded for it. Only env.server declarations of hubEnv() support env.schemaFrom().`);
867
932
  let input = value;
868
933
  if (entry.schemaModule.input === "json") {
869
934
  const json = readJsonInput(value);
@@ -872,7 +937,7 @@ function parseRuntimeValue(entry, value, path) {
872
937
  }
873
938
  let result;
874
939
  try {
875
- result = schema["~standard"].validate(input);
940
+ result = validate(input);
876
941
  } catch (error) {
877
942
  return {
878
943
  message: `The schema threw: ${error instanceof Error ? error.message : String(error)}`,
@@ -886,12 +951,12 @@ function parseRuntimeValue(entry, value, path) {
886
951
  success: false
887
952
  };
888
953
  }
889
- const issues = isRecord(result) ? result.issues : void 0;
890
- if (Array.isArray(issues) && issues.length) return {
891
- message: formatSchemaIssues(issues),
954
+ const issues = standardResultIssues(result);
955
+ if (issues) return {
956
+ message: formatStandardIssues(issues),
892
957
  success: false
893
958
  };
894
- if (!isRecord(result) || !("value" in result)) return {
959
+ if (!hasResultValue(result)) return {
895
960
  message: "The schema returned no value.",
896
961
  success: false
897
962
  };
@@ -903,13 +968,6 @@ function parseRuntimeValue(entry, value, path) {
903
968
  function isPromiseLike(value) {
904
969
  return (typeof value === "object" || typeof value === "function") && value !== null && typeof value.then === "function";
905
970
  }
906
- function formatSchemaIssues(issues) {
907
- return issues.map((issue) => {
908
- const message = isRecord(issue) && typeof issue.message === "string" ? issue.message : "Invalid value.";
909
- const segments = isRecord(issue) && Array.isArray(issue.path) ? issue.path.map((segment) => isRecord(segment) ? segment.key : segment).filter((segment) => typeof segment === "string" || typeof segment === "number") : [];
910
- return segments.length ? `${segments.join(".")}: ${message}` : message;
911
- }).join("; ");
912
- }
913
971
  function resolvedRuntimeValue(entry, value, found, path, snapshot = false) {
914
972
  const resolved = found ? value : entry.default;
915
973
  if (typeof resolved === "undefined") {
@@ -1274,5 +1332,4 @@ async function inspectServerEnv(registry, event, options = {}) {
1274
1332
  if (options.signal?.aborted) throw abortReason(options.signal);
1275
1333
  return Object.freeze({ entries: Object.freeze(entries.map((entry) => Object.freeze(entry))) });
1276
1334
  }
1277
- //#endregion
1278
- export { envValueTypeName as A, deriveViteHubSecret as C, verifyViteHubHmacSignature as D, readViteHubSecret as E, stringValueSchema as F, isEnvSchemaValue as I, parseEnvValue as M, readJsonInput as N, verifyViteHubStripeSignature as O, schemaContainsEnum as P, missingRequiredEnv as S, isViteHubBearerSecretEqual as T, runtimeEnv as _, isBlockingServerEnvEntry as a, invalidEnvDeclaration as b, runWithCloudflareEnv as c, unseal as d, invariant as f, runtimeRegistryEntries as g, isRuntimeProviderEntry as h, inspectServerEnv as i, listItemKinds as j, viteHubHmacSha256 as k, createSealing as l, isRuntimeLiteralEntry as m, deriveSecret as n, loadServerEnv as o, isRuntimeEnvEntry as p, describeServerEnv as r, resolveServerEnv as s, bindServerEnvSchemas as t, seal as u, standardSource as v, githubHmacSignatureFormat as w, isAbortError as x, envSourceFailed as y };
1335
+ export { schemaContainsEnum as A, verifyViteHubHmacSignature as C, listItemKinds as D, envValueTypeName as E, envSourceFailed as F, invalidEnvDeclaration as I, isAbortError as L, isEnvSchemaValue as M, parseSchema as N, parseEnvValue as O, readStandardValidate as P, missingRequiredEnv as R, readViteHubSecret as S, viteHubHmacSha256 as T, runtimeEnv as _, isBlockingServerEnvEntry as a, githubHmacSignatureFormat as b, runWithCloudflareEnv as c, unseal as d, invariant as f, runtimeRegistryEntries as g, isRuntimeProviderEntry as h, inspectServerEnv as i, stringValueSchema as j, readJsonInput as k, createSealing as l, isRuntimeLiteralEntry as m, deriveSecret as n, loadServerEnv as o, isRuntimeEnvEntry as p, describeServerEnv as r, resolveServerEnv as s, bindServerEnvSchemas as t, seal as u, standardSource as v, verifyViteHubStripeSignature as w, isViteHubBearerSecretEqual as x, deriveViteHubSecret as y };
package/dist/server.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { G as ServerEnvInspection, K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus, t as EnvAccessContext } from "./bridge-Cs9YfQWk.js";
2
- import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "./server-OvARy_y9.js";
1
+ import { G as ServerEnvInspection, K as ServerEnvInspectionEntry, q as ServerEnvInspectionStatus, t as EnvAccessContext } from "./bridge-BWwIooe0.js";
2
+ import { _ as unseal, a as describeServerEnv, c as loadServerEnv, d as SealOptions, f as UnsealErrorCode, g as seal, h as createSealing, i as deriveSecret, l as resolveServerEnv, m as UnsealSchemaOptions, n as ViteHubContext, o as inspectServerEnv, p as UnsealOptions, r as bindServerEnvSchemas, s as isBlockingServerEnvEntry, t as DeriveSecretOptions, u as runWithCloudflareEnv } from "./server-CPEywepM.js";
3
3
  export { DeriveSecretOptions, type EnvAccessContext, type SealOptions, type ServerEnvInspection, type ServerEnvInspectionEntry, type ServerEnvInspectionStatus, type UnsealErrorCode, type UnsealOptions, type UnsealSchemaOptions, type ViteHubContext, bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
package/dist/server.js CHANGED
@@ -1,2 +1 @@
1
- import { a as isBlockingServerEnvEntry, c as runWithCloudflareEnv, d as unseal, i as inspectServerEnv, l as createSealing, n as deriveSecret, o as loadServerEnv, r as describeServerEnv, s as resolveServerEnv, t as bindServerEnvSchemas, u as seal } from "./server-Ct3uvhf9.js";
2
- export { bindServerEnvSchemas, createSealing, deriveSecret, describeServerEnv, inspectServerEnv, isBlockingServerEnvEntry, loadServerEnv, resolveServerEnv, runWithCloudflareEnv, seal, unseal };
1
+ export { t as bindServerEnvSchemas, l as createSealing, n as deriveSecret, r as describeServerEnv, i as inspectServerEnv, a as isBlockingServerEnvEntry, o as loadServerEnv, s as resolveServerEnv, c as runWithCloudflareEnv, u as seal, d as unseal } from "./server-pTqnkM7n.js";