@vite-hub/rate-limit 0.4.1 → 0.5.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 (35) hide show
  1. package/README.md +7 -3
  2. package/dist/{cli-szm60zN5.d.ts → cli-B77bo6ii.d.ts} +1 -6
  3. package/dist/cli.d.ts +2 -4
  4. package/dist/cli.js +5 -7
  5. package/dist/{cloudflare-_Tz3DcpB.js → cloudflare-CWK4wJ9b.js} +4 -7
  6. package/dist/{counters-d8FaLiE1.d.ts → counters-BCNUEaDn.d.ts} +1 -3
  7. package/dist/{counters-D4LANMAi.js → counters-dyc0Q_HL.js} +3 -6
  8. package/dist/{dev-peer-CHafxbtj.js → dev-peer-D0vOxmrD.js} +1 -2
  9. package/dist/drivers/cloudflare.d.ts +2 -6
  10. package/dist/drivers/cloudflare.js +1 -2
  11. package/dist/drivers/kv.d.ts +1 -1
  12. package/dist/drivers/kv.js +2 -12
  13. package/dist/drivers/memory.d.ts +2 -4
  14. package/dist/drivers/memory.js +13 -7
  15. package/dist/durability.d.ts +1 -3
  16. package/dist/durability.js +1 -2
  17. package/dist/{error-diagnostics-DRuEG4wu.js → error-diagnostics-ulOX0clN.js} +1 -2
  18. package/dist/index.d.ts +2 -6
  19. package/dist/index.js +36 -13
  20. package/dist/{inspect-B6gTdgy9.js → inspect-Dqvi9vUt.js} +2 -4
  21. package/dist/{kv-Cw_jK6Gu.d.ts → kv-DldoJary.d.ts} +1 -4
  22. package/dist/{kv-provider-DlgNQC-o.js → kv-provider-DAq-42o6.js} +4 -6
  23. package/dist/{operation-definition-nmRu_O3V.d.ts → operation-definition-CqZkx1Rm.d.ts} +8 -6
  24. package/dist/{operations-B1MnA9cW.js → operations-BuAYwMe4.js} +4 -6
  25. package/dist/{operations-q0ieloSJ.js → operations-DWWMHBWt.js} +46 -27
  26. package/dist/operations.d.ts +2 -6
  27. package/dist/operations.js +7 -11
  28. package/dist/{policy-BeyQ0vnc.js → policy-CMsNKnqo.js} +2 -3
  29. package/dist/runtime.d.ts +2 -4
  30. package/dist/runtime.js +1 -2
  31. package/dist/{state-Fq3rGFO3.js → state-BXD6-GFo.js} +4 -6
  32. package/dist/{types-OzukEqHf.d.ts → types-Bw8vrrVF.d.ts} +0 -2
  33. package/dist/vite.d.ts +5 -15
  34. package/dist/vite.js +41 -51
  35. package/package.json +7 -6
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 |
@@ -1,8 +1,8 @@
1
1
  import { Diagnostic } from "nostics";
2
- //#region ../internal/src/host-credentials.d.ts
3
2
  interface HostCliRunResult {
4
3
  exitCode: number | null;
5
4
  stdout: string;
5
+ stderr?: string;
6
6
  }
7
7
  /** Runs a host CLI with an argument array and no shell, and returns its stdout. */
8
8
  type HostCliRun = (command: string, args: readonly string[], options: {
@@ -10,8 +10,6 @@ type HostCliRun = (command: string, args: readonly string[], options: {
10
10
  env: NodeJS.ProcessEnv;
11
11
  signal?: AbortSignal;
12
12
  }) => Promise<HostCliRunResult>;
13
- //#endregion
14
- //#region ../internal/src/provision.d.ts
15
13
  type ProvisionProvider = "cloudflare" | "vercel";
16
14
  interface ProvisionLogger {
17
15
  log: (message: string) => void;
@@ -63,8 +61,6 @@ interface ProvisionStep {
63
61
  /** Describes the Provision State this step records. Runs without network access, also without credentials. */
64
62
  recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
65
63
  }
66
- //#endregion
67
- //#region ../internal/src/cli.d.ts
68
64
  interface ViteHubCliStreams {
69
65
  stderr: {
70
66
  write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
@@ -159,5 +155,4 @@ interface ViteHubCliPluginMetadata {
159
155
  cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
160
156
  }
161
157
  type StdoutWriteCallback = (error?: Error | null) => void;
162
- //#endregion
163
158
  export { ViteHubCliStreams as i, ViteHubCliContributor as n, ViteHubCliPluginMetadata as r, ViteHubCliContext as t };
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-szm60zN5.js";
2
- //#region src/cli.d.ts
1
+ import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-B77bo6ii.js";
3
2
  export type RateLimitCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
4
3
  export interface RateLimitCliOptions {
5
4
  /** Asks whether `reset` may delete a counter. Defaults to a prompt on a terminal, and refuses without one. */
@@ -12,5 +11,4 @@ export interface RateLimitCliOptions {
12
11
  * `args[0]` is the command name, `peek` or `reset`.
13
12
  */
14
13
  export declare function runRateLimitCli(args: string[], context: RateLimitCliContext, options?: RateLimitCliOptions): Promise<number>;
15
- export declare function createRateLimitCliContributor(options?: RateLimitCliOptions): ViteHubCliContributor;
16
- //#endregion
14
+ export declare function createRateLimitCliContributor(options?: RateLimitCliOptions): ViteHubCliContributor;
package/dist/cli.js CHANGED
@@ -1,9 +1,9 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { r as parseRateLimitWindow } from "./policy-BeyQ0vnc.js";
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";
1
+ import { A as writeCliFailure, E as askOnTerminal, O as readViteHubDevTargetOption, n as callOperationFromCli, u as table } from "./operations-DWWMHBWt.js";
2
+ import { t as redactInspectionText } from "./inspect-Dqvi9vUt.js";
3
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-ulOX0clN.js";
4
+ import { r as parseRateLimitWindow } from "./policy-CMsNKnqo.js";
5
5
  import * as v from "valibot";
6
- //#region src/cli.ts
6
+ // src/cli.ts
7
7
  const rateLimitDevTargetErrors = {
8
8
  invalidInlineTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
9
9
  invalidTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
@@ -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,
@@ -265,5 +264,4 @@ function createRateLimitCliContributor(options = {}) {
265
264
  name: "rate-limit"
266
265
  }] };
267
266
  }
268
- //#endregion
269
267
  export { createRateLimitCliContributor, runRateLimitCli };
@@ -1,13 +1,12 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-ulOX0clN.js";
2
2
  import { toResultError } from "@vite-hub/runtime";
3
- //#region ../internal/src/integrations/hex.ts
3
+ // ../internal/src/integrations/hex.ts
4
4
  const textEncoder = new TextEncoder();
5
5
  new TextDecoder();
6
6
  function encodeNameHex(name) {
7
7
  return [...textEncoder.encode(name)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
8
8
  }
9
- //#endregion
10
- //#region src/integrations/cloudflare.ts
9
+ // src/integrations/cloudflare.ts
11
10
  const bindingPrefix = "RATE_LIMIT";
12
11
  function getCloudflareRateLimitBindingName(name) {
13
12
  const encoded = encodeNameHex(name).toUpperCase();
@@ -20,8 +19,7 @@ function getCloudflareRateLimitBindingName(name) {
20
19
  function isCloudflareRateLimitWindow(windowMs) {
21
20
  return windowMs === 1e4 || windowMs === 6e4;
22
21
  }
23
- //#endregion
24
- //#region src/drivers/cloudflare.ts
22
+ // src/drivers/cloudflare.ts
25
23
  function isBinding(value) {
26
24
  return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
27
25
  }
@@ -50,5 +48,4 @@ function cloudflareRateLimitDriver(options) {
50
48
  name: "cloudflare"
51
49
  };
52
50
  }
53
- //#endregion
54
51
  export { getCloudflareRateLimitBindingName as n, isCloudflareRateLimitWindow as r, cloudflareRateLimitDriver as t };
@@ -1,6 +1,5 @@
1
- import { O as RateLimitRuntimeConfig, a as RateLimitCounterScope } from "./types-OzukEqHf.js";
1
+ import { O as RateLimitRuntimeConfig, a as RateLimitCounterScope } from "./types-Bw8vrrVF.js";
2
2
  import { Duration } from "@vite-hub/runtime";
3
- //#region src/counters.d.ts
4
3
  type RateLimitRuntimeDriver = RateLimitRuntimeConfig["driver"];
5
4
  /** Counter of one key for one policy. `peekRateLimit()` reads it without consuming a token. */
6
5
  interface RateLimitCounterSnapshot {
@@ -44,5 +43,4 @@ declare function peekRateLimit(name: string, key: string): Promise<RateLimitPeek
44
43
  * `reset`. The result reports `unsupported` when the configured provider cannot reset counters.
45
44
  */
46
45
  declare function resetRateLimit(name: string, key: string): Promise<RateLimitResetInspection>;
47
- //#endregion
48
46
  export { resetRateLimit as a, peekRateLimit as i, RateLimitPeekInspection as n, RateLimitResetInspection as r, RateLimitCounterSnapshot as t };
@@ -1,11 +1,9 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { i as resolveRateLimitDriver, r as listRuntimeRateLimiters } from "./state-Fq3rGFO3.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-ulOX0clN.js";
2
+ import { i as resolveRateLimitDriver, r as listRuntimeRateLimiters } from "./state-BXD6-GFo.js";
3
3
  import * as v from "valibot";
4
- //#region src/counters.ts
5
- /** Reason that Cloudflare counters are not readable. The binding exposes only `limit({ key })`. */
4
+ // src/counters.ts
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)}`;
@@ -110,5 +108,4 @@ async function resetRateLimit(name, key) {
110
108
  status: "reset"
111
109
  };
112
110
  }
113
- //#endregion
114
111
  export { resetRateLimit as n, peekRateLimit as t };
@@ -1,4 +1,4 @@
1
- //#region ../internal/src/dev-peer.ts
1
+ // ../internal/src/dev-peer.ts
2
2
  /**
3
3
  * Proof that a development request came from this machine, for dev servers that run the app behind a proxy.
4
4
  *
@@ -234,5 +234,4 @@ function addViteHubDevPeerDevHandler(devHandlers) {
234
234
  devHandlers.unshift({ handler: devHandler });
235
235
  }
236
236
  readViteHubDevPeerKey();
237
- //#endregion
238
237
  export { isViteHubLoopbackPeer as n, addViteHubDevPeerDevHandler as t };
@@ -1,8 +1,5 @@
1
- import { c as RateLimitDriver } from "../types-OzukEqHf.js";
2
- //#region src/integrations/cloudflare.d.ts
1
+ import { c as RateLimitDriver } from "../types-Bw8vrrVF.js";
3
2
  export declare function getCloudflareRateLimitBindingName(name: string): string;
4
- //#endregion
5
- //#region src/drivers/cloudflare.d.ts
6
3
  export interface CloudflareRateLimitBinding {
7
4
  limit(input: {
8
5
  key: string;
@@ -13,5 +10,4 @@ export interface CloudflareRateLimitBinding {
13
10
  export interface CloudflareRateLimitDriverOptions {
14
11
  binding: CloudflareRateLimitBinding;
15
12
  }
16
- export declare function cloudflareRateLimitDriver(options: CloudflareRateLimitDriverOptions): RateLimitDriver;
17
- //#endregion
13
+ export declare function cloudflareRateLimitDriver(options: CloudflareRateLimitDriverOptions): RateLimitDriver;
@@ -1,2 +1 @@
1
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-_Tz3DcpB.js";
2
- export { cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
1
+ export { t as cloudflareRateLimitDriver, n as getCloudflareRateLimitBindingName } from "../cloudflare-CWK4wJ9b.js";
@@ -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-DldoJary.js";
2
2
  export { KVRateLimitDriver, KVRateLimitDriverOptions, RateLimitKVStorage, kvRateLimitDriver };
@@ -1,11 +1,10 @@
1
- import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-DRuEG4wu.js";
1
+ import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-ulOX0clN.js";
2
2
  import { toResultError } from "@vite-hub/runtime";
3
- //#region src/drivers/kv.ts
3
+ // src/drivers/kv.ts
4
4
  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;
@@ -127,5 +118,4 @@ function kvRateLimitDriver(options) {
127
118
  }
128
119
  };
129
120
  }
130
- //#endregion
131
121
  export { kvRateLimitDriver };
@@ -1,5 +1,4 @@
1
- import { c as RateLimitDriver } from "../types-OzukEqHf.js";
2
- //#region src/drivers/memory.d.ts
1
+ import { c as RateLimitDriver } from "../types-Bw8vrrVF.js";
3
2
  export interface MemoryRateLimitDriverOptions {
4
3
  maxEntries?: number;
5
4
  now?: () => number;
@@ -11,5 +10,4 @@ export interface MemoryRateLimitDriver extends RateLimitDriver {
11
10
  reset: NonNullable<RateLimitDriver["reset"]>;
12
11
  size: () => number;
13
12
  }
14
- export declare function memoryRateLimitDriver(options?: MemoryRateLimitDriverOptions): MemoryRateLimitDriver;
15
- //#endregion
13
+ export declare function memoryRateLimitDriver(options?: MemoryRateLimitDriverOptions): MemoryRateLimitDriver;
@@ -1,6 +1,13 @@
1
- import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-DRuEG4wu.js";
2
- //#region src/drivers/memory.ts
1
+ import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-ulOX0clN.js";
2
+ // 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
  },
@@ -81,5 +88,4 @@ function memoryRateLimitDriver(options = {}) {
81
88
  }
82
89
  };
83
90
  }
84
- //#endregion
85
91
  export { memoryRateLimitDriver };
@@ -1,5 +1,4 @@
1
1
  import { Durability, DurabilityContext } from "@vite-hub/runtime/durability";
2
- //#region src/durability.d.ts
3
2
  /** What the build passes to `rateLimitDurability()`. */
4
3
  export interface RateLimitDurabilityInput {
5
4
  driver: string;
@@ -8,5 +7,4 @@ export interface RateLimitDurabilityInput {
8
7
  * The durability of Rate Limit counters, from the driver. The `kv` driver counts in the default KV store when that
9
8
  * store is a database, Redis, or Upstash store, and falls back to memory otherwise.
10
9
  */
11
- export declare function rateLimitDurability(input: RateLimitDurabilityInput, context: DurabilityContext): Durability[];
12
- //#endregion
10
+ export declare function rateLimitDurability(input: RateLimitDurabilityInput, context: DurabilityContext): Durability[];
@@ -1,4 +1,4 @@
1
- //#region src/durability.ts
1
+ // src/durability.ts
2
2
  const memory = {
3
3
  primitive: "rate-limit",
4
4
  store: "memory",
@@ -31,5 +31,4 @@ function rateLimitDurability(input, context) {
31
31
  ...kv.fix ? { fix: kv.fix } : {}
32
32
  }];
33
33
  }
34
- //#endregion
35
34
  export { rateLimitDurability };
@@ -1,5 +1,5 @@
1
1
  import { defineDiagnostics } from "nostics";
2
- //#region src/error-diagnostics.ts
2
+ // src/error-diagnostics.ts
3
3
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
4
  const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
5
  docsBase: "https://vitehub.dev/docs/rate-limit/diagnostics",
@@ -234,5 +234,4 @@ const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
234
234
  }
235
235
  }
236
236
  });
237
- //#endregion
238
237
  export { rateLimitErrorDiagnostics as t };
package/dist/index.d.ts CHANGED
@@ -1,10 +1,7 @@
1
- import { A as RefundRateLimitErrorCode, C as RateLimitRefundResult, D as RateLimitResetResult, E as RateLimitRequestEvent, M as ResolvedRateLimitPolicy, O as RateLimitRuntimeConfig, S as RateLimitPolicy, T as RateLimitRequest, _ as RateLimitDriverResult, a as RateLimitCounterScope, b as RateLimitOptions, c as RateLimitDriver, d as RateLimitDriverName, f as RateLimitDriverOutcome, g as RateLimitDriverResetOutcome, h as RateLimitDriverRefundOutcome, i as RateLimitConsumeInput, j as RequireRateLimitOptions, k as RateLimiter, l as RateLimitDriverCapabilities, m as RateLimitDriverPeekResult, n as CheckRateLimitOptions, o as RateLimitDecision, p as RateLimitDriverPeekOutcome, r as CreateRateLimiterOptions, s as RateLimitDeclaration, t as CheckRateLimitErrorCode, u as RateLimitDriverInput, v as RateLimitEnforcement, w as RateLimitRejectedAttemptBehavior, x as RateLimitPeekResult, y as RateLimitFailurePolicy } from "./types-OzukEqHf.js";
2
- import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-d8FaLiE1.js";
1
+ import { A as RefundRateLimitErrorCode, C as RateLimitRefundResult, D as RateLimitResetResult, E as RateLimitRequestEvent, M as ResolvedRateLimitPolicy, O as RateLimitRuntimeConfig, S as RateLimitPolicy, T as RateLimitRequest, _ as RateLimitDriverResult, a as RateLimitCounterScope, b as RateLimitOptions, c as RateLimitDriver, d as RateLimitDriverName, f as RateLimitDriverOutcome, g as RateLimitDriverResetOutcome, h as RateLimitDriverRefundOutcome, i as RateLimitConsumeInput, j as RequireRateLimitOptions, k as RateLimiter, l as RateLimitDriverCapabilities, m as RateLimitDriverPeekResult, n as CheckRateLimitOptions, o as RateLimitDecision, p as RateLimitDriverPeekOutcome, r as CreateRateLimiterOptions, s as RateLimitDeclaration, t as CheckRateLimitErrorCode, u as RateLimitDriverInput, v as RateLimitEnforcement, w as RateLimitRejectedAttemptBehavior, x as RateLimitPeekResult, y as RateLimitFailurePolicy } from "./types-Bw8vrrVF.js";
2
+ import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-BCNUEaDn.js";
3
3
  import { Result } from "@vite-hub/runtime";
4
- //#region src/limiter.d.ts
5
4
  export declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
6
- //#endregion
7
- //#region src/guard.d.ts
8
5
  /**
9
6
  * Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
10
7
  * gets an answer, such as a cheaper fallback. `decision.reason` is `limited` or `unavailable` when not allowed.
@@ -27,5 +24,4 @@ export declare function refundRateLimit(event: RateLimitRequestEvent, name: stri
27
24
  * `checkRateLimit()` returns.
28
25
  */
29
26
  export declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
30
- //#endregion
31
27
  export { type CheckRateLimitErrorCode, type CheckRateLimitOptions, type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitCounterSnapshot, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverName, type RateLimitDriverOutcome, type RateLimitDriverPeekOutcome, type RateLimitDriverPeekResult, type RateLimitDriverRefundOutcome, type RateLimitDriverResetOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitOptions, type RateLimitPeekInspection, type RateLimitPeekResult, type RateLimitPolicy, type RateLimitRefundResult, type RateLimitRejectedAttemptBehavior, type RateLimitRequest, type RateLimitRequestEvent, type RateLimitResetInspection, type RateLimitResetResult, type RateLimitRuntimeConfig, type RateLimiter, type RefundRateLimitErrorCode, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, peekRateLimit, resetRateLimit };
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { a as rateLimitPolicyKeys, n as normalizeRateLimitPolicy, t as declaredRateLimitPolicy } from "./policy-BeyQ0vnc.js";
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";
6
- import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-_Tz3DcpB.js";
1
+ import { n as createRateLimiter } from "./kv-provider-DAq-42o6.js";
2
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-dyc0Q_HL.js";
3
+ import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-CWK4wJ9b.js";
4
+ import { a as rateLimitPolicyKeys, n as normalizeRateLimitPolicy, t as declaredRateLimitPolicy } from "./policy-CMsNKnqo.js";
5
+ import { i as resolveRateLimitDriver, n as getRuntimeRateLimiter } from "./state-BXD6-GFo.js";
6
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-ulOX0clN.js";
7
7
  import { toResultError } from "@vite-hub/runtime";
8
8
  import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
9
9
  import { getStandardContext } from "@vite-hub/runtime/internal/h3";
10
10
  import { createError } from "nitro/h3";
11
- //#region ../internal/src/runtime/cloudflare-env-lookup.ts
11
+ // ../internal/src/runtime/cloudflare-env-lookup.ts
12
12
  /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
13
13
  const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
14
14
  let activeEnv;
@@ -22,8 +22,23 @@ function getActiveCloudflareEnv() {
22
22
  const host = globalThis;
23
23
  return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
24
24
  }
25
- //#endregion
26
- //#region src/guard.ts
25
+ // ../internal/src/runtime/request-log.ts
26
+ function isRequestLog(value) {
27
+ return value !== null && typeof value === "object" && typeof Reflect.get(value, "set") === "function" && typeof Reflect.get(value, "warn") === "function" && typeof Reflect.get(value, "error") === "function";
28
+ }
29
+ function contextLog(value) {
30
+ const context = value !== null && typeof value === "object" ? Reflect.get(value, "context") : void 0;
31
+ return context !== null && typeof context === "object" ? Reflect.get(context, "log") : void 0;
32
+ }
33
+ /**
34
+ * The evlog request logger of a request, or `undefined` when the app does not register evlog. Pass a Nitro v3 event
35
+ * (evlog sets `event.req.context.log`) or its `Request` (`request.context.log`).
36
+ */
37
+ function requestLog(input) {
38
+ const log = contextLog(input !== null && typeof input === "object" ? Reflect.get(input, "req") : void 0) ?? contextLog(input);
39
+ return isRequestLog(log) ? log : void 0;
40
+ }
41
+ // src/guard.ts
27
42
  const guardOptionKeys = {
28
43
  checkRateLimit: /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]),
29
44
  refundRateLimit: /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]),
@@ -46,7 +61,6 @@ function isWebRequest(value) {
46
61
  const headers = Reflect.get(value, "headers");
47
62
  return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObject(headers) && typeof Reflect.get(headers, "get") === "function";
48
63
  }
49
- /** Structural Requests may carry unrelated event-named properties, so identify the event's shape. */
50
64
  function isRequestEvent(input) {
51
65
  if ("~standard" in input) {
52
66
  const standard = input["~standard"];
@@ -69,7 +83,6 @@ function getRequestScope(input) {
69
83
  function getRequestKey(scope, driver) {
70
84
  return driver === "cloudflare" ? scope.headers.get("cf-connecting-ip") || scope.clientAddress : scope.clientAddress;
71
85
  }
72
- /** A failure of one check, such as a request without a key. Option errors throw instead. */
73
86
  function checkError(code, message) {
74
87
  const diagnostic = code === "RATE_LIMIT_R0009" ? rateLimitErrorDiagnostics.RATE_LIMIT_R0009({ message }) : rateLimitErrorDiagnostics.RATE_LIMIT_R0013({ message });
75
88
  return toResultError(diagnostic);
@@ -109,7 +122,18 @@ async function consumeRateLimit(event, name, options, guard) {
109
122
  if (callError) return [callError, void 0];
110
123
  const [error, limiter] = call.counter === "cloudflare" ? getCloudflareRateLimiter(call.scope, call.id, call.policy) : [void 0, getRuntimeRateLimiter(call.counter, call.id, call.policy)];
111
124
  if (error) return [error, void 0];
112
- return [void 0, await limiter.consume({ key: call.key })];
125
+ const decision = await limiter.consume({ key: call.key });
126
+ if (decision.reason) requestLog(event)?.set({ rateLimit: [{
127
+ name: call.id,
128
+ limit: call.policy.limit,
129
+ window: call.policy.window,
130
+ driver: call.counter,
131
+ keySource: options.key === void 0 ? "client-address" : "option",
132
+ allowed: decision.allowed,
133
+ reason: decision.reason,
134
+ ...decision.retryAfter === void 0 ? {} : { retryAfter: decision.retryAfter }
135
+ }] });
136
+ return [void 0, decision];
113
137
  }
114
138
  /**
115
139
  * Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
@@ -168,5 +192,4 @@ async function requireRateLimit(event, name, options) {
168
192
  statusText: "Too Many Requests"
169
193
  });
170
194
  }
171
- //#endregion
172
195
  export { checkRateLimit, createRateLimiter, peekRateLimit, refundRateLimit, requireRateLimit, resetRateLimit };
@@ -1,4 +1,4 @@
1
- //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
1
+ // ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
2
2
  const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
3
3
  function normalizeWindowsPath(input = "") {
4
4
  if (!input) return input;
@@ -95,8 +95,7 @@ const dirname = function(p) {
95
95
  if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
96
96
  return segments.join("/") || (isAbsolute(p) ? "/" : ".");
97
97
  };
98
- //#endregion
99
- //#region ../internal/src/inspect.ts
98
+ // ../internal/src/inspect.ts
100
99
  function relativeDefinitionFile(projectRoot, file) {
101
100
  return relative(projectRoot, file).replaceAll("\\", "/");
102
101
  }
@@ -114,5 +113,4 @@ const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secr
114
113
  function redactInspectionText(value) {
115
114
  return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
116
115
  }
117
- //#endregion
118
116
  export { resolve as i, relativeDefinitionFile as n, dirname as r, redactInspectionText as t };
@@ -1,7 +1,5 @@
1
- import { c as RateLimitDriver } from "./types-OzukEqHf.js";
1
+ import { c as RateLimitDriver } from "./types-Bw8vrrVF.js";
2
2
  import { Result } from "@vite-hub/runtime";
3
- //#region src/drivers/kv.d.ts
4
- /** `[error, data]`, as KV operations return it. */
5
3
  type KVOperationResult<T> = Result<T>;
6
4
  /**
7
5
  * The KV operations that the driver uses. `kv` and `kv.store(name)` from `@vite-hub/kv` match it. `increment` must be
@@ -28,5 +26,4 @@ interface KVRateLimitDriver extends RateLimitDriver {
28
26
  * `refund()` increments a second counter, and `consume()` reads it only when the first counter passes the limit.
29
27
  */
30
28
  declare function kvRateLimitDriver(options: KVRateLimitDriverOptions): KVRateLimitDriver;
31
- //#endregion
32
29
  export { kvRateLimitDriver as i, KVRateLimitDriverOptions as n, RateLimitKVStorage as r, KVRateLimitDriver as t };
@@ -1,8 +1,8 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { n as normalizeRateLimitPolicy } from "./policy-BeyQ0vnc.js";
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-ulOX0clN.js";
2
+ import { n as normalizeRateLimitPolicy } from "./policy-CMsNKnqo.js";
3
3
  import * as v from "valibot";
4
4
  import { Diagnostic } from "nostics";
5
- //#region src/limiter.ts
5
+ // src/limiter.ts
6
6
  const driverErrorSchema = v.custom((value) => {
7
7
  return ("isError" in Error && v.is(v.function(), Error.isError) ? Error.isError(value) === true : v.is(v.instance(Error), value) || v.is(v.object({}), value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null && Object.prototype.toString.call(value) === "[object Error]") && v.is(v.object({
8
8
  message: v.string(),
@@ -254,11 +254,9 @@ function createRateLimiter(options) {
254
254
  }
255
255
  };
256
256
  }
257
- //#endregion
258
- //#region src/internal/kv-provider.ts
257
+ // src/internal/kv-provider.ts
259
258
  /** KV drivers with a shared atomic increment, as required by the KV Rate Limit driver. */
260
259
  function resolveKVRateLimitDriver(driver) {
261
260
  return driver === "database" || driver === "redis" || driver === "upstash" ? "kv" : "memory";
262
261
  }
263
- //#endregion
264
262
  export { createRateLimiter as n, resolveKVRateLimitDriver as t };
@@ -1,4 +1,3 @@
1
- //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
2
1
  /** The Standard Typed interface. This is a base type extended by other specs. */
3
2
  interface StandardTypedV1<Input = unknown, Output = Input> {
4
3
  /** The Standard properties. */
@@ -74,8 +73,6 @@ declare namespace StandardSchemaV1 {
74
73
  /** Infers the output type of a Standard. */
75
74
  type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
75
  }
77
- //#endregion
78
- //#region ../internal/src/operation-definition.d.ts
79
76
  /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
77
  type OperationKind = "read" | "write" | "destructive";
81
78
  /** The signed-in user of a call. */
@@ -104,6 +101,11 @@ interface OperationAccess {
104
101
  */
105
102
  readonly sections: "all" | readonly string[];
106
103
  readonly user?: OperationUser;
104
+ /**
105
+ * Who signed the call: `"console"` when the ViteHub Console signed it for a person, whose `user` is then a Console
106
+ * account and not an app user, or `"cli"` for a key. Not set for other calls.
107
+ */
108
+ readonly via?: "console" | "cli";
107
109
  }
108
110
  interface OperationContext {
109
111
  /** The checked Console access of the call. */
@@ -166,7 +168,8 @@ interface OperationDefinition<Input, Output> {
166
168
  /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
167
169
  input: StandardSchemaV1<unknown, Input>;
168
170
  output?: StandardSchemaV1<unknown, Output>;
169
- cli?: {
171
+ /** `false`: no `vitehub` command. The Console and MCP still call the operation. */
172
+ cli?: false | {
170
173
  /** Defaults: namespace = section, command = verb. */
171
174
  namespace?: string;
172
175
  /** A space groups commands: `jobs list` and `jobs show` run as `vitehub <namespace> jobs list` and `jobs show`. */
@@ -207,7 +210,7 @@ interface OperationDefinition<Input, Output> {
207
210
  /** An operation of any input and output, as a registry holds it. */
208
211
  interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "mcp" | "output" | "readOnlyWhen" | "run" | "scope" | "section"> {
209
212
  readOnlyWhen?: (input: never) => boolean;
210
- cli?: {
213
+ cli?: false | {
211
214
  namespace?: string;
212
215
  command?: string;
213
216
  default?: boolean;
@@ -235,5 +238,4 @@ interface OperationContributionEntry {
235
238
  /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
236
239
  runtime?: false;
237
240
  }
238
- //#endregion
239
241
  export { OperationContributionEntry as n, AnyOperation as t };
@@ -1,8 +1,7 @@
1
- import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
2
- import { n as resetRateLimit, t as peekRateLimit } from "./counters-D4LANMAi.js";
3
- import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
4
- //#region src/runtime/operations.ts
5
- /** Removes credentials from the echoed key and from driver error text before the result leaves the runtime. */
1
+ import { t as redactInspectionText } from "./inspect-Dqvi9vUt.js";
2
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-dyc0Q_HL.js";
3
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-ulOX0clN.js";
4
+ // src/runtime/operations.ts
6
5
  function redact(result) {
7
6
  return {
8
7
  ...result,
@@ -29,5 +28,4 @@ async function peekRateLimitOperation(name, key) {
29
28
  async function resetRateLimitOperation(name, key) {
30
29
  return await guarded(() => resetRateLimit(name, key));
31
30
  }
32
- //#endregion
33
31
  export { peekRateLimitOperation, resetRateLimitOperation };