@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
@@ -1,5 +1,7 @@
1
- import { a as normalizeKey, i as normalizeBaseKey, n as filterKeyByDepth, r as joinKeys, t as filterKeyByBase } from "./utils2-Dsb9P4_2.js";
2
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/_chunks/libs/destr.mjs
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
+ import { a as normalizeBaseKey, i as joinKeys, n as filterKeyByDepth, o as normalizeKey, r as hasDotSegment, t as filterKeyByBase } from "./utils2-FozcTsmb.js";
3
+ import { r as mapWithLimit } from "./batch--v0ri69O.js";
4
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/libs/destr.mjs
3
5
  const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
4
6
  const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
5
7
  const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
@@ -42,7 +44,7 @@ function destr(value, options = {}) {
42
44
  }
43
45
  }
44
46
  //#endregion
45
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/drivers/memory.mjs
47
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/drivers/memory.mjs
46
48
  const DRIVER_NAME = "memory";
47
49
  const driver = () => {
48
50
  const data = /* @__PURE__ */ new Map();
@@ -88,6 +90,7 @@ const driver = () => {
88
90
  }
89
91
  };
90
92
  };
93
+ const MAX_TIMER_DELAY = 2 ** 31 - 1;
91
94
  function _clearTimer(timers, key) {
92
95
  const existing = timers.get(key);
93
96
  if (existing !== void 0) {
@@ -96,17 +99,26 @@ function _clearTimer(timers, key) {
96
99
  }
97
100
  }
98
101
  function _scheduleExpiry(data, timers, key, ttl) {
99
- if (!ttl) return;
100
- const ttlMs = ttl * 1e3;
101
- const timer = setTimeout(() => {
102
- data.delete(key);
103
- timers.delete(key);
104
- }, ttlMs);
105
- if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
106
- timers.set(key, timer);
102
+ if (!ttl || !Number.isFinite(ttl)) return;
103
+ let remaining = ttl * 1e3;
104
+ const schedule = () => {
105
+ const delay = Math.min(remaining, MAX_TIMER_DELAY);
106
+ remaining -= delay;
107
+ const timer = setTimeout(() => {
108
+ if (remaining > 0) {
109
+ schedule();
110
+ return;
111
+ }
112
+ data.delete(key);
113
+ timers.delete(key);
114
+ }, delay);
115
+ if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
116
+ timers.set(key, timer);
117
+ };
118
+ schedule();
107
119
  }
108
120
  //#endregion
109
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/_chunks/_utils.mjs
121
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/_utils.mjs
110
122
  function wrapToPromise(value) {
111
123
  if (!value || typeof value.then !== "function") return Promise.resolve(value);
112
124
  return value;
@@ -126,6 +138,9 @@ function isPureObject(value) {
126
138
  const proto = Object.getPrototypeOf(value);
127
139
  return !proto || proto.isPrototypeOf(Object);
128
140
  }
141
+ function isPlainValue(value) {
142
+ return isPrimitive(value) || isPureObject(value) || Array.isArray(value);
143
+ }
129
144
  function stringify(value) {
130
145
  if (isPrimitive(value)) return String(value);
131
146
  if (isPureObject(value) || Array.isArray(value)) return JSON.stringify(value);
@@ -150,8 +165,88 @@ function base64Encode(input) {
150
165
  if (typeof Buffer !== "undefined") return Buffer.from(input).toString("base64");
151
166
  return globalThis.btoa(String.fromCodePoint(...input));
152
167
  }
168
+ async function toBytes(value) {
169
+ if (typeof value === "string") return new TextEncoder().encode(value);
170
+ if (ArrayBuffer.isView(value)) return value.constructor === Uint8Array ? value : new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
171
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
172
+ if (typeof value?.arrayBuffer === "function") return new Uint8Array(await value.arrayBuffer());
173
+ if (typeof value?.getReader === "function" || typeof value?.[Symbol.asyncIterator] === "function") return concatBytes(await readChunks(value));
174
+ if (isPlainValue(value)) return new TextEncoder().encode(stringify(value));
175
+ throw new TypeError(`[unstorage] Cannot convert \`${typeName(value)}\` to bytes.`);
176
+ }
177
+ async function toBlob(value) {
178
+ if (value instanceof Blob) return value;
179
+ return new Blob([await toBytes(value)]);
180
+ }
181
+ async function toStream(value) {
182
+ if (value instanceof ReadableStream) return value;
183
+ if (value instanceof Blob) return value.stream();
184
+ const bytes = await toBytes(value);
185
+ return new ReadableStream({ start(controller) {
186
+ controller.enqueue(bytes);
187
+ controller.close();
188
+ } });
189
+ }
190
+ async function readChunks(value) {
191
+ const chunks = [];
192
+ if (typeof value.getReader === "function") {
193
+ const reader = value.getReader();
194
+ try {
195
+ while (true) {
196
+ const { done, value: chunk } = await reader.read();
197
+ if (done) break;
198
+ chunks.push(await chunkToBytes(chunk));
199
+ }
200
+ } finally {
201
+ reader.releaseLock();
202
+ }
203
+ } else for await (const chunk of value) chunks.push(await chunkToBytes(chunk));
204
+ return chunks;
205
+ }
206
+ function chunkToBytes(chunk) {
207
+ if (typeof chunk !== "string" && isPlainValue(chunk)) throw new TypeError(`[unstorage] Cannot convert \`${typeName(chunk)}\` to bytes.`);
208
+ return toBytes(chunk);
209
+ }
210
+ function concatBytes(chunks) {
211
+ if (chunks.length === 1) return chunks[0];
212
+ const bytes = new Uint8Array(chunks.reduce((size, chunk) => size + chunk.length, 0));
213
+ let offset = 0;
214
+ for (const chunk of chunks) {
215
+ bytes.set(chunk, offset);
216
+ offset += chunk.length;
217
+ }
218
+ return bytes;
219
+ }
220
+ function typeName(value) {
221
+ return value?.constructor?.name || typeof value;
222
+ }
153
223
  //#endregion
154
- //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/index.mjs
224
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/index.mjs
225
+ function isRawType$1(type) {
226
+ return type === "bytes" || type === "blob" || type === "stream";
227
+ }
228
+ function isRawValue(value) {
229
+ return typeof value === "string" ? value.startsWith(BASE64_PREFIX) : ArrayBuffer.isView(value) || value instanceof ArrayBuffer || value instanceof Blob || value instanceof ReadableStream;
230
+ }
231
+ async function toValueType(value, type) {
232
+ if (value === null || value === void 0) return null;
233
+ if (type !== void 0 && isRawValue(value)) value = new TextDecoder().decode(await toBytes(deserializeRaw(value)));
234
+ if (type === "text") return typeof value === "string" ? value : stringify(value);
235
+ return destr(value);
236
+ }
237
+ async function getTypedItem(driver, relativeKey, opts = {}) {
238
+ const type = opts.type;
239
+ if (isRawType$1(type)) {
240
+ const raw = driver.getItemRaw ? await asyncCall(driver.getItemRaw, relativeKey, opts) : deserializeRaw(await asyncCall(driver.getItem, relativeKey, opts));
241
+ if (raw === null || raw === void 0) return null;
242
+ switch (type) {
243
+ case "bytes": return await toBytes(raw);
244
+ case "blob": return await toBlob(raw);
245
+ case "stream": return await toStream(raw);
246
+ }
247
+ }
248
+ return toValueType(await asyncCall(driver.getItem, relativeKey, opts), type);
249
+ }
155
250
  function createStorage(options = {}) {
156
251
  const context = {
157
252
  mounts: { "": options.driver || driver() },
@@ -160,6 +255,16 @@ function createStorage(options = {}) {
160
255
  watchListeners: [],
161
256
  unwatch: {}
162
257
  };
258
+ const normalizeItemKey = (key) => {
259
+ const normalizedKey = normalizeKey(key);
260
+ if (!normalizedKey || hasDotSegment(normalizedKey)) throw new Error(`[unstorage] Invalid key: ${JSON.stringify(key)}`);
261
+ return normalizedKey;
262
+ };
263
+ const normalizeBase = (base) => {
264
+ const normalizedBase = normalizeBaseKey(base);
265
+ if (hasDotSegment(normalizedBase)) throw new Error(`[unstorage] Invalid base: ${JSON.stringify(base)}`);
266
+ return normalizedBase;
267
+ };
163
268
  const getMount = (key) => {
164
269
  for (const base of context.mountpoints) if (key.startsWith(base)) return {
165
270
  base,
@@ -211,7 +316,7 @@ function createStorage(options = {}) {
211
316
  };
212
317
  for (const item of items) {
213
318
  const isStringItem = typeof item === "string";
214
- const key = normalizeKey(isStringItem ? item : item.key);
319
+ const key = normalizeItemKey(isStringItem ? item : item.key);
215
320
  const value = isStringItem ? void 0 : item.value;
216
321
  const options = isStringItem || !item.options ? commonOptions : {
217
322
  ...commonOptions,
@@ -228,42 +333,52 @@ function createStorage(options = {}) {
228
333
  return Promise.all([...batches.values()].map((batch) => cb(batch))).then((r) => r.flat());
229
334
  };
230
335
  const storage = {
231
- hasItem(key, opts = {}) {
232
- key = normalizeKey(key);
336
+ async hasItem(key, opts = {}) {
337
+ key = normalizeItemKey(key);
233
338
  const { relativeKey, driver } = getMount(key);
234
339
  return asyncCall(driver.hasItem, relativeKey, opts);
235
340
  },
236
- getItem(key, opts = {}) {
237
- key = normalizeKey(key);
341
+ getItem: async (key, opts = {}) => {
342
+ key = normalizeItemKey(key);
238
343
  const { relativeKey, driver } = getMount(key);
239
- return asyncCall(driver.getItem, relativeKey, opts).then((value) => destr(value));
344
+ return getTypedItem(driver, relativeKey, opts);
240
345
  },
241
- getItems(items, commonOptions = {}) {
242
- return runBatch(items, commonOptions, (batch) => {
243
- if (batch.driver.getItems) return asyncCall(batch.driver.getItems, batch.items.map((item) => ({
346
+ async getItems(items, commonOptions = {}) {
347
+ return runBatch(items, commonOptions, async (batch) => {
348
+ if (!batch.driver.getItems) return Promise.all(batch.items.map(async (item) => ({
349
+ key: item.key,
350
+ value: await getTypedItem(batch.driver, item.relativeKey, item.options)
351
+ })));
352
+ const rawItems = batch.items.filter((item) => isRawType$1(item.options?.type));
353
+ const plainItems = rawItems.length === 0 ? batch.items : batch.items.filter((item) => !isRawType$1(item.options?.type));
354
+ const [plain, raw] = await Promise.all([plainItems.length === 0 ? [] : asyncCall(batch.driver.getItems, plainItems.map((item) => ({
244
355
  key: item.relativeKey,
245
356
  options: item.options
246
- })), commonOptions).then((r) => r.map((item) => ({
247
- key: joinKeys(batch.base, item.key),
248
- value: destr(item.value)
249
- })));
250
- return Promise.all(batch.items.map((item) => {
251
- return asyncCall(batch.driver.getItem, item.relativeKey, item.options).then((value) => ({
252
- key: item.key,
253
- value: destr(value)
254
- }));
255
- }));
357
+ })), commonOptions).then((r) => {
358
+ const types = r.length === plainItems.length ? void 0 : new Map(plainItems.map((item) => [item.relativeKey, item.options?.type]));
359
+ return Promise.all(r.map(async (item, index) => ({
360
+ key: joinKeys(batch.base, item.key),
361
+ value: await toValueType(item.value, types ? types.has(item.key) ? types.get(item.key) : commonOptions.type : plainItems[index].options?.type)
362
+ })));
363
+ }), Promise.all(rawItems.map(async (item) => ({
364
+ key: item.key,
365
+ value: await getTypedItem(batch.driver, item.relativeKey, item.options)
366
+ })))]);
367
+ if (rawItems.length === 0 || plain.length !== plainItems.length) return [...plain, ...raw];
368
+ let plainIndex = 0;
369
+ let rawIndex = 0;
370
+ return batch.items.map((item) => isRawType$1(item.options?.type) ? raw[rawIndex++] : plain[plainIndex++]);
256
371
  });
257
372
  },
258
- getItemRaw(key, opts = {}) {
259
- key = normalizeKey(key);
373
+ async getItemRaw(key, opts = {}) {
374
+ key = normalizeItemKey(key);
260
375
  const { relativeKey, driver } = getMount(key);
261
376
  if (driver.getItemRaw) return asyncCall(driver.getItemRaw, relativeKey, opts);
262
377
  return asyncCall(driver.getItem, relativeKey, opts).then((value) => deserializeRaw(value));
263
378
  },
264
379
  async setItem(key, value, opts = {}) {
265
380
  if (value === void 0) return storage.removeItem(key);
266
- key = normalizeKey(key);
381
+ key = normalizeItemKey(key);
267
382
  const { relativeKey, driver } = getMount(key);
268
383
  if (!driver.setItem) return;
269
384
  await asyncCall(driver.setItem, relativeKey, stringify(value), opts);
@@ -284,7 +399,7 @@ function createStorage(options = {}) {
284
399
  },
285
400
  async setItemRaw(key, value, opts = {}) {
286
401
  if (value === void 0) return storage.removeItem(key, opts);
287
- key = normalizeKey(key);
402
+ key = normalizeItemKey(key);
288
403
  const { relativeKey, driver } = getMount(key);
289
404
  if (driver.setItemRaw) await asyncCall(driver.setItemRaw, relativeKey, value, opts);
290
405
  else if (driver.setItem) await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts);
@@ -293,7 +408,7 @@ function createStorage(options = {}) {
293
408
  },
294
409
  async removeItem(key, opts = {}) {
295
410
  if (typeof opts === "boolean") opts = { removeMeta: opts };
296
- key = normalizeKey(key);
411
+ key = normalizeItemKey(key);
297
412
  const { relativeKey, driver } = getMount(key);
298
413
  if (!driver.removeItem) return;
299
414
  await asyncCall(driver.removeItem, relativeKey, opts);
@@ -302,7 +417,7 @@ function createStorage(options = {}) {
302
417
  },
303
418
  async getMeta(key, opts = {}) {
304
419
  if (typeof opts === "boolean") opts = { nativeOnly: opts };
305
- key = normalizeKey(key);
420
+ key = normalizeItemKey(key);
306
421
  const { relativeKey, driver } = getMount(key);
307
422
  const meta = Object.create(null);
308
423
  if (driver.getMeta) Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts));
@@ -316,14 +431,14 @@ function createStorage(options = {}) {
316
431
  }
317
432
  return meta;
318
433
  },
319
- setMeta(key, value, opts = {}) {
320
- return this.setItem(key + "$", value, opts);
434
+ async setMeta(key, value, opts = {}) {
435
+ return this.setItem(normalizeItemKey(key) + "$", value, opts);
321
436
  },
322
- removeMeta(key, opts = {}) {
323
- return this.removeItem(key + "$", opts);
437
+ async removeMeta(key, opts = {}) {
438
+ return this.removeItem(normalizeItemKey(key) + "$", opts);
324
439
  },
325
440
  async getKeys(base, opts = {}) {
326
- base = normalizeBaseKey(base);
441
+ base = normalizeBase(base);
327
442
  const mounts = getMounts(base, true);
328
443
  let maskedMounts = [];
329
444
  const allKeys = [];
@@ -341,7 +456,7 @@ function createStorage(options = {}) {
341
456
  return allKeys.filter((key) => (!shouldFilterByDepth || filterKeyByDepth(key, opts.maxDepth)) && filterKeyByBase(key, base));
342
457
  },
343
458
  async clear(base, opts = {}) {
344
- base = normalizeBaseKey(base);
459
+ base = normalizeBase(base);
345
460
  await Promise.all(getMounts(base, false).map(async (m) => {
346
461
  if (m.driver.clear) return asyncCall(m.driver.clear, m.relativeBase, opts);
347
462
  if (m.driver.removeItem) {
@@ -366,7 +481,7 @@ function createStorage(options = {}) {
366
481
  await stopWatch();
367
482
  },
368
483
  mount(base, driver) {
369
- base = normalizeBaseKey(base);
484
+ base = normalizeBase(base);
370
485
  if (base && context.mounts[base]) throw new Error(`already mounted at ${base}`);
371
486
  if (base) {
372
487
  context.mountpoints.push(base);
@@ -428,15 +543,56 @@ function normalizeKVListPrefix(prefix = "") {
428
543
  }
429
544
  //#endregion
430
545
  //#region src/runtime/create-storage.ts
431
- /** Gives single-store KV prefixes the same meaning for clear() and getKeys(). */
546
+ function isRawType(type) {
547
+ return type === "bytes" || type === "blob" || type === "stream";
548
+ }
549
+ const removeBatchSize = 100;
550
+ /** Gives single-store KV prefixes the same meaning for clear() and getKeys(), and adds the batch methods. */
432
551
  function createKVStorage(driver) {
433
552
  const storage = createStorage({ driver });
434
553
  const clear = storage.clear;
435
- storage.clear = async (base, options) => {
436
- if (!normalizeKey(base)) return clear(base, options);
437
- for (const key of await storage.getKeys(base, options)) await storage.removeItem(key, options);
554
+ storage.clear = async (base, options = {}) => {
555
+ const prefix = normalizeBaseKey(base);
556
+ if (!prefix) return clear(base, options);
557
+ if (driver.clear) return driver.clear(prefix, options);
558
+ const keys = await storage.getKeys(base, options);
559
+ for (let offset = 0; offset < keys.length; offset += removeBatchSize) await Promise.all(keys.slice(offset, offset + removeBatchSize).map((key) => storage.removeItem(key, options)));
438
560
  };
439
- return storage;
561
+ return Object.assign(storage, {
562
+ async getMany(keys, options = {}) {
563
+ if (!Array.isArray(keys)) throw kvErrorDiagnostics.KV_INVALID_BATCH({ operation: "getMany" });
564
+ if (keys.length === 0) return [];
565
+ if (!driver.getItems || isRawType(options.type)) return mapWithLimit(keys, (key) => storage.getItem(key, options));
566
+ const entries = await storage.getItems(keys, options);
567
+ if (entries.length !== keys.length) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "The batch read returned another number of values than keys." });
568
+ return entries.map((entry) => entry.value);
569
+ },
570
+ async setMany(entries, options) {
571
+ if (!Array.isArray(entries)) throw kvErrorDiagnostics.KV_INVALID_BATCH({ operation: "setMany" });
572
+ const latest = /* @__PURE__ */ new Map();
573
+ for (const { key, value } of entries) {
574
+ const normalized = normalizeKey(key);
575
+ latest.delete(normalized);
576
+ latest.set(normalized, value);
577
+ }
578
+ const writes = [];
579
+ const removals = [];
580
+ for (const [key, value] of latest) if (value === void 0) removals.push(key);
581
+ else writes.push({
582
+ key,
583
+ value
584
+ });
585
+ if (driver.validateBatch) {
586
+ await driver.validateBatch([], removals, options);
587
+ const validateBatch = driver.validateBatch;
588
+ await createStorage({ driver: {
589
+ ...driver,
590
+ setItems: (items) => validateBatch(items, removals, options)
591
+ } }).setItems(writes, options);
592
+ }
593
+ await Promise.all([writes.length === 0 ? void 0 : driver.setItems ? storage.setItems(writes, options) : mapWithLimit(writes, (entry) => storage.setItem(entry.key, entry.value, options)), mapWithLimit(removals, (key) => storage.removeItem(key, options))]);
594
+ }
595
+ });
440
596
  }
441
597
  //#endregion
442
598
  export { normalizeKVListPrefix as n, createKVStorage as t };
@@ -1,4 +1,5 @@
1
- import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
1
+ import { t as invariant } from "./invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
2
3
  //#region src/runtime/cursor-history.ts
3
4
  const MAX_CURSOR_HISTORIES = 1024;
4
5
  const MAX_CURSORS_PER_HISTORY = 1024;
@@ -27,9 +28,22 @@ function encodeContinuation(providerCursor, history) {
27
28
  historyTag
28
29
  }));
29
30
  const token = `vhc1:${nonce}:${payload}:${continuationTag(payload)}`;
30
- if (token.length > MAX_CONTINUATION_LENGTH) throw new Error("ViteHub continuation cursor exceeds the maximum size.");
31
+ invariant(token.length <= MAX_CONTINUATION_LENGTH, "a KV continuation cursor stays below 128 KiB, because provider cursors are far shorter");
31
32
  return token;
32
33
  }
34
+ function decodeContinuation(token) {
35
+ const match = /^vhc1:[0-9a-f-]{36}:([^:]+):([0-9a-f]{32})$/.exec(token);
36
+ if (!match || continuationTag(match[1]) !== match[2]) return void 0;
37
+ let payload;
38
+ try {
39
+ payload = JSON.parse(decodeURIComponent(match[1]));
40
+ } catch {
41
+ return;
42
+ }
43
+ if (!payload || typeof payload !== "object" || Reflect.get(payload, "format") !== "vitehub-continuation") return void 0;
44
+ const providerCursor = Reflect.get(payload, "providerCursor");
45
+ return typeof providerCursor === "string" && providerCursor.length > 0 && providerCursor.length <= MAX_CURSOR_LENGTH ? providerCursor : void 0;
46
+ }
33
47
  const continuations = /* @__PURE__ */ new Map();
34
48
  const continuationOwners = /* @__PURE__ */ new Map();
35
49
  const consumedContinuations = /* @__PURE__ */ new Map();
@@ -47,25 +61,30 @@ function rememberInvalidated(cursor) {
47
61
  function createCursorHistory(namespace = "default") {
48
62
  const ownedContinuations = /* @__PURE__ */ new Set();
49
63
  const ownedConsumedContinuations = /* @__PURE__ */ new Set();
50
- let epoch = 0;
51
64
  function take(cursor, requestedNamespace = namespace) {
52
- const continuation = continuations.get(cursor);
65
+ let continuation = continuations.get(cursor);
53
66
  if (continuation && continuation.namespace !== requestedNamespace) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "foreign" });
54
67
  if (!continuation) {
55
68
  if (consumedContinuations.has(cursor)) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "in-use" });
56
69
  if (invalidatedContinuations.has(cursor)) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
57
- if (cursor.length > MAX_CURSOR_LENGTH) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
58
- return {
59
- providerCursor: cursor,
60
- history: /* @__PURE__ */ new Set([cursor]),
61
- epoch,
62
- namespace
70
+ const providerCursor = cursor.length <= MAX_CONTINUATION_LENGTH ? decodeContinuation(cursor) : void 0;
71
+ if (providerCursor) continuation = {
72
+ providerCursor,
73
+ history: /* @__PURE__ */ new Set([providerCursor]),
74
+ namespace: requestedNamespace
63
75
  };
76
+ else {
77
+ if (cursor.length > MAX_CURSOR_LENGTH) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
78
+ return {
79
+ providerCursor: cursor,
80
+ history: /* @__PURE__ */ new Set([cursor]),
81
+ namespace
82
+ };
83
+ }
64
84
  }
65
85
  continuations.delete(cursor);
66
86
  continuationOwners.get(cursor)?.delete(cursor);
67
87
  continuationOwners.delete(cursor);
68
- continuation.epoch = epoch;
69
88
  consumedContinuations.set(cursor, continuation);
70
89
  ownedConsumedContinuations.add(cursor);
71
90
  consumedOwners.set(cursor, ownedConsumedContinuations);
@@ -84,7 +103,6 @@ function createCursorHistory(namespace = "default") {
84
103
  continuations.set(token, {
85
104
  providerCursor,
86
105
  history,
87
- epoch,
88
106
  namespace: requestedNamespace
89
107
  });
90
108
  ownedContinuations.add(token);
@@ -100,7 +118,7 @@ function createCursorHistory(namespace = "default") {
100
118
  return token;
101
119
  }
102
120
  function restore(cursor, continuation) {
103
- if (continuation.epoch !== epoch || consumedContinuations.get(cursor) !== continuation) return;
121
+ if (consumedContinuations.get(cursor) !== continuation) return;
104
122
  continuations.set(cursor, continuation);
105
123
  ownedContinuations.add(cursor);
106
124
  continuationOwners.set(cursor, ownedContinuations);
@@ -116,7 +134,6 @@ function createCursorHistory(namespace = "default") {
116
134
  }
117
135
  }
118
136
  function clear() {
119
- epoch++;
120
137
  for (const token of ownedContinuations) {
121
138
  continuations.delete(token);
122
139
  continuationOwners.delete(token);