@vite-hub/rate-limit 0.0.4 → 0.3.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,35 @@
1
+ //#region src/durability.ts
2
+ const memory = {
3
+ primitive: "rate-limit",
4
+ store: "memory",
5
+ scope: "process",
6
+ reason: "Counters live in the memory of this process. Each instance counts on its own.",
7
+ fix: "Use a shared default KV store, such as Redis or a Postgres Default Database, with the `kv` driver."
8
+ };
9
+ /**
10
+ * The durability of Rate Limit counters, from the driver. The `kv` driver counts in the default KV store when that
11
+ * store is a database, Redis, or Upstash store, and falls back to memory otherwise.
12
+ */
13
+ function rateLimitDurability(input, context) {
14
+ if (input.driver === "cloudflare") return [{
15
+ primitive: "rate-limit",
16
+ store: "cloudflare",
17
+ scope: "shared",
18
+ reason: "Cloudflare Rate Limiting bindings count for every Worker."
19
+ }];
20
+ if (input.driver !== "kv") return [memory];
21
+ const kv = context.find("kv");
22
+ if (!kv || !/^(?:database|redis|upstash)\b/.test(kv.store)) return [{
23
+ ...memory,
24
+ reason: `The default KV store is ${kv ? kv.store : "off"}, so counters live in the memory of this process.`
25
+ }];
26
+ return [{
27
+ primitive: "rate-limit",
28
+ store: `kv (${kv.store})`,
29
+ scope: kv.scope,
30
+ reason: `Counters in the default KV store. ${kv.reason}`,
31
+ ...kv.fix ? { fix: kv.fix } : {}
32
+ }];
33
+ }
34
+ //#endregion
35
+ export { rateLimitDurability };
@@ -0,0 +1,234 @@
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/rate-limit/diagnostics",
6
+ codes: {
7
+ RATE_LIMIT_OPERATION_FAILED: {
8
+ why: "The Rate Limit operation failed.",
9
+ fix: "Read `error.cause` for the driver error. Check that the store of the Rate Limit is reachable, then retry."
10
+ },
11
+ RATE_LIMIT_R0001: {
12
+ ...dynamicError,
13
+ fix: "Call `requireRateLimit()` or `checkRateLimit()` at the place that the message names with a static string ID and an object literal of static `limit`, `window`, `enforcement`, and `failure` options, without spreads. `key` can stay a runtime value."
14
+ },
15
+ RATE_LIMIT_R0002: {
16
+ ...dynamicError,
17
+ fix: "Fix the syntax error in the file that the message names, so that ViteHub can read its Rate Limits."
18
+ },
19
+ RATE_LIMIT_R0003: {
20
+ ...dynamicError,
21
+ fix: "Give the files that the message lists the same `limit`, `window`, `enforcement`, and `failure` for this Rate Limit ID, or use a different ID for each policy."
22
+ },
23
+ RATE_LIMIT_R0004: {
24
+ ...dynamicError,
25
+ fix: "Pass `cloudflareRateLimitDriver({ binding })` the Rate Limiting binding from the Worker `env`, the object that has a `limit()` method."
26
+ },
27
+ RATE_LIMIT_R0005: {
28
+ ...dynamicError,
29
+ fix: "Read `error.cause` for the error of the Cloudflare Rate Limiting binding and check the `ratelimits` binding of the Worker. A retry can help when Cloudflare had a short outage."
30
+ },
31
+ RATE_LIMIT_R0006: {
32
+ ...dynamicError,
33
+ fix: "Check that the binding that you pass to `cloudflareRateLimitDriver()` is a Cloudflare Rate Limiting binding, whose `limit()` returns `{ success }`."
34
+ },
35
+ RATE_LIMIT_R0007: {
36
+ ...dynamicError,
37
+ fix: "Set `maxEntries` of `memoryRateLimitDriver()` to a whole number of 1 or more, or remove it to keep 100000."
38
+ },
39
+ RATE_LIMIT_R0008: {
40
+ ...dynamicError,
41
+ fix: "Set a larger `maxEntries` in `memoryRateLimitDriver()`, or use the `kv` driver, which keeps its counters out of process memory."
42
+ },
43
+ RATE_LIMIT_R0009: {
44
+ ...dynamicError,
45
+ fix: "Build the app for the Cloudflare host, so that the build adds the Rate Limiting bindings to the Wrangler config, and deploy the Worker with that config."
46
+ },
47
+ RATE_LIMIT_R0010: {
48
+ ...dynamicError,
49
+ fix: "Pass a non-empty static string ID, such as `\"image-upload\"`, as the second argument of `requireRateLimit()` or `checkRateLimit()`."
50
+ },
51
+ RATE_LIMIT_R0011: {
52
+ ...dynamicError,
53
+ fix: "Pass only `key`, `limit`, `window`, `enforcement`, and `failure` in the options of `checkRateLimit()`. `requireRateLimit()` also accepts `message` and `code`."
54
+ },
55
+ RATE_LIMIT_R0012: {
56
+ ...dynamicError,
57
+ fix: "Pass `key` as a non-empty string, such as the user ID, or remove `key` to limit by the client address."
58
+ },
59
+ RATE_LIMIT_R0013: {
60
+ ...dynamicError,
61
+ fix: "Pass `key`, such as the user or tenant ID, to `requireRateLimit()` or `checkRateLimit()` when the request has no client address."
62
+ },
63
+ RATE_LIMIT_R0015: {
64
+ ...dynamicError,
65
+ fix: "Remove `enforcement: \"strict\"` from this Rate Limit to use the Cloudflare binding, or use the `kv` driver for strict counts."
66
+ },
67
+ RATE_LIMIT_R0016: {
68
+ ...dynamicError,
69
+ fix: "Set `window` of this Rate Limit to \"10s\" or \"1m\" to use the Cloudflare binding, or use the `kv` driver for other windows."
70
+ },
71
+ RATE_LIMIT_R0019: {
72
+ ...dynamicError,
73
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: add `capabilities` with `enforcement`, `scope`, and `rejectedAttempts`."
74
+ },
75
+ RATE_LIMIT_R0020: {
76
+ ...dynamicError,
77
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: set `capabilities.enforcement` to \"best-effort\" or \"strict\"."
78
+ },
79
+ RATE_LIMIT_R0021: {
80
+ ...dynamicError,
81
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: set `capabilities.scope` to \"process\", \"location\", or \"global\"."
82
+ },
83
+ RATE_LIMIT_R0022: {
84
+ ...dynamicError,
85
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: set `capabilities.rejectedAttempts` to \"counted\", \"not-counted\", or \"unknown\"."
86
+ },
87
+ RATE_LIMIT_R0023: {
88
+ ...dynamicError,
89
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: list `capabilities.windows` as an array of whole numbers of milliseconds, or remove it to accept every window."
90
+ },
91
+ RATE_LIMIT_R0024: {
92
+ ...dynamicError,
93
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `remaining`, `retryAfter`, and `used` from `consume()` as whole numbers of 0 or more, or leave them out."
94
+ },
95
+ RATE_LIMIT_R0025: {
96
+ ...dynamicError,
97
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, { allowed }]` from `consume()`, with `allowed` as a boolean."
98
+ },
99
+ RATE_LIMIT_R0026: {
100
+ ...dynamicError,
101
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `resetAt` from `consume()` as a Unix timestamp in milliseconds, or leave it out."
102
+ },
103
+ RATE_LIMIT_R0027: {
104
+ ...dynamicError,
105
+ fix: "Remove `enforcement: \"strict\"` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()`, or use a driver with strict enforcement, such as the memory or kv driver."
106
+ },
107
+ RATE_LIMIT_R0028: {
108
+ ...dynamicError,
109
+ fix: "Set `window` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to one of the windows that the message lists, or use a driver without a window limit."
110
+ },
111
+ RATE_LIMIT_R0029: {
112
+ ...dynamicError,
113
+ fix: "Pass `createRateLimiter()` a plain object with a `driver`, such as `memoryRateLimitDriver()`, and the `limit` and `window` of the policy."
114
+ },
115
+ RATE_LIMIT_R0030: {
116
+ ...dynamicError,
117
+ fix: "Pass `consume({ key })` a non-empty string `key`, such as the user ID or the client address."
118
+ },
119
+ RATE_LIMIT_R0031: {
120
+ ...dynamicError,
121
+ fix: "Set `window` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to a duration string such as \"10s\", \"1m\", \"1h\", or \"1d\"."
122
+ },
123
+ RATE_LIMIT_R0032: {
124
+ ...dynamicError,
125
+ fix: "Set `window` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to a duration greater than zero and shorter than 100000000 days."
126
+ },
127
+ RATE_LIMIT_R0033: {
128
+ ...dynamicError,
129
+ fix: "Pass the Rate Limit policy as an object with `limit` and `window`, such as `{ limit: 10, window: \"1m\" }`."
130
+ },
131
+ RATE_LIMIT_R0034: {
132
+ ...dynamicError,
133
+ fix: "Set `limit` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to a whole number of 1 or more."
134
+ },
135
+ RATE_LIMIT_R0035: {
136
+ ...dynamicError,
137
+ fix: "Set `enforcement` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to \"best-effort\" or \"strict\", or remove it."
138
+ },
139
+ RATE_LIMIT_R0036: {
140
+ ...dynamicError,
141
+ fix: "Set `failure` in the options of `requireRateLimit()`, `checkRateLimit()`, or `createRateLimiter()` to \"allow\" or \"deny\", or remove it."
142
+ },
143
+ RATE_LIMIT_R0037: {
144
+ ...dynamicError,
145
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, { used }]` from `peek()`, with `used` as a whole number of 0 or more and an optional `resetAt` in milliseconds."
146
+ },
147
+ RATE_LIMIT_R0038: {
148
+ ...dynamicError,
149
+ fix: "Pass `peek({ key })` or `reset({ key })` a non-empty string `key`."
150
+ },
151
+ RATE_LIMIT_R0039: {
152
+ ...dynamicError,
153
+ fix: "Pass `peekRateLimit(id, key)` or `resetRateLimit(id, key)` the stable ID of a `requireRateLimit()` call and a non-empty key."
154
+ },
155
+ RATE_LIMIT_R0040: {
156
+ ...dynamicError,
157
+ fix: "Run `vitehub rate-limit peek <id> <key>` or `vitehub rate-limit reset <id> <key>` with only the options that `--help` lists. Put `--` before a key that starts with a dash."
158
+ },
159
+ RATE_LIMIT_R0041: {
160
+ ...dynamicError,
161
+ fix: "Pass `--timeout` as a whole number of milliseconds from 1 to 2147483647, such as `--timeout 5000`."
162
+ },
163
+ RATE_LIMIT_R0042: {
164
+ ...dynamicError,
165
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, undefined]` from `reset()`, or `[error, undefined]` for an outage."
166
+ },
167
+ RATE_LIMIT_R0043: {
168
+ ...dynamicError,
169
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, result]` from `peek()`, or `[error, undefined]` for an outage."
170
+ },
171
+ RATE_LIMIT_R0044: {
172
+ ...dynamicError,
173
+ fix: "Fix the custom driver that you pass to `createRateLimiter()`: return `[undefined, result]` from `consume()`, or `[error, undefined]` for an outage."
174
+ },
175
+ RATE_LIMIT_R0045: {
176
+ ...dynamicError,
177
+ fix: "Use a shorter `window` in the Rate Limit policy. With `memoryRateLimitDriver({ now })`, return the current time in milliseconds from `now`."
178
+ },
179
+ RATE_LIMIT_R0046: {
180
+ ...dynamicError,
181
+ fix: "Pass `kv` or `kv.store(name)` from `@vite-hub/kv` as the `storage` option to `kvRateLimitDriver()`."
182
+ },
183
+ RATE_LIMIT_R0047: {
184
+ ...dynamicError,
185
+ fix: "Enable KV in the app and build again. For a custom runtime, pass the KV driver, storage, and store name to `setRateLimitRuntimeConfig()`."
186
+ },
187
+ RATE_LIMIT_B0001: {
188
+ ...dynamicError,
189
+ fix: "Set `rateLimit: { namespace }` in `vitehub()`, or `namespace` in `hubRateLimit()`, to a name that is different for each Worker and environment, such as `\"acme-api-production\"`."
190
+ },
191
+ RATE_LIMIT_B0002: {
192
+ ...dynamicError,
193
+ fix: "Set `driver: \"kv\"` in `hubRateLimit()` with a Redis or Upstash KV store, or call `createRateLimiter()` with your own driver."
194
+ },
195
+ RATE_LIMIT_B0003: {
196
+ ...dynamicError,
197
+ fix: "Set `driver` in `hubRateLimit()` to `\"cloudflare\"` or `\"kv\"`, or to `\"memory\"` only for a deploy with one server process."
198
+ },
199
+ RATE_LIMIT_B0004: {
200
+ ...dynamicError,
201
+ fix: "Write every file that declares a Rate Limit before `vite build` starts. Do not create or change these files from a plugin during the build."
202
+ },
203
+ RATE_LIMIT_KV_RUNTIME_STORE_UNSUPPORTED: {
204
+ ...dynamicError,
205
+ fix: "Use a KV driver that every server process shares: Redis, a Postgres Database, or Upstash. To count in the memory of each process instead, pass `memoryFallback: true` to `setRateLimitRuntimeConfig()`."
206
+ },
207
+ RATE_LIMIT_KV_STORE_UNSUPPORTED: {
208
+ ...dynamicError,
209
+ fix: "Use a KV driver that every server process shares: `kv: { driver: 'redis' }`, a Postgres Database, or Upstash. Or remove `driver: 'kv'` to let ViteHub choose."
210
+ },
211
+ RATE_LIMIT_KV_TIMEOUT: {
212
+ why: "The KV store did not answer the Rate Limit within 1000 milliseconds.",
213
+ fix: "Check that the KV store of the Rate Limit is reachable and not overloaded, then retry. Until it answers, `consume()` applies the `failure` policy of the Rate Limit."
214
+ },
215
+ RATE_LIMIT_MEMORY_PER_PROCESS: {
216
+ why: "Rate Limit counts requests in the memory of each server process. With several instances, each one allows the full limit.",
217
+ fix: "Enable KV on Node so that ViteHub selects the kv driver, or set `rateLimit.driver` to \"kv\" and configure a Redis KV store or a Postgres Database. Keep `memory` only for one server process."
218
+ },
219
+ RATE_LIMIT_MEMORY_STRICT_UNSUPPORTED: {
220
+ ...dynamicError,
221
+ fix: "Count in a shared store: on Node, set `rateLimit: { driver: 'kv' }` with a Redis or Postgres KV store. Or set `enforcement: 'best-effort'` on the Rate Limit."
222
+ },
223
+ RATE_LIMIT_REFUSAL_OPTION_INVALID: {
224
+ ...dynamicError,
225
+ fix: "Pass `message` and `code` of `requireRateLimit()` as non-empty strings, such as `message: \"Too many tries. Wait a minute.\"`, or remove them to use the default `429` error."
226
+ },
227
+ RATE_LIMIT_RENAMED_PROVIDER_KEY: {
228
+ why: ({ value }) => `\`rateLimit.provider\` is ${value}. ViteHub renamed this key to \`driver\`, and it does not read \`provider\`, so Rate Limit would not use the driver you chose.`,
229
+ fix: ({ value }) => `Set \`rateLimit: { driver: ${value} }\`, or run \`npx @vite-hub/codemods driver-key\` to rename it in every config file.`
230
+ }
231
+ }
232
+ });
233
+ //#endregion
234
+ export { rateLimitErrorDiagnostics as t };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,24 @@
1
- import { S as ResolvedRateLimitPolicy, _ as RateLimitRequestEvent, a as RateLimitDeclaration, b as RateLimiter, c as RateLimitDriverInput, d as RateLimitEnforcement, f as RateLimitFailurePolicy, g as RateLimitRejectedAttemptBehavior, h as RateLimitProvider, i as RateLimitDecision, l as RateLimitDriverOutcome, m as RateLimitPolicy, n as RateLimitConsumeInput, o as RateLimitDriver, p as RateLimitModuleOptions, r as RateLimitCounterScope, s as RateLimitDriverCapabilities, t as CreateRateLimiterOptions, u as RateLimitDriverResult, v as RateLimitRuntimeConfig, x as RequireRateLimitOptions, y as RateLimitWindow } from "./types-DoyUiUt1.js";
2
-
1
+ import { A as ResolvedRateLimitPolicy, C as RateLimitRequest, D as RateLimitWindow, E as RateLimitRuntimeConfig, O as RateLimiter, S as RateLimitRejectedAttemptBehavior, T as RateLimitResetResult, _ as RateLimitEnforcement, a as RateLimitCounterScope, b as RateLimitPeekResult, c as RateLimitDriver, d as RateLimitDriverName, f as RateLimitDriverOutcome, g as RateLimitDriverResult, h as RateLimitDriverResetOutcome, i as RateLimitConsumeInput, k as RequireRateLimitOptions, 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 RateLimitFailurePolicy, w as RateLimitRequestEvent, x as RateLimitPolicy, y as RateLimitOptions } from "./types-CMyR1JeW.js";
2
+ import { a as resetRateLimit, i as peekRateLimit, n as RateLimitPeekInspection, r as RateLimitResetInspection, t as RateLimitCounterSnapshot } from "./counters-DXpF67J_.js";
3
+ import { Result } from "@vite-hub/runtime";
3
4
  //#region src/limiter.d.ts
4
- declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
5
+ export declare function createRateLimiter(options: CreateRateLimiterOptions): RateLimiter;
5
6
  //#endregion
6
7
  //#region src/guard.d.ts
7
- declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
8
+ /**
9
+ * Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
10
+ * gets an answer, such as a cheaper fallback. `decision.reason` is `limited` or `unavailable` when not allowed.
11
+ * `error` is set when the check cannot run: `RATE_LIMIT_R0013` for a request without a key, `RATE_LIMIT_R0009` for a
12
+ * missing Cloudflare binding. Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid
13
+ * options throw.
14
+ */
15
+ export declare function checkRateLimit(event: RateLimitRequestEvent, name: string, options: CheckRateLimitOptions): Promise<Result<RateLimitDecision, CheckRateLimitErrorCode>>;
16
+ /**
17
+ * Consumes one request from a managed Rate Limit inside a handler. Returns when the request is allowed. Otherwise
18
+ * it throws an HTTP error: `429` with `Retry-After` when the limit is reached, `503` when the limiter is unavailable.
19
+ * `message` and `code` set the message and `data.code` of the `429` error. It also throws the errors that
20
+ * `checkRateLimit()` returns.
21
+ */
22
+ export declare function requireRateLimit(event: RateLimitRequestEvent, name: string, options: RequireRateLimitOptions): Promise<void>;
8
23
  //#endregion
9
- export { type CreateRateLimiterOptions, type RateLimitConsumeInput, type RateLimitCounterScope, type RateLimitDecision, type RateLimitDeclaration, type RateLimitDriver, type RateLimitDriverCapabilities, type RateLimitDriverInput, type RateLimitDriverOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitModuleOptions, type RateLimitPolicy, type RateLimitProvider, type RateLimitRejectedAttemptBehavior, type RateLimitRequestEvent, type RateLimitRuntimeConfig, type RateLimitWindow, type RateLimiter, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, createRateLimiter, requireRateLimit };
24
+ 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 RateLimitDriverResetOutcome, type RateLimitDriverResult, type RateLimitEnforcement, type RateLimitFailurePolicy, type RateLimitOptions, type RateLimitPeekInspection, type RateLimitPeekResult, type RateLimitPolicy, type RateLimitRejectedAttemptBehavior, type RateLimitRequest, type RateLimitRequestEvent, type RateLimitResetInspection, type RateLimitResetResult, type RateLimitRuntimeConfig, type RateLimitWindow, type RateLimiter, type RequireRateLimitOptions, type ResolvedRateLimitPolicy, peekRateLimit, resetRateLimit };
package/dist/index.js CHANGED
@@ -1,76 +1,144 @@
1
- import { i as rateLimitPolicyKeys, n as declaredRateLimitPolicy, r as normalizeRateLimitPolicy, t as createRateLimiter } from "./limiter-CHaHluMr.js";
2
- import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-BYZQ2tim.js";
3
- import { memoryRateLimitDriver } from "./drivers/memory.js";
4
- import { n as getRateLimitRuntimeConfig, t as getRateLimitLimiterCache } from "./state-DB4uJN5P.js";
5
- import { HTTPError, getRequestIP } from "h3";
6
- //#region src/guard.ts
7
- const guardOptionKeys = new Set([...rateLimitPolicyKeys, "key"]);
8
- function getCloudflareEventEnv(event) {
9
- const target = event;
10
- return target.env ?? target.context?.cloudflare?.env ?? target.context?._platform?.cloudflare?.env ?? target.req?.runtime?.cloudflare?.env ?? target.node?.req?.runtime?.cloudflare?.env;
1
+ import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
2
+ import { a as rateLimitPolicyKeys, i as normalizeRateLimitPolicy, n as createRateLimiter, r as declaredRateLimitPolicy } from "./kv-provider-C1S6dRTR.js";
3
+ import { i as resolveRateLimitDriver, n as getRuntimeRateLimiter } from "./state-BU-zcLNY.js";
4
+ import { n as resetRateLimit, t as peekRateLimit } from "./counters-DgVdHwdL.js";
5
+ import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-otBvOPv4.js";
6
+ import { toResultError } from "@vite-hub/runtime";
7
+ import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
8
+ import { getStandardContext } from "@vite-hub/runtime/internal/h3";
9
+ import { createError } from "nitro/h3";
10
+ //#region ../internal/src/runtime/cloudflare-env-lookup.ts
11
+ /** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
12
+ const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
13
+ let activeEnv;
14
+ /** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
15
+ function getScopedCloudflareEnv() {
16
+ return globalThis[activeEnvStorageKey]?.getStore();
17
+ }
18
+ function getActiveCloudflareEnv() {
19
+ const scoped = getScopedCloudflareEnv();
20
+ if (scoped) return scoped.env;
21
+ const host = globalThis;
22
+ return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
11
23
  }
24
+ //#endregion
25
+ //#region src/guard.ts
26
+ const guardOptionKeys = {
27
+ checkRateLimit: /* @__PURE__ */ new Set([...rateLimitPolicyKeys, "key"]),
28
+ requireRateLimit: /* @__PURE__ */ new Set([
29
+ ...rateLimitPolicyKeys,
30
+ "code",
31
+ "key",
32
+ "message"
33
+ ])
34
+ };
12
35
  function isCloudflareBinding(value) {
13
36
  return Boolean(value) && typeof value === "object" && typeof value.limit === "function";
14
37
  }
15
- function getRequestKey(event, provider) {
16
- return provider === "cloudflare" ? event.req.headers.get("cf-connecting-ip") || getRequestIP(event) : getRequestIP(event);
38
+ function isObject(value) {
39
+ return value !== null && typeof value === "object";
17
40
  }
18
- function getMemoryRateLimiter(name, policy) {
19
- const cache = getRateLimitLimiterCache();
20
- const cacheKey = JSON.stringify([
21
- name,
22
- policy.enforcement,
23
- policy.failure,
24
- policy.limit,
25
- policy.window
26
- ]);
27
- const existing = cache.get(cacheKey);
28
- if (existing) return existing;
29
- const pending = Promise.resolve(createRateLimiter({
30
- ...policy,
31
- driver: memoryRateLimitDriver(),
32
- name
33
- })).catch((error) => {
34
- cache.delete(cacheKey);
35
- throw error;
36
- });
37
- cache.set(cacheKey, pending);
38
- return pending;
41
+ function isWebRequest(value) {
42
+ if (value instanceof Request) return true;
43
+ if (!isObject(value)) return false;
44
+ const headers = Reflect.get(value, "headers");
45
+ return typeof Reflect.get(value, "url") === "string" && typeof Reflect.get(value, "method") === "string" && isObject(headers) && typeof Reflect.get(headers, "get") === "function";
46
+ }
47
+ /** Structural Requests may carry unrelated event-named properties, so identify the event's shape. */
48
+ function isRequestEvent(input) {
49
+ if ("~standard" in input) {
50
+ const standard = input["~standard"];
51
+ return isObject(standard) && typeof Reflect.get(standard, "vendor") === "string" && isWebRequest(Reflect.get(standard, "req")) && isObject(Reflect.get(standard, "res"));
52
+ }
53
+ return Object.hasOwn(input, "req") && isWebRequest(Reflect.get(input, "req")) && isObject(Reflect.get(input, "res"));
54
+ }
55
+ function getRequestScope(input) {
56
+ if (!isRequestEvent(input)) return {
57
+ cloudflareEnv: getActiveCloudflareEnv(),
58
+ headers: input.headers
59
+ };
60
+ const standard = getStandardContext(input);
61
+ return {
62
+ clientAddress: standard.runtime?.clientAddress,
63
+ cloudflareEnv: standard.runtime?.cloudflare?.env,
64
+ headers: standard.req.headers
65
+ };
39
66
  }
40
- function getCloudflareRateLimiter(event, name, policy) {
67
+ function getRequestKey(scope, driver) {
68
+ return driver === "cloudflare" ? scope.headers.get("cf-connecting-ip") || scope.clientAddress : scope.clientAddress;
69
+ }
70
+ /** A failure of one check, such as a request without a key. Option errors throw instead. */
71
+ function checkError(code, message) {
72
+ const diagnostic = code === "RATE_LIMIT_R0009" ? rateLimitErrorDiagnostics.RATE_LIMIT_R0009({ message }) : rateLimitErrorDiagnostics.RATE_LIMIT_R0013({ message });
73
+ return toResultError(diagnostic);
74
+ }
75
+ function getCloudflareRateLimiter(scope, name, policy) {
41
76
  const bindingName = getCloudflareRateLimitBindingName(name);
42
- const binding = getCloudflareEventEnv(event)?.[bindingName];
43
- if (!isCloudflareBinding(binding)) throw new Error(`[vitehub] Cloudflare Rate Limit binding "${bindingName}" was not found on the request event.`);
44
- return createRateLimiter({
77
+ const env = scope.cloudflareEnv;
78
+ const binding = env && Object.hasOwn(env, bindingName) ? env[bindingName] : void 0;
79
+ if (!isCloudflareBinding(binding)) return [checkError("RATE_LIMIT_R0009", `[vitehub] Cloudflare Rate Limit binding "${bindingName}" was not found on the request event.`), void 0];
80
+ return [void 0, createRateLimiter({
45
81
  ...policy,
46
82
  driver: cloudflareRateLimitDriver({ binding }),
47
83
  name
48
- });
84
+ })];
49
85
  }
50
- async function requireRateLimit(event, name, options) {
86
+ async function consumeRateLimit(event, name, options, guard) {
51
87
  const id = typeof name === "string" ? name.trim() : "";
52
- if (!id) throw new TypeError("`requireRateLimit()` requires a non-empty stable ID.");
53
- const unknownKey = options && typeof options === "object" && !Array.isArray(options) ? Object.keys(options).find((key) => !guardOptionKeys.has(key)) : void 0;
54
- if (unknownKey) throw new TypeError(`\`requireRateLimit()\` does not support the "${unknownKey}" option.`);
55
- if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw new TypeError("`requireRateLimit()` key must be a non-empty string.");
88
+ if (!id) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0010({ message: `\`${guard}()\` requires a non-empty stable ID.` });
89
+ const unknownKey = options && typeof options === "object" && !Array.isArray(options) ? Object.keys(options).find((key) => !guardOptionKeys[guard].has(key)) : void 0;
90
+ if (unknownKey) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0011({ message: `\`${guard}()\` does not support the "${unknownKey}" option.` });
91
+ if (options?.key !== void 0 && (typeof options.key !== "string" || options.key.length === 0)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0012({ message: `\`${guard}()\` key must be a non-empty string.` });
56
92
  const policy = declaredRateLimitPolicy(normalizeRateLimitPolicy(options));
57
- const { provider } = getRateLimitRuntimeConfig();
58
- const key = options.key ?? getRequestKey(event, provider);
59
- if (!key) throw new Error("[vitehub] Rate Limit could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.");
60
- const decision = await (provider === "cloudflare" ? getCloudflareRateLimiter(event, id, policy) : await getMemoryRateLimiter(id, policy)).consume({ key });
93
+ const driver = await resolveRateLimitDriver();
94
+ const scope = getRequestScope(event);
95
+ const key = options.key ?? getRequestKey(scope, driver) ?? (getViteHubTestMode() ? "test-client" : void 0);
96
+ if (!key) return [checkError("RATE_LIMIT_R0013", `[vitehub] \`${guard}()\` could not determine a request key. Pass key when limiting by user or tenant or when the request has no client address.`), void 0];
97
+ const [error, limiter] = driver === "cloudflare" ? getCloudflareRateLimiter(scope, id, policy) : [void 0, getRuntimeRateLimiter(driver, id, policy)];
98
+ if (error) return [error, void 0];
99
+ return [void 0, await limiter.consume({ key })];
100
+ }
101
+ /**
102
+ * Consumes one request from a managed Rate Limit and returns `[error, decision]`. Use it when a limited request still
103
+ * gets an answer, such as a cheaper fallback. `decision.reason` is `limited` or `unavailable` when not allowed.
104
+ * `error` is set when the check cannot run: `RATE_LIMIT_R0013` for a request without a key, `RATE_LIMIT_R0009` for a
105
+ * missing Cloudflare binding. Shares counters, discovery, and Provider Output with `requireRateLimit()`. Invalid
106
+ * options throw.
107
+ */
108
+ async function checkRateLimit(event, name, options) {
109
+ return await consumeRateLimit(event, name, options, "checkRateLimit");
110
+ }
111
+ function refusalText(options, option) {
112
+ const value = options?.[option];
113
+ if (value === void 0) return;
114
+ if (typeof value !== "string" || !value.trim()) throw rateLimitErrorDiagnostics.RATE_LIMIT_REFUSAL_OPTION_INVALID({ message: `\`requireRateLimit()\` ${option} must be a non-empty string.` });
115
+ return value;
116
+ }
117
+ /**
118
+ * Consumes one request from a managed Rate Limit inside a handler. Returns when the request is allowed. Otherwise
119
+ * it throws an HTTP error: `429` with `Retry-After` when the limit is reached, `503` when the limiter is unavailable.
120
+ * `message` and `code` set the message and `data.code` of the `429` error. It also throws the errors that
121
+ * `checkRateLimit()` returns.
122
+ */
123
+ async function requireRateLimit(event, name, options) {
124
+ const message = refusalText(options, "message");
125
+ const code = refusalText(options, "code");
126
+ const [error, decision] = await consumeRateLimit(event, name, options, "requireRateLimit");
127
+ if (error) throw error;
61
128
  if (decision.allowed) return;
62
- if (decision.reason === "unavailable") throw new HTTPError({
129
+ if (decision.reason === "unavailable") throw createError({
63
130
  cause: decision.cause,
64
131
  message: "Rate limiting is unavailable.",
65
132
  status: 503,
66
133
  statusText: "Service Unavailable"
67
134
  });
68
- throw new HTTPError({
135
+ throw createError({
136
+ ...code === void 0 ? {} : { data: { code } },
69
137
  headers: decision.retryAfter === void 0 ? void 0 : { "Retry-After": String(decision.retryAfter) },
70
- message: "Rate limit exceeded.",
138
+ message: message ?? "Rate limit exceeded.",
71
139
  status: 429,
72
140
  statusText: "Too Many Requests"
73
141
  });
74
142
  }
75
143
  //#endregion
76
- export { createRateLimiter, requireRateLimit };
144
+ export { checkRateLimit, createRateLimiter, peekRateLimit, requireRateLimit, resetRateLimit };
@@ -0,0 +1,118 @@
1
+ //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
2
+ const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
3
+ function normalizeWindowsPath(input = "") {
4
+ if (!input) return input;
5
+ return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
6
+ }
7
+ const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
8
+ const _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
9
+ const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
10
+ function cwd() {
11
+ if (typeof process !== "undefined" && typeof process.cwd === "function") return process.cwd().replace(/\\/g, "/");
12
+ return "/";
13
+ }
14
+ const resolve = function(...arguments_) {
15
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
16
+ let resolvedPath = "";
17
+ let resolvedAbsolute = false;
18
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
19
+ const path = index >= 0 ? arguments_[index] : cwd();
20
+ if (!path || path.length === 0) continue;
21
+ resolvedPath = `${path}/${resolvedPath}`;
22
+ resolvedAbsolute = isAbsolute(path);
23
+ }
24
+ resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute);
25
+ if (resolvedAbsolute && !isAbsolute(resolvedPath)) return `/${resolvedPath}`;
26
+ return resolvedPath.length > 0 ? resolvedPath : ".";
27
+ };
28
+ function normalizeString(path, allowAboveRoot) {
29
+ let res = "";
30
+ let lastSegmentLength = 0;
31
+ let lastSlash = -1;
32
+ let dots = 0;
33
+ let char = null;
34
+ for (let index = 0; index <= path.length; ++index) {
35
+ if (index < path.length) char = path[index];
36
+ else if (char === "/") break;
37
+ else char = "/";
38
+ if (char === "/") {
39
+ if (lastSlash === index - 1 || dots === 1);
40
+ else if (dots === 2) {
41
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
42
+ if (res.length > 2) {
43
+ const lastSlashIndex = res.lastIndexOf("/");
44
+ if (lastSlashIndex === -1) {
45
+ res = "";
46
+ lastSegmentLength = 0;
47
+ } else {
48
+ res = res.slice(0, lastSlashIndex);
49
+ lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
50
+ }
51
+ lastSlash = index;
52
+ dots = 0;
53
+ continue;
54
+ } else if (res.length > 0) {
55
+ res = "";
56
+ lastSegmentLength = 0;
57
+ lastSlash = index;
58
+ dots = 0;
59
+ continue;
60
+ }
61
+ }
62
+ if (allowAboveRoot) {
63
+ res += res.length > 0 ? "/.." : "..";
64
+ lastSegmentLength = 2;
65
+ }
66
+ } else {
67
+ if (res.length > 0) res += `/${path.slice(lastSlash + 1, index)}`;
68
+ else res = path.slice(lastSlash + 1, index);
69
+ lastSegmentLength = index - lastSlash - 1;
70
+ }
71
+ lastSlash = index;
72
+ dots = 0;
73
+ } else if (char === "." && dots !== -1) ++dots;
74
+ else dots = -1;
75
+ }
76
+ return res;
77
+ }
78
+ const isAbsolute = function(p) {
79
+ return _IS_ABSOLUTE_RE.test(p);
80
+ };
81
+ const relative = function(from, to) {
82
+ const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/");
83
+ const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
84
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) return _to.join("/");
85
+ const _fromCopy = [..._from];
86
+ for (const segment of _fromCopy) {
87
+ if (_to[0] !== segment) break;
88
+ _from.shift();
89
+ _to.shift();
90
+ }
91
+ return [..._from.map(() => ".."), ..._to].join("/");
92
+ };
93
+ const dirname = function(p) {
94
+ const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
95
+ if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) segments[0] += "/";
96
+ return segments.join("/") || (isAbsolute(p) ? "/" : ".");
97
+ };
98
+ //#endregion
99
+ //#region ../internal/src/inspect.ts
100
+ function relativeDefinitionFile(projectRoot, file) {
101
+ return relative(projectRoot, file).replaceAll("\\", "/");
102
+ }
103
+ const redactedInspectionValue = "[redacted]";
104
+ const secretKeyPattern = /secret|token|passw(?:or)?d|credential|api[-_\s]?key|private[-_\s]?key|authorization|cookie|signature|dsn|connection[-_\s]?string/i;
105
+ const embeddedUrlCredentialPattern = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s?#]*@/gi;
106
+ const embeddedCookiePattern = /\b([\w-]*cookie[\w-]*["']?\s*[:=]\s*)(?:"(?:\\[^\r\n]|[^"\\\r\n])*"(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|'(?:\\[^\r\n]|[^'\\\r\n])*'(?:\s*;\s*[\w.-]+\s*=[^;\r\n]*)*|[^\r\n]+?(?=\s*(?:;\s*[^;=\r\n/]+\s*(?:\r?\n|$)|&|\r?\n|$)))/gi;
107
+ const embeddedBearerPattern = /\bbearer\s+[^\s,;]+/gi;
108
+ const embeddedAuthorizationPattern = new RegExp(String.raw`\b([\w-]*authorization[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\r\n]+?(?=\s*(?:[,;])?\s*(?:${secretKeyPattern.source})[\w-]*\s*[:=]|\s+rejected\b|$))`, "gi");
109
+ const embeddedSecretAssignmentPattern = new RegExp(String.raw`\b([\w-]*(?:${secretKeyPattern.source})[\w-]*["']?\s*[:=]\s*)(?!\[redacted\](?=$|[\s,;}&]))(?:"(?:\\[^\r\n]|[^"\\\r\n])*"|'(?:\\[^\r\n]|[^'\\\r\n])*'|[^\s,;&#&]+)`, "gi");
110
+ /**
111
+ * Removes credentials inside free text, for example an error message. URL credentials, bearer tokens, and
112
+ * `name=value` pairs with a secret name are replaced with `[redacted]`.
113
+ */
114
+ function redactInspectionText(value) {
115
+ return value.replace(embeddedUrlCredentialPattern, `$1${redactedInspectionValue}@`).replace(embeddedAuthorizationPattern, `$1${redactedInspectionValue}`).replace(embeddedCookiePattern, `$1${redactedInspectionValue}`).replace(embeddedBearerPattern, `Bearer ${redactedInspectionValue}`).replace(embeddedSecretAssignmentPattern, `$1${redactedInspectionValue}`);
116
+ }
117
+ //#endregion
118
+ export { resolve as i, relativeDefinitionFile as n, dirname as r, redactInspectionText as t };