@vite-hub/kv 0.6.0 → 0.7.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/README.md +7 -7
  2. package/dist/{cli-BvVInMht.d.ts → cli-C-uep33j.d.ts} +15 -0
  3. package/dist/cli.d.ts +2 -2
  4. package/dist/cli.js +3 -2
  5. package/dist/{cloudflare-kv-Cp8HPUlJ.js → cloudflare-kv-hMdZQZz1.js} +3 -3
  6. package/dist/{cloudflare-kv-local-COoOI34K.js → cloudflare-kv-local-DO1g7PrA.js} +2 -2
  7. package/dist/{config-_1oBDv2R.js → config-Dr4GKknB.js} +1 -1
  8. package/dist/{create-storage-DbWVAY9l.js → create-storage-DrhV0F4S.js} +1 -1
  9. package/dist/{cursor-history-CMcEEnTO.js → cursor-history-MzSrXXXX.js} +1 -1
  10. package/dist/{database-4iAg2GoV.js → database-DJp7XHhu.js} +64 -18
  11. package/dist/{deno-kv-CatE7zSS.js → deno-kv-DwcTL95B.js} +2 -2
  12. package/dist/{driver-BruahGvT.d.ts → driver-Cvu4k8t4.d.ts} +1 -1
  13. package/dist/{error-diagnostics-CuVl1nvE.js → error-diagnostics-DAi25E6F.js} +10 -5
  14. package/dist/{errors-CJoAP4Bu.js → errors-kZRpu7Wa.js} +15 -2
  15. package/dist/errors.d.ts +6 -1
  16. package/dist/errors.js +1 -1
  17. package/dist/{fs-lite-DzTTR6R3.js → fs-lite-4ccAiYae.js} +106 -26
  18. package/dist/fs-lite-BMY853UK.js +1 -0
  19. package/dist/index.d.ts +1 -1
  20. package/dist/index.js +32 -20
  21. package/dist/{operation-definition-CqZkx1Rm.d.ts → operations-BAlr2zUj.d.ts} +1 -0
  22. package/dist/{operations-BkVt17cd.js → operations-BKAO0rkO.js} +73 -10
  23. package/dist/{operations-DSOTGwST.js → operations-UeAgPdtY.js} +6 -6
  24. package/dist/operations.d.ts +2 -2
  25. package/dist/operations.js +2 -2
  26. package/dist/{redis-shared-CR3ANc_N.js → redis-shared-DEwmedD5.js} +1 -1
  27. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  28. package/dist/runtime/cloudflare-kv.js +1 -1
  29. package/dist/runtime/nitro-plugin.js +1 -1
  30. package/dist/runtime/redis-driver.d.ts +2 -2
  31. package/dist/runtime/redis-driver.js +2 -2
  32. package/dist/runtime/upstash-driver.d.ts +2 -2
  33. package/dist/runtime/upstash-driver.js +2 -2
  34. package/dist/{types-CPDL9enF.d.ts → types-BLxnI_rU.d.ts} +14 -14
  35. package/dist/{upstash-DeM3_U5H.js → upstash-BKkqGQGE.js} +2 -2
  36. package/dist/vite.d.ts +8 -5
  37. package/dist/vite.js +178 -44
  38. package/package.json +8 -4
  39. package/dist/fs-lite-DwbPkc-C.js +0 -1
package/dist/vite.js CHANGED
@@ -3,10 +3,10 @@ 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 { C as resolveViteHubProjectRoot, N as writeViteHubDevServerFile, P as internalErrorDiagnostics, S as markViteConfigPlugin, b as hasNitroConfigContext, j as removeViteHubDevServerFile, k as readViteHubDevServerFile, p as operationRpcPath, r as collectOperationContributions, v as VITEHUB_PROJECT_ROOT, w as shouldSkipViteProviderBuild, x as isServerEnvironment, y as createNoExternalAddition } from "./operations-BkVt17cd.js";
7
- import { a as upstashUrlEnvNames, i as upstashTokenEnvNames, n as kvRedisEnvHint, o as resolveHostPreset, r as normalizeKVOptions } from "./config-_1oBDv2R.js";
8
- import { n as kvErrorDiagnostics } from "./error-diagnostics-CuVl1nvE.js";
9
- import { n as resolveUpstashRuntimeValues } from "./upstash-DeM3_U5H.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";
8
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-DAi25E6F.js";
9
+ import { n as resolveUpstashRuntimeValues } from "./upstash-BKkqGQGE.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";
@@ -326,12 +326,32 @@ function mergeOwnedArrays(existing, value, arrays) {
326
326
  const next = { ...value };
327
327
  for (const [field, ownership] of Object.entries(arrays ?? {})) {
328
328
  const incoming = Array.isArray(value[field]) ? value[field] : [];
329
- const merged = [...preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming), ...incoming];
329
+ const unowned = preserveUnownedKeyedArrayEntries(existing[field], ownership, incoming);
330
+ const merged = ownership.key !== void 0 && ownership.preserveOrder && Array.isArray(existing[field]) ? mergeOrderedEntries(existing[field], unowned, incoming, ownership.key) : [...unowned, ...incoming];
330
331
  if (merged.length) next[field] = merged;
331
332
  else delete next[field];
332
333
  }
333
334
  return next;
334
335
  }
336
+ function mergeOrderedEntries(current, unowned, incoming, key) {
337
+ const preserved = new Set(unowned);
338
+ const replacements = new Map(incoming.flatMap((entry) => {
339
+ const identity = getKeyedArrayEntryValue(entry, key);
340
+ return identity === void 0 ? [] : [[identity, entry]];
341
+ }));
342
+ return [...current.flatMap((entry) => {
343
+ if (preserved.has(entry)) return [entry];
344
+ const identity = getKeyedArrayEntryValue(entry, key);
345
+ if (identity === void 0) return [];
346
+ const replacement = replacements.get(identity);
347
+ if (replacement === void 0) return [];
348
+ replacements.delete(identity);
349
+ return [replacement];
350
+ }), ...incoming.filter((entry) => {
351
+ const identity = getKeyedArrayEntryValue(entry, key);
352
+ return identity === void 0 || replacements.has(identity);
353
+ })];
354
+ }
335
355
  async function persistProviderJsonRecord(file, value, removeIfEmpty) {
336
356
  if (removeIfEmpty && !Object.keys(value).length) {
337
357
  await rm(file, { force: true });
@@ -351,19 +371,31 @@ async function writeProviderOutputConfig(file, value, ownership = {}, options =
351
371
  function mergeProviderOutputConfig(existing, value, ownership = {}) {
352
372
  assertProviderJsonRecord(existing);
353
373
  assertProviderJsonRecord(value);
354
- return {
374
+ const next = {
355
375
  ...deleteOwnedFields(existing, ownership),
356
376
  ...mergeOwnedArrays(existing, value, ownership.arrays)
357
377
  };
378
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
379
+ const current = existing[field];
380
+ const incoming = value[field];
381
+ const merged = mergeProviderOutputConfig(isProviderJsonRecord(current) ? current : {}, isProviderJsonRecord(incoming) ? incoming : {}, childOwnership);
382
+ if (Object.keys(merged).length) next[field] = merged;
383
+ else delete next[field];
384
+ }
385
+ return next;
358
386
  }
359
387
  function stringifyProviderOutputConfig(value) {
360
388
  assertProviderJsonRecord(value);
361
389
  return JSON.stringify(value, null, 2);
362
390
  }
363
391
  async function cleanProviderOutputConfig(file, ownership) {
364
- if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length) return;
392
+ if (!ownership.keys?.length && !Object.keys(ownership.arrays ?? {}).length && !Object.keys(ownership.objects ?? {}).length) return;
365
393
  const existing = await readProviderJsonRecord(file);
366
394
  if (!existing) return;
395
+ const next = cleanOwnedFields(existing, ownership);
396
+ if (next) await persistProviderJsonRecord(file, next, true);
397
+ }
398
+ function cleanOwnedFields(existing, ownership) {
367
399
  const next = deleteOwnedFields(existing, ownership, true);
368
400
  let changed = (ownership.keys ?? []).some((key) => key in existing);
369
401
  for (const [field, arrayOwnership] of Object.entries(ownership.arrays ?? {})) {
@@ -375,8 +407,16 @@ async function cleanProviderOutputConfig(file, ownership) {
375
407
  changed ||= retained.length > 0 || !Array.isArray(current) || preserved.length !== current.length || preserved.length === 0;
376
408
  if (preserved.length) next[field] = preserved;
377
409
  }
378
- if (!changed) return;
379
- await persistProviderJsonRecord(file, next, true);
410
+ for (const [field, childOwnership] of Object.entries(ownership.objects ?? {})) {
411
+ const current = existing[field];
412
+ if (!isProviderJsonRecord(current)) continue;
413
+ const cleaned = cleanOwnedFields(current, childOwnership);
414
+ if (!cleaned) continue;
415
+ changed = true;
416
+ if (Object.keys(cleaned).length) next[field] = cleaned;
417
+ else delete next[field];
418
+ }
419
+ if (changed) return next;
380
420
  }
381
421
  // ../internal/src/build/user-entry.ts
382
422
  function toSafeAppName(rootDir) {
@@ -3293,8 +3333,26 @@ async function copyRuntimePackageFiles(packageDir, targetDir) {
3293
3333
  }
3294
3334
  }
3295
3335
  // ../internal/src/build/provider-output-sources.ts
3296
- /** Removes retained provider output after readers release it, tolerating transient filesystem contention. */
3297
- async function removeProviderOutputArtifactDir(path) {
3336
+ const keptFailedProviderOutputArtifactDirs = /* @__PURE__ */ new Set();
3337
+ function failureText(failure) {
3338
+ return failure instanceof Error ? `${failure.message}\n${failure.stack ?? ""}` : String(failure);
3339
+ }
3340
+ /**
3341
+ * Removes retained provider output after readers release it, tolerating transient filesystem contention. Pass the
3342
+ * build failure when a failed build discards its generation: with `VITEHUB_KEEP_FAILED_BUILD=1` the folder stays
3343
+ * for inspection.
3344
+ */
3345
+ async function removeProviderOutputArtifactDir(path, failure) {
3346
+ if (failure !== void 0) {
3347
+ const shown = relative(process.cwd(), path) || path;
3348
+ if (/^(?:1|true)$/i.test(process.env.VITEHUB_KEEP_FAILED_BUILD ?? "")) {
3349
+ if (!existsSync(path)) return;
3350
+ if (!keptFailedProviderOutputArtifactDirs.has(path)) console.warn(`[vitehub] The build failed. ViteHub kept its provider sources in ${shown} so you can inspect them. Remove the folder when you are done.`);
3351
+ keptFailedProviderOutputArtifactDirs.add(path);
3352
+ return;
3353
+ }
3354
+ if (failureText(failure).includes(basename(path))) console.warn(`[vitehub] The build error names files in ${shown}, which ViteHub removes after a failed build. Set VITEHUB_KEEP_FAILED_BUILD=1 to keep them.`);
3355
+ }
3298
3356
  await rm(path, {
3299
3357
  force: true,
3300
3358
  maxRetries: 5,
@@ -3706,17 +3764,17 @@ var ProviderOutputCatalog = class {
3706
3764
  }
3707
3765
  this.#restoreDeploymentContribution(entry);
3708
3766
  }
3709
- resetDeploymentContributions(generation) {
3767
+ resetDeploymentContributions(generation, failure) {
3710
3768
  if (!generation) {
3711
3769
  for (const reference of this.#deploymentGenerations) {
3712
3770
  const current = reference.deref();
3713
3771
  if (current) current.valid = false;
3714
3772
  }
3715
3773
  this.#deploymentGenerations.clear();
3716
- for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry);
3774
+ for (const entries of this.#deploymentContributions.values()) for (const entry of entries) this.#queueDeploymentDiscard(entry, failure);
3717
3775
  for (const taken of this.#takenDeploymentContributions.values()) {
3718
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
3719
- for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback);
3776
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
3777
+ for (const fallback of taken.fallbacks) this.#queueDeploymentDiscard(fallback, failure);
3720
3778
  }
3721
3779
  this.#deploymentContributions.clear();
3722
3780
  this.#takenDeploymentContributions.clear();
@@ -3725,7 +3783,7 @@ var ProviderOutputCatalog = class {
3725
3783
  generation.valid = false;
3726
3784
  this.#deleteDeploymentGeneration(generation);
3727
3785
  for (const [owner, entries] of this.#deploymentContributions) {
3728
- for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry);
3786
+ for (const entry of entries) if (entry.generation === generation) this.#queueDeploymentDiscard(entry, failure);
3729
3787
  const remaining = entries.filter((entry) => entry.generation !== generation);
3730
3788
  if (remaining.length) this.#deploymentContributions.set(owner, remaining);
3731
3789
  else this.#deploymentContributions.delete(owner);
@@ -3733,10 +3791,10 @@ var ProviderOutputCatalog = class {
3733
3791
  for (const [contribution, taken] of this.#takenDeploymentContributions) {
3734
3792
  const invalidatedFallbacks = taken.fallbacks.filter((entry) => entry.generation === generation);
3735
3793
  taken.fallbacks = taken.fallbacks.filter((entry) => entry.generation !== generation);
3736
- for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback);
3794
+ for (const fallback of invalidatedFallbacks) this.#queueDeploymentDiscard(fallback, failure);
3737
3795
  if (taken.entry.generation !== generation) continue;
3738
3796
  this.#takenDeploymentContributions.delete(contribution);
3739
- if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry);
3797
+ if (!taken.entryDiscarded) this.#queueDeploymentDiscard(taken.entry, failure);
3740
3798
  for (const fallback of taken.fallbacks) if (taken.committed) this.#queueDeploymentDiscard(fallback);
3741
3799
  else this.#restoreDeploymentContribution(fallback);
3742
3800
  }
@@ -3779,7 +3837,7 @@ var ProviderOutputCatalog = class {
3779
3837
  const failure = (await Promise.allSettled(discarded)).find((result) => result.status === "rejected");
3780
3838
  if (failure) throw failure.reason;
3781
3839
  }
3782
- async completeDeploymentContributions(contributions) {
3840
+ async completeDeploymentContributions(contributions, buildFailure) {
3783
3841
  const discarded = this.#pendingDeploymentDiscards.splice(0);
3784
3842
  const completedGenerations = /* @__PURE__ */ new Set();
3785
3843
  for (const contribution of contributions) {
@@ -3789,7 +3847,7 @@ var ProviderOutputCatalog = class {
3789
3847
  const entries = taken.entryDiscarded ? taken.fallbacks : [...taken.fallbacks, taken.entry];
3790
3848
  for (const entry of entries) {
3791
3849
  if (entry.generation) completedGenerations.add(entry.generation);
3792
- if (entry.contribution.discard) discarded.push(entry.contribution.discard());
3850
+ if (entry.contribution.discard) discarded.push(entry.contribution.discard(entry === taken.entry ? buildFailure : void 0));
3793
3851
  }
3794
3852
  }
3795
3853
  for (const generation of completedGenerations) this.#retireDeploymentGeneration(generation);
@@ -3833,9 +3891,9 @@ var ProviderOutputCatalog = class {
3833
3891
  if (reference) this.#deploymentGenerations.delete(reference);
3834
3892
  this.#deploymentGenerationRefs.delete(generation);
3835
3893
  }
3836
- #queueDeploymentDiscard(entry) {
3894
+ #queueDeploymentDiscard(entry, failure) {
3837
3895
  if (!entry.contribution.discard) return;
3838
- const discard = Promise.resolve().then(entry.contribution.discard);
3896
+ const discard = Promise.resolve().then(async () => await entry.contribution.discard?.(failure));
3839
3897
  discard.catch(() => {});
3840
3898
  this.#pendingDeploymentDiscards.push(discard);
3841
3899
  }
@@ -4680,23 +4738,23 @@ async function resetProviderDeploymentOutputs(catalog, failure, generation) {
4680
4738
  if (!catalog) return;
4681
4739
  const completedReset = providerDeploymentOutputCompletedResets.get(catalog);
4682
4740
  if (completedReset && failure !== void 0 && completedReset.failures.has(failure)) {
4683
- if (generation) catalog.resetDeploymentContributions(generation);
4741
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
4684
4742
  await completedReset.promise;
4685
4743
  return;
4686
4744
  }
4687
4745
  if (completedReset) providerDeploymentOutputCompletedResets.delete(catalog);
4688
- if (generation) catalog.resetDeploymentContributions(generation);
4746
+ if (generation) catalog.resetDeploymentContributions(generation, failure);
4689
4747
  const active = providerDeploymentOutputFinalizations.get(catalog);
4690
4748
  if (active?.reset) {
4691
4749
  if (failure !== void 0 && !active.reset.failures.has(failure)) {
4692
4750
  active.reset.failures.add(failure);
4693
- if (!generation) catalog.resetDeploymentContributions();
4751
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
4694
4752
  }
4695
4753
  providerDeploymentOutputCompletedResets.set(catalog, active.reset);
4696
4754
  await active.reset.promise;
4697
4755
  return;
4698
4756
  }
4699
- if (!generation) catalog.resetDeploymentContributions();
4757
+ if (!generation) catalog.resetDeploymentContributions(void 0, failure);
4700
4758
  if (active && (!generation || active.state.generations.has(generation))) {
4701
4759
  active.state.rollback = true;
4702
4760
  active.controller.abort(internalErrorDiagnostics.INTERNAL_B0039({ message: "Provider Output finalization reset" }));
@@ -4845,7 +4903,7 @@ async function finalizeProviderDeploymentOutputs(catalog, options = {}) {
4845
4903
  await catalog.completeDeploymentContributions(contributions);
4846
4904
  } catch (error) {
4847
4905
  if (state.rollback) catalog.rollbackDeploymentContributions(contributions);
4848
- else await catalog.completeDeploymentContributions(contributions);
4906
+ else await catalog.completeDeploymentContributions(contributions, error);
4849
4907
  throw error;
4850
4908
  } finally {
4851
4909
  state.generations.clear();
@@ -5245,6 +5303,13 @@ function readProviderErrorCodes(body) {
5245
5303
  function isShellSafeProvisionValue(value) {
5246
5304
  return /^[A-Za-z0-9][\w.-]*$/.test(value);
5247
5305
  }
5306
+ /**
5307
+ * The warning of a Cloudflare Provision Step that skips without credentials. `vitehub provision` and `vitehub deploy`
5308
+ * read a `wrangler login` of the Wrangler installed in the project, so the warning names it.
5309
+ */
5310
+ function cloudflareProvisionSkipWarning(skipping) {
5311
+ return `${skipping}, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN. Install Wrangler in the project and run \`npx wrangler login\`, or set both variables. With more than one Cloudflare account, also set CLOUDFLARE_ACCOUNT_ID.`;
5312
+ }
5248
5313
  function resolveCloudflareProvisionConfig(env) {
5249
5314
  const credentials = readHostCredentialsFromEnv("cloudflare", env);
5250
5315
  if (!credentials?.accountId) return;
@@ -5439,7 +5504,7 @@ function createKVCloudflareProvisionStep(resolveOptions) {
5439
5504
  if (!storesByNamespace.size) return [];
5440
5505
  const config = resolveCloudflareProvisionConfig(context.env);
5441
5506
  if (!config) {
5442
- context.logger.warn("kv: skipping Cloudflare KV, missing CLOUDFLARE_ACCOUNT_ID/CLOUDFLARE_API_TOKEN.");
5507
+ context.logger.warn(cloudflareProvisionSkipWarning("kv: skipping Cloudflare KV"));
5443
5508
  context.markPlanUnchecked?.();
5444
5509
  return [];
5445
5510
  }
@@ -5460,7 +5525,7 @@ function createKVCloudflareProvisionStep(resolveOptions) {
5460
5525
  }
5461
5526
  // src/deployment-env.ts
5462
5527
  const owners = ["kv"];
5463
- const maskedRuntimeValue = "********";
5528
+ const maskedRuntimeValue$1 = "********";
5464
5529
  function entry(names) {
5465
5530
  return {
5466
5531
  names,
@@ -5471,7 +5536,7 @@ function entry(names) {
5471
5536
  };
5472
5537
  }
5473
5538
  function storeEntries(store) {
5474
- if (store.driver === "upstash") return [...store.url === maskedRuntimeValue ? [entry(upstashUrlEnvNames)] : [], ...store.token === maskedRuntimeValue ? [entry(upstashTokenEnvNames)] : []];
5539
+ if (store.driver === "upstash") return [...store.url === maskedRuntimeValue$1 ? [entry(upstashUrlEnvNames)] : [], ...store.token === maskedRuntimeValue$1 ? [entry(upstashTokenEnvNames)] : []];
5475
5540
  if (store.driver === "redis" && store.url.startsWith("env:")) return [entry([store.url.slice(4)])];
5476
5541
  return [];
5477
5542
  }
@@ -5483,6 +5548,39 @@ function kvDeploymentEnv(config) {
5483
5548
  if (!config) return [];
5484
5549
  return Object.values(config.stores ?? { default: config.store }).flatMap(storeEntries);
5485
5550
  }
5551
+ // src/server-env.ts
5552
+ const maskedRuntimeValue = "********";
5553
+ function storeFields(name, store) {
5554
+ const label = name === "default" ? "the default KV store" : `the ${name} KV store`;
5555
+ if (store.driver === "upstash") return {
5556
+ ...store.url === maskedRuntimeValue ? { url: {
5557
+ names: upstashUrlEnvNames,
5558
+ secret: true,
5559
+ description: `The Upstash REST URL of ${label}.`
5560
+ } } : {},
5561
+ ...store.token === maskedRuntimeValue ? { token: {
5562
+ names: upstashTokenEnvNames,
5563
+ secret: true,
5564
+ description: `The Upstash REST token of ${label}.`
5565
+ } } : {}
5566
+ };
5567
+ if (store.driver === "redis" && store.url.startsWith("env:")) return { url: {
5568
+ names: [store.url.slice(4)],
5569
+ secret: true,
5570
+ description: `The Redis URL of ${label}.`
5571
+ } };
5572
+ return {};
5573
+ }
5574
+ /** The Server Env fields of the KV stores, by store name, so Setup pages show them. The same variables as `kvDeploymentEnv()`. */
5575
+ function kvServerEnv(config) {
5576
+ if (!config) return {};
5577
+ const fields = {};
5578
+ for (const [name, store] of Object.entries(config.stores ?? { default: config.store })) {
5579
+ const group = storeFields(name, store);
5580
+ if (Object.keys(group).length) fields[name] = group;
5581
+ }
5582
+ return fields;
5583
+ }
5486
5584
  // src/vite.ts
5487
5585
  const operationsModule = ownModule(import.meta.url, "operations");
5488
5586
  const RESOLVED_KV_VIRTUAL_CONFIG_ID = `\0${KV_VIRTUAL_CONFIG_ID}`;
@@ -5615,7 +5713,7 @@ function createCloudflareKVWranglerConfig(kv, provisionState) {
5615
5713
  function serializeCloudflareRuntime(config) {
5616
5714
  return [
5617
5715
  `import { createCloudflareKVStorage } from ${JSON.stringify(CLOUDFLARE_KV_RUNTIME_IMPORT_ID)};`,
5618
- `import { kvClearOptionsError, kvInvalidLimitError, kvKeyLimitCodes, kvListLimitInvalid, kvResult, kvSetCodes, kvSetTTL, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, listKVKeys } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
5716
+ `import { kvClearOptionsError, kvInvalidKeyError, kvInvalidLimitError, kvKeyLimitCodes, kvListLimitInvalid, kvResult, kvSetCodes, kvSetTTL, kvStoreNotFoundError, kvStoreWithMode, kvUnsupportedOperationError, listKVKeys } from ${JSON.stringify(KV_ERRORS_IMPORT_ID)};`,
5619
5717
  "",
5620
5718
  `const kvConfig = ${JSON.stringify(config, null, 2)}`,
5621
5719
  "const storages = new Map();",
@@ -5641,6 +5739,12 @@ function serializeCloudflareRuntime(config) {
5641
5739
  " return storage;",
5642
5740
  "}",
5643
5741
  "",
5742
+ "async function keyedKVResult(operation, name, keys, run, codes) {",
5743
+ " const error = kvInvalidKeyError(keys);",
5744
+ " if (error) return [error, undefined];",
5745
+ " return kvResult(operation, name, run, codes);",
5746
+ "}",
5747
+ "",
5644
5748
  "function unsupported(operation, name) {",
5645
5749
  " resolveStoreConfig(name);",
5646
5750
  " return [kvUnsupportedOperationError(operation, name), undefined];",
@@ -5654,17 +5758,17 @@ function serializeCloudflareRuntime(config) {
5654
5758
  " if (error) return [error, undefined];",
5655
5759
  " return kvResult(\"clear\", name, async () => { await resolveStorage(name).clear(options?.prefix); });",
5656
5760
  " },",
5657
- " async delete(key, options) { return kvResult(\"delete\", name, async () => { await resolveStorage(name).removeItem(key, options); }, kvKeyLimitCodes); },",
5761
+ " async delete(key, options) { return keyedKVResult(\"delete\", name, [key], async () => { await resolveStorage(name).removeItem(key, options); }, kvKeyLimitCodes); },",
5658
5762
  " async deleteIfEquals() { return unsupported(\"deleteIfEquals\", name); },",
5659
- " async get(key, options) { return kvResult(\"get\", name, () => resolveStorage(name).getItem(key, options), kvKeyLimitCodes); },",
5763
+ " async get(key, options) { return keyedKVResult(\"get\", name, [key], () => resolveStorage(name).getItem(key, options), kvKeyLimitCodes); },",
5660
5764
  " async getAndDelete() { return unsupported(\"getAndDelete\", name); },",
5661
- " async getMany(keys, options) { return kvResult(\"getMany\", name, () => resolveStorage(name).getMany(keys, options), kvKeyLimitCodes); },",
5662
- " async has(key, options) { return kvResult(\"has\", name, () => resolveStorage(name).hasItem(key, options), kvKeyLimitCodes); },",
5765
+ " async getMany(keys, options) { return keyedKVResult(\"getMany\", name, keys, () => resolveStorage(name).getMany(keys, options), kvKeyLimitCodes); },",
5766
+ " async has(key, options) { return keyedKVResult(\"has\", name, [key], () => resolveStorage(name).hasItem(key, options), kvKeyLimitCodes); },",
5663
5767
  " async increment() { return unsupported(\"increment\", name); },",
5664
5768
  " lock() { return { async acquire() { return unsupported(\"lock\", name); }, async run() { return unsupported(\"lock\", name); } }; },",
5665
5769
  " async list(options = {}) { if (kvListLimitInvalid(options)) return [kvInvalidLimitError(), undefined]; return kvResult(\"list\", name, () => listKVKeys(page => resolveStorage(name).listKeys(page), options), [\"KV_INVALID_CURSOR\"]); },",
5666
- " async set(key, value, options) { return kvResult(\"set\", name, async () => { const storage = resolveStorage(name); const ttl = kvSetTTL(\"set\", options); await storage.setItem(key, value, ttl === undefined ? undefined : { ttl }); }, kvSetCodes); },",
5667
- " async setMany(entries, options) { return kvResult(\"setMany\", name, async () => { const storage = resolveStorage(name); const ttl = kvSetTTL(\"setMany\", options); await storage.setMany(entries, ttl === undefined ? undefined : { ttl }); }, kvSetCodes); },",
5770
+ " async set(key, value, options) { return keyedKVResult(\"set\", name, [key], async () => { const storage = resolveStorage(name); const ttl = kvSetTTL(\"set\", options); await storage.setItem(key, value, ttl === undefined ? undefined : { ttl }); }, kvSetCodes); },",
5771
+ " async setMany(entries, options) { return keyedKVResult(\"setMany\", name, Array.isArray(entries) ? entries.map(entry => Reflect.get(Object(entry), \"key\")) : entries, async () => { const storage = resolveStorage(name); const ttl = kvSetTTL(\"setMany\", options); await storage.setMany(entries, ttl === undefined ? undefined : { ttl }); }, kvSetCodes); },",
5668
5772
  " async setIfAbsent() { return unsupported(\"setIfAbsent\", name); },",
5669
5773
  " store(storeName, options) { return kvStoreWithMode(createKVStorage(storeName), options); },",
5670
5774
  " };",
@@ -5735,21 +5839,25 @@ function configureNitroCloudflareKV(config, options, input, ownedNamespaces, pro
5735
5839
  }
5736
5840
  return true;
5737
5841
  }
5738
- /** `input.hosting` names the host preset for driver inference, as `vitehub()` passes it. Without it, KV reads the host from env. */
5842
+ /** KV infers its driver from Nitro's preset, the supplied host, or the host environment. */
5739
5843
  function hubKV(options, input = {}) {
5740
5844
  let command = "build";
5741
5845
  let mode = "development";
5742
5846
  let viteEnv;
5743
5847
  let databasePlugin;
5744
5848
  const databaseImport = input.databaseImport ?? "@vite-hub/database/runtime/registry";
5745
- const postgresDatabase = () => databasePlugin?.api?.getConfig?.()?.databases.default?.dialect === "postgresql";
5849
+ const databaseConfig = (name) => databasePlugin?.api?.getConfig?.()?.databases[name];
5850
+ const postgresDatabase = () => databaseConfig("default")?.dialect === "postgresql" && databaseConfig("default")?.driver !== "drizzle-postgres";
5851
+ let configuredHosting = input.hosting;
5852
+ const hosting = () => resolvedNitroPreset ?? configuredHosting;
5746
5853
  const resolutionInput = () => ({
5747
5854
  dev: command === "serve",
5748
5855
  env: command === "serve" ? viteEnv : void 0,
5749
- hosting: input.hosting,
5856
+ hosting: hosting(),
5750
5857
  postgresDatabase: postgresDatabase()
5751
5858
  });
5752
5859
  let nitroOwned = false;
5860
+ let resolvedNitroPreset;
5753
5861
  let nitroOptions;
5754
5862
  const ownedNitroNamespaces = /* @__PURE__ */ new Set();
5755
5863
  let resolved;
@@ -5775,7 +5883,7 @@ function hubKV(options, input = {}) {
5775
5883
  api: {
5776
5884
  deploymentEnv: () => kvDeploymentEnv(getConfig().kv),
5777
5885
  getBuildConfig: () => resolveKVViteConfig(options, {
5778
- hosting: input.hosting,
5886
+ hosting: hosting(),
5779
5887
  postgresDatabase: postgresDatabase()
5780
5888
  }),
5781
5889
  getConfig
@@ -5783,12 +5891,23 @@ function hubKV(options, input = {}) {
5783
5891
  nitro: {
5784
5892
  name: "@vite-hub/kv/cloudflare-bindings",
5785
5893
  setup(nitro) {
5894
+ if (nitro.options.preset === "nitro-prerender") {
5895
+ configureNitroStorage(nitro.options, resolveKVViteConfig(options, {
5896
+ hosting: hosting(),
5897
+ prerender: true
5898
+ }).kv);
5899
+ return;
5900
+ }
5786
5901
  nitroOptions = nitro.options;
5902
+ if (!nitro.options.dev && nitro.options.preset !== resolvedNitroPreset) {
5903
+ resolvedNitroPreset = nitro.options.preset;
5904
+ runtimeConfig = void 0;
5905
+ }
5787
5906
  if (runtimeConfig) reconcileNitroCloudflareKV(nitroOptions, runtimeConfig.kv, ownedNitroNamespaces, readProvisionStateSync(projectRoot));
5788
5907
  else configureNitroStorage(nitroOptions, resolveKVViteConfig(options, resolutionInput()).kv);
5789
5908
  nitro.hooks?.hook("prerender:config", (config) => {
5790
5909
  const prerender = resolveKVViteConfig(options, {
5791
- hosting: input.hosting,
5910
+ hosting: hosting(),
5792
5911
  prerender: true
5793
5912
  });
5794
5913
  if (prerender.kv && Object.values({
@@ -5825,13 +5944,13 @@ function hubKV(options, input = {}) {
5825
5944
  },
5826
5945
  inspect: () => {
5827
5946
  const build = resolveKVViteConfig(options, {
5828
- hosting: input.hosting,
5947
+ hosting: hosting(),
5829
5948
  postgresDatabase: postgresDatabase()
5830
5949
  }).kv;
5831
5950
  const dev = resolveKVViteConfig(options, {
5832
5951
  dev: true,
5833
5952
  env: viteEnv,
5834
- hosting: input.hosting
5953
+ hosting: hosting()
5835
5954
  }).kv;
5836
5955
  if (!build || !dev) return;
5837
5956
  const file = resolved?.configFile ? relativeDefinitionFile(projectRoot, resolved.configFile) : "vite.config.ts";
@@ -5865,11 +5984,22 @@ function hubKV(options, input = {}) {
5865
5984
  async handler(config, env) {
5866
5985
  if (env) markViteConfigPlugin(env, KV_VITE_PLUGIN_NAME);
5867
5986
  command = env?.command ?? "build";
5987
+ configuredHosting = resolveHostPreset({
5988
+ hosting: input.hosting,
5989
+ nitro: Reflect.get(config, "nitro"),
5990
+ env: {}
5991
+ });
5992
+ resolvedNitroPreset = void 0;
5868
5993
  mode = env?.mode ?? config.mode ?? (command === "serve" ? "development" : "production");
5869
5994
  runtimeConfig = void 0;
5870
5995
  projectRoot = resolveViteHubProjectRoot(config.root || process.cwd());
5871
5996
  viteEnv = loadAllEnv((await import("vite")).loadEnv, mode, config.envDir === false ? false : resolve(config.root || process.cwd(), config.envDir ?? "."));
5872
5997
  nitroOwned = configureNitroCloudflareKV(config, options, resolutionInput(), ownedNitroNamespaces, readProvisionStateSync(projectRoot));
5998
+ const inspectedKV = Reflect.get(config, "vitehubCliDiscovery") === true && mode !== "development" ? resolveKVViteConfig(options, {
5999
+ hosting: hosting(),
6000
+ postgresDatabase: postgresDatabase()
6001
+ }).kv : getConfig().kv;
6002
+ contributeServerEnv(config, "kv", kvServerEnv(inspectedKV));
5873
6003
  return installStandaloneOperationRpc(config, env?.command ?? "build", operationsModule);
5874
6004
  }
5875
6005
  },
@@ -5944,6 +6074,10 @@ function hubKV(options, input = {}) {
5944
6074
  runtimeConfig = void 0;
5945
6075
  providerOutputGenerations.capture(this, providerOutput);
5946
6076
  if (command !== "build" || !resolved) return;
6077
+ for (const store of kvStores(getConfig().kv)) if (store.driver === "database" && databaseConfig(store.database)?.driver === "drizzle-postgres") throw kvErrorDiagnostics.KV_DATABASE_UNAVAILABLE({
6078
+ database: store.database,
6079
+ problem: "driver"
6080
+ });
5947
6081
  reportRedisEnvHint(resolved);
5948
6082
  }
5949
6083
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/kv",
3
- "version": "0.6.0",
3
+ "version": "0.7.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.6.0",
73
+ "@vite-hub/runtime": "0.7.0",
74
74
  "birpc": "^4.2.0",
75
75
  "defu": "^6.1.7",
76
76
  "destr": "^2.0.5",
@@ -82,11 +82,15 @@
82
82
  },
83
83
  "devDependencies": {
84
84
  "@types/node": "^24.19.2",
85
+ "@electric-sql/pglite": "^0.5.17",
85
86
  "@libsql/client": "^0.18.0",
86
- "@vite-hub/database": "0.6.0",
87
+ "@vite-hub/database": "0.7.0",
88
+ "@types/pg": "^8.23.1",
87
89
  "@types/proper-lockfile": "4.1.4",
88
90
  "@vite-hub/internal": "0.0.1",
91
+ "miniflare": "4.20260730.0",
89
92
  "ofetch": "^1.5.1",
93
+ "pg": "^8.23.1",
90
94
  "postgres": "^3.4.9",
91
95
  "publint": "^0.3.25",
92
96
  "typescript": "^6.0.3",
@@ -96,7 +100,7 @@
96
100
  },
97
101
  "peerDependencies": {
98
102
  "@upstash/redis": "^1.41.0",
99
- "@vite-hub/database": "0.6.0",
103
+ "@vite-hub/database": "0.7.0",
100
104
  "vite": ">=8.0.0"
101
105
  },
102
106
  "peerDependenciesMeta": {
@@ -1 +0,0 @@
1
- export { t as default } from "./fs-lite-DzTTR6R3.js";