@vite-hub/kv 0.0.3 → 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.
Files changed (39) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +40 -7
  3. package/dist/cli-Cniq99iX.d.ts +85 -0
  4. package/dist/cli.d.ts +15 -0
  5. package/dist/cli.js +448 -0
  6. package/dist/cloudflare-env-C5rM7kUY.js +74 -0
  7. package/dist/{config-C1ofyzSt.js → config-DR6_5ZwI.js} +37 -17
  8. package/dist/continuations-DPyH_vr1.js +63 -0
  9. package/dist/create-storage-29gMzf41.js +442 -0
  10. package/dist/cursor-history-dqYDlsaD.js +148 -0
  11. package/dist/deno-kv-CSYGvRx4.js +120 -0
  12. package/dist/driver-D9fI27jl.d.ts +94 -0
  13. package/dist/error-diagnostics-D_cQeZTi.js +82 -0
  14. package/dist/errors-Dc2oiW-Y.js +38 -0
  15. package/dist/errors.d.ts +12 -7
  16. package/dist/errors.js +2 -20
  17. package/dist/fs-lite-CbLKxLut.js +90 -0
  18. package/dist/index.d.ts +5 -4
  19. package/dist/index.js +119 -49
  20. package/dist/object-B1NW521B.js +7 -0
  21. package/dist/operations-ByuDE12r.js +1442 -0
  22. package/dist/operations-pn8_eGob.js +432 -0
  23. package/dist/operations-tNUdj3G4.d.ts +212 -0
  24. package/dist/operations.d.ts +68 -0
  25. package/dist/operations.js +455 -0
  26. package/dist/results-p7nPCnaJ.js +6 -0
  27. package/dist/runtime/cloudflare-kv.d.ts +6 -0
  28. package/dist/runtime/cloudflare-kv.js +100 -0
  29. package/dist/runtime/upstash-driver.d.ts +5 -2
  30. package/dist/runtime/upstash-driver.js +111 -2
  31. package/dist/types-CMDvN0Wr.d.ts +81 -0
  32. package/dist/utils2-Dsb9P4_2.js +28 -0
  33. package/dist/virtual-module.d.ts +6 -0
  34. package/dist/virtual.d.ts +2 -6
  35. package/dist/vite.d.ts +30 -10
  36. package/dist/vite.js +4910 -213
  37. package/package.json +57 -15
  38. package/dist/deno-kv-JnitV_jG.js +0 -54
  39. package/dist/types-Dg4l318i.d.ts +0 -60
package/dist/cli.js ADDED
@@ -0,0 +1,448 @@
1
+ import { b as readViteHubDevTargetOption, n as callOperationFromCli } from "./operations-ByuDE12r.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
3
+ import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
4
+ import { readFile } from "node:fs/promises";
5
+ import { resolve } from "node:path";
6
+ import { createInterface } from "node:readline/promises";
7
+ import * as v from "valibot";
8
+ //#region src/cli.ts
9
+ const kvDevTargetErrors = {
10
+ invalidInlineTimeout: (message) => kvErrorDiagnostics.KV_CLI_USAGE({ problem: message }),
11
+ invalidTimeout: (message) => kvErrorDiagnostics.KV_CLI_USAGE({ problem: message }),
12
+ missingValue: (message) => kvErrorDiagnostics.KV_CLI_USAGE({ problem: message })
13
+ };
14
+ const kvCommands = [
15
+ {
16
+ description: "List keys of a KV store, one page at a time.",
17
+ key: false,
18
+ name: "list",
19
+ options: [
20
+ "prefix",
21
+ "limit",
22
+ "cursor"
23
+ ]
24
+ },
25
+ {
26
+ description: "Print the value of one key.",
27
+ key: true,
28
+ name: "get",
29
+ options: []
30
+ },
31
+ {
32
+ description: "Check if a key exists. The exit code is 0 when it exists and 1 when it does not.",
33
+ key: true,
34
+ name: "has",
35
+ options: []
36
+ },
37
+ {
38
+ description: "Write the value of one key.",
39
+ key: true,
40
+ name: "set",
41
+ options: ["ttl", "json-value"],
42
+ value: true
43
+ },
44
+ {
45
+ description: "Delete one key.",
46
+ key: true,
47
+ name: "del",
48
+ options: []
49
+ }
50
+ ];
51
+ const optionUsage = {
52
+ "cursor": "[--cursor <cursor>]",
53
+ "json-value": "[--json-value]",
54
+ "limit": "[--limit <n>]",
55
+ "prefix": "[--prefix <prefix>]",
56
+ "ttl": "[--ttl <seconds>]"
57
+ };
58
+ const optionHelp = {
59
+ "cursor": " --cursor <cursor> Read the page after this cursor. `list` prints the next cursor.",
60
+ "json-value": " --json-value Parse the value as JSON. Without it, the value is a string.",
61
+ "limit": ` --limit <n> Show at most n keys. Defaults to 100. Maximum ${kvDevMaximumListLimit}.`,
62
+ "prefix": " --prefix <prefix> Show only keys that start with this prefix.",
63
+ "ttl": " --ttl <seconds> Expire the key after this time. Some drivers ignore TTL or raise it to a minimum."
64
+ };
65
+ function commandUsage(command) {
66
+ const key = command.key ? " <key>" : "";
67
+ const value = command.value ? " <value|@file>" : "";
68
+ const options = command.options.map((option) => ` ${optionUsage[option]}`).join("");
69
+ return `vitehub kv ${command.name}${key}${value}${options} [--store <name>] [--json]${command.name === "del" ? " [--yes]" : ""} [--url <url>]`;
70
+ }
71
+ function writeUsage(command, stream) {
72
+ stream.write([
73
+ `Usage: ${commandUsage(command)}`,
74
+ "",
75
+ command.description,
76
+ "The command runs the kv operation of the app: on the dev server of this project, or on a deployed app with --url.",
77
+ ...command.value ? ["A value that starts with @ names a UTF-8 file. The path is relative to the current directory."] : [],
78
+ "",
79
+ "Options:",
80
+ ...command.options.map((option) => optionHelp[option]),
81
+ " --store <name> KV store. Defaults to `default`.",
82
+ " --json Print JSON.",
83
+ ...command.name === "del" ? [" --yes, -y Delete without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
84
+ " --url <url> Deployed app URL. Credentials come from VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_*. Defaults to the dev server of this project.",
85
+ " --timeout <ms> Request timeout.",
86
+ " -h, --help Show this help.",
87
+ ""
88
+ ].join("\n"));
89
+ }
90
+ function parsePositiveInteger(name, value) {
91
+ const number = Number(value);
92
+ if (!value || !Number.isInteger(number) || number < 1) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `--${name} must be a positive integer.` });
93
+ return number;
94
+ }
95
+ function parseTTL(value) {
96
+ const ttl = Number(value);
97
+ if (!value || !Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--ttl must be a positive number." });
98
+ return ttl;
99
+ }
100
+ function readOptionValue(args, index, name) {
101
+ const arg = args[index];
102
+ if (arg === `--${name}`) {
103
+ const value = args[index + 1];
104
+ if (value === void 0 || value.startsWith("--")) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `--${name} needs a value.` });
105
+ return {
106
+ consumed: 1,
107
+ value
108
+ };
109
+ }
110
+ if (arg.startsWith(`--${name}=`)) return {
111
+ consumed: 0,
112
+ value: arg.slice(name.length + 3)
113
+ };
114
+ }
115
+ function parseArgs(command, args) {
116
+ const parsed = {
117
+ help: false,
118
+ json: false,
119
+ jsonValue: false,
120
+ yes: false
121
+ };
122
+ const positionals = [];
123
+ for (let index = 0; index < args.length; index += 1) {
124
+ const arg = args[index];
125
+ if (arg === "-h" || arg === "--help") {
126
+ parsed.help = true;
127
+ continue;
128
+ }
129
+ if (arg === "--json") {
130
+ parsed.json = true;
131
+ continue;
132
+ }
133
+ if (command.name === "del" && (arg === "--yes" || arg === "-y")) {
134
+ parsed.yes = true;
135
+ continue;
136
+ }
137
+ if (arg === "--json-value" && command.options.includes("json-value")) {
138
+ parsed.jsonValue = true;
139
+ continue;
140
+ }
141
+ if (arg === "--") {
142
+ positionals.push(...args.slice(index + 1));
143
+ break;
144
+ }
145
+ const targetOption = readViteHubDevTargetOption(args, index, parsed, kvDevTargetErrors);
146
+ if (targetOption !== void 0) {
147
+ index += targetOption;
148
+ continue;
149
+ }
150
+ const store = readOptionValue(args, index, "store");
151
+ if (store) {
152
+ if (!store.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--store needs a nonempty name." });
153
+ parsed.store = store.value;
154
+ index += store.consumed;
155
+ continue;
156
+ }
157
+ let matched = false;
158
+ for (const option of [
159
+ "cursor",
160
+ "limit",
161
+ "prefix",
162
+ "ttl"
163
+ ]) {
164
+ if (!command.options.includes(option)) continue;
165
+ const read = readOptionValue(args, index, option);
166
+ if (!read) continue;
167
+ if (option === "cursor" && !read.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--cursor needs a nonempty value." });
168
+ if (option === "ttl") parsed.ttl = parseTTL(read.value);
169
+ else if (option === "limit") parsed.limit = parsePositiveInteger(option, read.value);
170
+ else parsed[option] = read.value;
171
+ index += read.consumed;
172
+ matched = true;
173
+ break;
174
+ }
175
+ if (matched) continue;
176
+ if (arg.startsWith("-")) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `Unknown option: ${arg}.` });
177
+ positionals.push(arg);
178
+ }
179
+ const expected = (command.key ? 1 : 0) + (command.value ? 1 : 0);
180
+ if (positionals.length > expected) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `Unexpected argument: ${positionals[expected]}.` });
181
+ if (command.key) parsed.key = positionals[0];
182
+ if (command.value) parsed.value = positionals[1];
183
+ if (!parsed.help && command.key && parsed.key === void 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "Missing key." });
184
+ if (!parsed.help && command.value && parsed.value === void 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "Missing value." });
185
+ if (parsed.limit !== void 0 && parsed.limit > 1e3) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `--limit must be at most ${kvDevMaximumListLimit}.` });
186
+ return parsed;
187
+ }
188
+ function validateJSONNumbers(value) {
189
+ if (v.is(v.number(), value)) {
190
+ if (!Number.isFinite(value) || Object.is(value, -0)) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "JSON numbers must be finite and cannot be negative zero." });
191
+ 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." });
192
+ }
193
+ if (Array.isArray(value)) value.forEach(validateJSONNumbers);
194
+ else if (v.is(v.record(v.string(), v.unknown()), value)) Object.values(value).forEach(validateJSONNumbers);
195
+ }
196
+ function normalizedDecimal(source) {
197
+ const negative = source.startsWith("-");
198
+ const [mantissa = "", exponent = "0"] = source.replace(/^-/, "").split(/[eE]/);
199
+ const [whole = "", fraction = ""] = mantissa.split(".");
200
+ const digits = `${whole}${fraction}`.replace(/^0+/, "");
201
+ const significant = digits.replace(/0+$/, "");
202
+ const scale = BigInt(exponent) - BigInt(fraction.length) + BigInt(digits.length - significant.length);
203
+ return `${negative ? "-" : ""}${significant}e${scale}`;
204
+ }
205
+ async function readValue(parsed, cwd) {
206
+ const raw = parsed.value;
207
+ const text = raw.startsWith("@") ? await readFile(resolve(cwd, raw.slice(1)), "utf8") : raw;
208
+ if (!parsed.jsonValue) return text;
209
+ try {
210
+ const value = JSON.parse(text, (_key, value, context) => {
211
+ 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." });
212
+ if (v.is(v.number(), value)) validateJSONNumbers(value);
213
+ 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.` });
214
+ return value;
215
+ });
216
+ validateJSONNumbers(value);
217
+ return value;
218
+ } catch (error) {
219
+ throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `The value is not valid JSON: ${error instanceof Error ? error.message : String(error)}` });
220
+ }
221
+ }
222
+ function isRecord(value) {
223
+ return !Array.isArray(value) && v.is(v.record(v.string(), v.unknown()), value);
224
+ }
225
+ function formatValue(result) {
226
+ if (result.encoding === "base64" && v.is(v.string(), result.value)) return Uint8Array.from(atob(result.value), (character) => character.charCodeAt(0));
227
+ if (v.is(v.string(), result.value)) return result.value;
228
+ return `${JSON.stringify(result.value, null, 2)}\n`;
229
+ }
230
+ const targetFields = {
231
+ key: v.string(),
232
+ store: v.string()
233
+ };
234
+ const positiveNumber = v.pipe(v.number(), v.finite(), v.gtValue(0));
235
+ const resultSchemas = {
236
+ list: v.object({
237
+ cursor: v.optional(v.string()),
238
+ keys: v.array(v.string()),
239
+ limit: v.pipe(positiveNumber, v.integer()),
240
+ prefix: v.string(),
241
+ store: v.string(),
242
+ stores: v.array(v.string())
243
+ }),
244
+ get: v.pipe(v.object({
245
+ ...targetFields,
246
+ encoding: v.optional(v.literal("base64")),
247
+ found: v.boolean(),
248
+ type: v.optional(v.string()),
249
+ value: v.optional(v.unknown())
250
+ }), 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))),
251
+ has: v.object({
252
+ ...targetFields,
253
+ exists: v.boolean()
254
+ }),
255
+ set: v.object({
256
+ ...targetFields,
257
+ created: v.boolean(),
258
+ notice: v.optional(v.string()),
259
+ ttl: v.optional(positiveNumber),
260
+ type: v.string()
261
+ }),
262
+ del: v.object({
263
+ ...targetFields,
264
+ deleted: v.boolean()
265
+ })
266
+ };
267
+ function parseResult(operation, result) {
268
+ switch (operation) {
269
+ case "list": {
270
+ const parsed = v.safeParse(resultSchemas.list, result);
271
+ return parsed.success ? {
272
+ operation,
273
+ value: parsed.output
274
+ } : void 0;
275
+ }
276
+ case "get": {
277
+ const parsed = v.safeParse(resultSchemas.get, result);
278
+ return parsed.success ? {
279
+ operation,
280
+ value: parsed.output
281
+ } : void 0;
282
+ }
283
+ case "has": {
284
+ const parsed = v.safeParse(resultSchemas.has, result);
285
+ return parsed.success ? {
286
+ operation,
287
+ value: parsed.output
288
+ } : void 0;
289
+ }
290
+ case "set": {
291
+ const parsed = v.safeParse(resultSchemas.set, result);
292
+ return parsed.success ? {
293
+ operation,
294
+ value: parsed.output
295
+ } : void 0;
296
+ }
297
+ case "del": {
298
+ const parsed = v.safeParse(resultSchemas.del, result);
299
+ return parsed.success ? {
300
+ operation,
301
+ value: parsed.output
302
+ } : void 0;
303
+ }
304
+ }
305
+ }
306
+ function writeResult(result, context) {
307
+ switch (result.operation) {
308
+ case "list": {
309
+ const page = result.value;
310
+ if (page.keys.some((key) => /[\r\n\u2028\u2029]/.test(key))) return writeFailure({ json: false }, context, { message: "The KV list contains line-breaking keys. Use --json to preserve the complete keys." });
311
+ if (page.keys.length === 0 && page.cursor) context.stderr.write("No keys on this page.\n");
312
+ else if (page.keys.length === 0) context.stderr.write(`No keys${page.prefix ? ` with prefix ${page.prefix}` : ""} in store ${page.store}.\n`);
313
+ else context.stdout.write(`${page.keys.join("\n")}\n`);
314
+ if (page.cursor) context.stderr.write(`More keys exist. Next page: --cursor ${page.cursor}\n`);
315
+ return 0;
316
+ }
317
+ case "get": {
318
+ const value = result.value;
319
+ if (!value.found) {
320
+ context.stderr.write(`Key ${value.key} was not found in store ${value.store}.\n`);
321
+ return 1;
322
+ }
323
+ context.stdout.write(formatValue(value));
324
+ return 0;
325
+ }
326
+ case "has": {
327
+ const value = result.value;
328
+ context.stdout.write(`Key ${value.key} ${value.exists ? "exists" : "does not exist"} in store ${value.store}.\n`);
329
+ return value.exists ? 0 : 1;
330
+ }
331
+ case "set": {
332
+ const value = result.value;
333
+ context.stdout.write([
334
+ `${value.created ? "Created" : "Updated"} key ${value.key} in store ${value.store} (${value.type}${value.ttl ? `, TTL ${value.ttl} s` : ""}).`,
335
+ ...value.notice ? [value.notice] : [],
336
+ ""
337
+ ].join("\n"));
338
+ return 0;
339
+ }
340
+ case "del": {
341
+ const value = result.value;
342
+ 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`);
343
+ return 0;
344
+ }
345
+ }
346
+ }
347
+ function exitCode(operation, result) {
348
+ if (operation === "get") return result.found === true ? 0 : 1;
349
+ if (operation === "has") return result.exists === true ? 0 : 1;
350
+ return 0;
351
+ }
352
+ function writeFailure(parsed, context, failure) {
353
+ if (parsed.json) context.stdout.write(`${JSON.stringify({ error: failure }, null, 2)}\n`);
354
+ else context.stderr.write(`${failure.message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
355
+ return 1;
356
+ }
357
+ async function askOnTerminal(question) {
358
+ const terminal = createInterface({
359
+ input: process.stdin,
360
+ output: process.stderr
361
+ });
362
+ try {
363
+ return /^y(es)?$/i.test((await terminal.question(question)).trim());
364
+ } finally {
365
+ terminal.close();
366
+ }
367
+ }
368
+ async function runKVCommand(command, args, context, options) {
369
+ let parsed;
370
+ let value;
371
+ try {
372
+ parsed = parseArgs(command, args);
373
+ if (command.value && !parsed.help) value = await readValue(parsed, context.cwd);
374
+ } catch (error) {
375
+ const terminator = args.indexOf("--");
376
+ if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeFailure({ json: true }, context, { message: error instanceof Error ? error.message : String(error) });
377
+ context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
378
+ writeUsage(command, context.stderr);
379
+ return 1;
380
+ }
381
+ if (parsed.help) {
382
+ writeUsage(command, context.stdout);
383
+ return 0;
384
+ }
385
+ if (command.name === "del" && !parsed.yes) {
386
+ const question = `Delete key ${parsed.key} from KV store ${parsed.store ?? "default"} at ${parsed.url ?? context.rootDir}? [y/N] `;
387
+ if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return writeFailure(parsed, context, {
388
+ code: "KV_NOT_CONFIRMED",
389
+ fix: "Run it again with --yes.",
390
+ message: "kv del deletes a key and was not confirmed."
391
+ });
392
+ }
393
+ const input = {};
394
+ if (parsed.cursor !== void 0) input.cursor = parsed.cursor;
395
+ if (parsed.key !== void 0) input.key = parsed.key;
396
+ if (parsed.limit !== void 0) input.limit = parsed.limit;
397
+ if (parsed.prefix !== void 0) input.prefix = parsed.prefix;
398
+ if (parsed.store !== void 0) input.store = parsed.store;
399
+ if (parsed.ttl !== void 0) input.ttl = parsed.ttl;
400
+ if (command.value) input.value = value;
401
+ const called = await callOperationFromCli({
402
+ ...command.name === "del" ? { confirmed: true } : {},
403
+ env: context.env,
404
+ fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
405
+ rootDir: context.rootDir,
406
+ ...parsed.timeout ? { timeout: parsed.timeout } : {},
407
+ ...parsed.url ? { url: parsed.url } : {}
408
+ }, `kv.${command.name}`, input);
409
+ if (!called.ok) return writeFailure(parsed, context, {
410
+ code: called.code,
411
+ message: called.message,
412
+ ...called.fix ? { fix: called.fix } : {}
413
+ });
414
+ const result = called.value;
415
+ if (!isRecord(result)) return writeFailure(parsed, context, { message: "The kv operation answered with an invalid result." });
416
+ const commandResult = parseResult(command.name, result);
417
+ if (!commandResult) return writeFailure(parsed, context, { message: "The kv operation answered with an invalid result shape." });
418
+ if (!parsed.json) return writeResult(commandResult, context);
419
+ context.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
420
+ return exitCode(command.name, result);
421
+ }
422
+ /**
423
+ * Runs one `vitehub kv` command against a running Vite + Nitro Development Server.
424
+ * `args[0]` is the command name, for example `list` or `set`.
425
+ */
426
+ async function runKVCli(args, context, options = {}) {
427
+ const [name, ...rest] = args;
428
+ const command = kvCommands.find((entry) => entry.name === name);
429
+ if (!command) {
430
+ context.stderr.write(`${name ? `Unknown kv command: ${name}\n` : ""}Commands: ${kvCommands.map((entry) => entry.name).join(", ")}\n`);
431
+ return 1;
432
+ }
433
+ return await runKVCommand(command, rest, context, options);
434
+ }
435
+ function createKVCliContributor(options = {}) {
436
+ return { namespaces: [{
437
+ description: "Read and write keys of the KV stores in a running Vite + Nitro Development Server.",
438
+ features: kvCommands.map((command) => ({
439
+ description: command.description,
440
+ name: command.name,
441
+ run: async (args, context) => await runKVCommand(command, args, context, options),
442
+ usage: commandUsage(command)
443
+ })),
444
+ name: "kv"
445
+ }] };
446
+ }
447
+ //#endregion
448
+ export { createKVCliContributor, runKVCli };
@@ -0,0 +1,74 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ //#region ../internal/src/runtime/cloudflare-env.ts
3
+ let activeEnv;
4
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
5
+ const runtimeGlobal = globalThis;
6
+ const activeEnvStorage = runtimeGlobal[activeEnvStorageKey] ||= new AsyncLocalStorage();
7
+ function getActiveCloudflareEnv() {
8
+ const scoped = activeEnvStorage.getStore();
9
+ if (scoped) return scoped.env;
10
+ const host = globalThis;
11
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
12
+ }
13
+ function getActiveCloudflareBinding(name) {
14
+ const env = getActiveCloudflareEnv();
15
+ return env && Object.hasOwn(env, name) ? env[name] : void 0;
16
+ }
17
+ function ownValue(value, key) {
18
+ if (value === null || typeof value !== "object" && typeof value !== "function" || !Object.hasOwn(value, key)) return void 0;
19
+ return Reflect.get(value, key);
20
+ }
21
+ function ownObject(value) {
22
+ return value !== null && (typeof value === "object" || typeof value === "function") ? value : void 0;
23
+ }
24
+ /** The objects where H3 1, H3 2, and Nitro hosts put Cloudflare `env` and `context`, in lookup order. */
25
+ function cloudflareOwners(target) {
26
+ const context = ownObject(ownValue(target, "context"));
27
+ const platform = ownObject(ownValue(context, "_platform"));
28
+ const req = ownObject(ownValue(target, "req"));
29
+ const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
30
+ return [
31
+ ownObject(ownValue(context, "cloudflare")),
32
+ ownObject(ownValue(platform, "cloudflare")),
33
+ ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare")),
34
+ ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"))
35
+ ];
36
+ }
37
+ function getCloudflareEnv(event, options = {}) {
38
+ const target = ownObject(event);
39
+ for (const candidate of [ownValue(target, "env"), ...cloudflareOwners(target).map((owner) => ownValue(owner, "env"))]) if (candidate) return candidate;
40
+ return options.fallback === false ? void 0 : getActiveCloudflareEnv();
41
+ }
42
+ function resolveWaitUntil(event, options = {}) {
43
+ const target = ownObject(event);
44
+ const context = ownObject(ownValue(target, "context"));
45
+ const cloudflare = ownObject(ownValue(context, "cloudflare"));
46
+ const cloudflareContext = ownObject(ownValue(cloudflare, "context"));
47
+ const platformCloudflare = ownObject(ownValue(ownObject(ownValue(context, "_platform")), "cloudflare"));
48
+ const platformCloudflareContext = ownObject(ownValue(platformCloudflare, "context"));
49
+ const req = ownObject(ownValue(target, "req"));
50
+ const reqCloudflare = ownObject(ownValue(ownObject(ownValue(req, "runtime")), "cloudflare"));
51
+ const reqCloudflareContext = ownObject(ownValue(reqCloudflare, "context"));
52
+ const nodeReq = ownObject(ownValue(ownObject(ownValue(target, "node")), "req"));
53
+ const nodeCloudflare = ownObject(ownValue(ownObject(ownValue(nodeReq, "runtime")), "cloudflare"));
54
+ const hosts = [
55
+ context,
56
+ cloudflare,
57
+ cloudflareContext,
58
+ platformCloudflare,
59
+ platformCloudflareContext,
60
+ req,
61
+ reqCloudflare,
62
+ reqCloudflareContext,
63
+ nodeReq,
64
+ nodeCloudflare,
65
+ ownObject(ownValue(nodeCloudflare, "context"))
66
+ ];
67
+ const owners = options.preferHost ? [...hosts, target] : [target, ...hosts];
68
+ for (const owner of owners) {
69
+ const waitUntil = ownValue(owner, "waitUntil");
70
+ if (typeof waitUntil === "function") return waitUntil.bind(owner);
71
+ }
72
+ }
73
+ //#endregion
74
+ export { resolveWaitUntil as i, getActiveCloudflareEnv as n, getCloudflareEnv as r, getActiveCloudflareBinding as t };
@@ -1,3 +1,5 @@
1
+ import { t as isPlainObject } from "./object-B1NW521B.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
1
3
  import { defu } from "defu";
2
4
  //#region ../internal/src/env.ts
3
5
  function trimmed(value) {
@@ -11,22 +13,36 @@ function readEnv(env, ...names) {
11
13
  }
12
14
  //#endregion
13
15
  //#region ../internal/src/hosting.ts
16
+ /**
17
+ * Returns the Nitro preset name that this build targets, as the developer wrote it.
18
+ * The order is `nitro.preset`, `hosting`, `NITRO_PRESET`, `SERVER_PRESET`, then `VITEHUB_HOSTING`.
19
+ * Empty values are skipped.
20
+ */
21
+ function resolveHostPreset(input = {}) {
22
+ const env = input.env ?? (typeof process === "undefined" ? {} : process.env);
23
+ const nitroPreset = input.nitro && typeof input.nitro === "object" ? Reflect.get(input.nitro, "preset") : void 0;
24
+ for (const value of [
25
+ nitroPreset,
26
+ input.hosting,
27
+ env.NITRO_PRESET,
28
+ env.SERVER_PRESET,
29
+ env.VITEHUB_HOSTING
30
+ ]) if (typeof value === "string" && value.trim()) return value.trim();
31
+ }
14
32
  function normalizeHosting(hosting) {
15
33
  const normalized = hosting?.trim().toLowerCase().replaceAll("_", "-") || "";
16
34
  if (normalized === "cloudflare") return "cloudflare-module";
17
35
  return normalized;
18
36
  }
19
37
  //#endregion
20
- //#region ../internal/src/object.ts
21
- function isPlainObject(value) {
22
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
23
- }
24
- //#endregion
25
38
  //#region src/integrations/upstash.ts
26
39
  const maskedUpstashRuntimeValue = "********";
40
+ /** Vercel names first, then the names that the Upstash console and NuxtHub use. */
41
+ const upstashUrlEnvNames = ["KV_REST_API_URL", "UPSTASH_REDIS_REST_URL"];
42
+ const upstashTokenEnvNames = ["KV_REST_API_TOKEN", "UPSTASH_REDIS_REST_TOKEN"];
27
43
  function hasUpstashEnv(env) {
28
- const url = readEnv(env, "KV_REST_API_URL");
29
- const token = readEnv(env, "KV_REST_API_TOKEN");
44
+ const url = readEnv(env, ...upstashUrlEnvNames);
45
+ const token = readEnv(env, ...upstashTokenEnvNames);
30
46
  return Boolean(url && token);
31
47
  }
32
48
  function resolveUpstashStore(config = {}) {
@@ -41,13 +57,14 @@ function resolveUpstashStore(config = {}) {
41
57
  function resolveFsLiteStore(config = {}) {
42
58
  return defu({ base: trimmed(config.base) }, {
43
59
  driver: "fs-lite",
44
- base: ".data/kv"
60
+ base: ".vitehub/data/kv"
45
61
  });
46
62
  }
47
63
  function resolveCloudflareStore(config = {}, env = process.env) {
48
64
  return defu({
49
65
  binding: trimmed(config.binding),
50
- namespaceId: trimmed(config.namespaceId) ?? readEnv(env, "KV_NAMESPACE_ID")
66
+ namespaceId: trimmed(config.namespaceId) ?? readEnv(env, "KV_NAMESPACE_ID"),
67
+ namespaceName: trimmed(config.namespaceName)
51
68
  }, {
52
69
  driver: "cloudflare-kv-binding",
53
70
  binding: "KV"
@@ -66,7 +83,7 @@ function resolveExplicitStore(store, env) {
66
83
  case "deno-kv": return resolveDenoStore(store);
67
84
  case "upstash": return resolveUpstashStore(store);
68
85
  case "fs-lite": return resolveFsLiteStore(store);
69
- default: throw new TypeError(`Unknown \`kv.driver\`: ${JSON.stringify(store.driver)}. Expected "cloudflare-kv-binding", "deno-kv", "upstash", or "fs-lite".`);
86
+ default: throw kvErrorDiagnostics.KV_INVALID_DRIVER({ driver: JSON.stringify(store.driver) });
70
87
  }
71
88
  }
72
89
  function createResolvedConfig(store, stores) {
@@ -78,19 +95,22 @@ function createResolvedConfig(store, stores) {
78
95
  }
79
96
  } : { store };
80
97
  }
81
- function hasStoresConfig(options) {
82
- return !!options && "stores" in options && isPlainObject(options.stores);
98
+ function hasStoresConfig(options, stores) {
99
+ return !!options && Object.hasOwn(options, "stores") && isPlainObject(stores);
83
100
  }
84
101
  function normalizeKVOptions(options, input = {}) {
85
102
  if (options === false) return;
86
- if (typeof options !== "undefined" && !isPlainObject(options)) throw new TypeError("`kv` must be a plain object.");
103
+ if (typeof options !== "undefined" && !isPlainObject(options)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv" });
87
104
  const env = input.env || process.env;
88
105
  const hosting = normalizeHosting(input.hosting);
89
106
  const explicit = options;
90
- if (hasStoresConfig(options)) {
91
- const resolvedStores = Object.fromEntries(Object.entries(options.stores).map(([name, store]) => [name, resolveExplicitStore(store, env)]));
107
+ const hasOwnStores = options !== void 0 && Object.hasOwn(options, "stores");
108
+ const stores = hasOwnStores ? Reflect.get(options, "stores", options) : void 0;
109
+ if (hasOwnStores && !isPlainObject(stores)) throw kvErrorDiagnostics.KV_INVALID_CONFIG({ path: "kv.stores" });
110
+ if (hasStoresConfig(options, stores)) {
111
+ const resolvedStores = Object.fromEntries(Object.entries(stores).map(([name, store]) => [name, resolveExplicitStore(store, env)]));
92
112
  const defaultStore = resolvedStores.default;
93
- if (!defaultStore) throw new TypeError("`kv.stores.default` is required when using named KV stores.");
113
+ if (!defaultStore) throw kvErrorDiagnostics.KV_MISSING_DEFAULT_STORE();
94
114
  return createResolvedConfig(defaultStore, resolvedStores);
95
115
  }
96
116
  if (explicit?.driver) return createResolvedConfig(resolveExplicitStore(explicit, env));
@@ -101,4 +121,4 @@ function normalizeKVOptions(options, input = {}) {
101
121
  return createResolvedConfig(resolveFsLiteStore());
102
122
  }
103
123
  //#endregion
104
- export { readEnv as n, trimmed as r, normalizeKVOptions as t };
124
+ export { readEnv as a, resolveHostPreset as i, upstashTokenEnvNames as n, upstashUrlEnvNames as r, normalizeKVOptions as t };