@vite-hub/rate-limit 0.0.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-wdEMxDEY.js";
2
+ import { t as redactInspectionText } from "./inspect-D-FzyM_x.js";
3
+ //#region src/runtime/operations.ts
4
+ /** A failure with the fields that every surface reports. */
5
+ var RateLimitOperationError = class extends Error {
6
+ status;
7
+ code;
8
+ constructor(message, status, code) {
9
+ super(redactInspectionText(message));
10
+ this.status = status;
11
+ this.code = code;
12
+ }
13
+ };
14
+ /** Removes credentials from the echoed key and from driver error text before the result leaves the runtime. */
15
+ function redact(result) {
16
+ return {
17
+ ...result,
18
+ key: redactInspectionText(result.key),
19
+ ..."reason" in result ? { reason: redactInspectionText(result.reason) } : {}
20
+ };
21
+ }
22
+ async function guarded(run) {
23
+ try {
24
+ return redact(await run());
25
+ } catch (error) {
26
+ throw new RateLimitOperationError(error instanceof Error ? error.message : "The Rate Limit operation failed.", 500, "RATE_LIMIT_OPERATION_FAILED");
27
+ }
28
+ }
29
+ /** Reads the counter of one key without consuming a token. */
30
+ async function peekRateLimitOperation(name, key) {
31
+ return await guarded(() => peekRateLimit(name, key));
32
+ }
33
+ /** Deletes the counter of one key, where the provider supports it. */
34
+ async function resetRateLimitOperation(name, key) {
35
+ return await guarded(() => resetRateLimit(name, key));
36
+ }
37
+ //#endregion
38
+ export { RateLimitOperationError, peekRateLimitOperation, resetRateLimitOperation };
@@ -0,0 +1,212 @@
1
+ //#region ../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
2
+ /** The Standard Typed interface. This is a base type extended by other specs. */
3
+ interface StandardTypedV1<Input = unknown, Output = Input> {
4
+ /** The Standard properties. */
5
+ readonly "~standard": StandardTypedV1.Props<Input, Output>;
6
+ }
7
+ declare namespace StandardTypedV1 {
8
+ /** The Standard Typed properties interface. */
9
+ interface Props<Input = unknown, Output = Input> {
10
+ /** The version number of the standard. */
11
+ readonly version: 1;
12
+ /** The vendor name of the schema library. */
13
+ readonly vendor: string;
14
+ /** Inferred types associated with the schema. */
15
+ readonly types?: Types<Input, Output> | undefined;
16
+ }
17
+ /** The Standard Typed types interface. */
18
+ interface Types<Input = unknown, Output = Input> {
19
+ /** The input type of the schema. */
20
+ readonly input: Input;
21
+ /** The output type of the schema. */
22
+ readonly output: Output;
23
+ }
24
+ /** Infers the input type of a Standard Typed. */
25
+ type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
26
+ /** Infers the output type of a Standard Typed. */
27
+ type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
28
+ }
29
+ /** The Standard Schema interface. */
30
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
31
+ /** The Standard Schema properties. */
32
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
33
+ }
34
+ declare namespace StandardSchemaV1 {
35
+ /** The Standard Schema properties interface. */
36
+ interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
37
+ /** Validates unknown input values. */
38
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
39
+ }
40
+ /** The result interface of the validate function. */
41
+ type Result<Output> = SuccessResult<Output> | FailureResult;
42
+ /** The result interface if validation succeeds. */
43
+ interface SuccessResult<Output> {
44
+ /** The typed output value. */
45
+ readonly value: Output;
46
+ /** A falsy value for `issues` indicates success. */
47
+ readonly issues?: undefined;
48
+ }
49
+ interface Options {
50
+ /** Explicit support for additional vendor-specific parameters, if needed. */
51
+ readonly libraryOptions?: Record<string, unknown> | undefined;
52
+ }
53
+ /** The result interface if validation fails. */
54
+ interface FailureResult {
55
+ /** The issues of failed validation. */
56
+ readonly issues: ReadonlyArray<Issue>;
57
+ }
58
+ /** The issue interface of the failure output. */
59
+ interface Issue {
60
+ /** The error message of the issue. */
61
+ readonly message: string;
62
+ /** The path of the issue, if any. */
63
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
64
+ }
65
+ /** The path segment interface of the issue. */
66
+ interface PathSegment {
67
+ /** The key representing a path segment. */
68
+ readonly key: PropertyKey;
69
+ }
70
+ /** The Standard types interface. */
71
+ interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
72
+ /** Infers the input type of a Standard. */
73
+ type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
74
+ /** Infers the output type of a Standard. */
75
+ type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
76
+ }
77
+ //#endregion
78
+ //#region ../internal/src/operations.d.ts
79
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes. */
80
+ type OperationKind = "read" | "write" | "destructive";
81
+ /** The signed-in user of a call. */
82
+ interface OperationUser {
83
+ id: string;
84
+ name?: string;
85
+ email?: string;
86
+ image?: string;
87
+ [key: string]: unknown;
88
+ }
89
+ /** The Agent Actor when an agent calls through a capability or MCP on behalf of a user. */
90
+ interface OperationActor {
91
+ id: string;
92
+ kind?: string;
93
+ label?: string;
94
+ meta?: object;
95
+ }
96
+ /** The checked Console access of a call. `vite-hub` issues it. `ConsoleAccess` has this shape. */
97
+ interface OperationAccess {
98
+ readonly mode: string;
99
+ /**
100
+ * The sections that the call may use. `"all"` when no section filter applies. An entry is a section id (`"kv"`, every
101
+ * operation of the section) or `"<section>:read"` (only the operations that read).
102
+ */
103
+ readonly sections: "all" | readonly string[];
104
+ readonly user?: OperationUser;
105
+ }
106
+ interface OperationContext {
107
+ /** The checked Console access of the call. */
108
+ access: OperationAccess;
109
+ /** The signed-in user, or null. */
110
+ user: OperationUser | null;
111
+ /** The Agent Actor when an agent calls on behalf of `user`. */
112
+ actor?: OperationActor;
113
+ surface: "console" | "cli" | "mcp" | "agent";
114
+ /** Set by the host from generated build identity, never from request input or runtime NODE_ENV. */
115
+ development?: boolean;
116
+ env?: Record<string, unknown>;
117
+ waitUntil?: (task: Promise<unknown>) => void;
118
+ request?: Request;
119
+ /** Operations set a success status here, such as 202 for an accepted call. */
120
+ response?: {
121
+ status?: number;
122
+ };
123
+ /**
124
+ * An agent or an MCP client may pass `lease: "override"` to `content.save`, `content.remove`, and `content.restore`
125
+ * only when the developer allowed it. Defaults to false, so a model cannot take over a document that a person is editing.
126
+ */
127
+ overrideLeases?: boolean;
128
+ /**
129
+ * What an Agent may read of the Channel conversations, set by `operations({ conversations })`. `participant`: only the
130
+ * threads that the Actor takes part in. `all`: every thread. Unset: none.
131
+ */
132
+ conversations?: "all" | "participant";
133
+ }
134
+ interface OperationDefinition<Input, Output> {
135
+ /** `<section>.<verb>`, such as `content.publish`. Unique per app. */
136
+ name: string;
137
+ /** One sentence. Becomes the CLI help line and the MCP tool description. */
138
+ description: string;
139
+ /**
140
+ * Console section that grants access, such as `content`. `false`: any Console user. A function reads the section
141
+ * from the input, for operations that serve several sections.
142
+ */
143
+ section: string | false | ((input: Input) => string | undefined);
144
+ /** `read` never changes state. `write` changes state. `destructive` deletes or publishes; the CLI asks for `--yes`, MCP marks `destructiveHint`, agents require approval by default. */
145
+ kind: OperationKind;
146
+ /** Standard Schema (valibot in this repo). Its Standard JSON Schema builds CLI flags and the MCP input schema. */
147
+ input: StandardSchemaV1<unknown, Input>;
148
+ output?: StandardSchemaV1<unknown, Output>;
149
+ cli?: {
150
+ /** Defaults: namespace = section, command = verb. */
151
+ namespace?: string;
152
+ command?: string;
153
+ /** Input keys read from positional arguments, in order. */
154
+ positional?: string[];
155
+ /** Human output, written verbatim. Without it the CLI prints JSON. `--json` always prints JSON. */
156
+ format?: (output: Output) => string;
157
+ /** `vitehub <namespace>` runs this command when no command is named, such as `vitehub usage`. */
158
+ default?: boolean;
159
+ /**
160
+ * Route of the app that takes a signed dispatch of this operation, such as `/_vitehub/schedules/run`. With `--url`
161
+ * and a dispatch key in the environment (`VITEHUB_DISPATCH_KEY`), the command signs the input and posts it there, so
162
+ * a CI job needs no Console credentials. Without a key it calls the RPC.
163
+ */
164
+ dispatch?: string;
165
+ };
166
+ /** Largest request body in bytes. It can raise the 64 KiB default but not lower it. */
167
+ maxRequestBytes?: number;
168
+ /**
169
+ * Returns true when this call only reads, such as a dry run of a `destructive` operation. The CLI then skips the
170
+ * confirmation, and agents run it without approval. Without it, every call of a `destructive` operation asks.
171
+ */
172
+ readOnlyWhen?: (input: Input) => boolean;
173
+ /** `false`: MCP does not offer the operation as a tool, such as an editor transport that only the Console uses. */
174
+ mcp?: false;
175
+ /** `false`: the operation never reads `context.user`, so the Console skips the session lookup for it. */
176
+ user?: false;
177
+ /**
178
+ * The operation runs code of the app, such as a workflow, a job, a task, or a schedule. The Console registers it only
179
+ * when `console.invoke` is on, which is the default in development and off in a production build.
180
+ */
181
+ invoke?: true;
182
+ run: (input: Input, context: OperationContext) => Output | Promise<Output>;
183
+ }
184
+ /** An operation of any input and output, as a registry holds it. */
185
+ interface AnyOperation extends Omit<OperationDefinition<unknown, unknown>, "cli" | "input" | "output" | "readOnlyWhen" | "run" | "section"> {
186
+ readOnlyWhen?: (input: never) => boolean;
187
+ cli?: {
188
+ namespace?: string;
189
+ command?: string;
190
+ default?: boolean;
191
+ dispatch?: string;
192
+ positional?: string[];
193
+ format?: (output: never) => string;
194
+ };
195
+ input: StandardSchemaV1;
196
+ output?: StandardSchemaV1;
197
+ run: (input: never, context: OperationContext) => unknown;
198
+ section: string | false | ((input: never) => string | undefined);
199
+ }
200
+ /** The contribution of one plugin: operations, or a module that exports them. */
201
+ interface OperationContributionEntry {
202
+ /** Module the app imports, such as `@vite-hub/content/operations`. */
203
+ module: string;
204
+ /** Named export that holds an operation or an array of operations. Defaults to `default`. */
205
+ export?: string;
206
+ /** Loads the export in the tool process, for a module that the tool cannot resolve by name. */
207
+ load?: () => Promise<unknown>;
208
+ /** `false`: the app already has these operations at runtime. Only tools such as the CLI and `vitehub inspect` read the entry. */
209
+ runtime?: false;
210
+ }
211
+ //#endregion
212
+ export { OperationContributionEntry as n, AnyOperation as t };
@@ -0,0 +1,14 @@
1
+ import { n as RateLimitPeekInspection, r as RateLimitResetInspection } from "./counters-pKORpgGd.js";
2
+ import { t as AnyOperation } from "./operations-tNUdj3G4.js";
3
+ //#region ../internal/src/operations-dev.d.ts
4
+ /** Bundled into owner packages and used only by their serve-only generated Nitro route. */
5
+ export declare function createStandaloneOperationHandler(sources: {
6
+ operations: unknown;
7
+ plugin: string;
8
+ }[], root: string): (event: object) => Promise<Response>;
9
+ //#endregion
10
+ //#region src/operations.d.ts
11
+ /** The `rate-limit.*` operations: peek and reset. The Console, `vitehub rate-limit`, and agents run them. */
12
+ export declare const rateLimitOperations: readonly AnyOperation[];
13
+ //#endregion
14
+ export type { RateLimitPeekInspection, RateLimitResetInspection };
@@ -0,0 +1,244 @@
1
+ import { i as resolveWaitUntil, n as toEventRequest, r as getCloudflareEnv } from "./h3-v1-request-qoGwJr5-.js";
2
+ import { a as defineOperation, d as runOperation, f as toOperationFailure, i as createOperationRegistry, l as operationsOf, o as operationRootHeader, s as operationRpcHeader, t as assertOperationProject, u as projectRootHash } from "./operations-B09NnEjT.js";
3
+ import * as v from "valibot";
4
+ //#region ../internal/src/secret.ts
5
+ const secretEncoder = new TextEncoder();
6
+ /**
7
+ * Compares a request value with an expected secret in constant time for the length of `expected`. Returns `false`
8
+ * when either value is missing or empty. It uses no Node API, so it also runs in Worker runtimes.
9
+ */
10
+ function isViteHubSecretEqual(actual, expected) {
11
+ if (!actual || !expected) return false;
12
+ const left = secretEncoder.encode(actual);
13
+ const right = secretEncoder.encode(expected);
14
+ let difference = left.length ^ right.length;
15
+ for (let index = 0; index < right.length; index += 1) difference |= (left[index] ?? 0) ^ right[index];
16
+ return difference === 0;
17
+ }
18
+ //#endregion
19
+ //#region ../internal/src/dev-endpoint.ts
20
+ const viteHubDevRequestGrantBrand = Symbol("vitehub.devRequestGrant");
21
+ const devRequestGrants = /* @__PURE__ */ new WeakMap();
22
+ function grantDevRequest(request, label) {
23
+ const grant = Object.freeze({
24
+ [viteHubDevRequestGrantBrand]: true,
25
+ label
26
+ });
27
+ devRequestGrants.set(grant, request);
28
+ return { grant };
29
+ }
30
+ function rejectDevRequest(rejection) {
31
+ return { rejection };
32
+ }
33
+ const fileOrExtensionProtocol = /^(?:file|.+-extension):/i;
34
+ const ipv4Octet = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)";
35
+ const ipv4Literal = new RegExp(`^${ipv4Octet}(?:\\.${ipv4Octet}){3}$`);
36
+ /**
37
+ * Tests IP literals like `node:net` `isIP`, without a Node import, so the Nitro-side check also runs in Worker
38
+ * runtimes. IPv4 uses the Node pattern (dotted decimal, no leading zeros). IPv6 uses the WHATWG URL parser, which
39
+ * rejects zone IDs. Browsers do not send zone IDs in `Host`.
40
+ */
41
+ function isIPv4Literal(value) {
42
+ return ipv4Literal.test(value);
43
+ }
44
+ function isIPv6Literal(value) {
45
+ if (!value.includes(":") || !/^[\d.:a-f]+$/i.test(value)) return false;
46
+ try {
47
+ return new URL(`http://[${value}]/`).hostname !== "";
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+ function hostHeaderAllowed(host, allowedHosts) {
53
+ if (fileOrExtensionProtocol.test(host)) return true;
54
+ const trimmed = host.trim();
55
+ if (trimmed.startsWith("[")) {
56
+ const end = trimmed.indexOf("]");
57
+ return end > 0 && isIPv6Literal(trimmed.slice(1, end));
58
+ }
59
+ const colon = trimmed.indexOf(":");
60
+ const hostname = (colon === -1 ? trimmed : trimmed.slice(0, colon)).toLowerCase();
61
+ if (isIPv4Literal(hostname)) return true;
62
+ if (hostname === "localhost" || hostname.endsWith(".localhost")) return true;
63
+ return allowedHosts.some((allowed) => {
64
+ const normalized = allowed.toLowerCase();
65
+ return normalized === hostname || normalized.startsWith(".") && (normalized.slice(1) === hostname || hostname.endsWith(normalized));
66
+ });
67
+ }
68
+ /**
69
+ * Checks the host of a request that reaches the Nitro dev handler.
70
+ *
71
+ * {@link forwardViteHubDevRequestToNitro} always calls `http://localhost`, so a forwarded request passes. The Nitro
72
+ * route is also reachable over HTTP on the dev server, and the Nitro runtime does not know `server.allowedHosts`.
73
+ * This check therefore accepts only `localhost`, `*.localhost`, and IP literals in the request URL and in the `Host`
74
+ * header. A DNS rebinding page uses another host name, so it gets `403`.
75
+ */
76
+ function isViteHubNitroDevHostAllowed(request) {
77
+ const host = request.headers.get("host");
78
+ return hostHeaderAllowed(new URL(request.url).host, []) && (host === null || hostHeaderAllowed(host, []));
79
+ }
80
+ /**
81
+ * Checks a request inside the Nitro dev handler: the host, the guard header, the request origin, `POST`, the JSON
82
+ * content type, and the optional owner `authorize` callback. Returns a grant bound to `request`, or the rejection
83
+ * response. The Nitro route exists only in `vite dev`, but it is reachable on the dev server origin, so it checks the
84
+ * same guard as the Vite endpoint.
85
+ */
86
+ async function validateViteHubNitroDevRequest(request, guard) {
87
+ if (!isViteHubNitroDevHostAllowed(request)) return rejectDevRequest(new Response(`Forbidden ${guard.label} host.`, { status: 403 }));
88
+ if (!isViteHubSecretEqual(request.headers.get(guard.header), guard.headerValue)) return rejectDevRequest(new Response(`Forbidden ${guard.label} request.`, { status: 403 }));
89
+ const origin = request.headers.get("origin");
90
+ if (origin && origin !== new URL(request.url).origin) return rejectDevRequest(new Response(`Forbidden ${guard.label} origin.`, { status: 403 }));
91
+ if (request.method !== "POST") return rejectDevRequest(new Response("Method not allowed.", {
92
+ headers: { allow: "POST" },
93
+ status: 405
94
+ }));
95
+ if (!request.headers.get("content-type")?.toLowerCase().startsWith("application/json")) return rejectDevRequest(new Response(`${guard.label} requests must use application/json.`, { status: 415 }));
96
+ const rejection = await guard.authorize?.(request);
97
+ return rejection ? rejectDevRequest(rejection) : grantDevRequest(request, guard.label);
98
+ }
99
+ //#endregion
100
+ //#region ../internal/src/operations-dev.ts
101
+ function readPath(value, ...path) {
102
+ for (const key of path) value = value !== null && typeof value === "object" ? Reflect.get(value, key) : void 0;
103
+ return value;
104
+ }
105
+ function localHost(host) {
106
+ try {
107
+ const name = new URL(`http://${host}`).hostname;
108
+ return name === "localhost" || name.endsWith(".localhost") || name === "127.0.0.1" || name === "[::1]";
109
+ } catch {
110
+ return false;
111
+ }
112
+ }
113
+ function reject(status, message) {
114
+ throw Object.assign(new Error(message), {
115
+ code: "OPERATION_DEV_REQUEST",
116
+ status
117
+ });
118
+ }
119
+ /** Bundled into owner packages and used only by their serve-only generated Nitro route. */
120
+ function createStandaloneOperationHandler(sources, root) {
121
+ const registry = createOperationRegistry(sources.map((source) => ({
122
+ ...source,
123
+ operations: operationsOf(source.operations)
124
+ })));
125
+ const defaultLimit = 65536;
126
+ const maximum = Math.max(defaultLimit, ...registry.list().map((operation) => operation.maxRequestBytes ?? defaultLimit));
127
+ return async (event) => {
128
+ const headers = {
129
+ "cache-control": "no-store",
130
+ "x-content-type-options": "nosniff",
131
+ [operationRootHeader]: projectRootHash(root)
132
+ };
133
+ try {
134
+ const request = toEventRequest(event);
135
+ const address = [
136
+ readPath(event, "req", "ip"),
137
+ readPath(event, "req", "context", "clientAddress"),
138
+ readPath(event, "req", "runtime", "node", "req", "socket", "remoteAddress"),
139
+ readPath(event, "node", "req", "socket", "remoteAddress")
140
+ ].find((value) => typeof value === "string" && value !== "");
141
+ const forwarded = request.headers.get("x-forwarded-host");
142
+ if (!localHost(request.headers.get("host") ?? new URL(request.url).host) || forwarded && !localHost(forwarded) || address && address !== "::1" && !address.startsWith("127.") && !address.startsWith("::ffff:127.")) reject(403, "Standalone development operations accept only local requests.");
143
+ const site = request.headers.get("sec-fetch-site");
144
+ if (site === "cross-site" || site === "same-site") reject(403, "Cross-origin operation requests are not allowed.");
145
+ const checked = await validateViteHubNitroDevRequest(request, {
146
+ header: operationRpcHeader,
147
+ headerValue: "1",
148
+ label: "Operation RPC"
149
+ });
150
+ if (checked.rejection) reject(checked.rejection.status, await checked.rejection.text());
151
+ assertOperationProject(request, root);
152
+ const reader = request.body?.getReader();
153
+ const decoder = new TextDecoder();
154
+ let text = "";
155
+ let bytes = 0;
156
+ try {
157
+ if (reader) while (true) {
158
+ const chunk = await reader.read();
159
+ if (chunk.done) break;
160
+ bytes += chunk.value.byteLength;
161
+ if (bytes > maximum) reject(413, "Operation request exceeds the byte limit.");
162
+ text += decoder.decode(chunk.value, { stream: true });
163
+ }
164
+ text += decoder.decode();
165
+ } catch (error) {
166
+ await reader?.cancel();
167
+ throw error;
168
+ } finally {
169
+ reader?.releaseLock();
170
+ }
171
+ let payload;
172
+ try {
173
+ payload = JSON.parse(text);
174
+ } catch {
175
+ reject(400, "Malformed operation request.");
176
+ }
177
+ if (!payload || typeof payload !== "object" || !("operation" in payload) || typeof payload.operation !== "string") reject(400, "Invalid operation request.");
178
+ if (bytes > (registry.get(payload.operation)?.maxRequestBytes ?? defaultLimit)) reject(413, "Operation request exceeds the byte limit.");
179
+ const response = {};
180
+ const result = await runOperation(registry, payload.operation, "input" in payload ? payload.input : void 0, {
181
+ access: {
182
+ mode: "local",
183
+ sections: "all"
184
+ },
185
+ development: true,
186
+ surface: "cli",
187
+ user: null,
188
+ request,
189
+ response,
190
+ env: getCloudflareEnv(event, { fallback: false }),
191
+ waitUntil: resolveWaitUntil(event, { preferHost: true })
192
+ });
193
+ return Response.json(result, {
194
+ headers,
195
+ status: result.ok ? response.status ?? 200 : result.status
196
+ });
197
+ } catch (error) {
198
+ const failure = toOperationFailure(error);
199
+ return Response.json({
200
+ ok: false,
201
+ ...failure
202
+ }, {
203
+ headers,
204
+ status: failure.status
205
+ });
206
+ }
207
+ };
208
+ }
209
+ //#endregion
210
+ //#region src/operations.ts
211
+ const runtime = () => import("./operations-Bu-xulNd.js");
212
+ const target = v.object({
213
+ key: v.pipe(v.string(), v.minLength(1, "Name the limited key, for example a client IP or user ID.")),
214
+ name: v.pipe(v.string(), v.check((name) => name.trim() !== "", "Name the stable ID of `requireRateLimit()`."))
215
+ });
216
+ function defineRateLimitOperation(definition) {
217
+ return defineOperation({
218
+ ...definition,
219
+ cli: {
220
+ namespace: "rate-limit",
221
+ ...definition.cli
222
+ },
223
+ section: "rate-limits",
224
+ user: false
225
+ });
226
+ }
227
+ /** The `rate-limit.*` operations: peek and reset. The Console, `vitehub rate-limit`, and agents run them. */
228
+ const rateLimitOperations = [defineRateLimitOperation({
229
+ cli: { positional: ["name", "key"] },
230
+ description: "Show the counter of one key without consuming a token.",
231
+ input: target,
232
+ kind: "read",
233
+ name: "rate-limit.peek",
234
+ run: async (input) => await (await runtime()).peekRateLimitOperation(input.name, input.key)
235
+ }), defineRateLimitOperation({
236
+ cli: { positional: ["name", "key"] },
237
+ description: "Delete the counter of one key, where the provider supports it.",
238
+ input: target,
239
+ kind: "destructive",
240
+ name: "rate-limit.reset",
241
+ run: async (input) => await (await runtime()).resetRateLimitOperation(input.name, input.key)
242
+ })];
243
+ //#endregion
244
+ export { createStandaloneOperationHandler, rateLimitOperations };
package/dist/runtime.d.ts CHANGED
@@ -1,7 +1,5 @@
1
- import { v as RateLimitRuntimeConfig } from "./types-DoyUiUt1.js";
2
-
1
+ import { C as RateLimitRuntimeConfig } from "./types-CQEJpgtz.js";
3
2
  //#region src/runtime/state.d.ts
4
- declare function setRateLimitRuntimeConfig(config: RateLimitRuntimeConfig): void;
5
- declare function getRateLimitRuntimeConfig(): RateLimitRuntimeConfig;
6
- //#endregion
7
- export { getRateLimitRuntimeConfig, setRateLimitRuntimeConfig };
3
+ export declare function setRateLimitRuntimeConfig(config: RateLimitRuntimeConfig): void;
4
+ export declare function getRateLimitRuntimeConfig(): RateLimitRuntimeConfig;
5
+ //#endregion
package/dist/runtime.js CHANGED
@@ -1,2 +1,2 @@
1
- import { n as getRateLimitRuntimeConfig, r as setRateLimitRuntimeConfig } from "./state-DB4uJN5P.js";
1
+ import { i as setRateLimitRuntimeConfig, n as getRateLimitRuntimeConfig } from "./state-Ct7zR8fD.js";
2
2
  export { getRateLimitRuntimeConfig, setRateLimitRuntimeConfig };
@@ -0,0 +1,43 @@
1
+ import { r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-DBrMI4vi.js";
2
+ import { memoryRateLimitDriver } from "./drivers/memory.js";
3
+ //#region src/runtime/state.ts
4
+ let runtimeConfig = { provider: "memory" };
5
+ const memoryLimiters = /* @__PURE__ */ new Map();
6
+ function setRateLimitRuntimeConfig(config) {
7
+ runtimeConfig = config;
8
+ memoryLimiters.clear();
9
+ }
10
+ function getRateLimitRuntimeConfig() {
11
+ return runtimeConfig;
12
+ }
13
+ function normalizeRateLimitWindowKey(policy) {
14
+ return normalizeRateLimitPolicy(policy).windowMs;
15
+ }
16
+ function getMemoryRateLimiter(name, policy) {
17
+ let policies = memoryLimiters.get(name);
18
+ const policyKey = JSON.stringify([
19
+ policy.enforcement,
20
+ policy.failure,
21
+ policy.limit,
22
+ normalizeRateLimitWindowKey(policy)
23
+ ]);
24
+ const existing = policies?.get(policyKey);
25
+ if (existing) return existing;
26
+ const limiter = createRateLimiter({
27
+ ...policy,
28
+ driver: memoryRateLimitDriver(),
29
+ name
30
+ });
31
+ if (!policies) {
32
+ policies = /* @__PURE__ */ new Map();
33
+ memoryLimiters.set(name, policies);
34
+ }
35
+ policies.set(policyKey, limiter);
36
+ return limiter;
37
+ }
38
+ /** Lists each policy used by this name in the current runtime configuration. */
39
+ function listMemoryRateLimiters(name) {
40
+ return [...memoryLimiters.get(name)?.values() ?? []];
41
+ }
42
+ //#endregion
43
+ export { setRateLimitRuntimeConfig as i, getRateLimitRuntimeConfig as n, listMemoryRateLimiters as r, getMemoryRateLimiter as t };
@@ -14,13 +14,20 @@ interface RateLimitPolicy {
14
14
  interface RequireRateLimitOptions extends RateLimitPolicy {
15
15
  key?: string;
16
16
  }
17
- interface RateLimitRequestEvent {
17
+ /** A server request event: an H3 2 event, as in Nitro 3, or an H3 1 event, as in Nuxt 4. */
18
+ type RateLimitRequestEvent = {
18
19
  readonly req: {
19
20
  readonly headers: {
20
21
  get: (name: string) => string | null;
21
22
  };
22
23
  };
23
- }
24
+ } | {
25
+ readonly node: {
26
+ readonly req: {
27
+ readonly headers: Readonly<Record<string, string | string[] | undefined>>;
28
+ };
29
+ };
30
+ };
24
31
  interface ResolvedRateLimitPolicy {
25
32
  readonly enforcement: RateLimitEnforcement;
26
33
  readonly failure: RateLimitFailurePolicy;
@@ -39,6 +46,7 @@ interface RateLimitDriverInput extends RateLimitConsumeInput {
39
46
  interface RateLimitDriverResult {
40
47
  allowed: boolean;
41
48
  remaining?: number;
49
+ /** Positive Unix timestamp in milliseconds, at most `8.64e15`. */
42
50
  resetAt?: number;
43
51
  retryAfter?: number;
44
52
  used?: number;
@@ -69,15 +77,61 @@ interface RateLimitDriverCapabilities {
69
77
  readonly scope: RateLimitCounterScope;
70
78
  readonly windows?: readonly number[];
71
79
  }
80
+ /** Counter state that a driver reads without consuming a token. */
81
+ interface RateLimitDriverPeekResult {
82
+ /** Positive window-end timestamp in milliseconds, at most `8.64e15`. Omit it when no counter is active. */
83
+ resetAt?: number;
84
+ /** Tokens consumed in the current window. `0` when the key has no active counter. */
85
+ used: number;
86
+ }
87
+ type RateLimitDriverPeekOutcome = [error: null, value: RateLimitDriverPeekResult] | [error: Error, value: undefined];
88
+ type RateLimitDriverResetOutcome = [error: Error | null];
72
89
  interface RateLimitDriver {
73
90
  capabilities: RateLimitDriverCapabilities;
74
91
  consume: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverOutcome>;
75
92
  name: string;
93
+ /**
94
+ * Reads the counter of a key without consuming a token. Omit it when the provider cannot read a counter. The
95
+ * Rate Limiter then reports `unsupported`.
96
+ */
97
+ peek?: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverPeekOutcome>;
98
+ /** Deletes the counter of a key. Omit it when the provider cannot reset a counter. */
99
+ reset?: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverResetOutcome>;
100
+ }
101
+ interface RateLimitPeekBase {
102
+ limit: number;
103
+ windowMs: number;
76
104
  }
105
+ /** Counter state of one key. `peek()` does not consume a token. */
106
+ type RateLimitPeekResult = (RateLimitPeekBase & {
107
+ remaining: number;
108
+ resetAt?: number;
109
+ status: "known";
110
+ used: number;
111
+ }) | (RateLimitPeekBase & {
112
+ reason: string;
113
+ status: "unsupported";
114
+ }) | (RateLimitPeekBase & {
115
+ cause: unknown;
116
+ status: "unavailable";
117
+ });
118
+ type RateLimitResetResult = {
119
+ status: "reset";
120
+ } | {
121
+ reason: string;
122
+ status: "unsupported";
123
+ } | {
124
+ cause: unknown;
125
+ status: "unavailable";
126
+ };
77
127
  interface RateLimiter {
78
128
  readonly capabilities: RateLimitDriverCapabilities;
79
129
  consume: (input: RateLimitConsumeInput) => Promise<RateLimitDecision>;
130
+ /** Reads the counter of a key without consuming a token. */
131
+ peek: (input: RateLimitConsumeInput) => Promise<RateLimitPeekResult>;
80
132
  policy: ResolvedRateLimitPolicy;
133
+ /** Deletes the counter of a key, so the next request starts a new window. */
134
+ reset: (input: RateLimitConsumeInput) => Promise<RateLimitResetResult>;
81
135
  }
82
136
  interface RateLimitDeclaration {
83
137
  name: string;
@@ -103,4 +157,4 @@ interface RateLimitRuntimeConfig {
103
157
  provider: Exclude<RateLimitProvider, "auto">;
104
158
  }
105
159
  //#endregion
106
- export { ResolvedRateLimitPolicy as S, RateLimitRequestEvent as _, RateLimitDeclaration as a, RateLimiter as b, RateLimitDriverInput as c, RateLimitEnforcement as d, RateLimitFailurePolicy as f, RateLimitRejectedAttemptBehavior as g, RateLimitProvider as h, RateLimitDecision as i, RateLimitDriverOutcome as l, RateLimitPolicy as m, RateLimitConsumeInput as n, RateLimitDriver as o, RateLimitModuleOptions as p, RateLimitCounterScope as r, RateLimitDriverCapabilities as s, CreateRateLimiterOptions as t, RateLimitDriverResult as u, RateLimitRuntimeConfig as v, RequireRateLimitOptions as x, RateLimitWindow as y };
160
+ export { RateLimitRuntimeConfig as C, ResolvedRateLimitPolicy as D, RequireRateLimitOptions as E, RateLimitResetResult as S, RateLimiter as T, RateLimitPeekResult as _, RateLimitDeclaration as a, RateLimitRejectedAttemptBehavior as b, RateLimitDriverInput as c, RateLimitDriverPeekResult as d, RateLimitDriverResetOutcome as f, RateLimitModuleOptions as g, RateLimitFailurePolicy as h, RateLimitDecision as i, RateLimitDriverOutcome as l, RateLimitEnforcement as m, RateLimitConsumeInput as n, RateLimitDriver as o, RateLimitDriverResult as p, RateLimitCounterScope as r, RateLimitDriverCapabilities as s, CreateRateLimiterOptions as t, RateLimitDriverPeekOutcome as u, RateLimitPolicy as v, RateLimitWindow as w, RateLimitRequestEvent as x, RateLimitProvider as y };