@vite-hub/rate-limit 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -111,7 +111,7 @@ Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and
111
111
 
112
112
  Use `createRateLimiter()` when the application selects the driver and handles the decision. A production driver must implement one atomic `consume()` operation for its backend. A generic KV `get()` followed by `set()` is not safe under concurrent requests. `kvRateLimitDriver({ storage })` uses an atomic `increment` instead, so it works with any KV store that has one, for example `kv.store("limits")` from `vite-hub/kv` on Redis or Postgres. Its counters also count rejected requests.
113
113
 
114
- The KV driver waits at most one second for each storage operation. A timed-out operation returns `RATE_LIMIT_KV_TIMEOUT`: consume follows the `failure` policy; peek and reset return `unavailable`. The deadline does not cancel the storage operation, so a timed-out consume can still count. KV configuration errors still throw.
114
+ The KV driver waits at most one second for each individual storage call, so an operation with several calls can take longer. A timed-out call returns `RATE_LIMIT_KV_TIMEOUT`: consume follows the `failure` policy; peek, refund, and reset return `unavailable`. The deadline does not cancel the storage write (including consume, refund, or reset), so `unavailable` does not tell callers whether a write took effect. KV configuration errors still throw.
115
115
 
116
116
  Drivers return a `Result`: `[undefined, result]` after consuming the counter, and `[error, undefined]` only for an expected operational outage. Return the error of the store when it has one, such as a KV `Result` error, or a `ResultError` from your own `defineErrors()` catalog. The limiter then returns `reason: "unavailable"` and sets `allowed` from the failure policy, which defaults to deny. ViteHub-owned configuration errors, malformed provider results, and implementation defects throw Nostics diagnostics with `RATE_LIMIT_B####` or `RATE_LIMIT_R####` codes. Application driver errors keep their identity. See [Errors and diagnostics](https://vitehub.dev/docs/reference/errors-diagnostics).
117
117
 
@@ -124,18 +124,22 @@ The limiter exposes its resolved `policy` and the driver's declared `capabilitie
124
124
  | Driver | `peek()` | `refund()` | `reset()` |
125
125
  | ---------- | ------------------------------------------------------------------------- | ---------- | --------------------- |
126
126
  | memory | `used`, `remaining`, and `resetAt` in this process. `used: 0` when no counter exists. | Removes one request from the counter. | Deletes the counter. |
127
- | kv | `used`, `remaining`, and `resetAt` of the current window, shared by every process. | Adds one to a second counter that `consume()` subtracts at the limit. | Deletes the counters of the current window. |
127
+ | kv | `used`, `remaining`, and `resetAt` of the current window, shared by every process. | Adds one to a second counter that `consume()` subtracts at the limit. | Advances the counter generation so new requests start fresh; previous counters expire by TTL. |
128
128
  | cloudflare | `unsupported`. The binding exposes only `limit()`, which consumes a token. | `unsupported`. | `unsupported`. |
129
129
 
130
130
  For a managed guard, `refundRateLimit(event, id, options)` takes the same arguments as `checkRateLimit()` and returns `[error, result]`. The build discovers it like the other guards.
131
131
 
132
132
  For managed guards, `peekRateLimit(id, key)` and `resetRateLimit(id, key)` use the counters of `requireRateLimit()` in the current runtime. `vitehub rate-limit peek <id> <key>` and `vitehub rate-limit reset <id> <key>` (which asks on a terminal, or needs `--yes`) run the `rate-limit.peek` and `rate-limit.reset` operations of the running app, on the dev server or with `--url` on a deployed app that enables the Console. The Console **Rate Limits** page runs the same operations.
133
133
 
134
+ ## Refusals in request logs
135
+
136
+ With the evlog Nitro module registered, `requireRateLimit()` and `checkRateLimit()` append each refusal or unavailable decision to the `rateLimit` array on the request's wide event: `[{ name, limit, window, driver, keySource, allowed, reason, retryAfter? }]`. `keySource` is `option` or `client-address`; the key value is not on the event, because it can be an IP address or a user id. Without evlog, nothing is set. See [Server API](https://vitehub.dev/docs/rate-limit/server-api#see-refusals-on-each-request).
137
+
134
138
  ## Public imports
135
139
 
136
140
  | Import | Purpose |
137
141
  | ----------------------------------------- | ------------------------------------------------------------------------- |
138
- | `@vite-hub/rate-limit` | `requireRateLimit()`, `checkRateLimit()`, `createRateLimiter()`, `peekRateLimit()`, `resetRateLimit()`, and public contract types |
142
+ | `@vite-hub/rate-limit` | `requireRateLimit()`, `checkRateLimit()`, `refundRateLimit()`, `createRateLimiter()`, `peekRateLimit()`, `resetRateLimit()`, and public contract types |
139
143
  | `@vite-hub/rate-limit/drivers/memory` | Process-local fixed-window driver |
140
144
  | `@vite-hub/rate-limit/drivers/kv` | Fixed-window driver on a KV store with an atomic `increment` |
141
145
  | `@vite-hub/rate-limit/drivers/cloudflare` | Direct adapter for a request-scoped Cloudflare Rate Limiting binding |
@@ -3,6 +3,7 @@ import { Diagnostic } from "nostics";
3
3
  interface HostCliRunResult {
4
4
  exitCode: number | null;
5
5
  stdout: string;
6
+ stderr?: string;
6
7
  }
7
8
  /** Runs a host CLI with an argument array and no shell, and returns its stdout. */
8
9
  type HostCliRun = (command: string, args: readonly string[], options: {
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-szm60zN5.js";
1
+ import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-ITt8egpW.js";
2
2
  //#region src/cli.d.ts
3
3
  export type RateLimitCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
4
4
  export interface RateLimitCliOptions {
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
2
  import { r as parseRateLimitWindow } from "./policy-BeyQ0vnc.js";
3
3
  import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
4
- import { A as writeCliFailure, E as askOnTerminal, O as readViteHubDevTargetOption, n as callOperationFromCli, u as table } from "./operations-q0ieloSJ.js";
4
+ import { A as writeCliFailure, E as askOnTerminal, O as readViteHubDevTargetOption, n as callOperationFromCli, u as table } from "./operations-C6npllas.js";
5
5
  import * as v from "valibot";
6
6
  //#region src/cli.ts
7
7
  const rateLimitDevTargetErrors = {
@@ -188,7 +188,6 @@ function parseInspection(operation, value) {
188
188
  value: parsed.output
189
189
  } : void 0;
190
190
  }
191
- /** Writes a failure like the other primitive CLIs, but redacts the message, since it can echo a limited key. */
192
191
  function writeFailure(parsed, context, failure) {
193
192
  return writeCliFailure(parsed.json, context, {
194
193
  ...failure,
@@ -1,11 +1,9 @@
1
1
  import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { i as resolveRateLimitDriver, r as listRuntimeRateLimiters } from "./state-Fq3rGFO3.js";
2
+ import { i as resolveRateLimitDriver, r as listRuntimeRateLimiters } from "./state-D0GPlkS7.js";
3
3
  import * as v from "valibot";
4
4
  //#region src/counters.ts
5
- /** Reason that Cloudflare counters are not readable. The binding exposes only `limit({ key })`. */
6
5
  const cloudflareRateLimitCounterUnsupportedReason = "The Cloudflare Rate Limiting binding exposes only limit(), which consumes a token. It cannot read or reset a counter.";
7
6
  const unusedReason = "No request used this Rate Limit in this process since it started, so no counter exists.";
8
- /** A `kv` counter is shared, but the policy that names its window comes from the requests of this process. */
9
7
  const unusedKVReason = "No request used this Rate Limit in this process since it started, so this process does not know its window. Other processes can still have a counter.";
10
8
  function unavailableReason(cause) {
11
9
  return `The Rate Limit driver failed: ${cause instanceof Error ? cause.message : String(cause)}`;
@@ -1,2 +1,2 @@
1
- import { i as kvRateLimitDriver, n as KVRateLimitDriverOptions, r as RateLimitKVStorage, t as KVRateLimitDriver } from "../kv-Cw_jK6Gu.js";
1
+ import { i as kvRateLimitDriver, n as KVRateLimitDriverOptions, r as RateLimitKVStorage, t as KVRateLimitDriver } from "../kv-NA_0qogC.js";
2
2
  export { KVRateLimitDriver, KVRateLimitDriverOptions, RateLimitKVStorage, kvRateLimitDriver };
@@ -5,7 +5,6 @@ function isStorage(value) {
5
5
  if (!value || typeof value !== "object") return false;
6
6
  return typeof Reflect.get(value, "increment") === "function" && typeof Reflect.get(value, "get") === "function";
7
7
  }
8
- /** Bound the request wait without hiding configuration errors thrown by KV. */
9
8
  async function withKVDeadline(operation) {
10
9
  let timer;
11
10
  const deadline = new Promise((resolve) => {
@@ -17,17 +16,9 @@ async function withKVDeadline(operation) {
17
16
  clearTimeout(timer);
18
17
  }
19
18
  }
20
- /**
21
- * KV keys use `/` and `:` as separators and reject a `.` or `..` segment, so encode the parts that come from the app.
22
- * Without it, a client key such as `..` makes every increment fail, and `failure: "allow"` then lets it through.
23
- */
24
19
  function keySegment(value) {
25
20
  return encodeURIComponent(value).replaceAll(".", "%2E");
26
21
  }
27
- /**
28
- * One counter for each Rate Limit, window duration, key, and window start. A new window uses a new key, so no reset is
29
- * necessary. The duration keeps a `1m` and a `1h` limiter of one name apart when their window starts align.
30
- */
31
22
  function fixedWindow(input, timestamp, prefix) {
32
23
  const start = Math.floor(timestamp / input.windowMs) * input.windowMs;
33
24
  const resetAt = start + input.windowMs;
@@ -1,6 +1,13 @@
1
1
  import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-DRuEG4wu.js";
2
2
  //#region src/drivers/memory.ts
3
3
  const defaultMaxEntries = 1e5;
4
+ function entryKey(input) {
5
+ return JSON.stringify([
6
+ input.name ?? "default",
7
+ input.windowMs,
8
+ input.key
9
+ ]);
10
+ }
4
11
  function memoryRateLimitDriver(options = {}) {
5
12
  const entries = /* @__PURE__ */ new Map();
6
13
  let nextExpiry = Number.POSITIVE_INFINITY;
@@ -26,7 +33,7 @@ function memoryRateLimitDriver(options = {}) {
26
33
  consume(input) {
27
34
  const timestamp = now();
28
35
  prune(timestamp);
29
- const key = JSON.stringify([input.name ?? "default", input.key]);
36
+ const key = entryKey(input);
30
37
  const current = entries.get(key);
31
38
  if (!current && entries.size >= maxEntries) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0008({ message: `[vitehub] Memory Rate Limit driver reached maxEntries (${maxEntries}) while active counters remain.` });
32
39
  let entry = current;
@@ -58,7 +65,7 @@ function memoryRateLimitDriver(options = {}) {
58
65
  peek(input) {
59
66
  const timestamp = now();
60
67
  prune(timestamp);
61
- const key = JSON.stringify([input.name ?? "default", input.key]);
68
+ const key = entryKey(input);
62
69
  const entry = entries.get(key);
63
70
  return [void 0, {
64
71
  resetAt: entry && entry.resetAt > timestamp ? entry.resetAt : void 0,
@@ -67,12 +74,12 @@ function memoryRateLimitDriver(options = {}) {
67
74
  },
68
75
  name: "memory",
69
76
  refund(input) {
70
- const entry = entries.get(JSON.stringify([input.name ?? "default", input.key]));
77
+ const entry = entries.get(entryKey(input));
71
78
  if (entry && entry.resetAt > now() && entry.count > 0) entry.count -= 1;
72
79
  return [void 0, void 0];
73
80
  },
74
81
  reset(input) {
75
- const key = JSON.stringify([input.name ?? "default", input.key]);
82
+ const key = entryKey(input);
76
83
  entries.delete(key);
77
84
  return [void 0, void 0];
78
85
  },
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
2
  import { a as rateLimitPolicyKeys, n as normalizeRateLimitPolicy, t as declaredRateLimitPolicy } from "./policy-BeyQ0vnc.js";
3
3
  import { n as createRateLimiter } from "./kv-provider-DlgNQC-o.js";
4
- import { i as resolveRateLimitDriver, n as getRuntimeRateLimiter } from "./state-Fq3rGFO3.js";
5
- import { n as resetRateLimit, t as peekRateLimit } from "./counters-D4LANMAi.js";
4
+ import { i as resolveRateLimitDriver, n as getRuntimeRateLimiter } from "./state-D0GPlkS7.js";
5
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-CwyRigdy.js";
6
6
  import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-_Tz3DcpB.js";
7
7
  import { toResultError } from "@vite-hub/runtime";
8
8
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
@@ -23,6 +23,23 @@ function getActiveCloudflareEnv() {
23
23
  return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
24
24
  }
25
25
  //#endregion
26
+ //#region ../internal/src/runtime/request-log.ts
27
+ function isRequestLog(value) {
28
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
29
+ }
30
+ function contextLog(value) {
31
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
32
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
33
+ }
34
+ /**
35
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
36
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
37
+ */
38
+ function requestLog(input) {
39
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
40
+ return isRequestLog(log) ? log : void 0;
41
+ }
42
+ //#endregion
26
43
  //#region src/guard.ts
27
44
  const guardOptionKeys = {
28
45
  checkRateLimit: /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]),
@@ -46,7 +63,6 @@ function isWebRequest(value) {
46
63
  const headers = Reflect.get(value, "headers");
47
64
  return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObject(headers) && typeof Reflect.get(headers, "get") === "function";
48
65
  }
49
- /** Structural Requests may carry unrelated event-named properties, so identify the event's shape. */
50
66
  function isRequestEvent(input) {
51
67
  if ("~standard" in input) {
52
68
  const standard = input["~standard"];
@@ -69,7 +85,6 @@ function getRequestScope(input) {
69
85
  function getRequestKey(scope, driver) {
70
86
  return driver === "cloudflare" ? scope.headers.get("cf-connecting-ip") || scope.clientAddress : scope.clientAddress;
71
87
  }
72
- /** A failure of one check, such as a request without a key. Option errors throw instead. */
73
88
  function checkError(code, message) {
74
89
  const diagnostic = code === "RATE_LIMIT_R0009" ? rateLimitErrorDiagnostics.RATE_LIMIT_R0009({ message }) : rateLimitErrorDiagnostics.RATE_LIMIT_R0013({ message });
75
90
  return toResultError(diagnostic);
@@ -109,7 +124,18 @@ async function consumeRateLimit(event, name, options, guard) {
109
124
  if (callError) return [callError, void 0];
110
125
  const [error, limiter] = call.counter === "cloudflare" ? getCloudflareRateLimiter(call.scope, call.id, call.policy) : [void 0, getRuntimeRateLimiter(call.counter, call.id, call.policy)];
111
126
  if (error) return [error, void 0];
112
- return [void 0, await limiter.consume({ key: call.key })];
127
+ const decision = await limiter.consume({ key: call.key });
128
+ if (decision.reason) requestLog(event)?.set({ rateLimit: [{
129
+ name: call.id,
130
+ limit: call.policy.limit,
131
+ window: call.policy.window,
132
+ driver: call.counter,
133
+ keySource: options.key === void 0 ? "client-address" : "option",
134
+ allowed: decision.allowed,
135
+ reason: decision.reason,
136
+ ...decision.retryAfter === void 0 ? {} : { retryAfter: decision.retryAfter }
137
+ }] });
138
+ return [void 0, decision];
113
139
  }
114
140
  /**
115
141
  * Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
@@ -1,7 +1,6 @@
1
1
  import { c as RateLimitDriver } from "./types-OzukEqHf.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
3
  //#region src/drivers/kv.d.ts
4
- /** `[error, data]`, as KV operations return it. */
5
4
  type KVOperationResult<T> = Result<T>;
6
5
  /**
7
6
  * The KV operations that the driver uses. `kv` and `kv.store(name)` from `@vite-hub/kv` match it. `increment` must be
@@ -104,6 +104,11 @@ interface OperationAccess {
104
104
  */
105
105
  readonly sections: "all" | readonly string[];
106
106
  readonly user?: OperationUser;
107
+ /**
108
+ * Who signed the call: `"console"` when the ViteHub Console signed it for a person, whose `user` is then a Console
109
+ * account and not an app user, or `"cli"` for a key. Not set for other calls.
110
+ */
111
+ readonly via?: "console" | "cli";
107
112
  }
108
113
  interface OperationContext {
109
114
  /** The checked Console access of the call. */
@@ -166,7 +171,8 @@ interface OperationDefinition<Input, Output> {
166
171
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
167
172
  input: StandardSchemaV1<unknown, Input>;
168
173
  output?: StandardSchemaV1<unknown, Output>;
169
- cli?: {
174
+ /** `false`: no `vitehub` command. The Console and MCP still call the operation. */
175
+ cli?: false | {
170
176
  /** Defaults: namespace = section, command = verb. */
171
177
  namespace?: string;
172
178
  /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
@@ -207,7 +213,7 @@ interface OperationDefinition<Input, Output> {
207
213
  /** An operation of any input and output, as a registry holds it. */
208
214
  interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
209
215
  readOnlyWhen?: (input: never) => boolean;
210
- cli?: {
216
+ cli?: false | {
211
217
  namespace?: string;
212
218
  command?: string;
213
219
  default?: boolean;
@@ -32,7 +32,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
32
32
  why: ({ message }) => message === void 0 ? "" : String(message)
33
33
  },
34
34
  INTERNAL_R0022: {
35
- fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields.",
35
+ fix: "Send input that matches the schema of the operation. `vitehub <namespace> <command> --help` shows the fields, and the list_operations tool of the ViteHub MCP gives the input schema of each operation.",
36
36
  why: ({ message }) => message === void 0 ? "" : String(message)
37
37
  },
38
38
  INTERNAL_R0024: {
@@ -251,6 +251,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
251
251
  why: ({ owner }) => `[vitehub] ${owner} extends tuple requires [preset, options] with an options object.`,
252
252
  fix: "Set `extends` to a preset, or to a two-item tuple `[preset, { ...options }]` whose second item is a plain object."
253
253
  },
254
+ INTERNAL_RUNTIME_PACKAGE_VERSION_CONFLICT: {
255
+ why: ({ first, name, second }) => `[vitehub] One server function needs ${name} from two installations: ${first} and ${second}.`,
256
+ fix: "Install one version of the package that the message names, for example with `pnpm dedupe` or an `overrides` entry in `package.json`, then build again."
257
+ },
254
258
  INTERNAL_SECRET_PURPOSE_MISSING: {
255
259
  why: "[vitehub] A derived secret requires a purpose.",
256
260
  fix: "Pass a non-empty purpose to `deriveSecret()`, such as `deriveSecret(\"my-module:session\")`."
@@ -465,7 +469,7 @@ function hasProjectRootDirectoryMarker(root) {
465
469
  for (const marker of projectRootDirectoryMarkers) try {
466
470
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
467
471
  } catch (error) {
468
- if (error.code !== "ENOENT") throw error;
472
+ if (!isMissingProjectMarker(error)) throw error;
469
473
  }
470
474
  return false;
471
475
  }
@@ -479,11 +483,15 @@ function hasProjectRootFileMarker(root, markers) {
479
483
  try {
480
484
  if (statSync(resolve(root, ...path)).isFile()) return true;
481
485
  } catch (error) {
482
- if (error.code !== "ENOENT") throw error;
486
+ if (!isMissingProjectMarker(error)) throw error;
483
487
  }
484
488
  }
485
489
  return false;
486
490
  }
491
+ function isMissingProjectMarker(error) {
492
+ const code = error.code;
493
+ return code === "ENOENT" || code === "ENOTDIR";
494
+ }
487
495
  //#endregion
488
496
  //#region ../internal/src/invariant.ts
489
497
  const invariantDiagnostics = /*#__PURE__*/ defineDiagnostics({
@@ -1019,11 +1027,16 @@ function operationsOf(value) {
1019
1027
  /** The CLI namespace and command of an operation. Defaults: the section (or the name prefix) and the verb. */
1020
1028
  function operationCliPath(operation) {
1021
1029
  const dot = operation.name.indexOf(".");
1030
+ const cli = operationCliOptions(operation);
1022
1031
  return {
1023
- command: operation.cli?.command ?? operation.name.slice(dot + 1),
1024
- namespace: operation.cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
1032
+ command: cli?.command ?? operation.name.slice(dot + 1),
1033
+ namespace: cli?.namespace ?? (typeof operation.section === "string" ? operation.section : operation.name.slice(0, dot))
1025
1034
  };
1026
1035
  }
1036
+ /** The CLI options of an operation, or undefined for an operation without options or with `cli: false`. */
1037
+ function operationCliOptions(operation) {
1038
+ return operation.cli || void 0;
1039
+ }
1027
1040
  /**
1028
1041
  * The MCP tool name of an operation: every character outside `[a-zA-Z0-9_-]` becomes `_`, since clients such as
1029
1042
  * Claude reject a dot in a tool name. `content.publish` is `content_publish`.
@@ -1048,6 +1061,7 @@ function createOperationRegistry(sources) {
1048
1061
  const operations = [...byName.values()].map((entry) => entry.operation).sort((left, right) => left.name.localeCompare(right.name));
1049
1062
  const commands = /* @__PURE__ */ new Map();
1050
1063
  for (const operation of operations) {
1064
+ if (operation.cli === false) continue;
1051
1065
  const { command, namespace } = operationCliPath(operation);
1052
1066
  if (reservedOperationNamespaces.includes(namespace)) throw invalidDefinition(operation.name, `the CLI namespace ${JSON.stringify(namespace)} is reserved for built-in commands. Set cli.namespace to another name.`);
1053
1067
  const key = `${namespace} ${command}`;
@@ -1075,12 +1089,23 @@ function describeInputIssues(issues) {
1075
1089
  return path ? `${path}: ${issue.message}` : issue.message;
1076
1090
  }).join(" ");
1077
1091
  }
1092
+ function describeInputFields(schema) {
1093
+ const shapes = (Array.isArray(schema.anyOf) ? schema.anyOf : [schema]).map((shape) => {
1094
+ if (!isRecordOrFunction(shape) || !isRecordOrFunction(shape.properties)) return void 0;
1095
+ const required = Array.isArray(shape.required) ? shape.required : [];
1096
+ const fields = Object.keys(shape.properties).map((field) => required.includes(field) ? field : `${field}?`);
1097
+ return fields.length ? `{ ${fields.join(", ")} }` : "{}";
1098
+ });
1099
+ return shapes.every((shape) => shape !== void 0) ? shapes.join(" or ") : void 0;
1100
+ }
1078
1101
  /** Validate `input` with the schema of the operation. Throws `INTERNAL_R0022` with `status: 400`. */
1079
1102
  async function parseOperationInput(operation, input) {
1080
1103
  const result = await operation.input["~standard"].validate(input ?? {});
1081
1104
  if (!result.issues) return result.value;
1082
- const error = internalErrorDiagnostics.INTERNAL_R0022({ message: `Invalid input for ${operation.name}. ${describeInputIssues(result.issues)}` });
1083
- throw Object.assign(error, { status: 400 });
1105
+ const fields = describeInputFields(operationInputJsonSchema(operation));
1106
+ const issues = describeInputIssues(result.issues);
1107
+ const message = `Invalid input for ${operation.name}. ${issues}${fields ? `${/[.!?]$/.test(issues) ? "" : "."} ${operation.name} takes ${fields}.` : ""}`;
1108
+ throw Object.assign(internalErrorDiagnostics.INTERNAL_R0022({ message }), { status: 400 });
1084
1109
  }
1085
1110
  /**
1086
1111
  * The section that grants a call, or `false` for any Console user. `undefined` means the input names no valid section.
@@ -1,8 +1,7 @@
1
1
  import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { n as resetRateLimit, t as peekRateLimit } from "./counters-D4LANMAi.js";
2
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-CwyRigdy.js";
3
3
  import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
4
4
  //#region src/runtime/operations.ts
5
- /** Removes credentials from the echoed key and from driver error text before the result leaves the runtime. */
6
5
  function redact(result) {
7
6
  return {
8
7
  ...result,
@@ -1,5 +1,5 @@
1
1
  import { n as RateLimitPeekInspection, r as RateLimitResetInspection } from "./counters-d8FaLiE1.js";
2
- import { t as AnyOperation } from "./operation-definition-nmRu_O3V.js";
2
+ import { t as AnyOperation } from "./operation-definition-CI2PJGqu.js";
3
3
  //#region ../internal/src/operations-dev.d.ts
4
4
  /**
5
5
  * Bundled into owner packages and used only by their serve-only generated Nitro route. Operations get the Request as
@@ -1,4 +1,4 @@
1
- import { F as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as toOperationFailure, f as defineOperation, g as readOperationRpcCall, h as operationRpcRefusal, i as createOperationRegistry, l as runOperation, o as operationRpcHeader, p as answerOperationRpc, s as operationsOf, t as assertOperationProject } from "./operations-q0ieloSJ.js";
1
+ import { F as internalErrorDiagnostics, a as operationRootHeader, c as projectRootHash, d as toOperationFailure, f as defineOperation, g as readOperationRpcCall, h as operationRpcRefusal, i as createOperationRegistry, l as runOperation, o as operationRpcHeader, p as answerOperationRpc, s as operationsOf, t as assertOperationProject } from "./operations-C6npllas.js";
2
2
  import { n as isViteHubLoopbackPeer } from "./dev-peer-CHafxbtj.js";
3
3
  import * as v from "valibot";
4
4
  //#region ../internal/src/secret.ts
@@ -237,7 +237,7 @@ function createStandaloneOperationHandler(sources, root) {
237
237
  }
238
238
  //#endregion
239
239
  //#region src/operations.ts
240
- const runtime = () => import("./operations-B1MnA9cW.js");
240
+ const runtime = () => import("./operations-DcgGebib.js");
241
241
  const target = v.object({
242
242
  key: v.pipe(v.string(), v.minLength(1, "Name the limited key, for example a client IP or user ID.")),
243
243
  name: v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name the stable ID of `requireRateLimit()`."))
package/dist/runtime.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { O as RateLimitRuntimeConfig } from "./types-OzukEqHf.js";
2
- import { r as RateLimitKVStorage } from "./kv-Cw_jK6Gu.js";
2
+ import { r as RateLimitKVStorage } from "./kv-NA_0qogC.js";
3
3
  //#region src/runtime/state.d.ts
4
4
  /** The KV store of the `kv` driver. The generated Nitro plugin passes it from `@vite-hub/kv`. */
5
5
  interface RateLimitKVRuntime {
package/dist/runtime.js CHANGED
@@ -1,2 +1,2 @@
1
- import { a as setRateLimitRuntimeConfig, i as resolveRateLimitDriver, t as getRateLimitRuntimeConfig } from "./state-Fq3rGFO3.js";
1
+ import { a as setRateLimitRuntimeConfig, i as resolveRateLimitDriver, t as getRateLimitRuntimeConfig } from "./state-D0GPlkS7.js";
2
2
  export { getRateLimitRuntimeConfig, resolveRateLimitDriver, setRateLimitRuntimeConfig };
@@ -9,7 +9,6 @@ let runtimeConfig = { driver: "memory" };
9
9
  let kvRuntime;
10
10
  let activeDriver;
11
11
  const runtimeLimiters = /* @__PURE__ */ new Map();
12
- /** The counters of this process, or in app tests the counters of the current test. */
13
12
  function limiters() {
14
13
  const test = getViteHubTestMode();
15
14
  return test ? test.backend("rate-limit", () => /* @__PURE__ */ new Map()) : runtimeLimiters;
package/dist/vite.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { r as ViteHubCliPluginMetadata } from "./cli-szm60zN5.js";
1
+ import { r as ViteHubCliPluginMetadata } from "./cli-ITt8egpW.js";
2
2
  import { b as RateLimitOptions, s as RateLimitDeclaration } from "./types-OzukEqHf.js";
3
- import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
3
+ import { n as OperationContributionEntry } from "./operation-definition-CI2PJGqu.js";
4
4
  import { Plugin } from "vite";
5
5
  //#region ../internal/src/durability.d.ts
6
6
  /**
@@ -76,6 +76,8 @@ interface ViteHubResourceSummary {
76
76
  owner: string;
77
77
  /** Absent when no id is known yet. */
78
78
  source?: ViteHubResourceIdSource;
79
+ /** The resource is in the Wrangler config of a standalone Provider Output Worker, not in Nitro's. */
80
+ standalone?: boolean;
79
81
  }
80
82
  interface ViteHubInspectionContributor {
81
83
  definitions?: readonly ViteHubDefinitionInspector[];
package/dist/vite.js CHANGED
@@ -5,7 +5,7 @@ import { kvRateLimitDriver } from "./drivers/kv.js";
5
5
  import { memoryRateLimitDriver } from "./drivers/memory.js";
6
6
  import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-_Tz3DcpB.js";
7
7
  import { i as resolve$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-B6gTdgy9.js";
8
- import { C as isServerEnvironment, D as readViteHubDevServerFile, F as internalErrorDiagnostics, M as cloneRecord, N as isRecord, P as isRecordOrFunction, S as getResolvedFeatureOptions, T as shouldSkipViteProviderBuild, _ as invariant, b as createNoExternalAddition, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, m as operationRpcPath, r as collectOperationContributions, w as resolveViteHubProjectRoot, x as getDeploymentHost, y as VITEHUB_PROJECT_ROOT } from "./operations-q0ieloSJ.js";
8
+ import { C as isServerEnvironment, D as readViteHubDevServerFile, F as internalErrorDiagnostics, M as cloneRecord, N as isRecord, P as isRecordOrFunction, S as getResolvedFeatureOptions, T as shouldSkipViteProviderBuild, _ as invariant, b as createNoExternalAddition, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, m as operationRpcPath, r as collectOperationContributions, w as resolveViteHubProjectRoot, x as getDeploymentHost, y as VITEHUB_PROJECT_ROOT } from "./operations-C6npllas.js";
9
9
  import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
10
10
  import { formatDiagnostic } from "nostics";
11
11
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
@@ -176,8 +176,15 @@ async function writeFileIfChanged(file, contents) {
176
176
  await mkdir(resolve$1(file, ".."), { recursive: true });
177
177
  await writeFile(file, contents, "utf8");
178
178
  }
179
- //#endregion
180
- //#region ../internal/src/nitro-kit.ts
179
+ Object.freeze({ vitehubAuthAccess: "handler" });
180
+ /**
181
+ * The route meta of a generated handler that checks access on every request, even when the app adds no rule: a required
182
+ * `authorize` policy, an explicit `access` rule, a required access token, or a signature. Auth access routes still apply
183
+ * to it, so an app rule stays in force. `checksOwnAccess(event)` of `vite-hub/auth` reads it, so app middleware can skip
184
+ * the route. A route that can run without a check, such as a browser error sink, an optional `authorize`, or a webhook
185
+ * with `secret: false`, must not use it.
186
+ */
187
+ const ownAccessRouteMeta = Object.freeze({ vitehubOwnAccess: true });
181
188
  function cloneArray(value) {
182
189
  return Array.isArray(value) ? [...value] : [];
183
190
  }
@@ -293,6 +300,7 @@ async function installStandaloneOperationRpc(config, command, module) {
293
300
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
294
301
  kit.addHandler({
295
302
  handler,
303
+ meta: { ...ownAccessRouteMeta },
296
304
  route: operationRpcPath
297
305
  });
298
306
  const devHandlers = kit.config.devHandlers;
@@ -430,7 +438,11 @@ function cloneProviderValue(value) {
430
438
  if (value && typeof value === "object") return cloneProviderRecord(value);
431
439
  return value;
432
440
  }
433
- function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner) {
441
+ /**
442
+ * The incoming entries that the app config does not have yet. An entry that the app already has must agree on
443
+ * `conflictKeys`, and on each of `setKeys` that the incoming entry sets, because the app's entry is the one that stays.
444
+ */
445
+ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner, setKeys = []) {
434
446
  const current = Array.isArray(existing) ? existing.map(cloneProviderRecord) : [];
435
447
  return (incoming ?? []).filter((entry) => {
436
448
  const identity = entry[identityKey];
@@ -440,6 +452,8 @@ function compatibleEntries(existing, incoming, identityKey, conflictKeys, owner)
440
452
  return true;
441
453
  }
442
454
  if (conflictKeys.some((key) => !isDeepStrictEqual(match[key], entry[key]))) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] Cloudflare ${identityKey} ${JSON.stringify(identity)} from ${owner} is already assigned to an incompatible resource.` });
455
+ const differentKey = setKeys.find((key) => entry[key] !== void 0 && !isDeepStrictEqual(match[key], entry[key]));
456
+ if (differentKey) throw internalErrorDiagnostics.INTERNAL_B0001({ message: `[vitehub] The Cloudflare ${identityKey} ${JSON.stringify(identity)} in the app's Wrangler config has ${differentKey} ${JSON.stringify(match[differentKey]) ?? "unset"}, but ${owner} sets ${JSON.stringify(entry[differentKey])}. Remove the entry from the Wrangler config, because ViteHub writes it, or give it the same value.` });
443
457
  return false;
444
458
  });
445
459
  }
@@ -496,7 +510,7 @@ function mergeContribution(wrangler, owner, contribution) {
496
510
  const queues = cloneProviderRecord(wrangler.queues);
497
511
  const secrets = cloneProviderRecord(wrangler.secrets);
498
512
  const environments = cloneProviderRecord(wrangler.env);
499
- const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner);
513
+ const consumers = compatibleEntries(queues.consumers, contribution.queues?.consumers, "queue", [], owner, ["max_batch_size"]);
500
514
  const producers = compatibleEntries(queues.producers, contribution.queues?.producers, "binding", ["queue"], owner);
501
515
  const r2Buckets = compatibleEntries(wrangler.r2_buckets, contribution.r2Buckets, "binding", ["bucket_name", "jurisdiction"], owner);
502
516
  const rateLimits = compatibleEntries(wrangler.ratelimits, contribution.rateLimits, "name", ["namespace_id", "simple"], owner);
@@ -853,7 +867,6 @@ function getHostingProvider(hosting) {
853
867
  //#endregion
854
868
  //#region src/discovery.ts
855
869
  const rateLimitImports = /* @__PURE__ */ new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
856
- /** Functions whose calls declare a managed Rate Limit. They use the same counters. */
857
870
  const rateLimitGuards = [
858
871
  "checkRateLimit",
859
872
  "refundRateLimit",
@@ -907,7 +920,6 @@ function resolveDirectGuard(name, scopes) {
907
920
  if (scope.shadows.has(name)) return void 0;
908
921
  }
909
922
  }
910
- /** The literal value of the `const` that `name` reads in this scope, or `undefined` for any other binding. */
911
923
  function resolveConstant(name, scopes) {
912
924
  for (let index = scopes.length - 1; index >= 0; index -= 1) {
913
925
  const scope = scopes[index];
@@ -923,7 +935,6 @@ function resolveNamespace(name, scopes) {
923
935
  }
924
936
  return false;
925
937
  }
926
- /** The guard that a call invokes, or `undefined` when the callee is not a Rate Limit guard. */
927
938
  function rateLimitGuardOf(callee, scopes) {
928
939
  if (callee.type === "Identifier") return resolveDirectGuard(callee.name, scopes);
929
940
  if (callee.type !== "MemberExpression" || callee.object.type !== "Identifier" || !resolveNamespace(callee.object.name, scopes)) return;
@@ -1120,7 +1131,6 @@ function staticString(expression) {
1120
1131
  if (value.type === "Literal" && typeof value.value === "string") return value.value;
1121
1132
  if (value.type === "TemplateLiteral" && value.expressions.length === 0) return value.quasis[0]?.value.cooked ?? value.quasis[0]?.value.raw;
1122
1133
  }
1123
- /** A string or number literal, or an identifier that reads a `const` with one. */
1124
1134
  function staticScalar(expression, scopes) {
1125
1135
  const value = unwrapStaticExpression(expression);
1126
1136
  if (value.type === "Literal" && typeof value.value === "number") return value.value;
@@ -1430,7 +1440,6 @@ const packageName = "@vite-hub/rate-limit";
1430
1440
  const pluginName = "@vite-hub/rate-limit/vite";
1431
1441
  const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
1432
1442
  const mergeNoExternal = createNoExternalAddition(packageName);
1433
- /** The driver of the default KV store, or `undefined` when the app has no KV. */
1434
1443
  function kvStoreDriver(config, build = false) {
1435
1444
  const api = (config.plugins?.find((plugin) => plugin.name === "@vite-hub/kv/vite"))?.api;
1436
1445
  const kv = (build ? api?.getBuildConfig?.() : void 0)?.kv ?? api?.getConfig?.().kv;
@@ -1455,9 +1464,6 @@ function mergeNitroConfig(config, value, declarations, namespace, driver, nitroC
1455
1464
  });
1456
1465
  return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
1457
1466
  }
1458
- /**
1459
- * `kvWindows`: on Cloudflare, a Rate Limit uses a window that the binding does not support, so it counts in KV.
1460
- */
1461
1467
  function renderRuntimeInstaller(runtimeConfig, kvImport, kvWindows) {
1462
1468
  if (runtimeConfig.driver === "cloudflare" && kvWindows) return [
1463
1469
  "import { definePlugin } from 'nitro'",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/rate-limit",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Provider-neutral Rate Limit primitives and Vite deployment integration for ViteHub.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -67,7 +67,7 @@
67
67
  },
68
68
  "dependencies": {
69
69
  "@valibot/to-json-schema": "^1.8.0",
70
- "@vite-hub/runtime": "0.4.0",
70
+ "@vite-hub/runtime": "0.5.0",
71
71
  "birpc": "^4.2.0",
72
72
  "h3": "^2.0.8",
73
73
  "nostics": "1.4.0",
@@ -76,6 +76,7 @@
76
76
  "devDependencies": {
77
77
  "@types/node": "^24.19.1",
78
78
  "@vite-hub/internal": "0.0.1",
79
+ "evlog": "2.33.1",
79
80
  "nitro": "^3.0.261103-rc",
80
81
  "publint": "^0.3.25",
81
82
  "typescript": "^6.0.3",