@vite-hub/kv 0.1.0 → 0.4.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 (65) hide show
  1. package/README.md +94 -21
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +99 -77
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-C3NO4C21.js +201 -0
  9. package/dist/cloudflare-kv-local-C2sbIrFy.js +71 -0
  10. package/dist/config-LfpUj9hs.js +252 -0
  11. package/dist/{create-storage-29gMzf41.js → create-storage-BORQm2a8.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-DRHh5bO5.js} +31 -14
  13. package/dist/database-oJdy0ZVX.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-D_VtffFv.js} +12 -4
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-R4Z5Z5fl.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-C54QQEhN.js +155 -0
  20. package/dist/errors-DzD6YNEH.js +88 -0
  21. package/dist/errors.d.ts +17 -1
  22. package/dist/errors.js +2 -2
  23. package/dist/fs-lite-BAgpmNAF.js +2 -0
  24. package/dist/fs-lite-BaklCLuV.js +386 -0
  25. package/dist/index.d.ts +7 -2
  26. package/dist/index.js +326 -84
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/object-Da1zyPCR.js +11 -0
  30. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-nmRu_O3V.d.ts} +42 -15
  31. package/dist/{operations-pn8_eGob.js → operations-CtrWLmPK.js} +69 -66
  32. package/dist/operations-D2iI9oN4.js +1363 -0
  33. package/dist/operations.d.ts +15 -8
  34. package/dist/operations.js +56 -192
  35. package/dist/redis-shared-5ogRd3-Y.js +94 -0
  36. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  37. package/dist/runtime/cloudflare-kv.js +1 -99
  38. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  39. package/dist/runtime/cloudflare-request-env.js +11 -0
  40. package/dist/runtime/nitro-plugin.d.ts +12 -0
  41. package/dist/runtime/nitro-plugin.js +25 -0
  42. package/dist/runtime/redis-driver.d.ts +11 -0
  43. package/dist/runtime/redis-driver.js +113 -0
  44. package/dist/runtime/unstorage-driver.d.ts +14 -0
  45. package/dist/runtime/unstorage-driver.js +37 -0
  46. package/dist/runtime/upstash-driver.d.ts +2 -2
  47. package/dist/runtime/upstash-driver.js +58 -98
  48. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  49. package/dist/types-Dv-OSXZC.d.ts +325 -0
  50. package/dist/upstash-B-vaUYqO.js +40 -0
  51. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  52. package/dist/virtual-module.d.ts +3 -0
  53. package/dist/vite.d.ts +167 -14
  54. package/dist/vite.js +1195 -2876
  55. package/package.json +30 -21
  56. package/dist/cli-Cniq99iX.d.ts +0 -85
  57. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  58. package/dist/config-DR6_5ZwI.js +0 -124
  59. package/dist/continuations-DPyH_vr1.js +0 -63
  60. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  61. package/dist/errors-Dc2oiW-Y.js +0 -38
  62. package/dist/fs-lite-CbLKxLut.js +0 -90
  63. package/dist/object-B1NW521B.js +0 -7
  64. package/dist/operations-ByuDE12r.js +0 -1442
  65. package/dist/types-CMDvN0Wr.d.ts +0 -81
@@ -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-C3NO4C21.js";
4
+ import { t as createFsLiteKVDriver } from "./fs-lite-BaklCLuV.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,252 @@
1
+ import { t as isRecord } from "./object-Da1zyPCR.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-C54QQEhN.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
+ function resolveStoreMode(store, remote, input) {
72
+ if (input.dev && store.driver === "upstash") return {
73
+ ...store,
74
+ remote: true
75
+ };
76
+ if (store.driver !== "cloudflare" || !(input.dev || input.prerender)) return store;
77
+ return input.dev && remote ? {
78
+ ...store,
79
+ remote: true
80
+ } : {
81
+ ...store,
82
+ localBase: cloudflareKVLocalBase(store.binding)
83
+ };
84
+ }
85
+ /**
86
+ * The folder of an `fs-lite` store without `base`. The default store keeps `.vitehub/data/kv`. Each named store gets its
87
+ * own folder next to it, so stores never share keys. It is not inside `.vitehub/data/kv`, because the default store
88
+ * treats folders there as keys from the old layout.
89
+ */
90
+ function fsLiteStoreBase(name) {
91
+ if (name === "default") return ".vitehub/data/kv";
92
+ return `.vitehub/data/kv-stores/${encodeURIComponent(name).replace(/\./g, "%2E") || "%"}`;
93
+ }
94
+ function resolveFsLiteStore(config = {}, name = "default") {
95
+ return defu({ base: trimmed(config.base) }, {
96
+ driver: "fs-lite",
97
+ base: fsLiteStoreBase(name)
98
+ });
99
+ }
100
+ /** The key prefix of a Redis store without `base`. Every store has one, so a shared Redis keeps other keys apart. */
101
+ function redisStorePrefix(name) {
102
+ return `vitehub:kv:${name.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%"}`;
103
+ }
104
+ /** An empty prefix would let `kv.clear()` and `kv.list()` reach every key of the Redis or Upstash database. */
105
+ function resolveStoreBase(base, name) {
106
+ return normalizeKey(trimmed(base)) || redisStorePrefix(name);
107
+ }
108
+ function resolveRedisStore(config, name) {
109
+ return {
110
+ driver: "redis",
111
+ base: resolveStoreBase(config.base, name),
112
+ url: trimmed(config.url) ?? `env:REDIS_URL`
113
+ };
114
+ }
115
+ function resolveDatabaseStore(config, name) {
116
+ return {
117
+ driver: "database",
118
+ database: trimmed(config.database) ?? "default",
119
+ namespace: name
120
+ };
121
+ }
122
+ function resolveCloudflareStore(config = {}, env = process.env) {
123
+ return defu({
124
+ binding: trimmed(config.binding),
125
+ namespaceId: trimmed(config.namespaceId) ?? readEnv(env, "KV_NAMESPACE_ID"),
126
+ namespaceName: trimmed(config.namespaceName)
127
+ }, {
128
+ driver: "cloudflare",
129
+ binding: "KV"
130
+ });
131
+ }
132
+ function resolveDenoStore(config = {}) {
133
+ const path = trimmed(config.path);
134
+ return path ? {
135
+ driver: "deno-kv",
136
+ path
137
+ } : { driver: "deno-kv" };
138
+ }
139
+ function resolveExplicitStore(store, env, name, input) {
140
+ const remote = readRemote(store, name);
141
+ const { driver } = store;
142
+ if (input.dev && (remote === true && (driver === "fs-lite" || driver === "deno-kv") || remote === false && driver === "upstash")) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
143
+ driver,
144
+ remote,
145
+ store: name
146
+ });
147
+ return resolveStoreMode(resolveStoreDriver(store, env, name), remote, input);
148
+ }
149
+ function resolveStoreDriver(store, env, name) {
150
+ switch (store.driver) {
151
+ case "cloudflare": return resolveCloudflareStore(store, env);
152
+ case "database": return resolveDatabaseStore(store, name);
153
+ case "deno-kv": return resolveDenoStore(store);
154
+ case "fs-lite": return resolveFsLiteStore(store, name);
155
+ case "redis": return resolveRedisStore(store, name);
156
+ case "upstash": return resolveUpstashStore(store, resolveStoreBase(store.base, name));
157
+ default: {
158
+ const driver = store.driver;
159
+ throw kvErrorDiagnostics.KV_INVALID_DRIVER({
160
+ driver: JSON.stringify(driver) ?? String(driver),
161
+ renamed: renamedKVDrivers.get(String(driver))
162
+ });
163
+ }
164
+ }
165
+ }
166
+ /** Driver names that ViteHub renamed to the host name. `npx @vite-hub/codemods driver-key` moves them. */
167
+ const renamedKVDrivers = /* @__PURE__ */ new Map([["cloudflare-kv-binding", "cloudflare"]]);
168
+ function createResolvedConfig(store, stores) {
169
+ return stores ? {
170
+ store,
171
+ stores: {
172
+ default: store,
173
+ ...stores
174
+ }
175
+ } : { store };
176
+ }
177
+ function hasStoresConfig(options, stores) {
178
+ return !!options && Object.hasOwn(options, "stores") && isRecord(stores);
179
+ }
180
+ function normalizeKVOptions(options, input = {}) {
181
+ if (options === false) return;
182
+ if (typeof options !== "undefined" && !isRecord(options)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv" });
183
+ const env = input.env || process.env;
184
+ const hosting = normalizeHosting(input.hosting);
185
+ const explicit = options;
186
+ const hasOwnStores = options !== void 0 && Object.hasOwn(options, "stores");
187
+ const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
188
+ if (hasOwnStores && !isRecord(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
189
+ if (hasStoresConfig(options, stores)) {
190
+ const resolvedStores = Object.fromEntries(Object.entries(stores).map(([name, store]) => [name, resolveExplicitStore(store, env, name, input)]));
191
+ const defaultStore = resolvedStores.default;
192
+ if (!defaultStore) throw kvErrorDiagnostics.KV_MISSING_DEFAULT_STORE();
193
+ return createResolvedConfig(defaultStore, resolvedStores);
194
+ }
195
+ if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env, "default", input));
196
+ const remote = explicit ? readRemote(explicit, "default") : void 0;
197
+ const inferred = (store) => createResolvedConfig(resolveStoreMode(store, remote, input));
198
+ const hosted = !input.prerender && (!input.dev || remote === true);
199
+ if (hosting.includes("deno")) {
200
+ if (input.dev && remote === true) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
201
+ driver: "deno-kv",
202
+ remote,
203
+ store: "default"
204
+ });
205
+ return inferred(resolveDenoStore());
206
+ }
207
+ if (hosted && hasUpstashEnv(env)) return inferred(resolveUpstashStore({}, redisStorePrefix("default")));
208
+ if (hosted && hosting.includes("vercel")) return inferred(resolveUpstashStore({}, redisStorePrefix("default")));
209
+ if (hosting.includes("cloudflare")) return inferred(resolveCloudflareStore({}, env));
210
+ if (input.dev && remote === true) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
211
+ driver: "fs-lite",
212
+ remote,
213
+ store: "default"
214
+ });
215
+ if (input.dev || input.prerender) return inferred(resolveFsLiteStore());
216
+ if (input.postgresDatabase) return inferred({
217
+ ...resolveDatabaseStore({}, "default"),
218
+ inferred: true
219
+ });
220
+ return inferred({
221
+ ...resolveFsLiteStore(),
222
+ inferred: true
223
+ });
224
+ }
225
+ /** The line that a server prints at boot for its build-selected inferred store. */
226
+ function kvInferredStoreNotice(name, store) {
227
+ if (!("inferred" in store) || !store.inferred) return;
228
+ if (store.driver === "database") return `[vitehub] KV store "${name}" uses the table vitehub_kv of the Database "${store.database}", selected at build time.`;
229
+ 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.`;
230
+ }
231
+ /**
232
+ * The build hint for a Redis URL that KV does not use. Redis is never inferred, because a `REDIS_URL` often belongs to
233
+ * another service, such as BullMQ or sessions. A NuxtHub app that kept its keys in Redis must select it.
234
+ */
235
+ function kvRedisEnvHint(options, input = {}) {
236
+ if (options === false || input.dev || options && ("stores" in options || options.driver)) return;
237
+ const env = input.env || process.env;
238
+ const name = readEnv(env, "REDIS_URL") ? redisUrlEnvName : readEnv(env, "KV_URL")?.startsWith("rediss://") ? "KV_URL" : void 0;
239
+ if (!name) return;
240
+ const store = normalizeKVOptions(options, input)?.store;
241
+ if (store?.driver === "upstash" && !hasUpstashEnv(env)) return kvErrorDiagnostics.KV_REDIS_URL_UNUSED({
242
+ name,
243
+ store: "upstash"
244
+ });
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 kvErrorDiagnostics.KV_REDIS_URL_UNUSED({
247
+ name,
248
+ store: selected
249
+ });
250
+ }
251
+ //#endregion
252
+ export { upstashUrlEnvNames as a, upstashTokenEnvNames as i, kvRedisEnvHint as n, resolveHostPreset as o, normalizeKVOptions as r, readEnv as s, kvInferredStoreNotice as t };