@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,7 +1,8 @@
1
- import { t as invariant } from "./invariant-DolT9EEx.js";
2
- import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
3
- import { n as recordCursor, t as createCursorHistory } from "./cursor-history-DRHh5bO5.js";
4
- //#region src/runtime/deno-kv.ts
1
+ import { t as invariant } from "./invariant-Dj2R1eMr.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
3
+ import { n as recordCursor, t as createCursorHistory } from "./cursor-history-C6oG12QO.js";
4
+ // src/runtime/deno-kv.ts
5
+ const MAX_DENO_KEY_BYTES = 2048;
5
6
  function getDenoRuntime() {
6
7
  return globalThis.Deno;
7
8
  }
@@ -11,6 +12,21 @@ function toDenoKey(key) {
11
12
  function fromDenoKey(key) {
12
13
  return key.length === 1 && typeof key[0] === "string" ? key[0] : void 0;
13
14
  }
15
+ function canMatchStoredKey(prefix) {
16
+ const nulBytes = prefix.split("\0").length - 1;
17
+ return 2 + new TextEncoder().encode(prefix).length + nulBytes <= MAX_DENO_KEY_BYTES;
18
+ }
19
+ function sortsAfterPrefix(key, prefix) {
20
+ const [part] = key;
21
+ if (typeof part !== "string") return !(part instanceof Uint8Array);
22
+ if (part.startsWith(prefix)) return false;
23
+ const prefixCodePoints = prefix[Symbol.iterator]();
24
+ for (const character of part) {
25
+ const prefixCharacter = prefixCodePoints.next().value;
26
+ if (prefixCharacter === void 0 || character !== prefixCharacter) return (character.codePointAt(0) ?? 0) > (prefixCharacter?.codePointAt(0) ?? -1);
27
+ }
28
+ return false;
29
+ }
14
30
  function toDenoExpireIn(ttl) {
15
31
  if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0) return void 0;
16
32
  const expireIn = Math.max(1, Math.ceil(ttl * 1e3));
@@ -39,7 +55,14 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
39
55
  async function matchingKeys(base = "") {
40
56
  const kv = await open();
41
57
  const keys = [];
42
- for await (const entry of kv.list({ prefix: [] })) if (fromDenoKey(entry.key)?.startsWith(base)) keys.push(entry.key);
58
+ if (!canMatchStoredKey(base)) return keys;
59
+ for await (const entry of kv.list(base ? {
60
+ prefix: [],
61
+ start: [base]
62
+ } : { prefix: [] })) {
63
+ if (sortsAfterPrefix(entry.key, base)) break;
64
+ if (fromDenoKey(entry.key)?.startsWith(base)) keys.push(entry.key);
65
+ }
43
66
  return keys;
44
67
  }
45
68
  return {
@@ -79,22 +102,35 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
79
102
  };
80
103
  try {
81
104
  const cursors = continuation.history;
82
- const iterator = (await open()).list({ prefix: [] }, {
105
+ const keys = [];
106
+ if (!canMatchStoredKey(prefix)) {
107
+ cursorHistories.complete(cursor);
108
+ return { keys };
109
+ }
110
+ const selector = prefix && !continuation.providerCursor ? {
111
+ prefix: [],
112
+ start: [prefix]
113
+ } : { prefix: [] };
114
+ const iterator = (await open()).list(selector, {
83
115
  cursor: continuation.providerCursor,
84
116
  limit
85
117
  });
86
- const keys = [];
118
+ let pastPrefix = false;
87
119
  for await (const entry of iterator) {
120
+ if (sortsAfterPrefix(entry.key, prefix)) {
121
+ pastPrefix = true;
122
+ break;
123
+ }
88
124
  const key = fromDenoKey(entry.key);
89
125
  if (key?.startsWith(prefix)) keys.push(key);
90
126
  }
91
- if (!iterator.cursor) {
127
+ if (pastPrefix || !iterator.cursor) {
92
128
  cursorHistories.complete(cursor);
93
129
  return { keys };
94
130
  }
95
131
  invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
96
132
  if (cursors.has(iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV list returned a repeated pagination cursor." });
97
- if (!recordCursor(cursors, iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV rejected pagination after the cursor history limit was reached." });
133
+ if (!recordCursor(cursors, iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV returned a pagination cursor longer than 8 KiB." });
98
134
  const nextCursor = cursorHistories.store(iterator.cursor, cursors);
99
135
  cursorHistories.complete(cursor);
100
136
  return {
@@ -124,5 +160,4 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
124
160
  }
125
161
  };
126
162
  }
127
- //#endregion
128
163
  export { createDenoKVDriver as default };
@@ -1,4 +1,4 @@
1
- //#region ../internal/src/dev-peer.ts
1
+ // ../internal/src/dev-peer.ts
2
2
  /**
3
3
  * Proof that a development request came from this machine, for dev servers that run the app behind a proxy.
4
4
  *
@@ -234,5 +234,4 @@ function addViteHubDevPeerDevHandler(devHandlers) {
234
234
  devHandlers.unshift({ handler: devHandler });
235
235
  }
236
236
  readViteHubDevPeerKey();
237
- //#endregion
238
237
  export { isViteHubLoopbackPeer as n, addViteHubDevPeerDevHandler as t };
@@ -0,0 +1,43 @@
1
+ import { i as TransactionOptions, t as Driver } from "./types-BUb0FcjM.js";
2
+ import { P as ResolvedDatabaseKVStoreConfig, T as KVPageOptions, _ as KVListPage } from "./types-C397WKyf.js";
3
+ /** The table that keeps the keys of every `database` store. Each store has its rows under its own `namespace`. */
4
+ declare const kvTable = "vitehub_kv";
5
+ type KVSqlParam = string | number | null;
6
+ /**
7
+ * Runs one statement and resolves its rows as objects keyed by column name. `postgresql` SQL uses `$1`, `$2`, ... and
8
+ * `sqlite` SQL uses `?`.
9
+ */
10
+ interface KVSqlClient {
11
+ dialect: "postgresql" | "sqlite";
12
+ /** The most values that one statement may bind, such as 100 on Cloudflare D1. */
13
+ maxParameters?: number;
14
+ query(sql: string, params: KVSqlParam[]): Promise<readonly Record<string, unknown>[]>;
15
+ }
16
+ /** The databases of the app, as `@vite-hub/database/runtime/registry` exports them. */
17
+ type KVDatabases = Record<string, {
18
+ db: object;
19
+ } | undefined>;
20
+ /**
21
+ * A SQL client over the Drizzle database of the app: postgres.js, libSQL, primary Cloudflare D1, or D1 over HTTP. It resolves
22
+ * the client on each query because the Database connection can belong to the request.
23
+ */
24
+ declare function kvSqlClientFromDatabase(db: object, database: string): KVSqlClient;
25
+ type DatabaseKVDriver = KVRuntimeDriver & Required<Pick<KVRuntimeDriver, "getItems">>;
26
+ /**
27
+ * KV in a table of the app's Database. Each atomic operation is one statement, so two servers that write one key at
28
+ * the same time get one winner. Expiry uses the clock of the Database. Works on Postgres and on SQLite 3.35 or later,
29
+ * such as libSQL and Cloudflare D1. `table` defaults to `vitehub_kv`. A caller that passes another table keeps its rows
30
+ * out of reach of every KV store.
31
+ */
32
+ declare function createDatabaseKVDriver(options: ResolvedDatabaseKVStoreConfig, connect: () => Promise<KVSqlClient>, table?: string): DatabaseKVDriver;
33
+ type KVRuntimeDriver = Driver & Record<string, unknown> & {
34
+ validateBatch?: (items: Parameters<NonNullable<Driver["setItems"]>>[0], removals: string[], options?: TransactionOptions) => void | Promise<void>;
35
+ /** Deletes the key when it holds the serialized `expected` value. Resolves `true` when this call deleted it. */
36
+ deleteIfEqualsItem?: (key: string, expected: string) => Promise<boolean>;
37
+ getAndDeleteItem?: <T = unknown>(key: string) => Promise<T | null>;
38
+ incrementItem?: (key: string, ttl: number) => Promise<number>;
39
+ listKeys: (options: KVPageOptions) => Promise<KVListPage>;
40
+ /** Writes the serialized value only when the key is missing. Resolves `true` when this call wrote it. */
41
+ setIfAbsentItem?: (key: string, value: string, ttl?: number) => Promise<boolean>;
42
+ };
43
+ export { createDatabaseKVDriver as a, KVSqlParam as i, KVDatabases as n, kvSqlClientFromDatabase as o, KVSqlClient as r, kvTable as s, KVRuntimeDriver as t };
@@ -1,5 +1,4 @@
1
1
  import { Durability, DurabilityContext } from "@vite-hub/runtime/durability";
2
- //#region src/durability.d.ts
3
2
  /** One KV store as the build resolves it, without credentials. */
4
3
  export interface KVDurabilityStore {
5
4
  /** The folder of a file store. */
@@ -13,5 +12,4 @@ export interface KVDurabilityInput {
13
12
  stores: Record<string, KVDurabilityStore>;
14
13
  }
15
14
  /** The durability of each KV store, from its driver. A `database` store follows the Database that holds its rows. */
16
- export declare function kvDurability(input: KVDurabilityInput, context: DurabilityContext): Durability[];
17
- //#endregion
15
+ export declare function kvDurability(input: KVDurabilityInput, context: DurabilityContext): Durability[];
@@ -1,4 +1,4 @@
1
- //#region src/durability.ts
1
+ // src/durability.ts
2
2
  const sharedStores = {
3
3
  "cloudflare": "A Cloudflare KV namespace that every Worker reads.",
4
4
  "deno-kv": "Deno KV, which Deno Deploy shares between isolates.",
@@ -49,5 +49,4 @@ function kvDurability(input, context) {
49
49
  ...classify(store, context)
50
50
  }));
51
51
  }
52
- //#endregion
53
52
  export { kvDurability };
@@ -1,5 +1,5 @@
1
1
  import { defineErrors } from "@vite-hub/runtime";
2
- //#region src/error-diagnostics.ts
2
+ // src/error-diagnostics.ts
3
3
  const cursorProblems = {
4
4
  "expired": "The list cursor has expired.",
5
5
  "foreign": "The list cursor belongs to a different storage backend.",
@@ -73,8 +73,8 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
73
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."
74
74
  },
75
75
  KV_DATABASE_UNAVAILABLE: {
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 or libSQL. It does not support 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." : "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."
78
78
  },
79
79
  KV_DENO_KV_UNAVAILABLE: {
80
80
  why: "The `deno-kv` driver needs `Deno.openKv()`, and this runtime does not have it.",
@@ -120,6 +120,10 @@ const kvErrorDiagnostics = /*#__PURE__*/ defineErrors({
120
120
  why: ({ store, stores }) => stores ? `KV store "${store}" was not found. Stores: ${stores}.` : `The KV store "${store}" is not configured.`,
121
121
  fix: "Add the store under `kv.stores`, or use the name of a configured store."
122
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
+ },
123
127
  KV_INVALID_COUNTER: {
124
128
  why: "kv.increment() needs a stored integer below 9007199254740991. The value did not change.",
125
129
  fix: "Delete the key or replace its value with a canonical integer below Number.MAX_SAFE_INTEGER, then retry kv.increment()."
@@ -151,5 +155,4 @@ const kvConfigErrorCodes = /* @__PURE__ */ new Set([
151
155
  "KV_MISSING_ENV",
152
156
  "KV_STORE_NOT_FOUND"
153
157
  ]);
154
- //#endregion
155
158
  export { kvErrorDiagnostics as n, kvConfigErrorCodes as t };
@@ -1,6 +1,22 @@
1
- import { n as kvErrorDiagnostics, t as kvConfigErrorCodes } from "./error-diagnostics-C54QQEhN.js";
2
- import { isRuntimeDiagnostic, toResultError } from "@vite-hub/runtime";
3
- //#region src/store-mode.ts
1
+ import { n as kvErrorDiagnostics, t as kvConfigErrorCodes } from "./error-diagnostics-DUIp6FhO.js";
2
+ import { isRuntimeDiagnostic, parseDuration, toResultError } from "@vite-hub/runtime";
3
+ // 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
+ // src/store-mode.ts
4
20
  /**
5
21
  * Returns the handle that `kv.store(name, options)` gives. An unknown mode throws, so a typo never gives a writable handle.
6
22
  * The read-only handle has only the read methods; write methods are absent, not stubbed.
@@ -16,8 +32,7 @@ function kvStoreWithMode(storage, options) {
16
32
  list: storage.list
17
33
  };
18
34
  }
19
- //#endregion
20
- //#region src/errors.ts
35
+ // src/errors.ts
21
36
  function kvClearOptionsError(options) {
22
37
  if (options === void 0) return;
23
38
  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();
@@ -59,7 +74,6 @@ function kvInvalidLimitError() {
59
74
  function kvListLimitInvalid(options) {
60
75
  return options.limit !== void 0 && (!Number.isInteger(options.limit) || options.limit <= 0);
61
76
  }
62
- /** The page size when `list()` reads every key. Every driver accepts it. */
63
77
  const listAllPageSize = 1e3;
64
78
  /** One page with `limit`. Without it, every key from `cursor` on, in one page without a cursor. */
65
79
  async function listKVKeys(listKeys, options) {
@@ -84,5 +98,25 @@ async function listKVKeys(listKeys, options) {
84
98
  const kvKeyLimitCodes = ["KV_KEY_TOO_LONG"];
85
99
  /** Codes that a Cloudflare KV store returns for a write above the host limits. */
86
100
  const kvWriteLimitCodes = ["KV_KEY_TOO_LONG", "KV_VALUE_TOO_LARGE"];
87
- //#endregion
88
- export { kvResult as a, kvWriteLimitCodes as c, kvListLimitInvalid as i, listKVKeys as l, kvInvalidLimitError as n, kvStoreNotFoundError as o, kvKeyLimitCodes as r, kvUnsupportedOperationError as s, kvClearOptionsError as t, kvStoreWithMode as u };
101
+ /** The codes that `set()` and `setMany()` return: the write limits and an invalid option or `ttl`. */
102
+ const kvSetCodes = [
103
+ ...kvWriteLimitCodes,
104
+ "KV_INVALID_OPTION",
105
+ "KV_INVALID_TTL"
106
+ ];
107
+ /**
108
+ * The `ttl` of a write in seconds, or `undefined` when the caller sets none.
109
+ * Throws `KV_INVALID_OPTION` for any option other than `ttl`, and `KV_INVALID_TTL` for a `ttl` that is not a positive time.
110
+ */
111
+ function kvSetTTL(operation, options) {
112
+ if (options === void 0) return;
113
+ for (const option of Object.keys(options)) if (option !== "ttl") throw kvErrorDiagnostics.KV_INVALID_OPTION({
114
+ operation,
115
+ option
116
+ });
117
+ if (options.ttl === void 0) return;
118
+ const ttl = ttlSeconds(options.ttl);
119
+ if (ttl === void 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
120
+ return ttl;
121
+ }
122
+ 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,13 +1,10 @@
1
- import { A as KVStoreOptions, C as KVOperation, D as KVStorage, T as KVPageOptions, _ as KVListPage, f as KVErrorCode, g as KVListOptions, j as ReadonlyKVStorage } from "./types-Dv-OSXZC.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-C397WKyf.js";
2
2
  import { Result, ResultError } from "@vite-hub/runtime";
3
- //#region src/store-mode.d.ts
4
3
  /**
5
4
  * Returns the handle that `kv.store(name, options)` gives. An unknown mode throws, so a typo never gives a writable handle.
6
5
  * The read-only handle has only the read methods; write methods are absent, not stubbed.
7
6
  */
8
7
  export declare function kvStoreWithMode(storage: KVStorage, options: KVStoreOptions | undefined): KVStorage | ReadonlyKVStorage;
9
- //#endregion
10
- //#region src/errors.d.ts
11
8
  export declare function kvClearOptionsError(options: unknown): ResultError<"KV_INVALID_CLEAR_OPTIONS"> | undefined;
12
9
  /**
13
10
  * Runs one KV operation and returns `[error, data]`.
@@ -26,4 +23,10 @@ export declare function listKVKeys(listKeys: (options: KVPageOptions) => Promise
26
23
  export declare const kvKeyLimitCodes: readonly ["KV_KEY_TOO_LONG"];
27
24
  /** Codes that a Cloudflare KV store returns for a write above the host limits. */
28
25
  export declare const kvWriteLimitCodes: readonly ["KV_KEY_TOO_LONG", "KV_VALUE_TOO_LARGE"];
29
- //#endregion
26
+ /** The codes that `set()` and `setMany()` return: the write limits and an invalid option or `ttl`. */
27
+ export declare const kvSetCodes: readonly ["KV_KEY_TOO_LONG", "KV_VALUE_TOO_LARGE", "KV_INVALID_OPTION", "KV_INVALID_TTL"];
28
+ /**
29
+ * The `ttl` of a write in seconds, or `undefined` when the caller sets none.
30
+ * Throws `KV_INVALID_OPTION` for any option other than `ttl`, and `KV_INVALID_TTL` for a `ttl` that is not a positive time.
31
+ */
32
+ export declare function kvSetTTL(operation: "set" | "setIfAbsent" | "setMany", options: KVSetOptions | undefined): number | undefined;
package/dist/errors.js CHANGED
@@ -1,2 +1 @@
1
- import { a as kvResult, c as kvWriteLimitCodes, i as kvListLimitInvalid, l as listKVKeys, n as kvInvalidLimitError, o as kvStoreNotFoundError, r as kvKeyLimitCodes, s as kvUnsupportedOperationError, t as kvClearOptionsError, u as kvStoreWithMode } from "./errors-DzD6YNEH.js";
2
- export { kvClearOptionsError, kvInvalidLimitError, kvKeyLimitCodes, kvListLimitInvalid, kvResult, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, kvWriteLimitCodes, listKVKeys };
1
+ export { t as kvClearOptionsError, n as kvInvalidLimitError, r as kvKeyLimitCodes, i as kvListLimitInvalid, a as kvResult, o as kvSetCodes, s as kvSetTTL, c as kvStoreNotFoundError, f as kvStoreWithMode, l as kvUnsupportedOperationError, u as kvWriteLimitCodes, d as listKVKeys } from "./errors-IaVOqzAs.js";
@@ -0,0 +1 @@
1
+ export { t as default } from "./fs-lite-fvNdBEr9.js";
@@ -1,10 +1,10 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.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";
5
5
  import { createHash, randomUUID } from "node:crypto";
6
6
  import { lock } from "proper-lockfile";
7
- //#region src/runtime/continuations.ts
7
+ // src/runtime/continuations.ts
8
8
  /** Owns process-local cursor retention. Taking a cursor transfers its resource to the caller. */
9
9
  function createKVContinuations(options) {
10
10
  const entries = /* @__PURE__ */ new Map();
@@ -65,8 +65,7 @@ function createKVContinuations(options) {
65
65
  }
66
66
  };
67
67
  }
68
- //#endregion
69
- //#region src/runtime/fs-lite.ts
68
+ // src/runtime/fs-lite.ts
70
69
  const temporaryFile = /^\.unstorage-tmp-[\da-z-]+$/;
71
70
  const layoutRecord = /^\.unstorage-tmp-vitehub-layout-v1(?:-\d+)?$/;
72
71
  const layoutRecordName = ".unstorage-tmp-vitehub-layout-v1";
@@ -382,5 +381,4 @@ async function createFsLiteKVDriver(options) {
382
381
  }
383
382
  return driver;
384
383
  }
385
- //#endregion
386
384
  export { createFsLiteKVDriver as t };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
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-Dv-OSXZC.js";
2
- //#region src/runtime/storage.d.ts
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-C397WKyf.js";
3
2
  /** Releases every cached store. Call from the application's shutdown hook after stopping new work. */
4
3
  export declare function disposeKVStores(): Promise<void>;
5
4
  /**
@@ -8,5 +7,4 @@ export declare function disposeKVStores(): Promise<void>;
8
7
  */
9
8
  export declare function getKVStoreDriver(name?: KVStoreName): Promise<KVDriver>;
10
9
  export declare const kv: KVStorage;
11
- //#endregion
12
10
  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,15 +1,15 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.js";
2
- import { a as kvResult, c as kvWriteLimitCodes, i as kvListLimitInvalid, l as listKVKeys, r as kvKeyLimitCodes, t as kvClearOptionsError, u as kvStoreWithMode } from "./errors-DzD6YNEH.js";
3
- import { r as normalizeKVOptions, s as readEnv } from "./config-LfpUj9hs.js";
4
- import { n as getActiveCloudflareEnv } from "./cloudflare-env-lookup-Bs0VDpU5.js";
5
- import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-BORQm2a8.js";
6
- import { o as normalizeKey } from "./utils2-FozcTsmb.js";
7
- import { t as resolveRuntimeKVOptions } from "./upstash-B-vaUYqO.js";
8
- import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch--v0ri69O.js";
9
- import { parseDuration } from "@vite-hub/runtime";
1
+ import { r as normalizeKVOptions, s as readEnv } from "./config-B8FRGmX_.js";
2
+ import { n as getActiveCloudflareEnv } from "./cloudflare-env-lookup-Dgq5n1Aq.js";
3
+ 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-IaVOqzAs.js";
4
+ import { o as normalizeKey } from "./utils2-By8eee1x.js";
5
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
6
+ import { t as resolveRuntimeKVOptions } from "./upstash-DQVo1zbz.js";
7
+ import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch-D-ib5_0P.js";
8
+ import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-BMvkkYdM.js";
9
+ import { t as logFailure } from "./request-log-DllKQXj7.js";
10
10
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
11
11
  import { destr } from "destr";
12
- //#region src/runtime/driver.ts
12
+ // src/runtime/driver.ts
13
13
  const lazyDriverMethods = /* @__PURE__ */ new Set([
14
14
  "clear",
15
15
  "getItem",
@@ -19,7 +19,6 @@ const lazyDriverMethods = /* @__PURE__ */ new Set([
19
19
  "removeItem",
20
20
  "setItem"
21
21
  ]);
22
- /** The driver method behind each atomic KV operation. */
23
22
  const atomicDriverMethods = {
24
23
  deleteIfEquals: "deleteIfEqualsItem",
25
24
  getAndDelete: "getAndDeleteItem",
@@ -49,7 +48,6 @@ const driverAtomicOperations = {
49
48
  setIfAbsent: true
50
49
  }
51
50
  };
52
- /** Other optional unstorage methods that a driver has. */
53
51
  const otherOptionalDriverMethods = {
54
52
  "cloudflare": ["validateBatch"],
55
53
  "fs-lite": [
@@ -58,11 +56,10 @@ const otherOptionalDriverMethods = {
58
56
  "setItemRaw"
59
57
  ]
60
58
  };
61
- /** Batch methods. A driver without one gets a version that calls the single-key method for each key. */
62
59
  const batchDriverMethods = /* @__PURE__ */ new Set(["getItems", "setItems"]);
63
60
  const lazyOptionalDriverMethods = Object.fromEntries(Object.entries(driverAtomicOperations).map(([driver, operations]) => [driver, /* @__PURE__ */ new Set([...Object.keys(operations).map((operation) => atomicDriverMethods[operation]), ...otherOptionalDriverMethods[driver] ?? []])]));
64
61
  async function createDatabaseDriver(store, loadDatabases) {
65
- const { default: factory, kvSqlClientFromDatabase } = await import("./database-oJdy0ZVX.js");
62
+ const { default: factory, kvSqlClientFromDatabase } = await import("./runtime/database.js");
66
63
  return factory(store, async () => {
67
64
  const entry = loadDatabases ? (await loadDatabases())[store.database] : void 0;
68
65
  if (!entry) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
@@ -77,7 +74,7 @@ async function createRuntimeDriver(store, loadDatabases) {
77
74
  case "cloudflare": {
78
75
  const { localBase } = store;
79
76
  if (localBase) {
80
- const { default: factory } = await import("./cloudflare-kv-local-C2sbIrFy.js");
77
+ const { default: factory } = await import("./cloudflare-kv-local-lov9LLhU.js");
81
78
  return factory({
82
79
  ...store,
83
80
  localBase
@@ -88,11 +85,11 @@ async function createRuntimeDriver(store, loadDatabases) {
88
85
  }
89
86
  case "database": return createDatabaseDriver(store, loadDatabases);
90
87
  case "deno-kv": {
91
- const { default: factory } = await import("./deno-kv-D_VtffFv.js");
88
+ const { default: factory } = await import("./deno-kv-MnqlNH1e.js");
92
89
  return factory(store);
93
90
  }
94
91
  case "fs-lite": {
95
- const { default: factory } = await import("./fs-lite-BAgpmNAF.js");
92
+ const { default: factory } = await import("./fs-lite-DhXLUL-H.js");
96
93
  return factory(store);
97
94
  }
98
95
  case "redis": {
@@ -147,8 +144,7 @@ function createLazyKVRuntimeDriver(config, loadDatabases) {
147
144
  };
148
145
  } });
149
146
  }
150
- //#endregion
151
- //#region src/runtime/hosted-storage.ts
147
+ // src/runtime/hosted-storage.ts
152
148
  function assertHostedConfig(config) {
153
149
  if (!config) throw kvErrorDiagnostics.KV_DISABLED();
154
150
  return config;
@@ -235,25 +231,7 @@ function createHostedKVStorage(config, name = "default", loadDatabases) {
235
231
  if (deleteIfEqualsItem) storage.deleteIfEqualsItem = async (key, expected) => deleteIfEqualsItem(normalizeKey(key), serializeValue(expected, "deleteIfEquals"));
236
232
  return storage;
237
233
  }
238
- //#endregion
239
- //#region src/runtime/ttl.ts
240
- /**
241
- * The seconds of a KV `ttl`: a number of seconds, or a duration such as `"1h"`. `undefined` when it is not a positive
242
- * time, so the caller returns `KV_INVALID_TTL`.
243
- */
244
- function ttlSeconds(ttl) {
245
- let seconds;
246
- if (typeof ttl === "number") seconds = ttl;
247
- else if (typeof ttl !== "string") return;
248
- else try {
249
- seconds = parseDuration(ttl) / 1e3;
250
- } catch {
251
- return;
252
- }
253
- return Number.isFinite(seconds) && seconds > 0 && Number.isSafeInteger(Math.ceil(seconds * 1e3)) ? seconds : void 0;
254
- }
255
- //#endregion
256
- //#region src/runtime/lock.ts
234
+ // src/runtime/lock.ts
257
235
  const firstRetryMs = 25;
258
236
  const maxRetryMs = 500;
259
237
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -305,7 +283,18 @@ function createKVLock(store, resolveStorage, key, options) {
305
283
  try {
306
284
  value = await fn();
307
285
  } catch (cause) {
308
- await lock.release();
286
+ const [releaseError] = await lock.release();
287
+ if (releaseError) logFailure({
288
+ field: "kv",
289
+ fields: {
290
+ op: "lock-release",
291
+ store
292
+ },
293
+ message: "KV could not release a lock after its callback threw",
294
+ error: releaseError.cause
295
+ }, () => {
296
+ console.warn(`[vitehub] KV could not release the lock "${key}" after its callback threw. The lock expires after its ttl.`, releaseError);
297
+ });
309
298
  throw cause;
310
299
  }
311
300
  const [releaseError] = await lock.release();
@@ -317,8 +306,7 @@ function createKVLock(store, resolveStorage, key, options) {
317
306
  }
318
307
  };
319
308
  }
320
- //#endregion
321
- //#region src/runtime/storage.ts
309
+ // src/runtime/storage.ts
322
310
  const storagePromises = /* @__PURE__ */ new Map();
323
311
  let disposal;
324
312
  /** Releases every cached store. Call from the application's shutdown hook after stopping new work. */
@@ -397,17 +385,6 @@ async function runKVOperation(operation, name, run, codes = []) {
397
385
  const storage = await resolveStorage(name);
398
386
  return kvResult(operation, name, () => run(storage), codes);
399
387
  }
400
- function readSetTTL(operation, options) {
401
- if (options === void 0) return;
402
- for (const option of Object.keys(options)) if (option !== "ttl") throw kvErrorDiagnostics.KV_INVALID_OPTION({
403
- operation,
404
- option
405
- });
406
- if (options.ttl === void 0) return;
407
- const ttl = ttlSeconds(options.ttl);
408
- if (ttl === void 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
409
- return ttl;
410
- }
411
388
  function createKVStorage(name = "default") {
412
389
  return {
413
390
  async clear(options) {
@@ -465,23 +442,15 @@ function createKVStorage(name = "default") {
465
442
  },
466
443
  async set(key, value, options) {
467
444
  return runKVOperation("set", name, async (storage) => {
468
- const ttl = readSetTTL("set", options);
445
+ const ttl = kvSetTTL("set", options);
469
446
  return storage.setItem(key, value, ttl === void 0 ? void 0 : { ttl });
470
- }, [
471
- ...kvWriteLimitCodes,
472
- "KV_INVALID_OPTION",
473
- "KV_INVALID_TTL"
474
- ]);
447
+ }, kvSetCodes);
475
448
  },
476
449
  async setMany(entries, options) {
477
450
  return runKVOperation("setMany", name, async (storage) => {
478
- const ttl = readSetTTL("setMany", options);
451
+ const ttl = kvSetTTL("setMany", options);
479
452
  return storage.setMany(entries, ttl === void 0 ? void 0 : { ttl });
480
- }, [
481
- ...kvWriteLimitCodes,
482
- "KV_INVALID_OPTION",
483
- "KV_INVALID_TTL"
484
- ]);
453
+ }, kvSetCodes);
485
454
  },
486
455
  async setIfAbsent(key, value, options) {
487
456
  return runKVOperation("setIfAbsent", name, async (storage) => {
@@ -489,7 +458,7 @@ function createKVStorage(name = "default") {
489
458
  operation: "setIfAbsent",
490
459
  store: name
491
460
  });
492
- return storage.setIfAbsentItem(key, value, readSetTTL("setIfAbsent", options));
461
+ return storage.setIfAbsentItem(key, value, kvSetTTL("setIfAbsent", options));
493
462
  }, [
494
463
  "KV_INVALID_OPTION",
495
464
  "KV_INVALID_TTL",
@@ -504,5 +473,4 @@ function selectKVStore(name, options) {
504
473
  return kvStoreWithMode(createKVStorage(name), options);
505
474
  }
506
475
  const kv = createKVStorage();
507
- //#endregion
508
476
  export { disposeKVStores, getKVStoreDriver, kv };
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
1
+ // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
2
2
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
3
3
  function normalizeWindowsPath(input = "") {
4
4
  if (!input) return input;
@@ -95,8 +95,7 @@ const dirname = function(p) {
95
95
  if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
96
96
  return segments.join("/") || (isAbsolute(p) ? "/" : ".");
97
97
  };
98
- //#endregion
99
- //#region ../internal/src/inspect.ts
98
+ // ../internal/src/inspect.ts
100
99
  function relativeDefinitionFile(projectRoot, file) {
101
100
  return relative(projectRoot, file).replaceAll("\\", "/");
102
101
  }
@@ -114,5 +113,4 @@ const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secr
114
113
  function redactInspectionText(value) {
115
114
  return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
116
115
  }
117
- //#endregion
118
116
  export { resolve as a, relative as i, relativeDefinitionFile as n, dirname as r, redactInspectionText as t };
@@ -1,5 +1,5 @@
1
1
  import { defineDiagnostics } from "nostics";
2
- //#region ../internal/src/invariant.ts
2
+ // ../internal/src/invariant.ts
3
3
  const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
4
  docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
5
  codes: { INTERNAL_INVARIANT_FAILED: {
@@ -18,5 +18,4 @@ function invariantError(what) {
18
18
  function invariant(condition, what) {
19
19
  if (!condition) throw invariantError(what);
20
20
  }
21
- //#endregion
22
21
  export { invariantError as n, invariant as t };
@@ -1,4 +1,4 @@
1
- //#region ../internal/src/object.ts
1
+ // ../internal/src/object.ts
2
2
  /** A non-null object that is not an array. Functions do not pass. */
3
3
  function isRecord(value) {
4
4
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -7,5 +7,4 @@ function isRecord(value) {
7
7
  function isRecordOrFunction(value) {
8
8
  return Object(value) === value && !Array.isArray(value);
9
9
  }
10
- //#endregion
11
10
  export { isRecordOrFunction as n, isRecord as t };