@vite-hub/kv 0.3.1 → 0.5.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 (50) hide show
  1. package/README.md +19 -13
  2. package/dist/{cli-DpPhz_Ek.d.ts → cli-CLomw9ml.d.ts} +1 -0
  3. package/dist/cli.d.ts +1 -1
  4. package/dist/cli.js +24 -12
  5. package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Dl349h_9.js} +2 -1
  6. package/dist/{cloudflare-kv-BIEUFzRT.js → cloudflare-kv-DQJhmGof.js} +22 -10
  7. package/dist/{cloudflare-kv-local-BBw3ZT1K.js → cloudflare-kv-local-COjgHweC.js} +3 -7
  8. package/dist/{config-BXEVoZE3.js → config-pfyPiPrI.js} +65 -28
  9. package/dist/{create-storage-BGsrQKw3.js → create-storage-DQ1BbFqH.js} +5 -5
  10. package/dist/{cursor-history-BqIQePNP.js → cursor-history-CAT4mpP1.js} +7 -3
  11. package/dist/{deno-kv-BM9mYdUp.js → deno-kv-Cf0ZveeN.js} +43 -7
  12. package/dist/driver-Du6Eh9p2.d.ts +47 -0
  13. package/dist/{error-diagnostics-BxqvtEIb.js → error-diagnostics-C4VTHInS.js} +16 -4
  14. package/dist/errors-BpiM-Vmh.js +125 -0
  15. package/dist/errors.d.ts +13 -1
  16. package/dist/errors.js +2 -2
  17. package/dist/{fs-lite-BLZId9_P.js → fs-lite-BTcBUP6B.js} +1 -1
  18. package/dist/fs-lite-C8yXCVDM.js +2 -0
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +39 -52
  21. package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
  22. package/dist/{operations-Ch-gKaey.js → operations-CqKs7Ykc.js} +24 -45
  23. package/dist/{operations-B-WZ7P1h.js → operations-nAaONxzh.js} +273 -231
  24. package/dist/operations.d.ts +2 -2
  25. package/dist/operations.js +4 -3
  26. package/dist/out-BbXG-yVX.js +21755 -0
  27. package/dist/{redis-shared-E5mahECF.js → redis-shared-1M0IaguQ.js} +1 -1
  28. package/dist/request-log-Dj9Vw7qG.js +105 -0
  29. package/dist/{results-p7nPCnaJ.js → results-D6jfPtCk.js} +0 -1
  30. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  31. package/dist/runtime/cloudflare-kv.js +1 -1
  32. package/dist/runtime/cloudflare-request-env.js +1 -1
  33. package/dist/runtime/database.d.ts +2 -0
  34. package/dist/{database-72Jk3VVk.js → runtime/database.js} +68 -37
  35. package/dist/runtime/nitro-plugin.js +12 -5
  36. package/dist/runtime/redis-driver.d.ts +2 -2
  37. package/dist/runtime/redis-driver.js +2 -5
  38. package/dist/runtime/unstorage-driver.js +6 -2
  39. package/dist/runtime/upstash-driver.d.ts +2 -2
  40. package/dist/runtime/upstash-driver.js +2 -6
  41. package/dist/{types-DEiKew_3.d.ts → types-Cp6IBhSN.d.ts} +36 -37
  42. package/dist/{upstash-DDlqTttY.js → upstash-5sTbIR35.js} +2 -2
  43. package/dist/virtual-module.d.ts +1 -0
  44. package/dist/vite.d.ts +21 -6
  45. package/dist/vite.js +2738 -415
  46. package/package.json +10 -5
  47. package/dist/driver-BwxgaQ-f.d.ts +0 -15
  48. package/dist/errors-DbwufFZp.js +0 -60
  49. package/dist/fs-lite-RAoxu8L0.js +0 -2
  50. package/dist/main-F3Y22_uV.js +0 -2353
@@ -0,0 +1,47 @@
1
+ import { i as TransactionOptions, t as Driver } from "./types-Bj3EQoRg.js";
2
+ import { P as ResolvedDatabaseKVStoreConfig, T as KVPageOptions, _ as KVListPage } from "./types-Cp6IBhSN.js";
3
+ //#region src/runtime/database.d.ts
4
+ /** The table that keeps the keys of every `database` store. Each store has its rows under its own `namespace`. */
5
+ declare const kvTable = "vitehub_kv";
6
+ type KVSqlParam = string | number | null;
7
+ /**
8
+ * Runs one statement and resolves its rows as objects keyed by column name. `postgresql` SQL uses `$1`, `$2`, ... and
9
+ * `sqlite` SQL uses `?`.
10
+ */
11
+ interface KVSqlClient {
12
+ dialect: "postgresql" | "sqlite";
13
+ /** The most values that one statement may bind, such as 100 on Cloudflare D1. */
14
+ maxParameters?: number;
15
+ query(sql: string, params: KVSqlParam[]): Promise<readonly Record<string, unknown>[]>;
16
+ }
17
+ /** The databases of the app, as `@vite-hub/database/runtime/registry` exports them. */
18
+ type KVDatabases = Record<string, {
19
+ db: object;
20
+ } | undefined>;
21
+ /**
22
+ * A SQL client over the Drizzle database of the app: postgres.js, libSQL, primary Cloudflare D1, or D1 over HTTP. It resolves
23
+ * the client on each query because the Database connection can belong to the request.
24
+ */
25
+ declare function kvSqlClientFromDatabase(db: object, database: string): KVSqlClient;
26
+ type DatabaseKVDriver = KVRuntimeDriver & Required<Pick<KVRuntimeDriver, "getItems">>;
27
+ /**
28
+ * KV in a table of the app's Database. Each atomic operation is one statement, so two servers that write one key at
29
+ * the same time get one winner. Expiry uses the clock of the Database. Works on Postgres and on SQLite 3.35 or later,
30
+ * such as libSQL and Cloudflare D1. `table` defaults to `vitehub_kv`. A caller that passes another table keeps its rows
31
+ * out of reach of every KV store.
32
+ */
33
+ declare function createDatabaseKVDriver(options: ResolvedDatabaseKVStoreConfig, connect: () => Promise<KVSqlClient>, table?: string): DatabaseKVDriver;
34
+ //#endregion
35
+ //#region src/runtime/driver.d.ts
36
+ type KVRuntimeDriver = Driver & Record<string, unknown> & {
37
+ validateBatch?: (items: Parameters<NonNullable<Driver["setItems"]>>[0], removals: string[], options?: TransactionOptions) => void | Promise<void>;
38
+ /** Deletes the key when it holds the serialized `expected` value. Resolves `true` when this call deleted it. */
39
+ deleteIfEqualsItem?: (key: string, expected: string) => Promise<boolean>;
40
+ getAndDeleteItem?: <T = unknown>(key: string) => Promise<T | null>;
41
+ incrementItem?: (key: string, ttl: number) => Promise<number>;
42
+ listKeys: (options: KVPageOptions) => Promise<KVListPage>;
43
+ /** Writes the serialized value only when the key is missing. Resolves `true` when this call wrote it. */
44
+ setIfAbsentItem?: (key: string, value: string, ttl?: number) => Promise<boolean>;
45
+ };
46
+ //#endregion
47
+ export { createDatabaseKVDriver as a, KVSqlParam as i, KVDatabases as n, kvSqlClientFromDatabase as o, KVSqlClient as r, kvTable as s, KVRuntimeDriver as t };
@@ -9,6 +9,10 @@ const cursorProblems = {
9
9
  const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
10
10
  docs: "https://vitehub.dev/docs/kv/diagnostics",
11
11
  codes: {
12
+ KV_INVALID_CLEAR_OPTIONS: {
13
+ why: "`kv.clear()` needs an options object with an optional string `prefix`, or no argument. It rejects a legacy string argument before deleting any keys.",
14
+ fix: "Use `kv.clear({ prefix: 'drafts:' })` to clear the keys below `drafts`, or `kv.clear()` to clear the whole store."
15
+ },
12
16
  KV_INVALID_CURSOR: {
13
17
  why: ({ problem }) => cursorProblems[problem],
14
18
  fix: "Pass the `cursor` of the previous page once, to the same store. If it fails, start again without `cursor`."
@@ -22,8 +26,8 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
22
26
  fix: "Pass `{ ttl: seconds }` to expire the value, or no options to keep it. KV has no Cloudflare `expirationTtl`, `expiration`, or `metadata` option."
23
27
  },
24
28
  KV_INVALID_TTL: {
25
- why: "`ttl` must be a positive number of seconds within the safe integer range.",
26
- fix: "Pass the TTL in seconds, for example `kv.set('session', value, { ttl: 60 })`."
29
+ why: "`ttl` must be a positive number of seconds within the safe integer range, or a duration such as `\"1h\"`.",
30
+ fix: "Pass the TTL in seconds or as a duration, for example `kv.set('session', value, { ttl: 60 })` or `kv.set('session', value, { ttl: \"1h\" })`."
27
31
  },
28
32
  KV_INVALID_VALUE: {
29
33
  why: ({ operation, problem }) => problem === "missing" ? `kv.${operation}() needs a value. Use kv.delete() to remove a key.` : "KV cannot serialize this value.",
@@ -69,8 +73,8 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
69
73
  fix: "Read the value in the app with `kv.get()`. The `kv.get` operation shows JSON values, bigint values, and bytes, without getters, symbols, or class instances."
70
74
  },
71
75
  KV_DATABASE_UNAVAILABLE: {
72
- why: ({ database, problem }) => problem === "missing" ? `The KV \`database\` driver keeps keys in the Database "${database}", and the app has no Database with that name.` : `The KV \`database\` driver needs the Database "${database}" on Postgres or libSQL. It does not support D1.`,
73
- fix: ({ problem }) => problem === "missing" ? "Add a Database Definition, for example `server/database.ts` with `defineDatabase({ dialect: 'postgresql', schema: {} })`, or select another KV driver." : "On Cloudflare, use the `cloudflare` driver. Elsewhere, point the Database at Postgres or libSQL."
76
+ why: ({ database, problem }) => problem === "missing" ? `The KV \`database\` driver keeps keys in the Database "${database}", and the app has no Database with that name.` : `The KV \`database\` driver needs the Database "${database}" on postgres.js, libSQL, or Cloudflare D1.`,
77
+ fix: ({ problem }) => problem === "missing" ? "Add a Database Definition, for example `server/database.ts` with `defineDatabase({ dialect: 'postgresql', schema: {} })`, or select another KV driver." : "Point the Database at postgres.js, libSQL, or Cloudflare D1 by binding or over HTTP, or select another KV driver."
74
78
  },
75
79
  KV_DENO_KV_UNAVAILABLE: {
76
80
  why: "The `deno-kv` driver needs `Deno.openKv()`, and this runtime does not have it.",
@@ -116,6 +120,10 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
116
120
  why: ({ store, stores }) => stores ? `KV store "${store}" was not found. Stores: ${stores}.` : `The KV store "${store}" is not configured.`,
117
121
  fix: "Add the store under `kv.stores`, or use the name of a configured store."
118
122
  },
123
+ KV_UNKNOWN_STORE_OPTION: {
124
+ why: ({ driver, key, path, stores }) => stores ? `\`${path}\` has \`stores\`, so it takes no other key, and it has \`${key}\`.` : driver ? `\`${path}.${key}\` is not an option of the \`${driver}\` KV driver.` : `\`${path}.${key}\` is not an option of a KV store without \`driver\`. ViteHub picks the driver from the host and would ignore it.`,
125
+ fix: ({ drivers, driver, key, stores }) => stores ? `Move \`${key}\` into a store under \`stores\`, for example \`stores: { default: { driver: "fs-lite" } }\`.` : drivers.length && !driver ? `Set \`driver\` to ${drivers.map((name) => `"${name}"`).join(" or ")}, which reads \`${key}\`. ViteHub renamed some drivers, so run \`npx @vite-hub/codemods driver-key\` when the config had an old driver name.` : drivers.length ? `Remove \`${key}\`, or set \`driver\` to ${drivers.map((name) => `"${name}"`).join(" or ")}, which reads it.` : `Remove \`${key}\`. A KV store takes \`driver\`, \`remote\`, and the options of its driver.`
126
+ },
119
127
  KV_INVALID_COUNTER: {
120
128
  why: "kv.increment() needs a stored integer below 9007199254740991. The value did not change.",
121
129
  fix: "Delete the key or replace its value with a canonical integer below Number.MAX_SAFE_INTEGER, then retry kv.increment()."
@@ -131,6 +139,10 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
131
139
  KV_PROVISION_FAILED: {
132
140
  why: ({ problem }) => `Cloudflare KV provisioning failed. ${problem}`,
133
141
  fix: "Run `vitehub provision run --host cloudflare --dry-run` and check the Cloudflare token permissions."
142
+ },
143
+ KV_REDIS_URL_UNUSED: {
144
+ why: ({ name, store }) => store === "upstash" ? `KV on Vercel uses Upstash, and the build has no \`KV_REST_API_URL\` and \`KV_REST_API_TOKEN\`, so KV fails at runtime. The build has \`${name}\`, and KV does not select Redis on its own.` : `The build has \`${name}\`, but KV does not select Redis on its own. The KV store "default" uses ${store}.`,
145
+ fix: ({ name }) => `To keep KV in that Redis, set \`kv: { driver: "redis"${name === "REDIS_URL" ? "" : `, url: "env:${name}"`} }\`. To keep this store, set its \`driver\`.`
134
146
  }
135
147
  }
136
148
  });
@@ -0,0 +1,125 @@
1
+ import { n as kvErrorDiagnostics, t as kvConfigErrorCodes } from "./error-diagnostics-C4VTHInS.js";
2
+ import { isRuntimeDiagnostic, parseDuration, toResultError } from "@vite-hub/runtime";
3
+ //#region src/runtime/ttl.ts
4
+ /**
5
+ * The seconds of a KV `ttl`: a number of seconds, or a duration such as `"1h"`. `undefined` when it is not a positive
6
+ * time, so the caller returns `KV_INVALID_TTL`.
7
+ */
8
+ function ttlSeconds(ttl) {
9
+ let seconds;
10
+ if (typeof ttl === "number") seconds = ttl;
11
+ else if (typeof ttl !== "string") return;
12
+ else try {
13
+ seconds = parseDuration(ttl) / 1e3;
14
+ } catch {
15
+ return;
16
+ }
17
+ return Number.isFinite(seconds) && seconds > 0 && Number.isSafeInteger(Math.ceil(seconds * 1e3)) ? seconds : void 0;
18
+ }
19
+ //#endregion
20
+ //#region src/store-mode.ts
21
+ /**
22
+ * Returns the handle that `kv.store(name, options)` gives. An unknown mode throws, so a typo never gives a writable handle.
23
+ * The read-only handle has only the read methods; write methods are absent, not stubbed.
24
+ */
25
+ function kvStoreWithMode(storage, options) {
26
+ const mode = options?.mode === void 0 ? "write" : options.mode;
27
+ if (mode !== "read" && mode !== "write") throw kvErrorDiagnostics.KV_INVALID_STORE_MODE({ mode: JSON.stringify(mode) });
28
+ if (mode === "write") return storage;
29
+ return {
30
+ get: storage.get,
31
+ getMany: storage.getMany,
32
+ has: storage.has,
33
+ list: storage.list
34
+ };
35
+ }
36
+ //#endregion
37
+ //#region src/errors.ts
38
+ function kvClearOptionsError(options) {
39
+ if (options === void 0) return;
40
+ if (typeof options !== "object" || options === null || Array.isArray(options) || Object.keys(options).some((key) => key !== "prefix") || "prefix" in options && options.prefix !== void 0 && typeof options.prefix !== "string") return kvErrorDiagnostics.KV_INVALID_CLEAR_OPTIONS();
41
+ }
42
+ function hasCode(error, codes) {
43
+ return codes.some((code) => code === error.code);
44
+ }
45
+ /**
46
+ * Runs one KV operation and returns `[error, data]`.
47
+ * A KV error with one of `codes` is returned with Runtime's public serializer. A config error is thrown.
48
+ * Any other failure becomes `KV_OPERATION_FAILED` with the failure in `cause`.
49
+ */
50
+ async function kvResult(operation, store, run, codes = []) {
51
+ try {
52
+ return [void 0, await run()];
53
+ } catch (cause) {
54
+ if (kvErrorDiagnostics.is(cause) && kvConfigErrorCodes.has(cause.code)) throw cause;
55
+ if (isRuntimeDiagnostic(cause) && hasCode(cause, codes)) return [toResultError(cause), void 0];
56
+ return [kvErrorDiagnostics.KV_OPERATION_FAILED({
57
+ cause,
58
+ operation,
59
+ store
60
+ }), void 0];
61
+ }
62
+ }
63
+ function kvStoreNotFoundError(store) {
64
+ return kvErrorDiagnostics.KV_STORE_NOT_FOUND({ store });
65
+ }
66
+ function kvUnsupportedOperationError(operation, store) {
67
+ return kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
68
+ operation,
69
+ store
70
+ });
71
+ }
72
+ function kvInvalidLimitError() {
73
+ return kvErrorDiagnostics.KV_INVALID_LIMIT();
74
+ }
75
+ /** True when `list()` got a `limit` that is not a positive integer. Without a `limit`, `list()` reads every key. */
76
+ function kvListLimitInvalid(options) {
77
+ return options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit <= 0);
78
+ }
79
+ const listAllPageSize = 1e3;
80
+ /** One page with `limit`. Without it, every key from `cursor` on, in one page without a cursor. */
81
+ async function listKVKeys(listKeys, options) {
82
+ if (options.limit !== void 0) return listKeys({
83
+ ...options,
84
+ limit: options.limit
85
+ });
86
+ const keys = [];
87
+ let cursor = options.cursor;
88
+ do {
89
+ const page = await listKeys({
90
+ cursor,
91
+ limit: listAllPageSize,
92
+ prefix: options.prefix
93
+ });
94
+ keys.push(...page.keys);
95
+ cursor = page.cursor;
96
+ } while (cursor);
97
+ return { keys };
98
+ }
99
+ /** Codes that a Cloudflare KV store returns for a key above the host limit. */
100
+ const kvKeyLimitCodes = ["KV_KEY_TOO_LONG"];
101
+ /** Codes that a Cloudflare KV store returns for a write above the host limits. */
102
+ const kvWriteLimitCodes = ["KV_KEY_TOO_LONG", "KV_VALUE_TOO_LARGE"];
103
+ /** The codes that `set()` and `setMany()` return: the write limits and an invalid option or `ttl`. */
104
+ const kvSetCodes = [
105
+ ...kvWriteLimitCodes,
106
+ "KV_INVALID_OPTION",
107
+ "KV_INVALID_TTL"
108
+ ];
109
+ /**
110
+ * The `ttl` of a write in seconds, or `undefined` when the caller sets none.
111
+ * Throws `KV_INVALID_OPTION` for any option other than `ttl`, and `KV_INVALID_TTL` for a `ttl` that is not a positive time.
112
+ */
113
+ function kvSetTTL(operation, options) {
114
+ if (options === void 0) return;
115
+ for (const option of Object.keys(options)) if (option !== "ttl") throw kvErrorDiagnostics.KV_INVALID_OPTION({
116
+ operation,
117
+ option
118
+ });
119
+ if (options.ttl === void 0) return;
120
+ const ttl = ttlSeconds(options.ttl);
121
+ if (ttl === void 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
122
+ return ttl;
123
+ }
124
+ //#endregion
125
+ export { kvResult as a, kvStoreNotFoundError as c, listKVKeys as d, kvStoreWithMode as f, kvListLimitInvalid as i, kvUnsupportedOperationError as l, kvInvalidLimitError as n, kvSetCodes as o, ttlSeconds as p, kvKeyLimitCodes as r, kvSetTTL as s, kvClearOptionsError as t, kvWriteLimitCodes as u };
package/dist/errors.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { O as KVStoreOptions, S as KVOperation, T as KVStorage, d as KVErrorCode, k as ReadonlyKVStorage } from "./types-DEiKew_3.js";
1
+ import { A as KVStoreOptions, C as KVOperation, D as KVStorage, E as KVSetOptions, T as KVPageOptions, _ as KVListPage, f as KVErrorCode, g as KVListOptions, j as ReadonlyKVStorage } from "./types-Cp6IBhSN.js";
2
2
  import { Result, ResultError } from "@vite-hub/runtime";
3
3
  //#region src/store-mode.d.ts
4
4
  /**
@@ -8,6 +8,7 @@ import { Result, ResultError } from "@vite-hub/runtime";
8
8
  export declare function kvStoreWithMode(storage: KVStorage, options: KVStoreOptions | undefined): KVStorage | ReadonlyKVStorage;
9
9
  //#endregion
10
10
  //#region src/errors.d.ts
11
+ export declare function kvClearOptionsError(options: unknown): ResultError<"KV_INVALID_CLEAR_OPTIONS"> | undefined;
11
12
  /**
12
13
  * Runs one KV operation and returns `[error, data]`.
13
14
  * A KV error with one of `codes` is returned with Runtime's public serializer. A config error is thrown.
@@ -17,8 +18,19 @@ export declare function kvResult<TData, TCode extends KVErrorCode = never>(opera
17
18
  export declare function kvStoreNotFoundError(store: string): ResultError<"KV_STORE_NOT_FOUND">;
18
19
  export declare function kvUnsupportedOperationError(operation: KVOperation, store: string): ResultError<"KV_UNSUPPORTED_OPERATION">;
19
20
  export declare function kvInvalidLimitError(): ResultError<"KV_INVALID_LIMIT">;
21
+ /** True when `list()` got a `limit` that is not a positive integer. Without a `limit`, `list()` reads every key. */
22
+ export declare function kvListLimitInvalid(options: KVListOptions): boolean;
23
+ /** One page with `limit`. Without it, every key from `cursor` on, in one page without a cursor. */
24
+ export declare function listKVKeys(listKeys: (options: KVPageOptions) => Promise<KVListPage>, options: KVListOptions): Promise<KVListPage>;
20
25
  /** Codes that a Cloudflare KV store returns for a key above the host limit. */
21
26
  export declare const kvKeyLimitCodes: readonly ["KV_KEY_TOO_LONG"];
22
27
  /** Codes that a Cloudflare KV store returns for a write above the host limits. */
23
28
  export declare const kvWriteLimitCodes: readonly ["KV_KEY_TOO_LONG", "KV_VALUE_TOO_LARGE"];
29
+ /** The codes that `set()` and `setMany()` return: the write limits and an invalid option or `ttl`. */
30
+ export declare const kvSetCodes: readonly ["KV_KEY_TOO_LONG", "KV_VALUE_TOO_LARGE", "KV_INVALID_OPTION", "KV_INVALID_TTL"];
31
+ /**
32
+ * The `ttl` of a write in seconds, or `undefined` when the caller sets none.
33
+ * Throws `KV_INVALID_OPTION` for any option other than `ttl`, and `KV_INVALID_TTL` for a `ttl` that is not a positive time.
34
+ */
35
+ export declare function kvSetTTL(operation: "set" | "setIfAbsent" | "setMany", options: KVSetOptions | undefined): number | undefined;
24
36
  //#endregion
package/dist/errors.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as kvUnsupportedOperationError, i as kvStoreNotFoundError, n as kvKeyLimitCodes, o as kvWriteLimitCodes, r as kvResult, s as kvStoreWithMode, t as kvInvalidLimitError } from "./errors-DbwufFZp.js";
2
- export { kvInvalidLimitError, kvKeyLimitCodes, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes };
1
+ import { a as kvResult, c as kvStoreNotFoundError, d as listKVKeys, f as kvStoreWithMode, i as kvListLimitInvalid, l as kvUnsupportedOperationError, n as kvInvalidLimitError, o as kvSetCodes, r as kvKeyLimitCodes, s as kvSetTTL, t as kvClearOptionsError, u as kvWriteLimitCodes } from "./errors-BpiM-Vmh.js";
2
+ export { kvClearOptionsError, kvInvalidLimitError, kvKeyLimitCodes, kvListLimitInvalid, kvResult, kvSetCodes, kvSetTTL, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes, listKVKeys };
@@ -1,4 +1,4 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
2
2
  import { link, lstat, mkdir, mkdtemp, opendir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
3
  import { basename, join, relative, resolve, sep } from "node:path";
4
4
  import createDriver from "unstorage/drivers/fs-lite";
@@ -0,0 +1,2 @@
1
+ import { t as createFsLiteKVDriver } from "./fs-lite-BTcBUP6B.js";
2
+ export { createFsLiteKVDriver as default };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as RedisKVStoreConfig, C as KVOptions, D as KVStoreName, E as KVStoreConfig, F as ResolvedKVModuleOptions, I as ResolvedKVStoreConfig, L as ResolvedRedisKVStoreConfig, M as ResolvedDatabaseKVStoreConfig, N as ResolvedDenoKVStoreConfig, O as KVStoreOptions, P as ResolvedFsLiteKVStoreConfig, R as ResolvedUpstashKVStoreConfig, S as KVOperation, T as KVStorage, _ as KVLock, a as InferredKVStoreConfig, b as KVLockOptions, c as KVDriverAtomicOperations, d as KVErrorCode, f as KVGetOptions, g as KVListPage, h as KVListOptions, i as FsLiteKVStoreConfig, j as ResolvedCloudflareKVStoreConfig, k as ReadonlyKVStorage, l as KVDriversWith, m as KVGetTypeMap, n as DatabaseKVStoreConfig, o as KVAtomicOperation, p as KVGetType, r as DenoKVStoreConfig, s as KVDriver, t as CloudflareKVStoreConfig, u as KVEntry, v as KVLockAcquisition, w as KVSetOptions, x as KVLockRunResult, y as KVLockErrorCode, z as UpstashKVStoreConfig } from "./types-DEiKew_3.js";
1
+ import { A as KVStoreOptions, B as ResolvedUpstashKVStoreConfig, C as KVOperation, D as KVStorage, E as KVSetOptions, F as ResolvedDenoKVStoreConfig, I as ResolvedFsLiteKVStoreConfig, L as ResolvedKVModuleOptions, M as RedisKVStoreConfig, N as ResolvedCloudflareKVStoreConfig, O as KVStoreConfig, P as ResolvedDatabaseKVStoreConfig, R as ResolvedKVStoreConfig, S as KVLockRunResult, V as UpstashKVStoreConfig, _ as KVListPage, a as InferredKVStoreConfig, b as KVLockErrorCode, c as KVDriver, d as KVEntry, f as KVErrorCode, g as KVListOptions, h as KVGetTypeMap, i as FsLiteKVStoreConfig, j as ReadonlyKVStorage, k as KVStoreName, l as KVDriverAtomicOperations, m as KVGetType, n as DatabaseKVStoreConfig, o as KVAtomicOperation, p as KVGetOptions, r as DenoKVStoreConfig, s as KVClearOptions, t as CloudflareKVStoreConfig, u as KVDriversWith, v as KVLock, w as KVOptions, x as KVLockOptions, y as KVLockAcquisition, z as ResolvedRedisKVStoreConfig } from "./types-Cp6IBhSN.js";
2
2
  //#region src/runtime/storage.d.ts
3
3
  /** Releases every cached store. Call from the application's shutdown hook after stopping new work. */
4
4
  export declare function disposeKVStores(): Promise<void>;
@@ -9,4 +9,4 @@ export declare function disposeKVStores(): Promise<void>;
9
9
  export declare function getKVStoreDriver(name?: KVStoreName): Promise<KVDriver>;
10
10
  export declare const kv: KVStorage;
11
11
  //#endregion
12
- export type { CloudflareKVStoreConfig, DatabaseKVStoreConfig, DenoKVStoreConfig, FsLiteKVStoreConfig, InferredKVStoreConfig, KVAtomicOperation, KVDriver, KVDriverAtomicOperations, KVDriversWith, KVEntry, KVErrorCode, KVGetOptions, KVGetType, KVGetTypeMap, KVListOptions, KVListPage, KVLock, KVLockAcquisition, KVLockErrorCode, KVLockOptions, KVLockRunResult, KVOperation, KVOptions, KVSetOptions, KVStorage, KVStoreConfig, KVStoreOptions, ReadonlyKVStorage, RedisKVStoreConfig, ResolvedCloudflareKVStoreConfig, ResolvedDatabaseKVStoreConfig, ResolvedDenoKVStoreConfig, ResolvedFsLiteKVStoreConfig, ResolvedKVModuleOptions, ResolvedKVStoreConfig, ResolvedRedisKVStoreConfig, ResolvedUpstashKVStoreConfig, UpstashKVStoreConfig };
12
+ export type { CloudflareKVStoreConfig, DatabaseKVStoreConfig, DenoKVStoreConfig, FsLiteKVStoreConfig, InferredKVStoreConfig, KVAtomicOperation, KVClearOptions, KVDriver, KVDriverAtomicOperations, KVDriversWith, KVEntry, KVErrorCode, KVGetOptions, KVGetType, KVGetTypeMap, KVListOptions, KVListPage, KVLock, KVLockAcquisition, KVLockErrorCode, KVLockOptions, KVLockRunResult, KVOperation, KVOptions, KVSetOptions, KVStorage, KVStoreConfig, KVStoreOptions, ReadonlyKVStorage, RedisKVStoreConfig, ResolvedCloudflareKVStoreConfig, ResolvedDatabaseKVStoreConfig, ResolvedDenoKVStoreConfig, ResolvedFsLiteKVStoreConfig, ResolvedKVModuleOptions, ResolvedKVStoreConfig, ResolvedRedisKVStoreConfig, ResolvedUpstashKVStoreConfig, UpstashKVStoreConfig };
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
- import { n as kvKeyLimitCodes, o as kvWriteLimitCodes, r as kvResult, s as kvStoreWithMode } from "./errors-DbwufFZp.js";
3
- import { r as normalizeKVOptions, s as readEnv } from "./config-BXEVoZE3.js";
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
2
+ import { a as kvResult, d as listKVKeys, f as kvStoreWithMode, i as kvListLimitInvalid, o as kvSetCodes, p as ttlSeconds, r as kvKeyLimitCodes, s as kvSetTTL, t as kvClearOptionsError } from "./errors-BpiM-Vmh.js";
3
+ import { r as normalizeKVOptions, s as readEnv } from "./config-pfyPiPrI.js";
4
4
  import { n as getActiveCloudflareEnv } from "./cloudflare-env-lookup-Bs0VDpU5.js";
5
- import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-BGsrQKw3.js";
5
+ import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-DQ1BbFqH.js";
6
6
  import { o as normalizeKey } from "./utils2-FozcTsmb.js";
7
- import { t as resolveRuntimeKVOptions } from "./upstash-DDlqTttY.js";
7
+ import { t as resolveRuntimeKVOptions } from "./upstash-5sTbIR35.js";
8
8
  import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch--v0ri69O.js";
9
+ import { t as logFailure } from "./request-log-Dj9Vw7qG.js";
9
10
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
10
11
  import { destr } from "destr";
11
12
  //#region src/runtime/driver.ts
@@ -18,7 +19,6 @@ const lazyDriverMethods = /* @__PURE__ */ new Set([
18
19
  "removeItem",
19
20
  "setItem"
20
21
  ]);
21
- /** The driver method behind each atomic KV operation. */
22
22
  const atomicDriverMethods = {
23
23
  deleteIfEquals: "deleteIfEqualsItem",
24
24
  getAndDelete: "getAndDeleteItem",
@@ -48,7 +48,6 @@ const driverAtomicOperations = {
48
48
  setIfAbsent: true
49
49
  }
50
50
  };
51
- /** Other optional unstorage methods that a driver has. */
52
51
  const otherOptionalDriverMethods = {
53
52
  "cloudflare": ["validateBatch"],
54
53
  "fs-lite": [
@@ -57,11 +56,10 @@ const otherOptionalDriverMethods = {
57
56
  "setItemRaw"
58
57
  ]
59
58
  };
60
- /** Batch methods. A driver without one gets a version that calls the single-key method for each key. */
61
59
  const batchDriverMethods = /* @__PURE__ */ new Set(["getItems", "setItems"]);
62
60
  const lazyOptionalDriverMethods = Object.fromEntries(Object.entries(driverAtomicOperations).map(([driver, operations]) => [driver, /* @__PURE__ */ new Set([...Object.keys(operations).map((operation) => atomicDriverMethods[operation]), ...otherOptionalDriverMethods[driver] ?? []])]));
63
61
  async function createDatabaseDriver(store, loadDatabases) {
64
- const { default: factory, kvSqlClientFromDatabase } = await import("./database-72Jk3VVk.js");
62
+ const { default: factory, kvSqlClientFromDatabase } = await import("./runtime/database.js");
65
63
  return factory(store, async () => {
66
64
  const entry = loadDatabases ? (await loadDatabases())[store.database] : void 0;
67
65
  if (!entry) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
@@ -76,7 +74,7 @@ async function createRuntimeDriver(store, loadDatabases) {
76
74
  case "cloudflare": {
77
75
  const { localBase } = store;
78
76
  if (localBase) {
79
- const { default: factory } = await import("./cloudflare-kv-local-BBw3ZT1K.js");
77
+ const { default: factory } = await import("./cloudflare-kv-local-COjgHweC.js");
80
78
  return factory({
81
79
  ...store,
82
80
  localBase
@@ -87,11 +85,11 @@ async function createRuntimeDriver(store, loadDatabases) {
87
85
  }
88
86
  case "database": return createDatabaseDriver(store, loadDatabases);
89
87
  case "deno-kv": {
90
- const { default: factory } = await import("./deno-kv-BM9mYdUp.js");
88
+ const { default: factory } = await import("./deno-kv-Cf0ZveeN.js");
91
89
  return factory(store);
92
90
  }
93
91
  case "fs-lite": {
94
- const { default: factory } = await import("./fs-lite-RAoxu8L0.js");
92
+ const { default: factory } = await import("./fs-lite-C8yXCVDM.js");
95
93
  return factory(store);
96
94
  }
97
95
  case "redis": {
@@ -239,18 +237,15 @@ function createHostedKVStorage(config, name = "default", loadDatabases) {
239
237
  const firstRetryMs = 25;
240
238
  const maxRetryMs = 500;
241
239
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
242
- function validTtl(ttl) {
243
- return Number.isFinite(ttl) && ttl > 0 && Number.isSafeInteger(Math.ceil(ttl * 1e3));
244
- }
245
240
  /**
246
241
  * A lock on `key` built on `setIfAbsent()` with a TTL and `deleteIfEquals()`. Each acquire writes a new random owner
247
242
  * token, and the release deletes the key only when it still holds that token.
248
243
  */
249
244
  function createKVLock(store, resolveStorage, key, options) {
250
245
  async function acquire() {
251
- const { ttl } = options;
246
+ const ttl = ttlSeconds(options.ttl);
252
247
  const wait = options.wait ?? 0;
253
- if (!validTtl(ttl)) return [kvErrorDiagnostics.KV_INVALID_TTL(), void 0];
248
+ if (ttl === void 0) return [kvErrorDiagnostics.KV_INVALID_TTL(), void 0];
254
249
  if (!Number.isFinite(wait) || wait < 0) return [kvErrorDiagnostics.KV_INVALID_WAIT(), void 0];
255
250
  const storage = await resolveStorage();
256
251
  return kvResult("lock", store, async () => {
@@ -290,7 +285,18 @@ function createKVLock(store, resolveStorage, key, options) {
290
285
  try {
291
286
  value = await fn();
292
287
  } catch (cause) {
293
- await lock.release();
288
+ const [releaseError] = await lock.release();
289
+ if (releaseError) logFailure({
290
+ field: "kv",
291
+ fields: {
292
+ op: "lock-release",
293
+ store
294
+ },
295
+ message: "KV could not release a lock after its callback threw",
296
+ error: releaseError.cause
297
+ }, () => {
298
+ console.warn(`[vitehub] KV could not release the lock "${key}" after its callback threw. The lock expires after its ttl.`, releaseError);
299
+ });
294
300
  throw cause;
295
301
  }
296
302
  const [releaseError] = await lock.release();
@@ -382,21 +388,12 @@ async function runKVOperation(operation, name, run, codes = []) {
382
388
  const storage = await resolveStorage(name);
383
389
  return kvResult(operation, name, () => run(storage), codes);
384
390
  }
385
- function readSetTTL(operation, options) {
386
- if (options === void 0) return;
387
- for (const option of Object.keys(options)) if (option !== "ttl") throw kvErrorDiagnostics.KV_INVALID_OPTION({
388
- operation,
389
- option
390
- });
391
- const ttl = options.ttl;
392
- if (ttl === void 0) return;
393
- if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0 || !Number.isSafeInteger(Math.ceil(ttl))) throw kvErrorDiagnostics.KV_INVALID_TTL();
394
- return ttl;
395
- }
396
391
  function createKVStorage(name = "default") {
397
392
  return {
398
- async clear(base, options) {
399
- return runKVOperation("clear", name, async (storage) => storage.clear(base, options));
393
+ async clear(options) {
394
+ const error = kvClearOptionsError(options);
395
+ if (error) return [error, void 0];
396
+ return runKVOperation("clear", name, async (storage) => storage.clear(options?.prefix));
400
397
  },
401
398
  async delete(key, options) {
402
399
  return runKVOperation("delete", name, async (storage) => storage.removeItem(key, options), kvKeyLimitCodes);
@@ -434,39 +431,29 @@ function createKVStorage(name = "default") {
434
431
  operation: "increment",
435
432
  store: name
436
433
  });
437
- if (!Number.isFinite(ttl) || ttl <= 0 || !Number.isSafeInteger(Math.ceil(ttl))) throw kvErrorDiagnostics.KV_INVALID_TTL();
438
- return storage.incrementItem(key, ttl);
434
+ const seconds = ttlSeconds(ttl);
435
+ if (seconds === void 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
436
+ return storage.incrementItem(key, seconds);
439
437
  }, ["KV_INVALID_TTL", "KV_UNSUPPORTED_OPERATION"]);
440
438
  },
441
- async keys(base, options) {
442
- return runKVOperation("keys", name, (storage) => storage.getKeys(base, options));
443
- },
444
439
  lock(key, options) {
445
440
  return createKVLock(name, () => resolveStorage(name), key, options);
446
441
  },
447
- async list(options) {
448
- if (!Number.isInteger(options.limit) || options.limit <= 0) return [kvErrorDiagnostics.KV_INVALID_LIMIT(), void 0];
449
- return runKVOperation("list", name, (storage) => storage.listKeys(options), ["KV_INVALID_CURSOR"]);
442
+ async list(options = {}) {
443
+ if (kvListLimitInvalid(options)) return [kvErrorDiagnostics.KV_INVALID_LIMIT(), void 0];
444
+ return runKVOperation("list", name, (storage) => listKVKeys((page) => storage.listKeys(page), options), ["KV_INVALID_CURSOR"]);
450
445
  },
451
446
  async set(key, value, options) {
452
447
  return runKVOperation("set", name, async (storage) => {
453
- const ttl = readSetTTL("set", options);
448
+ const ttl = kvSetTTL("set", options);
454
449
  return storage.setItem(key, value, ttl === void 0 ? void 0 : { ttl });
455
- }, [
456
- ...kvWriteLimitCodes,
457
- "KV_INVALID_OPTION",
458
- "KV_INVALID_TTL"
459
- ]);
450
+ }, kvSetCodes);
460
451
  },
461
452
  async setMany(entries, options) {
462
453
  return runKVOperation("setMany", name, async (storage) => {
463
- const ttl = readSetTTL("setMany", options);
454
+ const ttl = kvSetTTL("setMany", options);
464
455
  return storage.setMany(entries, ttl === void 0 ? void 0 : { ttl });
465
- }, [
466
- ...kvWriteLimitCodes,
467
- "KV_INVALID_OPTION",
468
- "KV_INVALID_TTL"
469
- ]);
456
+ }, kvSetCodes);
470
457
  },
471
458
  async setIfAbsent(key, value, options) {
472
459
  return runKVOperation("setIfAbsent", name, async (storage) => {
@@ -474,7 +461,7 @@ function createKVStorage(name = "default") {
474
461
  operation: "setIfAbsent",
475
462
  store: name
476
463
  });
477
- return storage.setIfAbsentItem(key, value, readSetTTL("setIfAbsent", options));
464
+ return storage.setIfAbsentItem(key, value, kvSetTTL("setIfAbsent", options));
478
465
  }, [
479
466
  "KV_INVALID_OPTION",
480
467
  "KV_INVALID_TTL",
@@ -104,6 +104,11 @@ interface OperationAccess {
104
104
  */
105
105
  readonly sections: "all" | readonly string[];
106
106
  readonly user?: OperationUser;
107
+ /**
108
+ * Who signed the call: `"console"` when the ViteHub Console signed it for a person, whose `user` is then a Console
109
+ * account and not an app user, or `"cli"` for a key. Not set for other calls.
110
+ */
111
+ readonly via?: "console" | "cli";
107
112
  }
108
113
  interface OperationContext {
109
114
  /** The checked Console access of the call. */
@@ -115,6 +120,11 @@ interface OperationContext {
115
120
  surface: "console" | "cli" | "mcp" | "agent";
116
121
  /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
117
122
  development?: boolean;
123
+ /**
124
+ * The project root of a development server, for operations that read build files, such as `bundle.report`. Hosts set
125
+ * it only with `development`, so a deployed server never reads project files through it.
126
+ */
127
+ projectRoot?: string;
118
128
  env?: Record<string, unknown>;
119
129
  waitUntil?: (task: Promise<unknown>) => void;
120
130
  request?: Request;
@@ -161,7 +171,8 @@ interface OperationDefinition<Input, Output> {
161
171
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
162
172
  input: StandardSchemaV1<unknown, Input>;
163
173
  output?: StandardSchemaV1<unknown, Output>;
164
- cli?: {
174
+ /** `false`: no `vitehub` command. The Console and MCP still call the operation. */
175
+ cli?: false | {
165
176
  /** Defaults: namespace = section, command = verb. */
166
177
  namespace?: string;
167
178
  /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
@@ -202,7 +213,7 @@ interface OperationDefinition<Input, Output> {
202
213
  /** An operation of any input and output, as a registry holds it. */
203
214
  interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
204
215
  readOnlyWhen?: (input: never) => boolean;
205
- cli?: {
216
+ cli?: false | {
206
217
  namespace?: string;
207
218
  command?: string;
208
219
  default?: boolean;