@vite-hub/kv 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -13
- package/dist/{cli-DpPhz_Ek.d.ts → cli-CLomw9ml.d.ts} +1 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +24 -12
- package/dist/{cloudflare-env-lOtHHsgP.js → cloudflare-env-Dl349h_9.js} +2 -1
- package/dist/{cloudflare-kv-BIEUFzRT.js → cloudflare-kv-DQJhmGof.js} +22 -10
- package/dist/{cloudflare-kv-local-BBw3ZT1K.js → cloudflare-kv-local-COjgHweC.js} +3 -7
- package/dist/{config-BXEVoZE3.js → config-pfyPiPrI.js} +65 -28
- package/dist/{create-storage-BGsrQKw3.js → create-storage-DQ1BbFqH.js} +5 -5
- package/dist/{cursor-history-BqIQePNP.js → cursor-history-CAT4mpP1.js} +7 -3
- package/dist/{deno-kv-BM9mYdUp.js → deno-kv-Cf0ZveeN.js} +43 -7
- package/dist/driver-Du6Eh9p2.d.ts +47 -0
- package/dist/{error-diagnostics-BxqvtEIb.js → error-diagnostics-C4VTHInS.js} +16 -4
- package/dist/errors-BpiM-Vmh.js +125 -0
- package/dist/errors.d.ts +13 -1
- package/dist/errors.js +2 -2
- package/dist/{fs-lite-BLZId9_P.js → fs-lite-BTcBUP6B.js} +1 -1
- package/dist/fs-lite-C8yXCVDM.js +2 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +39 -52
- package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-CI2PJGqu.d.ts} +13 -2
- package/dist/{operations-Ch-gKaey.js → operations-CqKs7Ykc.js} +24 -45
- package/dist/{operations-B-WZ7P1h.js → operations-nAaONxzh.js} +273 -231
- package/dist/operations.d.ts +2 -2
- package/dist/operations.js +4 -3
- package/dist/out-BbXG-yVX.js +21755 -0
- package/dist/{redis-shared-E5mahECF.js → redis-shared-1M0IaguQ.js} +1 -1
- package/dist/request-log-Dj9Vw7qG.js +105 -0
- package/dist/{results-p7nPCnaJ.js → results-D6jfPtCk.js} +0 -1
- package/dist/runtime/cloudflare-kv.d.ts +1 -1
- package/dist/runtime/cloudflare-kv.js +1 -1
- package/dist/runtime/cloudflare-request-env.js +1 -1
- package/dist/runtime/database.d.ts +2 -0
- package/dist/{database-72Jk3VVk.js → runtime/database.js} +68 -37
- package/dist/runtime/nitro-plugin.js +12 -5
- package/dist/runtime/redis-driver.d.ts +2 -2
- package/dist/runtime/redis-driver.js +2 -5
- package/dist/runtime/unstorage-driver.js +6 -2
- package/dist/runtime/upstash-driver.d.ts +2 -2
- package/dist/runtime/upstash-driver.js +2 -6
- package/dist/{types-DEiKew_3.d.ts → types-Cp6IBhSN.d.ts} +36 -37
- package/dist/{upstash-DDlqTttY.js → upstash-5sTbIR35.js} +2 -2
- package/dist/virtual-module.d.ts +1 -0
- package/dist/vite.d.ts +21 -6
- package/dist/vite.js +2738 -415
- package/package.json +10 -5
- package/dist/driver-BwxgaQ-f.d.ts +0 -15
- package/dist/errors-DbwufFZp.js +0 -60
- package/dist/fs-lite-RAoxu8L0.js +0 -2
- package/dist/main-F3Y22_uV.js +0 -2353
package/README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# @vite-hub/kv
|
|
2
2
|
|
|
3
3
|
<p>
|
|
4
|
-
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://
|
|
5
|
-
<img alt="TypeScript" src="https://
|
|
6
|
-
<img alt="Vite" src="https://
|
|
7
|
-
<img alt="KV" src="https://
|
|
4
|
+
<a href="https://vitehub.dev"><img alt="ViteHub" src="https://img.shields.io/static/v1?label=ViteHub&message=vitehub.dev&color=blue"></a>
|
|
5
|
+
<img alt="TypeScript" src="https://img.shields.io/static/v1?label=TypeScript&message=ready&color=blue">
|
|
6
|
+
<img alt="Vite" src="https://img.shields.io/static/v1?label=Vite&message=config&color=blue">
|
|
7
|
+
<img alt="KV" src="https://img.shields.io/static/v1?label=KV&message=stores&color=blue">
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
10
|
`@vite-hub/kv` gives server code one small-state API for settings, flags, cache entries, and JSON-like records.
|
|
@@ -64,17 +64,17 @@ Several Node processes share keys only through a shared store. Without a `driver
|
|
|
64
64
|
|
|
65
65
|
`{ driver: "redis", url?, base? }` reads `url` at runtime when it is `env:<NAME>`, and `env:REDIS_URL` is the default. A literal URL goes into the build output. `base` prefixes every key and defaults to `vitehub:kv:<store>`, so keys that are not ViteHub's stay apart. The generated store segment escapes `%`, `:`, `/`, `\`, and `?`; an empty store name uses `%`. This keeps store names separate after key normalization. Two ViteHub apps on one Redis database share the default, so give each app its own database or `base`. A Redis listing cursor holds its whole state, so another server process can read the next page.
|
|
66
66
|
|
|
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.
|
|
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
|
-
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://`,
|
|
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
|
|
|
73
73
|
This changes the default of a Node build with a Postgres Database from `fs-lite` to `database`. Keys in `.vitehub/data/kv` are not copied. Set `kv: { driver: "fs-lite" }` to keep the old store.
|
|
74
74
|
|
|
75
75
|
`fs-lite` writes each key as one file in `base`. The file name starts with `key-`, followed by the key with `%` and `:` escaped as in a URL, so `signups` and `signups:reset-at` are the files `key-signups` and `key-signups%3Areset-at`. This prefix keeps application keys separate from migration metadata and temporary files. Most file systems limit a file name to 255 bytes, so an escaped key longer than 251 bytes fails with `KV_OPERATION_FAILED`. Earlier versions wrote `a:b` as the file `a/b`. The store moves those files to their new names when it opens the folder and preserves literal `%` characters in old key names. It keeps a hidden layout record and metadata folder in `base`. The migration lock stays in that folder, so only `base` needs write access. Stop all processes that use the store before moving it. Copies and backups must preserve hidden files and hard links. Use GNU `cp -a` and verify the copied layout record before opening the copy; see [Move an fs-lite store](https://vitehub.dev/docs/kv/configure#move-an-fs-lite-store). Ordinary `cp -R` breaks the layout identity and can make existing keys inaccessible.
|
|
76
76
|
|
|
77
|
-
`kv.set(key, value, { ttl
|
|
77
|
+
`kv.set(key, value, { ttl })` expires a value on every driver. `ttl` is a duration such as `"1h"`, or a number of seconds. Omitting `ttl` keeps the value until it is deleted or replaced. `ttl` is the only option; other options return `KV_INVALID_OPTION`. Cloudflare KV keeps a value at least 60 seconds. `fs-lite` keeps the expiry time of each key in its metadata folder and treats an expired key as missing. Initialization failures do not disable a store for the life of the process. The next operation can retry initialization.
|
|
78
78
|
|
|
79
79
|
## Development stays local
|
|
80
80
|
|
|
@@ -88,6 +88,8 @@ An explicit `driver` is honored as before; an `upstash` store prints the same no
|
|
|
88
88
|
|
|
89
89
|
## Nitro storage
|
|
90
90
|
|
|
91
|
+
During Nuxt prerender, the Node worker uses the configured KV stores and ignores the development `remote` option. Cloudflare stores use their local folders, and an app with a Deno KV store keeps the runtime fallback.
|
|
92
|
+
|
|
91
93
|
When KV is enabled in a Nitro app, the default store is the Nitro storage mount `kv`, and a named store is the mount `kv-<name>`. `useStorage("kv").getItem("a")` reads the same value as `kv.get("a")`, and `clear()` on a mount clears only that store. Store names escape `%`, `:`, `/`, `\\`, and `?` as percent-encoded characters; an empty name uses `%` (for example, `a/b` mounts at `kv-a%2Fb`). A mount with the same name in `nitro.kv` (or the deprecated `nitro.storage`) wins. Nuxt modules that take a mount name, such as nuxt-og-image's `runtimeCacheStorage: "kv"`, store their data in KV this way.
|
|
92
94
|
|
|
93
95
|
`kvStorageDriver` from `@vite-hub/kv/vite` is the file path of the unstorage driver behind these mounts. Its options are `store` (default: the default store) and `base`, a key prefix. Pass it to a module that takes a driver name, or mount it yourself. The driver opens the store on each call, so on Cloudflare it uses the binding of the current request. Nitro's `ttl` goes to `kv.set()`.
|
|
@@ -96,9 +98,9 @@ With `vitehub()`, `cache: { driver: "kv" }` mounts the same driver at Nitro's `c
|
|
|
96
98
|
|
|
97
99
|
## Listing keys
|
|
98
100
|
|
|
99
|
-
`kv.
|
|
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.
|
|
100
102
|
|
|
101
|
-
|
|
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`.
|
|
102
104
|
|
|
103
105
|
Cursors are opaque and provider-specific. Pass a returned cursor back to the same store with the same prefix. Cloudflare KV, Upstash, Deno KV, and `fs-lite` stop enumeration when the requested page is full. Cloudflare KV and Deno KV cursors carry the provider cursor, so a request in another isolate can continue the listing. An `fs-lite` cursor retains a directory iterator in the current process for up to 15 minutes. Upstash uses the same retention window when the provider returns more keys than requested. These process-local cursors can expire sooner when more than 32 listings are left unfinished. Calling `disposeKVStores()` from the application shutdown hook releases these process-local cursors, closes retained directory iterators, and clears their expiry timers. A pending listing cannot retain a new cursor after disposal. Callers must restart listing without a cursor when continuation fails.
|
|
104
106
|
|
|
@@ -115,18 +117,18 @@ KV operations return `[error, value]`. `error.code` is one of the codes of the m
|
|
|
115
117
|
`kv.lock(key, { ttl, wait })` gives a lock that one runner holds at a time across the processes that share a store. `run(fn)` takes the lock, calls `fn`, and releases the lock, also when `fn` throws:
|
|
116
118
|
|
|
117
119
|
```ts fragment
|
|
118
|
-
const [error, result] = await kv.lock("cron:daily", { ttl:
|
|
120
|
+
const [error, result] = await kv.lock("cron:daily", { ttl: "1m" }).run(() => sendDailyReport())
|
|
119
121
|
if (error) throw error
|
|
120
122
|
if (!result.acquired) return // Another runner holds the lock.
|
|
121
123
|
```
|
|
122
124
|
|
|
123
|
-
`ttl` (seconds) is required, so a crashed runner never keeps the lock. `wait` (seconds) polls with backoff until the lock is free. Each lock writes a random owner token with `setIfAbsent()` and frees it with `deleteIfEquals()`, so a runner whose lock expired cannot delete the next runner's lock. `acquire()` returns a `release()` function for code that does not fit in one callback. KV does not renew a lock: when the work runs longer than `ttl`, another runner can take it.
|
|
125
|
+
`ttl` (a duration or seconds) is required, so a crashed runner never keeps the lock. `wait` (seconds) polls with backoff until the lock is free. Each lock writes a random owner token with `setIfAbsent()` and frees it with `deleteIfEquals()`, so a runner whose lock expired cannot delete the next runner's lock. `acquire()` returns a `release()` function for code that does not fit in one callback. KV does not renew a lock: when the work runs longer than `ttl`, another runner can take it.
|
|
124
126
|
|
|
125
127
|
Only the drivers in `KVDriversWith<"deleteIfEquals">` (`redis`, `database`, `upstash`) support locks. Deno KV, Cloudflare KV, and `fs-lite` return `KV_UNSUPPORTED_OPERATION` without calling `fn`. App tests use `fs-lite`, so they return this code too.
|
|
126
128
|
|
|
127
129
|
## Read-only handles
|
|
128
130
|
|
|
129
|
-
`kv.store(name, { mode: "read" })` returns a `ReadonlyKVStorage` handle with `get()`, `getMany()`, `has()`,
|
|
131
|
+
`kv.store(name, { mode: "read" })` returns a `ReadonlyKVStorage` handle with `get()`, `getMany()`, `has()`, and `list()`. Write methods are a type error and absent at runtime. `mode` defaults to `"write"`, and another value throws `KV_INVALID_STORE_MODE`.
|
|
130
132
|
|
|
131
133
|
```ts
|
|
132
134
|
import { kv } from "@vite-hub/kv"
|
|
@@ -152,6 +154,10 @@ export default defineNitroPlugin((nitroApp) => {
|
|
|
152
154
|
})
|
|
153
155
|
```
|
|
154
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
|
+
|
|
155
161
|
## CLI
|
|
156
162
|
|
|
157
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.
|
|
@@ -3,6 +3,7 @@ import "nostics";
|
|
|
3
3
|
interface HostCliRunResult {
|
|
4
4
|
exitCode: number | null;
|
|
5
5
|
stdout: string;
|
|
6
|
+
stderr?: string;
|
|
6
7
|
}
|
|
7
8
|
/** Runs a host CLI with an argument array and no shell, and returns its stdout. */
|
|
8
9
|
type HostCliRun = (command: string, args: readonly string[], options: {
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-
|
|
1
|
+
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-CLomw9ml.js";
|
|
2
2
|
//#region src/cli.d.ts
|
|
3
3
|
export type KVCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
|
|
4
4
|
export interface KVCliOptions {
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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-nAaONxzh.js";
|
|
1
2
|
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
3
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
|
|
4
|
+
import { t as kvDevMaximumListLimit } from "./results-D6jfPtCk.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";
|
|
@@ -10,7 +10,8 @@ const usageError = (problem) => kvErrorDiagnostics.KV_CLI_USAGE({ problem });
|
|
|
10
10
|
const kvDevTargetErrors = {
|
|
11
11
|
invalidInlineTimeout: usageError,
|
|
12
12
|
invalidTimeout: usageError,
|
|
13
|
-
missingValue: usageError
|
|
13
|
+
missingValue: usageError,
|
|
14
|
+
unknownOption: usageError
|
|
14
15
|
};
|
|
15
16
|
const kvCommands = [
|
|
16
17
|
{
|
|
@@ -184,9 +185,16 @@ function normalizedDecimal(source) {
|
|
|
184
185
|
const scale = BigInt(exponent) - BigInt(fraction.length) + BigInt(digits.length - significant.length);
|
|
185
186
|
return `${negative ? "-" : ""}${significant}e${scale}`;
|
|
186
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
|
+
}
|
|
187
195
|
async function readValue(parsed, cwd) {
|
|
188
196
|
const raw = parsed.value;
|
|
189
|
-
const text = raw.startsWith("@") ? await
|
|
197
|
+
const text = raw.startsWith("@") ? await readValueFile(raw.slice(1), cwd) : raw;
|
|
190
198
|
if (!parsed.jsonValue) return text;
|
|
191
199
|
try {
|
|
192
200
|
const value = JSON.parse(text, (_key, value, context) => {
|
|
@@ -206,6 +214,10 @@ function formatValue(result) {
|
|
|
206
214
|
if (v.is(v.string(), result.value)) return result.value;
|
|
207
215
|
return `${JSON.stringify(result.value, null, 2)}\n`;
|
|
208
216
|
}
|
|
217
|
+
const codedError = v.object({
|
|
218
|
+
code: v.string(),
|
|
219
|
+
fix: v.optional(v.string())
|
|
220
|
+
});
|
|
209
221
|
const targetFields = {
|
|
210
222
|
key: v.string(),
|
|
211
223
|
store: v.string()
|
|
@@ -345,7 +357,13 @@ async function runKVCommand(command, args, context, options) {
|
|
|
345
357
|
if (command.value && !parsed.help) value = await readValue(parsed, context.cwd);
|
|
346
358
|
} catch (error) {
|
|
347
359
|
const terminator = args.indexOf("--");
|
|
348
|
-
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
|
+
}
|
|
349
367
|
context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
350
368
|
writeUsage(command, context.stderr);
|
|
351
369
|
return 1;
|
|
@@ -404,13 +422,7 @@ async function runKVCli(args, context, options = {}) {
|
|
|
404
422
|
}
|
|
405
423
|
return await runKVCommand(command, rest, context, options);
|
|
406
424
|
}
|
|
407
|
-
/** The folder of the KV seed files, relative to the project root. */
|
|
408
425
|
const kvSeedDir = "server/seed/kv";
|
|
409
|
-
/**
|
|
410
|
-
* Writes each file in `server/seed/kv/` to the default KV store with `kv set`. The key is the path without its
|
|
411
|
-
* extension, so `server/seed/kv/settings/theme.json` is the key `settings/theme`. A `.json` file is a JSON value, and
|
|
412
|
-
* any other file is a string.
|
|
413
|
-
*/
|
|
414
426
|
async function runKVSeed(seed, context, options) {
|
|
415
427
|
const dir = resolve(options.projectRoot?.() ?? context.rootDir, kvSeedDir);
|
|
416
428
|
const files = await listSeedFiles(dir);
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { i as setInstalledCloudflareEnv, n as getActiveCloudflareEnv, r as getCloudflareEnv, t as activeEnvStorageKey } from "./cloudflare-env-lookup-Bs0VDpU5.js";
|
|
2
2
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
3
|
//#region ../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");
|
|
@@ -43,4 +44,4 @@ function installCloudflareRequestEnv(event, fallback) {
|
|
|
43
44
|
if (env) setActiveCloudflareEnv(env);
|
|
44
45
|
}
|
|
45
46
|
//#endregion
|
|
46
|
-
export {
|
|
47
|
+
export { getActiveCloudflareBinding as n, installCloudflareRequestEnv as r, d1PrimaryClient as t };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as invariant } from "./invariant-DolT9EEx.js";
|
|
2
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
3
|
-
import {
|
|
4
|
-
import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
|
|
3
|
+
import { n as getActiveCloudflareBinding } from "./cloudflare-env-Dl349h_9.js";
|
|
4
|
+
import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-DQ1BbFqH.js";
|
|
5
5
|
import { i as setItemsOneByOne, t as chunks } from "./batch--v0ri69O.js";
|
|
6
|
-
import { n as recordCursor, t as createCursorHistory } from "./cursor-history-
|
|
6
|
+
import { n as recordCursor, t as createCursorHistory } from "./cursor-history-CAT4mpP1.js";
|
|
7
7
|
import createDriver from "unstorage/drivers/cloudflare-kv-binding";
|
|
8
8
|
//#region src/runtime/cloudflare-kv-limits.ts
|
|
9
9
|
const cloudflareKVLimits = {
|
|
@@ -12,7 +12,6 @@ const cloudflareKVLimits = {
|
|
|
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;
|
|
@@ -79,8 +77,8 @@ function isCloudflareKVListPage(value) {
|
|
|
79
77
|
})) return false;
|
|
80
78
|
return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
|
|
81
79
|
}
|
|
82
|
-
/** Cloudflare reads at most 100 keys in one bulk `get()`. */
|
|
83
80
|
const cloudflareKVBulkGetKeys = 100;
|
|
81
|
+
const cloudflareKVMaximumListLimit = 1e3;
|
|
84
82
|
const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
|
|
85
83
|
let nextCloudflareBindingIdentity = 0;
|
|
86
84
|
function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
|
|
@@ -143,7 +141,7 @@ function createCloudflareDriver(options) {
|
|
|
143
141
|
};
|
|
144
142
|
driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
|
|
145
143
|
invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
|
|
146
|
-
const listOptions = { limit };
|
|
144
|
+
const listOptions = { limit: Math.min(limit, cloudflareKVMaximumListLimit) };
|
|
147
145
|
if (cursor) listOptions.cursor = cursor;
|
|
148
146
|
if (prefix) listOptions.prefix = prefix;
|
|
149
147
|
const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
|
|
@@ -156,13 +154,13 @@ function createCloudflareDriver(options) {
|
|
|
156
154
|
try {
|
|
157
155
|
if (continuation.providerCursor) listOptions.cursor = continuation.providerCursor;
|
|
158
156
|
const cursors = continuation.history;
|
|
159
|
-
const page = await driver.getInstance().list(listOptions);
|
|
157
|
+
const page = await (await driver.getInstance()).list(listOptions);
|
|
160
158
|
if (!isCloudflareKVListPage(page)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV list returned an invalid page." });
|
|
161
159
|
const result = { keys: page.keys.map((key) => key.name) };
|
|
162
160
|
if (!page.list_complete) {
|
|
163
161
|
invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
|
|
164
162
|
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
|
|
163
|
+
if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a pagination cursor longer than 8 KiB." });
|
|
166
164
|
result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
|
|
167
165
|
}
|
|
168
166
|
cursorHistories.complete(cursor);
|
|
@@ -172,6 +170,20 @@ function createCloudflareDriver(options) {
|
|
|
172
170
|
throw error;
|
|
173
171
|
}
|
|
174
172
|
};
|
|
173
|
+
driver.clear = async (prefix = "") => {
|
|
174
|
+
const keys = [];
|
|
175
|
+
let cursor;
|
|
176
|
+
do {
|
|
177
|
+
const page = await driver.listKeys({
|
|
178
|
+
cursor,
|
|
179
|
+
limit: cloudflareKVMaximumListLimit,
|
|
180
|
+
prefix
|
|
181
|
+
});
|
|
182
|
+
keys.push(...page.keys);
|
|
183
|
+
cursor = page.cursor;
|
|
184
|
+
} while (cursor);
|
|
185
|
+
for (const key of keys) await driver.removeItem(key, {});
|
|
186
|
+
};
|
|
175
187
|
return driver;
|
|
176
188
|
}
|
|
177
189
|
function createCloudflareKVStorage(options) {
|
|
@@ -1,12 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as getActiveCloudflareBinding } from "./cloudflare-env-Dl349h_9.js";
|
|
2
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-
|
|
4
|
-
import { t as createFsLiteKVDriver } from "./fs-lite-
|
|
3
|
+
import { a as validateCloudflareKVBatch, i as installCloudflareKVLimits, r as assertCloudflareKVWrite, t as createCloudflareDriver } from "./cloudflare-kv-DQJhmGof.js";
|
|
4
|
+
import { t as createFsLiteKVDriver } from "./fs-lite-BTcBUP6B.js";
|
|
5
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
6
|
function cloudflareExpirationSeconds(options) {
|
|
11
7
|
if (!options || typeof options !== "object") return;
|
|
12
8
|
const ttl = Reflect.get(options, "ttl");
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
2
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
|
|
3
3
|
import { o as normalizeKey } from "./utils2-FozcTsmb.js";
|
|
4
4
|
import { defu } from "defu";
|
|
5
5
|
//#region ../internal/src/env.ts
|
|
@@ -68,14 +68,13 @@ function readRemote(config, store) {
|
|
|
68
68
|
if (remote === void 0 || typeof remote === "boolean") return remote;
|
|
69
69
|
throw kvErrorDiagnostics.KV_INVALID_REMOTE({ store });
|
|
70
70
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (store.driver === "upstash") return {
|
|
71
|
+
function resolveStoreMode(store, remote, input) {
|
|
72
|
+
if (input.dev && store.driver === "upstash") return {
|
|
74
73
|
...store,
|
|
75
74
|
remote: true
|
|
76
75
|
};
|
|
77
|
-
if (store.driver !== "cloudflare") return store;
|
|
78
|
-
return remote ? {
|
|
76
|
+
if (store.driver !== "cloudflare" || !(input.dev || input.prerender)) return store;
|
|
77
|
+
return input.dev && remote ? {
|
|
79
78
|
...store,
|
|
80
79
|
remote: true
|
|
81
80
|
} : {
|
|
@@ -83,11 +82,6 @@ function resolveDevStore(store, remote) {
|
|
|
83
82
|
localBase: cloudflareKVLocalBase(store.binding)
|
|
84
83
|
};
|
|
85
84
|
}
|
|
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
85
|
function fsLiteStoreBase(name) {
|
|
92
86
|
if (name === "default") return ".vitehub/data/kv";
|
|
93
87
|
return `.vitehub/data/kv-stores/${encodeURIComponent(name).replace(/\./g, "%2E") || "%"}`;
|
|
@@ -102,7 +96,6 @@ function resolveFsLiteStore(config = {}, name = "default") {
|
|
|
102
96
|
function redisStorePrefix(name) {
|
|
103
97
|
return `vitehub:kv:${name.replace(/[%:/\\?]/g, (character) => encodeURIComponent(character)) || "%"}`;
|
|
104
98
|
}
|
|
105
|
-
/** An empty prefix would let `kv.clear()` and `kv.keys()` reach every key of the Redis or Upstash database. */
|
|
106
99
|
function resolveStoreBase(base, name) {
|
|
107
100
|
return normalizeKey(trimmed(base)) || redisStorePrefix(name);
|
|
108
101
|
}
|
|
@@ -137,16 +130,17 @@ function resolveDenoStore(config = {}) {
|
|
|
137
130
|
path
|
|
138
131
|
} : { driver: "deno-kv" };
|
|
139
132
|
}
|
|
140
|
-
function resolveExplicitStore(store, env, name,
|
|
133
|
+
function resolveExplicitStore(store, env, name, input, path) {
|
|
141
134
|
const remote = readRemote(store, name);
|
|
142
135
|
const { driver } = store;
|
|
143
|
-
if (dev && (remote === true && (driver === "fs-lite" || driver === "deno-kv") || remote === false && driver === "upstash")) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
|
|
136
|
+
if (input.dev && (remote === true && (driver === "fs-lite" || driver === "deno-kv") || remote === false && driver === "upstash")) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
|
|
144
137
|
driver,
|
|
145
138
|
remote,
|
|
146
139
|
store: name
|
|
147
140
|
});
|
|
148
141
|
const resolved = resolveStoreDriver(store, env, name);
|
|
149
|
-
|
|
142
|
+
assertKnownKVStoreKeys(store, store.driver, path);
|
|
143
|
+
return resolveStoreMode(resolved, remote, input);
|
|
150
144
|
}
|
|
151
145
|
function resolveStoreDriver(store, env, name) {
|
|
152
146
|
switch (store.driver) {
|
|
@@ -165,7 +159,38 @@ function resolveStoreDriver(store, env, name) {
|
|
|
165
159
|
}
|
|
166
160
|
}
|
|
167
161
|
}
|
|
168
|
-
|
|
162
|
+
const kvDriverOptions = {
|
|
163
|
+
"cloudflare": [
|
|
164
|
+
"binding",
|
|
165
|
+
"namespaceId",
|
|
166
|
+
"namespaceName"
|
|
167
|
+
],
|
|
168
|
+
"database": ["database"],
|
|
169
|
+
"deno-kv": ["path"],
|
|
170
|
+
"fs-lite": ["base"],
|
|
171
|
+
"redis": ["base", "url"],
|
|
172
|
+
"upstash": [
|
|
173
|
+
"base",
|
|
174
|
+
"token",
|
|
175
|
+
"url"
|
|
176
|
+
]
|
|
177
|
+
};
|
|
178
|
+
function assertKnownKVStoreKeys(store, driver, path) {
|
|
179
|
+
const known = /* @__PURE__ */ new Set([
|
|
180
|
+
"driver",
|
|
181
|
+
"remote",
|
|
182
|
+
...driver ? kvDriverOptions[driver] : []
|
|
183
|
+
]);
|
|
184
|
+
const key = Object.keys(store).find((name) => !known.has(name) && Reflect.get(store, name) !== void 0);
|
|
185
|
+
if (key === void 0) return;
|
|
186
|
+
const drivers = Object.keys(kvDriverOptions).filter((name) => kvDriverOptions[name].includes(key));
|
|
187
|
+
throw kvErrorDiagnostics.KV_UNKNOWN_STORE_OPTION({
|
|
188
|
+
drivers,
|
|
189
|
+
driver,
|
|
190
|
+
key,
|
|
191
|
+
path
|
|
192
|
+
});
|
|
193
|
+
}
|
|
169
194
|
const renamedKVDrivers = /* @__PURE__ */ new Map([["cloudflare-kv-binding", "cloudflare"]]);
|
|
170
195
|
function createResolvedConfig(store, stores) {
|
|
171
196
|
return stores ? {
|
|
@@ -189,15 +214,23 @@ function normalizeKVOptions(options, input = {}) {
|
|
|
189
214
|
const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
|
|
190
215
|
if (hasOwnStores && !isRecord(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
|
|
191
216
|
if (hasStoresConfig(options, stores)) {
|
|
192
|
-
const
|
|
217
|
+
const extra = Object.entries(options ?? {}).find(([key, value]) => key !== "stores" && value !== void 0)?.[0];
|
|
218
|
+
if (extra !== void 0) throw kvErrorDiagnostics.KV_UNKNOWN_STORE_OPTION({
|
|
219
|
+
drivers: [],
|
|
220
|
+
key: extra,
|
|
221
|
+
path: "kv",
|
|
222
|
+
stores: true
|
|
223
|
+
});
|
|
224
|
+
const resolvedStores = Object.fromEntries(Object.entries(stores).map(([name, store]) => [name, resolveExplicitStore(store, env, name, input, `kv.stores.${name}`)]));
|
|
193
225
|
const defaultStore = resolvedStores.default;
|
|
194
226
|
if (!defaultStore) throw kvErrorDiagnostics.KV_MISSING_DEFAULT_STORE();
|
|
195
227
|
return createResolvedConfig(defaultStore, resolvedStores);
|
|
196
228
|
}
|
|
197
|
-
if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env, "default", input
|
|
229
|
+
if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env, "default", input, "kv"));
|
|
230
|
+
if (explicit) assertKnownKVStoreKeys(explicit, void 0, "kv");
|
|
198
231
|
const remote = explicit ? readRemote(explicit, "default") : void 0;
|
|
199
|
-
const inferred = (store) => createResolvedConfig(
|
|
200
|
-
const hosted = !input.dev || remote === true;
|
|
232
|
+
const inferred = (store) => createResolvedConfig(resolveStoreMode(store, remote, input));
|
|
233
|
+
const hosted = !input.prerender && (!input.dev || remote === true);
|
|
201
234
|
if (hosting.includes("deno")) {
|
|
202
235
|
if (input.dev && remote === true) throw kvErrorDiagnostics.KV_REMOTE_CONFLICT({
|
|
203
236
|
driver: "deno-kv",
|
|
@@ -214,7 +247,7 @@ function normalizeKVOptions(options, input = {}) {
|
|
|
214
247
|
remote,
|
|
215
248
|
store: "default"
|
|
216
249
|
});
|
|
217
|
-
if (input.dev) return inferred(resolveFsLiteStore());
|
|
250
|
+
if (input.dev || input.prerender) return inferred(resolveFsLiteStore());
|
|
218
251
|
if (input.postgresDatabase) return inferred({
|
|
219
252
|
...resolveDatabaseStore({}, "default"),
|
|
220
253
|
inferred: true
|
|
@@ -231,20 +264,24 @@ function kvInferredStoreNotice(name, store) {
|
|
|
231
264
|
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
265
|
}
|
|
233
266
|
/**
|
|
234
|
-
* The build
|
|
267
|
+
* The build hint for a Redis URL that KV does not use. Redis is never inferred, because a `REDIS_URL` often belongs to
|
|
235
268
|
* another service, such as BullMQ or sessions. A NuxtHub app that kept its keys in Redis must select it.
|
|
236
269
|
*/
|
|
237
|
-
function
|
|
270
|
+
function kvRedisEnvHint(options, input = {}) {
|
|
238
271
|
if (options === false || input.dev || options && ("stores" in options || options.driver)) return;
|
|
239
272
|
const env = input.env || process.env;
|
|
240
273
|
const name = readEnv(env, "REDIS_URL") ? redisUrlEnvName : readEnv(env, "KV_URL")?.startsWith("rediss://") ? "KV_URL" : void 0;
|
|
241
274
|
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
275
|
const store = normalizeKVOptions(options, input)?.store;
|
|
244
|
-
if (store?.driver === "upstash" && !hasUpstashEnv(env)) return
|
|
276
|
+
if (store?.driver === "upstash" && !hasUpstashEnv(env)) return kvErrorDiagnostics.KV_REDIS_URL_UNUSED({
|
|
277
|
+
name,
|
|
278
|
+
store: "upstash"
|
|
279
|
+
});
|
|
245
280
|
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 (
|
|
247
|
-
|
|
281
|
+
if (selected) return kvErrorDiagnostics.KV_REDIS_URL_UNUSED({
|
|
282
|
+
name,
|
|
283
|
+
store: selected
|
|
284
|
+
});
|
|
248
285
|
}
|
|
249
286
|
//#endregion
|
|
250
|
-
export { upstashUrlEnvNames as a, upstashTokenEnvNames as i,
|
|
287
|
+
export { upstashUrlEnvNames as a, upstashTokenEnvNames as i, kvRedisEnvHint as n, resolveHostPreset as o, normalizeKVOptions as r, readEnv as s, kvInferredStoreNotice as t };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
|
|
2
2
|
import { a as normalizeBaseKey, i as joinKeys, n as filterKeyByDepth, o as normalizeKey, r as hasDotSegment, t as filterKeyByBase } from "./utils2-FozcTsmb.js";
|
|
3
3
|
import { r as mapWithLimit } from "./batch--v0ri69O.js";
|
|
4
4
|
//#region ../../node_modules/.pnpm/unstorage@2.0.0-beta.0/node_modules/unstorage/dist/_chunks/libs/destr.mjs
|
|
@@ -547,15 +547,15 @@ function isRawType(type) {
|
|
|
547
547
|
return type === "bytes" || type === "blob" || type === "stream";
|
|
548
548
|
}
|
|
549
549
|
const removeBatchSize = 100;
|
|
550
|
-
/** Gives
|
|
550
|
+
/** Gives `clear(prefix)` the text-prefix meaning of `list({ prefix })`, and adds the batch methods. */
|
|
551
551
|
function createKVStorage(driver) {
|
|
552
552
|
const storage = createStorage({ driver });
|
|
553
553
|
const clear = storage.clear;
|
|
554
554
|
storage.clear = async (base, options = {}) => {
|
|
555
|
-
const prefix =
|
|
556
|
-
if (!prefix) return clear(
|
|
555
|
+
const prefix = normalizeKVListPrefix(base);
|
|
556
|
+
if (!prefix) return clear("", options);
|
|
557
557
|
if (driver.clear) return driver.clear(prefix, options);
|
|
558
|
-
const keys = await storage.getKeys(
|
|
558
|
+
const keys = (await storage.getKeys("", options)).filter((key) => key.startsWith(prefix));
|
|
559
559
|
for (let offset = 0; offset < keys.length; offset += removeBatchSize) await Promise.all(keys.slice(offset, offset + removeBatchSize).map((key) => storage.removeItem(key, options)));
|
|
560
560
|
};
|
|
561
561
|
return Object.assign(storage, {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as invariant } from "./invariant-DolT9EEx.js";
|
|
2
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
|
|
3
3
|
//#region src/runtime/cursor-history.ts
|
|
4
4
|
const MAX_CURSOR_HISTORIES = 1024;
|
|
5
5
|
const MAX_CURSORS_PER_HISTORY = 1024;
|
|
@@ -155,9 +155,13 @@ 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
|
}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { t as invariant } from "./invariant-DolT9EEx.js";
|
|
2
|
-
import { n as kvErrorDiagnostics } from "./error-diagnostics-
|
|
3
|
-
import { n as recordCursor, t as createCursorHistory } from "./cursor-history-
|
|
2
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-C4VTHInS.js";
|
|
3
|
+
import { n as recordCursor, t as createCursorHistory } from "./cursor-history-CAT4mpP1.js";
|
|
4
4
|
//#region src/runtime/deno-kv.ts
|
|
5
|
+
const MAX_DENO_KEY_BYTES = 2048;
|
|
5
6
|
function getDenoRuntime() {
|
|
6
7
|
return globalThis.Deno;
|
|
7
8
|
}
|
|
@@ -11,6 +12,21 @@ function toDenoKey(key) {
|
|
|
11
12
|
function fromDenoKey(key) {
|
|
12
13
|
return key.length === 1 && typeof key[0] === "string" ? key[0] : void 0;
|
|
13
14
|
}
|
|
15
|
+
function canMatchStoredKey(prefix) {
|
|
16
|
+
const nulBytes = prefix.split("\0").length - 1;
|
|
17
|
+
return 2 + new TextEncoder().encode(prefix).length + nulBytes <= MAX_DENO_KEY_BYTES;
|
|
18
|
+
}
|
|
19
|
+
function sortsAfterPrefix(key, prefix) {
|
|
20
|
+
const [part] = key;
|
|
21
|
+
if (typeof part !== "string") return !(part instanceof Uint8Array);
|
|
22
|
+
if (part.startsWith(prefix)) return false;
|
|
23
|
+
const prefixCodePoints = prefix[Symbol.iterator]();
|
|
24
|
+
for (const character of part) {
|
|
25
|
+
const prefixCharacter = prefixCodePoints.next().value;
|
|
26
|
+
if (prefixCharacter === void 0 || character !== prefixCharacter) return (character.codePointAt(0) ?? 0) > (prefixCharacter?.codePointAt(0) ?? -1);
|
|
27
|
+
}
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
14
30
|
function toDenoExpireIn(ttl) {
|
|
15
31
|
if (typeof ttl !== "number" || !Number.isFinite(ttl) || ttl <= 0) return void 0;
|
|
16
32
|
const expireIn = Math.max(1, Math.ceil(ttl * 1e3));
|
|
@@ -39,7 +55,14 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
|
|
|
39
55
|
async function matchingKeys(base = "") {
|
|
40
56
|
const kv = await open();
|
|
41
57
|
const keys = [];
|
|
42
|
-
|
|
58
|
+
if (!canMatchStoredKey(base)) return keys;
|
|
59
|
+
for await (const entry of kv.list(base ? {
|
|
60
|
+
prefix: [],
|
|
61
|
+
start: [base]
|
|
62
|
+
} : { prefix: [] })) {
|
|
63
|
+
if (sortsAfterPrefix(entry.key, base)) break;
|
|
64
|
+
if (fromDenoKey(entry.key)?.startsWith(base)) keys.push(entry.key);
|
|
65
|
+
}
|
|
43
66
|
return keys;
|
|
44
67
|
}
|
|
45
68
|
return {
|
|
@@ -79,22 +102,35 @@ function createDenoKVDriver(options = { driver: "deno-kv" }) {
|
|
|
79
102
|
};
|
|
80
103
|
try {
|
|
81
104
|
const cursors = continuation.history;
|
|
82
|
-
const
|
|
105
|
+
const keys = [];
|
|
106
|
+
if (!canMatchStoredKey(prefix)) {
|
|
107
|
+
cursorHistories.complete(cursor);
|
|
108
|
+
return { keys };
|
|
109
|
+
}
|
|
110
|
+
const selector = prefix && !continuation.providerCursor ? {
|
|
111
|
+
prefix: [],
|
|
112
|
+
start: [prefix]
|
|
113
|
+
} : { prefix: [] };
|
|
114
|
+
const iterator = (await open()).list(selector, {
|
|
83
115
|
cursor: continuation.providerCursor,
|
|
84
116
|
limit
|
|
85
117
|
});
|
|
86
|
-
|
|
118
|
+
let pastPrefix = false;
|
|
87
119
|
for await (const entry of iterator) {
|
|
120
|
+
if (sortsAfterPrefix(entry.key, prefix)) {
|
|
121
|
+
pastPrefix = true;
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
88
124
|
const key = fromDenoKey(entry.key);
|
|
89
125
|
if (key?.startsWith(prefix)) keys.push(key);
|
|
90
126
|
}
|
|
91
|
-
if (!iterator.cursor) {
|
|
127
|
+
if (pastPrefix || !iterator.cursor) {
|
|
92
128
|
cursorHistories.complete(cursor);
|
|
93
129
|
return { keys };
|
|
94
130
|
}
|
|
95
131
|
invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
|
|
96
132
|
if (cursors.has(iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV list returned a repeated pagination cursor." });
|
|
97
|
-
if (!recordCursor(cursors, iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV
|
|
133
|
+
if (!recordCursor(cursors, iterator.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Deno KV returned a pagination cursor longer than 8 KiB." });
|
|
98
134
|
const nextCursor = cursorHistories.store(iterator.cursor, cursors);
|
|
99
135
|
cursorHistories.complete(cursor);
|
|
100
136
|
return {
|