@vite-hub/kv 0.1.0 → 0.4.1

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 (65) hide show
  1. package/README.md +94 -21
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +99 -77
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-C3NO4C21.js +201 -0
  9. package/dist/cloudflare-kv-local-C2sbIrFy.js +71 -0
  10. package/dist/config-LfpUj9hs.js +252 -0
  11. package/dist/{create-storage-29gMzf41.js → create-storage-BORQm2a8.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-DRHh5bO5.js} +31 -14
  13. package/dist/database-oJdy0ZVX.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-D_VtffFv.js} +12 -4
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-R4Z5Z5fl.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-C54QQEhN.js +155 -0
  20. package/dist/errors-DzD6YNEH.js +88 -0
  21. package/dist/errors.d.ts +17 -1
  22. package/dist/errors.js +2 -2
  23. package/dist/fs-lite-BAgpmNAF.js +2 -0
  24. package/dist/fs-lite-BaklCLuV.js +386 -0
  25. package/dist/index.d.ts +7 -2
  26. package/dist/index.js +326 -84
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/object-Da1zyPCR.js +11 -0
  30. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
  31. package/dist/{operations-pn8_eGob.js → operations-CtrWLmPK.js} +69 -66
  32. package/dist/operations-D2iI9oN4.js +1363 -0
  33. package/dist/operations.d.ts +15 -8
  34. package/dist/operations.js +56 -192
  35. package/dist/redis-shared-5ogRd3-Y.js +94 -0
  36. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  37. package/dist/runtime/cloudflare-kv.js +1 -99
  38. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  39. package/dist/runtime/cloudflare-request-env.js +11 -0
  40. package/dist/runtime/nitro-plugin.d.ts +12 -0
  41. package/dist/runtime/nitro-plugin.js +25 -0
  42. package/dist/runtime/redis-driver.d.ts +11 -0
  43. package/dist/runtime/redis-driver.js +113 -0
  44. package/dist/runtime/unstorage-driver.d.ts +14 -0
  45. package/dist/runtime/unstorage-driver.js +37 -0
  46. package/dist/runtime/upstash-driver.d.ts +2 -2
  47. package/dist/runtime/upstash-driver.js +58 -98
  48. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  49. package/dist/types-Dv-OSXZC.d.ts +325 -0
  50. package/dist/upstash-B-vaUYqO.js +40 -0
  51. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  52. package/dist/virtual-module.d.ts +3 -0
  53. package/dist/vite.d.ts +167 -14
  54. package/dist/vite.js +1195 -2876
  55. package/package.json +30 -21
  56. package/dist/cli-Cniq99iX.d.ts +0 -85
  57. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  58. package/dist/config-DR6_5ZwI.js +0 -124
  59. package/dist/continuations-DPyH_vr1.js +0 -63
  60. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  61. package/dist/errors-Dc2oiW-Y.js +0 -38
  62. package/dist/fs-lite-CbLKxLut.js +0 -90
  63. package/dist/object-B1NW521B.js +0 -7
  64. package/dist/operations-ByuDE12r.js +0 -1442
  65. package/dist/types-CMDvN0Wr.d.ts +0 -81
@@ -0,0 +1,118 @@
1
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
2
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
3
+ function normalizeWindowsPath(input = "") {
4
+ if (!input) return input;
5
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
6
+ }
7
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
8
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
9
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
10
+ function cwd() {
11
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
12
+ return "/";
13
+ }
14
+ const resolve = function(...arguments_) {
15
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
16
+ let resolvedPath = "";
17
+ let resolvedAbsolute = false;
18
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
19
+ const path = index >= 0 ? arguments_[index] : cwd();
20
+ if (!path || path.length === 0) continue;
21
+ resolvedPath = `${path}/${resolvedPath}`;
22
+ resolvedAbsolute = isAbsolute(path);
23
+ }
24
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
25
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
26
+ return resolvedPath.length > 0 ? resolvedPath : ".";
27
+ };
28
+ function normalizeString(path, allowAboveRoot) {
29
+ let res = "";
30
+ let lastSegmentLength = 0;
31
+ let lastSlash = -1;
32
+ let dots = 0;
33
+ let char = null;
34
+ for (let index = 0; index <= path.length; ++index) {
35
+ if (index < path.length) char = path[index];
36
+ else if (char === "/") break;
37
+ else char = "/";
38
+ if (char === "/") {
39
+ if (lastSlash === index - 1 || dots === 1);
40
+ else if (dots === 2) {
41
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
42
+ if (res.length > 2) {
43
+ const lastSlashIndex = res.lastIndexOf("/");
44
+ if (lastSlashIndex === -1) {
45
+ res = "";
46
+ lastSegmentLength = 0;
47
+ } else {
48
+ res = res.slice(0, lastSlashIndex);
49
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
50
+ }
51
+ lastSlash = index;
52
+ dots = 0;
53
+ continue;
54
+ } else if (res.length > 0) {
55
+ res = "";
56
+ lastSegmentLength = 0;
57
+ lastSlash = index;
58
+ dots = 0;
59
+ continue;
60
+ }
61
+ }
62
+ if (allowAboveRoot) {
63
+ res += res.length > 0 ? "/.." : "..";
64
+ lastSegmentLength = 2;
65
+ }
66
+ } else {
67
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
68
+ else res = path.slice(lastSlash + 1, index);
69
+ lastSegmentLength = index - lastSlash - 1;
70
+ }
71
+ lastSlash = index;
72
+ dots = 0;
73
+ } else if (char === "." && dots !== -1) ++dots;
74
+ else dots = -1;
75
+ }
76
+ return res;
77
+ }
78
+ const isAbsolute = function(p) {
79
+ return _IS_ABSOLUTE_RE.test(p);
80
+ };
81
+ const relative = function(from, to) {
82
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
83
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
84
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
85
+ const _fromCopy = [..._from];
86
+ for (const segment of _fromCopy) {
87
+ if (_to[0] !== segment) break;
88
+ _from.shift();
89
+ _to.shift();
90
+ }
91
+ return [..._from.map(() => ".."), ..._to].join("/");
92
+ };
93
+ const dirname = function(p) {
94
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
95
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
96
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
97
+ };
98
+ //#endregion
99
+ //#region ../internal/src/inspect.ts
100
+ function relativeDefinitionFile(projectRoot, file) {
101
+ return relative(projectRoot, file).replaceAll("\\", "/");
102
+ }
103
+ const redactedInspectionValue = "[redacted]";
104
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
105
+ const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
106
+ const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
107
+ const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
108
+ const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
109
+ const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
110
+ /**
111
+ * Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
112
+ * `name=value` pairs with a secret name are replaced with `[redacted]`.
113
+ */
114
+ function redactInspectionText(value) {
115
+ return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
116
+ }
117
+ //#endregion
118
+ export { resolve as a, relative as i, relativeDefinitionFile as n, dirname as r, redactInspectionText as t };
@@ -0,0 +1,22 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/invariant.ts
3
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
+ codes: { INTERNAL_INVARIANT_FAILED: {
6
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
7
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
8
+ } }
9
+ });
10
+ /**
11
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
12
+ * Use a code from the package catalog when a developer can cause the error or fix it.
13
+ */
14
+ function invariantError(what) {
15
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
16
+ }
17
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
18
+ function invariant(condition, what) {
19
+ if (!condition) throw invariantError(what);
20
+ }
21
+ //#endregion
22
+ export { invariantError as n, invariant as t };
@@ -0,0 +1,11 @@
1
+ //#region ../internal/src/object.ts
2
+ /** A non-null object that is not an array. Functions do not pass. */
3
+ function isRecord(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ /** A non-null object or a function that is not an array. */
7
+ function isRecordOrFunction(value) {
8
+ return Object(value) === value && !Array.isArray(value);
9
+ }
10
+ //#endregion
11
+ export { isRecordOrFunction as n, isRecord as t };
@@ -75,7 +75,7 @@ declare namespace StandardSchemaV1 {
75
75
  type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
76
  }
77
77
  //#endregion
78
- //#region ../internal/src/operations.d.ts
78
+ //#region ../internal/src/operation-definition.d.ts
79
79
  /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
80
  type OperationKind = "read" | "write" | "destructive";
81
81
  /** The signed-in user of a call. */
@@ -98,7 +98,9 @@ interface OperationAccess {
98
98
  readonly mode: string;
99
99
  /**
100
100
  * The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
101
- * operation of the section) or `"<section>:read"` (only the operations that read).
101
+ * operation of the section), `"<section>:read"` (only the operations that read), or `"<section>:<scope>"` (only the
102
+ * calls of a scoped operation for that scope, such as `"blob:media"` for one Blob store). `"<section>:<scope>:read"`
103
+ * allows only the reads of that scope.
102
104
  */
103
105
  readonly sections: "all" | readonly string[];
104
106
  readonly user?: OperationUser;
@@ -113,9 +115,20 @@ interface OperationContext {
113
115
  surface: "console" | "cli" | "mcp" | "agent";
114
116
  /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
115
117
  development?: boolean;
118
+ /**
119
+ * The project root of a development server, for operations that read build files, such as `bundle.report`. Hosts set
120
+ * it only with `development`, so a deployed server never reads project files through it.
121
+ */
122
+ projectRoot?: string;
116
123
  env?: Record<string, unknown>;
117
124
  waitUntil?: (task: Promise<unknown>) => void;
118
125
  request?: Request;
126
+ /**
127
+ * The request event of the HTTP request that carries the call, when there is one: the Request of the Console route,
128
+ * with its Standard Context. Operations hand it to app hooks that read the request's own session, such as `identify`
129
+ * of Comments.
130
+ */
131
+ event?: unknown;
119
132
  /** Operations set a success status here, such as 202 for an accepted call. */
120
133
  response?: {
121
134
  status?: number;
@@ -138,9 +151,16 @@ interface OperationDefinition<Input, Output> {
138
151
  description: string;
139
152
  /**
140
153
  * Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
141
- * from the input, for operations that serve several sections.
154
+ * from the input, for operations that serve several sections. Section ids cannot contain `:`; it is reserved for
155
+ * scope and read-only grants. A function that returns an invalid id denies the call.
142
156
  */
143
157
  section: string | false | ((input: Input) => string | undefined);
158
+ /**
159
+ * The part of a string `section` that one call uses, such as the Blob store that the input names. The call then needs
160
+ * the section (every scope) or `"<section>:<scope>"` (only this scope). A scope that is empty, is `read`, or has a
161
+ * `:` needs the whole section.
162
+ */
163
+ scope?: (input: Input) => string | undefined;
144
164
  /** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
145
165
  kind: OperationKind;
146
166
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
@@ -149,19 +169,14 @@ interface OperationDefinition<Input, Output> {
149
169
  cli?: {
150
170
  /** Defaults: namespace = section, command = verb. */
151
171
  namespace?: string;
172
+ /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
152
173
  command?: string;
153
174
  /** Input keys read from positional arguments, in order. */
154
175
  positional?: string[];
155
176
  /** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
156
177
  format?: (output: Output) => string;
157
- /** `vitehub <namespace>` runs this command when no command is named, such as `vitehub usage`. */
178
+ /** `vitehub <namespace>` runs this command when no command is named. */
158
179
  default?: boolean;
159
- /**
160
- * Route of the app that takes a signed dispatch of this operation, such as `/_vitehub/schedules/run`. With `--url`
161
- * and a dispatch key in the environment (`VITEHUB_DISPATCH_KEY`), the command signs the input and posts it there, so
162
- * a CI job needs no Console credentials. Without a key it calls the RPC.
163
- */
164
- dispatch?: string;
165
180
  };
166
181
  /** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
167
182
  maxRequestBytes?: number;
@@ -170,8 +185,16 @@ interface OperationDefinition<Input, Output> {
170
185
  * confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
171
186
  */
172
187
  readOnlyWhen?: (input: Input) => boolean;
173
- /** `false`: MCP does not offer the operation as a tool, such as an editor transport that only the Console uses. */
174
- mcp?: false;
188
+ /**
189
+ * How MCP offers the operation as a tool. `false`: MCP does not offer it, such as an editor transport that only the
190
+ * Console uses. `title`: the short title that clients show, instead of the name in words. `format`: the text of a
191
+ * result for the Agent, such as a list of lines. The result stays the structured content. Without `format`, the text
192
+ * is the result as JSON.
193
+ */
194
+ mcp?: false | {
195
+ title?: string;
196
+ format?: (output: NoInfer<Output>) => string;
197
+ };
175
198
  /** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
176
199
  user?: false;
177
200
  /**
@@ -182,24 +205,28 @@ interface OperationDefinition<Input, Output> {
182
205
  run: (input: Input, context: OperationContext) => Output | Promise<Output>;
183
206
  }
184
207
  /** An operation of any input and output, as a registry holds it. */
185
- interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "output" | "readOnlyWhen" | "run" | "section"> {
208
+ interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
186
209
  readOnlyWhen?: (input: never) => boolean;
187
210
  cli?: {
188
211
  namespace?: string;
189
212
  command?: string;
190
213
  default?: boolean;
191
- dispatch?: string;
192
214
  positional?: string[];
193
215
  format?: (output: never) => string;
194
216
  };
217
+ mcp?: false | {
218
+ title?: string;
219
+ format?: (output: never) => string;
220
+ };
195
221
  input: StandardSchemaV1;
196
222
  output?: StandardSchemaV1;
197
223
  run: (input: never, context: OperationContext) => unknown;
224
+ scope?: (input: never) => string | undefined;
198
225
  section: string | false | ((input: never) => string | undefined);
199
226
  }
200
227
  /** The contribution of one plugin: operations, or a module that exports them. */
201
228
  interface OperationContributionEntry {
202
- /** Module the app imports, such as `@vite-hub/content/operations`. */
229
+ /** The absolute path of the module that generated code imports, such as `ownModule(import.meta.url, "operations")`. */
203
230
  module: string;
204
231
  /** Named export that holds an operation or an array of operations. Defaults to `default`. */
205
232
  export?: string;
@@ -1,24 +1,11 @@
1
+ import { t as redactInspectionText } from "./inspect-BIKQsqX4.js";
2
+ import { n as invariantError } from "./invariant-DolT9EEx.js";
3
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
1
4
  import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
2
- import { a as normalizeKey } from "./utils2-Dsb9P4_2.js";
5
+ import { o as normalizeKey } from "./utils2-FozcTsmb.js";
3
6
  import { kv } from "@vite-hub/kv";
4
- //#region ../internal/src/inspect.ts
5
- const redactedInspectionValue = "[redacted]";
6
- const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
7
- const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
8
- const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
9
- const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
10
- const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
11
- const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
12
- /**
13
- * Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
14
- * `name=value` pairs with a secret name are replaced with `[redacted]`.
15
- */
16
- function redactInspectionText(value) {
17
- return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
18
- }
19
- //#endregion
20
7
  //#region src/runtime/inspect-value.ts
21
- var UnsupportedValueError = class extends Error {};
8
+ const unsupported = () => kvErrorDiagnostics.KV_VALUE_UNSUPPORTED();
22
9
  function isUint8Array(value) {
23
10
  try {
24
11
  if (!ArrayBuffer.isView(value)) return false;
@@ -37,11 +24,11 @@ function kvValueType(value) {
37
24
  function encodeBase64(bytes) {
38
25
  try {
39
26
  const lengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length")?.get;
40
- if (!lengthGetter) throw new UnsupportedValueError();
27
+ if (!lengthGetter) throw unsupported();
41
28
  const length = Reflect.apply(lengthGetter, bytes, []);
42
29
  for (const key of ["byteLength", "length"]) {
43
30
  const descriptor = Object.getOwnPropertyDescriptor(bytes, key);
44
- if (descriptor && (!("value" in descriptor) || descriptor.value !== length)) throw new UnsupportedValueError();
31
+ if (descriptor && (!("value" in descriptor) || descriptor.value !== length)) throw unsupported();
45
32
  }
46
33
  const encoded = [];
47
34
  let chunk = [];
@@ -55,7 +42,7 @@ function encodeBase64(bytes) {
55
42
  if (chunk.length) encoded.push(btoa(String.fromCharCode(...chunk)));
56
43
  return encoded.join("");
57
44
  } catch {
58
- throw new UnsupportedValueError();
45
+ throw unsupported();
59
46
  }
60
47
  }
61
48
  /** JSON inspection accepts JSON values and represents bigint values as decimal strings. */
@@ -63,18 +50,18 @@ function inspectValue(value, seen = /* @__PURE__ */ new WeakSet()) {
63
50
  if (typeof value === "bigint") return value.toString();
64
51
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
65
52
  if (typeof value === "number" && Number.isFinite(value) && !Object.is(value, -0)) return value;
66
- if (typeof value !== "object" && typeof value !== "function" || seen.has(value)) throw new UnsupportedValueError();
53
+ if (typeof value !== "object" && typeof value !== "function" || seen.has(value)) throw unsupported();
67
54
  seen.add(value);
68
55
  try {
69
56
  const ownKeys = Reflect.ownKeys(value);
70
57
  const dataKeys = Array.isArray(value) ? ownKeys.filter((key) => key !== "length") : ownKeys;
71
- if (dataKeys.map((key) => Object.getOwnPropertyDescriptor(value, key)).some((descriptor) => !descriptor?.enumerable || !("value" in descriptor))) throw new UnsupportedValueError();
58
+ if (dataKeys.map((key) => Object.getOwnPropertyDescriptor(value, key)).some((descriptor) => !descriptor?.enumerable || !("value" in descriptor))) throw unsupported();
72
59
  if (Array.isArray(value)) {
73
- if (dataKeys.length !== value.length || dataKeys.some((key) => typeof key !== "string" || String(Number(key)) !== key || !Number.isInteger(Number(key)) || Number(key) < 0 || Number(key) >= value.length)) throw new UnsupportedValueError();
60
+ if (dataKeys.length !== value.length || dataKeys.some((key) => typeof key !== "string" || String(Number(key)) !== key || !Number.isInteger(Number(key)) || Number(key) < 0 || Number(key) >= value.length)) throw unsupported();
74
61
  return Array.from({ length: value.length }, (_, index) => inspectValue(Object.getOwnPropertyDescriptor(value, String(index))?.value, seen));
75
62
  }
76
63
  const prototype = Object.getPrototypeOf(value);
77
- if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length) throw new UnsupportedValueError();
64
+ if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length) throw unsupported();
78
65
  return Object.fromEntries(dataKeys.map((key) => [key, inspectValue(Object.getOwnPropertyDescriptor(value, key)?.value, seen)]));
79
66
  } finally {
80
67
  seen.delete(value);
@@ -93,19 +80,13 @@ function inspectKVValue(value) {
93
80
  value: inspectValue(value)
94
81
  };
95
82
  } catch (error) {
96
- if (error instanceof UnsupportedValueError) return;
83
+ if (Reflect.get(Object(error), "code") === "KV_VALUE_UNSUPPORTED") return;
97
84
  throw error;
98
85
  }
99
86
  }
100
87
  //#endregion
101
88
  //#region src/runtime/preview.ts
102
89
  const maximumValueBytes = 262144;
103
- function valueType(value) {
104
- if (value === null) return "null";
105
- if (Array.isArray(value)) return "array";
106
- if (value instanceof Uint8Array) return "bytes";
107
- return typeof value;
108
- }
109
90
  function truncateValue(value) {
110
91
  const encoder = new TextEncoder();
111
92
  let bytes = 0;
@@ -165,7 +146,7 @@ function boundedJSONStringify(value) {
165
146
  editable = false;
166
147
  const toJSON = Reflect.get(Object(input), "toJSON");
167
148
  if (applyToJSON && typeof toJSON === "function") return serialize(toJSON.call(input, key), depth, arrayValue, key, false);
168
- throw new TypeError("Cannot serialize bigint as JSON.");
149
+ throw invariantError("JSON has no bigint without `toJSON()`");
169
150
  }
170
151
  const object = Object(input);
171
152
  const prototype = Object.getPrototypeOf(object);
@@ -184,7 +165,7 @@ function boundedJSONStringify(value) {
184
165
  editable = false;
185
166
  return serialize(boxed, depth, arrayValue, key);
186
167
  }
187
- if (ancestors.has(object)) throw new TypeError("Cannot serialize a circular value as JSON.");
168
+ if (ancestors.has(object)) throw invariantError("JSON has no circular value");
188
169
  if (seen.has(object)) editable = false;
189
170
  seen.add(object);
190
171
  ancestors.add(object);
@@ -231,7 +212,7 @@ function boundedJSONStringify(value) {
231
212
  }
232
213
  /** A stored value as text of at most 256 KiB, for a page that shows it. Bytes become hex. */
233
214
  function previewKVValue(value) {
234
- const type = valueType(value);
215
+ const type = kvValueType(value);
235
216
  let format = "json";
236
217
  let rendered;
237
218
  let truncated = false;
@@ -240,7 +221,7 @@ function previewKVValue(value) {
240
221
  editable = true;
241
222
  format = "text";
242
223
  rendered = value;
243
- } else if (value instanceof Uint8Array) {
224
+ } else if (isUint8Array(value)) {
244
225
  format = "text";
245
226
  const maximumBytes = maximumValueBytes / 2;
246
227
  truncated = value.byteLength > maximumBytes;
@@ -279,24 +260,20 @@ try {
279
260
  } catch (error) {
280
261
  if (!isMissingKVConfig(error)) throw error;
281
262
  }
282
- /** A failure with the fields that every surface reports. */
283
- var KVOperationError = class extends Error {
284
- status;
285
- code;
286
- fix;
287
- constructor(message, status, code, fix) {
288
- super(redactInspectionText(message));
289
- this.status = status;
290
- this.code = code;
291
- this.fix = fix;
292
- }
263
+ /** The HTTP status that the CLI, the Console, and Agents report for each code of a failed operation. */
264
+ const kvOperationStatus = {
265
+ KV_DISABLED: 409,
266
+ KV_INVALID_CURSOR: 400,
267
+ KV_INVALID_INPUT: 400,
268
+ KV_RESERVED_KEY: 403,
269
+ KV_STORE_NOT_FOUND: 404,
270
+ KV_VALUE_UNSUPPORTED: 422
293
271
  };
294
272
  const maximumKeyLength = 2048;
295
273
  function unwrap(result) {
296
274
  const [error, value] = result;
297
275
  if (!error) return value;
298
- const cause = error.code === "KV_OPERATION_FAILED" && error.cause instanceof Error ? ` ${error.cause.message}` : "";
299
- throw new KVOperationError(`${error.message}${cause}`, error.code === "KV_INVALID_CURSOR" ? 400 : 502, error.code);
276
+ throw Object.assign(error, { status: kvOperationStatus[error.code] ?? 502 });
300
277
  }
301
278
  function resolvedStores(config) {
302
279
  if (!config) return [];
@@ -311,18 +288,20 @@ function listKVDevStores() {
311
288
  return resolvedStores(kvConfig);
312
289
  }
313
290
  function ttlNotice(driver, ttl) {
314
- if (driver === "fs-lite") return "The fs-lite driver ignores TTL. The value does not expire.";
315
291
  if (driver === "upstash" && Math.ceil(ttl) !== ttl) return `Upstash rounds the TTL up to ${Math.ceil(ttl)} seconds.`;
316
- if (driver === "cloudflare-kv-binding") {
292
+ if (driver === "cloudflare") {
317
293
  const effectiveTTL = Math.max(60, Math.ceil(ttl));
318
294
  if (ttl < 60) return "Cloudflare KV raises a TTL below 60 seconds to 60 seconds.";
319
295
  if (effectiveTTL !== ttl) return `Cloudflare KV rounds the TTL up to ${effectiveTTL} seconds.`;
320
296
  }
321
297
  }
322
298
  function selectStore(stores, name = "default") {
323
- if (stores.length === 0) throw new KVOperationError("KV is disabled in this runtime. Configure `hubKv()` without `kv: false`.", 409, "KV_DISABLED", "Enable KV with hubKv() or vitehub({ kv: true }).");
299
+ if (stores.length === 0) throw kvErrorDiagnostics.KV_DISABLED();
324
300
  const store = stores.find((entry) => entry.name === name);
325
- if (!store) throw new KVOperationError(`KV store "${name}" was not found. Stores: ${stores.map((entry) => entry.name).join(", ")}.`, 404, "KV_STORE_NOT_FOUND");
301
+ if (!store) throw kvErrorDiagnostics.KV_STORE_NOT_FOUND({
302
+ store: name,
303
+ stores: stores.map((entry) => entry.name).join(", ")
304
+ });
326
305
  return {
327
306
  driver: store.driver,
328
307
  name,
@@ -332,11 +311,17 @@ function selectStore(stores, name = "default") {
332
311
  /** The keys under `vitehub:` belong to ViteHub, which keeps its own state there. */
333
312
  function requireWritableKey(operation, key) {
334
313
  if (!normalizeKey(key).toLowerCase().startsWith("vitehub:")) return;
335
- throw new KVOperationError(`The ${operation} operation cannot change ${key}. ViteHub owns the keys that start with \`vitehub:\`.`, 403, "KV_RESERVED_KEY", "Use another key. Read access (get, has, list) stays open.");
314
+ throw kvErrorDiagnostics.KV_RESERVED_KEY({
315
+ key,
316
+ operation
317
+ });
336
318
  }
337
319
  function requireKey(operation, input) {
338
- if (input.key === void 0) throw new KVOperationError(`The ${operation} operation requires a key.`, 400, "KV_INVALID_INPUT");
339
- if (input.key.length > maximumKeyLength) throw new KVOperationError("The key is too long.", 400, "KV_INVALID_INPUT");
320
+ if (input.key === void 0) throw kvErrorDiagnostics.KV_INVALID_INPUT({
321
+ operation,
322
+ problem: "key"
323
+ });
324
+ if (input.key.length > maximumKeyLength) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "key-length" });
340
325
  return input.key;
341
326
  }
342
327
  /**
@@ -344,12 +329,29 @@ function requireKey(operation, input) {
344
329
  * bindings, so this runs where the app does. There is no operation that clears a store.
345
330
  */
346
331
  async function runKVOperation(operation, input, stores = listKVDevStores()) {
332
+ try {
333
+ return await runOperation(operation, input, stores);
334
+ } catch (error) {
335
+ const code = Reflect.get(Object(error), "code");
336
+ const status = Reflect.get(Object(error), "status") ?? (typeof code === "string" ? kvOperationStatus[code] : void 0);
337
+ if (typeof status !== "number" || !(error instanceof Error)) throw error;
338
+ const cause = code === "KV_OPERATION_FAILED" && error.cause instanceof Error ? ` ${error.cause.message}` : "";
339
+ throw Object.assign(error, {
340
+ status,
341
+ statusMessage: redactInspectionText(`${error.message}${cause}`)
342
+ });
343
+ }
344
+ }
345
+ async function runOperation(operation, input, stores) {
347
346
  const selected = selectStore(stores, input.store);
348
347
  switch (operation) {
349
348
  case "list": {
350
349
  const limit = input.limit ?? 100;
351
- if (limit > 1e3) throw new KVOperationError(`limit must be at most ${kvDevMaximumListLimit}.`, 400, "KV_INVALID_INPUT");
352
- if ((input.prefix?.length ?? 0) > maximumKeyLength) throw new KVOperationError("The prefix is too long.", 400, "KV_INVALID_INPUT");
350
+ if (limit > 1e3) throw kvErrorDiagnostics.KV_INVALID_INPUT({
351
+ limit: kvDevMaximumListLimit,
352
+ problem: "limit"
353
+ });
354
+ if ((input.prefix?.length ?? 0) > maximumKeyLength) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "prefix-length" });
353
355
  const listOptions = {
354
356
  limit,
355
357
  prefix: input.prefix ?? ""
@@ -357,6 +359,7 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
357
359
  if (input.cursor) listOptions.cursor = input.cursor;
358
360
  const page = unwrap(await selected.storage.list(listOptions));
359
361
  const result = {
362
+ driver: selected.driver,
360
363
  keys: page.keys,
361
364
  limit,
362
365
  prefix: input.prefix ?? "",
@@ -375,14 +378,14 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
375
378
  key,
376
379
  store: selected.name
377
380
  };
378
- if (found) result.expiry = selected.driver === "fs-lite" ? "none" : "unknown";
381
+ if (found) result.expiry = "unknown";
379
382
  if (!found) return result;
380
383
  if (input.preview) return {
381
384
  ...result,
382
385
  ...previewKVValue(value)
383
386
  };
384
387
  const inspected = inspectKVValue(value);
385
- if (!inspected) throw new KVOperationError("The stored value cannot be represented by the KV inspection protocol.", 422, "KV_VALUE_UNSUPPORTED");
388
+ if (!inspected) throw kvErrorDiagnostics.KV_VALUE_UNSUPPORTED();
386
389
  return {
387
390
  ...result,
388
391
  ...inspected
@@ -399,10 +402,10 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
399
402
  case "set": {
400
403
  const key = requireKey(operation, input);
401
404
  requireWritableKey(operation, key);
402
- if (input.value === void 0) throw new KVOperationError("The set operation requires a value.", 400, "KV_INVALID_INPUT");
403
- if (selected.driver === "upstash" && input.ttl !== void 0 && input.ttl < 1) throw new KVOperationError("Upstash TTL must be at least 1 second.", 400, "KV_INVALID_INPUT");
405
+ if (input.value === void 0) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "value" });
406
+ if (selected.driver === "upstash" && input.ttl !== void 0 && input.ttl < 1) throw kvErrorDiagnostics.KV_INVALID_INPUT({ problem: "ttl" });
404
407
  const existed = unwrap(await selected.storage.has(key));
405
- const ttl = input.ttl === void 0 ? void 0 : selected.driver === "cloudflare-kv-binding" ? Math.max(60, Math.ceil(input.ttl)) : selected.driver === "upstash" ? Math.ceil(input.ttl) : input.ttl;
408
+ const ttl = input.ttl === void 0 ? void 0 : selected.driver === "cloudflare" ? Math.max(60, Math.ceil(input.ttl)) : selected.driver === "upstash" ? Math.ceil(input.ttl) : input.ttl;
406
409
  unwrap(await selected.storage.set(key, input.value, ttl === void 0 ? void 0 : { ttl }));
407
410
  const notice = input.ttl ? ttlNotice(selected.driver, input.ttl) : void 0;
408
411
  const result = {
@@ -415,11 +418,11 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
415
418
  if (ttl) result.ttl = ttl;
416
419
  return result;
417
420
  }
418
- case "del": {
421
+ case "delete": {
419
422
  const key = requireKey(operation, input);
420
423
  requireWritableKey(operation, key);
421
424
  const existed = unwrap(await selected.storage.has(key));
422
- unwrap(await selected.storage.del(key));
425
+ unwrap(await selected.storage.delete(key));
423
426
  return {
424
427
  deleted: existed,
425
428
  key,
@@ -429,4 +432,4 @@ async function runKVOperation(operation, input, stores = listKVDevStores()) {
429
432
  }
430
433
  }
431
434
  //#endregion
432
- export { KVOperationError, listKVDevStores, runKVOperation };
435
+ export { listKVDevStores, runKVOperation };