@vite-hub/kv 0.0.4 → 0.1.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 +33 -8
- package/dist/cli-Cniq99iX.d.ts +85 -0
- package/dist/cli.d.ts +15 -0
- package/dist/cli.js +448 -0
- package/dist/cloudflare-env-C5rM7kUY.js +74 -0
- package/dist/{config-aM9Ae7tH.js → config-DR6_5ZwI.js} +36 -22
- package/dist/continuations-DPyH_vr1.js +63 -0
- package/dist/{dist-DDW1iC5f.js → create-storage-29gMzf41.js} +70 -75
- package/dist/cursor-history-dqYDlsaD.js +148 -0
- package/dist/deno-kv-CSYGvRx4.js +120 -0
- package/dist/{driver-BT9WefKi.d.ts → driver-D9fI27jl.d.ts} +33 -3
- package/dist/error-diagnostics-D_cQeZTi.js +82 -0
- package/dist/errors-Dc2oiW-Y.js +38 -0
- package/dist/errors.d.ts +12 -7
- package/dist/errors.js +2 -20
- package/dist/fs-lite-CbLKxLut.js +90 -0
- package/dist/index.d.ts +5 -4
- package/dist/index.js +92 -64
- package/dist/object-B1NW521B.js +7 -0
- package/dist/operations-ByuDE12r.js +1442 -0
- package/dist/operations-pn8_eGob.js +432 -0
- package/dist/operations-tNUdj3G4.d.ts +212 -0
- package/dist/operations.d.ts +68 -0
- package/dist/operations.js +455 -0
- package/dist/results-p7nPCnaJ.js +6 -0
- package/dist/runtime/cloudflare-kv.d.ts +3 -4
- package/dist/runtime/cloudflare-kv.js +84 -8
- package/dist/runtime/upstash-driver.d.ts +4 -6
- package/dist/runtime/upstash-driver.js +34 -44
- package/dist/{types-CO0DRjJa.d.ts → types-CMDvN0Wr.d.ts} +20 -17
- package/dist/utils2-Dsb9P4_2.js +28 -0
- package/dist/virtual.d.ts +1 -1
- package/dist/vite.d.ts +14 -10
- package/dist/vite.js +603 -224
- package/package.json +56 -16
- package/dist/deno-kv-cJx3jU10.js +0 -69
- package/dist/fs-lite-BxzdiJSi.js +0 -79
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import "./types-CMDvN0Wr.js";
|
|
2
|
+
import { t as AnyOperation } from "./operations-tNUdj3G4.js";
|
|
3
|
+
//#region src/runtime/operations.d.ts
|
|
4
|
+
interface KVDevListResult {
|
|
5
|
+
/** Present when more keys exist. Pass it as `--cursor` to read the next page. */
|
|
6
|
+
cursor?: string;
|
|
7
|
+
keys: string[];
|
|
8
|
+
limit: number;
|
|
9
|
+
prefix: string;
|
|
10
|
+
store: string;
|
|
11
|
+
stores: string[];
|
|
12
|
+
}
|
|
13
|
+
interface KVDevGetResult {
|
|
14
|
+
/** With `preview`: whether text/JSON editing preserves the value. */
|
|
15
|
+
editable?: boolean;
|
|
16
|
+
/** `base64` when the stored value is binary. `value` is then the base64 text. */
|
|
17
|
+
encoding?: "base64";
|
|
18
|
+
found: boolean;
|
|
19
|
+
/** With `preview`: how `value` is written. */
|
|
20
|
+
format?: "json" | "text";
|
|
21
|
+
/**
|
|
22
|
+
* Whether the key can expire. `none`: the store never expires keys (fs-lite ignores TTL). `unknown`: the store can
|
|
23
|
+
* expire keys, but its driver cannot report the time left, so a write that sets no TTL removes the expiry.
|
|
24
|
+
*/
|
|
25
|
+
expiry?: "none" | "unknown";
|
|
26
|
+
/** With `preview`: the value was cut at 256 KiB. */
|
|
27
|
+
truncated?: true;
|
|
28
|
+
key: string;
|
|
29
|
+
store: string;
|
|
30
|
+
/** JavaScript type of the stored value, for example `string`, `object`, `number`, or `bytes`. */
|
|
31
|
+
type?: string;
|
|
32
|
+
value?: unknown;
|
|
33
|
+
}
|
|
34
|
+
interface KVDevHasResult {
|
|
35
|
+
exists: boolean;
|
|
36
|
+
key: string;
|
|
37
|
+
store: string;
|
|
38
|
+
}
|
|
39
|
+
interface KVDevSetResult {
|
|
40
|
+
/** `true` when the key did not exist before the write. */
|
|
41
|
+
created: boolean;
|
|
42
|
+
key: string;
|
|
43
|
+
/** Limit of the provider that the write is subject to, for example a TTL that the driver ignores. */
|
|
44
|
+
notice?: string;
|
|
45
|
+
store: string;
|
|
46
|
+
/** Effective TTL in seconds passed to the driver. */
|
|
47
|
+
ttl?: number;
|
|
48
|
+
type: string;
|
|
49
|
+
}
|
|
50
|
+
interface KVDevDeleteResult {
|
|
51
|
+
/** `true` when the key was found before the delete. */
|
|
52
|
+
deleted: boolean;
|
|
53
|
+
key: string;
|
|
54
|
+
store: string;
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region ../internal/src/operations-dev.d.ts
|
|
58
|
+
/** Bundled into owner packages and used only by their serve-only generated Nitro route. */
|
|
59
|
+
export declare function createStandaloneOperationHandler(sources: {
|
|
60
|
+
operations: unknown;
|
|
61
|
+
plugin: string;
|
|
62
|
+
}[], root: string): (event: object) => Promise<Response>;
|
|
63
|
+
//#endregion
|
|
64
|
+
//#region src/operations.d.ts
|
|
65
|
+
/** The `kv.*` operations: list, get, has, set, and del. The Console, `vitehub kv`, and agents run them. */
|
|
66
|
+
export declare const kvOperations: readonly AnyOperation[];
|
|
67
|
+
//#endregion
|
|
68
|
+
export type { KVDevDeleteResult, KVDevGetResult, KVDevHasResult, KVDevListResult, KVDevSetResult };
|
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import { a as defineOperation, d as runOperation, f as toOperationFailure, i as createOperationRegistry, l as operationsOf, o as operationRootHeader, s as operationRpcHeader, t as assertOperationProject, u as projectRootHash } from "./operations-ByuDE12r.js";
|
|
2
|
+
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
3
|
+
import { i as resolveWaitUntil, r as getCloudflareEnv } from "./cloudflare-env-C5rM7kUY.js";
|
|
4
|
+
import * as v from "valibot";
|
|
5
|
+
//#region ../internal/src/secret.ts
|
|
6
|
+
const secretEncoder = new TextEncoder();
|
|
7
|
+
/**
|
|
8
|
+
* Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
|
|
9
|
+
* when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
|
|
10
|
+
*/
|
|
11
|
+
function isViteHubSecretEqual(actual, expected) {
|
|
12
|
+
if (!actual || !expected) return false;
|
|
13
|
+
const left = secretEncoder.encode(actual);
|
|
14
|
+
const right = secretEncoder.encode(expected);
|
|
15
|
+
let difference = left.length ^ right.length;
|
|
16
|
+
for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
|
|
17
|
+
return difference === 0;
|
|
18
|
+
}
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region ../internal/src/dev-endpoint.ts
|
|
21
|
+
const viteHubDevRequestGrantBrand = Symbol("vitehub.devRequestGrant");
|
|
22
|
+
const devRequestGrants = /* @__PURE__ */ new WeakMap();
|
|
23
|
+
function grantDevRequest(request, label) {
|
|
24
|
+
const grant = Object.freeze({
|
|
25
|
+
[viteHubDevRequestGrantBrand]: true,
|
|
26
|
+
label
|
|
27
|
+
});
|
|
28
|
+
devRequestGrants.set(grant, request);
|
|
29
|
+
return { grant };
|
|
30
|
+
}
|
|
31
|
+
function rejectDevRequest(rejection) {
|
|
32
|
+
return { rejection };
|
|
33
|
+
}
|
|
34
|
+
const fileOrExtensionProtocol = /^(?:file|.+-extension):/i;
|
|
35
|
+
const ipv4Octet = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)";
|
|
36
|
+
const ipv4Literal = new RegExp(`^${ipv4Octet}(?:\\.${ipv4Octet}){3}$`);
|
|
37
|
+
/**
|
|
38
|
+
* Tests IP literals like `node:net` `isIP`, without a Node import, so the Nitro-side check also runs in Worker
|
|
39
|
+
* runtimes. IPv4 uses the Node pattern (dotted decimal, no leading zeros). IPv6 uses the WHATWG URL parser, which
|
|
40
|
+
* rejects zone IDs. Browsers do not send zone IDs in `Host`.
|
|
41
|
+
*/
|
|
42
|
+
function isIPv4Literal(value) {
|
|
43
|
+
return ipv4Literal.test(value);
|
|
44
|
+
}
|
|
45
|
+
function isIPv6Literal(value) {
|
|
46
|
+
if (!value.includes(":") || !/^[\d.:a-f]+$/i.test(value)) return false;
|
|
47
|
+
try {
|
|
48
|
+
return new URL(`http://[${value}]/`).hostname !== "";
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
function hostHeaderAllowed(host, allowedHosts) {
|
|
54
|
+
if (fileOrExtensionProtocol.test(host)) return true;
|
|
55
|
+
const trimmed = host.trim();
|
|
56
|
+
if (trimmed.startsWith("[")) {
|
|
57
|
+
const end = trimmed.indexOf("]");
|
|
58
|
+
return end > 0 && isIPv6Literal(trimmed.slice(1, end));
|
|
59
|
+
}
|
|
60
|
+
const colon = trimmed.indexOf(":");
|
|
61
|
+
const hostname = (colon === -1 ? trimmed : trimmed.slice(0, colon)).toLowerCase();
|
|
62
|
+
if (isIPv4Literal(hostname)) return true;
|
|
63
|
+
if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
|
|
64
|
+
return allowedHosts.some((allowed) => {
|
|
65
|
+
const normalized = allowed.toLowerCase();
|
|
66
|
+
return normalized === hostname || normalized.startsWith(".") && (normalized.slice(1) === hostname || hostname.endsWith(normalized));
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Checks the host of a request that reaches the Nitro dev handler.
|
|
71
|
+
*
|
|
72
|
+
* {@link forwardViteHubDevRequestToNitro} always calls `http://localhost`, so a forwarded request passes. The Nitro
|
|
73
|
+
* route is also reachable over HTTP on the dev server, and the Nitro runtime does not know `server.allowedHosts`.
|
|
74
|
+
* This check therefore accepts only `localhost`, `*.localhost`, and IP literals in the request URL and in the `Host`
|
|
75
|
+
* header. A DNS rebinding page uses another host name, so it gets `403`.
|
|
76
|
+
*/
|
|
77
|
+
function isViteHubNitroDevHostAllowed(request) {
|
|
78
|
+
const host = request.headers.get("host");
|
|
79
|
+
return hostHeaderAllowed(new URL(request.url).host, []) && (host === null || hostHeaderAllowed(host, []));
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Checks a request inside the Nitro dev handler: the host, the guard header, the request origin, `POST`, the JSON
|
|
83
|
+
* content type, and the optional owner `authorize` callback. Returns a grant bound to `request`, or the rejection
|
|
84
|
+
* response. The Nitro route exists only in `vite dev`, but it is reachable on the dev server origin, so it checks the
|
|
85
|
+
* same guard as the Vite endpoint.
|
|
86
|
+
*/
|
|
87
|
+
async function validateViteHubNitroDevRequest(request, guard) {
|
|
88
|
+
if (!isViteHubNitroDevHostAllowed(request)) return rejectDevRequest(new Response(`Forbidden ${guard.label} host.`, { status: 403 }));
|
|
89
|
+
if (!isViteHubSecretEqual(request.headers.get(guard.header), guard.headerValue)) return rejectDevRequest(new Response(`Forbidden ${guard.label} request.`, { status: 403 }));
|
|
90
|
+
const origin = request.headers.get("origin");
|
|
91
|
+
if (origin && origin !== new URL(request.url).origin) return rejectDevRequest(new Response(`Forbidden ${guard.label} origin.`, { status: 403 }));
|
|
92
|
+
if (request.method !== "POST") return rejectDevRequest(new Response("Method not allowed.", {
|
|
93
|
+
headers: { allow: "POST" },
|
|
94
|
+
status: 405
|
|
95
|
+
}));
|
|
96
|
+
if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) return rejectDevRequest(new Response(`${guard.label} requests must use application/json.`, { status: 415 }));
|
|
97
|
+
const rejection = await guard.authorize?.(request);
|
|
98
|
+
return rejection ? rejectDevRequest(rejection) : grantDevRequest(request, guard.label);
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
//#region ../internal/src/runtime/h3-v1-request.ts
|
|
102
|
+
const payloadMethods = /* @__PURE__ */ new Set([
|
|
103
|
+
"DELETE",
|
|
104
|
+
"PATCH",
|
|
105
|
+
"POST",
|
|
106
|
+
"PUT"
|
|
107
|
+
]);
|
|
108
|
+
const rawBodySymbol = Symbol.for("h3RawBody");
|
|
109
|
+
const nodeEventRequests = /* @__PURE__ */ new WeakMap();
|
|
110
|
+
/** Return true for an event with an own `node.req` object, such as an H3 1 event. */
|
|
111
|
+
function isH3V1Event(input) {
|
|
112
|
+
if (!Object.hasOwn(input, "node")) return false;
|
|
113
|
+
const node = Reflect.get(input, "node");
|
|
114
|
+
return isObjectLike(node) && isObjectLike(Reflect.get(node, "req"));
|
|
115
|
+
}
|
|
116
|
+
function isObjectLike(value) {
|
|
117
|
+
return value !== null && (typeof value === "object" || typeof value === "function");
|
|
118
|
+
}
|
|
119
|
+
function isWebRequest(value) {
|
|
120
|
+
if (!isObjectLike(value)) return false;
|
|
121
|
+
const headers = Reflect.get(value, "headers");
|
|
122
|
+
return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObjectLike(headers) && typeof Reflect.get(headers, "get") === "function";
|
|
123
|
+
}
|
|
124
|
+
function firstHeader(value) {
|
|
125
|
+
return Array.isArray(value) ? value[0] : value;
|
|
126
|
+
}
|
|
127
|
+
function readNodeRequestHeaders(request) {
|
|
128
|
+
const headers = new Headers();
|
|
129
|
+
for (const [name, value] of Object.entries(request.headers)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
|
|
130
|
+
else if (value !== void 0) headers.set(name, value);
|
|
131
|
+
return headers;
|
|
132
|
+
}
|
|
133
|
+
/** Rebuild the public URL. H3 1 removes the app base path from `url` and keeps it in `originalUrl`. */
|
|
134
|
+
function readNodeRequestURL(request) {
|
|
135
|
+
const host = firstHeader(request.headers.host) || "localhost";
|
|
136
|
+
const encrypted = request.socket?.encrypted || request.connection?.encrypted;
|
|
137
|
+
const protocol = firstHeader(request.headers["x-forwarded-proto"]) === "https" || encrypted ? "https" : "http";
|
|
138
|
+
const path = (request.originalUrl || request.url || "/").replace(/^[/\\]+/, "/");
|
|
139
|
+
return new URL(path, `${protocol}://${host}`);
|
|
140
|
+
}
|
|
141
|
+
function toBodyStream(value) {
|
|
142
|
+
if (value instanceof ReadableStream) return value;
|
|
143
|
+
if (value instanceof Uint8Array) return new ReadableStream({ start(controller) {
|
|
144
|
+
controller.enqueue(value);
|
|
145
|
+
controller.close();
|
|
146
|
+
} });
|
|
147
|
+
if (typeof value === "string") return new Blob([value]).stream();
|
|
148
|
+
if (value instanceof URLSearchParams) return new Blob([value.toString()]).stream();
|
|
149
|
+
if (value instanceof Object && Object.getPrototypeOf(value) === Object.prototype) return new Blob([JSON.stringify(value)]).stream();
|
|
150
|
+
}
|
|
151
|
+
async function openNodeRequestBody(event) {
|
|
152
|
+
const request = event.node.req;
|
|
153
|
+
const stored = event._requestBody ?? request[rawBodySymbol] ?? request.rawBody ?? request.body;
|
|
154
|
+
if (stored !== void 0 && stored !== null) {
|
|
155
|
+
const stream = toBodyStream(await stored);
|
|
156
|
+
if (stream) {
|
|
157
|
+
const reader = stream.getReader();
|
|
158
|
+
return () => reader.read();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const iterator = request[Symbol.asyncIterator]?.();
|
|
162
|
+
if (!iterator) return void 0;
|
|
163
|
+
const chunks = [];
|
|
164
|
+
const collected = [];
|
|
165
|
+
let total = 0;
|
|
166
|
+
let ended = false;
|
|
167
|
+
let failed = false;
|
|
168
|
+
let failure;
|
|
169
|
+
let waiting;
|
|
170
|
+
const produce = async () => {
|
|
171
|
+
try {
|
|
172
|
+
for await (const chunk of { [Symbol.asyncIterator]: () => iterator }) {
|
|
173
|
+
let bytes;
|
|
174
|
+
if (typeof chunk === "string") bytes = new TextEncoder().encode(chunk);
|
|
175
|
+
else if (chunk instanceof Uint8Array) bytes = chunk;
|
|
176
|
+
else throw new TypeError("[vitehub] Request body chunks must be strings or bytes.");
|
|
177
|
+
collected.push(bytes);
|
|
178
|
+
total += bytes.byteLength;
|
|
179
|
+
if (waiting) {
|
|
180
|
+
waiting.resolve({ value: bytes });
|
|
181
|
+
waiting = void 0;
|
|
182
|
+
} else chunks.push(bytes);
|
|
183
|
+
}
|
|
184
|
+
ended = true;
|
|
185
|
+
waiting?.resolve({ done: true });
|
|
186
|
+
waiting = void 0;
|
|
187
|
+
} catch (error) {
|
|
188
|
+
failed = true;
|
|
189
|
+
failure = error;
|
|
190
|
+
ended = true;
|
|
191
|
+
waiting?.reject(error);
|
|
192
|
+
waiting = void 0;
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
const bytes = new Uint8Array(total);
|
|
196
|
+
let offset = 0;
|
|
197
|
+
for (const chunk of collected) {
|
|
198
|
+
bytes.set(chunk, offset);
|
|
199
|
+
offset += chunk.byteLength;
|
|
200
|
+
}
|
|
201
|
+
return bytes;
|
|
202
|
+
};
|
|
203
|
+
let body;
|
|
204
|
+
const start = () => body ??= produce();
|
|
205
|
+
event._requestBody = { then: (resolve, reject) => start().then(resolve, reject) };
|
|
206
|
+
return async () => {
|
|
207
|
+
start();
|
|
208
|
+
body?.catch(() => {});
|
|
209
|
+
if (failed) throw failure;
|
|
210
|
+
if (chunks.length) return { value: chunks.shift() };
|
|
211
|
+
if (ended) return { done: true };
|
|
212
|
+
return new Promise((resolve, reject) => {
|
|
213
|
+
waiting = {
|
|
214
|
+
resolve,
|
|
215
|
+
reject
|
|
216
|
+
};
|
|
217
|
+
});
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** Read the body lazily, from a value a host already read or from the Node request stream. */
|
|
221
|
+
function readNodeRequestBody(event) {
|
|
222
|
+
let reader;
|
|
223
|
+
return new ReadableStream({ async pull(controller) {
|
|
224
|
+
const chunk = await (await (reader ??= openNodeRequestBody(event)))?.();
|
|
225
|
+
if (!chunk || chunk.done) {
|
|
226
|
+
controller.close();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const value = chunk.value;
|
|
230
|
+
if (typeof value === "string") controller.enqueue(new TextEncoder().encode(value));
|
|
231
|
+
else if (value instanceof Uint8Array) controller.enqueue(value);
|
|
232
|
+
else controller.error(/* @__PURE__ */ new TypeError("[vitehub] Request body chunks must be strings or bytes."));
|
|
233
|
+
} }, { highWaterMark: 0 });
|
|
234
|
+
}
|
|
235
|
+
/** Return one Web Request per H3 1 event. The body is read only when a caller reads the Request body. */
|
|
236
|
+
function toH3V1Request(event) {
|
|
237
|
+
const cached = nodeEventRequests.get(event);
|
|
238
|
+
if (cached) return cached;
|
|
239
|
+
if (isWebRequest(event.web?.request)) return event.web.request;
|
|
240
|
+
const request = event.node.req;
|
|
241
|
+
const method = (request.method || "GET").toUpperCase();
|
|
242
|
+
const init = {
|
|
243
|
+
headers: readNodeRequestHeaders(request),
|
|
244
|
+
method
|
|
245
|
+
};
|
|
246
|
+
if (payloadMethods.has(method)) {
|
|
247
|
+
init.body = readNodeRequestBody(event);
|
|
248
|
+
init.duplex = "half";
|
|
249
|
+
}
|
|
250
|
+
const webRequest = new Request(readNodeRequestURL(request), init);
|
|
251
|
+
nodeEventRequests.set(event, webRequest);
|
|
252
|
+
return webRequest;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Return the Web Request of a request, an H3 2 event with an own `req` request, or an H3 1 event such as Nuxt 4's.
|
|
256
|
+
* H3 1 events have no `url`, so read the URL from the request this returns. Throws a `TypeError` for any other value.
|
|
257
|
+
*/
|
|
258
|
+
function toEventRequest(event) {
|
|
259
|
+
if (isWebRequest(event)) return event;
|
|
260
|
+
const req = Object.hasOwn(event, "req") ? Reflect.get(event, "req") : void 0;
|
|
261
|
+
if (isWebRequest(req)) return req;
|
|
262
|
+
if (isH3V1Event(event)) return toH3V1Request(event);
|
|
263
|
+
throw new TypeError("[vitehub] Expected a Request, an H3 2 event, or an H3 1 event.");
|
|
264
|
+
}
|
|
265
|
+
//#endregion
|
|
266
|
+
//#region ../internal/src/operations-dev.ts
|
|
267
|
+
function readPath(value, ...path) {
|
|
268
|
+
for (const key of path) value = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
|
|
269
|
+
return value;
|
|
270
|
+
}
|
|
271
|
+
function localHost(host) {
|
|
272
|
+
try {
|
|
273
|
+
const name = new URL(`http://${host}`).hostname;
|
|
274
|
+
return name === "localhost" || name.endsWith(".localhost") || name === "127.0.0.1" || name === "[::1]";
|
|
275
|
+
} catch {
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
function reject(status, message) {
|
|
280
|
+
throw Object.assign(new Error(message), {
|
|
281
|
+
code: "OPERATION_DEV_REQUEST",
|
|
282
|
+
status
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/** Bundled into owner packages and used only by their serve-only generated Nitro route. */
|
|
286
|
+
function createStandaloneOperationHandler(sources, root) {
|
|
287
|
+
const registry = createOperationRegistry(sources.map((source) => ({
|
|
288
|
+
...source,
|
|
289
|
+
operations: operationsOf(source.operations)
|
|
290
|
+
})));
|
|
291
|
+
const defaultLimit = 65536;
|
|
292
|
+
const maximum = Math.max(defaultLimit, ...registry.list().map((operation) => operation.maxRequestBytes ?? defaultLimit));
|
|
293
|
+
return async (event) => {
|
|
294
|
+
const headers = {
|
|
295
|
+
"cache-control": "no-store",
|
|
296
|
+
"x-content-type-options": "nosniff",
|
|
297
|
+
[operationRootHeader]: projectRootHash(root)
|
|
298
|
+
};
|
|
299
|
+
try {
|
|
300
|
+
const request = toEventRequest(event);
|
|
301
|
+
const address = [
|
|
302
|
+
readPath(event, "req", "ip"),
|
|
303
|
+
readPath(event, "req", "context", "clientAddress"),
|
|
304
|
+
readPath(event, "req", "runtime", "node", "req", "socket", "remoteAddress"),
|
|
305
|
+
readPath(event, "node", "req", "socket", "remoteAddress")
|
|
306
|
+
].find((value) => typeof value === "string" && value !== "");
|
|
307
|
+
const forwarded = request.headers.get("x-forwarded-host");
|
|
308
|
+
if (!localHost(request.headers.get("host") ?? new URL(request.url).host) || forwarded && !localHost(forwarded) || address && address !== "::1" && !address.startsWith("127.") && !address.startsWith("::ffff:127.")) reject(403, "Standalone development operations accept only local requests.");
|
|
309
|
+
const site = request.headers.get("sec-fetch-site");
|
|
310
|
+
if (site === "cross-site" || site === "same-site") reject(403, "Cross-origin operation requests are not allowed.");
|
|
311
|
+
const checked = await validateViteHubNitroDevRequest(request, {
|
|
312
|
+
header: operationRpcHeader,
|
|
313
|
+
headerValue: "1",
|
|
314
|
+
label: "Operation RPC"
|
|
315
|
+
});
|
|
316
|
+
if (checked.rejection) reject(checked.rejection.status, await checked.rejection.text());
|
|
317
|
+
assertOperationProject(request, root);
|
|
318
|
+
const reader = request.body?.getReader();
|
|
319
|
+
const decoder = new TextDecoder();
|
|
320
|
+
let text = "";
|
|
321
|
+
let bytes = 0;
|
|
322
|
+
try {
|
|
323
|
+
if (reader) while (true) {
|
|
324
|
+
const chunk = await reader.read();
|
|
325
|
+
if (chunk.done) break;
|
|
326
|
+
bytes += chunk.value.byteLength;
|
|
327
|
+
if (bytes > maximum) reject(413, "Operation request exceeds the byte limit.");
|
|
328
|
+
text += decoder.decode(chunk.value, { stream: true });
|
|
329
|
+
}
|
|
330
|
+
text += decoder.decode();
|
|
331
|
+
} catch (error) {
|
|
332
|
+
await reader?.cancel();
|
|
333
|
+
throw error;
|
|
334
|
+
} finally {
|
|
335
|
+
reader?.releaseLock();
|
|
336
|
+
}
|
|
337
|
+
let payload;
|
|
338
|
+
try {
|
|
339
|
+
payload = JSON.parse(text);
|
|
340
|
+
} catch {
|
|
341
|
+
reject(400, "Malformed operation request.");
|
|
342
|
+
}
|
|
343
|
+
if (!payload || typeof payload !== "object" || !("operation" in payload) || typeof payload.operation !== "string") reject(400, "Invalid operation request.");
|
|
344
|
+
if (bytes > (registry.get(payload.operation)?.maxRequestBytes ?? defaultLimit)) reject(413, "Operation request exceeds the byte limit.");
|
|
345
|
+
const response = {};
|
|
346
|
+
const result = await runOperation(registry, payload.operation, "input" in payload ? payload.input : void 0, {
|
|
347
|
+
access: {
|
|
348
|
+
mode: "local",
|
|
349
|
+
sections: "all"
|
|
350
|
+
},
|
|
351
|
+
development: true,
|
|
352
|
+
surface: "cli",
|
|
353
|
+
user: null,
|
|
354
|
+
request,
|
|
355
|
+
response,
|
|
356
|
+
env: getCloudflareEnv(event, { fallback: false }),
|
|
357
|
+
waitUntil: resolveWaitUntil(event, { preferHost: true })
|
|
358
|
+
});
|
|
359
|
+
return Response.json(result, {
|
|
360
|
+
headers,
|
|
361
|
+
status: result.ok ? response.status ?? 200 : result.status
|
|
362
|
+
});
|
|
363
|
+
} catch (error) {
|
|
364
|
+
const failure = toOperationFailure(error);
|
|
365
|
+
return Response.json({
|
|
366
|
+
ok: false,
|
|
367
|
+
...failure
|
|
368
|
+
}, {
|
|
369
|
+
headers,
|
|
370
|
+
status: failure.status
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
//#endregion
|
|
376
|
+
//#region src/operations.ts
|
|
377
|
+
const runtime = () => import("./operations-pn8_eGob.js");
|
|
378
|
+
const store = v.optional(v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name a store.")));
|
|
379
|
+
const key = v.string();
|
|
380
|
+
function defineKVOperation(definition) {
|
|
381
|
+
return defineOperation({
|
|
382
|
+
...definition,
|
|
383
|
+
section: "kv",
|
|
384
|
+
user: false
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
/** The `kv.*` operations: list, get, has, set, and del. The Console, `vitehub kv`, and agents run them. */
|
|
388
|
+
const kvOperations = [
|
|
389
|
+
defineKVOperation({
|
|
390
|
+
cli: { command: "list" },
|
|
391
|
+
description: "List the keys of a KV store, one page at a time.",
|
|
392
|
+
input: v.object({
|
|
393
|
+
cursor: v.optional(v.string()),
|
|
394
|
+
limit: v.optional(v.pipe(v.number(), v.integer(), v.minValue(1), v.maxValue(kvDevMaximumListLimit))),
|
|
395
|
+
prefix: v.optional(v.string()),
|
|
396
|
+
store
|
|
397
|
+
}),
|
|
398
|
+
kind: "read",
|
|
399
|
+
name: "kv.list",
|
|
400
|
+
run: async (input) => await (await runtime()).runKVOperation("list", input)
|
|
401
|
+
}),
|
|
402
|
+
defineKVOperation({
|
|
403
|
+
cli: { positional: ["key"] },
|
|
404
|
+
description: "Read the value of one key. `preview` returns it as text of at most 256 KiB.",
|
|
405
|
+
input: v.object({
|
|
406
|
+
key,
|
|
407
|
+
preview: v.optional(v.boolean()),
|
|
408
|
+
store
|
|
409
|
+
}),
|
|
410
|
+
kind: "read",
|
|
411
|
+
name: "kv.get",
|
|
412
|
+
run: async (input) => await (await runtime()).runKVOperation("get", input)
|
|
413
|
+
}),
|
|
414
|
+
defineKVOperation({
|
|
415
|
+
cli: { positional: ["key"] },
|
|
416
|
+
description: "Check if a key exists.",
|
|
417
|
+
input: v.object({
|
|
418
|
+
key,
|
|
419
|
+
store
|
|
420
|
+
}),
|
|
421
|
+
kind: "read",
|
|
422
|
+
name: "kv.has",
|
|
423
|
+
run: async (input) => await (await runtime()).runKVOperation("has", input)
|
|
424
|
+
}),
|
|
425
|
+
defineKVOperation({
|
|
426
|
+
cli: { positional: ["key", "value"] },
|
|
427
|
+
description: "Write the value of one key. A string, or any JSON value.",
|
|
428
|
+
input: v.object({
|
|
429
|
+
key,
|
|
430
|
+
store,
|
|
431
|
+
ttl: v.optional(v.pipe(v.number(), v.finite(), v.gtValue(0))),
|
|
432
|
+
value: v.unknown()
|
|
433
|
+
}),
|
|
434
|
+
kind: "write",
|
|
435
|
+
maxRequestBytes: 4194304,
|
|
436
|
+
name: "kv.set",
|
|
437
|
+
run: async (input) => await (await runtime()).runKVOperation("set", input)
|
|
438
|
+
}),
|
|
439
|
+
defineKVOperation({
|
|
440
|
+
cli: {
|
|
441
|
+
command: "del",
|
|
442
|
+
positional: ["key"]
|
|
443
|
+
},
|
|
444
|
+
description: "Delete one key. There is no operation that clears a store.",
|
|
445
|
+
input: v.object({
|
|
446
|
+
key,
|
|
447
|
+
store
|
|
448
|
+
}),
|
|
449
|
+
kind: "destructive",
|
|
450
|
+
name: "kv.del",
|
|
451
|
+
run: async (input) => await (await runtime()).runKVOperation("del", input)
|
|
452
|
+
})
|
|
453
|
+
];
|
|
454
|
+
//#endregion
|
|
455
|
+
export { createStandaloneOperationHandler, kvOperations };
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { t as KVRuntimeDriver } from "../driver-
|
|
2
|
-
|
|
1
|
+
import { t as KVRuntimeDriver } from "../driver-D9fI27jl.js";
|
|
3
2
|
//#region src/runtime/cloudflare-kv.d.ts
|
|
4
3
|
declare function createCloudflareDriver(options: Record<string, unknown>): KVRuntimeDriver;
|
|
5
|
-
declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
|
|
4
|
+
export declare function createCloudflareKVStorage(options: Record<string, unknown>): unknown;
|
|
6
5
|
//#endregion
|
|
7
|
-
export {
|
|
6
|
+
export { createCloudflareDriver as default };
|
|
@@ -1,23 +1,99 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as kvErrorDiagnostics } from "../error-diagnostics-D_cQeZTi.js";
|
|
2
|
+
import { t as getActiveCloudflareBinding } from "../cloudflare-env-C5rM7kUY.js";
|
|
3
|
+
import { n as normalizeKVListPrefix, t as createKVStorage } from "../create-storage-29gMzf41.js";
|
|
4
|
+
import { n as recordCursor, t as createCursorHistory } from "../cursor-history-dqYDlsaD.js";
|
|
2
5
|
import createDriver from "unstorage/drivers/cloudflare-kv-binding";
|
|
3
6
|
//#region src/runtime/cloudflare-kv.ts
|
|
7
|
+
function isCloudflareKVString(value) {
|
|
8
|
+
return typeof value === "string";
|
|
9
|
+
}
|
|
10
|
+
function isCloudflareKVListPage(value) {
|
|
11
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
12
|
+
const page = value;
|
|
13
|
+
if (typeof page.list_complete !== "boolean" || !Array.isArray(page.keys)) return false;
|
|
14
|
+
if (!page.keys.every((key) => {
|
|
15
|
+
if (!key || typeof key !== "object" || Array.isArray(key)) return false;
|
|
16
|
+
return isCloudflareKVString(Reflect.get(key, "name"));
|
|
17
|
+
})) return false;
|
|
18
|
+
return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
|
|
19
|
+
}
|
|
20
|
+
const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
|
|
21
|
+
let nextCloudflareBindingIdentity = 0;
|
|
22
|
+
function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
|
|
23
|
+
if (typeof namespaceId === "string" && namespaceId.length > 0) return `cloudflare-kv:id:${namespaceId}`;
|
|
24
|
+
if (binding && typeof binding === "object") {
|
|
25
|
+
let identity = cloudflareBindingIdentities.get(binding);
|
|
26
|
+
if (identity === void 0) {
|
|
27
|
+
identity = ++nextCloudflareBindingIdentity;
|
|
28
|
+
cloudflareBindingIdentities.set(binding, identity);
|
|
29
|
+
}
|
|
30
|
+
return `cloudflare-kv:object:${identity}`;
|
|
31
|
+
}
|
|
32
|
+
return typeof bindingName === "string" ? `cloudflare-kv:binding:${bindingName}` : "cloudflare-kv:default";
|
|
33
|
+
}
|
|
4
34
|
function createCloudflareDriver(options) {
|
|
5
|
-
const
|
|
35
|
+
const bindingName = options.binding;
|
|
36
|
+
const namespaceId = options.namespaceId;
|
|
37
|
+
const driverOptions = typeof bindingName === "string" ? {
|
|
38
|
+
...options,
|
|
39
|
+
get binding() {
|
|
40
|
+
return getActiveCloudflareBinding(bindingName) ?? bindingName;
|
|
41
|
+
}
|
|
42
|
+
} : options;
|
|
43
|
+
const driver = createDriver(driverOptions);
|
|
44
|
+
const cursorNamespace = cloudflareBindingNamespace(bindingName, namespaceId);
|
|
45
|
+
const cursorHistories = createCursorHistory(cursorNamespace);
|
|
46
|
+
let disposed = false;
|
|
47
|
+
const dispose = driver.dispose;
|
|
48
|
+
driver.dispose = async () => {
|
|
49
|
+
disposed = true;
|
|
50
|
+
cursorHistories.clear();
|
|
51
|
+
try {
|
|
52
|
+
await dispose?.call(driver);
|
|
53
|
+
} finally {
|
|
54
|
+
cursorHistories.clear();
|
|
55
|
+
}
|
|
56
|
+
};
|
|
6
57
|
driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
|
|
58
|
+
if (disposed) throw new Error("KV storage has been disposed.");
|
|
7
59
|
const listOptions = { limit };
|
|
8
60
|
if (cursor) listOptions.cursor = cursor;
|
|
9
61
|
if (prefix) listOptions.prefix = prefix;
|
|
10
|
-
const
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
62
|
+
const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
|
|
63
|
+
const requestNamespace = cloudflareBindingNamespace(bindingName, namespaceId, activeBinding);
|
|
64
|
+
const continuation = cursor ? cursorHistories.take(cursor, requestNamespace) : {
|
|
65
|
+
providerCursor: void 0,
|
|
66
|
+
history: /* @__PURE__ */ new Set(),
|
|
67
|
+
namespace: requestNamespace
|
|
68
|
+
};
|
|
69
|
+
try {
|
|
70
|
+
if (continuation.providerCursor) listOptions.cursor = continuation.providerCursor;
|
|
71
|
+
const cursors = continuation.history;
|
|
72
|
+
const page = await driver.getInstance().list(listOptions);
|
|
73
|
+
if (!isCloudflareKVListPage(page)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV list returned an invalid page." });
|
|
74
|
+
const result = { keys: page.keys.map((key) => key.name) };
|
|
75
|
+
if (!page.list_complete) {
|
|
76
|
+
if (disposed) throw new Error("KV storage has been disposed.");
|
|
77
|
+
if (cursors.has(page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a repeated pagination cursor." });
|
|
78
|
+
if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected pagination after the cursor history limit was reached." });
|
|
79
|
+
result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
|
|
80
|
+
}
|
|
81
|
+
cursorHistories.complete(cursor);
|
|
82
|
+
return result;
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (cursor && !disposed) cursorHistories.restore(cursor, continuation);
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
14
87
|
};
|
|
15
88
|
return driver;
|
|
16
89
|
}
|
|
17
90
|
function createCloudflareKVStorage(options) {
|
|
18
91
|
const driver = createCloudflareDriver(options);
|
|
19
|
-
const storage =
|
|
20
|
-
storage.listKeys = (listOptions) => driver.listKeys(
|
|
92
|
+
const storage = createKVStorage(driver);
|
|
93
|
+
storage.listKeys = (listOptions) => driver.listKeys({
|
|
94
|
+
...listOptions,
|
|
95
|
+
prefix: normalizeKVListPrefix(listOptions.prefix)
|
|
96
|
+
});
|
|
21
97
|
return storage;
|
|
22
98
|
}
|
|
23
99
|
//#endregion
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as KVRuntimeDriver } from "../driver-
|
|
3
|
-
|
|
1
|
+
import { _ as ResolvedUpstashKVStoreConfig } from "../types-CMDvN0Wr.js";
|
|
2
|
+
import { t as KVRuntimeDriver } from "../driver-D9fI27jl.js";
|
|
4
3
|
//#region src/runtime/upstash-driver.d.ts
|
|
5
|
-
|
|
6
|
-
//#endregion
|
|
7
|
-
export { createUpstashKVDriver as default };
|
|
4
|
+
export default function createUpstashKVDriver(options: ResolvedUpstashKVStoreConfig): KVRuntimeDriver;
|
|
5
|
+
//#endregion
|