@vite-hub/kv 0.7.0 → 0.8.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.
package/README.md CHANGED
@@ -19,6 +19,8 @@ Add `@upstash/redis` when you use the Upstash driver. The `redis` driver uses `i
19
19
 
20
20
  ## Minimal API
21
21
 
22
+ Install H3 2 for the route below: `pnpm add h3@^2.0.8`.
23
+
22
24
  ```ts
23
25
  // server/api/settings.put.ts
24
26
  import { kv } from "@vite-hub/kv"
package/dist/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import { D as listSeedFiles, E as askOnTerminal, N as writeCliFailure, O as parseCliPositiveInteger, j as readViteHubDevTargetOption, k as readCliOptionValue, n as callOperationFromCli } from "./operations-BKAO0rkO.js";
1
+ import { D as listSeedFiles, E as askOnTerminal, N as writeCliFailure, O as parseCliPositiveInteger, j as readViteHubDevTargetOption, k as readCliOptionValue, n as callOperationFromCli } from "./operations-DP8iWjQK.js";
2
2
  import { t as isRecord } from "./object-CAK6UYR5.js";
3
3
  import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
4
4
  import { t as kvDevMaximumListLimit } from "./results-emgN7uDS.js";
@@ -1,6 +1,6 @@
1
1
  import { t as getActiveCloudflareBinding } from "./cloudflare-env-Cpy3Bqdn.js";
2
2
  import { a as validateCloudflareKVBatch, i as installCloudflareKVLimits, r as assertCloudflareKVWrite, t as createCloudflareDriver } from "./cloudflare-kv-hMdZQZz1.js";
3
- import { t as createFsLiteKVDriver } from "./fs-lite-4ccAiYae.js";
3
+ import { t as createFsLiteKVDriver } from "./fs-lite-1n_Dvy4p.js";
4
4
  import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch-D-ib5_0P.js";
5
5
  // src/runtime/cloudflare-kv-local.ts
6
6
  function cloudflareExpirationSeconds(options) {
@@ -61,7 +61,7 @@ function cloudflareKVLocalBase(binding) {
61
61
  return `.vitehub/data/kv-cloudflare/${binding}`;
62
62
  }
63
63
  function readRemote(config, store) {
64
- const remote = Reflect.get(config, "remote");
64
+ const remote = config.remote;
65
65
  if (remote === void 0 || typeof remote === "boolean") return remote;
66
66
  throw kvErrorDiagnostics.KV_INVALID_REMOTE({ store });
67
67
  }
@@ -178,7 +178,7 @@ function assertKnownKVStoreKeys(store, driver, path) {
178
178
  "remote",
179
179
  ...driver ? kvDriverOptions[driver] : []
180
180
  ]);
181
- const key = Object.keys(store).find((name) => !known.has(name) && Reflect.get(store, name) !== void 0);
181
+ const key = Object.entries(store).find(([name, value]) => !known.has(name) && value !== void 0)?.[0];
182
182
  if (key === void 0) return;
183
183
  const drivers = Object.keys(kvDriverOptions).filter((name) => kvDriverOptions[name].includes(key));
184
184
  throw kvErrorDiagnostics.KV_UNKNOWN_STORE_OPTION({
@@ -208,7 +208,7 @@ function normalizeKVOptions(options, input = {}) {
208
208
  const hosting = normalizeHosting(input.hosting);
209
209
  const explicit = options;
210
210
  const hasOwnStores = options !== void 0 && Object.hasOwn(options, "stores");
211
- const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
211
+ const stores = hasOwnStores && "stores" in options ? options.stores : void 0;
212
212
  if (hasOwnStores && !isRecord(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
213
213
  if (hasStoresConfig(options, stores)) {
214
214
  const extra = Object.entries(options ?? {}).find(([key, value]) => key !== "stores" && value !== void 0)?.[0];
@@ -58,18 +58,18 @@ async function runStatement(value, database, sql, params) {
58
58
  }
59
59
  /**
60
60
  * A SQL client over the Drizzle database of the app: postgres.js, node-postgres, PGlite, libSQL, or a D1 binding. The
61
- * Database gives the dialect. It reads `$client` on each query, because a Postgres Database on Cloudflare has a client
62
- * per request.
61
+ * Database adapters can expose these properties only on read. Read `$client` on each query because a Postgres Database
62
+ * on Cloudflare has a client per request.
63
63
  */
64
64
  function kvSqlClientFromDatabase(db, database) {
65
- const client = () => Reflect.get(db, "$client");
65
+ const client = () => db.$client;
66
66
  const kind = sqlClient(client())?.kind;
67
67
  if (!kind) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
68
68
  database,
69
69
  problem: "unsupported"
70
70
  });
71
71
  return {
72
- dialect: typeof Reflect.get(db, postgresConnectionUrl) === "function" || kind === "postgres.js" || kind === "node-postgres-or-pglite" ? "postgresql" : "sqlite",
72
+ dialect: typeof db[postgresConnectionUrl] === "function" || kind === "postgres.js" || kind === "node-postgres-or-pglite" ? "postgresql" : "sqlite",
73
73
  ...kind === "d1" ? { maxParams: d1MaxParams } : {},
74
74
  query: (sql, params) => runStatement(client(), database, sql, params)
75
75
  };
@@ -87,7 +87,7 @@ function decodeCursor(cursor) {
87
87
  if (!cursor) return void 0;
88
88
  try {
89
89
  const value = JSON.parse(decodeURIComponent(cursor));
90
- const after = typeof value === "object" && value !== null ? Reflect.get(value, "after") : void 0;
90
+ const after = typeof value === "object" && value !== null && "after" in value ? value.after : void 0;
91
91
  if (typeof after === "string") return after;
92
92
  } catch {}
93
93
  throw kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "invalid" });
@@ -4,7 +4,7 @@ type KVRuntimeDriver = Driver & Record<string, unknown> & {
4
4
  validateBatch?: (items: Parameters<NonNullable<Driver["setItems"]>>[0], removals: string[], options?: TransactionOptions) => void | Promise<void>;
5
5
  /** Deletes the key when it holds the serialized `expected` value. Resolves `true` when this call deleted it. */
6
6
  deleteIfEqualsItem?: (key: string, expected: string) => Promise<boolean>;
7
- getAndDeleteItem?: <T = unknown>(key: string) => Promise<T | null>;
7
+ getAndDeleteItem?: (key: string) => Promise<string | null>;
8
8
  incrementItem?: (key: string, ttl: number) => Promise<number>;
9
9
  listKeys: (options: KVPageOptions) => Promise<KVListPage>;
10
10
  /** Writes the serialized value only when the key is missing. Resolves `true` when this call wrote it. */
@@ -249,9 +249,8 @@ function ttlMilliseconds(ttl) {
249
249
  return ms;
250
250
  }
251
251
  function setExpiry(options) {
252
- const ttl = options && typeof options === "object" ? Reflect.get(options, "ttl") : void 0;
253
- if (ttl === void 0 || ttl === null || ttl === 0) return;
254
- if (typeof ttl !== "number") throw kvErrorDiagnostics.KV_INVALID_TTL();
252
+ const ttl = options?.ttl;
253
+ if (ttl === void 0 || ttl === 0) return;
255
254
  return Date.now() + ttlMilliseconds(ttl);
256
255
  }
257
256
  async function createFsLiteKVDriver(options) {
@@ -285,51 +284,10 @@ async function createFsLiteKVDriver(options) {
285
284
  await rm(expiryPath(key), { force: true });
286
285
  return false;
287
286
  }
288
- const driver = createDriver(options);
289
- const { getItem, getItemRaw, getMeta, hasItem, removeItem, setItem, setItemRaw } = driver;
290
- driver.getItem = async (key, operationOptions) => {
291
- if (!await live(key)) return null;
292
- const value = await getItem(fileName(key), operationOptions);
293
- if (value instanceof Error) throw value;
294
- return value;
295
- };
296
- driver.getItemRaw = async (key, operationOptions) => {
297
- if (!await live(key)) return null;
298
- const value = await getItemRaw?.(fileName(key), operationOptions);
299
- if (value instanceof Error) throw value;
300
- return value;
301
- };
302
- driver.getMeta = async (key, operationOptions) => await live(key) ? getMeta?.(fileName(key), operationOptions) ?? null : null;
303
- driver.setItem = async (key, value, operationOptions) => {
304
- await writeExpiry(key, setExpiry(operationOptions));
305
- return setItem?.(fileName(key), value, operationOptions);
306
- };
307
- driver.setItemRaw = async (key, value, operationOptions) => {
308
- await writeExpiry(key, setExpiry(operationOptions));
309
- return setItemRaw?.(fileName(key), value, operationOptions);
310
- };
311
- driver.removeItem = async (key, operationOptions) => {
312
- await rm(expiryPath(key), { force: true });
313
- await removeItem?.(fileName(key), operationOptions);
314
- };
315
- driver.clear = (base = "") => queueUnderFolderLock(layout, async () => {
316
- const entries = await readdir(root).catch((error) => {
317
- if (hasCode(error, "ENOENT")) return [];
318
- throw error;
319
- });
320
- for (const entry of entries) {
321
- const key = keyOf(entry);
322
- if (key !== void 0 && key.startsWith(base)) {
323
- await rm(join(root, entry), {
324
- force: true,
325
- recursive: true
326
- });
327
- await rm(expiryPath(key), { force: true });
328
- }
329
- }
330
- }, "single");
287
+ const base = createDriver(options);
288
+ const locked = (operation) => (...args) => synchronized(() => operation(...args));
331
289
  const hasLiveItem = async (key, operationOptions) => {
332
- if (!await hasItem(fileName(key), operationOptions)) return false;
290
+ if (!await base.hasItem(fileName(key), operationOptions)) return false;
333
291
  if (!await live(key)) return false;
334
292
  try {
335
293
  return (await stat(join(root, fileName(key)))).isFile();
@@ -338,28 +296,9 @@ async function createFsLiteKVDriver(options) {
338
296
  throw error;
339
297
  }
340
298
  };
341
- driver.hasItem = hasLiveItem;
342
- driver.setIfAbsentItem = async (key, value, ttl) => {
343
- const expiresAt = ttl === void 0 ? void 0 : Date.now() + ttlMilliseconds(ttl);
344
- if (await hasLiveItem(key, {})) return false;
345
- const path = join(root, fileName(key));
346
- await mkdir(root, { recursive: true });
347
- const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
348
- await writeFile(temporary, value, "utf8");
349
- try {
350
- await link(temporary, path);
351
- await writeExpiry(key, expiresAt);
352
- return true;
353
- } catch (error) {
354
- if (hasCode(error, "EEXIST") && (await stat(path)).isFile()) return false;
355
- throw error;
356
- } finally {
357
- await rm(temporary, { force: true });
358
- }
359
- };
360
299
  async function readLiveText(key) {
361
300
  if (!await live(key)) return null;
362
- const value = await getItem(fileName(key), {});
301
+ const value = await base.getItem(fileName(key), {});
363
302
  if (value instanceof Error) throw value;
364
303
  return typeof value === "string" ? value : null;
365
304
  }
@@ -367,33 +306,6 @@ async function createFsLiteKVDriver(options) {
367
306
  await unlink(join(root, fileName(key)));
368
307
  await rm(expiryPath(key), { force: true });
369
308
  }
370
- driver.getAndDeleteItem = async (key) => {
371
- const text = await readLiveText(key);
372
- if (text === null) return null;
373
- await deleteKey(key);
374
- return text;
375
- };
376
- driver.incrementItem = async (key, ttl) => {
377
- const expiresAt = Date.now() + ttlMilliseconds(ttl);
378
- const text = await readLiveText(key);
379
- const counter = text === null ? 0 : canonicalInteger.test(text) ? Number(text) : NaN;
380
- if (!(counter >= Number.MIN_SAFE_INTEGER - 1 && counter < Number.MAX_SAFE_INTEGER)) throw kvErrorDiagnostics.KV_INVALID_COUNTER();
381
- const next = counter + 1;
382
- const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
383
- try {
384
- await writeFile(temporary, String(next));
385
- if (text === null) await writeExpiry(key, expiresAt);
386
- await rename(temporary, join(root, fileName(key)));
387
- } finally {
388
- await rm(temporary, { force: true });
389
- }
390
- return next;
391
- };
392
- driver.deleteIfEqualsItem = async (key, expected) => {
393
- if (await readLiveText(key) !== expected) return false;
394
- await deleteKey(key);
395
- return true;
396
- };
397
309
  async function* walk() {
398
310
  let entries;
399
311
  try {
@@ -408,57 +320,129 @@ async function createFsLiteKVDriver(options) {
408
320
  yield key !== void 0 && await synchronized(() => live(key)) ? key : void 0;
409
321
  }
410
322
  }
411
- driver.getKeys = async () => {
412
- const keys = [];
413
- for await (const key of walk()) if (key !== void 0) keys.push(key);
414
- return keys;
415
- };
416
323
  const expired = () => kvErrorDiagnostics.KV_INVALID_CURSOR({ problem: "expired" });
417
324
  const continuations = createKVContinuations({
418
325
  expired,
419
326
  release: (iterator) => iterator.return(void 0)
420
327
  });
421
- const dispose = driver.dispose;
422
- driver.dispose = async () => {
423
- try {
424
- await continuations.dispose();
425
- } finally {
426
- await dispose?.call(driver);
427
- }
428
- };
429
- driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
430
- const keys = [];
431
- const iterator = cursor ? continuations.take(cursor) : walk();
432
- if (!iterator) throw expired();
433
- let scanned = 0;
434
- while (scanned < limit) {
435
- const entry = await iterator.next();
436
- if (entry.done) return { keys };
437
- scanned++;
438
- const key = entry.value;
439
- if (key !== void 0 && key.startsWith(prefix)) keys.push(key);
328
+ return {
329
+ ...base,
330
+ getItem: locked(async (key, operationOptions) => {
331
+ if (!await live(key)) return null;
332
+ const value = await base.getItem(fileName(key), operationOptions);
333
+ if (value instanceof Error) throw value;
334
+ return value;
335
+ }),
336
+ getItemRaw: locked(async (key, operationOptions) => {
337
+ if (!await live(key)) return null;
338
+ const value = await base.getItemRaw?.(fileName(key), operationOptions);
339
+ if (value instanceof Error) throw value;
340
+ return value;
341
+ }),
342
+ getMeta: locked(async (key, operationOptions) => await live(key) ? base.getMeta?.(fileName(key), operationOptions) ?? null : null),
343
+ setItem: locked(async (key, value, operationOptions) => {
344
+ await writeExpiry(key, setExpiry(operationOptions));
345
+ return base.setItem?.(fileName(key), value, operationOptions);
346
+ }),
347
+ setItemRaw: locked(async (key, value, operationOptions) => {
348
+ await writeExpiry(key, setExpiry(operationOptions));
349
+ return base.setItemRaw?.(fileName(key), value, operationOptions);
350
+ }),
351
+ removeItem: locked(async (key, operationOptions) => {
352
+ await rm(expiryPath(key), { force: true });
353
+ await base.removeItem?.(fileName(key), operationOptions);
354
+ }),
355
+ clear: (prefix = "") => queueUnderFolderLock(layout, async () => {
356
+ const entries = await readdir(root).catch((error) => {
357
+ if (hasCode(error, "ENOENT")) return [];
358
+ throw error;
359
+ });
360
+ for (const entry of entries) {
361
+ const key = keyOf(entry);
362
+ if (key !== void 0 && key.startsWith(prefix)) {
363
+ await rm(join(root, entry), {
364
+ force: true,
365
+ recursive: true
366
+ });
367
+ await rm(expiryPath(key), { force: true });
368
+ }
369
+ }
370
+ }, "single"),
371
+ hasItem: locked(hasLiveItem),
372
+ setIfAbsentItem: locked(async (key, value, ttl) => {
373
+ const expiresAt = ttl === void 0 ? void 0 : Date.now() + ttlMilliseconds(ttl);
374
+ if (await hasLiveItem(key, {})) return false;
375
+ const path = join(root, fileName(key));
376
+ await mkdir(root, { recursive: true });
377
+ const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
378
+ await writeFile(temporary, value, "utf8");
379
+ try {
380
+ await link(temporary, path);
381
+ await writeExpiry(key, expiresAt);
382
+ return true;
383
+ } catch (error) {
384
+ if (hasCode(error, "EEXIST") && (await stat(path)).isFile()) return false;
385
+ throw error;
386
+ } finally {
387
+ await rm(temporary, { force: true });
388
+ }
389
+ }),
390
+ getAndDeleteItem: locked(async (key) => {
391
+ const text = await readLiveText(key);
392
+ if (text === null) return null;
393
+ await deleteKey(key);
394
+ return text;
395
+ }),
396
+ incrementItem: locked(async (key, ttl) => {
397
+ const expiresAt = Date.now() + ttlMilliseconds(ttl);
398
+ const text = await readLiveText(key);
399
+ const counter = text === null ? 0 : canonicalInteger.test(text) ? Number(text) : NaN;
400
+ if (!(counter >= Number.MIN_SAFE_INTEGER - 1 && counter < Number.MAX_SAFE_INTEGER)) throw kvErrorDiagnostics.KV_INVALID_COUNTER();
401
+ const next = counter + 1;
402
+ const temporary = join(root, `.unstorage-tmp-${randomUUID()}`);
403
+ try {
404
+ await writeFile(temporary, String(next));
405
+ if (text === null) await writeExpiry(key, expiresAt);
406
+ await rename(temporary, join(root, fileName(key)));
407
+ } finally {
408
+ await rm(temporary, { force: true });
409
+ }
410
+ return next;
411
+ }),
412
+ deleteIfEqualsItem: locked(async (key, expected) => {
413
+ if (await readLiveText(key) !== expected) return false;
414
+ await deleteKey(key);
415
+ return true;
416
+ }),
417
+ getKeys: async () => {
418
+ const keys = [];
419
+ for await (const key of walk()) if (key !== void 0) keys.push(key);
420
+ return keys;
421
+ },
422
+ dispose: async () => {
423
+ try {
424
+ await continuations.dispose();
425
+ } finally {
426
+ await base.dispose?.();
427
+ }
428
+ },
429
+ listKeys: async ({ cursor, limit, prefix = "" }) => {
430
+ const keys = [];
431
+ const iterator = cursor ? continuations.take(cursor) : walk();
432
+ if (!iterator) throw expired();
433
+ let scanned = 0;
434
+ while (scanned < limit) {
435
+ const entry = await iterator.next();
436
+ if (entry.done) return { keys };
437
+ scanned++;
438
+ const key = entry.value;
439
+ if (key !== void 0 && key.startsWith(prefix)) keys.push(key);
440
+ }
441
+ return {
442
+ keys,
443
+ cursor: await continuations.retain(iterator)
444
+ };
440
445
  }
441
- return {
442
- keys,
443
- cursor: await continuations.retain(iterator)
444
- };
445
446
  };
446
- for (const name of [
447
- "getItem",
448
- "getItemRaw",
449
- "getMeta",
450
- "hasItem",
451
- "setItem",
452
- "setItemRaw",
453
- "removeItem",
454
- "setIfAbsentItem",
455
- "getAndDeleteItem",
456
- "incrementItem",
457
- "deleteIfEqualsItem"
458
- ]) {
459
- const operation = driver[name];
460
- if (operation) Reflect.set(driver, name, (...args) => synchronized(async () => Reflect.apply(operation, driver, args)));
461
- }
462
- return driver;
463
447
  }
464
448
  export { createFsLiteKVDriver as t };
@@ -0,0 +1 @@
1
+ export { t as default } from "./fs-lite-1n_Dvy4p.js";
package/dist/index.js CHANGED
@@ -1,24 +1,15 @@
1
- import { r as normalizeKVOptions, s as readEnv } from "./config-Dr4GKknB.js";
1
+ import { r as normalizeKVOptions, s as readEnv } from "./config-x_Nru3R5.js";
2
2
  import { n as getActiveCloudflareEnv } from "./cloudflare-env-lookup-Dgq5n1Aq.js";
3
3
  import { a as kvListLimitInvalid, c as kvSetTTL, f as listKVKeys, i as kvKeyLimitCodes, m as ttlSeconds, n as kvInvalidKeyError, o as kvResult, p as kvStoreWithMode, s as kvSetCodes, t as kvClearOptionsError } from "./errors-kZRpu7Wa.js";
4
4
  import { o as normalizeKey } from "./utils2-By8eee1x.js";
5
5
  import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
6
- import { t as resolveRuntimeKVOptions } from "./upstash-BKkqGQGE.js";
6
+ import { t as resolveRuntimeKVOptions } from "./upstash-DINRYhXI.js";
7
7
  import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch-D-ib5_0P.js";
8
8
  import { n as normalizeKVListPrefix, t as createKVStorage$1 } from "./create-storage-DrhV0F4S.js";
9
9
  import { t as logFailure } from "./request-log-DllKQXj7.js";
10
10
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
11
11
  import { destr } from "destr";
12
12
  // src/runtime/driver.ts
13
- const lazyDriverMethods = /* @__PURE__ */ new Set([
14
- "clear",
15
- "getItem",
16
- "getKeys",
17
- "hasItem",
18
- "listKeys",
19
- "removeItem",
20
- "setItem"
21
- ]);
22
13
  const atomicDriverMethods = {
23
14
  deleteIfEquals: "deleteIfEqualsItem",
24
15
  getAndDelete: "getAndDeleteItem",
@@ -61,10 +52,9 @@ const otherOptionalDriverMethods = {
61
52
  "setItemRaw"
62
53
  ]
63
54
  };
64
- const batchDriverMethods = /* @__PURE__ */ new Set(["getItems", "setItems"]);
65
55
  const lazyOptionalDriverMethods = Object.fromEntries(Object.entries(driverAtomicOperations).map(([driver, operations]) => [driver, /* @__PURE__ */ new Set([...Object.keys(operations).map((operation) => atomicDriverMethods[operation]), ...otherOptionalDriverMethods[driver] ?? []])]));
66
56
  async function createDatabaseDriver(store, loadDatabases) {
67
- const { default: factory, kvSqlClientFromDatabase } = await import("./database-DJp7XHhu.js");
57
+ const { default: factory, kvSqlClientFromDatabase } = await import("./database-D0NvYrhk.js");
68
58
  return factory(store, async () => {
69
59
  const entry = loadDatabases ? (await loadDatabases())[store.database] : void 0;
70
60
  if (!entry) throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
@@ -79,7 +69,7 @@ async function createRuntimeDriver(store, loadDatabases) {
79
69
  case "cloudflare": {
80
70
  const { localBase } = store;
81
71
  if (localBase) {
82
- const { default: factory } = await import("./cloudflare-kv-local-DO1g7PrA.js");
72
+ const { default: factory } = await import("./cloudflare-kv-local-BpPaDG49.js");
83
73
  return factory({
84
74
  ...store,
85
75
  localBase
@@ -94,7 +84,7 @@ async function createRuntimeDriver(store, loadDatabases) {
94
84
  return factory(store);
95
85
  }
96
86
  case "fs-lite": {
97
- const { default: factory } = await import("./fs-lite-BMY853UK.js");
87
+ const { default: factory } = await import("./fs-lite-Co1NzxYo.js");
98
88
  return factory(store);
99
89
  }
100
90
  case "redis": {
@@ -124,30 +114,38 @@ function createLazyKVRuntimeDriver(config, loadDatabases) {
124
114
  });
125
115
  return pending;
126
116
  }
127
- const target = {
117
+ const optionalMethods = lazyOptionalDriverMethods[config.store.driver];
118
+ return {
128
119
  name: `lazy:${config.store.driver}`,
129
- options: config.store
130
- };
131
- return new Proxy(target, { get(t, prop) {
132
- const own = t[prop];
133
- if (own !== void 0) return own;
134
- if (prop === "dispose") return async () => {
120
+ options: config.store,
121
+ clear: async (base, options) => (await resolve()).clear?.(base, options),
122
+ getItem: async (key, options) => (await resolve()).getItem(key, options),
123
+ getItems: async (items, options) => {
124
+ const resolved = await resolve();
125
+ return (resolved.getItems ?? getItemsOneByOne(resolved))(items, options);
126
+ },
127
+ getKeys: async (base, options) => (await resolve()).getKeys(base, options),
128
+ hasItem: async (key, options) => (await resolve()).hasItem(key, options),
129
+ listKeys: async (options) => (await resolve()).listKeys(options),
130
+ removeItem: async (key, options) => (await resolve()).removeItem?.(key, options),
131
+ setItem: async (key, value, options) => (await resolve()).setItem?.(key, value, options),
132
+ setItems: async (items, options) => {
133
+ const resolved = await resolve();
134
+ return (resolved.setItems ?? setItemsOneByOne(resolved))(items, options);
135
+ },
136
+ dispose: async () => {
135
137
  disposed = true;
136
- if (!driverPromise) return;
137
- const driver = await driverPromise;
138
- return driver.dispose?.call(driver);
139
- };
140
- if (batchDriverMethods.has(prop)) return async (...args) => {
141
- const driver = await resolve();
142
- return (prop === "getItems" ? driver.getItems ?? getItemsOneByOne(driver) : driver.setItems ?? setItemsOneByOne(driver)).apply(driver, args);
143
- };
144
- const optionalMethods = lazyOptionalDriverMethods[config.store.driver];
145
- if (!lazyDriverMethods.has(prop) && !optionalMethods.has(prop)) return void 0;
146
- return async (...args) => {
147
- const driver = await resolve();
148
- return driver[prop]?.apply(driver, args);
149
- };
150
- } });
138
+ if (driverPromise) await (await driverPromise).dispose?.();
139
+ },
140
+ getItemRaw: optionalMethods.has("getItemRaw") ? async (key, options) => (await resolve()).getItemRaw?.(key, options) : void 0,
141
+ getMeta: optionalMethods.has("getMeta") ? async (key, options) => (await resolve()).getMeta?.(key, options) ?? null : void 0,
142
+ setItemRaw: optionalMethods.has("setItemRaw") ? async (key, value, options) => (await resolve()).setItemRaw?.(key, value, options) : void 0,
143
+ validateBatch: optionalMethods.has("validateBatch") ? async (items, removals, options) => (await resolve()).validateBatch(items, removals, options) : void 0,
144
+ deleteIfEqualsItem: optionalMethods.has("deleteIfEqualsItem") ? async (key, expected) => (await resolve()).deleteIfEqualsItem(key, expected) : void 0,
145
+ getAndDeleteItem: optionalMethods.has("getAndDeleteItem") ? async (key) => (await resolve()).getAndDeleteItem(key) : void 0,
146
+ incrementItem: optionalMethods.has("incrementItem") ? async (key, ttl) => (await resolve()).incrementItem(key, ttl) : void 0,
147
+ setIfAbsentItem: optionalMethods.has("setIfAbsentItem") ? async (key, value, ttl) => (await resolve()).setIfAbsentItem(key, value, ttl) : void 0
148
+ };
151
149
  }
152
150
  // src/runtime/hosted-storage.ts
153
151
  function assertHostedConfig(config) {
@@ -171,7 +169,7 @@ function serializeValue(value, operation = "setIfAbsent") {
171
169
  if (value && typeof value === "object") {
172
170
  const prototype = Object.getPrototypeOf(value);
173
171
  if (prototype === null || prototype === Object.prototype) return serializeJSONValue(value, operation);
174
- const toJSON = Reflect.get(value, "toJSON");
172
+ const toJSON = "toJSON" in value ? value.toJSON : void 0;
175
173
  if (typeof toJSON === "function") return serializeValue(toJSON.call(value), operation);
176
174
  }
177
175
  throw kvErrorDiagnostics.KV_INVALID_VALUE({
@@ -218,23 +216,23 @@ function createHostedKVStorage(config, name = "default", loadDatabases) {
218
216
  [name]: store
219
217
  }
220
218
  }, loadDatabases);
221
- const storage = createKVStorage$1(driver);
222
- storage.listKeys = (options) => driver.listKeys({
223
- ...options,
224
- prefix: normalizeKVListPrefix(options.prefix)
225
- });
226
- const getAndDeleteItem = driver.getAndDeleteItem;
227
- const incrementItem = driver.incrementItem;
228
- if (getAndDeleteItem) storage.getAndDeleteItem = async (key, options) => {
229
- const value = await getAndDeleteItem(normalizeKey(key));
230
- return options?.type === "text" ? value : deserializeValue(value);
219
+ const base = createKVStorage$1(driver);
220
+ const { getAndDeleteItem, incrementItem, setIfAbsentItem, deleteIfEqualsItem } = driver;
221
+ return {
222
+ ...base,
223
+ getMany: base.getMany,
224
+ listKeys: (options) => driver.listKeys({
225
+ ...options,
226
+ prefix: normalizeKVListPrefix(options.prefix)
227
+ }),
228
+ getAndDeleteItem: getAndDeleteItem && (async (key, options) => {
229
+ const value = await getAndDeleteItem(normalizeKey(key));
230
+ return options?.type === "text" ? value : deserializeValue(value);
231
+ }),
232
+ incrementItem: incrementItem && ((key, ttl) => incrementItem(normalizeKey(key), ttl)),
233
+ setIfAbsentItem: setIfAbsentItem && (async (key, value, ttl) => setIfAbsentItem(normalizeKey(key), serializeValue(value), ttl)),
234
+ deleteIfEqualsItem: deleteIfEqualsItem && (async (key, expected) => deleteIfEqualsItem(normalizeKey(key), serializeValue(expected, "deleteIfEquals")))
231
235
  };
232
- if (incrementItem) storage.incrementItem = (key, ttl) => incrementItem(normalizeKey(key), ttl);
233
- const setIfAbsentItem = driver.setIfAbsentItem;
234
- if (setIfAbsentItem) storage.setIfAbsentItem = async (key, value, ttl) => setIfAbsentItem(normalizeKey(key), serializeValue(value), ttl);
235
- const deleteIfEqualsItem = driver.deleteIfEqualsItem;
236
- if (deleteIfEqualsItem) storage.deleteIfEqualsItem = async (key, expected) => deleteIfEqualsItem(normalizeKey(key), serializeValue(expected, "deleteIfEquals"));
237
- return storage;
238
236
  }
239
237
  // src/runtime/lock.ts
240
238
  const firstRetryMs = 25;
@@ -6,13 +6,7 @@ import { kv } from "@vite-hub/kv";
6
6
  // src/runtime/inspect-value.ts
7
7
  const unsupported = () => kvErrorDiagnostics.KV_VALUE_UNSUPPORTED();
8
8
  function isUint8Array(value) {
9
- try {
10
- if (!ArrayBuffer.isView(value)) return false;
11
- const tagGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag)?.get;
12
- return Boolean(tagGetter && Reflect.apply(tagGetter, value, []) === "Uint8Array");
13
- } catch {
14
- return false;
15
- }
9
+ return ArrayBuffer.isView(value) && Object.prototype.toString.call(value) === "[object Uint8Array]";
16
10
  }
17
11
  function kvValueType(value) {
18
12
  if (value === null) return "null";
@@ -32,21 +26,20 @@ function inspectValue(value, seen = /* @__PURE__ */ new WeakSet()) {
32
26
  if (typeof value !== "object" && typeof value !== "function" || seen.has(value)) throw unsupported();
33
27
  seen.add(value);
34
28
  try {
35
- const ownKeys = Reflect.ownKeys(value);
36
- const dataKeys = Array.isArray(value) ? ownKeys.filter((key) => key !== "length") : ownKeys;
37
- if (dataKeys.map((key) => Object.getOwnPropertyDescriptor(value, key)).some((descriptor) => !descriptor?.enumerable || !("value" in descriptor))) throw unsupported();
29
+ const keys = Object.keys(value);
30
+ if (Object.getOwnPropertyNames(value).length - keys.length - (Array.isArray(value) ? 1 : 0) !== 0 || Object.getOwnPropertySymbols(value).length) throw unsupported();
38
31
  if (Array.isArray(value)) {
39
- if (dataKeys.length !== value.length || dataKeys.some((key) => typeof key !== "string" || String(Number(key)) !== key || !Number.isInteger(Number(key)) || Number(key) < 0 || Number(key) >= value.length)) throw unsupported();
40
- return Array.from({ length: value.length }, (_, index) => inspectValue(Object.getOwnPropertyDescriptor(value, String(index))?.value, seen));
32
+ if (keys.length !== value.length || keys.some((key, index) => key !== String(index))) throw unsupported();
33
+ return value.map((item) => inspectValue(item, seen));
41
34
  }
42
35
  const prototype = Object.getPrototypeOf(value);
43
- if (prototype !== Object.prototype && prototype !== null || Object.getOwnPropertySymbols(value).length) throw unsupported();
44
- return Object.fromEntries(dataKeys.map((key) => [key, inspectValue(Object.getOwnPropertyDescriptor(value, key)?.value, seen)]));
36
+ if (prototype !== Object.prototype && prototype !== null) throw unsupported();
37
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, inspectValue(item, seen)]));
45
38
  } finally {
46
39
  seen.delete(value);
47
40
  }
48
41
  }
49
- /** Encodes one inspection result without running getters or exposing non-JSON object behavior. */
42
+ /** Encodes a stored value as JSON data or Base64 bytes for inspection. */
50
43
  function inspectKVValue(value) {
51
44
  try {
52
45
  if (isUint8Array(value)) return {
@@ -59,7 +52,7 @@ function inspectKVValue(value) {
59
52
  value: inspectValue(value)
60
53
  };
61
54
  } catch (error) {
62
- if (Reflect.get(Object(error), "code") === "KV_VALUE_UNSUPPORTED") return;
55
+ if (error instanceof Error && "code" in error && error.code === "KV_VALUE_UNSUPPORTED") return;
63
56
  throw error;
64
57
  }
65
58
  }
@@ -123,7 +116,7 @@ function boundedJSONStringify(value) {
123
116
  }
124
117
  if (typeof input === "bigint") {
125
118
  editable = false;
126
- const toJSON = Reflect.get(Object(input), "toJSON");
119
+ const toJSON = Object(input).toJSON;
127
120
  if (applyToJSON && typeof toJSON === "function") return serialize(toJSON.call(input, key), depth, arrayValue, key, false);
128
121
  unsupported = true;
129
122
  return false;
@@ -131,16 +124,16 @@ function boundedJSONStringify(value) {
131
124
  const object = Object(input);
132
125
  const prototype = Object.getPrototypeOf(object);
133
126
  if (Array.isArray(object) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) editable = false;
134
- const keys = Reflect.ownKeys(object).filter((key) => !Array.isArray(object) || key !== "length");
135
- if (keys.some((key) => typeof key === "symbol" || !Object.getOwnPropertyDescriptor(object, key)?.enumerable)) editable = false;
127
+ const keys = Object.keys(object);
128
+ if (Object.getOwnPropertySymbols(object).length || Object.getOwnPropertyNames(object).length !== keys.length + (Array.isArray(object) ? 1 : 0)) editable = false;
136
129
  if (Array.isArray(object) && keys.length !== object.length) editable = false;
137
- const toJSON = Reflect.get(object, "toJSON");
130
+ const toJSON = object.toJSON;
138
131
  if (applyToJSON && typeof toJSON === "function") {
139
132
  editable = false;
140
133
  const replacement = toJSON.call(input, key);
141
134
  if (replacement !== input) return serialize(replacement, depth, arrayValue, key, false);
142
135
  }
143
- const boxed = input instanceof Number || input instanceof String || input instanceof Boolean || Object.prototype.toString.call(input) === "[object BigInt]" ? Reflect.apply(object.valueOf, input, []) : input;
136
+ const boxed = input instanceof Number || input instanceof String || input instanceof Boolean || Object.prototype.toString.call(input) === "[object BigInt]" ? object.valueOf() : input;
144
137
  if (boxed !== input) {
145
138
  editable = false;
146
139
  return serialize(boxed, depth, arrayValue, key);
@@ -166,9 +159,9 @@ function boundedJSONStringify(value) {
166
159
  let count = 0;
167
160
  for (const key in object) {
168
161
  if (!Object.prototype.hasOwnProperty.call(object, key)) continue;
169
- let item = Reflect.get(object, key);
162
+ let item = object[key];
170
163
  if (item !== null && (typeof item === "object" || typeof item === "bigint")) {
171
- const toJSON = Reflect.get(Object(item), "toJSON");
164
+ const toJSON = Object(item).toJSON;
172
165
  if (typeof toJSON === "function") {
173
166
  editable = false;
174
167
  item = toJSON.call(item, key);
@@ -1,12 +1,13 @@
1
1
  import { n as isRecordOrFunction, t as isRecord } from "./object-CAK6UYR5.js";
2
2
  import { t as invariant } from "./invariant-Dj2R1eMr.js";
3
+ import "node:module";
3
4
  import { readdir } from "node:fs/promises";
4
5
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
5
6
  import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
7
  import { createInterface } from "node:readline/promises";
8
+ import "node:url";
7
9
  import { defineDiagnostics } from "nostics";
8
10
  import { tmpdir } from "node:os";
9
- import "node:url";
10
11
  import { createBirpc } from "birpc";
11
12
  import { toJsonSchema } from "@valibot/to-json-schema";
12
13
  // ../internal/src/error-diagnostics.ts
@@ -1,4 +1,4 @@
1
- import { F as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as defineOperation, f as answerOperationRpc, h as readOperationRpcCall, i as createOperationRegistry, l as runOperation, m as operationRpcRefusal, o as operationRpcHeader, s as operationsOf, t as assertOperationProject, u as toOperationFailure } from "./operations-BKAO0rkO.js";
1
+ import { F as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as defineOperation, f as answerOperationRpc, h as readOperationRpcCall, i as createOperationRegistry, l as runOperation, m as operationRpcRefusal, o as operationRpcHeader, s as operationsOf, t as assertOperationProject, u as toOperationFailure } from "./operations-DP8iWjQK.js";
2
2
  import { t as kvDevMaximumListLimit } from "./results-emgN7uDS.js";
3
3
  import { n as isViteHubLoopbackPeer } from "./dev-peer-D0vOxmrD.js";
4
4
  import * as v from "valibot";
@@ -235,7 +235,7 @@ function createStandaloneOperationHandler(sources, root) {
235
235
  } };
236
236
  }
237
237
  // src/operations.ts
238
- const runtime = () => import("./operations-UeAgPdtY.js");
238
+ const runtime = () => import("./operations-Cj_0pSSA.js");
239
239
  const store = v.optional(v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name a store.")));
240
240
  const key = v.string();
241
241
  function defineKVOperation(definition) {
@@ -1,4 +1,4 @@
1
- import { t as KVRuntimeDriver } from "../driver-Cvu4k8t4.js";
1
+ import { t as KVRuntimeDriver } from "../driver-CZTAQ_07.js";
2
2
  declare function createCloudflareDriver(options: Record<string, unknown>): KVRuntimeDriver;
3
3
  export declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
4
4
  export { createCloudflareDriver as default };
@@ -1,5 +1,5 @@
1
1
  import { t as logFailure } from "../request-log-DllKQXj7.js";
2
- import { t as kvInferredStoreNotice } from "../config-Dr4GKknB.js";
2
+ import { t as kvInferredStoreNotice } from "../config-x_Nru3R5.js";
3
3
  import { disposeKVStores } from "@vite-hub/kv";
4
4
  // src/runtime/nitro-plugin.ts
5
5
  async function logInferredStores() {
@@ -1,5 +1,5 @@
1
1
  import { z as ResolvedRedisKVStoreConfig } from "../types-BLxnI_rU.js";
2
- import { t as KVRuntimeDriver } from "../driver-Cvu4k8t4.js";
2
+ import { t as KVRuntimeDriver } from "../driver-CZTAQ_07.js";
3
3
  /** The URL of a store: `env:<NAME>` reads the variable now, so a build never holds the URL of its server. */
4
4
  export declare function resolveRedisUrl(url: string, env?: Record<string, string | undefined>): string;
5
5
  /**
@@ -92,9 +92,7 @@ function createRedisKVDriver(options) {
92
92
  async setIfAbsentItem(key, value, ttl) {
93
93
  return (ttl === void 0 ? await client.set(prefixed(key), value, "NX") : await client.set(prefixed(key), value, "PX", ttlMilliseconds(ttl), "NX")) === "OK";
94
94
  },
95
- async getAndDeleteItem(key) {
96
- return await client.getdel(prefixed(key));
97
- },
95
+ getAndDeleteItem: async (key) => await client.getdel(prefixed(key)),
98
96
  incrementItem: async (key, ttl) => redisIncrementResult(await client.eval(redisIncrementScript, 1, prefixed(key), redisTTLSeconds(ttl))),
99
97
  deleteIfEqualsItem: async (key, expected) => Number(await client.eval(redisDeleteIfEqualsScript, 1, prefixed(key), expected)) === 1,
100
98
  listKeys: createPortableRedisKeyLister("Redis KV", async (cursor, match, count) => {
@@ -1,3 +1,3 @@
1
1
  import { B as ResolvedUpstashKVStoreConfig } from "../types-BLxnI_rU.js";
2
- import { t as KVRuntimeDriver } from "../driver-Cvu4k8t4.js";
2
+ import { t as KVRuntimeDriver } from "../driver-CZTAQ_07.js";
3
3
  export default function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
@@ -1,4 +1,4 @@
1
- import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, s as readEnv } from "./config-Dr4GKknB.js";
1
+ import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, s as readEnv } from "./config-x_Nru3R5.js";
2
2
  import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
3
3
  // src/runtime/upstash.ts
4
4
  function isMaskedValue(value) {
package/dist/vite.d.ts CHANGED
@@ -149,6 +149,7 @@ export interface KVVitePluginAPI {
149
149
  deploymentEnv: DeploymentEnvContribution;
150
150
  getConfig: () => KVViteRuntimeConfig;
151
151
  getBuildConfig: () => KVViteRuntimeConfig;
152
+ whenConfigResolved: () => Promise<void> | undefined;
152
153
  }
153
154
  export type KVVitePlugin = Plugin & {
154
155
  api: KVVitePluginAPI;
package/dist/vite.js CHANGED
@@ -3,17 +3,17 @@ import { n as invariantError, t as invariant } from "./invariant-Dj2R1eMr.js";
3
3
  import { a as resolve$1, i as relative$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-BWMcVWD8.js";
4
4
  import { t as addViteHubDevPeerDevHandler } from "./dev-peer-D0vOxmrD.js";
5
5
  import { n as isRecordOrFunction, t as isRecord } from "./object-CAK6UYR5.js";
6
- import { A as readViteHubDevServerFile, C as markViteConfigPlugin, F as internalErrorDiagnostics, M as removeViteHubDevServerFile, P as writeViteHubDevServerFile, S as isServerEnvironment, T as shouldSkipViteProviderBuild, b as createNoExternalAddition, p as operationRpcPath, r as collectOperationContributions, v as VITEHUB_PROJECT_ROOT, w as resolveViteHubProjectRoot, x as hasNitroConfigContext, y as contributeServerEnv } from "./operations-BKAO0rkO.js";
7
- import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvHint, o as resolveHostPreset, r as normalizeKVOptions } from "./config-Dr4GKknB.js";
6
+ import { A as readViteHubDevServerFile, C as markViteConfigPlugin, F as internalErrorDiagnostics, M as removeViteHubDevServerFile, P as writeViteHubDevServerFile, S as isServerEnvironment, T as shouldSkipViteProviderBuild, b as createNoExternalAddition, p as operationRpcPath, r as collectOperationContributions, v as VITEHUB_PROJECT_ROOT, w as resolveViteHubProjectRoot, x as hasNitroConfigContext, y as contributeServerEnv } from "./operations-DP8iWjQK.js";
7
+ import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvHint, o as resolveHostPreset, r as normalizeKVOptions } from "./config-x_Nru3R5.js";
8
8
  import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
9
- import { n as resolveUpstashRuntimeValues } from "./upstash-BKkqGQGE.js";
9
+ import { n as resolveUpstashRuntimeValues } from "./upstash-DINRYhXI.js";
10
10
  import { createRequire, isBuiltin } from "node:module";
11
11
  import { access, copyFile, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
12
12
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
13
13
  import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
14
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
15
  import { formatDiagnostic } from "nostics";
15
16
  import { tmpdir } from "node:os";
16
- import { fileURLToPath, pathToFileURL } from "node:url";
17
17
  import { createHash } from "node:crypto";
18
18
  // ../internal/src/build/paths.ts
19
19
  function resolveRuntimeModule(packageDir, modulePath) {
@@ -5780,11 +5780,11 @@ function serializeCloudflareRuntime(config) {
5780
5780
  }
5781
5781
  function getNitroCloudflareKVNamespaces(target) {
5782
5782
  if (!isRecord(target)) return [];
5783
- const cloudflare = Reflect.get(target, "cloudflare");
5783
+ const cloudflare = target.cloudflare;
5784
5784
  if (!isRecord(cloudflare)) return [];
5785
- const wrangler = Reflect.get(cloudflare, "wrangler");
5785
+ const wrangler = cloudflare.wrangler;
5786
5786
  if (!isRecord(wrangler)) return [];
5787
- const namespaces = Reflect.get(wrangler, "kv_namespaces");
5787
+ const namespaces = wrangler.kv_namespaces;
5788
5788
  if (!Array.isArray(namespaces)) return [];
5789
5789
  return namespaces.flatMap((namespace) => {
5790
5790
  let normalized;
@@ -5794,11 +5794,7 @@ function getNitroCloudflareKVNamespaces(target) {
5794
5794
  return [];
5795
5795
  }
5796
5796
  if (!isProviderJsonRecord(normalized)) return [];
5797
- const binding = Reflect.get(normalized, "binding");
5798
- const id = Reflect.get(normalized, "id");
5799
- const previewId = Reflect.get(normalized, "preview_id");
5800
- const experimentalRemote = Reflect.get(normalized, "experimental_remote");
5801
- const remote = Reflect.get(normalized, "remote");
5797
+ const { binding, id, preview_id: previewId, experimental_remote: experimentalRemote, remote } = normalized;
5802
5798
  if (typeof binding !== "string") return [];
5803
5799
  if (id !== void 0 && typeof id !== "string") return [];
5804
5800
  if (previewId !== void 0 && typeof previewId !== "string") return [];
@@ -5808,7 +5804,7 @@ function getNitroCloudflareKVNamespaces(target) {
5808
5804
  });
5809
5805
  }
5810
5806
  function getResolvedNitroConfig(config) {
5811
- return Reflect.get(config, "nitro");
5807
+ return "nitro" in config ? config.nitro : void 0;
5812
5808
  }
5813
5809
  function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState) {
5814
5810
  configureNitroCloudflareRequestEnv(target, kv);
@@ -5822,7 +5818,7 @@ function reconcileNitroCloudflareKV(target, kv, ownedNamespaces, provisionState)
5822
5818
  if (kv) configureCloudflareKV(target, kv, provisionState);
5823
5819
  }
5824
5820
  function configureNitroCloudflareKV(config, options, input, ownedNamespaces, provisionState) {
5825
- const nitro = Reflect.get(config, "nitro");
5821
+ const nitro = "nitro" in config ? config.nitro : void 0;
5826
5822
  if (!isRecord(nitro)) return false;
5827
5823
  const target = nitro;
5828
5824
  const namespaces = target.cloudflare?.wrangler?.kv_namespaces;
@@ -5831,7 +5827,7 @@ function configureNitroCloudflareKV(config, options, input, ownedNamespaces, pro
5831
5827
  const kv = resolveKVViteConfig(options, input).kv;
5832
5828
  configureNitroCloudflareRequestEnv(target, kv);
5833
5829
  configureNitroPlugin(target, kv);
5834
- if (Reflect.get(config, "__vitehubNitroConfigContext") === true) configureNitroStorage(target, kv);
5830
+ if ("__vitehubNitroConfigContext" in config && config["__vitehubNitroConfigContext"] === true) configureNitroStorage(target, kv);
5835
5831
  if (kv) {
5836
5832
  const existingNamespaces = new Set(target.cloudflare?.wrangler?.kv_namespaces);
5837
5833
  configureCloudflareKV(target, kv, provisionState);
@@ -5863,6 +5859,7 @@ function hubKV(options, input = {}) {
5863
5859
  let resolved;
5864
5860
  let providerOutput;
5865
5861
  let runtimeConfig;
5862
+ let configReady;
5866
5863
  let projectRoot = process.cwd();
5867
5864
  const getConfig = () => runtimeConfig ??= resolveKVViteConfig(options, resolutionInput());
5868
5865
  const providerOutputGenerations = createProviderDeploymentOutputGenerationState();
@@ -5877,6 +5874,25 @@ function hubKV(options, input = {}) {
5877
5874
  });
5878
5875
  if (hint) reportViteHubHint(config, hint);
5879
5876
  }
5877
+ async function resolveRuntimeConfig(config) {
5878
+ resolved = config;
5879
+ startViteHubHints(config);
5880
+ if (config.command) command = config.command;
5881
+ mode = config.mode ?? mode;
5882
+ projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
5883
+ viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
5884
+ databasePlugin = findDatabasePlugin(config.plugins);
5885
+ await databasePlugin?.api?.whenConfigResolved?.();
5886
+ providerOutput = useProviderOutputCatalog(config);
5887
+ runtimeConfig = resolveKVViteConfig(options, resolutionInput());
5888
+ const provisionState = readProvisionStateSync(projectRoot);
5889
+ if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
5890
+ if (hasNitroConfigContext(config) || isRecord(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, provisionState);
5891
+ if (!config.command && command === "build" && Reflect.get(config, "__vitehubNuxtHints")) reportRedisEnvHint({
5892
+ ...config,
5893
+ command
5894
+ });
5895
+ }
5880
5896
  return {
5881
5897
  name: KV_VITE_PLUGIN_NAME,
5882
5898
  enforce: "post",
@@ -5886,7 +5902,8 @@ function hubKV(options, input = {}) {
5886
5902
  hosting: hosting(),
5887
5903
  postgresDatabase: postgresDatabase()
5888
5904
  }),
5889
- getConfig
5905
+ getConfig,
5906
+ whenConfigResolved: () => configReady
5890
5907
  },
5891
5908
  nitro: {
5892
5909
  name: "@vite-hub/kv/cloudflare-bindings",
@@ -5931,7 +5948,7 @@ function hubKV(options, input = {}) {
5931
5948
  default: kv.store,
5932
5949
  ...kv.stores
5933
5950
  }).map(([name, store]) => {
5934
- const database = Reflect.get(store, "database");
5951
+ const database = "database" in store ? store.database : void 0;
5935
5952
  return [name, {
5936
5953
  driver: store.driver,
5937
5954
  ..."base" in store && store.base ? { base: store.base } : {},
@@ -5986,7 +6003,7 @@ function hubKV(options, input = {}) {
5986
6003
  command = env?.command ?? "build";
5987
6004
  configuredHosting = resolveHostPreset({
5988
6005
  hosting: input.hosting,
5989
- nitro: Reflect.get(config, "nitro"),
6006
+ nitro: "nitro" in config ? config.nitro : void 0,
5990
6007
  env: {}
5991
6008
  });
5992
6009
  resolvedNitroPreset = void 0;
@@ -5995,7 +6012,7 @@ function hubKV(options, input = {}) {
5995
6012
  projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
5996
6013
  viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
5997
6014
  nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, readProvisionStateSync(projectRoot));
5998
- const inspectedKV = Reflect.get(config, "vitehubCliDiscovery") === true && mode !== "development" ? resolveKVViteConfig(options, {
6015
+ const inspectedKV = "vitehubCliDiscovery" in config && config.vitehubCliDiscovery === true && mode !== "development" ? resolveKVViteConfig(options, {
5999
6016
  hosting: hosting(),
6000
6017
  postgresDatabase: postgresDatabase()
6001
6018
  }).kv : getConfig().kv;
@@ -6005,23 +6022,8 @@ function hubKV(options, input = {}) {
6005
6022
  },
6006
6023
  configResolved: {
6007
6024
  order: "pre",
6008
- async handler(config) {
6009
- resolved = config;
6010
- startViteHubHints(config);
6011
- if (config.command) command = config.command;
6012
- mode = config.mode ?? mode;
6013
- projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
6014
- viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
6015
- databasePlugin = findDatabasePlugin(config.plugins);
6016
- providerOutput = useProviderOutputCatalog(config);
6017
- runtimeConfig = resolveKVViteConfig(options, resolutionInput());
6018
- const provisionState = readProvisionStateSync(projectRoot);
6019
- if (nitroOptions) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, provisionState);
6020
- if (hasNitroConfigContext(config) || isRecord(getResolvedNitroConfig(config))) nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, provisionState);
6021
- if (!config.command && command === "build" && Reflect.get(config, "__vitehubNuxtHints")) reportRedisEnvHint({
6022
- ...config,
6023
- command
6024
- });
6025
+ handler(config) {
6026
+ return configReady = resolveRuntimeConfig(config);
6025
6027
  }
6026
6028
  },
6027
6029
  configureServer(server) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/kv",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Vite-first key-value storage primitives and integration for ViteHub.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -70,7 +70,7 @@
70
70
  },
71
71
  "dependencies": {
72
72
  "@valibot/to-json-schema": "^1.8.0",
73
- "@vite-hub/runtime": "0.7.0",
73
+ "@vite-hub/runtime": "0.8.0",
74
74
  "birpc": "^4.2.0",
75
75
  "defu": "^6.1.7",
76
76
  "destr": "^2.0.5",
@@ -84,7 +84,7 @@
84
84
  "@types/node": "^24.19.2",
85
85
  "@electric-sql/pglite": "^0.5.17",
86
86
  "@libsql/client": "^0.18.0",
87
- "@vite-hub/database": "0.7.0",
87
+ "@vite-hub/database": "0.8.0",
88
88
  "@types/pg": "^8.23.1",
89
89
  "@types/proper-lockfile": "4.1.4",
90
90
  "@vite-hub/internal": "0.0.1",
@@ -100,7 +100,7 @@
100
100
  },
101
101
  "peerDependencies": {
102
102
  "@upstash/redis": "^1.41.0",
103
- "@vite-hub/database": "0.7.0",
103
+ "@vite-hub/database": "0.8.0",
104
104
  "vite": ">=8.0.0"
105
105
  },
106
106
  "peerDependenciesMeta": {
@@ -1 +0,0 @@
1
- export { t as default } from "./fs-lite-4ccAiYae.js";