@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
package/dist/index.js CHANGED
@@ -1,43 +1,13 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
2
- import { n as kvResult } from "./errors-Dc2oiW-Y.js";
3
- import { a as readEnv, n as upstashTokenEnvNames, r as upstashUrlEnvNames, t as normalizeKVOptions } from "./config-DR6_5ZwI.js";
4
- import { n as getActiveCloudflareEnv } from "./cloudflare-env-C5rM7kUY.js";
5
- import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-29gMzf41.js";
6
- import { a as normalizeKey } from "./utils2-Dsb9P4_2.js";
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";
7
10
  import { destr } from "destr";
8
- //#region src/runtime/upstash.ts
9
- function isMaskedValue(value) {
10
- return !value || /^\*+$/.test(value);
11
- }
12
- function assertRuntimeValue(value, envNames) {
13
- if (isMaskedValue(value)) {
14
- const names = envNames.map((name) => `\`${name}\``).join(" or ");
15
- throw kvErrorDiagnostics.KV_MISSING_ENV({ names });
16
- }
17
- }
18
- function resolveRuntimeUpstashStore(config, env) {
19
- const completeEnvPair = upstashUrlEnvNames.map((urlName, index) => [readEnv(env, urlName), readEnv(env, upstashTokenEnvNames[index])]).find(([url, token]) => url && token);
20
- const envUrl = readEnv(env, ...upstashUrlEnvNames);
21
- const envToken = readEnv(env, ...upstashTokenEnvNames);
22
- const hasMaskedPair = isMaskedValue(config.url) && isMaskedValue(config.token);
23
- const resolveMaskedValue = (value, pairValue, fallback) => isMaskedValue(value) ? pairValue || fallback || value || "********" : value ?? "********";
24
- const resolved = {
25
- ...config,
26
- token: resolveMaskedValue(config.token, completeEnvPair?.[1], hasMaskedPair ? void 0 : envToken),
27
- url: resolveMaskedValue(config.url, completeEnvPair?.[0], hasMaskedPair ? void 0 : envUrl)
28
- };
29
- assertRuntimeValue(resolved.url, upstashUrlEnvNames);
30
- assertRuntimeValue(resolved.token, upstashTokenEnvNames);
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
12
  const lazyDriverMethods = /* @__PURE__ */ new Set([
43
13
  "clear",
@@ -48,32 +18,84 @@ const lazyDriverMethods = /* @__PURE__ */ new Set([
48
18
  "removeItem",
49
19
  "setItem"
50
20
  ]);
51
- const lazyOptionalDriverMethods = {
52
- "cloudflare-kv-binding": /* @__PURE__ */ new Set(),
53
- "deno-kv": /* @__PURE__ */ new Set(),
54
- "fs-lite": /* @__PURE__ */ new Set([
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": /* @__PURE__ */ new Set([
60
- "getAndDeleteItem",
61
- "getItems",
62
- "incrementItem"
63
- ])
58
+ ]
64
59
  };
65
- async function createRuntimeDriver(store) {
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-kv-binding": {
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-CSYGvRx4.js");
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-CbLKxLut.js");
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,7 +104,7 @@ async function createRuntimeDriver(store) {
82
104
  }
83
105
  }
84
106
  }
85
- function createLazyKVRuntimeDriver(config) {
107
+ function createLazyKVRuntimeDriver(config, loadDatabases) {
86
108
  let driverPromise;
87
109
  let disposed = false;
88
110
  function resolve() {
@@ -91,7 +113,7 @@ function createLazyKVRuntimeDriver(config) {
91
113
  const pending = (async () => {
92
114
  const runtime = resolveRuntimeKVOptions(config);
93
115
  if (!runtime) throw kvErrorDiagnostics.KV_DISABLED();
94
- return createRuntimeDriver(runtime.store);
116
+ return createRuntimeDriver(runtime.store, loadDatabases);
95
117
  })();
96
118
  driverPromise = pending;
97
119
  pending.catch(() => {
@@ -112,6 +134,10 @@ function createLazyKVRuntimeDriver(config) {
112
134
  const driver = await driverPromise;
113
135
  return driver.dispose?.call(driver);
114
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
+ };
115
141
  const optionalMethods = lazyOptionalDriverMethods[config.store.driver];
116
142
  if (!lazyDriverMethods.has(prop) && !optionalMethods.has(prop)) return void 0;
117
143
  return async (...args) => {
@@ -130,18 +156,66 @@ function deserializeValue(value) {
130
156
  if (typeof value !== "string") return value;
131
157
  return destr(value);
132
158
  }
133
- function createHostedKVStorage(config, name = "default") {
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.`;
199
+ }
200
+ function resolveHostedKVStore(config, name = "default") {
134
201
  const resolved = assertHostedConfig(config);
135
202
  const stores = resolved.stores || { default: resolved.store };
136
203
  const store = Object.hasOwn(stores, name) ? stores[name] : void 0;
137
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);
138
212
  const driver = createLazyKVRuntimeDriver({
139
213
  store,
140
214
  stores: {
141
215
  default: store,
142
216
  [name]: store
143
217
  }
144
- });
218
+ }, loadDatabases);
145
219
  const storage = createKVStorage$1(driver);
146
220
  storage.listKeys = (options) => driver.listKeys({
147
221
  ...options,
@@ -149,13 +223,86 @@ function createHostedKVStorage(config, name = "default") {
149
223
  });
150
224
  const getAndDeleteItem = driver.getAndDeleteItem;
151
225
  const incrementItem = driver.incrementItem;
152
- if (getAndDeleteItem) storage.getAndDeleteItem = async (key) => {
153
- return deserializeValue(await getAndDeleteItem(normalizeKey(key)));
226
+ if (getAndDeleteItem) storage.getAndDeleteItem = async (key, options) => {
227
+ const value = await getAndDeleteItem(normalizeKey(key));
228
+ return options?.type === "text" ? value : deserializeValue(value);
154
229
  };
155
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"));
156
235
  return storage;
157
236
  }
158
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
159
306
  //#region src/runtime/storage.ts
160
307
  const storagePromises = /* @__PURE__ */ new Map();
161
308
  let disposal;
@@ -177,7 +324,7 @@ function disposeKVStores() {
177
324
  }
178
325
  function inferHosting(env) {
179
326
  if (getActiveCloudflareEnv()) return "cloudflare";
180
- const explicit = readEnv(env, "VITEHUB_HOSTING");
327
+ const explicit = readEnv(env, "VITEHUB_HOST");
181
328
  if (explicit) return explicit;
182
329
  if (typeof globalThis.Deno?.openKv === "function") return "deno";
183
330
  return readEnv(env, "KV_REST_API_URL") ? "vercel" : void 0;
@@ -188,53 +335,98 @@ function shouldFallbackHostedConfigImport(error) {
188
335
  }
189
336
  async function resolveHostedConfig() {
190
337
  try {
191
- return (await import("#vitehub/kv/config")).kv;
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
+ };
192
344
  } catch (error) {
193
345
  if (!shouldFallbackHostedConfigImport(error)) throw error;
194
346
  const env = typeof process !== "undefined" ? process.env : {};
195
- return normalizeKVOptions(void 0, {
347
+ return { kv: normalizeKVOptions(void 0, {
196
348
  env,
197
349
  hosting: inferHosting(env)
198
- }) || false;
350
+ }) || false };
199
351
  }
200
352
  }
201
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
+ }
202
362
  if (disposal) await disposal;
203
363
  const existing = storagePromises.get(name);
204
364
  if (existing) return existing;
205
- const promise = resolveHostedConfig().then((config) => createHostedKVStorage(config, name));
365
+ const promise = resolveHostedConfig().then((config) => createHostedKVStorage(config.kv, name, config.loadDatabases));
206
366
  storagePromises.set(name, promise);
207
367
  promise.catch(() => {
208
368
  if (storagePromises.get(name) === promise) storagePromises.delete(name);
209
369
  });
210
370
  return promise;
211
371
  }
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
+ }
212
381
  async function runKVOperation(operation, name, run, codes = []) {
213
382
  const storage = await resolveStorage(name);
214
383
  return kvResult(operation, name, () => run(storage), codes);
215
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;
395
+ }
216
396
  function createKVStorage(name = "default") {
217
397
  return {
218
398
  async clear(base, options) {
219
399
  return runKVOperation("clear", name, async (storage) => storage.clear(base, options));
220
400
  },
221
- async del(key, options) {
222
- return runKVOperation("del", name, async (storage) => storage.removeItem(key, options));
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"]);
223
412
  },
224
413
  async get(key, options) {
225
- return runKVOperation("get", name, (storage) => storage.getItem(key, options));
414
+ return runKVOperation("get", name, (storage) => storage.getItem(key, options), kvKeyLimitCodes);
226
415
  },
227
- async getAndDelete(key) {
416
+ async getAndDelete(key, options) {
228
417
  return runKVOperation("getAndDelete", name, async (storage) => {
229
418
  if (!storage.getAndDeleteItem) throw kvErrorDiagnostics.KV_UNSUPPORTED_OPERATION({
230
419
  operation: "getAndDelete",
231
420
  store: name
232
421
  });
233
- return storage.getAndDeleteItem(key);
422
+ return storage.getAndDeleteItem(key, options);
234
423
  }, ["KV_UNSUPPORTED_OPERATION"]);
235
424
  },
425
+ async getMany(keys, options) {
426
+ return runKVOperation("getMany", name, (storage) => storage.getMany(keys, options), kvKeyLimitCodes);
427
+ },
236
428
  async has(key, options) {
237
- return runKVOperation("has", name, (storage) => storage.hasItem(key, options));
429
+ return runKVOperation("has", name, (storage) => storage.hasItem(key, options), kvKeyLimitCodes);
238
430
  },
239
431
  async increment(key, ttl) {
240
432
  return runKVOperation("increment", name, async (storage) => {
@@ -249,18 +441,53 @@ function createKVStorage(name = "default") {
249
441
  async keys(base, options) {
250
442
  return runKVOperation("keys", name, (storage) => storage.getKeys(base, options));
251
443
  },
444
+ lock(key, options) {
445
+ return createKVLock(name, () => resolveStorage(name), key, options);
446
+ },
252
447
  async list(options) {
253
448
  if (!Number.isInteger(options.limit) || options.limit <= 0) return [kvErrorDiagnostics.KV_INVALID_LIMIT(), void 0];
254
449
  return runKVOperation("list", name, (storage) => storage.listKeys(options), ["KV_INVALID_CURSOR"]);
255
450
  },
256
451
  async set(key, value, options) {
257
- return runKVOperation("set", name, async (storage) => storage.setItem(key, value, options));
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
+ ]);
258
460
  },
259
- store(storeName) {
260
- return createKVStorage(storeName);
261
- }
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
262
486
  };
263
487
  }
488
+ function selectKVStore(name, options) {
489
+ return kvStoreWithMode(createKVStorage(name), options);
490
+ }
264
491
  const kv = createKVStorage();
265
492
  //#endregion
266
- export { disposeKVStores, kv };
493
+ export { disposeKVStores, getKVStoreDriver, kv };
@@ -0,0 +1,118 @@
1
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
2
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
3
+ function normalizeWindowsPath(input = "") {
4
+ if (!input) return input;
5
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
6
+ }
7
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
8
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
9
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
10
+ function cwd() {
11
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
12
+ return "/";
13
+ }
14
+ const resolve = function(...arguments_) {
15
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
16
+ let resolvedPath = "";
17
+ let resolvedAbsolute = false;
18
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
19
+ const path = index >= 0 ? arguments_[index] : cwd();
20
+ if (!path || path.length === 0) continue;
21
+ resolvedPath = `${path}/${resolvedPath}`;
22
+ resolvedAbsolute = isAbsolute(path);
23
+ }
24
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
25
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
26
+ return resolvedPath.length > 0 ? resolvedPath : ".";
27
+ };
28
+ function normalizeString(path, allowAboveRoot) {
29
+ let res = "";
30
+ let lastSegmentLength = 0;
31
+ let lastSlash = -1;
32
+ let dots = 0;
33
+ let char = null;
34
+ for (let index = 0; index <= path.length; ++index) {
35
+ if (index < path.length) char = path[index];
36
+ else if (char === "/") break;
37
+ else char = "/";
38
+ if (char === "/") {
39
+ if (lastSlash === index - 1 || dots === 1);
40
+ else if (dots === 2) {
41
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
42
+ if (res.length > 2) {
43
+ const lastSlashIndex = res.lastIndexOf("/");
44
+ if (lastSlashIndex === -1) {
45
+ res = "";
46
+ lastSegmentLength = 0;
47
+ } else {
48
+ res = res.slice(0, lastSlashIndex);
49
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
50
+ }
51
+ lastSlash = index;
52
+ dots = 0;
53
+ continue;
54
+ } else if (res.length > 0) {
55
+ res = "";
56
+ lastSegmentLength = 0;
57
+ lastSlash = index;
58
+ dots = 0;
59
+ continue;
60
+ }
61
+ }
62
+ if (allowAboveRoot) {
63
+ res += res.length > 0 ? "/.." : "..";
64
+ lastSegmentLength = 2;
65
+ }
66
+ } else {
67
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
68
+ else res = path.slice(lastSlash + 1, index);
69
+ lastSegmentLength = index - lastSlash - 1;
70
+ }
71
+ lastSlash = index;
72
+ dots = 0;
73
+ } else if (char === "." && dots !== -1) ++dots;
74
+ else dots = -1;
75
+ }
76
+ return res;
77
+ }
78
+ const isAbsolute = function(p) {
79
+ return _IS_ABSOLUTE_RE.test(p);
80
+ };
81
+ const relative = function(from, to) {
82
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
83
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
84
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
85
+ const _fromCopy = [..._from];
86
+ for (const segment of _fromCopy) {
87
+ if (_to[0] !== segment) break;
88
+ _from.shift();
89
+ _to.shift();
90
+ }
91
+ return [..._from.map(() => ".."), ..._to].join("/");
92
+ };
93
+ const dirname = function(p) {
94
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
95
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
96
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
97
+ };
98
+ //#endregion
99
+ //#region ../internal/src/inspect.ts
100
+ function relativeDefinitionFile(projectRoot, file) {
101
+ return relative(projectRoot, file).replaceAll("\\", "/");
102
+ }
103
+ const redactedInspectionValue = "[redacted]";
104
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
105
+ const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
106
+ const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
107
+ const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
108
+ const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
109
+ const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
110
+ /**
111
+ * Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
112
+ * `name=value` pairs with a secret name are replaced with `[redacted]`.
113
+ */
114
+ function redactInspectionText(value) {
115
+ return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
116
+ }
117
+ //#endregion
118
+ export { resolve as a, relative as i, relativeDefinitionFile as n, dirname as r, redactInspectionText as t };
@@ -0,0 +1,22 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region ../internal/src/invariant.ts
3
+ const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
4
+ docsBase: "https://vitehub.dev/docs/development/diagnostics",
5
+ codes: { INTERNAL_INVARIANT_FAILED: {
6
+ why: ({ what }) => `ViteHub reached a state that it does not expect: ${what}`,
7
+ fix: "This is a ViteHub bug. Open an issue at https://github.com/vite-hub/vitehub/issues with this error message and its stack trace."
8
+ } }
9
+ });
10
+ /**
11
+ * The error for a state that only a ViteHub bug can reach, such as an impossible branch. `what` says which rule broke.
12
+ * Use a code from the package catalog when a developer can cause the error or fix it.
13
+ */
14
+ function invariantError(what) {
15
+ return invariantDiagnostics.INTERNAL_INVARIANT_FAILED({ what });
16
+ }
17
+ /** Throws `INTERNAL_INVARIANT_FAILED` when `condition` is falsy. */
18
+ function invariant(condition, what) {
19
+ if (!condition) throw invariantError(what);
20
+ }
21
+ //#endregion
22
+ export { invariantError as n, invariant as t };