@vite-hub/kv 0.1.0 → 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.
Files changed (67) hide show
  1. package/README.md +86 -15
  2. package/dist/batch--v0ri69O.js +40 -0
  3. package/dist/cli-DpPhz_Ek.d.ts +163 -0
  4. package/dist/cli.d.ts +4 -2
  5. package/dist/cli.js +98 -77
  6. package/dist/cloudflare-env-lOtHHsgP.js +46 -0
  7. package/dist/cloudflare-env-lookup-Bs0VDpU5.js +42 -0
  8. package/dist/cloudflare-kv-BIEUFzRT.js +187 -0
  9. package/dist/cloudflare-kv-local-BBw3ZT1K.js +71 -0
  10. package/dist/config-BXEVoZE3.js +250 -0
  11. package/dist/{create-storage-29gMzf41.js → create-storage-BGsrQKw3.js} +206 -50
  12. package/dist/{cursor-history-dqYDlsaD.js → cursor-history-BqIQePNP.js} +31 -14
  13. package/dist/database-72Jk3VVk.js +250 -0
  14. package/dist/{deno-kv-CSYGvRx4.js → deno-kv-BM9mYdUp.js} +12 -4
  15. package/dist/dev-peer-CHafxbtj.js +238 -0
  16. package/dist/driver-BwxgaQ-f.d.ts +15 -0
  17. package/dist/durability.d.ts +17 -0
  18. package/dist/durability.js +53 -0
  19. package/dist/error-diagnostics-BxqvtEIb.js +147 -0
  20. package/dist/errors-DbwufFZp.js +60 -0
  21. package/dist/errors.d.ts +12 -1
  22. package/dist/errors.js +2 -2
  23. package/dist/fs-lite-BLZId9_P.js +386 -0
  24. package/dist/fs-lite-RAoxu8L0.js +2 -0
  25. package/dist/index.d.ts +7 -2
  26. package/dist/index.js +302 -75
  27. package/dist/inspect-BIKQsqX4.js +118 -0
  28. package/dist/invariant-DolT9EEx.js +22 -0
  29. package/dist/main-F3Y22_uV.js +2353 -0
  30. package/dist/object-Da1zyPCR.js +11 -0
  31. package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
  32. package/dist/operations-B-WZ7P1h.js +1351 -0
  33. package/dist/{operations-pn8_eGob.js → operations-Ch-gKaey.js} +67 -58
  34. package/dist/operations.d.ts +15 -8
  35. package/dist/operations.js +55 -192
  36. package/dist/redis-shared-E5mahECF.js +94 -0
  37. package/dist/rolldown-runtime-CMFfr-1z.js +26 -0
  38. package/dist/runtime/cloudflare-kv.d.ts +1 -1
  39. package/dist/runtime/cloudflare-kv.js +1 -99
  40. package/dist/runtime/cloudflare-request-env.d.ts +7 -0
  41. package/dist/runtime/cloudflare-request-env.js +11 -0
  42. package/dist/runtime/nitro-plugin.d.ts +12 -0
  43. package/dist/runtime/nitro-plugin.js +22 -0
  44. package/dist/runtime/redis-driver.d.ts +11 -0
  45. package/dist/runtime/redis-driver.js +113 -0
  46. package/dist/runtime/unstorage-driver.d.ts +14 -0
  47. package/dist/runtime/unstorage-driver.js +33 -0
  48. package/dist/runtime/upstash-driver.d.ts +2 -2
  49. package/dist/runtime/upstash-driver.js +58 -98
  50. package/dist/{driver-D9fI27jl.d.ts → types-Bj3EQoRg.d.ts} +16 -41
  51. package/dist/types-DEiKew_3.d.ts +312 -0
  52. package/dist/upstash-DDlqTttY.js +40 -0
  53. package/dist/{utils2-Dsb9P4_2.js → utils2-FozcTsmb.js} +5 -2
  54. package/dist/virtual-module.d.ts +2 -0
  55. package/dist/vite.d.ts +152 -11
  56. package/dist/vite.js +888 -2836
  57. package/package.json +30 -21
  58. package/dist/cli-Cniq99iX.d.ts +0 -85
  59. package/dist/cloudflare-env-C5rM7kUY.js +0 -74
  60. package/dist/config-DR6_5ZwI.js +0 -124
  61. package/dist/continuations-DPyH_vr1.js +0 -63
  62. package/dist/error-diagnostics-D_cQeZTi.js +0 -82
  63. package/dist/errors-Dc2oiW-Y.js +0 -38
  64. package/dist/fs-lite-CbLKxLut.js +0 -90
  65. package/dist/object-B1NW521B.js +0 -7
  66. package/dist/operations-ByuDE12r.js +0 -1442
  67. package/dist/types-CMDvN0Wr.d.ts +0 -81
package/dist/cli.js CHANGED
@@ -1,15 +1,16 @@
1
- import { b as readViteHubDevTargetOption, n as callOperationFromCli } from "./operations-ByuDE12r.js";
2
- import { n as kvErrorDiagnostics } from "./error-diagnostics-D_cQeZTi.js";
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";
3
4
  import { t as kvDevMaximumListLimit } from "./results-p7nPCnaJ.js";
4
5
  import { readFile } from "node:fs/promises";
5
- import { resolve } from "node:path";
6
- import { createInterface } from "node:readline/promises";
6
+ import { extname, join, relative, resolve } from "node:path";
7
7
  import * as v from "valibot";
8
8
  //#region src/cli.ts
9
+ const usageError = (problem) => kvErrorDiagnostics.KV_CLI_USAGE({ problem });
9
10
  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 })
11
+ invalidInlineTimeout: usageError,
12
+ invalidTimeout: usageError,
13
+ missingValue: usageError
13
14
  };
14
15
  const kvCommands = [
15
16
  {
@@ -44,10 +45,11 @@ const kvCommands = [
44
45
  {
45
46
  description: "Delete one key.",
46
47
  key: true,
47
- name: "del",
48
+ name: "delete",
48
49
  options: []
49
50
  }
50
51
  ];
52
+ const setCommand = kvCommands.find((command) => command.name === "set");
51
53
  const optionUsage = {
52
54
  "cursor": "[--cursor <cursor>]",
53
55
  "json-value": "[--json-value]",
@@ -66,7 +68,7 @@ function commandUsage(command) {
66
68
  const key = command.key ? " <key>" : "";
67
69
  const value = command.value ? " <value|@file>" : "";
68
70
  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>]`;
71
+ return `vitehub kv ${command.name}${key}${value}${options} [--store <name>] [--json]${command.name === "delete" ? " [--yes]" : ""} [--url <url>]`;
70
72
  }
71
73
  function writeUsage(command, stream) {
72
74
  stream.write([
@@ -80,38 +82,18 @@ function writeUsage(command, stream) {
80
82
  ...command.options.map((option) => optionHelp[option]),
81
83
  " --store <name> KV store. Defaults to `default`.",
82
84
  " --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
+ ...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.",
85
87
  " --timeout <ms> Request timeout.",
86
88
  " -h, --help Show this help.",
87
89
  ""
88
90
  ].join("\n"));
89
91
  }
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
92
  function parseTTL(value) {
96
93
  const ttl = Number(value);
97
94
  if (!value || !Number.isFinite(ttl) || ttl <= 0) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--ttl must be a positive number." });
98
95
  return ttl;
99
96
  }
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
97
  function parseArgs(command, args) {
116
98
  const parsed = {
117
99
  help: false,
@@ -130,7 +112,7 @@ function parseArgs(command, args) {
130
112
  parsed.json = true;
131
113
  continue;
132
114
  }
133
- if (command.name === "del" && (arg === "--yes" || arg === "-y")) {
115
+ if (command.name === "delete" && (arg === "--yes" || arg === "-y")) {
134
116
  parsed.yes = true;
135
117
  continue;
136
118
  }
@@ -147,7 +129,7 @@ function parseArgs(command, args) {
147
129
  index += targetOption;
148
130
  continue;
149
131
  }
150
- const store = readOptionValue(args, index, "store");
132
+ const store = readCliOptionValue(args, index, "store", usageError);
151
133
  if (store) {
152
134
  if (!store.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--store needs a nonempty name." });
153
135
  parsed.store = store.value;
@@ -162,11 +144,11 @@ function parseArgs(command, args) {
162
144
  "ttl"
163
145
  ]) {
164
146
  if (!command.options.includes(option)) continue;
165
- const read = readOptionValue(args, index, option);
147
+ const read = readCliOptionValue(args, index, option, usageError);
166
148
  if (!read) continue;
167
149
  if (option === "cursor" && !read.value.trim()) throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: "--cursor needs a nonempty value." });
168
150
  if (option === "ttl") parsed.ttl = parseTTL(read.value);
169
- else if (option === "limit") parsed.limit = parsePositiveInteger(option, read.value);
151
+ else if (option === "limit") parsed.limit = parseCliPositiveInteger(option, read.value, usageError);
170
152
  else parsed[option] = read.value;
171
153
  index += read.consumed;
172
154
  matched = true;
@@ -219,9 +201,6 @@ async function readValue(parsed, cwd) {
219
201
  throw kvErrorDiagnostics.KV_CLI_USAGE({ problem: `The value is not valid JSON: ${error instanceof Error ? error.message : String(error)}` });
220
202
  }
221
203
  }
222
- function isRecord(value) {
223
- return !Array.isArray(value) && v.is(v.record(v.string(), v.unknown()), value);
224
- }
225
204
  function formatValue(result) {
226
205
  if (result.encoding === "base64" && v.is(v.string(), result.value)) return Uint8Array.from(atob(result.value), (character) => character.charCodeAt(0));
227
206
  if (v.is(v.string(), result.value)) return result.value;
@@ -235,6 +214,14 @@ const positiveNumber = v.pipe(v.number(), v.finite(), v.gtValue(0));
235
214
  const resultSchemas = {
236
215
  list: v.object({
237
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
+ ])),
238
225
  keys: v.array(v.string()),
239
226
  limit: v.pipe(positiveNumber, v.integer()),
240
227
  prefix: v.string(),
@@ -259,7 +246,7 @@ const resultSchemas = {
259
246
  ttl: v.optional(positiveNumber),
260
247
  type: v.string()
261
248
  }),
262
- del: v.object({
249
+ delete: v.object({
263
250
  ...targetFields,
264
251
  deleted: v.boolean()
265
252
  })
@@ -294,8 +281,8 @@ function parseResult(operation, result) {
294
281
  value: parsed.output
295
282
  } : void 0;
296
283
  }
297
- case "del": {
298
- const parsed = v.safeParse(resultSchemas.del, result);
284
+ case "delete": {
285
+ const parsed = v.safeParse(resultSchemas.delete, result);
299
286
  return parsed.success ? {
300
287
  operation,
301
288
  value: parsed.output
@@ -307,10 +294,11 @@ function writeResult(result, context) {
307
294
  switch (result.operation) {
308
295
  case "list": {
309
296
  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." });
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." });
311
298
  if (page.keys.length === 0 && page.cursor) context.stderr.write("No keys on this page.\n");
312
299
  else if (page.keys.length === 0) context.stderr.write(`No keys${page.prefix ? ` with prefix ${page.prefix}` : ""} in store ${page.store}.\n`);
313
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`);
314
302
  if (page.cursor) context.stderr.write(`More keys exist. Next page: --cursor ${page.cursor}\n`);
315
303
  return 0;
316
304
  }
@@ -337,7 +325,7 @@ function writeResult(result, context) {
337
325
  ].join("\n"));
338
326
  return 0;
339
327
  }
340
- case "del": {
328
+ case "delete": {
341
329
  const value = result.value;
342
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`);
343
331
  return 0;
@@ -349,22 +337,6 @@ function exitCode(operation, result) {
349
337
  if (operation === "has") return result.exists === true ? 0 : 1;
350
338
  return 0;
351
339
  }
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
340
  async function runKVCommand(command, args, context, options) {
369
341
  let parsed;
370
342
  let value;
@@ -373,7 +345,7 @@ async function runKVCommand(command, args, context, options) {
373
345
  if (command.value && !parsed.help) value = await readValue(parsed, context.cwd);
374
346
  } catch (error) {
375
347
  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) });
348
+ if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeCliFailure(true, context, { message: error instanceof Error ? error.message : String(error) });
377
349
  context.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
378
350
  writeUsage(command, context.stderr);
379
351
  return 1;
@@ -382,12 +354,12 @@ async function runKVCommand(command, args, context, options) {
382
354
  writeUsage(command, context.stdout);
383
355
  return 0;
384
356
  }
385
- if (command.name === "del" && !parsed.yes) {
357
+ if (command.name === "delete" && !parsed.yes) {
386
358
  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, {
359
+ if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return writeCliFailure(parsed.json, context, {
388
360
  code: "KV_NOT_CONFIRMED",
389
361
  fix: "Run it again with --yes.",
390
- message: "kv del deletes a key and was not confirmed."
362
+ message: "kv delete deletes a key and was not confirmed."
391
363
  });
392
364
  }
393
365
  const input = {};
@@ -399,22 +371,22 @@ async function runKVCommand(command, args, context, options) {
399
371
  if (parsed.ttl !== void 0) input.ttl = parsed.ttl;
400
372
  if (command.value) input.value = value;
401
373
  const called = await callOperationFromCli({
402
- ...command.name === "del" ? { confirmed: true } : {},
374
+ ...command.name === "delete" ? { confirmed: true } : {},
403
375
  env: context.env,
404
376
  fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
405
377
  rootDir: context.rootDir,
406
378
  ...parsed.timeout ? { timeout: parsed.timeout } : {},
407
379
  ...parsed.url ? { url: parsed.url } : {}
408
380
  }, `kv.${command.name}`, input);
409
- if (!called.ok) return writeFailure(parsed, context, {
381
+ if (!called.ok) return writeCliFailure(parsed.json, context, {
410
382
  code: called.code,
411
383
  message: called.message,
412
384
  ...called.fix ? { fix: called.fix } : {}
413
385
  });
414
386
  const result = called.value;
415
- if (!isRecord(result)) return writeFailure(parsed, context, { message: "The kv operation answered with an invalid result." });
387
+ if (!isRecord(result)) return writeCliFailure(parsed.json, context, { message: "The kv operation answered with an invalid result." });
416
388
  const commandResult = parseResult(command.name, result);
417
- if (!commandResult) return writeFailure(parsed, context, { message: "The kv operation answered with an invalid result shape." });
389
+ if (!commandResult) return writeCliFailure(parsed.json, context, { message: "The kv operation answered with an invalid result shape." });
418
390
  if (!parsed.json) return writeResult(commandResult, context);
419
391
  context.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
420
392
  return exitCode(command.name, result);
@@ -432,17 +404,66 @@ async function runKVCli(args, context, options = {}) {
432
404
  }
433
405
  return await runKVCommand(command, rest, context, options);
434
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
+ }
435
449
  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
- }] };
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
+ };
446
467
  }
447
468
  //#endregion
448
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 };
@@ -0,0 +1,187 @@
1
+ import { t as invariant } from "./invariant-DolT9EEx.js";
2
+ import { n as kvErrorDiagnostics } from "./error-diagnostics-BxqvtEIb.js";
3
+ import { t as getActiveCloudflareBinding } from "./cloudflare-env-lOtHHsgP.js";
4
+ import { n as normalizeKVListPrefix, t as createKVStorage } from "./create-storage-BGsrQKw3.js";
5
+ import { i as setItemsOneByOne, t as chunks } from "./batch--v0ri69O.js";
6
+ import { n as recordCursor, t as createCursorHistory } from "./cursor-history-BqIQePNP.js";
7
+ import createDriver from "unstorage/drivers/cloudflare-kv-binding";
8
+ //#region src/runtime/cloudflare-kv-limits.ts
9
+ const cloudflareKVLimits = {
10
+ keyBytes: 512,
11
+ minExpirationTtl: 60,
12
+ valueBytes: 26214400
13
+ };
14
+ const encoder = /*#__PURE__*/ new TextEncoder();
15
+ /** Returns the UTF-8 size of `value` when it is above `limit`. */
16
+ function bytesAbove(value, limit) {
17
+ if (value.length * 3 <= limit) return;
18
+ const bytes = encoder.encode(value).byteLength;
19
+ return bytes > limit ? bytes : void 0;
20
+ }
21
+ function assertCloudflareKVKey(key) {
22
+ const bytes = bytesAbove(key, cloudflareKVLimits.keyBytes);
23
+ if (bytes !== void 0) throw kvErrorDiagnostics.KV_KEY_TOO_LONG({
24
+ bytes,
25
+ limit: cloudflareKVLimits.keyBytes
26
+ });
27
+ }
28
+ /** Checks a `put()` before the binding gets it. `value` is the string that unstorage serialized. */
29
+ function assertCloudflareKVWrite(key, value) {
30
+ assertCloudflareKVKey(key);
31
+ const valueBytes = typeof value === "string" ? bytesAbove(value, cloudflareKVLimits.valueBytes) : void 0;
32
+ if (valueBytes !== void 0) throw kvErrorDiagnostics.KV_VALUE_TOO_LARGE({
33
+ bytes: valueBytes,
34
+ limit: cloudflareKVLimits.valueBytes
35
+ });
36
+ }
37
+ /** Cloudflare KV rejects an expiration below 60 seconds, so a shorter `ttl` becomes 60 seconds, also on the local store of `vite dev`. */
38
+ function cloudflareKVSetOptions(options) {
39
+ const ttl = options?.ttl;
40
+ return typeof ttl === "number" ? { ttl: Math.max(cloudflareKVLimits.minExpirationTtl, ttl) } : options;
41
+ }
42
+ /** Rejects what a Cloudflare KV binding rejects before the driver call, so every store returns the same named code. */
43
+ function installCloudflareKVLimits(driver) {
44
+ const { getItem, hasItem, removeItem, setItem } = driver;
45
+ driver.getItem = (key, options) => {
46
+ assertCloudflareKVKey(key);
47
+ return getItem.call(driver, key, options);
48
+ };
49
+ driver.hasItem = (key, options) => {
50
+ assertCloudflareKVKey(key);
51
+ return hasItem.call(driver, key, options);
52
+ };
53
+ if (removeItem) driver.removeItem = (key, options) => {
54
+ assertCloudflareKVKey(key);
55
+ return removeItem.call(driver, key, options);
56
+ };
57
+ if (setItem) driver.setItem = (key, value, options) => {
58
+ assertCloudflareKVWrite(key, value);
59
+ return setItem.call(driver, key, value, cloudflareKVSetOptions(options));
60
+ };
61
+ }
62
+ /** Preflight serialized writes and deletion keys before either branch starts. */
63
+ function validateCloudflareKVBatch(items, removals) {
64
+ for (const key of removals) assertCloudflareKVKey(key);
65
+ for (const item of items) assertCloudflareKVWrite(item.key, item.value);
66
+ }
67
+ //#endregion
68
+ //#region src/runtime/cloudflare-kv.ts
69
+ function isCloudflareKVString(value) {
70
+ return typeof value === "string";
71
+ }
72
+ function isCloudflareKVListPage(value) {
73
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
74
+ const page = value;
75
+ if (typeof page.list_complete !== "boolean" || !Array.isArray(page.keys)) return false;
76
+ if (!page.keys.every((key) => {
77
+ if (!key || typeof key !== "object" || Array.isArray(key)) return false;
78
+ return isCloudflareKVString(Reflect.get(key, "name"));
79
+ })) return false;
80
+ return page.list_complete || isCloudflareKVString(page.cursor) && page.cursor.length > 0;
81
+ }
82
+ /** Cloudflare reads at most 100 keys in one bulk `get()`. */
83
+ const cloudflareKVBulkGetKeys = 100;
84
+ const cloudflareBindingIdentities = /* @__PURE__ */ new WeakMap();
85
+ let nextCloudflareBindingIdentity = 0;
86
+ function cloudflareBindingNamespace(bindingName, namespaceId, binding) {
87
+ if (typeof namespaceId === "string" && namespaceId.length > 0) return `cloudflare-kv:id:${namespaceId}`;
88
+ if (binding && typeof binding === "object") {
89
+ let identity = cloudflareBindingIdentities.get(binding);
90
+ if (identity === void 0) {
91
+ identity = ++nextCloudflareBindingIdentity;
92
+ cloudflareBindingIdentities.set(binding, identity);
93
+ }
94
+ return `cloudflare-kv:object:${identity}`;
95
+ }
96
+ return typeof bindingName === "string" ? `cloudflare-kv:binding:${bindingName}` : "cloudflare-kv:default";
97
+ }
98
+ function createCloudflareDriver(options) {
99
+ const bindingName = options.binding;
100
+ const namespaceId = options.namespaceId;
101
+ const driverOptions = typeof bindingName === "string" ? {
102
+ ...options,
103
+ get binding() {
104
+ return getActiveCloudflareBinding(bindingName) ?? bindingName;
105
+ }
106
+ } : options;
107
+ const driver = createDriver(driverOptions);
108
+ installCloudflareKVLimits(driver);
109
+ driver.validateBatch = validateCloudflareKVBatch;
110
+ driver.getItems = async (items) => {
111
+ for (const item of items) assertCloudflareKVKey(item.key);
112
+ const values = /* @__PURE__ */ new Map();
113
+ for (const batch of chunks([...new Set(items.map((item) => item.key))], cloudflareKVBulkGetKeys)) {
114
+ const page = await (await driver.getInstance()).get(batch, "text");
115
+ if (!(page instanceof Map)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV bulk get did not return a Map." });
116
+ for (const key of batch) {
117
+ const value = page.get(key);
118
+ values.set(key, typeof value === "string" ? value : null);
119
+ }
120
+ }
121
+ return items.map((item) => ({
122
+ key: item.key,
123
+ value: values.get(item.key) ?? null
124
+ }));
125
+ };
126
+ const setItemsOneByOneWithLimits = setItemsOneByOne(driver);
127
+ driver.setItems = async (items, commonOptions) => {
128
+ for (const item of items) assertCloudflareKVWrite(item.key, item.value);
129
+ await setItemsOneByOneWithLimits(items, commonOptions);
130
+ };
131
+ const cursorNamespace = cloudflareBindingNamespace(bindingName, namespaceId);
132
+ const cursorHistories = createCursorHistory(cursorNamespace);
133
+ let disposed = false;
134
+ const dispose = driver.dispose;
135
+ driver.dispose = async () => {
136
+ disposed = true;
137
+ cursorHistories.clear();
138
+ try {
139
+ await dispose?.call(driver);
140
+ } finally {
141
+ cursorHistories.clear();
142
+ }
143
+ };
144
+ driver.listKeys = async ({ cursor, limit, prefix = "" }) => {
145
+ invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
146
+ const listOptions = { limit };
147
+ if (cursor) listOptions.cursor = cursor;
148
+ if (prefix) listOptions.prefix = prefix;
149
+ const activeBinding = typeof bindingName === "string" ? getActiveCloudflareBinding(bindingName) : void 0;
150
+ const requestNamespace = cloudflareBindingNamespace(bindingName, namespaceId, activeBinding);
151
+ const continuation = cursor ? cursorHistories.take(cursor, requestNamespace) : {
152
+ providerCursor: void 0,
153
+ history: /* @__PURE__ */ new Set(),
154
+ namespace: requestNamespace
155
+ };
156
+ try {
157
+ if (continuation.providerCursor) listOptions.cursor = continuation.providerCursor;
158
+ const cursors = continuation.history;
159
+ const page = await driver.getInstance().list(listOptions);
160
+ if (!isCloudflareKVListPage(page)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "Cloudflare KV list returned an invalid page." });
161
+ const result = { keys: page.keys.map((key) => key.name) };
162
+ if (!page.list_complete) {
163
+ invariant(!disposed, "a KV store is open while the app runs, because Nitro disposes it only when it closes");
164
+ if (cursors.has(page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected a repeated pagination cursor." });
165
+ if (!recordCursor(cursors, page.cursor)) throw kvErrorDiagnostics.KV_PROVIDER_INVALID_RESPONSE({ problem: "ViteHub rejected pagination after the cursor history limit was reached." });
166
+ result.cursor = cursorHistories.store(page.cursor, cursors, requestNamespace);
167
+ }
168
+ cursorHistories.complete(cursor);
169
+ return result;
170
+ } catch (error) {
171
+ if (cursor && !disposed) cursorHistories.restore(cursor, continuation);
172
+ throw error;
173
+ }
174
+ };
175
+ return driver;
176
+ }
177
+ function createCloudflareKVStorage(options) {
178
+ const driver = createCloudflareDriver(options);
179
+ const storage = createKVStorage(driver);
180
+ storage.listKeys = (listOptions) => driver.listKeys({
181
+ ...listOptions,
182
+ prefix: normalizeKVListPrefix(listOptions.prefix)
183
+ });
184
+ return storage;
185
+ }
186
+ //#endregion
187
+ export { validateCloudflareKVBatch as a, installCloudflareKVLimits as i, createCloudflareKVStorage as n, assertCloudflareKVWrite as r, createCloudflareDriver as t };