@vite-hub/kv 0.4.1 → 0.5.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 (62) hide show
  1. package/README.md +7 -3
  2. package/dist/{batch--v0ri69O.js → batch-D-ib5_0P.js} +0 -1
  3. package/dist/{cli-DpPhz_Ek.d.ts → cli-BvVInMht.d.ts} +1 -6
  4. package/dist/cli.d.ts +2 -4
  5. package/dist/cli.js +24 -14
  6. package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Bm6huR35.js} +4 -4
  7. package/dist/{cloudflare-env-lookup-Bs0VDpU5.js → cloudflare-env-lookup-Dgq5n1Aq.js} +1 -2
  8. package/dist/{cloudflare-kv-C3NO4C21.js → cloudflare-kv-K2MzfP6D.js} +12 -16
  9. package/dist/{cloudflare-kv-local-C2sbIrFy.js → cloudflare-kv-local-lov9LLhU.js} +5 -10
  10. package/dist/{config-LfpUj9hs.js → config-B8FRGmX_.js} +53 -22
  11. package/dist/{create-storage-BORQm2a8.js → create-storage-BMvkkYdM.js} +9 -15
  12. package/dist/{cursor-history-DRHh5bO5.js → cursor-history-C6oG12QO.js} +9 -6
  13. package/dist/{deno-kv-D_VtffFv.js → deno-kv-MnqlNH1e.js} +45 -10
  14. package/dist/{dev-peer-CHafxbtj.js → dev-peer-D0vOxmrD.js} +1 -2
  15. package/dist/driver-bLMl-wMO.d.ts +43 -0
  16. package/dist/durability.d.ts +1 -3
  17. package/dist/durability.js +1 -2
  18. package/dist/{error-diagnostics-C54QQEhN.js → error-diagnostics-DUIp6FhO.js} +7 -4
  19. package/dist/{errors-DzD6YNEH.js → errors-IaVOqzAs.js} +42 -8
  20. package/dist/errors.d.ts +8 -5
  21. package/dist/errors.js +1 -2
  22. package/dist/fs-lite-DhXLUL-H.js +1 -0
  23. package/dist/{fs-lite-BaklCLuV.js → fs-lite-fvNdBEr9.js} +3 -5
  24. package/dist/index.d.ts +1 -3
  25. package/dist/index.js +34 -66
  26. package/dist/{inspect-BIKQsqX4.js → inspect-BWMcVWD8.js} +2 -4
  27. package/dist/{invariant-DolT9EEx.js → invariant-Dj2R1eMr.js} +1 -2
  28. package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
  29. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  30. package/dist/{operations-D2iI9oN4.js → operations-CGAX5ASA.js} +53 -28
  31. package/dist/{operations-CtrWLmPK.js → operations-FgS_sJ3M.js} +27 -45
  32. package/dist/operations.d.ts +2 -8
  33. package/dist/operations.js +8 -12
  34. package/dist/out-By90R-Bo.js +22706 -0
  35. package/dist/{redis-shared-5ogRd3-Y.js → redis-shared-DO7Ib1Sz.js} +2 -3
  36. package/dist/request-log-DllKQXj7.js +104 -0
  37. package/dist/results-emgN7uDS.js +4 -0
  38. package/dist/rolldown-runtime-DegdyBIC.js +25 -0
  39. package/dist/runtime/cloudflare-kv.d.ts +1 -3
  40. package/dist/runtime/cloudflare-kv.js +1 -2
  41. package/dist/runtime/cloudflare-request-env.d.ts +1 -3
  42. package/dist/runtime/cloudflare-request-env.js +2 -3
  43. package/dist/runtime/database.d.ts +2 -0
  44. package/dist/{database-oJdy0ZVX.js → runtime/database.js} +69 -39
  45. package/dist/runtime/nitro-plugin.d.ts +1 -2
  46. package/dist/runtime/nitro-plugin.js +11 -8
  47. package/dist/runtime/redis-driver.d.ts +3 -5
  48. package/dist/runtime/redis-driver.js +6 -10
  49. package/dist/runtime/unstorage-driver.d.ts +2 -4
  50. package/dist/runtime/unstorage-driver.js +2 -3
  51. package/dist/runtime/upstash-driver.d.ts +3 -5
  52. package/dist/runtime/upstash-driver.js +6 -11
  53. package/dist/{types-Bj3EQoRg.d.ts → types-BUb0FcjM.d.ts} +0 -2
  54. package/dist/{types-Dv-OSXZC.d.ts → types-C397WKyf.d.ts} +4 -20
  55. package/dist/{upstash-B-vaUYqO.js → upstash-DQVo1zbz.js} +3 -4
  56. package/dist/{utils2-FozcTsmb.js → utils2-By8eee1x.js} +1 -2
  57. package/dist/vite.d.ts +8 -19
  58. package/dist/vite.js +2676 -104
  59. package/package.json +15 -10
  60. package/dist/driver-R4Z5Z5fl.d.ts +0 -15
  61. package/dist/fs-lite-BAgpmNAF.js +0 -2
  62. package/dist/results-p7nPCnaJ.js +0 -6
@@ -1,4 +1,3 @@
1
- //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
2
1
  /** The Standard Typed interface. This is a base type extended by other specs. */
3
2
  interface StandardTypedV1<Input = unknown, Output = Input> {
4
3
  /** The Standard properties. */
@@ -74,8 +73,6 @@ declare namespace StandardSchemaV1 {
74
73
  /** Infers the output type of a Standard. */
75
74
  type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
75
  }
77
- //#endregion
78
- //#region ../internal/src/operation-definition.d.ts
79
76
  /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
77
  type OperationKind = "read" | "write" | "destructive";
81
78
  /** The signed-in user of a call. */
@@ -104,6 +101,11 @@ interface OperationAccess {
104
101
  */
105
102
  readonly sections: "all" | readonly string[];
106
103
  readonly user?: OperationUser;
104
+ /**
105
+ * Who signed the call: `"console"` when the ViteHub Console signed it for a person, whose `user` is then a Console
106
+ * account and not an app user, or `"cli"` for a key. Not set for other calls.
107
+ */
108
+ readonly via?: "console" | "cli";
107
109
  }
108
110
  interface OperationContext {
109
111
  /** The checked Console access of the call. */
@@ -166,7 +168,8 @@ interface OperationDefinition<Input, Output> {
166
168
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
167
169
  input: StandardSchemaV1<unknown, Input>;
168
170
  output?: StandardSchemaV1<unknown, Output>;
169
- cli?: {
171
+ /** `false`: no `vitehub` command. The Console and MCP still call the operation. */
172
+ cli?: false | {
170
173
  /** Defaults: namespace = section, command = verb. */
171
174
  namespace?: string;
172
175
  /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
@@ -207,7 +210,7 @@ interface OperationDefinition<Input, Output> {
207
210
  /** An operation of any input and output, as a registry holds it. */
208
211
  interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
209
212
  readOnlyWhen?: (input: never) => boolean;
210
- cli?: {
213
+ cli?: false | {
211
214
  namespace?: string;
212
215
  command?: string;
213
216
  default?: boolean;
@@ -235,5 +238,4 @@ interface OperationContributionEntry {
235
238
  /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
236
239
  runtime?: false;
237
240
  }
238
- //#endregion
239
241
  export { OperationContributionEntry as n, AnyOperation as t };
@@ -1,5 +1,5 @@
1
- import { n as isRecordOrFunction, t as isRecord } from "./object-Da1zyPCR.js";
2
- import { t as invariant } from "./invariant-DolT9EEx.js";
1
+ import { n as isRecordOrFunction, t as isRecord } from "./object-CAK6UYR5.js";
2
+ import { t as invariant } from "./invariant-Dj2R1eMr.js";
3
3
  import { readdir } from "node:fs/promises";
4
4
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
5
5
  import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -9,7 +9,7 @@ import { tmpdir } from "node:os";
9
9
  import "node:url";
10
10
  import { createBirpc } from "birpc";
11
11
  import { toJsonSchema } from "@valibot/to-json-schema";
12
- //#region ../internal/src/error-diagnostics.ts
12
+ // ../internal/src/error-diagnostics.ts
13
13
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
14
14
  const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
15
15
  docsBase: "https://vitehub.dev/docs/development/diagnostics",
@@ -35,7 +35,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
35
35
  why: ({ message }) => message === void 0 ? "" : String(message)
36
36
  },
37
37
  INTERNAL_R0022: {
38
- fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
38
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields, and the list_operations tool of the ViteHub MCP gives the input schema of each operation.",
39
39
  why: ({ message }) => message === void 0 ? "" : String(message)
40
40
  },
41
41
  INTERNAL_R0024: {
@@ -254,6 +254,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
254
254
  why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
255
255
  fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
256
256
  },
257
+ INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT: {
258
+ why: ({ first, name, second }) => `[vitehub] One server function needs ${name} from two installations: ${first} and ${second}.`,
259
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`, then build again."
260
+ },
257
261
  INTERNAL_SECRET_PURPOSE_MISSING: {
258
262
  why: "[vitehub] A derived secret requires a purpose.",
259
263
  fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
@@ -262,6 +266,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
262
266
  why: ({ minimum }) => `[vitehub] VITEHUB_SECRET must be at least ${minimum} characters. Generate one with \`openssl rand -base64 32\`.`,
263
267
  fix: "Set `VITEHUB_SECRET` to the output of `openssl rand -base64 32`, which has 44 characters."
264
268
  },
269
+ INTERNAL_SITE_TOKEN_TOO_LONG: {
270
+ why: ({ length, maximum }) => `The Site access token is ${length} characters, and an app accepts ${maximum}.`,
271
+ fix: "Open the app with a shorter path, or give the person and the project shorter names, so that the Site access token fits."
272
+ },
265
273
  INTERNAL_SQLITE_ARGUMENT_INVALID: {
266
274
  why: ({ value }) => value === "undefined" ? "undefined cannot be passed as argument to the database" : "Only finite numbers (not Infinity or NaN) can be passed as arguments",
267
275
  fix: "Pass query arguments as finite numbers, strings, booleans, bigints, dates, byte arrays, or null. Replace undefined with null, and check numbers with `Number.isFinite()` before the query."
@@ -276,8 +284,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
276
284
  }
277
285
  }
278
286
  });
279
- //#endregion
280
- //#region ../internal/src/cli.ts
287
+ // ../internal/src/cli.ts
281
288
  /**
282
289
  * The seed files in `dir` and its subfolders, as sorted paths relative to `dir` with `/`. Files and folders whose name
283
290
  * starts with `.`, such as `.gitkeep`, are not seed files. Returns `undefined` when `dir` does not exist.
@@ -414,8 +421,7 @@ function findViteHubDevServerUrl(roots, env) {
414
421
  }
415
422
  return env["VITEHUB_DEV_SERVER_URL"] || void 0;
416
423
  }
417
- //#endregion
418
- //#region ../internal/src/build/vite.ts
424
+ // ../internal/src/build/vite.ts
419
425
  const projectRootDirectoryMarkers = [
420
426
  ["server", "agents"],
421
427
  ["server", "channels"],
@@ -432,6 +438,10 @@ const projectRootFileMarkers = [
432
438
  ["nuxt.config.js"],
433
439
  ["nuxt.config.mjs"]
434
440
  ];
441
+ /** Record a selected plugin in its pre config hook, before other plugins consume the selection. */
442
+ function markViteConfigPlugin(env, name) {
443
+ Reflect.set(env, Symbol.for(`vitehub.config-plugin:${name}`), true);
444
+ }
435
445
  function createNoExternalAddition(...packageNames) {
436
446
  return (current) => {
437
447
  if (current === true) return;
@@ -443,6 +453,7 @@ function createNoExternalAddition(...packageNames) {
443
453
  function isServerEnvironment(name, config) {
444
454
  return name === "ssr" || config.consumer === "server";
445
455
  }
456
+ const VITEHUB_NITRO_CONFIG_CONTEXT = "__vitehubNitroConfigContext";
446
457
  const VITEHUB_PROJECT_ROOT = "__vitehubProjectRoot";
447
458
  /**
448
459
  * Set by `vite-hub/nuxt` when it replays Vite config hooks for `nuxt prepare`. Prepare uses `command: "build"` to write
@@ -487,7 +498,7 @@ function hasProjectRootDirectoryMarker(root) {
487
498
  for (const marker of projectRootDirectoryMarkers) try {
488
499
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
489
500
  } catch (error) {
490
- if (error.code !== "ENOENT") throw error;
501
+ if (!isMissingProjectMarker(error)) throw error;
491
502
  }
492
503
  return false;
493
504
  }
@@ -501,13 +512,16 @@ function hasProjectRootFileMarker(root, markers) {
501
512
  try {
502
513
  if (statSync(resolve(root, ...path)).isFile()) return true;
503
514
  } catch (error) {
504
- if (error.code !== "ENOENT") throw error;
515
+ if (!isMissingProjectMarker(error)) throw error;
505
516
  }
506
517
  }
507
518
  return false;
508
519
  }
509
- //#endregion
510
- //#region ../internal/src/operation-rpc.ts
520
+ function isMissingProjectMarker(error) {
521
+ const code = error.code;
522
+ return code === "ENOENT" || code === "ENOTDIR";
523
+ }
524
+ // ../internal/src/operation-rpc.ts
511
525
  /** Path of the operation RPC under the app. Dev servers and deployed apps serve it the same way, one birpc call per POST. */
512
526
  const operationRpcPath = "/_vitehub/rpc";
513
527
  const maximumIdLength = 128;
@@ -660,8 +674,7 @@ async function callOperationRpc(name, input, send) {
660
674
  };
661
675
  }
662
676
  }
663
- //#endregion
664
- //#region ../internal/src/console-signature.ts
677
+ // ../internal/src/console-signature.ts
665
678
  /**
666
679
  * Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
667
680
  * CI job, has an Ed25519 key pair. The app keeps only the public keys, in `VITEHUB_CONSOLE_KEY_<NAME>`, so a copy of
@@ -790,8 +803,7 @@ function readConsoleSigningKey(env) {
790
803
  privateKey
791
804
  };
792
805
  }
793
- //#endregion
794
- //#region ../internal/src/standard-schema.ts
806
+ // ../internal/src/standard-schema.ts
795
807
  function readOwn(value, key) {
796
808
  if (value === null || Object(value) !== value) return;
797
809
  try {
@@ -820,8 +832,7 @@ function standardJsonSchema(schema, direction, target = "draft-2020-12", library
820
832
  return;
821
833
  }
822
834
  }
823
- //#endregion
824
- //#region ../internal/src/valibot.ts
835
+ // ../internal/src/valibot.ts
825
836
  const valibotTargets = /* @__PURE__ */ new Set([
826
837
  "draft-07",
827
838
  "draft-2020-12",
@@ -862,8 +873,7 @@ function withValibotJsonSchema(schema, options = {}) {
862
873
  }
863
874
  };
864
875
  }
865
- //#endregion
866
- //#region ../internal/src/operation-definition.ts
876
+ // ../internal/src/operation-definition.ts
867
877
  const nameFormat = /^[a-z][a-z0-9-]*\.[a-z][a-z0-9-]*$/;
868
878
  const kinds = /* @__PURE__ */ new Set([
869
879
  "read",
@@ -953,8 +963,7 @@ function isSectionId(section) {
953
963
  function operationInputJsonSchema(operation) {
954
964
  return standardJsonSchema(operation.input, "input") ?? { type: "object" };
955
965
  }
956
- //#endregion
957
- //#region ../internal/src/operations.ts
966
+ // ../internal/src/operations.ts
958
967
  /** Header that proves the caller is not a browser page. A foreign page cannot send it without a CORS preflight. */
959
968
  const operationRpcHeader = "x-vitehub-console";
960
969
  /** Response header of the local dev RPC. Its value is {@link projectRootHash} of the project that the server runs. */
@@ -1021,11 +1030,16 @@ function operationsOf(value) {
1021
1030
  /** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
1022
1031
  function operationCliPath(operation) {
1023
1032
  const dot = operation.name.indexOf(".");
1033
+ const cli = operationCliOptions(operation);
1024
1034
  return {
1025
- command: operation.cli?.command ?? operation.name.slice(dot + 1),
1026
- namespace: operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
1035
+ command: cli?.command ?? operation.name.slice(dot + 1),
1036
+ namespace: cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
1027
1037
  };
1028
1038
  }
1039
+ /** The CLI options of an operation, or undefined for an operation without options or with `cli: false`. */
1040
+ function operationCliOptions(operation) {
1041
+ return operation.cli || void 0;
1042
+ }
1029
1043
  /**
1030
1044
  * The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
1031
1045
  * Claude reject a dot in a tool name. `content.publish` is `content_publish`.
@@ -1050,6 +1064,7 @@ function createOperationRegistry(sources) {
1050
1064
  const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
1051
1065
  const commands = /* @__PURE__ */ new Map();
1052
1066
  for (const operation of operations) {
1067
+ if (operation.cli === false) continue;
1053
1068
  const { command, namespace } = operationCliPath(operation);
1054
1069
  if (reservedOperationNamespaces.includes(namespace)) throw invalidDefinition(operation.name, `the CLI namespace ${JSON.stringify(namespace)} is reserved for built-in commands. Set cli.namespace to another name.`);
1055
1070
  const key = `${namespace} ${command}`;
@@ -1077,12 +1092,23 @@ function describeInputIssues(issues) {
1077
1092
  return path ? `${path}: ${issue.message}` : issue.message;
1078
1093
  }).join(" ");
1079
1094
  }
1095
+ function describeInputFields(schema) {
1096
+ const shapes = (Array.isArray(schema.anyOf) ? schema.anyOf : [schema]).map((shape) => {
1097
+ if (!isRecordOrFunction(shape) || !isRecordOrFunction(shape.properties)) return void 0;
1098
+ const required = Array.isArray(shape.required) ? shape.required : [];
1099
+ const fields = Object.keys(shape.properties).map((field) => required.includes(field) ? field : `${field}?`);
1100
+ return fields.length ? `{ ${fields.join(", ")} }` : "{}";
1101
+ });
1102
+ return shapes.every((shape) => shape !== void 0) ? shapes.join(" or ") : void 0;
1103
+ }
1080
1104
  /** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
1081
1105
  async function parseOperationInput(operation, input) {
1082
1106
  const result = await operation.input["~standard"].validate(input ?? {});
1083
1107
  if (!result.issues) return result.value;
1084
- const error = internalErrorDiagnostics.INTERNAL_R0022({ message: `Invalid input for ${operation.name}. ${describeInputIssues(result.issues)}` });
1085
- throw Object.assign(error, { status: 400 });
1108
+ const fields = describeInputFields(operationInputJsonSchema(operation));
1109
+ const issues = describeInputIssues(result.issues);
1110
+ const message = `Invalid input for ${operation.name}. ${issues}${fields ? `${/[.!?]$/.test(issues) ? "" : "."} ${operation.name} takes ${fields}.` : ""}`;
1111
+ throw Object.assign(internalErrorDiagnostics.INTERNAL_R0022({ message }), { status: 400 });
1086
1112
  }
1087
1113
  /**
1088
1114
  * The section that grants a call, or `false` for any Console user. `undefined` means the input names no valid section.
@@ -1359,5 +1385,4 @@ async function callOperationFromCli(call, name, input) {
1359
1385
  url
1360
1386
  }, name, input);
1361
1387
  }
1362
- //#endregion
1363
- export { writeCliFailure as A, askOnTerminal as C, readViteHubDevServerFile as D, readCliOptionValue as E, internalErrorDiagnostics as M, readViteHubDevTargetOption as O, shouldSkipViteProviderBuild as S, parseCliPositiveInteger as T, VITEHUB_PROJECT_ROOT as _, operationRootHeader as a, isServerEnvironment as b, projectRootHash as c, defineOperation as d, answerOperationRpc as f, VITEHUB_PREPARE as g, readOperationRpcCall as h, createOperationRegistry as i, writeViteHubDevServerFile as j, removeViteHubDevServerFile as k, runOperation as l, operationRpcRefusal as m, callOperationFromCli as n, operationRpcHeader as o, operationRpcPath as p, collectOperationContributions as r, operationsOf as s, assertOperationProject as t, toOperationFailure as u, createNoExternalAddition as v, listSeedFiles as w, resolveViteHubProjectRoot as x, hasNitroConfigContext as y };
1388
+ export { readViteHubDevTargetOption as A, resolveViteHubProjectRoot as C, parseCliPositiveInteger as D, listSeedFiles as E, writeCliFailure as M, writeViteHubDevServerFile as N, readCliOptionValue as O, internalErrorDiagnostics as P, markViteConfigPlugin as S, askOnTerminal as T, VITEHUB_PREPARE as _, operationRootHeader as a, hasNitroConfigContext as b, projectRootHash as c, defineOperation as d, answerOperationRpc as f, VITEHUB_NITRO_CONFIG_CONTEXT as g, readOperationRpcCall as h, createOperationRegistry as i, removeViteHubDevServerFile as j, readViteHubDevServerFile as k, runOperation as l, operationRpcRefusal as m, callOperationFromCli as n, operationRpcHeader as o, operationRpcPath as p, collectOperationContributions as r, operationsOf as s, assertOperationProject as t, toOperationFailure as u, VITEHUB_PROJECT_ROOT as v, shouldSkipViteProviderBuild as w, isServerEnvironment as x, createNoExternalAddition as y };
@@ -1,10 +1,9 @@
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";
4
- import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
5
- import { o as normalizeKey } from "./utils2-FozcTsmb.js";
1
+ import { o as normalizeKey } from "./utils2-By8eee1x.js";
2
+ import { t as redactInspectionText } from "./inspect-BWMcVWD8.js";
3
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
4
+ import { t as kvDevMaximumListLimit } from "./results-emgN7uDS.js";
6
5
  import { kv } from "@vite-hub/kv";
7
- //#region src/runtime/inspect-value.ts
6
+ // src/runtime/inspect-value.ts
8
7
  const unsupported = () => kvErrorDiagnostics.KV_VALUE_UNSUPPORTED();
9
8
  function isUint8Array(value) {
10
9
  try {
@@ -22,30 +21,10 @@ function kvValueType(value) {
22
21
  return typeof value;
23
22
  }
24
23
  function encodeBase64(bytes) {
25
- try {
26
- const lengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "length")?.get;
27
- if (!lengthGetter) throw unsupported();
28
- const length = Reflect.apply(lengthGetter, bytes, []);
29
- for (const key of ["byteLength", "length"]) {
30
- const descriptor = Object.getOwnPropertyDescriptor(bytes, key);
31
- if (descriptor && (!("value" in descriptor) || descriptor.value !== length)) throw unsupported();
32
- }
33
- const encoded = [];
34
- let chunk = [];
35
- for (const byte of Reflect.apply(Uint8Array.prototype.values, bytes, [])) {
36
- chunk.push(byte);
37
- if (chunk.length === 12288) {
38
- encoded.push(btoa(String.fromCharCode(...chunk)));
39
- chunk = [];
40
- }
41
- }
42
- if (chunk.length) encoded.push(btoa(String.fromCharCode(...chunk)));
43
- return encoded.join("");
44
- } catch {
45
- throw unsupported();
46
- }
24
+ const encoded = [];
25
+ for (let offset = 0; offset < bytes.byteLength; offset += 12288) encoded.push(btoa(String.fromCharCode(...bytes.subarray(offset, offset + 12288))));
26
+ return encoded.join("");
47
27
  }
48
- /** JSON inspection accepts JSON values and represents bigint values as decimal strings. */
49
28
  function inspectValue(value, seen = /* @__PURE__ */ new WeakSet()) {
50
29
  if (typeof value === "bigint") return value.toString();
51
30
  if (value === null || typeof value === "string" || typeof value === "boolean") return value;
@@ -84,8 +63,7 @@ function inspectKVValue(value) {
84
63
  throw error;
85
64
  }
86
65
  }
87
- //#endregion
88
- //#region src/runtime/preview.ts
66
+ // src/runtime/preview.ts
89
67
  const maximumValueBytes = 262144;
90
68
  function truncateValue(value) {
91
69
  const encoder = new TextEncoder();
@@ -107,6 +85,7 @@ function truncateValue(value) {
107
85
  }
108
86
  function boundedJSONStringify(value) {
109
87
  let editable = true;
88
+ let unsupported = false;
110
89
  let bytes = 0;
111
90
  let rendered = "";
112
91
  let truncated = false;
@@ -146,7 +125,8 @@ function boundedJSONStringify(value) {
146
125
  editable = false;
147
126
  const toJSON = Reflect.get(Object(input), "toJSON");
148
127
  if (applyToJSON && typeof toJSON === "function") return serialize(toJSON.call(input, key), depth, arrayValue, key, false);
149
- throw invariantError("JSON has no bigint without `toJSON()`");
128
+ unsupported = true;
129
+ return false;
150
130
  }
151
131
  const object = Object(input);
152
132
  const prototype = Object.getPrototypeOf(object);
@@ -165,7 +145,10 @@ function boundedJSONStringify(value) {
165
145
  editable = false;
166
146
  return serialize(boxed, depth, arrayValue, key);
167
147
  }
168
- if (ancestors.has(object)) throw invariantError("JSON has no circular value");
148
+ if (ancestors.has(object)) {
149
+ unsupported = true;
150
+ return false;
151
+ }
169
152
  if (seen.has(object)) editable = false;
170
153
  seen.add(object);
171
154
  ancestors.add(object);
@@ -204,6 +187,7 @@ function boundedJSONStringify(value) {
204
187
  return append("}");
205
188
  }
206
189
  const serialized = serialize(value, 0, false, "");
190
+ if (unsupported) return void 0;
207
191
  return {
208
192
  editable,
209
193
  truncated,
@@ -226,14 +210,16 @@ function previewKVValue(value) {
226
210
  const maximumBytes = maximumValueBytes / 2;
227
211
  truncated = value.byteLength > maximumBytes;
228
212
  rendered = Array.from(value.subarray(0, maximumBytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
229
- } else try {
213
+ } else {
230
214
  const result = boundedJSONStringify(value);
231
- rendered = result.value ?? String(value);
232
- truncated = result.truncated;
233
- editable = result.editable;
234
- } catch {
235
- format = "text";
236
- rendered = String(value);
215
+ if (result) {
216
+ rendered = result.value ?? String(value);
217
+ truncated = result.truncated;
218
+ editable = result.editable;
219
+ } else {
220
+ format = "text";
221
+ rendered = String(value);
222
+ }
237
223
  }
238
224
  const result = truncateValue(rendered);
239
225
  const formatted = {
@@ -245,8 +231,7 @@ function previewKVValue(value) {
245
231
  if (truncated || result.truncated) formatted.truncated = true;
246
232
  return formatted;
247
233
  }
248
- //#endregion
249
- //#region src/runtime/operations.ts
234
+ // src/runtime/operations.ts
250
235
  function isMissingKVConfig(error) {
251
236
  const code = error instanceof Error && "code" in error ? error.code : void 0;
252
237
  const message = error instanceof Error ? error.message : "";
@@ -260,7 +245,6 @@ try {
260
245
  } catch (error) {
261
246
  if (!isMissingKVConfig(error)) throw error;
262
247
  }
263
- /** The HTTP status that the CLI, the Console, and Agents report for each code of a failed operation. */
264
248
  const kvOperationStatus = {
265
249
  KV_DISABLED: 409,
266
250
  KV_INVALID_CURSOR: 400,
@@ -308,7 +292,6 @@ function selectStore(stores, name = "default") {
308
292
  storage: name === "default" ? kv : kv.store(name)
309
293
  };
310
294
  }
311
- /** The keys under `vitehub:` belong to ViteHub, which keeps its own state there. */
312
295
  function requireWritableKey(operation, key) {
313
296
  if (!normalizeKey(key).toLowerCase().startsWith("vitehub:")) return;
314
297
  throw kvErrorDiagnostics.KV_RESERVED_KEY({
@@ -431,5 +414,4 @@ async function runOperation(operation, input, stores) {
431
414
  }
432
415
  }
433
416
  }
434
- //#endregion
435
417
  export { listKVDevStores, runKVOperation };
@@ -1,6 +1,5 @@
1
- import { c as KVDriver } from "./types-Dv-OSXZC.js";
2
- import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
3
- //#region src/runtime/operations.d.ts
1
+ import { t as AnyOperation } from "./operation-definition-CqZkx1Rm.js";
2
+ import { c as KVDriver } from "./types-C397WKyf.js";
4
3
  interface KVDevListResult {
5
4
  /** Present when more keys exist. Pass it as `--cursor` to read the next page. */
6
5
  cursor?: string;
@@ -55,8 +54,6 @@ interface KVDevDeleteResult {
55
54
  key: string;
56
55
  store: string;
57
56
  }
58
- //#endregion
59
- //#region ../internal/src/operations-dev.d.ts
60
57
  /**
61
58
  * Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
62
59
  * `context.event`, so owner hooks such as `identify` of Comments read its Standard Context.
@@ -67,9 +64,6 @@ export declare function createStandaloneOperationHandler(sources: {
67
64
  }[], root: string): {
68
65
  fetch(request: Request): Promise<Response>;
69
66
  };
70
- //#endregion
71
- //#region src/operations.d.ts
72
67
  /** The `kv.*` operations: list, get, has, set, and delete. The Console, `vitehub kv`, and agents run them. */
73
68
  export declare const kvOperations: readonly AnyOperation[];
74
- //#endregion
75
69
  export type { KVDevDeleteResult, KVDevGetResult, KVDevHasResult, KVDevListResult, KVDevSetResult };
@@ -1,8 +1,8 @@
1
- import { M as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as defineOperation, f as answerOperationRpc, h as readOperationRpcCall, i as createOperationRegistry, l as runOperation, m as operationRpcRefusal, o as operationRpcHeader, s as operationsOf, t as assertOperationProject, u as toOperationFailure } from "./operations-D2iI9oN4.js";
2
- import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
3
- import { n as isViteHubLoopbackPeer } from "./dev-peer-CHafxbtj.js";
1
+ import { P as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as defineOperation, f as answerOperationRpc, h as readOperationRpcCall, i as createOperationRegistry, l as runOperation, m as operationRpcRefusal, o as operationRpcHeader, s as operationsOf, t as assertOperationProject, u as toOperationFailure } from "./operations-CGAX5ASA.js";
2
+ import { t as kvDevMaximumListLimit } from "./results-emgN7uDS.js";
3
+ import { n as isViteHubLoopbackPeer } from "./dev-peer-D0vOxmrD.js";
4
4
  import * as v from "valibot";
5
- //#region ../internal/src/secret.ts
5
+ // ../internal/src/secret.ts
6
6
  const secretEncoder = new TextEncoder();
7
7
  /**
8
8
  * Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
@@ -17,8 +17,7 @@ function isViteHubSecretEqual(actual, expected) {
17
17
  return difference === 0;
18
18
  }
19
19
  Object.freeze({ prefix: "sha256=" });
20
- //#endregion
21
- //#region ../internal/src/dev-endpoint.ts
20
+ // ../internal/src/dev-endpoint.ts
22
21
  const viteHubDevRequestGrantBrand = Symbol("vitehub.devRequestGrant");
23
22
  const devRequestGrants = /* @__PURE__ */ new WeakMap();
24
23
  function grantDevRequest(request, label) {
@@ -98,8 +97,7 @@ async function validateViteHubNitroDevRequest(request, guard) {
98
97
  const rejection = await guard.authorize?.(request);
99
98
  return rejection ? rejectDevRequest(rejection) : grantDevRequest(request, guard.label);
100
99
  }
101
- //#endregion
102
- //#region ../internal/src/operations-dev.ts
100
+ // ../internal/src/operations-dev.ts
103
101
  function readPath(value, ...path) {
104
102
  for (const key of path) value = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
105
103
  return value;
@@ -236,9 +234,8 @@ function createStandaloneOperationHandler(sources, root) {
236
234
  }
237
235
  } };
238
236
  }
239
- //#endregion
240
- //#region src/operations.ts
241
- const runtime = () => import("./operations-CtrWLmPK.js");
237
+ // src/operations.ts
238
+ const runtime = () => import("./operations-FgS_sJ3M.js");
242
239
  const store = v.optional(v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name a store.")));
243
240
  const key = v.string();
244
241
  function defineKVOperation(definition) {
@@ -315,5 +312,4 @@ const kvOperations = [
315
312
  run: async (input) => await (await runtime()).runKVOperation("delete", input)
316
313
  })
317
314
  ];
318
- //#endregion
319
315
  export { createStandaloneOperationHandler, kvOperations };