@vite-hub/kv 0.1.0 → 0.3.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 (67) hide show
  1. package/README.md +86 -15
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +98 -77
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
  9. package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
  10. package/dist/config-BXEVoZE3.js +250 -0
  11. package/dist/{create-storage-29gMzf41.js → create-storage-BGsrQKw3.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-BqIQePNP.js} +31 -14
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-BM9mYdUp.js} +12 -4
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-BwxgaQ-f.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-BxqvtEIb.js +147 -0
  20. package/dist/errors-DbwufFZp.js +60 -0
  21. package/dist/errors.d.ts +12 -1
  22. package/dist/errors.js +2 -2
  23. package/dist/fs-lite-BLZId9_P.js +386 -0
  24. package/dist/fs-lite-RAoxu8L0.js +2 -0
  25. package/dist/index.d.ts +7 -2
  26. package/dist/index.js +302 -75
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/main-F3Y22_uV.js +2353 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/{operations-pn8_eGob.js → operations-Ch-gKaey.js} +67 -58
  34. package/dist/operations.d.ts +15 -8
  35. package/dist/operations.js +55 -192
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  38. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  39. package/dist/runtime/cloudflare-kv.js +1 -99
  40. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  41. package/dist/runtime/cloudflare-request-env.js +11 -0
  42. package/dist/runtime/nitro-plugin.d.ts +12 -0
  43. package/dist/runtime/nitro-plugin.js +22 -0
  44. package/dist/runtime/redis-driver.d.ts +11 -0
  45. package/dist/runtime/redis-driver.js +113 -0
  46. package/dist/runtime/unstorage-driver.d.ts +14 -0
  47. package/dist/runtime/unstorage-driver.js +33 -0
  48. package/dist/runtime/upstash-driver.d.ts +2 -2
  49. package/dist/runtime/upstash-driver.js +58 -98
  50. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  51. package/dist/types-DEiKew_3.d.ts +312 -0
  52. package/dist/upstash-DDlqTttY.js +40 -0
  53. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  54. package/dist/virtual-module.d.ts +2 -0
  55. package/dist/vite.d.ts +152 -11
  56. package/dist/vite.js +888 -2836
  57. package/package.json +30 -21
  58. package/dist/cli-Cniq99iX.d.ts +0 -85
  59. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  60. package/dist/config-DR6_5ZwI.js +0 -124
  61. package/dist/continuations-DPyH_vr1.js +0 -63
  62. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  63. package/dist/errors-Dc2oiW-Y.js +0 -38
  64. package/dist/fs-lite-CbLKxLut.js +0 -90
  65. package/dist/object-B1NW521B.js +0 -7
  66. package/dist/operations-ByuDE12r.js +0 -1442
  67. package/dist/types-CMDvN0Wr.d.ts +0 -81
@@ -0,0 +1,94 @@
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
+ //#region src/runtime/redis-shared.ts
3
+ const redisIncrementScript = `
4
+ local existed = redis.call('EXISTS', KEYS[1])
5
+ local current = redis.call('GET', KEYS[1])
6
+ if current then
7
+ local negative = string.sub(current, 1, 1) == '-'
8
+ local digits = negative and string.sub(current, 2) or current
9
+ local boundary = negative and '9007199254740992' or '9007199254740991'
10
+ local beyond = #digits > #boundary or (#digits == #boundary and digits > boundary)
11
+ local at_positive_boundary = not negative and digits == boundary
12
+ if beyond or at_positive_boundary then
13
+ return redis.error_reply('Atomic KV increment exceeds the JavaScript safe integer range.')
14
+ end
15
+ end
16
+ local value = redis.call('INCR', KEYS[1])
17
+ if existed == 0 then
18
+ redis.call('EXPIRE', KEYS[1], ARGV[1])
19
+ end
20
+ return value
21
+ `;
22
+ /** Deletes the key only when it holds ARGV[1]. Redis runs a script as one step. */
23
+ const redisDeleteIfEqualsScript = `
24
+ if redis.call('GET', KEYS[1]) == ARGV[1] then
25
+ return redis.call('DEL', KEYS[1])
26
+ end
27
+ return 0
28
+ `;
29
+ /** Whole seconds for `EXPIRE` and `SET EX`. */
30
+ function redisTTLSeconds(ttl) {
31
+ if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
32
+ const seconds = Math.ceil(ttl);
33
+ if (!Number.isSafeInteger(seconds)) throw kvErrorDiagnostics.KV_INVALID_TTL();
34
+ return seconds;
35
+ }
36
+ function redisIncrementResult(value) {
37
+ const counter = Number(value);
38
+ if (!Number.isSafeInteger(counter)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The counter exceeds the JavaScript safe integer range." });
39
+ return counter;
40
+ }
41
+ function escapeRedisGlob(value) {
42
+ return value.replaceAll(/([*?[\\\]])/g, "\\$1");
43
+ }
44
+ const maximumScanCount = 1e4;
45
+ function decodePortableCursor(cursor) {
46
+ try {
47
+ const value = JSON.parse(decodeURIComponent(cursor));
48
+ if (typeof value === "object" && value !== null) {
49
+ const scan = Reflect.get(value, "cursor");
50
+ const keys = Reflect.get(value, "keys");
51
+ if (typeof scan === "string" && /^\d+$/.test(scan) && Array.isArray(keys) && keys.every((key) => typeof key === "string")) return {
52
+ cursor: scan,
53
+ keys
54
+ };
55
+ }
56
+ } catch {}
57
+ throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
58
+ }
59
+ function encodePortableCursor(cursor) {
60
+ return encodeURIComponent(JSON.stringify(cursor));
61
+ }
62
+ /**
63
+ * `listKeys()` over Redis `SCAN` with a cursor that holds all its state, so another server process can read the next
64
+ * page. Overflow keys travel with the next SCAN cursor, preserving SCAN's full-iteration guarantee even when earlier
65
+ * pages are deleted. Like SCAN itself, a key that changes during the listing can be missed or repeated.
66
+ */
67
+ function createPortableRedisKeyLister(provider, scan) {
68
+ return async function listKeys({ cursor, limit, prefix = "" }) {
69
+ const state = cursor ? decodePortableCursor(cursor) : {
70
+ cursor: "0",
71
+ keys: []
72
+ };
73
+ let next = state.cursor;
74
+ let batch = state.keys;
75
+ if (batch.length === 0) {
76
+ const [position, found] = await scan(next, `${escapeRedisGlob(prefix)}*`, Math.min(limit, maximumScanCount));
77
+ if (position === next && position !== "0") throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: `${provider} scan returned a repeated pagination cursor.` });
78
+ next = position;
79
+ batch = [...new Set(found)].sort();
80
+ }
81
+ const keys = batch.slice(0, limit);
82
+ const overflow = batch.slice(limit);
83
+ if (overflow.length === 0 && next === "0") return { keys };
84
+ return {
85
+ keys,
86
+ cursor: encodePortableCursor({
87
+ cursor: next,
88
+ keys: overflow
89
+ })
90
+ };
91
+ };
92
+ }
93
+ //#endregion
94
+ export { redisIncrementScript as a, redisIncrementResult as i, escapeRedisGlob as n, redisTTLSeconds as o, redisDeleteIfEqualsScript as r, createPortableRedisKeyLister as t };
@@ -0,0 +1,26 @@
1
+ import { createRequire } from "node:module";
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
12
+ key = keys[i];
13
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
21
+ value: mod,
22
+ enumerable: true
23
+ }) : target, mod));
24
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
25
+ //#endregion
26
+ export { __require as n, __toESM as r, __commonJSMin as t };
@@ -1,4 +1,4 @@
1
- import { t as KVRuntimeDriver } from "../driver-D9fI27jl.js";
1
+ import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
2
2
  //#region src/runtime/cloudflare-kv.d.ts
3
3
  declare function createCloudflareDriver(options: Record<string, unknown>): KVRuntimeDriver;
4
4
  export declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
@@ -1,100 +1,2 @@
1
- import { n as kvErrorDiagnostics } from "../error-diagnostics-D_cQeZTi.js";
2
- import { t as getActiveCloudflareBinding } from "../cloudflare-env-C5rM7kUY.js";
3
- import { n as normalizeKVListPrefix, t as createKVStorage } from "../create-storage-29gMzf41.js";
4
- import { n as recordCursor, t as createCursorHistory } from "../cursor-history-dqYDlsaD.js";
5
- import createDriver from "unstorage/drivers/cloudflare-kv-binding";
6
- //#region src/runtime/cloudflare-kv.ts
7
- function isCloudflareKVString(value) {
8
- return typeof value === "string";
9
- }
10
- function isCloudflareKVListPage(value) {
11
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
12
- const page = value;
13
- if (typeof page.list_complete !== "boolean" || !Array.isArray(page.keys)) return false;
14
- if (!page.keys.every((key) => {
15
- if (!key || typeof key !== "object" || Array.isArray(key)) return false;
16
- return isCloudflareKVString(Reflect.get(key, "name"));
17
- })) return false;
18
- return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
19
- }
20
- const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
21
- let nextCloudflareBindingIdentity = 0;
22
- function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
23
- if (typeof namespaceId === "string" && namespaceId.length > 0) return `cloudflare-kv:id:${namespaceId}`;
24
- if (binding && typeof binding === "object") {
25
- let identity = cloudflareBindingIdentities.get(binding);
26
- if (identity === void 0) {
27
- identity = ++nextCloudflareBindingIdentity;
28
- cloudflareBindingIdentities.set(binding, identity);
29
- }
30
- return `cloudflare-kv:object:${identity}`;
31
- }
32
- return typeof bindingName === "string" ? `cloudflare-kv:binding:${bindingName}` : "cloudflare-kv:default";
33
- }
34
- function createCloudflareDriver(options) {
35
- const bindingName = options.binding;
36
- const namespaceId = options.namespaceId;
37
- const driverOptions = typeof bindingName === "string" ? {
38
- ...options,
39
- get binding() {
40
- return getActiveCloudflareBinding(bindingName) ?? bindingName;
41
- }
42
- } : options;
43
- const driver = createDriver(driverOptions);
44
- const cursorNamespace = cloudflareBindingNamespace(bindingName, namespaceId);
45
- const cursorHistories = createCursorHistory(cursorNamespace);
46
- let disposed = false;
47
- const dispose = driver.dispose;
48
- driver.dispose = async () => {
49
- disposed = true;
50
- cursorHistories.clear();
51
- try {
52
- await dispose?.call(driver);
53
- } finally {
54
- cursorHistories.clear();
55
- }
56
- };
57
- driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
58
- if (disposed) throw new Error("KV storage has been disposed.");
59
- const listOptions = { limit };
60
- if (cursor) listOptions.cursor = cursor;
61
- if (prefix) listOptions.prefix = prefix;
62
- const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
63
- const requestNamespace = cloudflareBindingNamespace(bindingName, namespaceId, activeBinding);
64
- const continuation = cursor ? cursorHistories.take(cursor, requestNamespace) : {
65
- providerCursor: void 0,
66
- history: /* @__PURE__ */ new Set(),
67
- namespace: requestNamespace
68
- };
69
- try {
70
- if (continuation.providerCursor) listOptions.cursor = continuation.providerCursor;
71
- const cursors = continuation.history;
72
- const page = await driver.getInstance().list(listOptions);
73
- if (!isCloudflareKVListPage(page)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV list returned an invalid page." });
74
- const result = { keys: page.keys.map((key) => key.name) };
75
- if (!page.list_complete) {
76
- if (disposed) throw new Error("KV storage has been disposed.");
77
- if (cursors.has(page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a repeated pagination cursor." });
78
- if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected pagination after the cursor history limit was reached." });
79
- result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
80
- }
81
- cursorHistories.complete(cursor);
82
- return result;
83
- } catch (error) {
84
- if (cursor && !disposed) cursorHistories.restore(cursor, continuation);
85
- throw error;
86
- }
87
- };
88
- return driver;
89
- }
90
- function createCloudflareKVStorage(options) {
91
- const driver = createCloudflareDriver(options);
92
- const storage = createKVStorage(driver);
93
- storage.listKeys = (listOptions) => driver.listKeys({
94
- ...listOptions,
95
- prefix: normalizeKVListPrefix(listOptions.prefix)
96
- });
97
- return storage;
98
- }
99
- //#endregion
1
+ import { n as createCloudflareKVStorage, t as createCloudflareDriver } from "../cloudflare-kv-BIEUFzRT.js";
100
2
  export { createCloudflareKVStorage, createCloudflareDriver as default };
@@ -0,0 +1,7 @@
1
+ //#region src/runtime/cloudflare-request-env.d.ts
2
+ /**
3
+ * Nitro middleware for Cloudflare KV. A Cloudflare KV store reads its binding from the active env, and only the request
4
+ * carries that env in `vite dev`, so the middleware installs it before the route runs.
5
+ */
6
+ export default function vitehubKVCloudflareRequestEnv(event: unknown): void;
7
+ //#endregion
@@ -0,0 +1,11 @@
1
+ import { n as installCloudflareRequestEnv } from "../cloudflare-env-lOtHHsgP.js";
2
+ //#region src/runtime/cloudflare-request-env.ts
3
+ /**
4
+ * Nitro middleware for Cloudflare KV. A Cloudflare KV store reads its binding from the active env, and only the request
5
+ * carries that env in `vite dev`, so the middleware installs it before the route runs.
6
+ */
7
+ function vitehubKVCloudflareRequestEnv(event) {
8
+ installCloudflareRequestEnv(event);
9
+ }
10
+ //#endregion
11
+ export { vitehubKVCloudflareRequestEnv as default };
@@ -0,0 +1,12 @@
1
+ //#region src/runtime/nitro-plugin.d.ts
2
+ interface NitroAppLike {
3
+ hooks: {
4
+ hook(name: "close", callback: () => Promise<void>): unknown;
5
+ };
6
+ }
7
+ /**
8
+ * Nitro plugin of KV for Redis connections and inferred-store boot notices. On close it releases KV connections,
9
+ * so the process can exit.
10
+ */
11
+ export default function kvNitroPlugin(nitroApp: NitroAppLike): void;
12
+ //#endregion
@@ -0,0 +1,22 @@
1
+ import { t as kvInferredStoreNotice } from "../config-BXEVoZE3.js";
2
+ import { disposeKVStores } from "@vite-hub/kv";
3
+ //#region src/runtime/nitro-plugin.ts
4
+ /** Prints the driver that each inferred store uses in this process. */
5
+ async function logInferredStores() {
6
+ const { kv } = await import("#vitehub/kv/config");
7
+ if (!kv) return;
8
+ for (const [name, store] of Object.entries(kv.stores ?? { default: kv.store })) {
9
+ const notice = kvInferredStoreNotice(name, store);
10
+ if (notice) console.info(notice);
11
+ }
12
+ }
13
+ /**
14
+ * Nitro plugin of KV for Redis connections and inferred-store boot notices. On close it releases KV connections,
15
+ * so the process can exit.
16
+ */
17
+ function kvNitroPlugin(nitroApp) {
18
+ nitroApp.hooks.hook("close", disposeKVStores);
19
+ logInferredStores().catch((error) => console.warn("[vitehub] Could not read the KV configuration.", error));
20
+ }
21
+ //#endregion
22
+ export { kvNitroPlugin as default };
@@ -0,0 +1,11 @@
1
+ import { L as ResolvedRedisKVStoreConfig } from "../types-DEiKew_3.js";
2
+ import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
3
+ //#region src/runtime/redis-driver.d.ts
4
+ /** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
5
+ export declare function resolveRedisUrl(url: string, env?: Record<string, string | undefined>): string;
6
+ /**
7
+ * KV over a Redis server through TCP, with `ioredis`. Each atomic operation is one command or one script. This module
8
+ * loads only for a Redis store, so other stores do not load `ioredis`.
9
+ */
10
+ export default function createRedisKVDriver(options: ResolvedRedisKVStoreConfig): KVRuntimeDriver;
11
+ //#endregion
@@ -0,0 +1,113 @@
1
+ import { t as invariant } from "../invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-BxqvtEIb.js";
3
+ import { o as normalizeKey } from "../utils2-FozcTsmb.js";
4
+ import { t as chunks } from "../batch--v0ri69O.js";
5
+ import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-E5mahECF.js";
6
+ import { Redis } from "ioredis";
7
+ //#region src/runtime/redis-driver.ts
8
+ /** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
9
+ function resolveRedisUrl(url, env = globalThis.process?.env ?? {}) {
10
+ if (!url.startsWith("env:")) return url;
11
+ const name = url.slice(4);
12
+ const value = env[name]?.trim();
13
+ if (!value) throw kvErrorDiagnostics.KV_MISSING_ENV({
14
+ driver: "redis",
15
+ names: `\`${name}\``
16
+ });
17
+ return value;
18
+ }
19
+ /** Milliseconds for `SET PX`, which keeps fractional TTLs, as the other drivers do. */
20
+ function ttlMilliseconds(ttl) {
21
+ redisTTLSeconds(ttl);
22
+ return Math.ceil(ttl * 1e3);
23
+ }
24
+ /** The `PX` milliseconds of a write. Like other unstorage drivers, no TTL or 0 keeps the key. */
25
+ function writeTTL(options) {
26
+ const ttl = options?.ttl;
27
+ if (ttl === void 0 || ttl === null || ttl === 0) return;
28
+ if (typeof ttl === "number") return ttlMilliseconds(ttl);
29
+ throw kvErrorDiagnostics.KV_INVALID_TTL();
30
+ }
31
+ /** Keys per `MGET`, so one reply stays a moderate size. */
32
+ const mgetBatchSize = 1e3;
33
+ /**
34
+ * KV over a Redis server through TCP, with `ioredis`. Each atomic operation is one command or one script. This module
35
+ * loads only for a Redis store, so other stores do not load `ioredis`.
36
+ */
37
+ function createRedisKVDriver(options) {
38
+ const base = normalizeKey(options.base);
39
+ invariant(base, "resolveRedisStore() gives a Redis KV store a non-empty `base`, which keeps clear() inside the store");
40
+ const client = new Redis(resolveRedisUrl(options.url), {
41
+ lazyConnect: true,
42
+ maxRetriesPerRequest: 3
43
+ });
44
+ const prefixed = (key) => `${base}:${key}`;
45
+ const unprefixed = (key) => key.startsWith(`${base}:`) ? key.slice(base.length + 1) : key;
46
+ const pattern = (match) => `${escapeRedisGlob(base)}:${match}`;
47
+ async function scanAll(prefix) {
48
+ const keys = [];
49
+ let cursor = "0";
50
+ do {
51
+ const [next, page] = await client.scan(cursor, "MATCH", pattern(`${escapeRedisGlob(prefix ?? "")}*`), "COUNT", 1e3);
52
+ cursor = next;
53
+ for (const key of page) keys.push(key);
54
+ } while (cursor !== "0");
55
+ return keys;
56
+ }
57
+ return {
58
+ name: "vitehub-kv-redis",
59
+ options,
60
+ hasItem: async (key) => await client.exists(prefixed(key)) > 0,
61
+ getItem: async (key) => await client.get(prefixed(key)),
62
+ async getItems(items) {
63
+ const values = [];
64
+ for (const batch of chunks(items, mgetBatchSize)) values.push(...await client.mget(...batch.map((item) => prefixed(item.key))));
65
+ return items.map((item, index) => ({
66
+ key: item.key,
67
+ value: values[index] ?? null
68
+ }));
69
+ },
70
+ async setItem(key, value, setOptions) {
71
+ const ttl = writeTTL(setOptions);
72
+ if (ttl === void 0) await client.set(prefixed(key), value);
73
+ else await client.set(prefixed(key), value, "PX", ttl);
74
+ },
75
+ async setItems(items, setOptions) {
76
+ const pipeline = client.pipeline();
77
+ for (const item of items) {
78
+ const ttl = writeTTL({
79
+ ...setOptions,
80
+ ...item.options
81
+ });
82
+ if (ttl === void 0) pipeline.set(prefixed(item.key), item.value);
83
+ else pipeline.set(prefixed(item.key), item.value, "PX", ttl);
84
+ }
85
+ for (const [error] of await pipeline.exec() ?? []) if (error) throw error;
86
+ },
87
+ async removeItem(key) {
88
+ await client.unlink(prefixed(key));
89
+ },
90
+ getKeys: async (base) => (await scanAll(base)).map(unprefixed),
91
+ async clear(base) {
92
+ const keys = await scanAll(base);
93
+ for (let offset = 0; offset < keys.length; offset += 1e3) await client.unlink(...keys.slice(offset, offset + 1e3));
94
+ },
95
+ async setIfAbsentItem(key, value, ttl) {
96
+ return (ttl === void 0 ? await client.set(prefixed(key), value, "NX") : await client.set(prefixed(key), value, "PX", ttlMilliseconds(ttl), "NX")) === "OK";
97
+ },
98
+ async getAndDeleteItem(key) {
99
+ return await client.getdel(prefixed(key));
100
+ },
101
+ incrementItem: async (key, ttl) => redisIncrementResult(await client.eval(redisIncrementScript, 1, prefixed(key), redisTTLSeconds(ttl))),
102
+ deleteIfEqualsItem: async (key, expected) => Number(await client.eval(redisDeleteIfEqualsScript, 1, prefixed(key), expected)) === 1,
103
+ listKeys: createPortableRedisKeyLister("Redis KV", async (cursor, match, count) => {
104
+ const [next, keys] = await client.scan(cursor, "MATCH", pattern(match), "COUNT", count);
105
+ return [next, keys.map(unprefixed)];
106
+ }),
107
+ async dispose() {
108
+ client.disconnect();
109
+ }
110
+ };
111
+ }
112
+ //#endregion
113
+ export { createRedisKVDriver as default, resolveRedisUrl };
@@ -0,0 +1,14 @@
1
+ import { t as Driver } from "../types-Bj3EQoRg.js";
2
+ //#region src/runtime/unstorage-driver.d.ts
3
+ export interface KVStorageDriverOptions {
4
+ /** The named KV store. Default: the default store. */
5
+ store?: string;
6
+ /** Key prefix inside the store, so the mount's keys stay apart from the app's other keys. Default: no prefix. */
7
+ base?: string;
8
+ }
9
+ /**
10
+ * Unstorage driver over one KV store, for Nitro storage mounts such as `kv` and `cache`.
11
+ * It resolves the store on each call, so a Cloudflare store uses the binding of the current request.
12
+ */
13
+ export default function createKVStorageDriver(options?: KVStorageDriverOptions): Driver<KVStorageDriverOptions>;
14
+ //#endregion
@@ -0,0 +1,33 @@
1
+ import { o as normalizeKey } from "../utils2-FozcTsmb.js";
2
+ import { kv } from "@vite-hub/kv";
3
+ //#region src/runtime/unstorage-driver.ts
4
+ async function unwrap(pending) {
5
+ const [error, value] = await pending;
6
+ if (error) throw error;
7
+ return value;
8
+ }
9
+ /**
10
+ * Unstorage driver over one KV store, for Nitro storage mounts such as `kv` and `cache`.
11
+ * It resolves the store on each call, so a Cloudflare store uses the binding of the current request.
12
+ */
13
+ function createKVStorageDriver(options = {}) {
14
+ const base = normalizeKey(options.base);
15
+ const prefix = base ? `${base}:` : "";
16
+ const key = (name) => prefix + normalizeKey(name);
17
+ const store = () => options.store === void 0 ? kv : kv.store(options.store);
18
+ return {
19
+ name: "vitehub-kv",
20
+ options,
21
+ hasItem: (name) => unwrap(store().has(key(name))),
22
+ getItem: (name) => unwrap(store().get(key(name), { type: "text" })),
23
+ getItemRaw: (name) => unwrap(store().get(key(name), { type: "bytes" })),
24
+ setItem: (name, value, opts) => unwrap(store().set(key(name), value, typeof opts?.ttl === "number" ? { ttl: opts.ttl } : void 0)),
25
+ removeItem: (name) => unwrap(store().delete(key(name))),
26
+ async getKeys(keyBase) {
27
+ return (await unwrap(store().keys(key(keyBase)))).map((name) => name.slice(prefix.length));
28
+ },
29
+ clear: (keyBase) => unwrap(store().clear(key(keyBase)))
30
+ };
31
+ }
32
+ //#endregion
33
+ export { createKVStorageDriver as default };
@@ -1,5 +1,5 @@
1
- import { _ as ResolvedUpstashKVStoreConfig } from "../types-CMDvN0Wr.js";
2
- import { t as KVRuntimeDriver } from "../driver-D9fI27jl.js";
1
+ import { R as ResolvedUpstashKVStoreConfig } from "../types-DEiKew_3.js";
2
+ import { t as KVRuntimeDriver } from "../driver-BwxgaQ-f.js";
3
3
  //#region src/runtime/upstash-driver.d.ts
4
4
  export default function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
5
5
  //#endregion
@@ -1,109 +1,69 @@
1
- import { n as kvErrorDiagnostics } from "../error-diagnostics-D_cQeZTi.js";
2
- import { t as createKVContinuations } from "../continuations-DPyH_vr1.js";
1
+ import { t as invariant } from "../invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "../error-diagnostics-BxqvtEIb.js";
3
+ import { o as normalizeKey } from "../utils2-FozcTsmb.js";
4
+ import { t as chunks } from "../batch--v0ri69O.js";
5
+ import { a as redisIncrementScript, i as redisIncrementResult, n as escapeRedisGlob, o as redisTTLSeconds, r as redisDeleteIfEqualsScript, t as createPortableRedisKeyLister } from "../redis-shared-E5mahECF.js";
3
6
  import createDriver from "unstorage/drivers/upstash";
4
7
  //#region src/runtime/upstash-driver.ts
5
- const incrementScript = `
6
- local existed = redis.call('EXISTS', KEYS[1])
7
- local current = redis.call('GET', KEYS[1])
8
- if current then
9
- local negative = string.sub(current, 1, 1) == '-'
10
- local digits = negative and string.sub(current, 2) or current
11
- local boundary = negative and '9007199254740992' or '9007199254740991'
12
- local beyond = #digits > #boundary or (#digits == #boundary and digits > boundary)
13
- local at_positive_boundary = not negative and digits == boundary
14
- if beyond or at_positive_boundary then
15
- return redis.error_reply('Atomic KV increment exceeds the JavaScript safe integer range.')
16
- end
17
- end
18
- local value = redis.call('INCR', KEYS[1])
19
- if existed == 0 then
20
- redis.call('EXPIRE', KEYS[1], ARGV[1])
21
- end
22
- return value
23
- `;
24
- function normalizeTTL(ttl) {
25
- if (!Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_INVALID_TTL();
26
- const seconds = Math.ceil(ttl);
27
- if (!Number.isSafeInteger(seconds)) throw kvErrorDiagnostics.KV_INVALID_TTL();
28
- return seconds;
29
- }
30
- function decodeCursor(cursor) {
31
- if (!cursor) return { cursor: "0" };
32
- try {
33
- const value = JSON.parse(decodeURIComponent(cursor));
34
- if (typeof value.cursor !== "string" || value.cursor.length === 0) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
35
- return value;
36
- } catch {
37
- throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
38
- }
39
- }
40
- function encodeCursor(cursor) {
41
- return encodeURIComponent(JSON.stringify(cursor));
42
- }
43
- function escapeRedisGlob(value) {
44
- return value.replaceAll(/([*?[\\\]])/g, "\\$1");
45
- }
8
+ const keyBatchSize = 1e3;
46
9
  function createUpstashKVDriver(options) {
47
- const driver = createDriver(options);
48
- const maximumContinuationBytes = 1048576;
49
- const expired = () => kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
50
- const continuations = createKVContinuations({
51
- expired,
52
- maximumBytes: maximumContinuationBytes
10
+ const base = normalizeKey(options.base);
11
+ invariant(base, "resolveUpstashStore() gives an Upstash KV store a non-empty `base`, which keeps clear() inside the store");
12
+ const driver = createDriver({
13
+ lib: () => import("@upstash/redis"),
14
+ ...options,
15
+ base,
16
+ automaticDeserialization: false
53
17
  });
54
- const dispose = driver.dispose;
55
- driver.dispose = async () => {
56
- try {
57
- await continuations.dispose();
58
- } finally {
59
- await dispose?.call(driver);
60
- }
18
+ const client = () => driver.getInstance();
19
+ const prefixed = (key) => `${base}:${key}`;
20
+ const unprefixed = (key) => key.startsWith(`${base}:`) ? key.slice(base.length + 1) : key;
21
+ driver.setItem = async (key, value, setOptions) => {
22
+ const ttl = setOptions?.ttl;
23
+ if (ttl !== void 0 && ttl !== null && ttl !== 0 && typeof ttl !== "number") throw kvErrorDiagnostics.KV_INVALID_TTL();
24
+ await (await client()).set(prefixed(key), value, typeof ttl === "number" && ttl !== 0 ? { ex: redisTTLSeconds(ttl) } : void 0);
61
25
  };
62
- driver.getAndDeleteItem = async (key) => (await driver.getInstance()).getdel(key);
63
- driver.incrementItem = async (key, ttl) => {
64
- const value = Number(await (await driver.getInstance()).eval(incrementScript, [key], [String(normalizeTTL(ttl))]));
65
- if (!Number.isSafeInteger(value)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The counter exceeds the JavaScript safe integer range." });
66
- return value;
26
+ driver.getItems = async (items) => {
27
+ const values = [];
28
+ for (const batch of chunks(items, keyBatchSize)) values.push(...await (await client()).mget(...batch.map((item) => prefixed(item.key))));
29
+ return items.map((item, index) => ({
30
+ key: item.key,
31
+ value: values[index] ?? null
32
+ }));
67
33
  };
68
- function retainContinuation(keys, providerCursor) {
69
- const encoder = new TextEncoder();
70
- const bytes = keys.reduce((total, key) => total + encoder.encode(key).byteLength, 0);
71
- if (bytes > maximumContinuationBytes) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Upstash KV scan overflow exceeds the continuation size limit." });
72
- return continuations.retain({
73
- cursor: providerCursor,
74
- keys
75
- }, bytes);
76
- }
77
- driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
78
- const retained = cursor ? continuations.take(cursor) : void 0;
79
- if (cursor && !retained && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(cursor)) throw expired();
80
- let providerCursor;
81
- let keys;
82
- if (retained) {
83
- providerCursor = retained.cursor;
84
- keys = retained.keys;
85
- } else {
86
- const state = decodeCursor(cursor);
87
- providerCursor = state.cursor;
88
- const scanned = await (await driver.getInstance()).scan(providerCursor, {
89
- count: limit,
90
- match: `${escapeRedisGlob(prefix)}*`
34
+ driver.clear = async (prefix) => {
35
+ const keys = [];
36
+ let cursor = "0";
37
+ do {
38
+ const [next, page] = await (await client()).scan(cursor, {
39
+ count: keyBatchSize,
40
+ match: `${escapeRedisGlob(prefixed(prefix ?? ""))}*`
91
41
  });
92
- providerCursor = String(scanned[0]);
93
- if (providerCursor === state.cursor && providerCursor !== "0") throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Upstash KV scan returned a repeated pagination cursor." });
94
- keys = [...new Set(scanned[1])];
95
- }
96
- const pageKeys = keys.slice(0, limit);
97
- const overflow = keys.slice(limit);
98
- if (overflow.length > 0) return {
99
- keys: pageKeys,
100
- cursor: await retainContinuation(overflow, providerCursor)
101
- };
102
- if (providerCursor === "0") return { keys: pageKeys };
103
- return {
104
- keys: pageKeys,
105
- cursor: encodeCursor({ cursor: providerCursor })
42
+ cursor = String(next);
43
+ keys.push(...page);
44
+ } while (cursor !== "0");
45
+ for (const batch of chunks(keys, keyBatchSize)) await (await client()).del(...batch);
46
+ };
47
+ driver.getAndDeleteItem = async (key) => (await client()).getdel(prefixed(key));
48
+ driver.incrementItem = async (key, ttl) => redisIncrementResult(await (await client()).eval(redisIncrementScript, [prefixed(key)], [String(redisTTLSeconds(ttl))]));
49
+ driver.deleteIfEqualsItem = async (key, expected) => Number(await (await client()).eval(redisDeleteIfEqualsScript, [prefixed(key)], [expected])) === 1;
50
+ driver.setIfAbsentItem = async (key, value, ttl) => {
51
+ const setOptions = ttl === void 0 ? { nx: true } : {
52
+ ex: redisTTLSeconds(ttl),
53
+ nx: true
106
54
  };
55
+ return await (await client()).set(prefixed(key), value, setOptions) === "OK";
56
+ };
57
+ driver.listKeys = createPortableRedisKeyLister("Upstash KV", async (cursor, match, count) => {
58
+ const [next, keys] = await (await client()).scan(cursor, {
59
+ count,
60
+ match: `${escapeRedisGlob(base)}:${match}`
61
+ });
62
+ return [String(next), keys.map(unprefixed)];
63
+ });
64
+ const dispose = driver.dispose;
65
+ driver.dispose = async () => {
66
+ await dispose?.call(driver);
107
67
  };
108
68
  return driver;
109
69
  }