@vite-hub/kv 0.4.1 → 0.5.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.
- package/README.md +7 -3
- package/dist/{batch--v0ri69O.js → batch-D-ib5_0P.js} +0 -1
- package/dist/{cli-DpPhz_Ek.d.ts → cli-BvVInMht.d.ts} +1 -6
- package/dist/cli.d.ts +2 -4
- package/dist/cli.js +24 -14
- package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Bm6huR35.js} +4 -4
- package/dist/{cloudflare-env-lookup-Bs0VDpU5.js → cloudflare-env-lookup-Dgq5n1Aq.js} +1 -2
- package/dist/{cloudflare-kv-C3NO4C21.js → cloudflare-kv-K2MzfP6D.js} +12 -16
- package/dist/{cloudflare-kv-local-C2sbIrFy.js → cloudflare-kv-local-lov9LLhU.js} +5 -10
- package/dist/{config-LfpUj9hs.js → config-B8FRGmX_.js} +53 -22
- package/dist/{create-storage-BORQm2a8.js → create-storage-BMvkkYdM.js} +9 -15
- package/dist/{cursor-history-DRHh5bO5.js → cursor-history-C6oG12QO.js} +9 -6
- package/dist/{deno-kv-D_VtffFv.js → deno-kv-MnqlNH1e.js} +45 -10
- package/dist/{dev-peer-CHafxbtj.js → dev-peer-D0vOxmrD.js} +1 -2
- package/dist/driver-bLMl-wMO.d.ts +43 -0
- package/dist/durability.d.ts +1 -3
- package/dist/durability.js +1 -2
- package/dist/{error-diagnostics-C54QQEhN.js → error-diagnostics-DUIp6FhO.js} +7 -4
- package/dist/{errors-DzD6YNEH.js → errors-IaVOqzAs.js} +42 -8
- package/dist/errors.d.ts +8 -5
- package/dist/errors.js +1 -2
- package/dist/fs-lite-DhXLUL-H.js +1 -0
- package/dist/{fs-lite-BaklCLuV.js → fs-lite-fvNdBEr9.js} +3 -5
- package/dist/index.d.ts +1 -3
- package/dist/index.js +34 -66
- package/dist/{inspect-BIKQsqX4.js → inspect-BWMcVWD8.js} +2 -4
- package/dist/{invariant-DolT9EEx.js → invariant-Dj2R1eMr.js} +1 -2
- package/dist/{object-Da1zyPCR.js → object-CAK6UYR5.js} +1 -2
- package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
- package/dist/{operations-D2iI9oN4.js → operations-CGAX5ASA.js} +53 -28
- package/dist/{operations-CtrWLmPK.js → operations-FgS_sJ3M.js} +27 -45
- package/dist/operations.d.ts +2 -8
- package/dist/operations.js +8 -12
- package/dist/out-By90R-Bo.js +22706 -0
- package/dist/{redis-shared-5ogRd3-Y.js → redis-shared-DO7Ib1Sz.js} +2 -3
- package/dist/request-log-DllKQXj7.js +104 -0
- package/dist/results-emgN7uDS.js +4 -0
- package/dist/rolldown-runtime-DegdyBIC.js +25 -0
- package/dist/runtime/cloudflare-kv.d.ts +1 -3
- package/dist/runtime/cloudflare-kv.js +1 -2
- package/dist/runtime/cloudflare-request-env.d.ts +1 -3
- package/dist/runtime/cloudflare-request-env.js +2 -3
- package/dist/runtime/database.d.ts +2 -0
- package/dist/{database-oJdy0ZVX.js → runtime/database.js} +69 -39
- package/dist/runtime/nitro-plugin.d.ts +1 -2
- package/dist/runtime/nitro-plugin.js +11 -8
- package/dist/runtime/redis-driver.d.ts +3 -5
- package/dist/runtime/redis-driver.js +6 -10
- package/dist/runtime/unstorage-driver.d.ts +2 -4
- package/dist/runtime/unstorage-driver.js +2 -3
- package/dist/runtime/upstash-driver.d.ts +3 -5
- package/dist/runtime/upstash-driver.js +6 -11
- package/dist/{types-Bj3EQoRg.d.ts → types-BUb0FcjM.d.ts} +0 -2
- package/dist/{types-Dv-OSXZC.d.ts → types-C397WKyf.d.ts} +4 -20
- package/dist/{upstash-B-vaUYqO.js → upstash-DQVo1zbz.js} +3 -4
- package/dist/{utils2-FozcTsmb.js → utils2-By8eee1x.js} +1 -2
- package/dist/vite.d.ts +8 -19
- package/dist/vite.js +2676 -104
- package/package.json +15 -10
- package/dist/driver-R4Z5Z5fl.d.ts +0 -15
- package/dist/fs-lite-BAgpmNAF.js +0 -2
- package/dist/results-p7nPCnaJ.js +0 -6
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
pnpm add @vite-hub/kv
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
Add `@upstash/redis` when you use the Upstash driver. The `redis` driver uses `ioredis`, which KV installs.
|
|
18
|
+
Add `@upstash/redis` when you use the Upstash driver. The `redis` driver uses `ioredis`, which KV installs, and needs Redis 6 or later.
|
|
19
19
|
|
|
20
20
|
## Minimal API
|
|
21
21
|
|
|
@@ -66,7 +66,7 @@ Several Node processes share keys only through a shared store. Without a `driver
|
|
|
66
66
|
|
|
67
67
|
`{ driver: "upstash", url?, token?, base? }` uses the same `base` rule as `redis`: every key gets the prefix `vitehub:kv:<store>` unless `base` sets another one, so `kv.clear()` and `kv.list()` stay inside the store. Upstash takes whole seconds, so `set()` rounds a TTL up. Its listing cursor also holds its whole state, so the next page works in another serverless invocation.
|
|
68
68
|
|
|
69
|
-
`{ driver: "database", database? }` keeps keys in the table `vitehub_kv` of the Database `database` (default `"default"`), with one `namespace` per store. The store creates the table when it is missing; on Postgres, an advisory lock lets several servers start at once. Every atomic operation is one SQL statement, and expiry uses the clock of the Database. Writes start background cleanup of at most 1000 expired rows in their namespace. A full batch lets the next write start another batch; once a batch is not full, cleanup waits a minute. Postgres sweeps skip rows locked by another process. It works on Postgres and
|
|
69
|
+
`{ driver: "database", database? }` keeps keys in the table `vitehub_kv` of the Database `database` (default `"default"`), with one `namespace` per store. The store creates the table when it is missing; on Postgres, an advisory lock lets several servers start at once. Every atomic operation is one SQL statement, and expiry uses the clock of the Database. Writes start background cleanup of at most 1000 expired rows in their namespace. A full batch lets the next write start another batch; once a batch is not full, cleanup waits a minute. Postgres sweeps skip rows locked by another process. It works on Postgres, libSQL, and Cloudflare D1, by binding or over HTTP. On D1, one statement binds at most 100 values, so a large `setMany()` or `getMany()` uses more statements.
|
|
70
70
|
|
|
71
71
|
The driver is selected at build time. Redis requires `kv: { driver: "redis" }`; every process must supply its URL, and a missing URL fails. An unrelated `REDIS_URL` never changes the selected driver. A build without a `driver` that has `REDIS_URL`, or a `KV_URL` that starts with `rediss://`, reports the hint `KV_REDIS_URL_UNUSED` in the build output and in `.vitehub/hints.json`, with the fix `kv: { driver: "redis" }`. On Vercel without Upstash variables, the same hint says that the inferred Upstash store fails at runtime. The `kv.list` operation (`vitehub kv list`, the Console) reports that driver.
|
|
72
72
|
|
|
@@ -98,7 +98,7 @@ With `vitehub()`, `cache: { driver: "kv" }` mounts the same driver at Nitro's `c
|
|
|
98
98
|
|
|
99
99
|
## Listing keys
|
|
100
100
|
|
|
101
|
-
`kv.list({ prefix })` returns every key that starts with `prefix`. Add `limit` when the caller needs bounded work: `kv.list({ prefix, limit, cursor })` reads one page. `limit` must be a positive integer. A page returns `{ keys, cursor? }`; an omitted cursor means the listing is complete. `kv.clear({ prefix })` deletes the keys that `kv.list({ prefix })` lists.
|
|
101
|
+
`kv.list({ prefix })` returns every key that starts with `prefix`. Add `limit` when the caller needs bounded work: `kv.list({ prefix, limit, cursor })` reads one page. `limit` must be a positive integer. A page returns `{ keys, cursor? }`; an omitted cursor means the listing is complete. On Cloudflare KV, each binding request returns at most 1,000 keys: with `limit` above 1,000, `kv.list()` caps the request at 1,000 keys and returns a `cursor` only when more keys remain; without `limit`, it reads every page and returns no cursor. `kv.clear({ prefix })` deletes the keys that `kv.list({ prefix })` lists.
|
|
102
102
|
|
|
103
103
|
Prefixes match text, and use the same key normalization as reads and writes. For example, `users/al` matches the stored key `users:alice`, and `user` matches `users:alice` and `user-old:1`. A trailing separator, such as `users/` or `users:`, limits the prefix to children and does not match `users-other`.
|
|
104
104
|
|
|
@@ -154,6 +154,10 @@ export default defineNitroPlugin((nitroApp) => {
|
|
|
154
154
|
})
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
+
## Failures in logs
|
|
158
|
+
|
|
159
|
+
A failed delete of expired rows in a `database` store does not fail the write. With the evlog Nitro module registered, KV logs each streak of failures once, as its own evlog event with `kv: { op: "expiry-sweep", driver, namespace, code }`. Without evlog, it goes to the console. See [Limits and errors](https://vitehub.dev/docs/kv/limits-and-errors#see-expiry-failures-in-logs).
|
|
160
|
+
|
|
157
161
|
## CLI
|
|
158
162
|
|
|
159
163
|
`hubKV()` contributes the `vitehub kv` CLI namespace: `list [--prefix] [--limit] [--cursor]`, `get <key>`, `has <key>`, `set <key> <value|@file> [--ttl <seconds>] [--json-value]`, and `delete <key>`. Each command accepts `--store <name>` and `--json`. `get` writes stored strings unchanged, without adding a newline. JSON input rejects underflow and decimal values that change magnitude during parsing; use strings to preserve them. Write commands print what they changed. There is no `clear` command.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import "nostics";
|
|
2
|
-
//#region ../internal/src/host-credentials.d.ts
|
|
3
2
|
interface HostCliRunResult {
|
|
4
3
|
exitCode: number | null;
|
|
5
4
|
stdout: string;
|
|
5
|
+
stderr?: string;
|
|
6
6
|
}
|
|
7
7
|
/** Runs a host CLI with an argument array and no shell, and returns its stdout. */
|
|
8
8
|
type HostCliRun = (command: string, args: readonly string[], options: {
|
|
@@ -10,8 +10,6 @@ type HostCliRun = (command: string, args: readonly string[], options: {
|
|
|
10
10
|
env: NodeJS.ProcessEnv;
|
|
11
11
|
signal?: AbortSignal;
|
|
12
12
|
}) => Promise<HostCliRunResult>;
|
|
13
|
-
//#endregion
|
|
14
|
-
//#region ../internal/src/provision.d.ts
|
|
15
13
|
type ProvisionProvider = "cloudflare" | "vercel";
|
|
16
14
|
interface ProvisionLogger {
|
|
17
15
|
log: (message: string) => void;
|
|
@@ -63,8 +61,6 @@ interface ProvisionStep {
|
|
|
63
61
|
/** Describes the Provision State this step records. Runs without network access, also without credentials. */
|
|
64
62
|
recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
|
|
65
63
|
}
|
|
66
|
-
//#endregion
|
|
67
|
-
//#region ../internal/src/cli.d.ts
|
|
68
64
|
interface ViteHubCliStreams {
|
|
69
65
|
stderr: {
|
|
70
66
|
write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
|
|
@@ -159,5 +155,4 @@ interface ViteHubCliPluginMetadata {
|
|
|
159
155
|
cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
|
|
160
156
|
}
|
|
161
157
|
type StdoutWriteCallback = (error?: Error | null) => void;
|
|
162
|
-
//#endregion
|
|
163
158
|
export { ViteHubCliStreams as i, ViteHubCliContributor as n, ViteHubCliPluginMetadata as r, ViteHubCliContext as t };
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-
|
|
2
|
-
//#region src/cli.d.ts
|
|
1
|
+
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-BvVInMht.js";
|
|
3
2
|
export type KVCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
|
|
4
3
|
export interface KVCliOptions {
|
|
5
4
|
/** Asks whether `delete` may delete a key. Defaults to a prompt on a terminal, and refuses without one. */
|
|
@@ -13,5 +12,4 @@ export interface KVCliOptions {
|
|
|
13
12
|
* `args[0]` is the command name, for example `list` or `set`.
|
|
14
13
|
*/
|
|
15
14
|
export declare function runKVCli(args: string[], context: KVCliContext, options?: KVCliOptions): Promise<number>;
|
|
16
|
-
export declare function createKVCliContributor(options?: KVCliOptions): ViteHubCliContributor;
|
|
17
|
-
//#endregion
|
|
15
|
+
export declare function createKVCliContributor(options?: KVCliOptions): ViteHubCliContributor;
|
package/dist/cli.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { t as isRecord } from "./object-
|
|
3
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
4
|
-
import { t as kvDevMaximumListLimit } from "./results-
|
|
1
|
+
import { A as readViteHubDevTargetOption, D as parseCliPositiveInteger, E as listSeedFiles, M as writeCliFailure, O as readCliOptionValue, T as askOnTerminal, n as callOperationFromCli } from "./operations-CGAX5ASA.js";
|
|
2
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
3
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
|
|
4
|
+
import { t as kvDevMaximumListLimit } from "./results-emgN7uDS.js";
|
|
5
5
|
import { readFile } from "node:fs/promises";
|
|
6
6
|
import { extname, join, relative, resolve } from "node:path";
|
|
7
7
|
import * as v from "valibot";
|
|
8
|
-
|
|
8
|
+
// src/cli.ts
|
|
9
9
|
const usageError = (problem) => kvErrorDiagnostics.KV_CLI_USAGE({ problem });
|
|
10
10
|
const kvDevTargetErrors = {
|
|
11
11
|
invalidInlineTimeout: usageError,
|
|
@@ -185,9 +185,16 @@ function normalizedDecimal(source) {
|
|
|
185
185
|
const scale = BigInt(exponent) - BigInt(fraction.length) + BigInt(digits.length - significant.length);
|
|
186
186
|
return `${negative ? "-" : ""}${significant}e${scale}`;
|
|
187
187
|
}
|
|
188
|
+
async function readValueFile(path, cwd) {
|
|
189
|
+
try {
|
|
190
|
+
return await readFile(resolve(cwd, path), "utf8");
|
|
191
|
+
} catch (error) {
|
|
192
|
+
throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `Could not read the file ${path}: ${error instanceof Error ? error.message : String(error)}` });
|
|
193
|
+
}
|
|
194
|
+
}
|
|
188
195
|
async function readValue(parsed, cwd) {
|
|
189
196
|
const raw = parsed.value;
|
|
190
|
-
const text = raw.startsWith("@") ? await
|
|
197
|
+
const text = raw.startsWith("@") ? await readValueFile(raw.slice(1), cwd) : raw;
|
|
191
198
|
if (!parsed.jsonValue) return text;
|
|
192
199
|
try {
|
|
193
200
|
const value = JSON.parse(text, (_key, value, context) => {
|
|
@@ -207,6 +214,10 @@ function formatValue(result) {
|
|
|
207
214
|
if (v.is(v.string(), result.value)) return result.value;
|
|
208
215
|
return `${JSON.stringify(result.value, null, 2)}\n`;
|
|
209
216
|
}
|
|
217
|
+
const codedError = v.object({
|
|
218
|
+
code: v.string(),
|
|
219
|
+
fix: v.optional(v.string())
|
|
220
|
+
});
|
|
210
221
|
const targetFields = {
|
|
211
222
|
key: v.string(),
|
|
212
223
|
store: v.string()
|
|
@@ -346,7 +357,13 @@ async function runKVCommand(command, args, context, options) {
|
|
|
346
357
|
if (command.value && !parsed.help) value = await readValue(parsed, context.cwd);
|
|
347
358
|
} catch (error) {
|
|
348
359
|
const terminator = args.indexOf("--");
|
|
349
|
-
if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json"))
|
|
360
|
+
if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) {
|
|
361
|
+
const coded = v.safeParse(codedError, error);
|
|
362
|
+
return writeCliFailure(true, context, {
|
|
363
|
+
...coded.success ? coded.output : {},
|
|
364
|
+
message: error instanceof Error ? error.message : String(error)
|
|
365
|
+
});
|
|
366
|
+
}
|
|
350
367
|
context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
351
368
|
writeUsage(command, context.stderr);
|
|
352
369
|
return 1;
|
|
@@ -405,13 +422,7 @@ async function runKVCli(args, context, options = {}) {
|
|
|
405
422
|
}
|
|
406
423
|
return await runKVCommand(command, rest, context, options);
|
|
407
424
|
}
|
|
408
|
-
/** The folder of the KV seed files, relative to the project root. */
|
|
409
425
|
const kvSeedDir = "server/seed/kv";
|
|
410
|
-
/**
|
|
411
|
-
* Writes each file in `server/seed/kv/` to the default KV store with `kv set`. The key is the path without its
|
|
412
|
-
* extension, so `server/seed/kv/settings/theme.json` is the key `settings/theme`. A `.json` file is a JSON value, and
|
|
413
|
-
* any other file is a string.
|
|
414
|
-
*/
|
|
415
426
|
async function runKVSeed(seed, context, options) {
|
|
416
427
|
const dir = resolve(options.projectRoot?.() ?? context.rootDir, kvSeedDir);
|
|
417
428
|
const files = await listSeedFiles(dir);
|
|
@@ -466,5 +477,4 @@ function createKVCliContributor(options = {}) {
|
|
|
466
477
|
}]
|
|
467
478
|
};
|
|
468
479
|
}
|
|
469
|
-
//#endregion
|
|
470
480
|
export { createKVCliContributor, runKVCli };
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { i as setInstalledCloudflareEnv, n as getActiveCloudflareEnv, r as getCloudflareEnv, t as activeEnvStorageKey } from "./cloudflare-env-lookup-
|
|
1
|
+
import { i as setInstalledCloudflareEnv, n as getActiveCloudflareEnv, r as getCloudflareEnv, t as activeEnvStorageKey } from "./cloudflare-env-lookup-Dgq5n1Aq.js";
|
|
2
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
-
|
|
3
|
+
// ../internal/src/runtime/cloudflare-env.ts
|
|
4
|
+
const d1PrimaryClient = Symbol.for("vitehub.database.d1-primary-client");
|
|
4
5
|
const runtimeGlobal = globalThis;
|
|
5
6
|
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
6
7
|
const globalEnvProbe = Symbol("vitehub.cloudflare.global-env-probe");
|
|
@@ -42,5 +43,4 @@ function installCloudflareRequestEnv(event, fallback) {
|
|
|
42
43
|
const env = getCloudflareEnv(event, { fallback: false }) ?? fallback;
|
|
43
44
|
if (env) setActiveCloudflareEnv(env);
|
|
44
45
|
}
|
|
45
|
-
|
|
46
|
-
export { installCloudflareRequestEnv as n, getActiveCloudflareBinding as t };
|
|
46
|
+
export { getActiveCloudflareBinding as n, installCloudflareRequestEnv as r, d1PrimaryClient as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
2
2
|
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
3
3
|
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
4
4
|
let activeEnv;
|
|
@@ -38,5 +38,4 @@ function getCloudflareEnv(event, options = {}) {
|
|
|
38
38
|
for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
|
|
39
39
|
return options.fallback === false ? void 0 : getActiveCloudflareEnv();
|
|
40
40
|
}
|
|
41
|
-
//#endregion
|
|
42
41
|
export { setInstalledCloudflareEnv as i, getActiveCloudflareEnv as n, getCloudflareEnv as r, activeEnvStorageKey as t };
|
|
@@ -1,18 +1,17 @@
|
|
|
1
|
-
import { t as invariant } from "./invariant-
|
|
2
|
-
import { n as
|
|
3
|
-
import { t as
|
|
4
|
-
import { n as
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
1
|
+
import { t as invariant } from "./invariant-Dj2R1eMr.js";
|
|
2
|
+
import { n as getActiveCloudflareBinding } from "./cloudflare-env-Bm6huR35.js";
|
|
3
|
+
import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-BMvkkYdM.js";
|
|
4
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
|
|
5
|
+
import { n as recordCursor, t as createCursorHistory } from "./cursor-history-C6oG12QO.js";
|
|
6
|
+
import { i as setItemsOneByOne, t as chunks } from "./batch-D-ib5_0P.js";
|
|
7
7
|
import createDriver from "unstorage/drivers/cloudflare-kv-binding";
|
|
8
|
-
|
|
8
|
+
// src/runtime/cloudflare-kv-limits.ts
|
|
9
9
|
const cloudflareKVLimits = {
|
|
10
10
|
keyBytes: 512,
|
|
11
11
|
minExpirationTtl: 60,
|
|
12
12
|
valueBytes: 26214400
|
|
13
13
|
};
|
|
14
14
|
const encoder = /*#__PURE__*/ new TextEncoder();
|
|
15
|
-
/** Returns the UTF-8 size of `value` when it is above `limit`. */
|
|
16
15
|
function bytesAbove(value, limit) {
|
|
17
16
|
if (value.length * 3 <= limit) return;
|
|
18
17
|
const bytes = encoder.encode(value).byteLength;
|
|
@@ -34,7 +33,6 @@ function assertCloudflareKVWrite(key, value) {
|
|
|
34
33
|
limit: cloudflareKVLimits.valueBytes
|
|
35
34
|
});
|
|
36
35
|
}
|
|
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
36
|
function cloudflareKVSetOptions(options) {
|
|
39
37
|
const ttl = options?.ttl;
|
|
40
38
|
return typeof ttl === "number" ? { ttl: Math.max(cloudflareKVLimits.minExpirationTtl, ttl) } : options;
|
|
@@ -64,8 +62,7 @@ function validateCloudflareKVBatch(items, removals) {
|
|
|
64
62
|
for (const key of removals) assertCloudflareKVKey(key);
|
|
65
63
|
for (const item of items) assertCloudflareKVWrite(item.key, item.value);
|
|
66
64
|
}
|
|
67
|
-
|
|
68
|
-
//#region src/runtime/cloudflare-kv.ts
|
|
65
|
+
// src/runtime/cloudflare-kv.ts
|
|
69
66
|
function isCloudflareKVString(value) {
|
|
70
67
|
return typeof value === "string";
|
|
71
68
|
}
|
|
@@ -79,8 +76,8 @@ function isCloudflareKVListPage(value) {
|
|
|
79
76
|
})) return false;
|
|
80
77
|
return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
|
|
81
78
|
}
|
|
82
|
-
/** Cloudflare reads at most 100 keys in one bulk `get()`. */
|
|
83
79
|
const cloudflareKVBulkGetKeys = 100;
|
|
80
|
+
const cloudflareKVMaximumListLimit = 1e3;
|
|
84
81
|
const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
|
|
85
82
|
let nextCloudflareBindingIdentity = 0;
|
|
86
83
|
function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
|
|
@@ -143,7 +140,7 @@ function createCloudflareDriver(options) {
|
|
|
143
140
|
};
|
|
144
141
|
driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
|
|
145
142
|
invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
|
|
146
|
-
const listOptions = { limit };
|
|
143
|
+
const listOptions = { limit: Math.min(limit, cloudflareKVMaximumListLimit) };
|
|
147
144
|
if (cursor) listOptions.cursor = cursor;
|
|
148
145
|
if (prefix) listOptions.prefix = prefix;
|
|
149
146
|
const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
|
|
@@ -162,7 +159,7 @@ function createCloudflareDriver(options) {
|
|
|
162
159
|
if (!page.list_complete) {
|
|
163
160
|
invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
|
|
164
161
|
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
|
|
162
|
+
if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a pagination cursor longer than 8 KiB." });
|
|
166
163
|
result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
|
|
167
164
|
}
|
|
168
165
|
cursorHistories.complete(cursor);
|
|
@@ -178,7 +175,7 @@ function createCloudflareDriver(options) {
|
|
|
178
175
|
do {
|
|
179
176
|
const page = await driver.listKeys({
|
|
180
177
|
cursor,
|
|
181
|
-
limit:
|
|
178
|
+
limit: cloudflareKVMaximumListLimit,
|
|
182
179
|
prefix
|
|
183
180
|
});
|
|
184
181
|
keys.push(...page.keys);
|
|
@@ -197,5 +194,4 @@ function createCloudflareKVStorage(options) {
|
|
|
197
194
|
});
|
|
198
195
|
return storage;
|
|
199
196
|
}
|
|
200
|
-
//#endregion
|
|
201
197
|
export { validateCloudflareKVBatch as a, installCloudflareKVLimits as i, createCloudflareKVStorage as n, assertCloudflareKVWrite as r, createCloudflareDriver as t };
|
|
@@ -1,12 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { i as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
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
|
-
*/
|
|
1
|
+
import { n as getActiveCloudflareBinding } from "./cloudflare-env-Bm6huR35.js";
|
|
2
|
+
import { a as validateCloudflareKVBatch, i as installCloudflareKVLimits, r as assertCloudflareKVWrite, t as createCloudflareDriver } from "./cloudflare-kv-K2MzfP6D.js";
|
|
3
|
+
import { t as createFsLiteKVDriver } from "./fs-lite-fvNdBEr9.js";
|
|
4
|
+
import { i as setItemsOneByOne, n as getItemsOneByOne } from "./batch-D-ib5_0P.js";
|
|
5
|
+
// src/runtime/cloudflare-kv-local.ts
|
|
10
6
|
function cloudflareExpirationSeconds(options) {
|
|
11
7
|
if (!options || typeof options !== "object") return;
|
|
12
8
|
const ttl = Reflect.get(options, "ttl");
|
|
@@ -67,5 +63,4 @@ function createCloudflareKVLocalDriver(store) {
|
|
|
67
63
|
}
|
|
68
64
|
};
|
|
69
65
|
}
|
|
70
|
-
//#endregion
|
|
71
66
|
export { createCloudflareKVLocalDriver as default };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { o as normalizeKey } from "./utils2-By8eee1x.js";
|
|
2
|
+
import { t as isRecord } from "./object-CAK6UYR5.js";
|
|
3
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
|
|
4
4
|
import { defu } from "defu";
|
|
5
|
-
|
|
5
|
+
// ../internal/src/env.ts
|
|
6
6
|
function trimmed(value) {
|
|
7
7
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
|
|
8
8
|
}
|
|
@@ -12,8 +12,7 @@ function readEnv(env, ...names) {
|
|
|
12
12
|
if (value) return value;
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
//#region ../internal/src/hosting.ts
|
|
15
|
+
// ../internal/src/hosting.ts
|
|
17
16
|
/**
|
|
18
17
|
* Returns the Nitro preset name that this build targets, as the developer wrote it.
|
|
19
18
|
* The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOST`.
|
|
@@ -35,8 +34,7 @@ function normalizeHosting(hosting) {
|
|
|
35
34
|
if (normalized === "cloudflare") return "cloudflare-module";
|
|
36
35
|
return normalized;
|
|
37
36
|
}
|
|
38
|
-
|
|
39
|
-
//#region src/integrations/upstash.ts
|
|
37
|
+
// src/integrations/upstash.ts
|
|
40
38
|
const maskedUpstashRuntimeValue = "********";
|
|
41
39
|
/** Vercel names first, then the names that the Upstash console and NuxtHub use. */
|
|
42
40
|
const upstashUrlEnvNames = ["KV_REST_API_URL", "UPSTASH_REDIS_REST_URL"];
|
|
@@ -55,8 +53,7 @@ function resolveUpstashStore(config, base) {
|
|
|
55
53
|
url: trimmed(config.url) ?? maskedUpstashRuntimeValue
|
|
56
54
|
};
|
|
57
55
|
}
|
|
58
|
-
|
|
59
|
-
//#region src/config.ts
|
|
56
|
+
// src/config.ts
|
|
60
57
|
/** The variable that a `redis` store reads at runtime when it sets no `url`. */
|
|
61
58
|
const redisUrlEnvName = "REDIS_URL";
|
|
62
59
|
/** Where a Cloudflare KV store keeps its keys in `vite dev` when the runtime has no binding. */
|
|
@@ -82,11 +79,6 @@ function resolveStoreMode(store, remote, input) {
|
|
|
82
79
|
localBase: cloudflareKVLocalBase(store.binding)
|
|
83
80
|
};
|
|
84
81
|
}
|
|
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
82
|
function fsLiteStoreBase(name) {
|
|
91
83
|
if (name === "default") return ".vitehub/data/kv";
|
|
92
84
|
return `.vitehub/data/kv-stores/${encodeURIComponent(name).replace(/\./g, "%2E") || "%"}`;
|
|
@@ -101,7 +93,6 @@ function resolveFsLiteStore(config = {}, name = "default") {
|
|
|
101
93
|
function redisStorePrefix(name) {
|
|
102
94
|
return `vitehub:kv:${name.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%"}`;
|
|
103
95
|
}
|
|
104
|
-
/** An empty prefix would let `kv.clear()` and `kv.list()` reach every key of the Redis or Upstash database. */
|
|
105
96
|
function resolveStoreBase(base, name) {
|
|
106
97
|
return normalizeKey(trimmed(base)) || redisStorePrefix(name);
|
|
107
98
|
}
|
|
@@ -136,7 +127,7 @@ function resolveDenoStore(config = {}) {
|
|
|
136
127
|
path
|
|
137
128
|
} : { driver: "deno-kv" };
|
|
138
129
|
}
|
|
139
|
-
function resolveExplicitStore(store, env, name, input) {
|
|
130
|
+
function resolveExplicitStore(store, env, name, input, path) {
|
|
140
131
|
const remote = readRemote(store, name);
|
|
141
132
|
const { driver } = store;
|
|
142
133
|
if (input.dev && (remote === true && (driver === "fs-lite" || driver === "deno-kv") || remote === false && driver === "upstash")) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
|
|
@@ -144,7 +135,9 @@ function resolveExplicitStore(store, env, name, input) {
|
|
|
144
135
|
remote,
|
|
145
136
|
store: name
|
|
146
137
|
});
|
|
147
|
-
|
|
138
|
+
const resolved = resolveStoreDriver(store, env, name);
|
|
139
|
+
assertKnownKVStoreKeys(store, store.driver, path);
|
|
140
|
+
return resolveStoreMode(resolved, remote, input);
|
|
148
141
|
}
|
|
149
142
|
function resolveStoreDriver(store, env, name) {
|
|
150
143
|
switch (store.driver) {
|
|
@@ -163,7 +156,38 @@ function resolveStoreDriver(store, env, name) {
|
|
|
163
156
|
}
|
|
164
157
|
}
|
|
165
158
|
}
|
|
166
|
-
|
|
159
|
+
const kvDriverOptions = {
|
|
160
|
+
"cloudflare": [
|
|
161
|
+
"binding",
|
|
162
|
+
"namespaceId",
|
|
163
|
+
"namespaceName"
|
|
164
|
+
],
|
|
165
|
+
"database": ["database"],
|
|
166
|
+
"deno-kv": ["path"],
|
|
167
|
+
"fs-lite": ["base"],
|
|
168
|
+
"redis": ["base", "url"],
|
|
169
|
+
"upstash": [
|
|
170
|
+
"base",
|
|
171
|
+
"token",
|
|
172
|
+
"url"
|
|
173
|
+
]
|
|
174
|
+
};
|
|
175
|
+
function assertKnownKVStoreKeys(store, driver, path) {
|
|
176
|
+
const known = /* @__PURE__ */ new Set([
|
|
177
|
+
"driver",
|
|
178
|
+
"remote",
|
|
179
|
+
...driver ? kvDriverOptions[driver] : []
|
|
180
|
+
]);
|
|
181
|
+
const key = Object.keys(store).find((name) => !known.has(name) && Reflect.get(store, name) !== void 0);
|
|
182
|
+
if (key === void 0) return;
|
|
183
|
+
const drivers = Object.keys(kvDriverOptions).filter((name) => kvDriverOptions[name].includes(key));
|
|
184
|
+
throw kvErrorDiagnostics.KV_UNKNOWN_STORE_OPTION({
|
|
185
|
+
drivers,
|
|
186
|
+
driver,
|
|
187
|
+
key,
|
|
188
|
+
path
|
|
189
|
+
});
|
|
190
|
+
}
|
|
167
191
|
const renamedKVDrivers = /* @__PURE__ */ new Map([["cloudflare-kv-binding", "cloudflare"]]);
|
|
168
192
|
function createResolvedConfig(store, stores) {
|
|
169
193
|
return stores ? {
|
|
@@ -187,12 +211,20 @@ function normalizeKVOptions(options, input = {}) {
|
|
|
187
211
|
const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
|
|
188
212
|
if (hasOwnStores && !isRecord(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
|
|
189
213
|
if (hasStoresConfig(options, stores)) {
|
|
190
|
-
const
|
|
214
|
+
const extra = Object.entries(options ?? {}).find(([key, value]) => key !== "stores" && value !== void 0)?.[0];
|
|
215
|
+
if (extra !== void 0) throw kvErrorDiagnostics.KV_UNKNOWN_STORE_OPTION({
|
|
216
|
+
drivers: [],
|
|
217
|
+
key: extra,
|
|
218
|
+
path: "kv",
|
|
219
|
+
stores: true
|
|
220
|
+
});
|
|
221
|
+
const resolvedStores = Object.fromEntries(Object.entries(stores).map(([name, store]) => [name, resolveExplicitStore(store, env, name, input, `kv.stores.${name}`)]));
|
|
191
222
|
const defaultStore = resolvedStores.default;
|
|
192
223
|
if (!defaultStore) throw kvErrorDiagnostics.KV_MISSING_DEFAULT_STORE();
|
|
193
224
|
return createResolvedConfig(defaultStore, resolvedStores);
|
|
194
225
|
}
|
|
195
|
-
if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env, "default", input));
|
|
226
|
+
if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env, "default", input, "kv"));
|
|
227
|
+
if (explicit) assertKnownKVStoreKeys(explicit, void 0, "kv");
|
|
196
228
|
const remote = explicit ? readRemote(explicit, "default") : void 0;
|
|
197
229
|
const inferred = (store) => createResolvedConfig(resolveStoreMode(store, remote, input));
|
|
198
230
|
const hosted = !input.prerender && (!input.dev || remote === true);
|
|
@@ -248,5 +280,4 @@ function kvRedisEnvHint(options, input = {}) {
|
|
|
248
280
|
store: selected
|
|
249
281
|
});
|
|
250
282
|
}
|
|
251
|
-
//#endregion
|
|
252
283
|
export { upstashUrlEnvNames as a, upstashTokenEnvNames as i, kvRedisEnvHint as n, resolveHostPreset as o, normalizeKVOptions as r, readEnv as s, kvInferredStoreNotice as t };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import {
|
|
3
|
-
import { r as mapWithLimit } from "./batch
|
|
4
|
-
|
|
1
|
+
import { a as normalizeBaseKey, i as joinKeys, n as filterKeyByDepth, o as normalizeKey, r as hasDotSegment, t as filterKeyByBase } from "./utils2-By8eee1x.js";
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
|
|
3
|
+
import { r as mapWithLimit } from "./batch-D-ib5_0P.js";
|
|
4
|
+
// ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/libs/destr.mjs
|
|
5
5
|
const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
|
|
6
6
|
const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
|
|
7
7
|
const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
|
|
@@ -43,8 +43,7 @@ function destr(value, options = {}) {
|
|
|
43
43
|
return value;
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
|
-
|
|
47
|
-
//#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/drivers/memory.mjs
|
|
46
|
+
// ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/drivers/memory.mjs
|
|
48
47
|
const DRIVER_NAME = "memory";
|
|
49
48
|
const driver = () => {
|
|
50
49
|
const data = /* @__PURE__ */ new Map();
|
|
@@ -117,8 +116,7 @@ function _scheduleExpiry(data, timers, key, ttl) {
|
|
|
117
116
|
};
|
|
118
117
|
schedule();
|
|
119
118
|
}
|
|
120
|
-
|
|
121
|
-
//#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/_utils.mjs
|
|
119
|
+
// ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/_utils.mjs
|
|
122
120
|
function wrapToPromise(value) {
|
|
123
121
|
if (!value || typeof value.then !== "function") return Promise.resolve(value);
|
|
124
122
|
return value;
|
|
@@ -220,8 +218,7 @@ function concatBytes(chunks) {
|
|
|
220
218
|
function typeName(value) {
|
|
221
219
|
return value?.constructor?.name || typeof value;
|
|
222
220
|
}
|
|
223
|
-
|
|
224
|
-
//#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/index.mjs
|
|
221
|
+
// ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/index.mjs
|
|
225
222
|
function isRawType$1(type) {
|
|
226
223
|
return type === "bytes" || type === "blob" || type === "stream";
|
|
227
224
|
}
|
|
@@ -534,15 +531,13 @@ function watch(driver, onChange, base) {
|
|
|
534
531
|
async function dispose(driver) {
|
|
535
532
|
if (typeof driver.dispose === "function") await asyncCall(driver.dispose);
|
|
536
533
|
}
|
|
537
|
-
|
|
538
|
-
//#region src/runtime/list-prefix.ts
|
|
534
|
+
// src/runtime/list-prefix.ts
|
|
539
535
|
function normalizeKVListPrefix(prefix = "") {
|
|
540
536
|
const normalized = normalizeKey(prefix);
|
|
541
537
|
const path = prefix.split("?")[0] ?? "";
|
|
542
538
|
return normalized && /[:/\\]$/.test(path) ? `${normalized}:` : normalized;
|
|
543
539
|
}
|
|
544
|
-
|
|
545
|
-
//#region src/runtime/create-storage.ts
|
|
540
|
+
// src/runtime/create-storage.ts
|
|
546
541
|
function isRawType(type) {
|
|
547
542
|
return type === "bytes" || type === "blob" || type === "stream";
|
|
548
543
|
}
|
|
@@ -594,5 +589,4 @@ function createKVStorage(driver) {
|
|
|
594
589
|
}
|
|
595
590
|
});
|
|
596
591
|
}
|
|
597
|
-
//#endregion
|
|
598
592
|
export { normalizeKVListPrefix as n, createKVStorage as t };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as invariant } from "./invariant-
|
|
2
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
3
|
-
|
|
1
|
+
import { t as invariant } from "./invariant-Dj2R1eMr.js";
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-DUIp6FhO.js";
|
|
3
|
+
// src/runtime/cursor-history.ts
|
|
4
4
|
const MAX_CURSOR_HISTORIES = 1024;
|
|
5
5
|
const MAX_CURSORS_PER_HISTORY = 1024;
|
|
6
6
|
const MAX_CURSOR_LENGTH = 8192;
|
|
@@ -155,11 +155,14 @@ function createCursorHistory(namespace = "default") {
|
|
|
155
155
|
clear
|
|
156
156
|
};
|
|
157
157
|
}
|
|
158
|
-
/** Records a provider cursor,
|
|
158
|
+
/** Records a provider cursor. At the bound it forgets the oldest cursor, so a long listing continues and a recent repeat is still caught. */
|
|
159
159
|
function recordCursor(history, cursor) {
|
|
160
|
-
if (cursor.length > MAX_CURSOR_LENGTH
|
|
160
|
+
if (cursor.length > MAX_CURSOR_LENGTH) return false;
|
|
161
|
+
if (history.size >= MAX_CURSORS_PER_HISTORY) {
|
|
162
|
+
const oldest = history.values().next();
|
|
163
|
+
if (!oldest.done) history.delete(oldest.value);
|
|
164
|
+
}
|
|
161
165
|
history.add(cursor);
|
|
162
166
|
return true;
|
|
163
167
|
}
|
|
164
|
-
//#endregion
|
|
165
168
|
export { recordCursor as n, createCursorHistory as t };
|