@vite-hub/kv 0.0.3 → 0.1.0

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 (39) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +40 -7
  3. package/dist/cli-Cniq99iX.d.ts +85 -0
  4. package/dist/cli.d.ts +15 -0
  5. package/dist/cli.js +448 -0
  6. package/dist/cloudflare-env-C5rM7kUY.js +74 -0
  7. package/dist/{config-C1ofyzSt.js → config-DR6_5ZwI.js} +37 -17
  8. package/dist/continuations-DPyH_vr1.js +63 -0
  9. package/dist/create-storage-29gMzf41.js +442 -0
  10. package/dist/cursor-history-dqYDlsaD.js +148 -0
  11. package/dist/deno-kv-CSYGvRx4.js +120 -0
  12. package/dist/driver-D9fI27jl.d.ts +94 -0
  13. package/dist/error-diagnostics-D_cQeZTi.js +82 -0
  14. package/dist/errors-Dc2oiW-Y.js +38 -0
  15. package/dist/errors.d.ts +12 -7
  16. package/dist/errors.js +2 -20
  17. package/dist/fs-lite-CbLKxLut.js +90 -0
  18. package/dist/index.d.ts +5 -4
  19. package/dist/index.js +119 -49
  20. package/dist/object-B1NW521B.js +7 -0
  21. package/dist/operations-ByuDE12r.js +1442 -0
  22. package/dist/operations-pn8_eGob.js +432 -0
  23. package/dist/operations-tNUdj3G4.d.ts +212 -0
  24. package/dist/operations.d.ts +68 -0
  25. package/dist/operations.js +455 -0
  26. package/dist/results-p7nPCnaJ.js +6 -0
  27. package/dist/runtime/cloudflare-kv.d.ts +6 -0
  28. package/dist/runtime/cloudflare-kv.js +100 -0
  29. package/dist/runtime/upstash-driver.d.ts +5 -2
  30. package/dist/runtime/upstash-driver.js +111 -2
  31. package/dist/types-CMDvN0Wr.d.ts +81 -0
  32. package/dist/utils2-Dsb9P4_2.js +28 -0
  33. package/dist/virtual-module.d.ts +6 -0
  34. package/dist/virtual.d.ts +2 -6
  35. package/dist/vite.d.ts +30 -10
  36. package/dist/vite.js +4910 -213
  37. package/package.json +57 -15
  38. package/dist/deno-kv-JnitV_jG.js +0 -54
  39. package/dist/types-Dg4l318i.d.ts +0 -60
@@ -0,0 +1,63 @@
1
+ //#region src/runtime/continuations.ts
2
+ /** Owns process-local cursor retention. Taking a cursor transfers its resource to the caller. */
3
+ function createKVContinuations(options) {
4
+ const entries = /* @__PURE__ */ new Map();
5
+ const releases = /* @__PURE__ */ new Set();
6
+ const failures = [];
7
+ let bytes = 0;
8
+ let disposed = false;
9
+ function take(cursor) {
10
+ const entry = entries.get(cursor);
11
+ if (!entry) return void 0;
12
+ clearTimeout(entry.timeout);
13
+ entries.delete(cursor);
14
+ bytes -= entry.bytes;
15
+ return entry.value;
16
+ }
17
+ function release(value, surfaceFailure = false) {
18
+ const pending = Promise.resolve().then(() => options.release?.(value)).then(() => void 0).catch((error) => {
19
+ if (failures.length === 0) failures.push(error);
20
+ if (surfaceFailure) throw error;
21
+ }).finally(() => {
22
+ releases.delete(pending);
23
+ });
24
+ releases.add(pending);
25
+ return pending;
26
+ }
27
+ function evict(cursor) {
28
+ const value = take(cursor);
29
+ if (value !== void 0) release(value);
30
+ }
31
+ return {
32
+ take,
33
+ async retain(value, size = 0) {
34
+ if (disposed) {
35
+ await release(value, true);
36
+ throw options.expired();
37
+ }
38
+ while (entries.size >= 32 || bytes + size > (options.maximumBytes ?? Number.POSITIVE_INFINITY)) {
39
+ const oldest = entries.keys().next().value;
40
+ if (!oldest) break;
41
+ evict(oldest);
42
+ }
43
+ const cursor = globalThis.crypto.randomUUID();
44
+ const timeout = setTimeout(() => evict(cursor), 9e5);
45
+ timeout.unref?.();
46
+ entries.set(cursor, {
47
+ value,
48
+ bytes: size,
49
+ timeout
50
+ });
51
+ bytes += size;
52
+ return cursor;
53
+ },
54
+ async dispose() {
55
+ disposed = true;
56
+ for (const cursor of entries.keys()) evict(cursor);
57
+ await Promise.all(releases);
58
+ if (failures.length > 0) throw new AggregateError(failures.splice(0), "Failed to release KV listing continuations.");
59
+ }
60
+ };
61
+ }
62
+ //#endregion
63
+ export { createKVContinuations as t };
@@ -0,0 +1,442 @@
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
3
+ 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
+ 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
+ const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
6
+ function jsonParseTransform(key, value) {
7
+ if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
8
+ warnKeyDropped(key);
9
+ return;
10
+ }
11
+ return value;
12
+ }
13
+ function warnKeyDropped(key) {
14
+ console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
15
+ }
16
+ function destr(value, options = {}) {
17
+ if (typeof value !== "string") return value;
18
+ if (value[0] === "\"" && value[value.length - 1] === "\"" && value.indexOf("\\") === -1) return value.slice(1, -1);
19
+ const _value = value.trim();
20
+ if (_value.length <= 9) switch (_value.toLowerCase()) {
21
+ case "true": return true;
22
+ case "false": return false;
23
+ case "undefined": return;
24
+ case "null": return null;
25
+ case "nan": return NaN;
26
+ case "infinity": return Number.POSITIVE_INFINITY;
27
+ case "-infinity": return Number.NEGATIVE_INFINITY;
28
+ }
29
+ if (!JsonSigRx.test(value)) {
30
+ if (options.strict) throw new SyntaxError("[destr] Invalid JSON");
31
+ return value;
32
+ }
33
+ try {
34
+ if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
35
+ if (options.strict) throw new Error("[destr] Possible prototype pollution");
36
+ return JSON.parse(value, jsonParseTransform);
37
+ }
38
+ return JSON.parse(value);
39
+ } catch (error) {
40
+ if (options.strict) throw error;
41
+ return value;
42
+ }
43
+ }
44
+ //#endregion
45
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/drivers/memory.mjs
46
+ const DRIVER_NAME = "memory";
47
+ const driver = () => {
48
+ const data = /* @__PURE__ */ new Map();
49
+ const timers = /* @__PURE__ */ new Map();
50
+ return {
51
+ name: DRIVER_NAME,
52
+ getInstance: () => data,
53
+ hasItem(key) {
54
+ return data.has(key);
55
+ },
56
+ getItem(key) {
57
+ return data.get(key) ?? null;
58
+ },
59
+ getItemRaw(key) {
60
+ return data.get(key) ?? null;
61
+ },
62
+ setItem(key, value, opts) {
63
+ _clearTimer(timers, key);
64
+ data.set(key, value);
65
+ _scheduleExpiry(data, timers, key, opts?.ttl);
66
+ },
67
+ setItemRaw(key, value, opts) {
68
+ _clearTimer(timers, key);
69
+ data.set(key, value);
70
+ _scheduleExpiry(data, timers, key, opts?.ttl);
71
+ },
72
+ removeItem(key) {
73
+ _clearTimer(timers, key);
74
+ data.delete(key);
75
+ },
76
+ getKeys() {
77
+ return [...data.keys()];
78
+ },
79
+ clear() {
80
+ for (const timer of timers.values()) clearTimeout(timer);
81
+ timers.clear();
82
+ data.clear();
83
+ },
84
+ dispose() {
85
+ for (const timer of timers.values()) clearTimeout(timer);
86
+ timers.clear();
87
+ data.clear();
88
+ }
89
+ };
90
+ };
91
+ function _clearTimer(timers, key) {
92
+ const existing = timers.get(key);
93
+ if (existing !== void 0) {
94
+ clearTimeout(existing);
95
+ timers.delete(key);
96
+ }
97
+ }
98
+ 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);
107
+ }
108
+ //#endregion
109
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/_chunks/_utils.mjs
110
+ function wrapToPromise(value) {
111
+ if (!value || typeof value.then !== "function") return Promise.resolve(value);
112
+ return value;
113
+ }
114
+ function asyncCall(function_, ...arguments_) {
115
+ try {
116
+ return wrapToPromise(function_(...arguments_));
117
+ } catch (error) {
118
+ return Promise.reject(error);
119
+ }
120
+ }
121
+ function isPrimitive(value) {
122
+ const type = typeof value;
123
+ return value === null || type !== "object" && type !== "function";
124
+ }
125
+ function isPureObject(value) {
126
+ const proto = Object.getPrototypeOf(value);
127
+ return !proto || proto.isPrototypeOf(Object);
128
+ }
129
+ function stringify(value) {
130
+ if (isPrimitive(value)) return String(value);
131
+ if (isPureObject(value) || Array.isArray(value)) return JSON.stringify(value);
132
+ if (typeof value.toJSON === "function") return stringify(value.toJSON());
133
+ throw new Error("[unstorage] Cannot stringify value!");
134
+ }
135
+ const BASE64_PREFIX = "base64:";
136
+ function serializeRaw(value) {
137
+ if (typeof value === "string") return value;
138
+ return BASE64_PREFIX + base64Encode(value);
139
+ }
140
+ function deserializeRaw(value) {
141
+ if (typeof value !== "string") return value;
142
+ if (!value.startsWith("base64:")) return value;
143
+ return base64Decode(value.slice(7));
144
+ }
145
+ function base64Decode(input) {
146
+ if (typeof Buffer !== "undefined") return Buffer.from(input, "base64");
147
+ return Uint8Array.from(globalThis.atob(input), (c) => c.codePointAt(0));
148
+ }
149
+ function base64Encode(input) {
150
+ if (typeof Buffer !== "undefined") return Buffer.from(input).toString("base64");
151
+ return globalThis.btoa(String.fromCodePoint(...input));
152
+ }
153
+ //#endregion
154
+ //#region ../../node_modules/.pnpm/unstorage@2.0.0-alpha.10/node_modules/unstorage/dist/index.mjs
155
+ function createStorage(options = {}) {
156
+ const context = {
157
+ mounts: { "": options.driver || driver() },
158
+ mountpoints: [""],
159
+ watching: false,
160
+ watchListeners: [],
161
+ unwatch: {}
162
+ };
163
+ const getMount = (key) => {
164
+ for (const base of context.mountpoints) if (key.startsWith(base)) return {
165
+ base,
166
+ relativeKey: key.slice(base.length),
167
+ driver: context.mounts[base]
168
+ };
169
+ return {
170
+ base: "",
171
+ relativeKey: key,
172
+ driver: context.mounts[""]
173
+ };
174
+ };
175
+ const getMounts = (base, includeParent) => {
176
+ return context.mountpoints.filter((mountpoint) => mountpoint.startsWith(base) || includeParent && base.startsWith(mountpoint)).map((mountpoint) => ({
177
+ relativeBase: base.length > mountpoint.length ? base.slice(mountpoint.length) : void 0,
178
+ mountpoint,
179
+ driver: context.mounts[mountpoint]
180
+ }));
181
+ };
182
+ const onChange = (event, key) => {
183
+ if (!context.watching) return;
184
+ key = normalizeKey(key);
185
+ for (const listener of context.watchListeners) listener(event, key);
186
+ };
187
+ const startWatch = async () => {
188
+ if (context.watching) return;
189
+ context.watching = true;
190
+ for (const mountpoint in context.mounts) context.unwatch[mountpoint] = await watch(context.mounts[mountpoint], onChange, mountpoint);
191
+ };
192
+ const stopWatch = async () => {
193
+ if (!context.watching) return;
194
+ for (const mountpoint in context.unwatch) await context.unwatch[mountpoint]();
195
+ context.unwatch = {};
196
+ context.watching = false;
197
+ };
198
+ const runBatch = (items, commonOptions, cb) => {
199
+ const batches = /* @__PURE__ */ new Map();
200
+ const getBatch = (mount) => {
201
+ let batch = batches.get(mount.base);
202
+ if (!batch) {
203
+ batch = {
204
+ driver: mount.driver,
205
+ base: mount.base,
206
+ items: []
207
+ };
208
+ batches.set(mount.base, batch);
209
+ }
210
+ return batch;
211
+ };
212
+ for (const item of items) {
213
+ const isStringItem = typeof item === "string";
214
+ const key = normalizeKey(isStringItem ? item : item.key);
215
+ const value = isStringItem ? void 0 : item.value;
216
+ const options = isStringItem || !item.options ? commonOptions : {
217
+ ...commonOptions,
218
+ ...item.options
219
+ };
220
+ const mount = getMount(key);
221
+ getBatch(mount).items.push({
222
+ key,
223
+ value,
224
+ relativeKey: mount.relativeKey,
225
+ options
226
+ });
227
+ }
228
+ return Promise.all([...batches.values()].map((batch) => cb(batch))).then((r) => r.flat());
229
+ };
230
+ const storage = {
231
+ hasItem(key, opts = {}) {
232
+ key = normalizeKey(key);
233
+ const { relativeKey, driver } = getMount(key);
234
+ return asyncCall(driver.hasItem, relativeKey, opts);
235
+ },
236
+ getItem(key, opts = {}) {
237
+ key = normalizeKey(key);
238
+ const { relativeKey, driver } = getMount(key);
239
+ return asyncCall(driver.getItem, relativeKey, opts).then((value) => destr(value));
240
+ },
241
+ getItems(items, commonOptions = {}) {
242
+ return runBatch(items, commonOptions, (batch) => {
243
+ if (batch.driver.getItems) return asyncCall(batch.driver.getItems, batch.items.map((item) => ({
244
+ key: item.relativeKey,
245
+ 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
+ }));
256
+ });
257
+ },
258
+ getItemRaw(key, opts = {}) {
259
+ key = normalizeKey(key);
260
+ const { relativeKey, driver } = getMount(key);
261
+ if (driver.getItemRaw) return asyncCall(driver.getItemRaw, relativeKey, opts);
262
+ return asyncCall(driver.getItem, relativeKey, opts).then((value) => deserializeRaw(value));
263
+ },
264
+ async setItem(key, value, opts = {}) {
265
+ if (value === void 0) return storage.removeItem(key);
266
+ key = normalizeKey(key);
267
+ const { relativeKey, driver } = getMount(key);
268
+ if (!driver.setItem) return;
269
+ await asyncCall(driver.setItem, relativeKey, stringify(value), opts);
270
+ if (!driver.watch) onChange("update", key);
271
+ },
272
+ async setItems(items, commonOptions) {
273
+ await runBatch(items, commonOptions, async (batch) => {
274
+ if (batch.driver.setItems) return asyncCall(batch.driver.setItems, batch.items.map((item) => ({
275
+ key: item.relativeKey,
276
+ value: stringify(item.value),
277
+ options: item.options
278
+ })), commonOptions);
279
+ if (!batch.driver.setItem) return;
280
+ await Promise.all(batch.items.map((item) => {
281
+ return asyncCall(batch.driver.setItem, item.relativeKey, stringify(item.value), item.options);
282
+ }));
283
+ });
284
+ },
285
+ async setItemRaw(key, value, opts = {}) {
286
+ if (value === void 0) return storage.removeItem(key, opts);
287
+ key = normalizeKey(key);
288
+ const { relativeKey, driver } = getMount(key);
289
+ if (driver.setItemRaw) await asyncCall(driver.setItemRaw, relativeKey, value, opts);
290
+ else if (driver.setItem) await asyncCall(driver.setItem, relativeKey, serializeRaw(value), opts);
291
+ else return;
292
+ if (!driver.watch) onChange("update", key);
293
+ },
294
+ async removeItem(key, opts = {}) {
295
+ if (typeof opts === "boolean") opts = { removeMeta: opts };
296
+ key = normalizeKey(key);
297
+ const { relativeKey, driver } = getMount(key);
298
+ if (!driver.removeItem) return;
299
+ await asyncCall(driver.removeItem, relativeKey, opts);
300
+ if (opts.removeMeta || opts.removeMata) await asyncCall(driver.removeItem, relativeKey + "$", opts);
301
+ if (!driver.watch) onChange("remove", key);
302
+ },
303
+ async getMeta(key, opts = {}) {
304
+ if (typeof opts === "boolean") opts = { nativeOnly: opts };
305
+ key = normalizeKey(key);
306
+ const { relativeKey, driver } = getMount(key);
307
+ const meta = Object.create(null);
308
+ if (driver.getMeta) Object.assign(meta, await asyncCall(driver.getMeta, relativeKey, opts));
309
+ if (!opts.nativeOnly) {
310
+ const value = await asyncCall(driver.getItem, relativeKey + "$", opts).then((value_) => destr(value_));
311
+ if (value && typeof value === "object") {
312
+ if (typeof value.atime === "string") value.atime = new Date(value.atime);
313
+ if (typeof value.mtime === "string") value.mtime = new Date(value.mtime);
314
+ Object.assign(meta, value);
315
+ }
316
+ }
317
+ return meta;
318
+ },
319
+ setMeta(key, value, opts = {}) {
320
+ return this.setItem(key + "$", value, opts);
321
+ },
322
+ removeMeta(key, opts = {}) {
323
+ return this.removeItem(key + "$", opts);
324
+ },
325
+ async getKeys(base, opts = {}) {
326
+ base = normalizeBaseKey(base);
327
+ const mounts = getMounts(base, true);
328
+ let maskedMounts = [];
329
+ const allKeys = [];
330
+ let allMountsSupportMaxDepth = true;
331
+ for (const mount of mounts) {
332
+ if (!mount.driver.flags?.maxDepth) allMountsSupportMaxDepth = false;
333
+ const rawKeys = await asyncCall(mount.driver.getKeys, mount.relativeBase, opts);
334
+ for (const key of rawKeys) {
335
+ const fullKey = mount.mountpoint + normalizeKey(key);
336
+ if (!maskedMounts.some((p) => fullKey.startsWith(p))) allKeys.push(fullKey);
337
+ }
338
+ maskedMounts = [mount.mountpoint, ...maskedMounts.filter((p) => !p.startsWith(mount.mountpoint))];
339
+ }
340
+ const shouldFilterByDepth = opts.maxDepth !== void 0 && !allMountsSupportMaxDepth;
341
+ return allKeys.filter((key) => (!shouldFilterByDepth || filterKeyByDepth(key, opts.maxDepth)) && filterKeyByBase(key, base));
342
+ },
343
+ async clear(base, opts = {}) {
344
+ base = normalizeBaseKey(base);
345
+ await Promise.all(getMounts(base, false).map(async (m) => {
346
+ if (m.driver.clear) return asyncCall(m.driver.clear, m.relativeBase, opts);
347
+ if (m.driver.removeItem) {
348
+ const keys = await m.driver.getKeys(m.relativeBase || "", opts);
349
+ return Promise.all(keys.map((key) => m.driver.removeItem(key, opts)));
350
+ }
351
+ }));
352
+ },
353
+ async dispose() {
354
+ await Promise.all(Object.values(context.mounts).map((driver) => dispose(driver)));
355
+ },
356
+ async watch(callback) {
357
+ await startWatch();
358
+ context.watchListeners.push(callback);
359
+ return async () => {
360
+ context.watchListeners = context.watchListeners.filter((listener) => listener !== callback);
361
+ if (context.watchListeners.length === 0) await stopWatch();
362
+ };
363
+ },
364
+ async unwatch() {
365
+ context.watchListeners = [];
366
+ await stopWatch();
367
+ },
368
+ mount(base, driver) {
369
+ base = normalizeBaseKey(base);
370
+ if (base && context.mounts[base]) throw new Error(`already mounted at ${base}`);
371
+ if (base) {
372
+ context.mountpoints.push(base);
373
+ context.mountpoints.sort((a, b) => b.length - a.length);
374
+ }
375
+ context.mounts[base] = driver;
376
+ if (context.watching) Promise.resolve(watch(driver, onChange, base)).then((unwatcher) => {
377
+ context.unwatch[base] = unwatcher;
378
+ }).catch(console.error);
379
+ return storage;
380
+ },
381
+ async unmount(base, _dispose = true) {
382
+ base = normalizeBaseKey(base);
383
+ if (!base || !context.mounts[base]) return;
384
+ if (context.watching && base in context.unwatch) {
385
+ context.unwatch[base]?.();
386
+ delete context.unwatch[base];
387
+ }
388
+ if (_dispose) await dispose(context.mounts[base]);
389
+ context.mountpoints = context.mountpoints.filter((key) => key !== base);
390
+ delete context.mounts[base];
391
+ },
392
+ getMount(key = "") {
393
+ key = normalizeKey(key) + ":";
394
+ const m = getMount(key);
395
+ return {
396
+ driver: m.driver,
397
+ base: m.base
398
+ };
399
+ },
400
+ getMounts(base = "", opts = {}) {
401
+ base = normalizeKey(base);
402
+ return getMounts(base, opts.parents).map((m) => ({
403
+ driver: m.driver,
404
+ base: m.mountpoint
405
+ }));
406
+ },
407
+ keys: (base, opts = {}) => storage.getKeys(base, opts),
408
+ get: (key, opts = {}) => storage.getItem(key, opts),
409
+ set: (key, value, opts = {}) => storage.setItem(key, value, opts),
410
+ has: (key, opts = {}) => storage.hasItem(key, opts),
411
+ del: (key, opts = {}) => storage.removeItem(key, opts),
412
+ remove: (key, opts = {}) => storage.removeItem(key, opts)
413
+ };
414
+ return storage;
415
+ }
416
+ function watch(driver, onChange, base) {
417
+ return driver.watch ? driver.watch((event, key) => onChange(event, base + key)) : () => {};
418
+ }
419
+ async function dispose(driver) {
420
+ if (typeof driver.dispose === "function") await asyncCall(driver.dispose);
421
+ }
422
+ //#endregion
423
+ //#region src/runtime/list-prefix.ts
424
+ function normalizeKVListPrefix(prefix = "") {
425
+ const normalized = normalizeKey(prefix);
426
+ const path = prefix.split("?")[0] ?? "";
427
+ return normalized && /[:/\\]$/.test(path) ? `${normalized}:` : normalized;
428
+ }
429
+ //#endregion
430
+ //#region src/runtime/create-storage.ts
431
+ /** Gives single-store KV prefixes the same meaning for clear() and getKeys(). */
432
+ function createKVStorage(driver) {
433
+ const storage = createStorage({ driver });
434
+ 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);
438
+ };
439
+ return storage;
440
+ }
441
+ //#endregion
442
+ export { normalizeKVListPrefix as n, createKVStorage as t };
@@ -0,0 +1,148 @@
1
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
2
+ //#region src/runtime/cursor-history.ts
3
+ const MAX_CURSOR_HISTORIES = 1024;
4
+ const MAX_CURSORS_PER_HISTORY = 1024;
5
+ const MAX_CURSOR_LENGTH = 8192;
6
+ const MAX_CONTINUATION_LENGTH = 131072;
7
+ function continuationTag(value) {
8
+ const hashes = [
9
+ 2166136261,
10
+ 2246822519,
11
+ 3266489917,
12
+ 668265263
13
+ ];
14
+ for (let index = 0; index < value.length; index++) {
15
+ const code = value.charCodeAt(index);
16
+ for (let hashIndex = 0; hashIndex < hashes.length; hashIndex++) hashes[hashIndex] = Math.imul(hashes[hashIndex] ^ code, 16777619 + hashIndex * 2);
17
+ }
18
+ return hashes.map((hash) => (hash >>> 0).toString(16).padStart(8, "0")).join("");
19
+ }
20
+ function encodeContinuation(providerCursor, history) {
21
+ const nonce = globalThis.crypto.randomUUID();
22
+ const historyTag = continuationTag([...history].join("\0"));
23
+ const payload = encodeURIComponent(JSON.stringify({
24
+ format: "vitehub-continuation",
25
+ providerCursor,
26
+ historyCount: history.size,
27
+ historyTag
28
+ }));
29
+ 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
+ return token;
32
+ }
33
+ const continuations = /* @__PURE__ */ new Map();
34
+ const continuationOwners = /* @__PURE__ */ new Map();
35
+ const consumedContinuations = /* @__PURE__ */ new Map();
36
+ const consumedOwners = /* @__PURE__ */ new Map();
37
+ const invalidatedContinuations = /* @__PURE__ */ new Set();
38
+ function rememberInvalidated(cursor) {
39
+ invalidatedContinuations.add(cursor);
40
+ while (invalidatedContinuations.size > MAX_CURSOR_HISTORIES) {
41
+ const oldest = invalidatedContinuations.values().next().value;
42
+ if (oldest === void 0) break;
43
+ invalidatedContinuations.delete(oldest);
44
+ }
45
+ }
46
+ /** Keeps continuation history tied to an opaque, traversal-owned token. */
47
+ function createCursorHistory(namespace = "default") {
48
+ const ownedContinuations = /* @__PURE__ */ new Set();
49
+ const ownedConsumedContinuations = /* @__PURE__ */ new Set();
50
+ let epoch = 0;
51
+ function take(cursor, requestedNamespace = namespace) {
52
+ const continuation = continuations.get(cursor);
53
+ if (continuation && continuation.namespace !== requestedNamespace) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "foreign" });
54
+ if (!continuation) {
55
+ if (consumedContinuations.has(cursor)) throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "in-use" });
56
+ 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
63
+ };
64
+ }
65
+ continuations.delete(cursor);
66
+ continuationOwners.get(cursor)?.delete(cursor);
67
+ continuationOwners.delete(cursor);
68
+ continuation.epoch = epoch;
69
+ consumedContinuations.set(cursor, continuation);
70
+ ownedConsumedContinuations.add(cursor);
71
+ consumedOwners.set(cursor, ownedConsumedContinuations);
72
+ while (consumedContinuations.size > MAX_CURSOR_HISTORIES) {
73
+ const oldest = consumedContinuations.keys().next().value;
74
+ if (oldest === void 0) break;
75
+ consumedContinuations.delete(oldest);
76
+ consumedOwners.get(oldest)?.delete(oldest);
77
+ consumedOwners.delete(oldest);
78
+ rememberInvalidated(oldest);
79
+ }
80
+ return continuation;
81
+ }
82
+ function store(providerCursor, history, requestedNamespace = namespace) {
83
+ const token = encodeContinuation(providerCursor, history);
84
+ continuations.set(token, {
85
+ providerCursor,
86
+ history,
87
+ epoch,
88
+ namespace: requestedNamespace
89
+ });
90
+ ownedContinuations.add(token);
91
+ continuationOwners.set(token, ownedContinuations);
92
+ while (continuations.size > MAX_CURSOR_HISTORIES) {
93
+ const oldest = continuations.keys().next().value;
94
+ if (oldest === void 0) break;
95
+ continuations.delete(oldest);
96
+ continuationOwners.get(oldest)?.delete(oldest);
97
+ continuationOwners.delete(oldest);
98
+ rememberInvalidated(oldest);
99
+ }
100
+ return token;
101
+ }
102
+ function restore(cursor, continuation) {
103
+ if (continuation.epoch !== epoch || consumedContinuations.get(cursor) !== continuation) return;
104
+ continuations.set(cursor, continuation);
105
+ ownedContinuations.add(cursor);
106
+ continuationOwners.set(cursor, ownedContinuations);
107
+ consumedContinuations.delete(cursor);
108
+ consumedOwners.delete(cursor);
109
+ ownedConsumedContinuations.delete(cursor);
110
+ }
111
+ function complete(cursor) {
112
+ if (cursor && ownedConsumedContinuations.has(cursor)) {
113
+ consumedContinuations.delete(cursor);
114
+ consumedOwners.delete(cursor);
115
+ ownedConsumedContinuations.delete(cursor);
116
+ }
117
+ }
118
+ function clear() {
119
+ epoch++;
120
+ for (const token of ownedContinuations) {
121
+ continuations.delete(token);
122
+ continuationOwners.delete(token);
123
+ rememberInvalidated(token);
124
+ }
125
+ ownedContinuations.clear();
126
+ for (const token of ownedConsumedContinuations) {
127
+ consumedContinuations.delete(token);
128
+ consumedOwners.delete(token);
129
+ rememberInvalidated(token);
130
+ }
131
+ ownedConsumedContinuations.clear();
132
+ }
133
+ return {
134
+ take,
135
+ store,
136
+ restore,
137
+ complete,
138
+ clear
139
+ };
140
+ }
141
+ /** Records a provider cursor, refusing to weaken repeat detection at the bound. */
142
+ function recordCursor(history, cursor) {
143
+ if (cursor.length > MAX_CURSOR_LENGTH || history.size >= MAX_CURSORS_PER_HISTORY) return false;
144
+ history.add(cursor);
145
+ return true;
146
+ }
147
+ //#endregion
148
+ export { recordCursor as n, createCursorHistory as t };