@vite-hub/kv 0.0.4 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +110 -14
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +17 -0
  5. package/dist/cli.js +469 -0
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
  9. package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
  10. package/dist/config-BXEVoZE3.js +250 -0
  11. package/dist/{dist-DDW1iC5f.js → create-storage-BGsrQKw3.js} +266 -115
  12. package/dist/cursor-history-BqIQePNP.js +165 -0
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/deno-kv-BM9mYdUp.js +128 -0
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-BwxgaQ-f.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-BxqvtEIb.js +147 -0
  20. package/dist/errors-DbwufFZp.js +60 -0
  21. package/dist/errors.d.ts +23 -7
  22. package/dist/errors.js +2 -20
  23. package/dist/fs-lite-BLZId9_P.js +386 -0
  24. package/dist/fs-lite-RAoxu8L0.js +2 -0
  25. package/dist/index.d.ts +10 -4
  26. package/dist/index.js +364 -109
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/main-F3Y22_uV.js +2353 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/operations-Ch-gKaey.js +441 -0
  34. package/dist/operations.d.ts +75 -0
  35. package/dist/operations.js +318 -0
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/results-p7nPCnaJ.js +6 -0
  38. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  39. package/dist/runtime/cloudflare-kv.d.ts +3 -4
  40. package/dist/runtime/cloudflare-kv.js +1 -23
  41. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  42. package/dist/runtime/cloudflare-request-env.js +11 -0
  43. package/dist/runtime/nitro-plugin.d.ts +12 -0
  44. package/dist/runtime/nitro-plugin.js +22 -0
  45. package/dist/runtime/redis-driver.d.ts +11 -0
  46. package/dist/runtime/redis-driver.js +113 -0
  47. package/dist/runtime/unstorage-driver.d.ts +14 -0
  48. package/dist/runtime/unstorage-driver.js +33 -0
  49. package/dist/runtime/upstash-driver.d.ts +4 -6
  50. package/dist/runtime/upstash-driver.js +60 -110
  51. package/dist/{driver-BT9WefKi.d.ts → types-Bj3EQoRg.d.ts} +16 -11
  52. package/dist/types-DEiKew_3.d.ts +312 -0
  53. package/dist/upstash-DDlqTttY.js +40 -0
  54. package/dist/utils2-FozcTsmb.js +31 -0
  55. package/dist/virtual-module.d.ts +2 -0
  56. package/dist/virtual.d.ts +1 -1
  57. package/dist/vite.d.ts +159 -14
  58. package/dist/vite.js +1329 -2898
  59. package/package.json +68 -19
  60. package/dist/config-aM9Ae7tH.js +0 -110
  61. package/dist/deno-kv-cJx3jU10.js +0 -69
  62. package/dist/fs-lite-BxzdiJSi.js +0 -79
  63. package/dist/types-CO0DRjJa.d.ts +0 -78
@@ -0,0 +1,187 @@
1
+ import { t as invariant } from "./invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
3
+ import { t as getActiveCloudflareBinding } from "./cloudflare-env-lOtHHsgP.js";
4
+ import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-BGsrQKw3.js";
5
+ import { i as setItemsOneByOne, t as chunks } from "./batch--v0ri69O.js";
6
+ import { n as recordCursor, t as createCursorHistory } from "./cursor-history-BqIQePNP.js";
7
+ import createDriver from "unstorage/drivers/cloudflare-kv-binding";
8
+ //#region src/runtime/cloudflare-kv-limits.ts
9
+ const cloudflareKVLimits = {
10
+ keyBytes: 512,
11
+ minExpirationTtl: 60,
12
+ valueBytes: 26214400
13
+ };
14
+ const encoder = /*#__PURE__*/ new TextEncoder();
15
+ /** Returns the UTF-8 size of `value` when it is above `limit`. */
16
+ function bytesAbove(value, limit) {
17
+ if (value.length * 3 <= limit) return;
18
+ const bytes = encoder.encode(value).byteLength;
19
+ return bytes > limit ? bytes : void 0;
20
+ }
21
+ function assertCloudflareKVKey(key) {
22
+ const bytes = bytesAbove(key, cloudflareKVLimits.keyBytes);
23
+ if (bytes !== void 0) throw kvErrorDiagnostics.KV_KEY_TOO_LONG({
24
+ bytes,
25
+ limit: cloudflareKVLimits.keyBytes
26
+ });
27
+ }
28
+ /** Checks a `put()` before the binding gets it. `value` is the string that unstorage serialized. */
29
+ function assertCloudflareKVWrite(key, value) {
30
+ assertCloudflareKVKey(key);
31
+ const valueBytes = typeof value === "string" ? bytesAbove(value, cloudflareKVLimits.valueBytes) : void 0;
32
+ if (valueBytes !== void 0) throw kvErrorDiagnostics.KV_VALUE_TOO_LARGE({
33
+ bytes: valueBytes,
34
+ limit: cloudflareKVLimits.valueBytes
35
+ });
36
+ }
37
+ /** Cloudflare KV rejects an expiration below 60 seconds, so a shorter `ttl` becomes 60 seconds, also on the local store of `vite dev`. */
38
+ function cloudflareKVSetOptions(options) {
39
+ const ttl = options?.ttl;
40
+ return typeof ttl === "number" ? { ttl: Math.max(cloudflareKVLimits.minExpirationTtl, ttl) } : options;
41
+ }
42
+ /** Rejects what a Cloudflare KV binding rejects before the driver call, so every store returns the same named code. */
43
+ function installCloudflareKVLimits(driver) {
44
+ const { getItem, hasItem, removeItem, setItem } = driver;
45
+ driver.getItem = (key, options) => {
46
+ assertCloudflareKVKey(key);
47
+ return getItem.call(driver, key, options);
48
+ };
49
+ driver.hasItem = (key, options) => {
50
+ assertCloudflareKVKey(key);
51
+ return hasItem.call(driver, key, options);
52
+ };
53
+ if (removeItem) driver.removeItem = (key, options) => {
54
+ assertCloudflareKVKey(key);
55
+ return removeItem.call(driver, key, options);
56
+ };
57
+ if (setItem) driver.setItem = (key, value, options) => {
58
+ assertCloudflareKVWrite(key, value);
59
+ return setItem.call(driver, key, value, cloudflareKVSetOptions(options));
60
+ };
61
+ }
62
+ /** Preflight serialized writes and deletion keys before either branch starts. */
63
+ function validateCloudflareKVBatch(items, removals) {
64
+ for (const key of removals) assertCloudflareKVKey(key);
65
+ for (const item of items) assertCloudflareKVWrite(item.key, item.value);
66
+ }
67
+ //#endregion
68
+ //#region src/runtime/cloudflare-kv.ts
69
+ function isCloudflareKVString(value) {
70
+ return typeof value === "string";
71
+ }
72
+ function isCloudflareKVListPage(value) {
73
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
74
+ const page = value;
75
+ if (typeof page.list_complete !== "boolean" || !Array.isArray(page.keys)) return false;
76
+ if (!page.keys.every((key) => {
77
+ if (!key || typeof key !== "object" || Array.isArray(key)) return false;
78
+ return isCloudflareKVString(Reflect.get(key, "name"));
79
+ })) return false;
80
+ return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
81
+ }
82
+ /** Cloudflare reads at most 100 keys in one bulk `get()`. */
83
+ const cloudflareKVBulkGetKeys = 100;
84
+ const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
85
+ let nextCloudflareBindingIdentity = 0;
86
+ function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
87
+ if (typeof namespaceId === "string" && namespaceId.length > 0) return `cloudflare-kv:id:${namespaceId}`;
88
+ if (binding && typeof binding === "object") {
89
+ let identity = cloudflareBindingIdentities.get(binding);
90
+ if (identity === void 0) {
91
+ identity = ++nextCloudflareBindingIdentity;
92
+ cloudflareBindingIdentities.set(binding, identity);
93
+ }
94
+ return `cloudflare-kv:object:${identity}`;
95
+ }
96
+ return typeof bindingName === "string" ? `cloudflare-kv:binding:${bindingName}` : "cloudflare-kv:default";
97
+ }
98
+ function createCloudflareDriver(options) {
99
+ const bindingName = options.binding;
100
+ const namespaceId = options.namespaceId;
101
+ const driverOptions = typeof bindingName === "string" ? {
102
+ ...options,
103
+ get binding() {
104
+ return getActiveCloudflareBinding(bindingName) ?? bindingName;
105
+ }
106
+ } : options;
107
+ const driver = createDriver(driverOptions);
108
+ installCloudflareKVLimits(driver);
109
+ driver.validateBatch = validateCloudflareKVBatch;
110
+ driver.getItems = async (items) => {
111
+ for (const item of items) assertCloudflareKVKey(item.key);
112
+ const values = /* @__PURE__ */ new Map();
113
+ for (const batch of chunks([...new Set(items.map((item) => item.key))], cloudflareKVBulkGetKeys)) {
114
+ const page = await (await driver.getInstance()).get(batch, "text");
115
+ if (!(page instanceof Map)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV bulk get did not return a Map." });
116
+ for (const key of batch) {
117
+ const value = page.get(key);
118
+ values.set(key, typeof value === "string" ? value : null);
119
+ }
120
+ }
121
+ return items.map((item) => ({
122
+ key: item.key,
123
+ value: values.get(item.key) ?? null
124
+ }));
125
+ };
126
+ const setItemsOneByOneWithLimits = setItemsOneByOne(driver);
127
+ driver.setItems = async (items, commonOptions) => {
128
+ for (const item of items) assertCloudflareKVWrite(item.key, item.value);
129
+ await setItemsOneByOneWithLimits(items, commonOptions);
130
+ };
131
+ const cursorNamespace = cloudflareBindingNamespace(bindingName, namespaceId);
132
+ const cursorHistories = createCursorHistory(cursorNamespace);
133
+ let disposed = false;
134
+ const dispose = driver.dispose;
135
+ driver.dispose = async () => {
136
+ disposed = true;
137
+ cursorHistories.clear();
138
+ try {
139
+ await dispose?.call(driver);
140
+ } finally {
141
+ cursorHistories.clear();
142
+ }
143
+ };
144
+ driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
145
+ invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
146
+ const listOptions = { limit };
147
+ if (cursor) listOptions.cursor = cursor;
148
+ if (prefix) listOptions.prefix = prefix;
149
+ const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
150
+ const requestNamespace = cloudflareBindingNamespace(bindingName, namespaceId, activeBinding);
151
+ const continuation = cursor ? cursorHistories.take(cursor, requestNamespace) : {
152
+ providerCursor: void 0,
153
+ history: /* @__PURE__ */ new Set(),
154
+ namespace: requestNamespace
155
+ };
156
+ try {
157
+ if (continuation.providerCursor) listOptions.cursor = continuation.providerCursor;
158
+ const cursors = continuation.history;
159
+ const page = await driver.getInstance().list(listOptions);
160
+ if (!isCloudflareKVListPage(page)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV list returned an invalid page." });
161
+ const result = { keys: page.keys.map((key) => key.name) };
162
+ if (!page.list_complete) {
163
+ invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
164
+ if (cursors.has(page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a repeated pagination cursor." });
165
+ if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected pagination after the cursor history limit was reached." });
166
+ result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
167
+ }
168
+ cursorHistories.complete(cursor);
169
+ return result;
170
+ } catch (error) {
171
+ if (cursor && !disposed) cursorHistories.restore(cursor, continuation);
172
+ throw error;
173
+ }
174
+ };
175
+ return driver;
176
+ }
177
+ function createCloudflareKVStorage(options) {
178
+ const driver = createCloudflareDriver(options);
179
+ const storage = createKVStorage(driver);
180
+ storage.listKeys = (listOptions) => driver.listKeys({
181
+ ...listOptions,
182
+ prefix: normalizeKVListPrefix(listOptions.prefix)
183
+ });
184
+ return storage;
185
+ }
186
+ //#endregion
187
+ export { validateCloudflareKVBatch as a, installCloudflareKVLimits as i, createCloudflareKVStorage as n, assertCloudflareKVWrite as r, createCloudflareDriver as t };
@@ -0,0 +1,71 @@
1
+ import { t as getActiveCloudflareBinding } from "./cloudflare-env-lOtHHsgP.js";
2
+ import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch--v0ri69O.js";
3
+ import { a as validateCloudflareKVBatch, i as installCloudflareKVLimits, r as assertCloudflareKVWrite, t as createCloudflareDriver } from "./cloudflare-kv-BIEUFzRT.js";
4
+ import { t as createFsLiteKVDriver } from "./fs-lite-BLZId9_P.js";
5
+ //#region src/runtime/cloudflare-kv-local.ts
6
+ /**
7
+ * Seconds until the key expires, as the binding computes them from unstorage's options: `ttl` becomes an
8
+ * `expirationTtl` of at least 60 seconds, and a relative expiration wins over the absolute `expiration`.
9
+ */
10
+ function cloudflareExpirationSeconds(options) {
11
+ if (!options || typeof options !== "object") return;
12
+ const ttl = Reflect.get(options, "ttl");
13
+ const put = {
14
+ expirationTtl: typeof ttl === "number" && ttl ? Math.max(ttl, 60) : void 0,
15
+ ...options
16
+ };
17
+ if (typeof put.expirationTtl === "number") return put.expirationTtl;
18
+ if (typeof put.expiration === "number") return put.expiration - Date.now() / 1e3;
19
+ }
20
+ /**
21
+ * A Cloudflare KV store in `vite dev`. It uses the binding when the runtime has one, for example on the workerd
22
+ * runner. Otherwise, for example on Nitro's default Node runner, it uses a local `fs-lite` store with the Workers KV limits and expirations.
23
+ */
24
+ function createCloudflareKVLocalDriver(store) {
25
+ const binding = createCloudflareDriver({
26
+ binding: store.binding,
27
+ namespaceId: store.namespaceId
28
+ });
29
+ let localPromise;
30
+ const pick = async () => {
31
+ if (getActiveCloudflareBinding(store.binding)) return binding;
32
+ return localPromise ??= createFsLiteKVDriver({
33
+ base: store.localBase,
34
+ driver: "fs-lite"
35
+ }).then((local) => {
36
+ const { setItem } = local;
37
+ local.setItem = (key, value, options) => setItem?.call(local, key, value, { ttl: cloudflareExpirationSeconds(options) });
38
+ installCloudflareKVLimits(local);
39
+ return local;
40
+ }).catch((error) => {
41
+ localPromise = void 0;
42
+ throw error;
43
+ });
44
+ };
45
+ return {
46
+ name: "cloudflare-kv-local",
47
+ validateBatch: validateCloudflareKVBatch,
48
+ options: store,
49
+ clear: async (base, options) => (await pick()).clear?.(base, options),
50
+ async dispose() {
51
+ await Promise.all([binding.dispose?.(), localPromise?.then((local) => local.dispose?.())]);
52
+ },
53
+ getItem: async (key, options) => (await pick()).getItem(key, options),
54
+ async getItems(items, options) {
55
+ const driver = await pick();
56
+ return (driver.getItems ?? getItemsOneByOne(driver))(items, options);
57
+ },
58
+ getKeys: async (base, options) => (await pick()).getKeys(base, options),
59
+ hasItem: async (key, options) => (await pick()).hasItem(key, options),
60
+ listKeys: async (options) => (await pick()).listKeys(options),
61
+ removeItem: async (key, options) => (await pick()).removeItem?.(key, options),
62
+ setItem: async (key, value, options) => (await pick()).setItem?.(key, value, options),
63
+ async setItems(items, options) {
64
+ for (const item of items) assertCloudflareKVWrite(item.key, item.value);
65
+ const driver = await pick();
66
+ return (driver.setItems ?? setItemsOneByOne(driver))(items, options);
67
+ }
68
+ };
69
+ }
70
+ //#endregion
71
+ export { createCloudflareKVLocalDriver as default };
@@ -0,0 +1,250 @@
1
+ import { t as isRecord } from "./object-Da1zyPCR.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
3
+ import { o as normalizeKey } from "./utils2-FozcTsmb.js";
4
+ import { defu } from "defu";
5
+ //#region ../internal/src/env.ts
6
+ function trimmed(value) {
7
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
8
+ }
9
+ function readEnv(env, ...names) {
10
+ for (const name of names) {
11
+ const value = trimmed(env[name]);
12
+ if (value) return value;
13
+ }
14
+ }
15
+ //#endregion
16
+ //#region ../internal/src/hosting.ts
17
+ /**
18
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
19
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
20
+ * Empty values are skipped.
21
+ */
22
+ function resolveHostPreset(input = {}) {
23
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
24
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
25
+ for (const value of [
26
+ nitroPreset,
27
+ input.hosting,
28
+ env.NITRO_PRESET,
29
+ env.SERVER_PRESET,
30
+ env.VITEHUB_HOST
31
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
32
+ }
33
+ function normalizeHosting(hosting) {
34
+ const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
35
+ if (normalized === "cloudflare") return "cloudflare-module";
36
+ return normalized;
37
+ }
38
+ //#endregion
39
+ //#region src/integrations/upstash.ts
40
+ const maskedUpstashRuntimeValue = "********";
41
+ /** Vercel names first, then the names that the Upstash console and NuxtHub use. */
42
+ const upstashUrlEnvNames = ["KV_REST_API_URL", "UPSTASH_REDIS_REST_URL"];
43
+ const upstashTokenEnvNames = ["KV_REST_API_TOKEN", "UPSTASH_REDIS_REST_TOKEN"];
44
+ function hasUpstashEnv(env) {
45
+ const url = readEnv(env, ...upstashUrlEnvNames);
46
+ const token = readEnv(env, ...upstashTokenEnvNames);
47
+ return Boolean(url && token);
48
+ }
49
+ /** `base` is the resolved key prefix of the store, never empty. */
50
+ function resolveUpstashStore(config, base) {
51
+ return {
52
+ driver: "upstash",
53
+ base,
54
+ token: trimmed(config.token) ?? maskedUpstashRuntimeValue,
55
+ url: trimmed(config.url) ?? maskedUpstashRuntimeValue
56
+ };
57
+ }
58
+ //#endregion
59
+ //#region src/config.ts
60
+ /** The variable that a `redis` store reads at runtime when it sets no `url`. */
61
+ const redisUrlEnvName = "REDIS_URL";
62
+ /** Where a Cloudflare KV store keeps its keys in `vite dev` when the runtime has no binding. */
63
+ function cloudflareKVLocalBase(binding) {
64
+ return `.vitehub/data/kv-cloudflare/${binding}`;
65
+ }
66
+ function readRemote(config, store) {
67
+ const remote = Reflect.get(config, "remote");
68
+ if (remote === void 0 || typeof remote === "boolean") return remote;
69
+ throw kvErrorDiagnostics.KV_INVALID_REMOTE({ store });
70
+ }
71
+ /** Applies `vite dev` mode: hosted stores are marked remote, and a Cloudflare store gets its local fallback. */
72
+ function resolveDevStore(store, remote) {
73
+ if (store.driver === "upstash") return {
74
+ ...store,
75
+ remote: true
76
+ };
77
+ if (store.driver !== "cloudflare") return store;
78
+ return remote ? {
79
+ ...store,
80
+ remote: true
81
+ } : {
82
+ ...store,
83
+ localBase: cloudflareKVLocalBase(store.binding)
84
+ };
85
+ }
86
+ /**
87
+ * The folder of an `fs-lite` store without `base`. The default store keeps `.vitehub/data/kv`. Each named store gets its
88
+ * own folder next to it, so stores never share keys. It is not inside `.vitehub/data/kv`, because the default store
89
+ * treats folders there as keys from the old layout.
90
+ */
91
+ function fsLiteStoreBase(name) {
92
+ if (name === "default") return ".vitehub/data/kv";
93
+ return `.vitehub/data/kv-stores/${encodeURIComponent(name).replace(/\./g, "%2E") || "%"}`;
94
+ }
95
+ function resolveFsLiteStore(config = {}, name = "default") {
96
+ return defu({ base: trimmed(config.base) }, {
97
+ driver: "fs-lite",
98
+ base: fsLiteStoreBase(name)
99
+ });
100
+ }
101
+ /** The key prefix of a Redis store without `base`. Every store has one, so a shared Redis keeps other keys apart. */
102
+ function redisStorePrefix(name) {
103
+ return `vitehub:kv:${name.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%"}`;
104
+ }
105
+ /** An empty prefix would let `kv.clear()` and `kv.keys()` reach every key of the Redis or Upstash database. */
106
+ function resolveStoreBase(base, name) {
107
+ return normalizeKey(trimmed(base)) || redisStorePrefix(name);
108
+ }
109
+ function resolveRedisStore(config, name) {
110
+ return {
111
+ driver: "redis",
112
+ base: resolveStoreBase(config.base, name),
113
+ url: trimmed(config.url) ?? `env:REDIS_URL`
114
+ };
115
+ }
116
+ function resolveDatabaseStore(config, name) {
117
+ return {
118
+ driver: "database",
119
+ database: trimmed(config.database) ?? "default",
120
+ namespace: name
121
+ };
122
+ }
123
+ function resolveCloudflareStore(config = {}, env = process.env) {
124
+ return defu({
125
+ binding: trimmed(config.binding),
126
+ namespaceId: trimmed(config.namespaceId) ?? readEnv(env, "KV_NAMESPACE_ID"),
127
+ namespaceName: trimmed(config.namespaceName)
128
+ }, {
129
+ driver: "cloudflare",
130
+ binding: "KV"
131
+ });
132
+ }
133
+ function resolveDenoStore(config = {}) {
134
+ const path = trimmed(config.path);
135
+ return path ? {
136
+ driver: "deno-kv",
137
+ path
138
+ } : { driver: "deno-kv" };
139
+ }
140
+ function resolveExplicitStore(store, env, name, dev) {
141
+ const remote = readRemote(store, name);
142
+ const { driver } = store;
143
+ if (dev && (remote === true && (driver === "fs-lite" || driver === "deno-kv") || remote === false && driver === "upstash")) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
144
+ driver,
145
+ remote,
146
+ store: name
147
+ });
148
+ const resolved = resolveStoreDriver(store, env, name);
149
+ return dev ? resolveDevStore(resolved, remote) : resolved;
150
+ }
151
+ function resolveStoreDriver(store, env, name) {
152
+ switch (store.driver) {
153
+ case "cloudflare": return resolveCloudflareStore(store, env);
154
+ case "database": return resolveDatabaseStore(store, name);
155
+ case "deno-kv": return resolveDenoStore(store);
156
+ case "fs-lite": return resolveFsLiteStore(store, name);
157
+ case "redis": return resolveRedisStore(store, name);
158
+ case "upstash": return resolveUpstashStore(store, resolveStoreBase(store.base, name));
159
+ default: {
160
+ const driver = store.driver;
161
+ throw kvErrorDiagnostics.KV_INVALID_DRIVER({
162
+ driver: JSON.stringify(driver) ?? String(driver),
163
+ renamed: renamedKVDrivers.get(String(driver))
164
+ });
165
+ }
166
+ }
167
+ }
168
+ /** Driver names that ViteHub renamed to the host name. `npx @vite-hub/codemods driver-key` moves them. */
169
+ const renamedKVDrivers = /* @__PURE__ */ new Map([["cloudflare-kv-binding", "cloudflare"]]);
170
+ function createResolvedConfig(store, stores) {
171
+ return stores ? {
172
+ store,
173
+ stores: {
174
+ default: store,
175
+ ...stores
176
+ }
177
+ } : { store };
178
+ }
179
+ function hasStoresConfig(options, stores) {
180
+ return !!options && Object.hasOwn(options, "stores") && isRecord(stores);
181
+ }
182
+ function normalizeKVOptions(options, input = {}) {
183
+ if (options === false) return;
184
+ if (typeof options !== "undefined" && !isRecord(options)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv" });
185
+ const env = input.env || process.env;
186
+ const hosting = normalizeHosting(input.hosting);
187
+ const explicit = options;
188
+ const hasOwnStores = options !== void 0 && Object.hasOwn(options, "stores");
189
+ const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
190
+ if (hasOwnStores && !isRecord(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
191
+ if (hasStoresConfig(options, stores)) {
192
+ const resolvedStores = Object.fromEntries(Object.entries(stores).map(([name, store]) => [name, resolveExplicitStore(store, env, name, input.dev)]));
193
+ const defaultStore = resolvedStores.default;
194
+ if (!defaultStore) throw kvErrorDiagnostics.KV_MISSING_DEFAULT_STORE();
195
+ return createResolvedConfig(defaultStore, resolvedStores);
196
+ }
197
+ if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env, "default", input.dev));
198
+ const remote = explicit ? readRemote(explicit, "default") : void 0;
199
+ const inferred = (store) => createResolvedConfig(input.dev ? resolveDevStore(store, remote) : store);
200
+ const hosted = !input.dev || remote === true;
201
+ if (hosting.includes("deno")) {
202
+ if (input.dev && remote === true) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
203
+ driver: "deno-kv",
204
+ remote,
205
+ store: "default"
206
+ });
207
+ return inferred(resolveDenoStore());
208
+ }
209
+ if (hosted && hasUpstashEnv(env)) return inferred(resolveUpstashStore({}, redisStorePrefix("default")));
210
+ if (hosted && hosting.includes("vercel")) return inferred(resolveUpstashStore({}, redisStorePrefix("default")));
211
+ if (hosting.includes("cloudflare")) return inferred(resolveCloudflareStore({}, env));
212
+ if (input.dev && remote === true) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
213
+ driver: "fs-lite",
214
+ remote,
215
+ store: "default"
216
+ });
217
+ if (input.dev) return inferred(resolveFsLiteStore());
218
+ if (input.postgresDatabase) return inferred({
219
+ ...resolveDatabaseStore({}, "default"),
220
+ inferred: true
221
+ });
222
+ return inferred({
223
+ ...resolveFsLiteStore(),
224
+ inferred: true
225
+ });
226
+ }
227
+ /** The line that a server prints at boot for its build-selected inferred store. */
228
+ function kvInferredStoreNotice(name, store) {
229
+ if (!("inferred" in store) || !store.inferred) return;
230
+ if (store.driver === "database") return `[vitehub] KV store "${name}" uses the table vitehub_kv of the Database "${store.database}", selected at build time.`;
231
+ if (store.driver === "fs-lite") return `[vitehub] KV store "${name}" uses fs-lite in ${store.base}, selected at build time. Other server processes cannot read its keys.`;
232
+ }
233
+ /**
234
+ * The build warning for a Redis URL that KV does not use. Redis is never inferred, because a `REDIS_URL` often belongs to
235
+ * another service, such as BullMQ or sessions. A NuxtHub app that kept its keys in Redis must select it.
236
+ */
237
+ function kvRedisEnvWarning(options, input = {}) {
238
+ if (options === false || input.dev || options && ("stores" in options || options.driver)) return;
239
+ const env = input.env || process.env;
240
+ const name = readEnv(env, "REDIS_URL") ? redisUrlEnvName : readEnv(env, "KV_URL")?.startsWith("rediss://") ? "KV_URL" : void 0;
241
+ if (!name) return;
242
+ const fix = `To keep KV in that Redis, set \`kv: { driver: "redis"${name === "REDIS_URL" ? "" : `, url: "env:${name}"`} }\`. To keep this store, set its \`driver\`.`;
243
+ const store = normalizeKVOptions(options, input)?.store;
244
+ if (store?.driver === "upstash" && !hasUpstashEnv(env)) return `[vitehub] KV on Vercel uses Upstash, and the build has no \`KV_REST_API_URL\` and \`KV_REST_API_TOKEN\`, so KV fails at runtime. The build has \`${name}\`, and KV does not select Redis on its own. ${fix}`;
245
+ const selected = store?.driver === "database" ? `the table vitehub_kv of the Database "${store.database}"` : store?.driver === "fs-lite" ? `fs-lite in ${store.base}` : void 0;
246
+ if (!selected) return;
247
+ return `[vitehub] The build has \`${name}\`, but KV does not select Redis on its own. The KV store "default" uses ${selected}. ${fix}`;
248
+ }
249
+ //#endregion
250
+ export { upstashUrlEnvNames as a, upstashTokenEnvNames as i, kvRedisEnvWarning as n, resolveHostPreset as o, normalizeKVOptions as r, readEnv as s, kvInferredStoreNotice as t };