@vite-hub/rate-limit 0.0.3 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,273 @@
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
2
+ import { t as redactInspectionText } from "./inspect-D-FzyM_x.js";
3
+ import { n as callOperationFromCli, y as readViteHubDevTargetOption } from "./operations-B09NnEjT.js";
4
+ import * as v from "valibot";
5
+ import { createInterface } from "node:readline/promises";
6
+ //#region src/cli.ts
7
+ const rateLimitDevTargetErrors = {
8
+ invalidInlineTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
9
+ invalidTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
10
+ missingValue: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message })
11
+ };
12
+ const rateLimitCommands = [{
13
+ description: "Show the counter of one key without consuming a token.",
14
+ name: "peek"
15
+ }, {
16
+ description: "Delete the counter of one key, where the provider supports it.",
17
+ name: "reset"
18
+ }];
19
+ function commandUsage(command) {
20
+ return `vitehub rate-limit ${command.name} <id> <key> [--json]${command.name === "reset" ? " [--yes]" : ""} [--url <url>]`;
21
+ }
22
+ function writeUsage(command, stream) {
23
+ stream.write([
24
+ `Usage: ${commandUsage(command)}`,
25
+ "",
26
+ command.description,
27
+ "The command runs the rate-limit operation of the app: on the dev server of this project, or on a deployed app with --url.",
28
+ "`<id>` is the stable ID of `requireRateLimit()`. `<key>` is the limited key, for example a client IP or user ID.",
29
+ "",
30
+ "Use -- before a key that starts with a dash.",
31
+ "",
32
+ "Options:",
33
+ ...command.name === "reset" ? [" --yes, -y Reset without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
34
+ " --json Print JSON.",
35
+ " --url <url> Deployed app URL. Credentials come from VITEHUB_CONSOLE_AUTHORIZATION, VITEHUB_CONSOLE_COOKIE, or CF_ACCESS_*. Defaults to the dev server of this project.",
36
+ " --timeout <ms> Request timeout.",
37
+ " -h, --help Show this help.",
38
+ ""
39
+ ].join("\n"));
40
+ }
41
+ function parseArgs(args) {
42
+ const parsed = {
43
+ help: false,
44
+ json: false,
45
+ yes: false
46
+ };
47
+ let positionalOnly = false;
48
+ for (let index = 0; index < args.length; index += 1) {
49
+ const arg = args[index];
50
+ if (!positionalOnly && arg === "--") {
51
+ positionalOnly = true;
52
+ continue;
53
+ }
54
+ if (!positionalOnly && (arg === "-h" || arg === "--help")) {
55
+ parsed.help = true;
56
+ continue;
57
+ }
58
+ if (!positionalOnly && (arg === "--yes" || arg === "-y")) {
59
+ parsed.yes = true;
60
+ continue;
61
+ }
62
+ if (!positionalOnly && arg === "--json") {
63
+ parsed.json = true;
64
+ continue;
65
+ }
66
+ const targetOption = positionalOnly ? void 0 : readViteHubDevTargetOption(args, index, parsed, rateLimitDevTargetErrors);
67
+ if (targetOption !== void 0) {
68
+ index += targetOption;
69
+ continue;
70
+ }
71
+ if (!positionalOnly && arg.startsWith("-")) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: `Unknown option: ${arg}.` });
72
+ if (parsed.name === void 0) {
73
+ parsed.name = arg;
74
+ continue;
75
+ }
76
+ if (parsed.key === void 0) {
77
+ parsed.key = arg;
78
+ continue;
79
+ }
80
+ throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: `Unexpected argument: ${arg}.` });
81
+ }
82
+ if (!parsed.help && !parsed.name) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: "Missing Rate Limit ID." });
83
+ if (!parsed.help && !parsed.key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: "Missing Rate Limit key." });
84
+ return parsed;
85
+ }
86
+ function table(rows) {
87
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
88
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" ")).join("\n");
89
+ }
90
+ function scopeNotice(scope) {
91
+ return scope === "process" ? "Scope: process. The counter exists only in this server process." : `Scope: ${scope}.`;
92
+ }
93
+ function formatPeek(result) {
94
+ const header = `Rate Limit ${result.name}, key ${result.key}\nProvider: ${result.provider}\n`;
95
+ if (result.status !== "known") return `${header}${result.status === "unused" ? "No counter" : "Counter unknown"}: ${result.reason}\n`;
96
+ return `${header}${scopeNotice(result.scope)}\n${table([[
97
+ "LIMIT",
98
+ "WINDOW",
99
+ "USED",
100
+ "REMAINING",
101
+ "RESETS AT"
102
+ ], ...result.counters.map((counter) => [
103
+ String(counter.limit),
104
+ counter.window,
105
+ String(counter.used),
106
+ String(counter.remaining),
107
+ counter.resetAt === void 0 ? "-" : new Date(counter.resetAt).toISOString()
108
+ ])])}\n`;
109
+ }
110
+ function formatReset(result) {
111
+ if (result.status !== "reset") return `Rate Limit ${result.name}, key ${result.key}\nProvider: ${result.provider}\nNot reset: ${result.reason}\n`;
112
+ return `Reset Rate Limit ${result.name} for key ${result.key}.\nProvider: ${result.provider}\n${scopeNotice(result.scope)}\n`;
113
+ }
114
+ const windowSchema = v.custom((value) => v.is(v.pipe(v.string(), v.regex(/^\d+(?:\.\d+)?(?:ms|s|m|h|d)$/)), value));
115
+ const finiteNumber = v.pipe(v.number(), v.finite());
116
+ const targetFields = {
117
+ key: v.string(),
118
+ name: v.string(),
119
+ provider: v.picklist(["memory", "cloudflare"])
120
+ };
121
+ const scopeSchema = v.picklist([
122
+ "global",
123
+ "location",
124
+ "process"
125
+ ]);
126
+ const counterSchema = v.object({
127
+ limit: finiteNumber,
128
+ remaining: finiteNumber,
129
+ resetAt: v.optional(v.pipe(finiteNumber, v.minValue(-864e13), v.maxValue(864e13))),
130
+ used: finiteNumber,
131
+ window: windowSchema,
132
+ windowMs: finiteNumber
133
+ });
134
+ const unavailableSchema = v.object({
135
+ ...targetFields,
136
+ reason: v.string(),
137
+ status: v.literal("unavailable")
138
+ });
139
+ const unsupportedSchema = v.object({
140
+ ...targetFields,
141
+ reason: v.string(),
142
+ status: v.literal("unsupported")
143
+ });
144
+ const peekSchema = v.variant("status", [
145
+ v.object({
146
+ ...targetFields,
147
+ counters: v.array(counterSchema),
148
+ scope: scopeSchema,
149
+ status: v.literal("known")
150
+ }),
151
+ v.object({
152
+ ...targetFields,
153
+ reason: v.string(),
154
+ status: v.literal("unused")
155
+ }),
156
+ unavailableSchema,
157
+ unsupportedSchema
158
+ ]);
159
+ const resetSchema = v.variant("status", [
160
+ v.object({
161
+ ...targetFields,
162
+ scope: scopeSchema,
163
+ status: v.literal("reset")
164
+ }),
165
+ unavailableSchema,
166
+ unsupportedSchema
167
+ ]);
168
+ function parseInspection(operation, value) {
169
+ if (operation === "peek") {
170
+ const parsed = v.safeParse(peekSchema, value);
171
+ return parsed.success ? {
172
+ operation,
173
+ value: parsed.output
174
+ } : void 0;
175
+ }
176
+ const parsed = v.safeParse(resetSchema, value);
177
+ return parsed.success ? {
178
+ operation,
179
+ value: parsed.output
180
+ } : void 0;
181
+ }
182
+ function writeFailure(parsed, context, failure) {
183
+ const message = redactInspectionText(failure.message);
184
+ if (parsed.json) context.stdout.write(`${JSON.stringify({ error: {
185
+ ...failure,
186
+ message
187
+ } }, null, 2)}\n`);
188
+ else context.stderr.write(`${message}${failure.fix ? `\n${failure.fix}` : ""}\n`);
189
+ return 1;
190
+ }
191
+ async function askOnTerminal(question) {
192
+ const terminal = createInterface({
193
+ input: process.stdin,
194
+ output: process.stderr
195
+ });
196
+ try {
197
+ return /^y(es)?$/i.test((await terminal.question(question)).trim());
198
+ } finally {
199
+ terminal.close();
200
+ }
201
+ }
202
+ async function runRateLimitCommand(command, args, context, options) {
203
+ let parsed;
204
+ try {
205
+ parsed = parseArgs(args);
206
+ } catch (error) {
207
+ const terminator = args.indexOf("--");
208
+ if (args.slice(0, terminator < 0 ? args.length : terminator).includes("--json")) return writeFailure({ json: true }, context, { message: error instanceof Error ? error.message : String(error) });
209
+ writeFailure({ json: false }, context, { message: error instanceof Error ? error.message : String(error) });
210
+ writeUsage(command, context.stderr);
211
+ return 1;
212
+ }
213
+ if (parsed.help) {
214
+ writeUsage(command, context.stdout);
215
+ return 0;
216
+ }
217
+ if (command.name === "reset" && !parsed.yes) {
218
+ const question = `Reset the Rate Limit ${parsed.name} for key ${redactInspectionText(parsed.key)}? The next request starts a new window. [y/N] `;
219
+ if (!(options.confirm ? await options.confirm(question) : process.stdin.isTTY && process.stderr.isTTY ? await askOnTerminal(question) : false)) return writeFailure(parsed, context, {
220
+ code: "RATE_LIMIT_NOT_CONFIRMED",
221
+ fix: "Run it again with --yes.",
222
+ message: "rate-limit reset deletes a counter and was not confirmed."
223
+ });
224
+ }
225
+ const called = await callOperationFromCli({
226
+ env: context.env,
227
+ fetch: context.fetch ?? options.fetch ?? globalThis.fetch,
228
+ rootDir: context.rootDir,
229
+ ...parsed.timeout ? { timeout: parsed.timeout } : {},
230
+ ...parsed.url ? { url: parsed.url } : {}
231
+ }, `rate-limit.${command.name}`, {
232
+ key: parsed.key,
233
+ name: parsed.name
234
+ });
235
+ if (!called.ok) return writeFailure(parsed, context, {
236
+ code: called.code,
237
+ message: called.message,
238
+ ...called.fix ? { fix: called.fix } : {}
239
+ });
240
+ const result = parseInspection(command.name, called.value);
241
+ if (!result) return writeFailure(parsed, context, { message: "The rate-limit operation answered with an invalid result." });
242
+ const output = result.operation === "peek" ? formatPeek(result.value) : formatReset(result.value);
243
+ context.stdout.write(parsed.json ? `${JSON.stringify(result.value, null, 2)}\n` : output);
244
+ return result.value.status === "unsupported" || result.value.status === "unavailable" ? 1 : 0;
245
+ }
246
+ /**
247
+ * Runs one `vitehub rate-limit` command through the `rate-limit.*` operations, on the dev server of this project or on a
248
+ * deployed app with `--url`.
249
+ * `args[0]` is the command name, `peek` or `reset`.
250
+ */
251
+ async function runRateLimitCli(args, context, options = {}) {
252
+ const [name, ...rest] = args;
253
+ const command = rateLimitCommands.find((entry) => entry.name === name);
254
+ if (!command) {
255
+ context.stderr.write(`${name ? `Unknown rate-limit command: ${redactInspectionText(name)}\n` : ""}Commands: ${rateLimitCommands.map((entry) => entry.name).join(", ")}\n`);
256
+ return 1;
257
+ }
258
+ return await runRateLimitCommand(command, rest, context, options);
259
+ }
260
+ function createRateLimitCliContributor(options = {}) {
261
+ return { namespaces: [{
262
+ description: "Read and reset Rate Limit counters in the running app.",
263
+ features: rateLimitCommands.map((command) => ({
264
+ description: command.description,
265
+ name: command.name,
266
+ run: async (args, context) => await runRateLimitCommand(command, args, context, options),
267
+ usage: commandUsage(command)
268
+ })),
269
+ name: "rate-limit"
270
+ }] };
271
+ }
272
+ //#endregion
273
+ export { createRateLimitCliContributor, runRateLimitCli };
@@ -1,3 +1,4 @@
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
1
2
  //#region ../internal/src/integrations/hex.ts
2
3
  const textEncoder = new TextEncoder();
3
4
  new TextDecoder();
@@ -17,7 +18,7 @@ function isBinding(value) {
17
18
  return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
18
19
  }
19
20
  function cloudflareRateLimitDriver(options) {
20
- if (!isBinding(options?.binding)) throw new TypeError("[vitehub] cloudflareRateLimitDriver() requires a Cloudflare Rate Limit binding.");
21
+ if (!isBinding(options?.binding)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0004({ message: "[vitehub] cloudflareRateLimitDriver() requires a Cloudflare Rate Limit binding." });
21
22
  return {
22
23
  capabilities: {
23
24
  enforcement: "best-effort",
@@ -30,9 +31,12 @@ function cloudflareRateLimitDriver(options) {
30
31
  try {
31
32
  result = await options.binding.limit({ key: input.key });
32
33
  } catch (cause) {
33
- return [new Error("[vitehub] Cloudflare Rate Limit binding failed.", { cause }), void 0];
34
+ return [rateLimitErrorDiagnostics.RATE_LIMIT_R0005({
35
+ message: "[vitehub] Cloudflare Rate Limit binding failed.",
36
+ cause
37
+ }), void 0];
34
38
  }
35
- if (!result || typeof result.success !== "boolean") throw new TypeError("[vitehub] Cloudflare Rate Limit binding returned an invalid result.");
39
+ if (!result || typeof result.success !== "boolean") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0006({ message: "[vitehub] Cloudflare Rate Limit binding returned an invalid result." });
36
40
  return [null, { allowed: result.success }];
37
41
  },
38
42
  name: "cloudflare"
@@ -0,0 +1,47 @@
1
+ import { C as RateLimitRuntimeConfig, r as RateLimitCounterScope, w as RateLimitWindow } from "./types-CQEJpgtz.js";
2
+ //#region src/counters.d.ts
3
+ type RateLimitRuntimeProvider = RateLimitRuntimeConfig["provider"];
4
+ /** Counter of one key for one policy. `peekRateLimit()` reads it without consuming a token. */
5
+ interface RateLimitCounterSnapshot {
6
+ limit: number;
7
+ remaining: number;
8
+ /** End of the current window in epoch milliseconds. Absent when the key has no active counter. */
9
+ resetAt?: number;
10
+ used: number;
11
+ window: RateLimitWindow;
12
+ windowMs: number;
13
+ }
14
+ interface RateLimitCounterTarget {
15
+ key: string;
16
+ name: string;
17
+ provider: RateLimitRuntimeProvider;
18
+ }
19
+ type RateLimitPeekInspection = (RateLimitCounterTarget & {
20
+ /** One entry for each policy that requests used with this name. Usually one. */
21
+ counters: RateLimitCounterSnapshot[];
22
+ /** Where the counter lives. A `process` counter exists only in the current server process. */
23
+ scope: RateLimitCounterScope;
24
+ status: "known";
25
+ }) | (RateLimitCounterTarget & {
26
+ reason: string;
27
+ status: "unavailable" | "unsupported" | "unused";
28
+ });
29
+ type RateLimitResetInspection = (RateLimitCounterTarget & {
30
+ scope: RateLimitCounterScope;
31
+ status: "reset";
32
+ }) | (RateLimitCounterTarget & {
33
+ reason: string;
34
+ status: "unavailable" | "unsupported";
35
+ });
36
+ /**
37
+ * Reads the counter of one key without consuming a token. The result reports `unsupported` when the configured
38
+ * provider cannot read counters, and `unused` when no request used the Rate Limit in this process.
39
+ */
40
+ declare function peekRateLimit(name: string, key: string): Promise<RateLimitPeekInspection>;
41
+ /**
42
+ * Deletes the counter of one key, so the next request starts a new window. A key without a counter also returns
43
+ * `reset`. The result reports `unsupported` when the configured provider cannot reset counters.
44
+ */
45
+ declare function resetRateLimit(name: string, key: string): Promise<RateLimitResetInspection>;
46
+ //#endregion
47
+ export { resetRateLimit as a, peekRateLimit as i, RateLimitPeekInspection as n, RateLimitResetInspection as r, RateLimitCounterSnapshot as t };
@@ -0,0 +1,106 @@
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-CTAC_bbr.js";
2
+ import { n as getRateLimitRuntimeConfig, r as listMemoryRateLimiters } from "./state-Ct7zR8fD.js";
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 })`. */
6
+ const cloudflareRateLimitCounterUnsupportedReason = "The Cloudflare Rate Limiting binding exposes only limit(), which consumes a token. It cannot read or reset a counter.";
7
+ const unusedReason = "No request used this Rate Limit in this process since it started, so no counter exists.";
8
+ function unavailableReason(cause) {
9
+ return `The Rate Limit driver failed: ${cause instanceof Error ? cause.message : String(cause)}`;
10
+ }
11
+ function assertTarget(name, key) {
12
+ if (!v.is(v.string(), name) || !name.trim()) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0039({ message: "[vitehub] Rate Limit name must be a non-empty string." });
13
+ if (!v.is(v.string(), key) || !key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0039({ message: "[vitehub] Rate Limit key must be a non-empty string." });
14
+ }
15
+ function limitersFor(target) {
16
+ return target.provider === "memory" ? listMemoryRateLimiters(target.name) : void 0;
17
+ }
18
+ /**
19
+ * Reads the counter of one key without consuming a token. The result reports `unsupported` when the configured
20
+ * provider cannot read counters, and `unused` when no request used the Rate Limit in this process.
21
+ */
22
+ async function peekRateLimit(name, key) {
23
+ assertTarget(name, key);
24
+ const target = {
25
+ key,
26
+ name: name.trim(),
27
+ provider: getRateLimitRuntimeConfig().provider
28
+ };
29
+ const limiters = limitersFor(target);
30
+ if (!limiters) return {
31
+ ...target,
32
+ reason: cloudflareRateLimitCounterUnsupportedReason,
33
+ status: "unsupported"
34
+ };
35
+ if (limiters.length === 0) return {
36
+ ...target,
37
+ reason: unusedReason,
38
+ status: "unused"
39
+ };
40
+ const counters = [];
41
+ for (const limiter of limiters) {
42
+ const result = await limiter.peek({ key });
43
+ if (result.status === "unsupported") return {
44
+ ...target,
45
+ reason: result.reason,
46
+ status: "unsupported"
47
+ };
48
+ if (result.status === "unavailable") return {
49
+ ...target,
50
+ reason: unavailableReason(result.cause),
51
+ status: "unavailable"
52
+ };
53
+ counters.push({
54
+ limit: result.limit,
55
+ remaining: result.remaining,
56
+ ...result.resetAt === void 0 ? {} : { resetAt: result.resetAt },
57
+ used: result.used,
58
+ window: limiter.policy.window,
59
+ windowMs: result.windowMs
60
+ });
61
+ }
62
+ return {
63
+ ...target,
64
+ counters,
65
+ scope: limiters[0].capabilities.scope,
66
+ status: "known"
67
+ };
68
+ }
69
+ /**
70
+ * Deletes the counter of one key, so the next request starts a new window. A key without a counter also returns
71
+ * `reset`. The result reports `unsupported` when the configured provider cannot reset counters.
72
+ */
73
+ async function resetRateLimit(name, key) {
74
+ assertTarget(name, key);
75
+ const target = {
76
+ key,
77
+ name: name.trim(),
78
+ provider: getRateLimitRuntimeConfig().provider
79
+ };
80
+ const limiters = limitersFor(target);
81
+ if (!limiters) return {
82
+ ...target,
83
+ reason: cloudflareRateLimitCounterUnsupportedReason,
84
+ status: "unsupported"
85
+ };
86
+ for (const limiter of limiters) {
87
+ const result = await limiter.reset({ key });
88
+ if (result.status === "unsupported") return {
89
+ ...target,
90
+ reason: result.reason,
91
+ status: "unsupported"
92
+ };
93
+ if (result.status === "unavailable") return {
94
+ ...target,
95
+ reason: unavailableReason(result.cause),
96
+ status: "unavailable"
97
+ };
98
+ }
99
+ return {
100
+ ...target,
101
+ scope: limiters[0]?.capabilities.scope ?? "process",
102
+ status: "reset"
103
+ };
104
+ }
105
+ //#endregion
106
+ export { resetRateLimit as n, peekRateLimit as t };
@@ -1,19 +1,17 @@
1
- import { a as RateLimitDriver } from "../types-BX4hSfYX.js";
2
-
1
+ import { o as RateLimitDriver } from "../types-CQEJpgtz.js";
3
2
  //#region src/integrations/cloudflare.d.ts
4
- declare function getCloudflareRateLimitBindingName(name: string): string;
3
+ export declare function getCloudflareRateLimitBindingName(name: string): string;
5
4
  //#endregion
6
5
  //#region src/drivers/cloudflare.d.ts
7
- interface CloudflareRateLimitBinding {
6
+ export interface CloudflareRateLimitBinding {
8
7
  limit(input: {
9
8
  key: string;
10
9
  }): Promise<{
11
10
  success: boolean;
12
11
  }>;
13
12
  }
14
- interface CloudflareRateLimitDriverOptions {
13
+ export interface CloudflareRateLimitDriverOptions {
15
14
  binding: CloudflareRateLimitBinding;
16
15
  }
17
- declare function cloudflareRateLimitDriver(options: CloudflareRateLimitDriverOptions): RateLimitDriver;
18
- //#endregion
19
- export { CloudflareRateLimitBinding, CloudflareRateLimitDriverOptions, cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
16
+ export declare function cloudflareRateLimitDriver(options: CloudflareRateLimitDriverOptions): RateLimitDriver;
17
+ //#endregion
@@ -1,2 +1,2 @@
1
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-BYZQ2tim.js";
1
+ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "../cloudflare-DUDRACVB.js";
2
2
  export { cloudflareRateLimitDriver, getCloudflareRateLimitBindingName };
@@ -1,14 +1,14 @@
1
- import { a as RateLimitDriver } from "../types-BX4hSfYX.js";
2
-
1
+ import { o as RateLimitDriver } from "../types-CQEJpgtz.js";
3
2
  //#region src/drivers/memory.d.ts
4
- interface MemoryRateLimitDriverOptions {
3
+ export interface MemoryRateLimitDriverOptions {
5
4
  maxEntries?: number;
6
5
  now?: () => number;
7
6
  }
8
- interface MemoryRateLimitDriver extends RateLimitDriver {
7
+ export interface MemoryRateLimitDriver extends RateLimitDriver {
9
8
  clear: () => void;
9
+ peek: NonNullable<RateLimitDriver["peek"]>;
10
+ reset: NonNullable<RateLimitDriver["reset"]>;
10
11
  size: () => number;
11
12
  }
12
- declare function memoryRateLimitDriver(options?: MemoryRateLimitDriverOptions): MemoryRateLimitDriver;
13
- //#endregion
14
- export { MemoryRateLimitDriver, MemoryRateLimitDriverOptions, memoryRateLimitDriver };
13
+ export declare function memoryRateLimitDriver(options?: MemoryRateLimitDriverOptions): MemoryRateLimitDriver;
14
+ //#endregion
@@ -1,12 +1,17 @@
1
+ import { t as rateLimitErrorDiagnostics } from "../error-diagnostics-CTAC_bbr.js";
1
2
  //#region src/drivers/memory.ts
2
3
  const defaultMaxEntries = 1e5;
3
4
  function memoryRateLimitDriver(options = {}) {
4
5
  const entries = /* @__PURE__ */ new Map();
6
+ let nextExpiry = Number.POSITIVE_INFINITY;
5
7
  const maxEntries = options.maxEntries ?? defaultMaxEntries;
6
- if (!Number.isInteger(maxEntries) || maxEntries <= 0) throw new TypeError("[vitehub] Memory Rate Limit driver maxEntries must be a positive integer.");
8
+ if (!Number.isInteger(maxEntries) || maxEntries <= 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0007({ message: "[vitehub] Memory Rate Limit driver maxEntries must be a positive integer." });
7
9
  const now = options.now ?? Date.now;
8
10
  function prune(timestamp) {
11
+ if (timestamp < nextExpiry) return;
12
+ nextExpiry = Number.POSITIVE_INFINITY;
9
13
  for (const [key, entry] of entries) if (entry.resetAt <= timestamp) entries.delete(key);
14
+ else nextExpiry = Math.min(nextExpiry, entry.resetAt);
10
15
  }
11
16
  return {
12
17
  capabilities: {
@@ -16,18 +21,23 @@ function memoryRateLimitDriver(options = {}) {
16
21
  },
17
22
  clear() {
18
23
  entries.clear();
24
+ nextExpiry = Number.POSITIVE_INFINITY;
19
25
  },
20
26
  consume(input) {
21
27
  const timestamp = now();
22
28
  prune(timestamp);
23
- const key = `${input.name ?? "default"}\0${input.key}`;
24
- const resetAt = Math.floor(timestamp / input.windowMs) * input.windowMs + input.windowMs;
29
+ const key = JSON.stringify([input.name ?? "default", input.key]);
25
30
  const current = entries.get(key);
26
- if (!current && entries.size >= maxEntries) throw new Error(`[vitehub] Memory Rate Limit driver reached maxEntries (${maxEntries}) while active counters remain.`);
27
- const entry = current && current.resetAt > timestamp ? current : {
28
- count: 0,
29
- resetAt
30
- };
31
+ if (!current && entries.size >= maxEntries) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0008({ message: `[vitehub] Memory Rate Limit driver reached maxEntries (${maxEntries}) while active counters remain.` });
32
+ let entry = current;
33
+ if (!entry || entry.resetAt <= timestamp) {
34
+ const resetAt = Math.floor(timestamp / input.windowMs) * input.windowMs + input.windowMs;
35
+ if (!Number.isFinite(resetAt) || resetAt <= 0 || resetAt > 864e13) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0045({ message: "[vitehub] Memory Rate Limit fixed-window end must be a positive timestamp at most 8640000000000000 milliseconds." });
36
+ entry = {
37
+ count: 0,
38
+ resetAt
39
+ };
40
+ }
31
41
  if (entry.count >= input.limit) return [null, {
32
42
  allowed: false,
33
43
  remaining: 0,
@@ -37,6 +47,7 @@ function memoryRateLimitDriver(options = {}) {
37
47
  }];
38
48
  entry.count += 1;
39
49
  entries.set(key, entry);
50
+ nextExpiry = Math.min(nextExpiry, entry.resetAt);
40
51
  return [null, {
41
52
  allowed: true,
42
53
  remaining: input.limit - entry.count,
@@ -44,7 +55,22 @@ function memoryRateLimitDriver(options = {}) {
44
55
  used: entry.count
45
56
  }];
46
57
  },
58
+ peek(input) {
59
+ const timestamp = now();
60
+ prune(timestamp);
61
+ const key = JSON.stringify([input.name ?? "default", input.key]);
62
+ const entry = entries.get(key);
63
+ return [null, {
64
+ resetAt: entry && entry.resetAt > timestamp ? entry.resetAt : void 0,
65
+ used: entry && entry.resetAt > timestamp ? entry.count : 0
66
+ }];
67
+ },
47
68
  name: "memory",
69
+ reset(input) {
70
+ const key = JSON.stringify([input.name ?? "default", input.key]);
71
+ entries.delete(key);
72
+ return [null];
73
+ },
48
74
  size() {
49
75
  return entries.size;
50
76
  }
@@ -0,0 +1,56 @@
1
+ import { defineDiagnostics } from "nostics";
2
+ //#region src/error-diagnostics.ts
3
+ const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
4
+ const rateLimitErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
5
+ docsBase: () => "https://vitehub.dev/docs/reference/diagnostics",
6
+ codes: {
7
+ RATE_LIMIT_R0001: dynamicError,
8
+ RATE_LIMIT_R0002: dynamicError,
9
+ RATE_LIMIT_R0003: dynamicError,
10
+ RATE_LIMIT_R0004: dynamicError,
11
+ RATE_LIMIT_R0005: dynamicError,
12
+ RATE_LIMIT_R0006: dynamicError,
13
+ RATE_LIMIT_R0007: dynamicError,
14
+ RATE_LIMIT_R0008: dynamicError,
15
+ RATE_LIMIT_R0009: dynamicError,
16
+ RATE_LIMIT_R0010: dynamicError,
17
+ RATE_LIMIT_R0011: dynamicError,
18
+ RATE_LIMIT_R0012: dynamicError,
19
+ RATE_LIMIT_R0013: dynamicError,
20
+ RATE_LIMIT_R0015: dynamicError,
21
+ RATE_LIMIT_R0016: dynamicError,
22
+ RATE_LIMIT_R0019: dynamicError,
23
+ RATE_LIMIT_R0020: dynamicError,
24
+ RATE_LIMIT_R0021: dynamicError,
25
+ RATE_LIMIT_R0022: dynamicError,
26
+ RATE_LIMIT_R0023: dynamicError,
27
+ RATE_LIMIT_R0024: dynamicError,
28
+ RATE_LIMIT_R0025: dynamicError,
29
+ RATE_LIMIT_R0026: dynamicError,
30
+ RATE_LIMIT_R0027: dynamicError,
31
+ RATE_LIMIT_R0028: dynamicError,
32
+ RATE_LIMIT_R0029: dynamicError,
33
+ RATE_LIMIT_R0030: dynamicError,
34
+ RATE_LIMIT_R0031: dynamicError,
35
+ RATE_LIMIT_R0032: dynamicError,
36
+ RATE_LIMIT_R0033: dynamicError,
37
+ RATE_LIMIT_R0034: dynamicError,
38
+ RATE_LIMIT_R0035: dynamicError,
39
+ RATE_LIMIT_R0036: dynamicError,
40
+ RATE_LIMIT_R0037: dynamicError,
41
+ RATE_LIMIT_R0038: dynamicError,
42
+ RATE_LIMIT_R0039: dynamicError,
43
+ RATE_LIMIT_R0040: dynamicError,
44
+ RATE_LIMIT_R0041: dynamicError,
45
+ RATE_LIMIT_R0042: dynamicError,
46
+ RATE_LIMIT_R0043: dynamicError,
47
+ RATE_LIMIT_R0044: dynamicError,
48
+ RATE_LIMIT_R0045: dynamicError,
49
+ RATE_LIMIT_B0001: dynamicError,
50
+ RATE_LIMIT_B0002: dynamicError,
51
+ RATE_LIMIT_B0003: dynamicError,
52
+ RATE_LIMIT_B0004: dynamicError
53
+ }
54
+ });
55
+ //#endregion
56
+ export { rateLimitErrorDiagnostics as t };