@vite-hub/kv 0.0.4 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +110 -14
- package/dist/batch--v0ri69O.js +40 -0
- package/dist/cli-DpPhz_Ek.d.ts +163 -0
- package/dist/cli.d.ts +17 -0
- package/dist/cli.js +469 -0
- package/dist/cloudflare-env-lOtHHsgP.js +46 -0
- package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
- package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
- package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
- package/dist/config-BXEVoZE3.js +250 -0
- package/dist/{dist-DDW1iC5f.js → create-storage-BGsrQKw3.js} +266 -115
- package/dist/cursor-history-BqIQePNP.js +165 -0
- package/dist/database-72Jk3VVk.js +250 -0
- package/dist/deno-kv-BM9mYdUp.js +128 -0
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/driver-BwxgaQ-f.d.ts +15 -0
- package/dist/durability.d.ts +17 -0
- package/dist/durability.js +53 -0
- package/dist/error-diagnostics-BxqvtEIb.js +147 -0
- package/dist/errors-DbwufFZp.js +60 -0
- package/dist/errors.d.ts +23 -7
- package/dist/errors.js +2 -20
- package/dist/fs-lite-BLZId9_P.js +386 -0
- package/dist/fs-lite-RAoxu8L0.js +2 -0
- package/dist/index.d.ts +10 -4
- package/dist/index.js +364 -109
- package/dist/inspect-BIKQsqX4.js +118 -0
- package/dist/invariant-DolT9EEx.js +22 -0
- package/dist/main-F3Y22_uV.js +2353 -0
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-B-WZ7P1h.js +1351 -0
- package/dist/operations-Ch-gKaey.js +441 -0
- package/dist/operations.d.ts +75 -0
- package/dist/operations.js +318 -0
- package/dist/redis-shared-E5mahECF.js +94 -0
- package/dist/results-p7nPCnaJ.js +6 -0
- package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
- package/dist/runtime/cloudflare-kv.d.ts +3 -4
- package/dist/runtime/cloudflare-kv.js +1 -23
- package/dist/runtime/cloudflare-request-env.d.ts +7 -0
- package/dist/runtime/cloudflare-request-env.js +11 -0
- package/dist/runtime/nitro-plugin.d.ts +12 -0
- package/dist/runtime/nitro-plugin.js +22 -0
- package/dist/runtime/redis-driver.d.ts +11 -0
- package/dist/runtime/redis-driver.js +113 -0
- package/dist/runtime/unstorage-driver.d.ts +14 -0
- package/dist/runtime/unstorage-driver.js +33 -0
- package/dist/runtime/upstash-driver.d.ts +4 -6
- package/dist/runtime/upstash-driver.js +60 -110
- package/dist/{driver-BT9WefKi.d.ts → types-Bj3EQoRg.d.ts} +16 -11
- package/dist/types-DEiKew_3.d.ts +312 -0
- package/dist/upstash-DDlqTttY.js +40 -0
- package/dist/utils2-FozcTsmb.js +31 -0
- package/dist/virtual-module.d.ts +2 -0
- package/dist/virtual.d.ts +1 -1
- package/dist/vite.d.ts +159 -14
- package/dist/vite.js +1329 -2898
- package/package.json +68 -19
- package/dist/config-aM9Ae7tH.js +0 -110
- package/dist/deno-kv-cJx3jU10.js +0 -69
- package/dist/fs-lite-BxzdiJSi.js +0 -79
- package/dist/types-CO0DRjJa.d.ts +0 -78
package/dist/cli.js
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import { t as isRecord } from "./object-Da1zyPCR.js";
|
|
2
|
+
import { C as listSeedFiles, D as readViteHubDevTargetOption, S as askOnTerminal, T as readCliOptionValue, k as writeCliFailure, n as callOperationFromCli, w as parseCliPositiveInteger } from "./operations-B-WZ7P1h.js";
|
|
3
|
+
import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
|
|
4
|
+
import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { extname, join, relative, resolve } from "node:path";
|
|
7
|
+
import * as v from "valibot";
|
|
8
|
+
//#region src/cli.ts
|
|
9
|
+
const usageError = (problem) => kvErrorDiagnostics.KV_CLI_USAGE({ problem });
|
|
10
|
+
const kvDevTargetErrors = {
|
|
11
|
+
invalidInlineTimeout: usageError,
|
|
12
|
+
invalidTimeout: usageError,
|
|
13
|
+
missingValue: usageError
|
|
14
|
+
};
|
|
15
|
+
const kvCommands = [
|
|
16
|
+
{
|
|
17
|
+
description: "List keys of a KV store, one page at a time.",
|
|
18
|
+
key: false,
|
|
19
|
+
name: "list",
|
|
20
|
+
options: [
|
|
21
|
+
"prefix",
|
|
22
|
+
"limit",
|
|
23
|
+
"cursor"
|
|
24
|
+
]
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
description: "Print the value of one key.",
|
|
28
|
+
key: true,
|
|
29
|
+
name: "get",
|
|
30
|
+
options: []
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
description: "Check if a key exists. The exit code is 0 when it exists and 1 when it does not.",
|
|
34
|
+
key: true,
|
|
35
|
+
name: "has",
|
|
36
|
+
options: []
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
description: "Write the value of one key.",
|
|
40
|
+
key: true,
|
|
41
|
+
name: "set",
|
|
42
|
+
options: ["ttl", "json-value"],
|
|
43
|
+
value: true
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
description: "Delete one key.",
|
|
47
|
+
key: true,
|
|
48
|
+
name: "delete",
|
|
49
|
+
options: []
|
|
50
|
+
}
|
|
51
|
+
];
|
|
52
|
+
const setCommand = kvCommands.find((command) => command.name === "set");
|
|
53
|
+
const optionUsage = {
|
|
54
|
+
"cursor": "[--cursor <cursor>]",
|
|
55
|
+
"json-value": "[--json-value]",
|
|
56
|
+
"limit": "[--limit <n>]",
|
|
57
|
+
"prefix": "[--prefix <prefix>]",
|
|
58
|
+
"ttl": "[--ttl <seconds>]"
|
|
59
|
+
};
|
|
60
|
+
const optionHelp = {
|
|
61
|
+
"cursor": " --cursor <cursor> Read the page after this cursor. `list` prints the next cursor.",
|
|
62
|
+
"json-value": " --json-value Parse the value as JSON. Without it, the value is a string.",
|
|
63
|
+
"limit": ` --limit <n> Show at most n keys. Defaults to 100. Maximum ${kvDevMaximumListLimit}.`,
|
|
64
|
+
"prefix": " --prefix <prefix> Show only keys that start with this prefix.",
|
|
65
|
+
"ttl": " --ttl <seconds> Expire the key after this time. Some drivers ignore TTL or raise it to a minimum."
|
|
66
|
+
};
|
|
67
|
+
function commandUsage(command) {
|
|
68
|
+
const key = command.key ? " <key>" : "";
|
|
69
|
+
const value = command.value ? " <value|@file>" : "";
|
|
70
|
+
const options = command.options.map((option) => ` ${optionUsage[option]}`).join("");
|
|
71
|
+
return `vitehub kv ${command.name}${key}${value}${options} [--store <name>] [--json]${command.name === "delete" ? " [--yes]" : ""} [--url <url>]`;
|
|
72
|
+
}
|
|
73
|
+
function writeUsage(command, stream) {
|
|
74
|
+
stream.write([
|
|
75
|
+
`Usage: ${commandUsage(command)}`,
|
|
76
|
+
"",
|
|
77
|
+
command.description,
|
|
78
|
+
"The command runs the kv operation of the app: on the dev server of this project, or on a deployed app with --url.",
|
|
79
|
+
...command.value ? ["A value that starts with @ names a UTF-8 file. The path is relative to the current directory."] : [],
|
|
80
|
+
"",
|
|
81
|
+
"Options:",
|
|
82
|
+
...command.options.map((option) => optionHelp[option]),
|
|
83
|
+
" --store <name> KV store. Defaults to `default`.",
|
|
84
|
+
" --json Print JSON.",
|
|
85
|
+
...command.name === "delete" ? [" --yes, -y Delete without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
|
|
86
|
+
" --url <url> Deployed app URL. Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to sign the calls. Defaults to the dev server of this project.",
|
|
87
|
+
" --timeout <ms> Request timeout.",
|
|
88
|
+
" -h, --help Show this help.",
|
|
89
|
+
""
|
|
90
|
+
].join("\n"));
|
|
91
|
+
}
|
|
92
|
+
function parseTTL(value) {
|
|
93
|
+
const ttl = Number(value);
|
|
94
|
+
if (!value || !Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--ttl must be a positive number." });
|
|
95
|
+
return ttl;
|
|
96
|
+
}
|
|
97
|
+
function parseArgs(command, args) {
|
|
98
|
+
const parsed = {
|
|
99
|
+
help: false,
|
|
100
|
+
json: false,
|
|
101
|
+
jsonValue: false,
|
|
102
|
+
yes: false
|
|
103
|
+
};
|
|
104
|
+
const positionals = [];
|
|
105
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
106
|
+
const arg = args[index];
|
|
107
|
+
if (arg === "-h" || arg === "--help") {
|
|
108
|
+
parsed.help = true;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (arg === "--json") {
|
|
112
|
+
parsed.json = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (command.name === "delete" && (arg === "--yes" || arg === "-y")) {
|
|
116
|
+
parsed.yes = true;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (arg === "--json-value" && command.options.includes("json-value")) {
|
|
120
|
+
parsed.jsonValue = true;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (arg === "--") {
|
|
124
|
+
positionals.push(...args.slice(index + 1));
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
const targetOption = readViteHubDevTargetOption(args, index, parsed, kvDevTargetErrors);
|
|
128
|
+
if (targetOption !== void 0) {
|
|
129
|
+
index += targetOption;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
const store = readCliOptionValue(args, index, "store", usageError);
|
|
133
|
+
if (store) {
|
|
134
|
+
if (!store.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--store needs a nonempty name." });
|
|
135
|
+
parsed.store = store.value;
|
|
136
|
+
index += store.consumed;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
let matched = false;
|
|
140
|
+
for (const option of [
|
|
141
|
+
"cursor",
|
|
142
|
+
"limit",
|
|
143
|
+
"prefix",
|
|
144
|
+
"ttl"
|
|
145
|
+
]) {
|
|
146
|
+
if (!command.options.includes(option)) continue;
|
|
147
|
+
const read = readCliOptionValue(args, index, option, usageError);
|
|
148
|
+
if (!read) continue;
|
|
149
|
+
if (option === "cursor" && !read.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--cursor needs a nonempty value." });
|
|
150
|
+
if (option === "ttl") parsed.ttl = parseTTL(read.value);
|
|
151
|
+
else if (option === "limit") parsed.limit = parseCliPositiveInteger(option, read.value, usageError);
|
|
152
|
+
else parsed[option] = read.value;
|
|
153
|
+
index += read.consumed;
|
|
154
|
+
matched = true;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
if (matched) continue;
|
|
158
|
+
if (arg.startsWith("-")) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `Unknown option: ${arg}.` });
|
|
159
|
+
positionals.push(arg);
|
|
160
|
+
}
|
|
161
|
+
const expected = (command.key ? 1 : 0) + (command.value ? 1 : 0);
|
|
162
|
+
if (positionals.length > expected) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `Unexpected argument: ${positionals[expected]}.` });
|
|
163
|
+
if (command.key) parsed.key = positionals[0];
|
|
164
|
+
if (command.value) parsed.value = positionals[1];
|
|
165
|
+
if (!parsed.help && command.key && parsed.key === void 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "Missing key." });
|
|
166
|
+
if (!parsed.help && command.value && parsed.value === void 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "Missing value." });
|
|
167
|
+
if (parsed.limit !== void 0 && parsed.limit > 1e3) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `--limit must be at most ${kvDevMaximumListLimit}.` });
|
|
168
|
+
return parsed;
|
|
169
|
+
}
|
|
170
|
+
function validateJSONNumbers(value) {
|
|
171
|
+
if (v.is(v.number(), value)) {
|
|
172
|
+
if (!Number.isFinite(value) || Object.is(value, -0)) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "JSON numbers must be finite and cannot be negative zero." });
|
|
173
|
+
if (Number.isInteger(value) && !Number.isSafeInteger(value)) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "JSON integers must be within the safe integer range. Use a string for larger integers." });
|
|
174
|
+
}
|
|
175
|
+
if (Array.isArray(value)) value.forEach(validateJSONNumbers);
|
|
176
|
+
else if (v.is(v.record(v.string(), v.unknown()), value)) Object.values(value).forEach(validateJSONNumbers);
|
|
177
|
+
}
|
|
178
|
+
function normalizedDecimal(source) {
|
|
179
|
+
const negative = source.startsWith("-");
|
|
180
|
+
const [mantissa = "", exponent = "0"] = source.replace(/^-/, "").split(/[eE]/);
|
|
181
|
+
const [whole = "", fraction = ""] = mantissa.split(".");
|
|
182
|
+
const digits = `${whole}${fraction}`.replace(/^0+/, "");
|
|
183
|
+
const significant = digits.replace(/0+$/, "");
|
|
184
|
+
const scale = BigInt(exponent) - BigInt(fraction.length) + BigInt(digits.length - significant.length);
|
|
185
|
+
return `${negative ? "-" : ""}${significant}e${scale}`;
|
|
186
|
+
}
|
|
187
|
+
async function readValue(parsed, cwd) {
|
|
188
|
+
const raw = parsed.value;
|
|
189
|
+
const text = raw.startsWith("@") ? await readFile(resolve(cwd, raw.slice(1)), "utf8") : raw;
|
|
190
|
+
if (!parsed.jsonValue) return text;
|
|
191
|
+
try {
|
|
192
|
+
const value = JSON.parse(text, (_key, value, context) => {
|
|
193
|
+
if (value === 0 && context?.source && /[1-9]/.test(context.source.split(/[eE]/, 1)[0])) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "JSON numbers cannot underflow to zero. Use a string to preserve the supplied value." });
|
|
194
|
+
if (v.is(v.number(), value)) validateJSONNumbers(value);
|
|
195
|
+
if (context?.source && v.is(v.number(), value) && value !== 0 && normalizedDecimal(context.source) !== normalizedDecimal(JSON.stringify(value))) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `${Math.abs(value) <= 2 ** -1022 ? "JSON subnormal numbers" : "JSON numbers"} cannot change magnitude when parsed. Use a string to preserve the supplied value.` });
|
|
196
|
+
return value;
|
|
197
|
+
});
|
|
198
|
+
validateJSONNumbers(value);
|
|
199
|
+
return value;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `The value is not valid JSON: ${error instanceof Error ? error.message : String(error)}` });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function formatValue(result) {
|
|
205
|
+
if (result.encoding === "base64" && v.is(v.string(), result.value)) return Uint8Array.from(atob(result.value), (character) => character.charCodeAt(0));
|
|
206
|
+
if (v.is(v.string(), result.value)) return result.value;
|
|
207
|
+
return `${JSON.stringify(result.value, null, 2)}\n`;
|
|
208
|
+
}
|
|
209
|
+
const targetFields = {
|
|
210
|
+
key: v.string(),
|
|
211
|
+
store: v.string()
|
|
212
|
+
};
|
|
213
|
+
const positiveNumber = v.pipe(v.number(), v.finite(), v.gtValue(0));
|
|
214
|
+
const resultSchemas = {
|
|
215
|
+
list: v.object({
|
|
216
|
+
cursor: v.optional(v.string()),
|
|
217
|
+
driver: v.optional(v.picklist([
|
|
218
|
+
"cloudflare",
|
|
219
|
+
"database",
|
|
220
|
+
"deno-kv",
|
|
221
|
+
"fs-lite",
|
|
222
|
+
"redis",
|
|
223
|
+
"upstash"
|
|
224
|
+
])),
|
|
225
|
+
keys: v.array(v.string()),
|
|
226
|
+
limit: v.pipe(positiveNumber, v.integer()),
|
|
227
|
+
prefix: v.string(),
|
|
228
|
+
store: v.string(),
|
|
229
|
+
stores: v.array(v.string())
|
|
230
|
+
}),
|
|
231
|
+
get: v.pipe(v.object({
|
|
232
|
+
...targetFields,
|
|
233
|
+
encoding: v.optional(v.literal("base64")),
|
|
234
|
+
found: v.boolean(),
|
|
235
|
+
type: v.optional(v.string()),
|
|
236
|
+
value: v.optional(v.unknown())
|
|
237
|
+
}), v.check((result) => !result.found || result.type !== void 0 && result.value !== void 0, "found KV values require type and value"), v.check((result) => result.encoding !== "base64" || v.is(v.pipe(v.string(), v.regex(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/)), result.value))),
|
|
238
|
+
has: v.object({
|
|
239
|
+
...targetFields,
|
|
240
|
+
exists: v.boolean()
|
|
241
|
+
}),
|
|
242
|
+
set: v.object({
|
|
243
|
+
...targetFields,
|
|
244
|
+
created: v.boolean(),
|
|
245
|
+
notice: v.optional(v.string()),
|
|
246
|
+
ttl: v.optional(positiveNumber),
|
|
247
|
+
type: v.string()
|
|
248
|
+
}),
|
|
249
|
+
delete: v.object({
|
|
250
|
+
...targetFields,
|
|
251
|
+
deleted: v.boolean()
|
|
252
|
+
})
|
|
253
|
+
};
|
|
254
|
+
function parseResult(operation, result) {
|
|
255
|
+
switch (operation) {
|
|
256
|
+
case "list": {
|
|
257
|
+
const parsed = v.safeParse(resultSchemas.list, result);
|
|
258
|
+
return parsed.success ? {
|
|
259
|
+
operation,
|
|
260
|
+
value: parsed.output
|
|
261
|
+
} : void 0;
|
|
262
|
+
}
|
|
263
|
+
case "get": {
|
|
264
|
+
const parsed = v.safeParse(resultSchemas.get, result);
|
|
265
|
+
return parsed.success ? {
|
|
266
|
+
operation,
|
|
267
|
+
value: parsed.output
|
|
268
|
+
} : void 0;
|
|
269
|
+
}
|
|
270
|
+
case "has": {
|
|
271
|
+
const parsed = v.safeParse(resultSchemas.has, result);
|
|
272
|
+
return parsed.success ? {
|
|
273
|
+
operation,
|
|
274
|
+
value: parsed.output
|
|
275
|
+
} : void 0;
|
|
276
|
+
}
|
|
277
|
+
case "set": {
|
|
278
|
+
const parsed = v.safeParse(resultSchemas.set, result);
|
|
279
|
+
return parsed.success ? {
|
|
280
|
+
operation,
|
|
281
|
+
value: parsed.output
|
|
282
|
+
} : void 0;
|
|
283
|
+
}
|
|
284
|
+
case "delete": {
|
|
285
|
+
const parsed = v.safeParse(resultSchemas.delete, result);
|
|
286
|
+
return parsed.success ? {
|
|
287
|
+
operation,
|
|
288
|
+
value: parsed.output
|
|
289
|
+
} : void 0;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
function writeResult(result, context) {
|
|
294
|
+
switch (result.operation) {
|
|
295
|
+
case "list": {
|
|
296
|
+
const page = result.value;
|
|
297
|
+
if (page.keys.some((key) => /[\r\n\u2028\u2029]/.test(key))) return writeCliFailure(false, context, { message: "The KV list contains line-breaking keys. Use --json to preserve the complete keys." });
|
|
298
|
+
if (page.keys.length === 0 && page.cursor) context.stderr.write("No keys on this page.\n");
|
|
299
|
+
else if (page.keys.length === 0) context.stderr.write(`No keys${page.prefix ? ` with prefix ${page.prefix}` : ""} in store ${page.store}.\n`);
|
|
300
|
+
else context.stdout.write(`${page.keys.join("\n")}\n`);
|
|
301
|
+
if (page.driver) context.stderr.write(`Store ${page.store} uses the ${page.driver} driver in this server process.\n`);
|
|
302
|
+
if (page.cursor) context.stderr.write(`More keys exist. Next page: --cursor ${page.cursor}\n`);
|
|
303
|
+
return 0;
|
|
304
|
+
}
|
|
305
|
+
case "get": {
|
|
306
|
+
const value = result.value;
|
|
307
|
+
if (!value.found) {
|
|
308
|
+
context.stderr.write(`Key ${value.key} was not found in store ${value.store}.\n`);
|
|
309
|
+
return 1;
|
|
310
|
+
}
|
|
311
|
+
context.stdout.write(formatValue(value));
|
|
312
|
+
return 0;
|
|
313
|
+
}
|
|
314
|
+
case "has": {
|
|
315
|
+
const value = result.value;
|
|
316
|
+
context.stdout.write(`Key ${value.key} ${value.exists ? "exists" : "does not exist"} in store ${value.store}.\n`);
|
|
317
|
+
return value.exists ? 0 : 1;
|
|
318
|
+
}
|
|
319
|
+
case "set": {
|
|
320
|
+
const value = result.value;
|
|
321
|
+
context.stdout.write([
|
|
322
|
+
`${value.created ? "Created" : "Updated"} key ${value.key} in store ${value.store} (${value.type}${value.ttl ? `, TTL ${value.ttl} s` : ""}).`,
|
|
323
|
+
...value.notice ? [value.notice] : [],
|
|
324
|
+
""
|
|
325
|
+
].join("\n"));
|
|
326
|
+
return 0;
|
|
327
|
+
}
|
|
328
|
+
case "delete": {
|
|
329
|
+
const value = result.value;
|
|
330
|
+
context.stdout.write(value.deleted ? `Deleted key ${value.key} from store ${value.store}.\n` : `Key ${value.key} was not found in store ${value.store}. Deletion completed.\n`);
|
|
331
|
+
return 0;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
function exitCode(operation, result) {
|
|
336
|
+
if (operation === "get") return result.found === true ? 0 : 1;
|
|
337
|
+
if (operation === "has") return result.exists === true ? 0 : 1;
|
|
338
|
+
return 0;
|
|
339
|
+
}
|
|
340
|
+
async function runKVCommand(command, args, context, options) {
|
|
341
|
+
let parsed;
|
|
342
|
+
let value;
|
|
343
|
+
try {
|
|
344
|
+
parsed = parseArgs(command, args);
|
|
345
|
+
if (command.value && !parsed.help) value = await readValue(parsed, context.cwd);
|
|
346
|
+
} catch (error) {
|
|
347
|
+
const terminator = args.indexOf("--");
|
|
348
|
+
if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeCliFailure(true, context, { message: error instanceof Error ? error.message : String(error) });
|
|
349
|
+
context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
350
|
+
writeUsage(command, context.stderr);
|
|
351
|
+
return 1;
|
|
352
|
+
}
|
|
353
|
+
if (parsed.help) {
|
|
354
|
+
writeUsage(command, context.stdout);
|
|
355
|
+
return 0;
|
|
356
|
+
}
|
|
357
|
+
if (command.name === "delete" && !parsed.yes) {
|
|
358
|
+
const question = `Delete key ${parsed.key} from KV store ${parsed.store ?? "default"} at ${parsed.url ?? context.rootDir}? [y/N] `;
|
|
359
|
+
if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return writeCliFailure(parsed.json, context, {
|
|
360
|
+
code: "KV_NOT_CONFIRMED",
|
|
361
|
+
fix: "Run it again with --yes.",
|
|
362
|
+
message: "kv delete deletes a key and was not confirmed."
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
const input = {};
|
|
366
|
+
if (parsed.cursor !== void 0) input.cursor = parsed.cursor;
|
|
367
|
+
if (parsed.key !== void 0) input.key = parsed.key;
|
|
368
|
+
if (parsed.limit !== void 0) input.limit = parsed.limit;
|
|
369
|
+
if (parsed.prefix !== void 0) input.prefix = parsed.prefix;
|
|
370
|
+
if (parsed.store !== void 0) input.store = parsed.store;
|
|
371
|
+
if (parsed.ttl !== void 0) input.ttl = parsed.ttl;
|
|
372
|
+
if (command.value) input.value = value;
|
|
373
|
+
const called = await callOperationFromCli({
|
|
374
|
+
...command.name === "delete" ? { confirmed: true } : {},
|
|
375
|
+
env: context.env,
|
|
376
|
+
fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
|
|
377
|
+
rootDir: context.rootDir,
|
|
378
|
+
...parsed.timeout ? { timeout: parsed.timeout } : {},
|
|
379
|
+
...parsed.url ? { url: parsed.url } : {}
|
|
380
|
+
}, `kv.${command.name}`, input);
|
|
381
|
+
if (!called.ok) return writeCliFailure(parsed.json, context, {
|
|
382
|
+
code: called.code,
|
|
383
|
+
message: called.message,
|
|
384
|
+
...called.fix ? { fix: called.fix } : {}
|
|
385
|
+
});
|
|
386
|
+
const result = called.value;
|
|
387
|
+
if (!isRecord(result)) return writeCliFailure(parsed.json, context, { message: "The kv operation answered with an invalid result." });
|
|
388
|
+
const commandResult = parseResult(command.name, result);
|
|
389
|
+
if (!commandResult) return writeCliFailure(parsed.json, context, { message: "The kv operation answered with an invalid result shape." });
|
|
390
|
+
if (!parsed.json) return writeResult(commandResult, context);
|
|
391
|
+
context.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
392
|
+
return exitCode(command.name, result);
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Runs one `vitehub kv` command against a running Vite + Nitro Development Server.
|
|
396
|
+
* `args[0]` is the command name, for example `list` or `set`.
|
|
397
|
+
*/
|
|
398
|
+
async function runKVCli(args, context, options = {}) {
|
|
399
|
+
const [name, ...rest] = args;
|
|
400
|
+
const command = kvCommands.find((entry) => entry.name === name);
|
|
401
|
+
if (!command) {
|
|
402
|
+
context.stderr.write(`${name ? `Unknown kv command: ${name}\n` : ""}Commands: ${kvCommands.map((entry) => entry.name).join(", ")}\n`);
|
|
403
|
+
return 1;
|
|
404
|
+
}
|
|
405
|
+
return await runKVCommand(command, rest, context, options);
|
|
406
|
+
}
|
|
407
|
+
/** The folder of the KV seed files, relative to the project root. */
|
|
408
|
+
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
|
+
async function runKVSeed(seed, context, options) {
|
|
415
|
+
const dir = resolve(options.projectRoot?.() ?? context.rootDir, kvSeedDir);
|
|
416
|
+
const files = await listSeedFiles(dir);
|
|
417
|
+
if (!files?.length) return void 0;
|
|
418
|
+
if (seed.remote && !seed.url) {
|
|
419
|
+
context.stderr.write("[vitehub] The KV seed with --remote writes the deployed app. Pass --url <url>, or set `vitehub({ publicUrl })`.\n");
|
|
420
|
+
return 1;
|
|
421
|
+
}
|
|
422
|
+
const keys = /* @__PURE__ */ new Map();
|
|
423
|
+
for (const file of files) {
|
|
424
|
+
const key = file.slice(0, file.length - extname(file).length);
|
|
425
|
+
const other = keys.get(key);
|
|
426
|
+
if (other) {
|
|
427
|
+
context.stderr.write(`[vitehub] ${kvSeedDir}/${other} and ${kvSeedDir}/${file} are both the KV key ${key}. Keep one of them.\n`);
|
|
428
|
+
return 1;
|
|
429
|
+
}
|
|
430
|
+
keys.set(key, file);
|
|
431
|
+
}
|
|
432
|
+
for (const [key, file] of keys) {
|
|
433
|
+
const path = relative(context.cwd, join(dir, file)) || join(dir, file);
|
|
434
|
+
const flags = [
|
|
435
|
+
...extname(file) === ".json" ? ["--json-value"] : [],
|
|
436
|
+
...seed.url ? ["--url", seed.url] : [],
|
|
437
|
+
...seed.timeout ? ["--timeout", String(seed.timeout)] : []
|
|
438
|
+
];
|
|
439
|
+
const code = await runKVCommand(setCommand, [
|
|
440
|
+
...flags,
|
|
441
|
+
"--",
|
|
442
|
+
key,
|
|
443
|
+
`@${path}`
|
|
444
|
+
], context, options);
|
|
445
|
+
if (code !== 0) return code;
|
|
446
|
+
}
|
|
447
|
+
return 0;
|
|
448
|
+
}
|
|
449
|
+
function createKVCliContributor(options = {}) {
|
|
450
|
+
return {
|
|
451
|
+
namespaces: [{
|
|
452
|
+
description: "Read and write keys of the KV stores in a running Vite + Nitro Development Server.",
|
|
453
|
+
features: kvCommands.map((command) => ({
|
|
454
|
+
description: command.description,
|
|
455
|
+
name: command.name,
|
|
456
|
+
run: async (args, context) => await runKVCommand(command, args, context, options),
|
|
457
|
+
usage: commandUsage(command)
|
|
458
|
+
})),
|
|
459
|
+
name: "kv"
|
|
460
|
+
}],
|
|
461
|
+
seeds: [{
|
|
462
|
+
files: `${kvSeedDir}/<key>.json`,
|
|
463
|
+
name: "kv",
|
|
464
|
+
run: async (seed, context) => await runKVSeed(seed, context, options)
|
|
465
|
+
}]
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
//#endregion
|
|
469
|
+
export { createKVCliContributor, runKVCli };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { i as setInstalledCloudflareEnv, n as getActiveCloudflareEnv, r as getCloudflareEnv, t as activeEnvStorageKey } from "./cloudflare-env-lookup-Bs0VDpU5.js";
|
|
2
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
|
+
//#region ../internal/src/runtime/cloudflare-env.ts
|
|
4
|
+
const runtimeGlobal = globalThis;
|
|
5
|
+
const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
|
|
6
|
+
const globalEnvProbe = Symbol("vitehub.cloudflare.global-env-probe");
|
|
7
|
+
/**
|
|
8
|
+
* Under the Nitro Cloudflare dev server, `cloudflare:workers` exports unenv's env proxy, which reads every key from
|
|
9
|
+
* `globalThis.__env__`. Storing that proxy in `__env__` makes it read itself, and the next read overflows the stack.
|
|
10
|
+
*/
|
|
11
|
+
function readsGlobalEnv(env) {
|
|
12
|
+
const scope = globalThis;
|
|
13
|
+
const owned = Object.hasOwn(scope, "__env__");
|
|
14
|
+
const previous = scope.__env__;
|
|
15
|
+
scope.__env__ = { [globalEnvProbe]: true };
|
|
16
|
+
try {
|
|
17
|
+
return Reflect.get(env, globalEnvProbe) === true;
|
|
18
|
+
} catch {
|
|
19
|
+
return false;
|
|
20
|
+
} finally {
|
|
21
|
+
if (owned) scope.__env__ = previous;
|
|
22
|
+
else delete scope.__env__;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function setActiveCloudflareEnv(env) {
|
|
26
|
+
setInstalledCloudflareEnv(env);
|
|
27
|
+
if (!env || !readsGlobalEnv(env)) globalThis.__env__ = env;
|
|
28
|
+
try {
|
|
29
|
+
activeEnvStorage.enterWith({ env });
|
|
30
|
+
} catch {}
|
|
31
|
+
}
|
|
32
|
+
function getActiveCloudflareBinding(name) {
|
|
33
|
+
const env = getActiveCloudflareEnv();
|
|
34
|
+
return env && Object.hasOwn(env, name) ? env[name] : void 0;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Installs the Cloudflare env of a request event, so code without the event, such as a KV or Blob store, finds its
|
|
38
|
+
* bindings. Nitro middleware of Cloudflare primitives call this. A Node dev runner gives the event no env, so without a
|
|
39
|
+
* `fallback` the active env stays as it is.
|
|
40
|
+
*/
|
|
41
|
+
function installCloudflareRequestEnv(event, fallback) {
|
|
42
|
+
const env = getCloudflareEnv(event, { fallback: false }) ?? fallback;
|
|
43
|
+
if (env) setActiveCloudflareEnv(env);
|
|
44
|
+
}
|
|
45
|
+
//#endregion
|
|
46
|
+
export { installCloudflareRequestEnv as n, getActiveCloudflareBinding as t };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
//#region ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
2
|
+
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
3
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
4
|
+
let activeEnv;
|
|
5
|
+
function setInstalledCloudflareEnv(env) {
|
|
6
|
+
activeEnv = env;
|
|
7
|
+
}
|
|
8
|
+
/** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
|
|
9
|
+
function getScopedCloudflareEnv() {
|
|
10
|
+
return globalThis[activeEnvStorageKey]?.getStore();
|
|
11
|
+
}
|
|
12
|
+
function getActiveCloudflareEnv() {
|
|
13
|
+
const scoped = getScopedCloudflareEnv();
|
|
14
|
+
if (scoped) return scoped.env;
|
|
15
|
+
const host = globalThis;
|
|
16
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
17
|
+
}
|
|
18
|
+
function ownValue(value, key) {
|
|
19
|
+
if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
|
|
20
|
+
return Reflect.get(value, key);
|
|
21
|
+
}
|
|
22
|
+
function ownObject(value) {
|
|
23
|
+
return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
|
|
24
|
+
}
|
|
25
|
+
/** The objects where H3 and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
|
|
26
|
+
function cloudflareOwners(target) {
|
|
27
|
+
const context = ownObject(ownValue(target, "context"));
|
|
28
|
+
const platform = ownObject(ownValue(context, "_platform"));
|
|
29
|
+
const req = ownObject(ownValue(target, "req"));
|
|
30
|
+
return [
|
|
31
|
+
ownObject(ownValue(context, "cloudflare")),
|
|
32
|
+
ownObject(ownValue(platform, "cloudflare")),
|
|
33
|
+
ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"))
|
|
34
|
+
];
|
|
35
|
+
}
|
|
36
|
+
function getCloudflareEnv(event, options = {}) {
|
|
37
|
+
const target = ownObject(event);
|
|
38
|
+
for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
|
|
39
|
+
return options.fallback === false ? void 0 : getActiveCloudflareEnv();
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { setInstalledCloudflareEnv as i, getActiveCloudflareEnv as n, getCloudflareEnv as r, activeEnvStorageKey as t };
|