@vite-hub/rate-limit 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -13
- package/dist/cli.js +14 -4
- package/dist/{cloudflare-otBvOPv4.js → cloudflare-_Tz3DcpB.js} +9 -2
- package/dist/{counters-DgVdHwdL.js → counters-D4LANMAi.js} +4 -3
- package/dist/{counters-DXpF67J_.d.ts → counters-d8FaLiE1.d.ts} +3 -2
- package/dist/drivers/cloudflare.d.ts +1 -1
- package/dist/drivers/cloudflare.js +1 -1
- package/dist/drivers/kv.d.ts +1 -1
- package/dist/drivers/kv.js +54 -15
- package/dist/drivers/memory.d.ts +2 -1
- package/dist/drivers/memory.js +6 -1
- package/dist/{error-diagnostics-MgAnhRTP.js → error-diagnostics-DRuEG4wu.js} +6 -2
- package/dist/index.d.ts +10 -3
- package/dist/index.js +38 -10
- package/dist/{kv-C1wpLulE.d.ts → kv-Cw_jK6Gu.d.ts} +6 -3
- package/dist/{kv-provider-C1S6dRTR.js → kv-provider-DlgNQC-o.js} +28 -57
- package/dist/{operation-definition-8gOe-ubD.d.ts → operation-definition-nmRu_O3V.d.ts} +5 -0
- package/dist/{operations-CLI9w3rO.js → operations-B1MnA9cW.js} +2 -2
- package/dist/{operations-BYRa7wpx.js → operations-q0ieloSJ.js} +218 -207
- package/dist/operations.d.ts +2 -2
- package/dist/operations.js +3 -2
- package/dist/policy-BeyQ0vnc.js +51 -0
- package/dist/runtime.d.ts +2 -2
- package/dist/runtime.js +1 -1
- package/dist/{state-BU-zcLNY.js → state-Fq3rGFO3.js} +9 -12
- package/dist/{types-CMyR1JeW.d.ts → types-OzukEqHf.d.ts} +30 -5
- package/dist/vite.d.ts +4 -2
- package/dist/vite.js +122 -68
- package/package.json +3 -3
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
|
|
2
|
+
import { parseDuration } from "@vite-hub/runtime";
|
|
3
|
+
//#region src/policy.ts
|
|
4
|
+
const rateLimitPolicyKeys = /* @__PURE__ */ new Set([
|
|
5
|
+
"enforcement",
|
|
6
|
+
"failure",
|
|
7
|
+
"limit",
|
|
8
|
+
"window"
|
|
9
|
+
]);
|
|
10
|
+
function parseRateLimitWindow(value) {
|
|
11
|
+
const windowMs = parseDuration(value, "window", "ceil");
|
|
12
|
+
if (windowMs <= 0 || windowMs > 864e13) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0032({ message: "[vitehub] Rate Limit window must resolve to milliseconds greater than zero and at most 8640000000000000." });
|
|
13
|
+
return windowMs;
|
|
14
|
+
}
|
|
15
|
+
function normalizeRateLimitPolicy(policy) {
|
|
16
|
+
if (!policy || typeof policy !== "object" || Array.isArray(policy)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0033({ message: "[vitehub] Rate Limit policy must be an object." });
|
|
17
|
+
const limit = Object.hasOwn(policy, "limit") ? policy.limit : void 0;
|
|
18
|
+
const duration = Object.hasOwn(policy, "window") ? policy.window : void 0;
|
|
19
|
+
const enforcement = Object.hasOwn(policy, "enforcement") ? policy.enforcement : void 0;
|
|
20
|
+
const failure = Object.hasOwn(policy, "failure") ? policy.failure : void 0;
|
|
21
|
+
if (limit === void 0 || !Number.isInteger(limit) || limit <= 0) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0034({ message: "[vitehub] Rate Limit limit must be a positive integer." });
|
|
22
|
+
if (typeof duration !== "string") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0031({ message: `[vitehub] Rate Limit window must be a duration string such as "10s", "1m", "1h", or "1d", not ${typeof duration === "number" ? `the number ${duration}` : `a ${typeof duration}`}.` });
|
|
23
|
+
if (enforcement !== void 0 && enforcement !== "best-effort" && enforcement !== "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0035({ message: "[vitehub] Rate Limit enforcement must be \"best-effort\" or \"strict\"." });
|
|
24
|
+
if (failure !== void 0 && failure !== "allow" && failure !== "deny") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0036({ message: "[vitehub] Rate Limit failure must be \"allow\" or \"deny\"." });
|
|
25
|
+
return {
|
|
26
|
+
enforcement: enforcement ?? "best-effort",
|
|
27
|
+
failure: failure ?? "deny",
|
|
28
|
+
limit,
|
|
29
|
+
window: duration,
|
|
30
|
+
windowMs: parseRateLimitWindow(duration)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function rateLimitPolicyKey(policy) {
|
|
34
|
+
const { enforcement, failure, limit, windowMs } = normalizeRateLimitPolicy(policy);
|
|
35
|
+
return JSON.stringify([
|
|
36
|
+
enforcement,
|
|
37
|
+
failure,
|
|
38
|
+
limit,
|
|
39
|
+
windowMs
|
|
40
|
+
]);
|
|
41
|
+
}
|
|
42
|
+
function declaredRateLimitPolicy(policy) {
|
|
43
|
+
return {
|
|
44
|
+
enforcement: policy.enforcement,
|
|
45
|
+
failure: policy.failure,
|
|
46
|
+
limit: policy.limit,
|
|
47
|
+
window: policy.window
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
export { rateLimitPolicyKeys as a, rateLimitPolicyKey as i, normalizeRateLimitPolicy as n, parseRateLimitWindow as r, declaredRateLimitPolicy as t };
|
package/dist/runtime.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { r as RateLimitKVStorage } from "./kv-
|
|
1
|
+
import { O as RateLimitRuntimeConfig } from "./types-OzukEqHf.js";
|
|
2
|
+
import { r as RateLimitKVStorage } from "./kv-Cw_jK6Gu.js";
|
|
3
3
|
//#region src/runtime/state.d.ts
|
|
4
4
|
/** The KV store of the `kv` driver. The generated Nitro plugin passes it from `@vite-hub/kv`. */
|
|
5
5
|
interface RateLimitKVRuntime {
|
package/dist/runtime.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as setRateLimitRuntimeConfig, i as resolveRateLimitDriver, t as getRateLimitRuntimeConfig } from "./state-
|
|
1
|
+
import { a as setRateLimitRuntimeConfig, i as resolveRateLimitDriver, t as getRateLimitRuntimeConfig } from "./state-Fq3rGFO3.js";
|
|
2
2
|
export { getRateLimitRuntimeConfig, resolveRateLimitDriver, setRateLimitRuntimeConfig };
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { i as
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
|
|
2
|
+
import { i as rateLimitPolicyKey } from "./policy-BeyQ0vnc.js";
|
|
3
|
+
import { n as createRateLimiter, t as resolveKVRateLimitDriver } from "./kv-provider-DlgNQC-o.js";
|
|
3
4
|
import { kvRateLimitDriver } from "./drivers/kv.js";
|
|
4
5
|
import { memoryRateLimitDriver } from "./drivers/memory.js";
|
|
5
6
|
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
@@ -54,24 +55,20 @@ async function resolveRateLimitDriver() {
|
|
|
54
55
|
});
|
|
55
56
|
return await pending;
|
|
56
57
|
}
|
|
57
|
-
function policyKey(policy) {
|
|
58
|
-
return JSON.stringify([
|
|
59
|
-
policy.enforcement,
|
|
60
|
-
policy.failure,
|
|
61
|
-
policy.limit,
|
|
62
|
-
normalizeRateLimitPolicy(policy).windowMs
|
|
63
|
-
]);
|
|
64
|
-
}
|
|
65
58
|
/** The Rate Limiter of one name and policy in this process. `kv` limiters share their counters through KV. */
|
|
66
59
|
function getRuntimeRateLimiter(driver, name, policy) {
|
|
67
60
|
const all = limiters();
|
|
68
61
|
let policies = all.get(name);
|
|
69
|
-
const key =
|
|
62
|
+
const key = rateLimitPolicyKey(policy);
|
|
70
63
|
const existing = policies?.get(key);
|
|
71
64
|
if (existing) return existing;
|
|
65
|
+
const config = getRateLimitRuntimeConfig();
|
|
72
66
|
const limiter = createRateLimiter({
|
|
73
67
|
...policy,
|
|
74
|
-
driver: driver === "kv" ? kvRateLimitDriver({
|
|
68
|
+
driver: driver === "kv" ? kvRateLimitDriver({
|
|
69
|
+
namespace: config.driver === "cloudflare" ? config.namespace : void 0,
|
|
70
|
+
storage: requireKVRuntime().storage
|
|
71
|
+
}) : memoryRateLimitDriver(),
|
|
75
72
|
name
|
|
76
73
|
});
|
|
77
74
|
if (!policies) {
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { Result, ViteHubContext } from "@vite-hub/runtime";
|
|
1
|
+
import { Duration, Result, ViteHubContext } from "@vite-hub/runtime";
|
|
2
2
|
//#region src/types.d.ts
|
|
3
3
|
type MaybePromise<T> = Promise<T> | T;
|
|
4
|
-
type RateLimitWindow = `${number}ms` | `${number}s` | `${number}m` | `${number}h` | `${number}d`;
|
|
5
4
|
type RateLimitEnforcement = "best-effort" | "strict";
|
|
6
5
|
type RateLimitFailurePolicy = "allow" | "deny";
|
|
7
6
|
type RateLimitCounterScope = "global" | "location" | "process";
|
|
@@ -10,7 +9,8 @@ interface RateLimitPolicy {
|
|
|
10
9
|
enforcement?: RateLimitEnforcement;
|
|
11
10
|
failure?: RateLimitFailurePolicy;
|
|
12
11
|
limit: number;
|
|
13
|
-
window
|
|
12
|
+
/** The length of the window, such as `"10s"`, `"1m"`, or `"1 hour"`. */
|
|
13
|
+
window: Duration;
|
|
14
14
|
}
|
|
15
15
|
interface CheckRateLimitOptions extends RateLimitPolicy {
|
|
16
16
|
key?: string;
|
|
@@ -34,7 +34,7 @@ interface ResolvedRateLimitPolicy {
|
|
|
34
34
|
readonly enforcement: RateLimitEnforcement;
|
|
35
35
|
readonly failure: RateLimitFailurePolicy;
|
|
36
36
|
readonly limit: number;
|
|
37
|
-
readonly window:
|
|
37
|
+
readonly window: Duration;
|
|
38
38
|
readonly windowMs: number;
|
|
39
39
|
}
|
|
40
40
|
interface RateLimitConsumeInput {
|
|
@@ -79,6 +79,8 @@ type RateLimitDecision = RateLimitAllowedDecision | RateLimitLimitedDecision | R
|
|
|
79
79
|
* no `key`. `RATE_LIMIT_R0009`: the Cloudflare Rate Limiting binding of the policy is not on the request.
|
|
80
80
|
*/
|
|
81
81
|
type CheckRateLimitErrorCode = "RATE_LIMIT_R0009" | "RATE_LIMIT_R0013";
|
|
82
|
+
/** The error that `refundRateLimit()` returns. `RATE_LIMIT_R0013`: the request has no client address and the call has no `key`. */
|
|
83
|
+
type RefundRateLimitErrorCode = "RATE_LIMIT_R0013";
|
|
82
84
|
interface RateLimitDriverCapabilities {
|
|
83
85
|
readonly enforcement: RateLimitEnforcement;
|
|
84
86
|
readonly rejectedAttempts: RateLimitRejectedAttemptBehavior;
|
|
@@ -96,6 +98,8 @@ interface RateLimitDriverPeekResult {
|
|
|
96
98
|
type RateLimitDriverPeekOutcome = Result<RateLimitDriverPeekResult>;
|
|
97
99
|
/** `[undefined, undefined]` after the driver deleted the counter, or `[error, undefined]` for an outage. */
|
|
98
100
|
type RateLimitDriverResetOutcome = Result<void>;
|
|
101
|
+
/** `[undefined, undefined]` after the driver gave back one request, or `[error, undefined]` for an outage. */
|
|
102
|
+
type RateLimitDriverRefundOutcome = Result<void>;
|
|
99
103
|
interface RateLimitDriver {
|
|
100
104
|
capabilities: RateLimitDriverCapabilities;
|
|
101
105
|
consume: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverOutcome>;
|
|
@@ -105,6 +109,11 @@ interface RateLimitDriver {
|
|
|
105
109
|
* Rate Limiter then reports `unsupported`.
|
|
106
110
|
*/
|
|
107
111
|
peek?: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverPeekOutcome>;
|
|
112
|
+
/**
|
|
113
|
+
* Gives back one request to the counter of a key in the current window. It does nothing when the counter is at
|
|
114
|
+
* zero. Omit it when the provider cannot give back a request. The Rate Limiter then reports `unsupported`.
|
|
115
|
+
*/
|
|
116
|
+
refund?: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverRefundOutcome>;
|
|
108
117
|
/** Deletes the counter of a key. Omit it when the provider cannot reset a counter. */
|
|
109
118
|
reset?: (input: RateLimitDriverInput) => MaybePromise<RateLimitDriverResetOutcome>;
|
|
110
119
|
}
|
|
@@ -134,12 +143,26 @@ type RateLimitResetResult = {
|
|
|
134
143
|
cause: unknown;
|
|
135
144
|
status: "unavailable";
|
|
136
145
|
};
|
|
146
|
+
type RateLimitRefundResult = {
|
|
147
|
+
status: "refunded";
|
|
148
|
+
} | {
|
|
149
|
+
reason: string;
|
|
150
|
+
status: "unsupported";
|
|
151
|
+
} | {
|
|
152
|
+
cause: unknown;
|
|
153
|
+
status: "unavailable";
|
|
154
|
+
};
|
|
137
155
|
interface RateLimiter {
|
|
138
156
|
readonly capabilities: RateLimitDriverCapabilities;
|
|
139
157
|
consume: (input: RateLimitConsumeInput) => Promise<RateLimitDecision>;
|
|
140
158
|
/** Reads the counter of a key without consuming a token. */
|
|
141
159
|
peek: (input: RateLimitConsumeInput) => Promise<RateLimitPeekResult>;
|
|
142
160
|
policy: ResolvedRateLimitPolicy;
|
|
161
|
+
/**
|
|
162
|
+
* Gives back one request of a key in the current window, for example when the work that the request paid for
|
|
163
|
+
* failed. Refund only a request that the limiter allowed.
|
|
164
|
+
*/
|
|
165
|
+
refund: (input: RateLimitConsumeInput) => Promise<RateLimitRefundResult>;
|
|
143
166
|
/** Deletes the counter of a key, so the next request starts a new window. */
|
|
144
167
|
reset: (input: RateLimitConsumeInput) => Promise<RateLimitResetResult>;
|
|
145
168
|
}
|
|
@@ -170,6 +193,8 @@ interface RateLimitOptions {
|
|
|
170
193
|
}
|
|
171
194
|
interface RateLimitRuntimeConfig {
|
|
172
195
|
driver: Exclude<RateLimitDriverName, "auto">;
|
|
196
|
+
/** Cloudflare deployment namespace for policies counted in KV. */
|
|
197
|
+
namespace?: string;
|
|
173
198
|
/**
|
|
174
199
|
* With the `kv` driver: count in the memory of this process, with a warning, when the KV store cannot share counts.
|
|
175
200
|
* Without it, such a store fails with `RATE_LIMIT_KV_RUNTIME_STORE_UNSUPPORTED`. ViteHub sets it in `vite dev` and when it selects `kv` itself.
|
|
@@ -177,4 +202,4 @@ interface RateLimitRuntimeConfig {
|
|
|
177
202
|
memoryFallback?: boolean;
|
|
178
203
|
}
|
|
179
204
|
//#endregion
|
|
180
|
-
export {
|
|
205
|
+
export { RefundRateLimitErrorCode as A, RateLimitRefundResult as C, RateLimitResetResult as D, RateLimitRequestEvent as E, ResolvedRateLimitPolicy as M, RateLimitRuntimeConfig as O, RateLimitPolicy as S, RateLimitRequest as T, RateLimitDriverResult as _, RateLimitCounterScope as a, RateLimitOptions as b, RateLimitDriver as c, RateLimitDriverName as d, RateLimitDriverOutcome as f, RateLimitDriverResetOutcome as g, RateLimitDriverRefundOutcome as h, RateLimitConsumeInput as i, RequireRateLimitOptions as j, RateLimiter as k, RateLimitDriverCapabilities as l, RateLimitDriverPeekResult as m, CheckRateLimitOptions as n, RateLimitDecision as o, RateLimitDriverPeekOutcome as p, CreateRateLimiterOptions as r, RateLimitDeclaration as s, CheckRateLimitErrorCode as t, RateLimitDriverInput as u, RateLimitEnforcement as v, RateLimitRejectedAttemptBehavior as w, RateLimitPeekResult as x, RateLimitFailurePolicy as y };
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as ViteHubCliPluginMetadata } from "./cli-szm60zN5.js";
|
|
2
|
-
import {
|
|
3
|
-
import { n as OperationContributionEntry } from "./operation-definition-
|
|
2
|
+
import { b as RateLimitOptions, s as RateLimitDeclaration } from "./types-OzukEqHf.js";
|
|
3
|
+
import { n as OperationContributionEntry } from "./operation-definition-nmRu_O3V.js";
|
|
4
4
|
import { Plugin } from "vite";
|
|
5
5
|
//#region ../internal/src/durability.d.ts
|
|
6
6
|
/**
|
|
@@ -407,6 +407,8 @@ interface ViteHubConsoleDocumentHint {
|
|
|
407
407
|
* failing without a reason.
|
|
408
408
|
*/
|
|
409
409
|
interface ViteHubConsoleDocumentSetup {
|
|
410
|
+
/** The project has GitHub Sources but no document collections. */
|
|
411
|
+
sourceHeadsOnly?: true;
|
|
410
412
|
/** Present when no user can read anything because the owner has no access policy. */
|
|
411
413
|
access?: ViteHubConsoleDocumentHint;
|
|
412
414
|
/**
|
package/dist/vite.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { a as rateLimitPolicyKeys, i as
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-DRuEG4wu.js";
|
|
2
|
+
import { a as rateLimitPolicyKeys, i as rateLimitPolicyKey, n as normalizeRateLimitPolicy, t as declaredRateLimitPolicy } from "./policy-BeyQ0vnc.js";
|
|
3
|
+
import { n as createRateLimiter, t as resolveKVRateLimitDriver } from "./kv-provider-DlgNQC-o.js";
|
|
3
4
|
import { kvRateLimitDriver } from "./drivers/kv.js";
|
|
4
5
|
import { memoryRateLimitDriver } from "./drivers/memory.js";
|
|
5
|
-
import { n as getCloudflareRateLimitBindingName, t as cloudflareRateLimitDriver } from "./cloudflare-
|
|
6
|
+
import { n as getCloudflareRateLimitBindingName, r as isCloudflareRateLimitWindow, t as cloudflareRateLimitDriver } from "./cloudflare-_Tz3DcpB.js";
|
|
6
7
|
import { i as resolve$1, n as relativeDefinitionFile, r as dirname$1 } from "./inspect-B6gTdgy9.js";
|
|
7
|
-
import { C as isServerEnvironment, D as readViteHubDevServerFile, M as cloneRecord, N as isRecord, P as isRecordOrFunction, S as getResolvedFeatureOptions, T as shouldSkipViteProviderBuild, _ as invariant, b as createNoExternalAddition, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, m as operationRpcPath, r as collectOperationContributions,
|
|
8
|
+
import { C as isServerEnvironment, D as readViteHubDevServerFile, F as internalErrorDiagnostics, M as cloneRecord, N as isRecord, P as isRecordOrFunction, S as getResolvedFeatureOptions, T as shouldSkipViteProviderBuild, _ as invariant, b as createNoExternalAddition, j as writeViteHubDevServerFile, k as removeViteHubDevServerFile, m as operationRpcPath, r as collectOperationContributions, w as resolveViteHubProjectRoot, x as getDeploymentHost, y as VITEHUB_PROJECT_ROOT } from "./operations-q0ieloSJ.js";
|
|
8
9
|
import { t as addViteHubDevPeerDevHandler } from "./dev-peer-CHafxbtj.js";
|
|
9
10
|
import { formatDiagnostic } from "nostics";
|
|
10
11
|
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
@@ -19,6 +20,7 @@ import { Visitor, parseSync } from "vite";
|
|
|
19
20
|
* the file instead of the terminal.
|
|
20
21
|
*/
|
|
21
22
|
const viteHubHintsFile = ".vitehub/hints.json";
|
|
23
|
+
const VITEHUB_NUXT_HINTS = "__vitehubNuxtHints";
|
|
22
24
|
const runsKey = Symbol.for("vitehub.hints.runs");
|
|
23
25
|
const shared = globalThis;
|
|
24
26
|
const runs = shared[runsKey] ??= /* @__PURE__ */ new Map();
|
|
@@ -53,10 +55,13 @@ function write(run) {
|
|
|
53
55
|
writeFileSync(run.file, `${JSON.stringify(run.report, null, 2)}\n`);
|
|
54
56
|
}
|
|
55
57
|
/**
|
|
56
|
-
* Reports a hint from a Vite plugin hook: prints it once with its fix and docs link, and adds it to
|
|
58
|
+
* Reports a hint from a Vite plugin hook, or from a Nitro or Nuxt hook of the same build: prints it once with its fix and docs link, and adds it to
|
|
57
59
|
* {@link viteHubHintsFile}. Build the diagnostic from the package's nostics catalog, so its code has a docs page.
|
|
58
60
|
*/
|
|
59
61
|
function reportViteHubHint(config, diagnostic) {
|
|
62
|
+
if (skipHints(config)) return;
|
|
63
|
+
const nuxt = config[VITEHUB_NUXT_HINTS];
|
|
64
|
+
if (typeof nuxt === "function") return nuxt(diagnostic);
|
|
60
65
|
const run = runs.get(hintsFile(config)) ?? startRun(config);
|
|
61
66
|
const hint = {
|
|
62
67
|
code: diagnostic.code,
|
|
@@ -70,17 +75,20 @@ function reportViteHubHint(config, diagnostic) {
|
|
|
70
75
|
run.keys.add(key);
|
|
71
76
|
run.report.hints.push(hint);
|
|
72
77
|
write(run);
|
|
73
|
-
config.logger.warn(formatDiagnostic(diagnostic));
|
|
78
|
+
(config.logger ?? console).warn(formatDiagnostic(diagnostic));
|
|
79
|
+
}
|
|
80
|
+
function skipHints(config) {
|
|
81
|
+
return !config.command || Reflect.get(config, "__vitehubPrepare") === true || Reflect.get(config, "vitehubCliDiscovery") === true;
|
|
74
82
|
}
|
|
75
83
|
/**
|
|
76
84
|
* Starts the hints of a build or dev server: writes an empty {@link viteHubHintsFile}, so a run without hints does not
|
|
77
85
|
* leave the hints of an earlier run in place. Every plugin that reports hints calls it from `configResolved`, so a
|
|
78
|
-
* package used without `vitehub()` starts its own run.
|
|
79
|
-
*
|
|
86
|
+
* package used without `vitehub()` starts its own run. Nuxt uses the app instance as owner so its Vite builds and
|
|
87
|
+
* separate Nitro build share one report; replay, prepare and discovery never reset it.
|
|
80
88
|
*/
|
|
81
|
-
function startViteHubHints(config) {
|
|
82
|
-
if (started.has(
|
|
83
|
-
started.add(
|
|
89
|
+
function startViteHubHints(config, owner = config) {
|
|
90
|
+
if (skipHints(config) || config["__vitehubNuxtHints"] || started.has(owner)) return;
|
|
91
|
+
started.add(owner);
|
|
84
92
|
write(startRun(config));
|
|
85
93
|
}
|
|
86
94
|
//#endregion
|
|
@@ -845,8 +853,12 @@ function getHostingProvider(hosting) {
|
|
|
845
853
|
//#endregion
|
|
846
854
|
//#region src/discovery.ts
|
|
847
855
|
const rateLimitImports = /* @__PURE__ */ new Set(["@vite-hub/rate-limit", "vite-hub/rate-limit"]);
|
|
848
|
-
/** Functions whose calls declare a managed Rate Limit.
|
|
849
|
-
const rateLimitGuards = [
|
|
856
|
+
/** Functions whose calls declare a managed Rate Limit. They use the same counters. */
|
|
857
|
+
const rateLimitGuards = [
|
|
858
|
+
"checkRateLimit",
|
|
859
|
+
"refundRateLimit",
|
|
860
|
+
"requireRateLimit"
|
|
861
|
+
];
|
|
850
862
|
function isRateLimitGuard(name) {
|
|
851
863
|
return rateLimitGuards.some((guard) => guard === name);
|
|
852
864
|
}
|
|
@@ -1263,7 +1275,7 @@ function discoverRateLimitCatalog(options, snapshots = /* @__PURE__ */ new Map()
|
|
|
1263
1275
|
} else snapshots.delete(file);
|
|
1264
1276
|
for (const declaration of extracted) {
|
|
1265
1277
|
const existing = declarations.get(declaration.name);
|
|
1266
|
-
if (existing &&
|
|
1278
|
+
if (existing && rateLimitPolicyKey(existing.policy) !== rateLimitPolicyKey(declaration.policy)) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0003({ message: [
|
|
1267
1279
|
`[vitehub] Conflicting Rate Limit policies for ID "${declaration.name}":`,
|
|
1268
1280
|
` - ${existing.source.file}:${existing.source.line}:${existing.source.column} ${JSON.stringify(existing.policy)}`,
|
|
1269
1281
|
` - ${declaration.source.file}:${declaration.source.line}:${declaration.source.column} ${JSON.stringify(declaration.policy)}`
|
|
@@ -1334,6 +1346,50 @@ const rateLimitConsoleSection = {
|
|
|
1334
1346
|
}
|
|
1335
1347
|
};
|
|
1336
1348
|
//#endregion
|
|
1349
|
+
//#region src/internal/cloudflare-bindings.ts
|
|
1350
|
+
function namespaceId(namespace, rateLimitId) {
|
|
1351
|
+
let hash = 2166136261;
|
|
1352
|
+
for (const character of `${namespace}:${rateLimitId}`) {
|
|
1353
|
+
hash ^= character.charCodeAt(0);
|
|
1354
|
+
hash = Math.imul(hash, 16777619);
|
|
1355
|
+
}
|
|
1356
|
+
return String(hash >>> 0 || 1);
|
|
1357
|
+
}
|
|
1358
|
+
/** True when the Cloudflare Rate Limiting binding counts this Rate Limit. Other windows count in KV. */
|
|
1359
|
+
function usesCloudflareBinding(declaration) {
|
|
1360
|
+
return isCloudflareRateLimitWindow(normalizeRateLimitPolicy(declaration.policy).windowMs);
|
|
1361
|
+
}
|
|
1362
|
+
function cloudflareSimpleLimit(declaration) {
|
|
1363
|
+
const policy = normalizeRateLimitPolicy(declaration.policy);
|
|
1364
|
+
if (policy.enforcement === "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0015({ message: `Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.` });
|
|
1365
|
+
return {
|
|
1366
|
+
limit: policy.limit,
|
|
1367
|
+
period: policy.windowMs / 1e3
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
/**
|
|
1371
|
+
* Throws the build error for the first policy that Cloudflare cannot run: strict enforcement on the binding, or a
|
|
1372
|
+
* window other than 10 or 60 seconds when the default KV store, which uses `kvDriver`, cannot share its counts.
|
|
1373
|
+
*/
|
|
1374
|
+
function assertCloudflareRateLimitPolicies(declarations, kvDriver) {
|
|
1375
|
+
for (const declaration of declarations) {
|
|
1376
|
+
if (usesCloudflareBinding(declaration)) {
|
|
1377
|
+
cloudflareSimpleLimit(declaration);
|
|
1378
|
+
continue;
|
|
1379
|
+
}
|
|
1380
|
+
if (resolveKVRateLimitDriver(kvDriver) === "kv") continue;
|
|
1381
|
+
const store = kvDriver ? `the default KV store uses ${kvDriver}, which has no shared atomic increment` : "the app has no KV store";
|
|
1382
|
+
throw rateLimitErrorDiagnostics.RATE_LIMIT_R0016({ message: `Rate Limit "${declaration.name}" uses ${declaration.policy.window}. Cloudflare Rate Limiting supports only 10s and 1m windows, so ViteHub counts other windows in KV, but ${store}.` });
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
function createCloudflareRateLimitBindings(declarations, namespace) {
|
|
1386
|
+
return declarations.filter(usesCloudflareBinding).map((declaration) => ({
|
|
1387
|
+
name: getCloudflareRateLimitBindingName(declaration.name),
|
|
1388
|
+
namespace_id: namespaceId(namespace, declaration.name),
|
|
1389
|
+
simple: cloudflareSimpleLimit(declaration)
|
|
1390
|
+
}));
|
|
1391
|
+
}
|
|
1392
|
+
//#endregion
|
|
1337
1393
|
//#region src/internal/manifest.ts
|
|
1338
1394
|
const rateLimitManifestPath = ".vitehub/rate-limit/manifest.json";
|
|
1339
1395
|
const unusedResult = async () => [void 0, void 0];
|
|
@@ -1350,14 +1406,16 @@ function resolveProviderCapabilities(provider) {
|
|
|
1350
1406
|
}).capabilities;
|
|
1351
1407
|
}
|
|
1352
1408
|
function createRateLimitManifest(declarations, provider) {
|
|
1353
|
-
const capabilities = resolveProviderCapabilities(provider);
|
|
1354
1409
|
return {
|
|
1355
1410
|
schemaVersion: 2,
|
|
1356
|
-
rateLimits: [...declarations].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0).map((definition) =>
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1411
|
+
rateLimits: [...declarations].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0).map((definition) => {
|
|
1412
|
+
const counter = provider === "cloudflare" && !usesCloudflareBinding(definition) ? "kv" : provider;
|
|
1413
|
+
return {
|
|
1414
|
+
name: definition.name,
|
|
1415
|
+
provider: counter,
|
|
1416
|
+
capabilities: resolveProviderCapabilities(counter)
|
|
1417
|
+
};
|
|
1418
|
+
})
|
|
1361
1419
|
};
|
|
1362
1420
|
}
|
|
1363
1421
|
async function writeRateLimitManifest(rootDir, declarations, provider) {
|
|
@@ -1365,37 +1423,6 @@ async function writeRateLimitManifest(rootDir, declarations, provider) {
|
|
|
1365
1423
|
await writeFileIfChanged(resolve(rootDir, rateLimitManifestPath), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
1366
1424
|
}
|
|
1367
1425
|
//#endregion
|
|
1368
|
-
//#region src/internal/cloudflare-bindings.ts
|
|
1369
|
-
function namespaceId(namespace, rateLimitId) {
|
|
1370
|
-
let hash = 2166136261;
|
|
1371
|
-
for (const character of `${namespace}:${rateLimitId}`) {
|
|
1372
|
-
hash ^= character.charCodeAt(0);
|
|
1373
|
-
hash = Math.imul(hash, 16777619);
|
|
1374
|
-
}
|
|
1375
|
-
return String(hash >>> 0 || 1);
|
|
1376
|
-
}
|
|
1377
|
-
function cloudflareSimpleLimit(declaration) {
|
|
1378
|
-
const policy = normalizeRateLimitPolicy(declaration.policy);
|
|
1379
|
-
if (policy.enforcement === "strict") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0015({ message: `Rate Limit "${declaration.name}" requires strict enforcement, but Cloudflare's native Rate Limiting binding is best-effort.` });
|
|
1380
|
-
const period = policy.windowMs / 1e3;
|
|
1381
|
-
if (period !== 10 && period !== 60) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0016({ message: `Rate Limit "${declaration.name}" uses ${policy.window}, but Cloudflare Rate Limiting supports only 10s and 1m windows.` });
|
|
1382
|
-
return {
|
|
1383
|
-
limit: policy.limit,
|
|
1384
|
-
period
|
|
1385
|
-
};
|
|
1386
|
-
}
|
|
1387
|
-
/** Throws the build error for the first policy that a Cloudflare Rate Limiting binding cannot run. */
|
|
1388
|
-
function assertCloudflareRateLimitPolicies(declarations) {
|
|
1389
|
-
for (const declaration of declarations) cloudflareSimpleLimit(declaration);
|
|
1390
|
-
}
|
|
1391
|
-
function createCloudflareRateLimitBindings(declarations, namespace) {
|
|
1392
|
-
return declarations.map((declaration) => ({
|
|
1393
|
-
name: getCloudflareRateLimitBindingName(declaration.name),
|
|
1394
|
-
namespace_id: namespaceId(namespace, declaration.name),
|
|
1395
|
-
simple: cloudflareSimpleLimit(declaration)
|
|
1396
|
-
}));
|
|
1397
|
-
}
|
|
1398
|
-
//#endregion
|
|
1399
1426
|
//#region src/vite.ts
|
|
1400
1427
|
const operationsModule = ownModule(import.meta.url, "operations");
|
|
1401
1428
|
const runtimeModule = ownModule(import.meta.url, "runtime");
|
|
@@ -1403,10 +1430,14 @@ const packageName = "@vite-hub/rate-limit";
|
|
|
1403
1430
|
const pluginName = "@vite-hub/rate-limit/vite";
|
|
1404
1431
|
const generatedNitroPlugin = ".vitehub/nitro/rate-limit/plugin.ts";
|
|
1405
1432
|
const mergeNoExternal = createNoExternalAddition(packageName);
|
|
1433
|
+
/** The driver of the default KV store, or `undefined` when the app has no KV. */
|
|
1434
|
+
function kvStoreDriver(config, build = false) {
|
|
1435
|
+
const api = (config.plugins?.find((plugin) => plugin.name === "@vite-hub/kv/vite"))?.api;
|
|
1436
|
+
const kv = (build ? api?.getBuildConfig?.() : void 0)?.kv ?? api?.getConfig?.().kv;
|
|
1437
|
+
return kv ? kv.store.driver : void 0;
|
|
1438
|
+
}
|
|
1406
1439
|
function effectiveDriver(driver, config) {
|
|
1407
|
-
|
|
1408
|
-
const kv = (config.plugins?.find((plugin) => plugin.name === "@vite-hub/kv/vite"))?.api?.getConfig?.().kv;
|
|
1409
|
-
return resolveKVRateLimitDriver(kv ? kv.store.driver : void 0);
|
|
1440
|
+
return driver === "kv" ? resolveKVRateLimitDriver(kvStoreDriver(config)) : driver;
|
|
1410
1441
|
}
|
|
1411
1442
|
function mergeNitroConfig(config, value, declarations, namespace, driver, nitroCloudflare, projectRoot) {
|
|
1412
1443
|
const providerOutput = useProviderOutputCatalog(config);
|
|
@@ -1424,7 +1455,21 @@ function mergeNitroConfig(config, value, declarations, namespace, driver, nitroC
|
|
|
1424
1455
|
});
|
|
1425
1456
|
return composeNitroCloudflareProviderOutput(providerOutput, baseNitro, value);
|
|
1426
1457
|
}
|
|
1427
|
-
|
|
1458
|
+
/**
|
|
1459
|
+
* `kvWindows`: on Cloudflare, a Rate Limit uses a window that the binding does not support, so it counts in KV.
|
|
1460
|
+
*/
|
|
1461
|
+
function renderRuntimeInstaller(runtimeConfig, kvImport, kvWindows) {
|
|
1462
|
+
if (runtimeConfig.driver === "cloudflare" && kvWindows) return [
|
|
1463
|
+
"import { definePlugin } from 'nitro'",
|
|
1464
|
+
`import { setRateLimitRuntimeConfig } from ${JSON.stringify(runtimeModule)}`,
|
|
1465
|
+
`import { getKVStoreDriver, kv } from ${JSON.stringify(kvImport)}`,
|
|
1466
|
+
"",
|
|
1467
|
+
`const config = ${JSON.stringify(runtimeConfig)}`,
|
|
1468
|
+
"export default definePlugin(() => {",
|
|
1469
|
+
" setRateLimitRuntimeConfig(config, { driver: () => getKVStoreDriver(), storage: kv, store: 'default' })",
|
|
1470
|
+
"})",
|
|
1471
|
+
""
|
|
1472
|
+
].join("\n");
|
|
1428
1473
|
if (runtimeConfig.driver !== "kv") return [
|
|
1429
1474
|
"import { definePlugin } from 'nitro'",
|
|
1430
1475
|
`import { setRateLimitRuntimeConfig } from ${JSON.stringify(runtimeModule)}`,
|
|
@@ -1490,15 +1535,20 @@ function hubRateLimit(options = {}) {
|
|
|
1490
1535
|
const refreshDeclarations = async () => {
|
|
1491
1536
|
if (!projectRoot || !resolved) return;
|
|
1492
1537
|
collectDeclarations();
|
|
1493
|
-
if (checkCloudflarePolicies) assertCloudflareRateLimitPolicies(declarations);
|
|
1538
|
+
if (checkCloudflarePolicies) assertCloudflareRateLimitPolicies(declarations, kvStoreDriver(resolved, true));
|
|
1494
1539
|
await writeRateLimitManifest(projectRoot, declarations, effectiveDriver(driver, resolved));
|
|
1495
1540
|
};
|
|
1496
1541
|
const assertBuildDriver = () => {
|
|
1497
1542
|
if (!resolved || resolved.command !== "build") return;
|
|
1498
|
-
|
|
1543
|
+
const effective = effectiveDriver(driver, resolved);
|
|
1544
|
+
if (effective === "cloudflare") {
|
|
1545
|
+
assertCloudflareRateLimitPolicies(declarations, kvStoreDriver(resolved));
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
if (effective !== "memory") return;
|
|
1499
1549
|
if (driver === "kv" && !rateLimit.memoryFallback) {
|
|
1500
|
-
const kv = resolved
|
|
1501
|
-
const store = kv ? `the default KV store uses ${kv
|
|
1550
|
+
const kv = kvStoreDriver(resolved);
|
|
1551
|
+
const store = kv ? `the default KV store uses ${kv}, which has no shared atomic increment` : "the app has no KV store";
|
|
1502
1552
|
throw rateLimitErrorDiagnostics.RATE_LIMIT_KV_STORE_UNSUPPORTED({ message: `[vitehub] rateLimit.driver is "kv", but ${store}. Each server process would count in its own memory.` });
|
|
1503
1553
|
}
|
|
1504
1554
|
const strict = declarations.find((declaration) => normalizeRateLimitPolicy(declaration.policy).enforcement === "strict");
|
|
@@ -1510,14 +1560,24 @@ function hubRateLimit(options = {}) {
|
|
|
1510
1560
|
warnedAboutMemory = true;
|
|
1511
1561
|
};
|
|
1512
1562
|
const inspectionRoot = () => projectRoot ?? resolveViteHubProjectRoot(process.cwd(), { projectRoot: rateLimit.projectRoot });
|
|
1563
|
+
async function writeRuntimeOutput(config, root) {
|
|
1564
|
+
const runtimeConfig = { driver };
|
|
1565
|
+
if (driver === "kv" && (rateLimit.memoryFallback === true || config.command === "serve")) runtimeConfig.memoryFallback = true;
|
|
1566
|
+
const kvWindows = driver === "cloudflare" && !declarations.every(usesCloudflareBinding);
|
|
1567
|
+
const namespace = resolveRateLimitNamespace(rateLimit.namespace);
|
|
1568
|
+
if (kvWindows && namespace) runtimeConfig.namespace = namespace;
|
|
1569
|
+
await writeRateLimitManifest(root, declarations, effectiveDriver(driver, config));
|
|
1570
|
+
await writeFileIfChanged(resolve(root, generatedNitroPlugin), renderRuntimeInstaller(runtimeConfig, kvImport, kvWindows));
|
|
1571
|
+
}
|
|
1513
1572
|
return {
|
|
1514
|
-
api: { validateNitroBuild(config) {
|
|
1573
|
+
api: { async validateNitroBuild(config) {
|
|
1515
1574
|
resolved = config;
|
|
1516
1575
|
rateLimit = getResolvedFeatureOptions(config, "rateLimit") ?? rateLimit;
|
|
1517
1576
|
projectRoot = resolveViteHubProjectRoot(config.root, { projectRoot: rateLimit.projectRoot });
|
|
1518
1577
|
driver = resolveDriver(rateLimit, config.command, config.nitro);
|
|
1519
1578
|
collectDeclarations();
|
|
1520
1579
|
assertBuildDriver();
|
|
1580
|
+
await writeRuntimeOutput(config, projectRoot);
|
|
1521
1581
|
} },
|
|
1522
1582
|
name: pluginName,
|
|
1523
1583
|
enforce: "pre",
|
|
@@ -1582,15 +1642,9 @@ function hubRateLimit(options = {}) {
|
|
|
1582
1642
|
cloudflareBindings = nitroCloudflare && driver === "cloudflare";
|
|
1583
1643
|
checkCloudflarePolicies = config.command === "serve" && buildTargetsCloudflare(config, rateLimit, configuredNitro);
|
|
1584
1644
|
collectDeclarations();
|
|
1585
|
-
if (checkCloudflarePolicies) assertCloudflareRateLimitPolicies(declarations);
|
|
1645
|
+
if (checkCloudflarePolicies) assertCloudflareRateLimitPolicies(declarations, kvStoreDriver(config, true));
|
|
1586
1646
|
config.nitro = mergeNitroConfig(config, configuredNitro, declarations, resolveRateLimitNamespace(rateLimit.namespace), driver, nitroCloudflare, projectRoot);
|
|
1587
|
-
await
|
|
1588
|
-
const pluginFile = resolve(projectRoot, generatedNitroPlugin);
|
|
1589
|
-
const memoryFallback = driver === "kv" && (rateLimit.memoryFallback === true || config.command === "serve");
|
|
1590
|
-
await writeFileIfChanged(pluginFile, renderRuntimeInstaller(memoryFallback ? {
|
|
1591
|
-
memoryFallback,
|
|
1592
|
-
driver
|
|
1593
|
-
} : { driver }, kvImport));
|
|
1647
|
+
await writeRuntimeOutput(config, projectRoot);
|
|
1594
1648
|
if (driver !== "kv") {
|
|
1595
1649
|
assertBuildDriver();
|
|
1596
1650
|
warnAboutMemory();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vite-hub/rate-limit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "Provider-neutral Rate Limit primitives and Vite deployment integration for ViteHub.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
69
|
"@valibot/to-json-schema": "^1.8.0",
|
|
70
|
-
"@vite-hub/runtime": "0.
|
|
70
|
+
"@vite-hub/runtime": "0.4.0",
|
|
71
71
|
"birpc": "^4.2.0",
|
|
72
72
|
"h3": "^2.0.8",
|
|
73
73
|
"nostics": "1.4.0",
|
|
@@ -93,7 +93,7 @@
|
|
|
93
93
|
}
|
|
94
94
|
},
|
|
95
95
|
"engines": {
|
|
96
|
-
"node": ">=
|
|
96
|
+
"node": ">=24.15.0"
|
|
97
97
|
},
|
|
98
98
|
"scripts": {
|
|
99
99
|
"build": "vp pack",
|