@vite-hub/rate-limit 0.1.0 → 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.
- package/README.md +18 -14
- package/dist/cli-szm60zN5.d.ts +163 -0
- package/dist/cli.d.ts +1 -1
- package/dist/cli.js +12 -26
- package/dist/{cloudflare-DUDRACVB.js → cloudflare-otBvOPv4.js} +5 -4
- package/dist/{counters-pKORpgGd.d.ts → counters-DXpF67J_.d.ts} +3 -3
- package/dist/{counters-wdEMxDEY.js → counters-DgVdHwdL.js} +13 -6
- package/dist/dev-peer-CHafxbtj.js +238 -0
- package/dist/drivers/cloudflare.d.ts +1 -1
- package/dist/drivers/cloudflare.js +1 -1
- package/dist/drivers/kv.d.ts +2 -0
- package/dist/drivers/kv.js +92 -0
- package/dist/drivers/memory.d.ts +1 -1
- package/dist/drivers/memory.js +5 -5
- package/dist/durability.d.ts +12 -0
- package/dist/durability.js +35 -0
- package/dist/error-diagnostics-MgAnhRTP.js +234 -0
- package/dist/index.d.ts +16 -7
- package/dist/index.js +108 -38
- package/dist/{inspect-D-FzyM_x.js → inspect-B6gTdgy9.js} +7 -1
- package/dist/kv-C1wpLulE.d.ts +29 -0
- package/dist/{limiter-DBrMI4vi.js → kv-provider-C1S6dRTR.js} +16 -9
- package/dist/{operations-tNUdj3G4.d.ts → operation-definition-8gOe-ubD.d.ts} +37 -15
- package/dist/operations-BYRa7wpx.js +1355 -0
- package/dist/{operations-Bu-xulNd.js → operations-CLI9w3rO.js} +9 -14
- package/dist/operations.d.ts +9 -4
- package/dist/operations.js +51 -23
- package/dist/runtime.d.ts +21 -3
- package/dist/runtime.js +2 -2
- package/dist/state-BU-zcLNY.js +89 -0
- package/dist/{types-CQEJpgtz.d.ts → types-CMyR1JeW.d.ts} +43 -23
- package/dist/vite.d.ts +131 -21
- package/dist/vite.js +349 -2479
- package/package.json +21 -17
- package/dist/cli-Cniq99iX.d.ts +0 -85
- package/dist/error-diagnostics-CTAC_bbr.js +0 -56
- package/dist/h3-v1-request-qoGwJr5-.js +0 -235
- package/dist/operations-B09NnEjT.js +0 -1438
- package/dist/state-Ct7zR8fD.js +0 -43
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ Install this owner package when you need a direct Rate Limiter, a custom driver,
|
|
|
15
15
|
pnpm add @vite-hub/rate-limit
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
The package requires Node
|
|
18
|
+
The package requires Node.js 22.18 or newer. Vite is an optional peer dependency and is needed only for the managed Vite integration.
|
|
19
19
|
|
|
20
20
|
## Get the first decision
|
|
21
21
|
|
|
@@ -57,7 +57,7 @@ Reset timestamps must also be positive and at most `8.64e15`. The memory driver
|
|
|
57
57
|
3: limited
|
|
58
58
|
```
|
|
59
59
|
|
|
60
|
-
Direct Rate Limiters return a decision. Your code must stop the operation when `allowed` is false. The memory driver performs strict atomic consumption inside one process, so use it for development, tests, or a known single-process host. Its counters do not coordinate across processes, regions, or request-scoped runtimes.
|
|
60
|
+
Direct Rate Limiters return a decision. Your code must stop the operation when `allowed` is false. The memory driver performs strict atomic consumption inside one process, so use it for development, tests, or a known single-process host. A production build of declared Rate Limits does not accept `enforcement: "strict"` on memory. Its counters do not coordinate across processes, regions, or request-scoped runtimes.
|
|
61
61
|
|
|
62
62
|
## Choose managed guards or a direct driver
|
|
63
63
|
|
|
@@ -85,12 +85,12 @@ export default defineConfig({
|
|
|
85
85
|
|
|
86
86
|
Then require a budget before expensive work:
|
|
87
87
|
|
|
88
|
-
```ts
|
|
88
|
+
```ts fragment
|
|
89
89
|
import { requireRateLimit } from "@vite-hub/rate-limit";
|
|
90
90
|
|
|
91
|
-
export async function handleImageUpload(
|
|
92
|
-
await requireRateLimit(
|
|
93
|
-
key:
|
|
91
|
+
export async function handleImageUpload(request: Request, userId: string): Promise<Response> {
|
|
92
|
+
await requireRateLimit(request, "image-upload", {
|
|
93
|
+
key: userId,
|
|
94
94
|
limit: 10,
|
|
95
95
|
window: "1m",
|
|
96
96
|
});
|
|
@@ -99,29 +99,32 @@ export async function handleImageUpload(event): Promise<Response> {
|
|
|
99
99
|
}
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
The stable ID and provider policy must use
|
|
102
|
+
The stable ID and provider policy must use literals, or a `const` with a literal value in the same file, so the Vite integration can discover them and generate provider configuration. The request, `key`, `message`, and `code` are runtime values. `message` and `code` customize the `429` error of `requireRateLimit()`, and `checkRateLimit()` does not take them. The guard takes a Web `Request` or a request event with Standard Context properties, such as an H3 event in a ViteHub app. If you omit `key`, the guard uses the client address of the event and fails when it cannot find one. A `Request` has no client address, so pass `key`, except on Cloudflare, where the guard reads `cf-connecting-ip`.
|
|
103
103
|
|
|
104
|
-
An allowed request continues. An exhausted budget throws an H3 `HTTPError` with status `429`. The default `failure: "deny"` turns an expected driver outage into status `503`; `failure: "allow"` lets the request continue. Use fail-open behavior only when the protected operation is safe without enforcement. Invalid configuration, malformed provider results, missing bindings, and driver defects still throw instead of following the failure policy.
|
|
104
|
+
An allowed request continues. An exhausted budget throws an H3 `HTTPError` with status `429` and the message `Rate limit exceeded.`. Pass `message` to set the message of the `429`, and `code` to set its `data.code`, for example `{ code: "errorTooManyTries", message: "Too many tries. Wait a minute and try again." }`. Both can be runtime values. `checkRateLimit()` does not accept them. The default `failure: "deny"` turns an expected driver outage into status `503`; `failure: "allow"` lets the request continue. Use fail-open behavior only when the protected operation is safe without enforcement. Invalid configuration, malformed provider results, missing bindings, and driver defects still throw instead of following the failure policy.
|
|
105
105
|
|
|
106
|
-
Local Vite development uses the process-local memory driver. A Cloudflare Nitro preset selects Cloudflare Rate Limiting, and every deployed Worker and environment needs a unique namespace. ViteHub has no native Rate Limit driver for Vercel, Netlify, or Deno. Automatic
|
|
106
|
+
Local Vite development uses the process-local memory driver. `driver: "kv"` counts in the default KV store of `@vite-hub/kv` with one atomic `increment` for each request. The Nitro plugin asks KV at boot which driver the store uses: with `redis`, `database`, or `upstash`, every server process shares the counts. An explicit `driver: "kv"` on another driver, such as `fs-lite`, fails the build with `RATE_LIMIT_KV_STORE_UNSUPPORTED`; `vite dev` counts in memory. With ViteHub, a `node` build selects `kv` when KV is on, and `memory` otherwise; when ViteHub selected `kv` and the store cannot share counts, it counts in memory and prints a warning. A build that counts declared Rate Limits in memory prints a warning, and fails with `RATE_LIMIT_MEMORY_STRICT_UNSUPPORTED` for a Rate Limit with `enforcement: "strict"`. A Cloudflare Nitro preset selects Cloudflare Rate Limiting, and every deployed Worker and environment needs a unique namespace. ViteHub has no native Rate Limit driver for Vercel, Netlify, or Deno. Automatic driver selection fails for an unknown production host instead of falling back to unsafe per-instance memory. Select memory explicitly only for a known single-process deployment; otherwise supply a direct production driver. Check the [runtime and host support matrix](https://vitehub.dev/docs/frameworks-hosts/support-matrix) before choosing a deployment target.
|
|
107
107
|
|
|
108
|
-
Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and `1m` windows. It does not report portable remaining, reset, or retry metadata. A policy that requests strict enforcement or another window fails before deployment. The [Cloudflare host guide](https://vitehub.dev/docs/frameworks-hosts/cloudflare#rate-limiting-bindings) covers generated bindings and deployment verification.
|
|
108
|
+
Cloudflare enforcement is best-effort, location-scoped, and limited to `10s` and `1m` windows. It does not report portable remaining, reset, or retry metadata. A policy that requests strict enforcement or another window fails before deployment, and `vite dev` fails the same way when the build targets Cloudflare, although the dev server counts in memory. The [Cloudflare host guide](https://vitehub.dev/docs/frameworks-hosts/cloudflare#rate-limiting-bindings) covers generated bindings and deployment verification.
|
|
109
109
|
|
|
110
110
|
## Supply a direct driver
|
|
111
111
|
|
|
112
|
-
Use `createRateLimiter()` when the application selects the driver and handles the decision. A production driver must implement one atomic `consume()` operation for its backend. A generic KV `get()` followed by `set()` is not safe under concurrent requests.
|
|
112
|
+
Use `createRateLimiter()` when the application selects the driver and handles the decision. A production driver must implement one atomic `consume()` operation for its backend. A generic KV `get()` followed by `set()` is not safe under concurrent requests. `kvRateLimitDriver({ storage })` uses an atomic `increment` instead, so it works with any KV store that has one, for example `kv.store("limits")` from `vite-hub/kv` on Redis or Postgres. Its counters also count rejected requests.
|
|
113
|
+
|
|
114
|
+
The KV driver waits at most one second for each storage operation. A timed-out operation returns `RATE_LIMIT_KV_TIMEOUT`: consume follows the `failure` policy; peek and reset return `unavailable`. The deadline does not cancel the storage operation, so a timed-out consume can still count. KV configuration errors still throw.
|
|
113
115
|
|
|
114
|
-
Drivers return `[
|
|
116
|
+
Drivers return a `Result`: `[undefined, result]` after consuming the counter, and `[error, undefined]` only for an expected operational outage. Return the error of the store when it has one, such as a KV `Result` error, or a `ResultError` from your own `defineErrors()` catalog. The limiter then returns `reason: "unavailable"` and sets `allowed` from the failure policy, which defaults to deny. ViteHub-owned configuration errors, malformed provider results, and implementation defects throw Nostics diagnostics with `RATE_LIMIT_B####` or `RATE_LIMIT_R####` codes. Application driver errors keep their identity. See [Errors and diagnostics](https://vitehub.dev/docs/reference/errors-diagnostics).
|
|
115
117
|
|
|
116
118
|
The limiter exposes its resolved `policy` and the driver's declared `capabilities`, including enforcement, counter scope, rejected-attempt behavior, and supported windows. Inspect them when deciding whether a driver fits a deployment.
|
|
117
119
|
|
|
118
120
|
## Read or reset a counter
|
|
119
121
|
|
|
120
|
-
`limiter.peek({ key })` reads the counter of a key without consuming a token. `limiter.reset({ key })` deletes the counter. A driver supports them through optional `peek(input)` and `reset(input)` methods. Like `consume()`, `peek()` returns `[
|
|
122
|
+
`limiter.peek({ key })` reads the counter of a key without consuming a token. `limiter.reset({ key })` deletes the counter. A driver supports them through optional `peek(input)` and `reset(input)` methods. Like `consume()`, `peek()` returns `[undefined, value]` or `[error, undefined]`. The `reset()` method returns `[undefined, undefined]` or `[error, undefined]`. When the driver omits a method, the result has `status: "unsupported"` and a `reason`.
|
|
121
123
|
|
|
122
124
|
| Driver | `peek()` | `reset()` |
|
|
123
125
|
| ---------- | ------------------------------------------------------------------------- | --------------------- |
|
|
124
126
|
| memory | `used`, `remaining`, and `resetAt` in this process. `used: 0` when no counter exists. | Deletes the counter. |
|
|
127
|
+
| kv | `used`, `remaining`, and `resetAt` of the current window, shared by every process. | Deletes the counter of the current window. |
|
|
125
128
|
| cloudflare | `unsupported`. The binding exposes only `limit()`, which consumes a token. | `unsupported`. |
|
|
126
129
|
|
|
127
130
|
For managed guards, `peekRateLimit(id, key)` and `resetRateLimit(id, key)` use the counters of `requireRateLimit()` in the current runtime. `vitehub rate-limit peek <id> <key>` and `vitehub rate-limit reset <id> <key>` (which asks on a terminal, or needs `--yes`) run the `rate-limit.peek` and `rate-limit.reset` operations of the running app, on the dev server or with `--url` on a deployed app that enables the Console. The Console **Rate Limits** page runs the same operations.
|
|
@@ -132,10 +135,11 @@ For managed guards, `peekRateLimit(id, key)` and `resetRateLimit(id, key)` use t
|
|
|
132
135
|
| ----------------------------------------- | ------------------------------------------------------------------------- |
|
|
133
136
|
| `@vite-hub/rate-limit` | `requireRateLimit()`, `checkRateLimit()`, `createRateLimiter()`, `peekRateLimit()`, `resetRateLimit()`, and public contract types |
|
|
134
137
|
| `@vite-hub/rate-limit/drivers/memory` | Process-local fixed-window driver |
|
|
138
|
+
| `@vite-hub/rate-limit/drivers/kv` | Fixed-window driver on a KV store with an atomic `increment` |
|
|
135
139
|
| `@vite-hub/rate-limit/drivers/cloudflare` | Direct adapter for a request-scoped Cloudflare Rate Limiting binding |
|
|
136
140
|
| `@vite-hub/rate-limit/vite` | Source discovery, Nitro runtime setup, manifest generation, and Cloudflare bindings |
|
|
137
141
|
|
|
138
|
-
`@vite-hub/rate-limit/runtime
|
|
142
|
+
`@vite-hub/rate-limit/runtime` is reserved for framework integrations. Application code should use the guard or a direct Rate Limiter.
|
|
139
143
|
|
|
140
144
|
## Go deeper
|
|
141
145
|
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { Diagnostic } from "nostics";
|
|
2
|
+
//#region ../internal/src/host-credentials.d.ts
|
|
3
|
+
interface HostCliRunResult {
|
|
4
|
+
exitCode: number | null;
|
|
5
|
+
stdout: string;
|
|
6
|
+
}
|
|
7
|
+
/** Runs a host CLI with an argument array and no shell, and returns its stdout. */
|
|
8
|
+
type HostCliRun = (command: string, args: readonly string[], options: {
|
|
9
|
+
cwd?: string;
|
|
10
|
+
env: NodeJS.ProcessEnv;
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
}) => Promise<HostCliRunResult>;
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region ../internal/src/provision.d.ts
|
|
15
|
+
type ProvisionProvider = "cloudflare" | "vercel";
|
|
16
|
+
interface ProvisionLogger {
|
|
17
|
+
log: (message: string) => void;
|
|
18
|
+
warn: (message: string) => void;
|
|
19
|
+
}
|
|
20
|
+
interface ProvisionContext {
|
|
21
|
+
env: Record<string, string | undefined>;
|
|
22
|
+
fetch: typeof globalThis.fetch;
|
|
23
|
+
logger: ProvisionLogger;
|
|
24
|
+
markPlanUnchecked?: () => void;
|
|
25
|
+
}
|
|
26
|
+
interface ProvisionState {
|
|
27
|
+
cloudflare?: Record<string, Record<string, string>>;
|
|
28
|
+
vercel?: Record<string, Record<string, string>>;
|
|
29
|
+
}
|
|
30
|
+
interface ProvisionResult {
|
|
31
|
+
ids?: ProvisionState;
|
|
32
|
+
}
|
|
33
|
+
interface ProvisionAction {
|
|
34
|
+
kind: string;
|
|
35
|
+
name: string;
|
|
36
|
+
exists: boolean;
|
|
37
|
+
pending?: boolean;
|
|
38
|
+
/** Describes the change that `apply()` makes to an existing resource, for example `read replication: disabled -> auto`. */
|
|
39
|
+
update?: string;
|
|
40
|
+
apply: () => Promise<ProvisionResult>;
|
|
41
|
+
}
|
|
42
|
+
/** One Provision State category that a step records, with the keys that current Definitions use. */
|
|
43
|
+
interface ProvisionStateCategory {
|
|
44
|
+
category: string;
|
|
45
|
+
declared: readonly string[];
|
|
46
|
+
/** Provider resource identity for shared-resource checks. Return undefined when the recorded id lacks enough information. Defaults to the recorded id. */
|
|
47
|
+
resourceIdentity?: (entry: {
|
|
48
|
+
id: string;
|
|
49
|
+
key: string;
|
|
50
|
+
}) => string | undefined;
|
|
51
|
+
/** Identity expected by current config for a declared key. Omit when it cannot be established without provider access. */
|
|
52
|
+
declaredResourceIdentity?: (key: string) => string | undefined;
|
|
53
|
+
/** Tells a developer how to delete the resource of a recorded entry that no Definition declares. ViteHub never runs it. */
|
|
54
|
+
deleteHint: (entry: {
|
|
55
|
+
id: string;
|
|
56
|
+
key: string;
|
|
57
|
+
}) => string;
|
|
58
|
+
}
|
|
59
|
+
interface ProvisionStep {
|
|
60
|
+
id: string;
|
|
61
|
+
provider: ProvisionProvider;
|
|
62
|
+
plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
|
|
63
|
+
/** Describes the Provision State this step records. Runs without network access, also without credentials. */
|
|
64
|
+
recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region ../internal/src/cli.d.ts
|
|
68
|
+
interface ViteHubCliStreams {
|
|
69
|
+
stderr: {
|
|
70
|
+
write: (chunk: string | Uint8Array, encoding?: BufferEncoding | StdoutWriteCallback, callback?: StdoutWriteCallback) => unknown;
|
|
71
|
+
};
|
|
72
|
+
stdout: {
|
|
73
|
+
write: (chunk: string | Uint8Array) => unknown;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
interface ViteHubCliSpawnResult {
|
|
77
|
+
exitCode: number | null;
|
|
78
|
+
signal?: NodeJS.Signals | null;
|
|
79
|
+
/** The output of the child when `stdout` is `pipe`. */
|
|
80
|
+
stdout?: string;
|
|
81
|
+
}
|
|
82
|
+
interface ViteHubCliSpawnOptions {
|
|
83
|
+
cwd?: string;
|
|
84
|
+
env?: NodeJS.ProcessEnv;
|
|
85
|
+
stderr?: "inherit" | "pipe";
|
|
86
|
+
/** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
|
|
87
|
+
stdin?: "ignore" | "inherit";
|
|
88
|
+
/** `stderr` sends the child's stdout to the parent's stderr, so the parent's stdout keeps only its own output. */
|
|
89
|
+
stdout?: "inherit" | "pipe" | "stderr";
|
|
90
|
+
}
|
|
91
|
+
type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
|
|
92
|
+
interface ViteHubCliContext extends ViteHubCliStreams {
|
|
93
|
+
cwd: string;
|
|
94
|
+
env: NodeJS.ProcessEnv;
|
|
95
|
+
/** Replaces `fetch` for commands that call a running app, so tests need no server. */
|
|
96
|
+
fetch?: typeof fetch;
|
|
97
|
+
/**
|
|
98
|
+
* Loads the project config for a build on `host` and returns the Provision Steps of its plugins, with the config root
|
|
99
|
+
* that holds `.vitehub/provision.json`. Setup commands, such as `vitehub deploy`, call it only when they need the
|
|
100
|
+
* steps, so they still run on a config that throws.
|
|
101
|
+
*/
|
|
102
|
+
loadProvision?: (host: ProvisionProvider) => Promise<ViteHubCliProvision>;
|
|
103
|
+
/** The deployed app's public origin from `vitehub({ publicUrl })`, when it is one string. */
|
|
104
|
+
publicUrl?: string;
|
|
105
|
+
rootDir: string;
|
|
106
|
+
/** Replaces the host CLI runner, such as for `wrangler auth token`, so tests need no real host CLI. */
|
|
107
|
+
runHostCli?: HostCliRun;
|
|
108
|
+
spawn: ViteHubCliSpawn;
|
|
109
|
+
}
|
|
110
|
+
interface ViteHubCliProvision {
|
|
111
|
+
rootDir: string;
|
|
112
|
+
steps: readonly ProvisionStep[];
|
|
113
|
+
}
|
|
114
|
+
interface ViteHubCliFeature {
|
|
115
|
+
description?: string;
|
|
116
|
+
name: string;
|
|
117
|
+
run: (args: string[], context: ViteHubCliContext) => Promise<number | void> | number | void;
|
|
118
|
+
usage?: string;
|
|
119
|
+
}
|
|
120
|
+
interface ViteHubCliCommandNamespace {
|
|
121
|
+
/** The feature that `vitehub <name>` runs when the next argument names no other feature. It gets every argument after `<name>`. */
|
|
122
|
+
defaultFeature?: string;
|
|
123
|
+
description?: string;
|
|
124
|
+
features: ViteHubCliFeature[];
|
|
125
|
+
name: string;
|
|
126
|
+
}
|
|
127
|
+
/** The flags of `vitehub seed` that every seed gets. */
|
|
128
|
+
interface ViteHubCliSeedOptions {
|
|
129
|
+
/** `--database <name>`: seed only this Database. Only the Database seed runs. */
|
|
130
|
+
database?: string;
|
|
131
|
+
/** The process environment with the env files of `--stage`. */
|
|
132
|
+
env: NodeJS.ProcessEnv;
|
|
133
|
+
/** `--remote`: write the deployed stores. Without it, a seed writes only local data. */
|
|
134
|
+
remote: boolean;
|
|
135
|
+
/** `--timeout <ms>` of each call to the app. */
|
|
136
|
+
timeout?: number;
|
|
137
|
+
/** The deployed app with `--remote`: `--url`, or `vitehub({ publicUrl })`. */
|
|
138
|
+
url?: string;
|
|
139
|
+
}
|
|
140
|
+
/** The seed files of one primitive, which `vitehub seed` writes. */
|
|
141
|
+
interface ViteHubCliSeed {
|
|
142
|
+
/** Where the seed files are, such as `server/seed/kv/`. `vitehub seed` names it when it finds no seed files. */
|
|
143
|
+
files: string;
|
|
144
|
+
/** The primitive, such as `database` or `kv`. `vitehub seed <name>` runs only this seed. */
|
|
145
|
+
name: string;
|
|
146
|
+
/** Writes the seed files and returns the exit code, or `undefined` when the project has no seed files for this primitive. */
|
|
147
|
+
run: (options: ViteHubCliSeedOptions, context: ViteHubCliContext) => Promise<number | undefined>;
|
|
148
|
+
}
|
|
149
|
+
interface ViteHubCliContributor {
|
|
150
|
+
namespaces: ViteHubCliCommandNamespace[];
|
|
151
|
+
provision?: ProvisionStep[];
|
|
152
|
+
/** The seed files that `vitehub seed` writes. */
|
|
153
|
+
seeds?: ViteHubCliSeed[];
|
|
154
|
+
/** The deployed app's public origin. Commands receive it as `context.publicUrl`. */
|
|
155
|
+
publicUrl?: string;
|
|
156
|
+
}
|
|
157
|
+
type ViteHubCliContributorFactory = () => ViteHubCliContributor | undefined | Promise<ViteHubCliContributor | undefined>;
|
|
158
|
+
interface ViteHubCliPluginMetadata {
|
|
159
|
+
cli?: ViteHubCliContributor | ViteHubCliContributorFactory;
|
|
160
|
+
}
|
|
161
|
+
type StdoutWriteCallback = (error?: Error | null) => void;
|
|
162
|
+
//#endregion
|
|
163
|
+
export { ViteHubCliStreams as i, ViteHubCliContributor as n, ViteHubCliPluginMetadata as r, ViteHubCliContext as t };
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-
|
|
1
|
+
import { i as ViteHubCliStreams, n as ViteHubCliContributor, t as ViteHubCliContext } from "./cli-szm60zN5.js";
|
|
2
2
|
//#region src/cli.d.ts
|
|
3
3
|
export type RateLimitCliContext = Pick<ViteHubCliContext, "cwd" | "env" | "fetch" | "rootDir"> & ViteHubCliStreams;
|
|
4
4
|
export interface RateLimitCliOptions {
|
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import { t as redactInspectionText } from "./inspect-
|
|
3
|
-
import { n as callOperationFromCli,
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
|
|
2
|
+
import { t as redactInspectionText } from "./inspect-B6gTdgy9.js";
|
|
3
|
+
import { A as writeCliFailure, E as askOnTerminal, O as readViteHubDevTargetOption, n as callOperationFromCli, u as table } from "./operations-BYRa7wpx.js";
|
|
4
4
|
import * as v from "valibot";
|
|
5
|
-
import { createInterface } from "node:readline/promises";
|
|
6
5
|
//#region src/cli.ts
|
|
7
6
|
const rateLimitDevTargetErrors = {
|
|
8
7
|
invalidInlineTimeout: (message) => rateLimitErrorDiagnostics.RATE_LIMIT_R0041({ message }),
|
|
@@ -32,7 +31,7 @@ function writeUsage(command, stream) {
|
|
|
32
31
|
"Options:",
|
|
33
32
|
...command.name === "reset" ? [" --yes, -y Reset without asking. Without it, the command asks on a terminal and refuses elsewhere."] : [],
|
|
34
33
|
" --json Print JSON.",
|
|
35
|
-
" --url <url> Deployed app URL.
|
|
34
|
+
" --url <url> Deployed app URL. Set VITEHUB_CONSOLE_PRIVATE_KEY_<NAME> to sign the calls. Defaults to the dev server of this project.",
|
|
36
35
|
" --timeout <ms> Request timeout.",
|
|
37
36
|
" -h, --help Show this help.",
|
|
38
37
|
""
|
|
@@ -83,10 +82,6 @@ function parseArgs(args) {
|
|
|
83
82
|
if (!parsed.help && !parsed.key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0040({ message: "Missing Rate Limit key." });
|
|
84
83
|
return parsed;
|
|
85
84
|
}
|
|
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
85
|
function scopeNotice(scope) {
|
|
91
86
|
return scope === "process" ? "Scope: process. The counter exists only in this server process." : `Scope: ${scope}.`;
|
|
92
87
|
}
|
|
@@ -116,7 +111,11 @@ const finiteNumber = v.pipe(v.number(), v.finite());
|
|
|
116
111
|
const targetFields = {
|
|
117
112
|
key: v.string(),
|
|
118
113
|
name: v.string(),
|
|
119
|
-
provider: v.picklist([
|
|
114
|
+
provider: v.picklist([
|
|
115
|
+
"memory",
|
|
116
|
+
"kv",
|
|
117
|
+
"cloudflare"
|
|
118
|
+
])
|
|
120
119
|
};
|
|
121
120
|
const scopeSchema = v.picklist([
|
|
122
121
|
"global",
|
|
@@ -179,25 +178,12 @@ function parseInspection(operation, value) {
|
|
|
179
178
|
value: parsed.output
|
|
180
179
|
} : void 0;
|
|
181
180
|
}
|
|
181
|
+
/** Writes a failure like the other primitive CLIs, but redacts the message, since it can echo a limited key. */
|
|
182
182
|
function writeFailure(parsed, context, failure) {
|
|
183
|
-
|
|
184
|
-
if (parsed.json) context.stdout.write(`${JSON.stringify({ error: {
|
|
183
|
+
return writeCliFailure(parsed.json, context, {
|
|
185
184
|
...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
|
|
185
|
+
message: redactInspectionText(failure.message)
|
|
195
186
|
});
|
|
196
|
-
try {
|
|
197
|
-
return /^y(es)?$/i.test((await terminal.question(question)).trim());
|
|
198
|
-
} finally {
|
|
199
|
-
terminal.close();
|
|
200
|
-
}
|
|
201
187
|
}
|
|
202
188
|
async function runRateLimitCommand(command, args, context, options) {
|
|
203
189
|
let parsed;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
|
|
2
|
+
import { toResultError } from "@vite-hub/runtime";
|
|
2
3
|
//#region ../internal/src/integrations/hex.ts
|
|
3
4
|
const textEncoder = new TextEncoder();
|
|
4
5
|
new TextDecoder();
|
|
@@ -31,13 +32,13 @@ function cloudflareRateLimitDriver(options) {
|
|
|
31
32
|
try {
|
|
32
33
|
result = await options.binding.limit({ key: input.key });
|
|
33
34
|
} catch (cause) {
|
|
34
|
-
return [rateLimitErrorDiagnostics.RATE_LIMIT_R0005({
|
|
35
|
+
return [toResultError(rateLimitErrorDiagnostics.RATE_LIMIT_R0005({
|
|
35
36
|
message: "[vitehub] Cloudflare Rate Limit binding failed.",
|
|
36
37
|
cause
|
|
37
|
-
}), void 0];
|
|
38
|
+
})), void 0];
|
|
38
39
|
}
|
|
39
40
|
if (!result || typeof result.success !== "boolean") throw rateLimitErrorDiagnostics.RATE_LIMIT_R0006({ message: "[vitehub] Cloudflare Rate Limit binding returned an invalid result." });
|
|
40
|
-
return [
|
|
41
|
+
return [void 0, { allowed: result.success }];
|
|
41
42
|
},
|
|
42
43
|
name: "cloudflare"
|
|
43
44
|
};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as RateLimitWindow, E as RateLimitRuntimeConfig, a as RateLimitCounterScope } from "./types-CMyR1JeW.js";
|
|
2
2
|
//#region src/counters.d.ts
|
|
3
|
-
type
|
|
3
|
+
type RateLimitRuntimeDriver = RateLimitRuntimeConfig["driver"];
|
|
4
4
|
/** Counter of one key for one policy. `peekRateLimit()` reads it without consuming a token. */
|
|
5
5
|
interface RateLimitCounterSnapshot {
|
|
6
6
|
limit: number;
|
|
@@ -14,7 +14,7 @@ interface RateLimitCounterSnapshot {
|
|
|
14
14
|
interface RateLimitCounterTarget {
|
|
15
15
|
key: string;
|
|
16
16
|
name: string;
|
|
17
|
-
provider:
|
|
17
|
+
provider: RateLimitRuntimeDriver;
|
|
18
18
|
}
|
|
19
19
|
type RateLimitPeekInspection = (RateLimitCounterTarget & {
|
|
20
20
|
/** One entry for each policy that requests used with this name. Usually one. */
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-
|
|
2
|
-
import {
|
|
1
|
+
import { t as rateLimitErrorDiagnostics } from "./error-diagnostics-MgAnhRTP.js";
|
|
2
|
+
import { i as resolveRateLimitDriver, r as listRuntimeRateLimiters } from "./state-BU-zcLNY.js";
|
|
3
3
|
import * as v from "valibot";
|
|
4
4
|
//#region src/counters.ts
|
|
5
5
|
/** Reason that Cloudflare counters are not readable. The binding exposes only `limit({ key })`. */
|
|
6
6
|
const cloudflareRateLimitCounterUnsupportedReason = "The Cloudflare Rate Limiting binding exposes only limit(), which consumes a token. It cannot read or reset a counter.";
|
|
7
7
|
const unusedReason = "No request used this Rate Limit in this process since it started, so no counter exists.";
|
|
8
|
+
/** A `kv` counter is shared, but the policy that names its window comes from the requests of this process. */
|
|
9
|
+
const unusedKVReason = "No request used this Rate Limit in this process since it started, so this process does not know its window. Other processes can still have a counter.";
|
|
8
10
|
function unavailableReason(cause) {
|
|
9
11
|
return `The Rate Limit driver failed: ${cause instanceof Error ? cause.message : String(cause)}`;
|
|
10
12
|
}
|
|
@@ -13,7 +15,7 @@ function assertTarget(name, key) {
|
|
|
13
15
|
if (!v.is(v.string(), key) || !key) throw rateLimitErrorDiagnostics.RATE_LIMIT_R0039({ message: "[vitehub] Rate Limit key must be a non-empty string." });
|
|
14
16
|
}
|
|
15
17
|
function limitersFor(target) {
|
|
16
|
-
return target.provider === "
|
|
18
|
+
return target.provider === "cloudflare" ? void 0 : listRuntimeRateLimiters(target.name);
|
|
17
19
|
}
|
|
18
20
|
/**
|
|
19
21
|
* Reads the counter of one key without consuming a token. The result reports `unsupported` when the configured
|
|
@@ -24,7 +26,7 @@ async function peekRateLimit(name, key) {
|
|
|
24
26
|
const target = {
|
|
25
27
|
key,
|
|
26
28
|
name: name.trim(),
|
|
27
|
-
provider:
|
|
29
|
+
provider: await resolveRateLimitDriver()
|
|
28
30
|
};
|
|
29
31
|
const limiters = limitersFor(target);
|
|
30
32
|
if (!limiters) return {
|
|
@@ -34,7 +36,7 @@ async function peekRateLimit(name, key) {
|
|
|
34
36
|
};
|
|
35
37
|
if (limiters.length === 0) return {
|
|
36
38
|
...target,
|
|
37
|
-
reason: unusedReason,
|
|
39
|
+
reason: target.provider === "kv" ? unusedKVReason : unusedReason,
|
|
38
40
|
status: "unused"
|
|
39
41
|
};
|
|
40
42
|
const counters = [];
|
|
@@ -75,7 +77,7 @@ async function resetRateLimit(name, key) {
|
|
|
75
77
|
const target = {
|
|
76
78
|
key,
|
|
77
79
|
name: name.trim(),
|
|
78
|
-
provider:
|
|
80
|
+
provider: await resolveRateLimitDriver()
|
|
79
81
|
};
|
|
80
82
|
const limiters = limitersFor(target);
|
|
81
83
|
if (!limiters) return {
|
|
@@ -83,6 +85,11 @@ async function resetRateLimit(name, key) {
|
|
|
83
85
|
reason: cloudflareRateLimitCounterUnsupportedReason,
|
|
84
86
|
status: "unsupported"
|
|
85
87
|
};
|
|
88
|
+
if (limiters.length === 0 && target.provider === "kv") return {
|
|
89
|
+
...target,
|
|
90
|
+
reason: unusedKVReason,
|
|
91
|
+
status: "unsupported"
|
|
92
|
+
};
|
|
86
93
|
for (const limiter of limiters) {
|
|
87
94
|
const result = await limiter.reset({ key });
|
|
88
95
|
if (result.status === "unsupported") return {
|