@vite-hub/kv 0.0.4 → 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.
- package/README.md +110 -14
- package/dist/batch--v0ri69O.js +40 -0
- package/dist/cli-DpPhz_Ek.d.ts +163 -0
- package/dist/cli.d.ts +17 -0
- package/dist/cli.js +469 -0
- package/dist/cloudflare-env-lOtHHsgP.js +46 -0
- package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
- package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
- package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
- package/dist/config-BXEVoZE3.js +250 -0
- package/dist/{dist-DDW1iC5f.js → create-storage-BGsrQKw3.js} +266 -115
- package/dist/cursor-history-BqIQePNP.js +165 -0
- package/dist/database-72Jk3VVk.js +250 -0
- package/dist/deno-kv-BM9mYdUp.js +128 -0
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/driver-BwxgaQ-f.d.ts +15 -0
- package/dist/durability.d.ts +17 -0
- package/dist/durability.js +53 -0
- package/dist/error-diagnostics-BxqvtEIb.js +147 -0
- package/dist/errors-DbwufFZp.js +60 -0
- package/dist/errors.d.ts +23 -7
- package/dist/errors.js +2 -20
- package/dist/fs-lite-BLZId9_P.js +386 -0
- package/dist/fs-lite-RAoxu8L0.js +2 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +364 -109
- package/dist/inspect-BIKQsqX4.js +118 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/main-F3Y22_uV.js +2353 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-B-WZ7P1h.js +1351 -0
- package/dist/operations-Ch-gKaey.js +441 -0
- package/dist/operations.d.ts +75 -0
- package/dist/operations.js +318 -0
- package/dist/redis-shared-E5mahECF.js +94 -0
- package/dist/results-p7nPCnaJ.js +6 -0
- package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
- package/dist/runtime/cloudflare-kv.d.ts +3 -4
- package/dist/runtime/cloudflare-kv.js +1 -23
- package/dist/runtime/cloudflare-request-env.d.ts +7 -0
- package/dist/runtime/cloudflare-request-env.js +11 -0
- package/dist/runtime/nitro-plugin.d.ts +12 -0
- package/dist/runtime/nitro-plugin.js +22 -0
- package/dist/runtime/redis-driver.d.ts +11 -0
- package/dist/runtime/redis-driver.js +113 -0
- package/dist/runtime/unstorage-driver.d.ts +14 -0
- package/dist/runtime/unstorage-driver.js +33 -0
- package/dist/runtime/upstash-driver.d.ts +4 -6
- package/dist/runtime/upstash-driver.js +60 -110
- package/dist/{driver-BT9WefKi.d.ts → types-Bj3EQoRg.d.ts} +16 -11
- package/dist/types-DEiKew_3.d.ts +312 -0
- package/dist/upstash-DDlqTttY.js +40 -0
- package/dist/utils2-FozcTsmb.js +31 -0
- package/dist/virtual-module.d.ts +2 -0
- package/dist/virtual.d.ts +1 -1
- package/dist/vite.d.ts +159 -14
- package/dist/vite.js +1329 -2898
- package/package.json +68 -19
- package/dist/config-aM9Ae7tH.js +0 -110
- package/dist/deno-kv-cJx3jU10.js +0 -69
- package/dist/fs-lite-BxzdiJSi.js +0 -79
- package/dist/types-CO0DRjJa.d.ts +0 -78
package/dist/index.js
CHANGED
|
@@ -1,45 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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";
|
|
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";
|
|
6
|
+
import { o as normalizeKey } from "./utils2-FozcTsmb.js";
|
|
7
|
+
import { t as resolveRuntimeKVOptions } from "./upstash-DDlqTttY.js";
|
|
8
|
+
import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch--v0ri69O.js";
|
|
9
|
+
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
5
10
|
import { destr } from "destr";
|
|
6
|
-
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
7
|
-
const runtimeGlobal = globalThis;
|
|
8
|
-
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
9
|
-
function getActiveCloudflareEnv() {
|
|
10
|
-
const scoped = activeEnvStorage.getStore();
|
|
11
|
-
return scoped ? scoped.env : globalThis.__env__;
|
|
12
|
-
}
|
|
13
|
-
//#endregion
|
|
14
|
-
//#region src/runtime/upstash.ts
|
|
15
|
-
function isMaskedValue(value) {
|
|
16
|
-
return !value || /^\*+$/.test(value);
|
|
17
|
-
}
|
|
18
|
-
function assertRuntimeValue(value, envName) {
|
|
19
|
-
if (isMaskedValue(value)) throw new Error(`Missing runtime environment variable \`${envName}\` for Upstash KV.`);
|
|
20
|
-
}
|
|
21
|
-
function resolveRuntimeUpstashStore(config, env) {
|
|
22
|
-
const envUrl = readEnv(env, "KV_REST_API_URL");
|
|
23
|
-
const envToken = readEnv(env, "KV_REST_API_TOKEN");
|
|
24
|
-
const resolved = {
|
|
25
|
-
...config,
|
|
26
|
-
token: isMaskedValue(config.token) ? envToken || config.token : config.token,
|
|
27
|
-
url: isMaskedValue(config.url) ? envUrl || config.url : config.url
|
|
28
|
-
};
|
|
29
|
-
assertRuntimeValue(resolved.url, "KV_REST_API_URL");
|
|
30
|
-
assertRuntimeValue(resolved.token, "KV_REST_API_TOKEN");
|
|
31
|
-
return resolved;
|
|
32
|
-
}
|
|
33
|
-
function resolveRuntimeKVOptions(config, env = process.env) {
|
|
34
|
-
if (!config || config.store.driver !== "upstash") return config;
|
|
35
|
-
return {
|
|
36
|
-
...config,
|
|
37
|
-
store: resolveRuntimeUpstashStore(config.store, env)
|
|
38
|
-
};
|
|
39
|
-
}
|
|
40
|
-
//#endregion
|
|
41
11
|
//#region src/runtime/driver.ts
|
|
42
|
-
const lazyDriverMethods = new Set([
|
|
12
|
+
const lazyDriverMethods = /* @__PURE__ */ new Set([
|
|
43
13
|
"clear",
|
|
44
14
|
"getItem",
|
|
45
15
|
"getKeys",
|
|
@@ -48,32 +18,84 @@ const lazyDriverMethods = new Set([
|
|
|
48
18
|
"removeItem",
|
|
49
19
|
"setItem"
|
|
50
20
|
]);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
"
|
|
54
|
-
"
|
|
21
|
+
/** The driver method behind each atomic KV operation. */
|
|
22
|
+
const atomicDriverMethods = {
|
|
23
|
+
deleteIfEquals: "deleteIfEqualsItem",
|
|
24
|
+
getAndDelete: "getAndDeleteItem",
|
|
25
|
+
increment: "incrementItem",
|
|
26
|
+
setIfAbsent: "setIfAbsentItem"
|
|
27
|
+
};
|
|
28
|
+
const driverAtomicOperations = {
|
|
29
|
+
"cloudflare": {},
|
|
30
|
+
"database": {
|
|
31
|
+
deleteIfEquals: true,
|
|
32
|
+
getAndDelete: true,
|
|
33
|
+
increment: true,
|
|
34
|
+
setIfAbsent: true
|
|
35
|
+
},
|
|
36
|
+
"deno-kv": { setIfAbsent: true },
|
|
37
|
+
"fs-lite": { setIfAbsent: true },
|
|
38
|
+
"redis": {
|
|
39
|
+
deleteIfEquals: true,
|
|
40
|
+
getAndDelete: true,
|
|
41
|
+
increment: true,
|
|
42
|
+
setIfAbsent: true
|
|
43
|
+
},
|
|
44
|
+
"upstash": {
|
|
45
|
+
deleteIfEquals: true,
|
|
46
|
+
getAndDelete: true,
|
|
47
|
+
increment: true,
|
|
48
|
+
setIfAbsent: true
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
/** Other optional unstorage methods that a driver has. */
|
|
52
|
+
const otherOptionalDriverMethods = {
|
|
53
|
+
"cloudflare": ["validateBatch"],
|
|
54
|
+
"fs-lite": [
|
|
55
55
|
"getItemRaw",
|
|
56
56
|
"getMeta",
|
|
57
57
|
"setItemRaw"
|
|
58
|
-
]
|
|
59
|
-
"upstash": new Set([
|
|
60
|
-
"getAndDeleteItem",
|
|
61
|
-
"getItems",
|
|
62
|
-
"incrementItem"
|
|
63
|
-
])
|
|
58
|
+
]
|
|
64
59
|
};
|
|
65
|
-
|
|
60
|
+
/** Batch methods. A driver without one gets a version that calls the single-key method for each key. */
|
|
61
|
+
const batchDriverMethods = /* @__PURE__ */ new Set(["getItems", "setItems"]);
|
|
62
|
+
const lazyOptionalDriverMethods = Object.fromEntries(Object.entries(driverAtomicOperations).map(([driver, operations]) => [driver, /* @__PURE__ */ new Set([...Object.keys(operations).map((operation) => atomicDriverMethods[operation]), ...otherOptionalDriverMethods[driver] ?? []])]));
|
|
63
|
+
async function createDatabaseDriver(store, loadDatabases) {
|
|
64
|
+
const { default: factory, kvSqlClientFromDatabase } = await import("./database-72Jk3VVk.js");
|
|
65
|
+
return factory(store, async () => {
|
|
66
|
+
const entry = loadDatabases ? (await loadDatabases())[store.database] : void 0;
|
|
67
|
+
if (!entry) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
|
|
68
|
+
database: store.database,
|
|
69
|
+
problem: "missing"
|
|
70
|
+
});
|
|
71
|
+
return kvSqlClientFromDatabase(entry.db, store.database);
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
async function createRuntimeDriver(store, loadDatabases) {
|
|
66
75
|
switch (store.driver) {
|
|
67
|
-
case "cloudflare
|
|
76
|
+
case "cloudflare": {
|
|
77
|
+
const { localBase } = store;
|
|
78
|
+
if (localBase) {
|
|
79
|
+
const { default: factory } = await import("./cloudflare-kv-local-BBw3ZT1K.js");
|
|
80
|
+
return factory({
|
|
81
|
+
...store,
|
|
82
|
+
localBase
|
|
83
|
+
});
|
|
84
|
+
}
|
|
68
85
|
const { default: factory } = await import("./runtime/cloudflare-kv.js");
|
|
69
86
|
return factory(store);
|
|
70
87
|
}
|
|
88
|
+
case "database": return createDatabaseDriver(store, loadDatabases);
|
|
71
89
|
case "deno-kv": {
|
|
72
|
-
const { default: factory } = await import("./deno-kv-
|
|
90
|
+
const { default: factory } = await import("./deno-kv-BM9mYdUp.js");
|
|
73
91
|
return factory(store);
|
|
74
92
|
}
|
|
75
93
|
case "fs-lite": {
|
|
76
|
-
const { default: factory } = await import("./fs-lite-
|
|
94
|
+
const { default: factory } = await import("./fs-lite-RAoxu8L0.js");
|
|
95
|
+
return factory(store);
|
|
96
|
+
}
|
|
97
|
+
case "redis": {
|
|
98
|
+
const { default: factory } = await import("@vite-hub/kv/runtime/redis-driver");
|
|
77
99
|
return factory(store);
|
|
78
100
|
}
|
|
79
101
|
case "upstash": {
|
|
@@ -82,13 +104,23 @@ async function createRuntimeDriver(store) {
|
|
|
82
104
|
}
|
|
83
105
|
}
|
|
84
106
|
}
|
|
85
|
-
function createLazyKVRuntimeDriver(config) {
|
|
107
|
+
function createLazyKVRuntimeDriver(config, loadDatabases) {
|
|
86
108
|
let driverPromise;
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
if (
|
|
90
|
-
|
|
91
|
-
|
|
109
|
+
let disposed = false;
|
|
110
|
+
function resolve() {
|
|
111
|
+
if (disposed) return Promise.reject(/* @__PURE__ */ new Error("KV storage has been disposed."));
|
|
112
|
+
if (driverPromise) return driverPromise;
|
|
113
|
+
const pending = (async () => {
|
|
114
|
+
const runtime = resolveRuntimeKVOptions(config);
|
|
115
|
+
if (!runtime) throw kvErrorDiagnostics.KV_DISABLED();
|
|
116
|
+
return createRuntimeDriver(runtime.store, loadDatabases);
|
|
117
|
+
})();
|
|
118
|
+
driverPromise = pending;
|
|
119
|
+
pending.catch(() => {
|
|
120
|
+
if (driverPromise === pending) driverPromise = void 0;
|
|
121
|
+
});
|
|
122
|
+
return pending;
|
|
123
|
+
}
|
|
92
124
|
const target = {
|
|
93
125
|
name: `lazy:${config.store.driver}`,
|
|
94
126
|
options: config.store
|
|
@@ -97,10 +129,15 @@ function createLazyKVRuntimeDriver(config) {
|
|
|
97
129
|
const own = t[prop];
|
|
98
130
|
if (own !== void 0) return own;
|
|
99
131
|
if (prop === "dispose") return async () => {
|
|
132
|
+
disposed = true;
|
|
100
133
|
if (!driverPromise) return;
|
|
101
134
|
const driver = await driverPromise;
|
|
102
135
|
return driver.dispose?.call(driver);
|
|
103
136
|
};
|
|
137
|
+
if (batchDriverMethods.has(prop)) return async (...args) => {
|
|
138
|
+
const driver = await resolve();
|
|
139
|
+
return (prop === "getItems" ? driver.getItems ?? getItemsOneByOne(driver) : driver.setItems ?? setItemsOneByOne(driver)).apply(driver, args);
|
|
140
|
+
};
|
|
104
141
|
const optionalMethods = lazyOptionalDriverMethods[config.store.driver];
|
|
105
142
|
if (!lazyDriverMethods.has(prop) && !optionalMethods.has(prop)) return void 0;
|
|
106
143
|
return async (...args) => {
|
|
@@ -111,50 +148,183 @@ function createLazyKVRuntimeDriver(config) {
|
|
|
111
148
|
}
|
|
112
149
|
//#endregion
|
|
113
150
|
//#region src/runtime/hosted-storage.ts
|
|
114
|
-
var KVStoreConfigurationError = class extends Error {};
|
|
115
|
-
var KVAtomicOperationUnsupportedError = class extends KVStoreConfigurationError {
|
|
116
|
-
constructor(store) {
|
|
117
|
-
super(`[vitehub] KV store "${store}" does not support atomic operations. Use Upstash.`);
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
151
|
function assertHostedConfig(config) {
|
|
121
|
-
if (!config) throw
|
|
152
|
+
if (!config) throw kvErrorDiagnostics.KV_DISABLED();
|
|
122
153
|
return config;
|
|
123
154
|
}
|
|
124
155
|
function deserializeValue(value) {
|
|
125
156
|
if (typeof value !== "string") return value;
|
|
126
157
|
return destr(value);
|
|
127
158
|
}
|
|
128
|
-
function
|
|
129
|
-
return
|
|
159
|
+
function isPrimitive(value) {
|
|
160
|
+
return value === null || typeof value !== "object" && typeof value !== "function";
|
|
161
|
+
}
|
|
162
|
+
function serializeValue(value, operation = "setIfAbsent") {
|
|
163
|
+
if (value === void 0) throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
164
|
+
operation,
|
|
165
|
+
problem: "missing"
|
|
166
|
+
});
|
|
167
|
+
if (isPrimitive(value)) return String(value);
|
|
168
|
+
if (Array.isArray(value)) return serializeJSONValue(value, operation);
|
|
169
|
+
if (value && typeof value === "object") {
|
|
170
|
+
const prototype = Object.getPrototypeOf(value);
|
|
171
|
+
if (prototype === null || prototype === Object.prototype) return serializeJSONValue(value, operation);
|
|
172
|
+
const toJSON = Reflect.get(value, "toJSON");
|
|
173
|
+
if (typeof toJSON === "function") return serializeValue(toJSON.call(value), operation);
|
|
174
|
+
}
|
|
175
|
+
throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
176
|
+
operation,
|
|
177
|
+
problem: "unserializable"
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
function serializeJSONValue(value, operation) {
|
|
181
|
+
try {
|
|
182
|
+
const serialized = JSON.stringify(value);
|
|
183
|
+
if (serialized !== void 0) return serialized;
|
|
184
|
+
} catch {
|
|
185
|
+
throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
186
|
+
operation,
|
|
187
|
+
problem: "unserializable"
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
throw kvErrorDiagnostics.KV_INVALID_VALUE({
|
|
191
|
+
operation,
|
|
192
|
+
problem: "unserializable"
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
/** The line that `vite dev` prints when a store uses real data. Only `vite dev` resolves a store with `remote: true`. */
|
|
196
|
+
function kvRemoteNotice(name, store) {
|
|
197
|
+
if (store.driver === "upstash" && store.remote) return `[vitehub] KV store "${name}" is remote: \`vite dev\` uses the real Upstash database. Writes change real data.`;
|
|
198
|
+
if (store.driver === "cloudflare" && store.remote) return `[vitehub] KV store "${name}" is remote: \`vite dev\` uses the real Cloudflare KV namespace${store.namespaceId ? ` ${store.namespaceId}` : ""} through the \`${store.binding}\` binding. Writes change real data.`;
|
|
130
199
|
}
|
|
131
|
-
function
|
|
200
|
+
function resolveHostedKVStore(config, name = "default") {
|
|
132
201
|
const resolved = assertHostedConfig(config);
|
|
133
|
-
const
|
|
134
|
-
|
|
202
|
+
const stores = resolved.stores || { default: resolved.store };
|
|
203
|
+
const store = Object.hasOwn(stores, name) ? stores[name] : void 0;
|
|
204
|
+
if (!store) throw kvErrorDiagnostics.KV_STORE_NOT_FOUND({ store: name });
|
|
205
|
+
return store;
|
|
206
|
+
}
|
|
207
|
+
/** Creates storage with the build-selected driver; connection credentials are resolved at runtime. */
|
|
208
|
+
function createHostedKVStorage(config, name = "default", loadDatabases) {
|
|
209
|
+
const store = resolveHostedKVStore(config, name);
|
|
210
|
+
const notice = kvRemoteNotice(name, store);
|
|
211
|
+
if (notice) console.warn(notice);
|
|
135
212
|
const driver = createLazyKVRuntimeDriver({
|
|
136
213
|
store,
|
|
137
214
|
stores: {
|
|
138
215
|
default: store,
|
|
139
216
|
[name]: store
|
|
140
217
|
}
|
|
218
|
+
}, loadDatabases);
|
|
219
|
+
const storage = createKVStorage$1(driver);
|
|
220
|
+
storage.listKeys = (options) => driver.listKeys({
|
|
221
|
+
...options,
|
|
222
|
+
prefix: normalizeKVListPrefix(options.prefix)
|
|
141
223
|
});
|
|
142
|
-
const storage = createStorage({ driver });
|
|
143
|
-
storage.listKeys = (options) => driver.listKeys(options);
|
|
144
224
|
const getAndDeleteItem = driver.getAndDeleteItem;
|
|
145
225
|
const incrementItem = driver.incrementItem;
|
|
146
|
-
if (getAndDeleteItem) storage.getAndDeleteItem = async (key) => {
|
|
147
|
-
|
|
226
|
+
if (getAndDeleteItem) storage.getAndDeleteItem = async (key, options) => {
|
|
227
|
+
const value = await getAndDeleteItem(normalizeKey(key));
|
|
228
|
+
return options?.type === "text" ? value : deserializeValue(value);
|
|
148
229
|
};
|
|
149
230
|
if (incrementItem) storage.incrementItem = (key, ttl) => incrementItem(normalizeKey(key), ttl);
|
|
231
|
+
const setIfAbsentItem = driver.setIfAbsentItem;
|
|
232
|
+
if (setIfAbsentItem) storage.setIfAbsentItem = async (key, value, ttl) => setIfAbsentItem(normalizeKey(key), serializeValue(value), ttl);
|
|
233
|
+
const deleteIfEqualsItem = driver.deleteIfEqualsItem;
|
|
234
|
+
if (deleteIfEqualsItem) storage.deleteIfEqualsItem = async (key, expected) => deleteIfEqualsItem(normalizeKey(key), serializeValue(expected, "deleteIfEquals"));
|
|
150
235
|
return storage;
|
|
151
236
|
}
|
|
152
237
|
//#endregion
|
|
238
|
+
//#region src/runtime/lock.ts
|
|
239
|
+
const firstRetryMs = 25;
|
|
240
|
+
const maxRetryMs = 500;
|
|
241
|
+
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
|
+
/**
|
|
246
|
+
* A lock on `key` built on `setIfAbsent()` with a TTL and `deleteIfEquals()`. Each acquire writes a new random owner
|
|
247
|
+
* token, and the release deletes the key only when it still holds that token.
|
|
248
|
+
*/
|
|
249
|
+
function createKVLock(store, resolveStorage, key, options) {
|
|
250
|
+
async function acquire() {
|
|
251
|
+
const { ttl } = options;
|
|
252
|
+
const wait = options.wait ?? 0;
|
|
253
|
+
if (!validTtl(ttl)) return [kvErrorDiagnostics.KV_INVALID_TTL(), void 0];
|
|
254
|
+
if (!Number.isFinite(wait) || wait < 0) return [kvErrorDiagnostics.KV_INVALID_WAIT(), void 0];
|
|
255
|
+
const storage = await resolveStorage();
|
|
256
|
+
return kvResult("lock", store, async () => {
|
|
257
|
+
const claim = storage.setIfAbsentItem;
|
|
258
|
+
const free = storage.deleteIfEqualsItem;
|
|
259
|
+
if (!claim || !free) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
260
|
+
operation: "lock",
|
|
261
|
+
store
|
|
262
|
+
});
|
|
263
|
+
const owner = globalThis.crypto.randomUUID();
|
|
264
|
+
const deadline = performance.now() + wait * 1e3;
|
|
265
|
+
let delay = firstRetryMs;
|
|
266
|
+
while (true) {
|
|
267
|
+
const started = performance.now();
|
|
268
|
+
if (await claim(key, owner, ttl)) {
|
|
269
|
+
if (performance.now() - started < ttl * 1e3) return {
|
|
270
|
+
acquired: true,
|
|
271
|
+
release: () => kvResult("lock", store, () => free(key, owner))
|
|
272
|
+
};
|
|
273
|
+
await free(key, owner);
|
|
274
|
+
return { acquired: false };
|
|
275
|
+
}
|
|
276
|
+
const left = deadline - performance.now();
|
|
277
|
+
if (left <= 0) return { acquired: false };
|
|
278
|
+
await sleep(Math.min(left, delay / 2 + Math.random() * delay / 2));
|
|
279
|
+
delay = Math.min(delay * 2, maxRetryMs);
|
|
280
|
+
}
|
|
281
|
+
}, ["KV_UNSUPPORTED_OPERATION"]);
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
acquire,
|
|
285
|
+
async run(fn) {
|
|
286
|
+
const [error, lock] = await acquire();
|
|
287
|
+
if (error) return [error, void 0];
|
|
288
|
+
if (!lock.acquired) return [void 0, { acquired: false }];
|
|
289
|
+
let value;
|
|
290
|
+
try {
|
|
291
|
+
value = await fn();
|
|
292
|
+
} catch (cause) {
|
|
293
|
+
await lock.release();
|
|
294
|
+
throw cause;
|
|
295
|
+
}
|
|
296
|
+
const [releaseError] = await lock.release();
|
|
297
|
+
if (releaseError) return [releaseError, void 0];
|
|
298
|
+
return [void 0, {
|
|
299
|
+
acquired: true,
|
|
300
|
+
value
|
|
301
|
+
}];
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
//#endregion
|
|
153
306
|
//#region src/runtime/storage.ts
|
|
154
307
|
const storagePromises = /* @__PURE__ */ new Map();
|
|
308
|
+
let disposal;
|
|
309
|
+
/** Releases every cached store. Call from the application's shutdown hook after stopping new work. */
|
|
310
|
+
function disposeKVStores() {
|
|
311
|
+
if (disposal) return disposal;
|
|
312
|
+
const stores = [...storagePromises.values()];
|
|
313
|
+
storagePromises.clear();
|
|
314
|
+
const pending = Promise.allSettled(stores.map(async (promise) => {
|
|
315
|
+
await (await promise.catch(() => void 0))?.dispose();
|
|
316
|
+
})).then((results) => {
|
|
317
|
+
const failures = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
|
|
318
|
+
if (failures.length) throw new AggregateError(failures, "Failed to dispose KV stores.");
|
|
319
|
+
}).finally(() => {
|
|
320
|
+
disposal = void 0;
|
|
321
|
+
});
|
|
322
|
+
disposal = pending;
|
|
323
|
+
return pending;
|
|
324
|
+
}
|
|
155
325
|
function inferHosting(env) {
|
|
156
326
|
if (getActiveCloudflareEnv()) return "cloudflare";
|
|
157
|
-
const explicit = readEnv(env, "
|
|
327
|
+
const explicit = readEnv(env, "VITEHUB_HOST");
|
|
158
328
|
if (explicit) return explicit;
|
|
159
329
|
if (typeof globalThis.Deno?.openKv === "function") return "deno";
|
|
160
330
|
return readEnv(env, "KV_REST_API_URL") ? "vercel" : void 0;
|
|
@@ -165,74 +335,159 @@ function shouldFallbackHostedConfigImport(error) {
|
|
|
165
335
|
}
|
|
166
336
|
async function resolveHostedConfig() {
|
|
167
337
|
try {
|
|
168
|
-
|
|
338
|
+
const module = await import("#vitehub/kv/config");
|
|
339
|
+
const loadDatabases = "loadDatabases" in module ? module.loadDatabases : void 0;
|
|
340
|
+
return {
|
|
341
|
+
kv: module.kv,
|
|
342
|
+
...loadDatabases ? { loadDatabases } : {}
|
|
343
|
+
};
|
|
169
344
|
} catch (error) {
|
|
170
345
|
if (!shouldFallbackHostedConfigImport(error)) throw error;
|
|
171
346
|
const env = typeof process !== "undefined" ? process.env : {};
|
|
172
|
-
return normalizeKVOptions(void 0, {
|
|
347
|
+
return { kv: normalizeKVOptions(void 0, {
|
|
173
348
|
env,
|
|
174
349
|
hosting: inferHosting(env)
|
|
175
|
-
}) || false;
|
|
350
|
+
}) || false };
|
|
176
351
|
}
|
|
177
352
|
}
|
|
178
353
|
async function resolveStorage(name = "default") {
|
|
354
|
+
const test = getViteHubTestMode();
|
|
355
|
+
if (test) {
|
|
356
|
+
resolveHostedKVStore((await resolveHostedConfig()).kv, name);
|
|
357
|
+
return await test.backend(`kv:${name}`, async () => createHostedKVStorage({ store: {
|
|
358
|
+
base: await test.directory(`kv-${name}`),
|
|
359
|
+
driver: "fs-lite"
|
|
360
|
+
} }, "default"), (storage) => storage.dispose());
|
|
361
|
+
}
|
|
362
|
+
if (disposal) await disposal;
|
|
179
363
|
const existing = storagePromises.get(name);
|
|
180
364
|
if (existing) return existing;
|
|
181
|
-
|
|
182
|
-
const promise = resolveHostedConfig().then((config) => name === "default" ? createHostedKVStorage(config) : createNamedHostedKVStorage(config, name));
|
|
183
|
-
storagePromises.set(name, promise);
|
|
184
|
-
return promise;
|
|
185
|
-
}
|
|
186
|
-
const promise = resolveHostedConfig().then((config) => name === "default" ? createHostedKVStorage(config) : createNamedHostedKVStorage(config, name));
|
|
365
|
+
const promise = resolveHostedConfig().then((config) => createHostedKVStorage(config.kv, name, config.loadDatabases));
|
|
187
366
|
storagePromises.set(name, promise);
|
|
367
|
+
promise.catch(() => {
|
|
368
|
+
if (storagePromises.get(name) === promise) storagePromises.delete(name);
|
|
369
|
+
});
|
|
188
370
|
return promise;
|
|
189
371
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
372
|
+
/**
|
|
373
|
+
* The configured driver that a store uses in this server process. App tests return `fs-lite`.
|
|
374
|
+
* An unknown store throws. Reading the driver does not open a connection to the store.
|
|
375
|
+
*/
|
|
376
|
+
async function getKVStoreDriver(name = "default") {
|
|
377
|
+
const store = resolveHostedKVStore((await resolveHostedConfig()).kv, name);
|
|
378
|
+
if (getViteHubTestMode()) return "fs-lite";
|
|
379
|
+
return store.driver;
|
|
380
|
+
}
|
|
381
|
+
async function runKVOperation(operation, name, run, codes = []) {
|
|
382
|
+
const storage = await resolveStorage(name);
|
|
383
|
+
return kvResult(operation, name, () => run(storage), codes);
|
|
384
|
+
}
|
|
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;
|
|
194
395
|
}
|
|
195
396
|
function createKVStorage(name = "default") {
|
|
196
397
|
return {
|
|
197
398
|
async clear(base, options) {
|
|
198
399
|
return runKVOperation("clear", name, async (storage) => storage.clear(base, options));
|
|
199
400
|
},
|
|
200
|
-
async
|
|
201
|
-
return runKVOperation("
|
|
401
|
+
async delete(key, options) {
|
|
402
|
+
return runKVOperation("delete", name, async (storage) => storage.removeItem(key, options), kvKeyLimitCodes);
|
|
403
|
+
},
|
|
404
|
+
async deleteIfEquals(key, expected) {
|
|
405
|
+
return runKVOperation("deleteIfEquals", name, async (storage) => {
|
|
406
|
+
if (!storage.deleteIfEqualsItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
407
|
+
operation: "deleteIfEquals",
|
|
408
|
+
store: name
|
|
409
|
+
});
|
|
410
|
+
return storage.deleteIfEqualsItem(key, expected);
|
|
411
|
+
}, ["KV_INVALID_VALUE", "KV_UNSUPPORTED_OPERATION"]);
|
|
202
412
|
},
|
|
203
413
|
async get(key, options) {
|
|
204
|
-
return runKVOperation("get", name, (storage) => storage.getItem(key, options));
|
|
414
|
+
return runKVOperation("get", name, (storage) => storage.getItem(key, options), kvKeyLimitCodes);
|
|
205
415
|
},
|
|
206
|
-
async getAndDelete(key) {
|
|
207
|
-
return runKVOperation("getAndDelete", name, (storage) => {
|
|
208
|
-
if (!storage.getAndDeleteItem) throw
|
|
209
|
-
|
|
210
|
-
|
|
416
|
+
async getAndDelete(key, options) {
|
|
417
|
+
return runKVOperation("getAndDelete", name, async (storage) => {
|
|
418
|
+
if (!storage.getAndDeleteItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
419
|
+
operation: "getAndDelete",
|
|
420
|
+
store: name
|
|
421
|
+
});
|
|
422
|
+
return storage.getAndDeleteItem(key, options);
|
|
423
|
+
}, ["KV_UNSUPPORTED_OPERATION"]);
|
|
424
|
+
},
|
|
425
|
+
async getMany(keys, options) {
|
|
426
|
+
return runKVOperation("getMany", name, (storage) => storage.getMany(keys, options), kvKeyLimitCodes);
|
|
211
427
|
},
|
|
212
428
|
async has(key, options) {
|
|
213
|
-
return runKVOperation("has", name, (storage) => storage.hasItem(key, options));
|
|
429
|
+
return runKVOperation("has", name, (storage) => storage.hasItem(key, options), kvKeyLimitCodes);
|
|
214
430
|
},
|
|
215
431
|
async increment(key, ttl) {
|
|
216
|
-
return runKVOperation("increment", name, (storage) => {
|
|
217
|
-
if (!storage.incrementItem) throw
|
|
432
|
+
return runKVOperation("increment", name, async (storage) => {
|
|
433
|
+
if (!storage.incrementItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
434
|
+
operation: "increment",
|
|
435
|
+
store: name
|
|
436
|
+
});
|
|
437
|
+
if (!Number.isFinite(ttl) || ttl <= 0 || !Number.isSafeInteger(Math.ceil(ttl))) throw kvErrorDiagnostics.KV_INVALID_TTL();
|
|
218
438
|
return storage.incrementItem(key, ttl);
|
|
219
|
-
});
|
|
439
|
+
}, ["KV_INVALID_TTL", "KV_UNSUPPORTED_OPERATION"]);
|
|
220
440
|
},
|
|
221
441
|
async keys(base, options) {
|
|
222
442
|
return runKVOperation("keys", name, (storage) => storage.getKeys(base, options));
|
|
223
443
|
},
|
|
444
|
+
lock(key, options) {
|
|
445
|
+
return createKVLock(name, () => resolveStorage(name), key, options);
|
|
446
|
+
},
|
|
224
447
|
async list(options) {
|
|
225
|
-
if (!Number.isInteger(options.limit) || options.limit <= 0)
|
|
226
|
-
return runKVOperation("list", name, (storage) => storage.listKeys(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"]);
|
|
227
450
|
},
|
|
228
451
|
async set(key, value, options) {
|
|
229
|
-
return runKVOperation("set", name, async (storage) =>
|
|
452
|
+
return runKVOperation("set", name, async (storage) => {
|
|
453
|
+
const ttl = readSetTTL("set", options);
|
|
454
|
+
return storage.setItem(key, value, ttl === void 0 ? void 0 : { ttl });
|
|
455
|
+
}, [
|
|
456
|
+
...kvWriteLimitCodes,
|
|
457
|
+
"KV_INVALID_OPTION",
|
|
458
|
+
"KV_INVALID_TTL"
|
|
459
|
+
]);
|
|
230
460
|
},
|
|
231
|
-
|
|
232
|
-
return
|
|
233
|
-
|
|
461
|
+
async setMany(entries, options) {
|
|
462
|
+
return runKVOperation("setMany", name, async (storage) => {
|
|
463
|
+
const ttl = readSetTTL("setMany", options);
|
|
464
|
+
return storage.setMany(entries, ttl === void 0 ? void 0 : { ttl });
|
|
465
|
+
}, [
|
|
466
|
+
...kvWriteLimitCodes,
|
|
467
|
+
"KV_INVALID_OPTION",
|
|
468
|
+
"KV_INVALID_TTL"
|
|
469
|
+
]);
|
|
470
|
+
},
|
|
471
|
+
async setIfAbsent(key, value, options) {
|
|
472
|
+
return runKVOperation("setIfAbsent", name, async (storage) => {
|
|
473
|
+
if (!storage.setIfAbsentItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
|
|
474
|
+
operation: "setIfAbsent",
|
|
475
|
+
store: name
|
|
476
|
+
});
|
|
477
|
+
return storage.setIfAbsentItem(key, value, readSetTTL("setIfAbsent", options));
|
|
478
|
+
}, [
|
|
479
|
+
"KV_INVALID_OPTION",
|
|
480
|
+
"KV_INVALID_TTL",
|
|
481
|
+
"KV_INVALID_VALUE",
|
|
482
|
+
"KV_UNSUPPORTED_OPERATION"
|
|
483
|
+
]);
|
|
484
|
+
},
|
|
485
|
+
store: selectKVStore
|
|
234
486
|
};
|
|
235
487
|
}
|
|
488
|
+
function selectKVStore(name, options) {
|
|
489
|
+
return kvStoreWithMode(createKVStorage(name), options);
|
|
490
|
+
}
|
|
236
491
|
const kv = createKVStorage();
|
|
237
492
|
//#endregion
|
|
238
|
-
export { kv };
|
|
493
|
+
export { disposeKVStores, getKVStoreDriver, kv };
|