@lunora/ratelimit 1.0.0-alpha.184 → 1.0.0-alpha.186

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -295,26 +295,7 @@ interface SqlStoreOptions {
295
295
  /** Table name. Created if missing. Defaults to `_lunora_rate_limits`. */
296
296
  table?: string;
297
297
  }
298
- /**
299
- * SQLite-backed store for durable, per-DO rate-limit state. Persists each
300
- * `(name, key)` pair as one row so limits survive hibernation and eviction.
301
- *
302
- * **Retention:** the limiter calls `sweep` after each write, which deletes up to 32
303
- * rows older than its horizon. The index on `ts` covers only rows with a
304
- * non-negative `value`, so a reserved debt (never swept) adds nothing to the scan.
305
- * The table holds the live keys plus the expired ones not yet swept. Limiters may
306
- * share the table: each sweep deletes only the keys its own limiter owns, so a
307
- * shorter-window limiter cannot evict a longer-window one's rows. A sweep reads
308
- * candidates by `ts` before filtering by owner, so a long run of another limiter's
309
- * expired rows can use up the window for a while.
310
- *
311
- * **Atomicity:** `exec` is synchronous and the limiter does not yield between a
312
- * synchronous store's read and its write, so one consume's read, decision and
313
- * write run as a single JavaScript step. No other call on the same isolate can
314
- * interleave, which is what makes concurrent consumes admit exactly the
315
- * configured rate. Two isolates sharing one SQLite file (not a Durable Object
316
- * case) are not covered; serialize those yourself.
317
- */
298
+ /** Sql store, with keys stored losslessly; see {@link encodeStorageKey}. */
318
299
  declare const createSqlStore: (options: SqlStoreOptions) => RateLimitStore;
319
300
  /**
320
301
  * The READ slice — everything the store needs to answer `RateLimiter.getValue`
@@ -383,58 +364,7 @@ interface ReadOnlyDatabaseStoreOptions extends DatabaseStoreLocation {
383
364
  /** The Lunora ORM reader — `ctx.db` inside a query. */
384
365
  db: RateLimitDatabaseReader;
385
366
  }
386
- /**
387
- * Store backed by a Lunora table through `ctx.db`, for durable limits inside a
388
- * procedure (the procedure context exposes no raw SQL). Works on a shard-local
389
- * table and on a `.global()` one. Declare a table with the key column and its
390
- * index, e.g.
391
- *
392
- * ```ts
393
- * rateLimits: defineTable({
394
- * key: v.string(),
395
- * ts: v.number(),
396
- * value: v.number(),
397
- * prev: v.optional(v.number()),
398
- * })
399
- * .index("by_key", ["key"])
400
- * .index("by_ts", ["ts"])
401
- * ```
402
- *
403
- * **Table shape change:** `by_ts` is new. The sweep finds expired rows through it.
404
- * A table declared without it still works, but each sweep scans every row. Apps
405
- * that already declared the table add the index. The sweep deletes at most 32
406
- * expired rows per write; a reserved debt (negative `value`) is never deleted.
407
- * The ORM index cannot be partial, so debts stay in it: many old debts make each
408
- * sweep read past them. Reserves are rare, so this is accepted.
409
- *
410
- * **Ceiling:** the sweep deletes only a row whose `ts`, `value` and `prev` still match
411
- * what it read, but the framework resolves that match and deletes in two steps.
412
- * On a `.global()` table another shard can rewrite the row between them, so the
413
- * row is deleted live and its bucket resets. Closing that needs a conditional
414
- * delete on `ctx.db`, which does not exist yet. A shard-local table is not exposed:
415
- * the Durable Object's input gate holds across the sweep's storage operations.
416
- *
417
- * **Soft delete:** the sweep deletes with `ctx.db.delete`, which has no hard-delete
418
- * option. Declare the table without `.softDelete()`: a tombstoned row keeps its
419
- * deterministic id, so the next consume for that key conflicts forever.
420
- *
421
- * **Atomic against concurrent consumes.** `setIf` writes only if the row still
422
- * holds the value `get` returned: an existing row through `ctx.db.patchIf` with
423
- * that value as its `where`, a new row through an `insert` under an id derived
424
- * from the key, which a concurrent creator's insert collides with. A consume
425
- * that loses either race gets `false` back and the limiter reads and decides
426
- * again, so a limit of 1 admits one caller however many arrive together — on a
427
- * `.global()` table too, where D1 calls do not hold the Durable Object's input
428
- * gate.
429
- *
430
- * **Consumption commits with the procedure.** A mutation's `ctx.db` writes ride
431
- * its storage transaction, so a handler that throws after `limit()` rolls the
432
- * consumed unit back with everything else — inside a mutation this store counts
433
- * successful calls, not attempts. To charge every attempt (a login limiter),
434
- * consume from an action, where each write commits on its own, or return a
435
- * failure value from the mutation instead of throwing. A `.global()` table's
436
- * row lives in D1, outside the DO transaction, so there the unit stays spent.
437
- */
367
+ /** Database store, with keys stored losslessly; see {@link encodeStorageKey}. */
438
368
  declare const createDatabaseStore: (options: DatabaseStoreOptions) => RateLimitStore;
439
369
  /**
440
370
  * Read-only counterpart to {@link createDatabaseStore}, for a query context.
package/dist/index.d.ts CHANGED
@@ -295,26 +295,7 @@ interface SqlStoreOptions {
295
295
  /** Table name. Created if missing. Defaults to `_lunora_rate_limits`. */
296
296
  table?: string;
297
297
  }
298
- /**
299
- * SQLite-backed store for durable, per-DO rate-limit state. Persists each
300
- * `(name, key)` pair as one row so limits survive hibernation and eviction.
301
- *
302
- * **Retention:** the limiter calls `sweep` after each write, which deletes up to 32
303
- * rows older than its horizon. The index on `ts` covers only rows with a
304
- * non-negative `value`, so a reserved debt (never swept) adds nothing to the scan.
305
- * The table holds the live keys plus the expired ones not yet swept. Limiters may
306
- * share the table: each sweep deletes only the keys its own limiter owns, so a
307
- * shorter-window limiter cannot evict a longer-window one's rows. A sweep reads
308
- * candidates by `ts` before filtering by owner, so a long run of another limiter's
309
- * expired rows can use up the window for a while.
310
- *
311
- * **Atomicity:** `exec` is synchronous and the limiter does not yield between a
312
- * synchronous store's read and its write, so one consume's read, decision and
313
- * write run as a single JavaScript step. No other call on the same isolate can
314
- * interleave, which is what makes concurrent consumes admit exactly the
315
- * configured rate. Two isolates sharing one SQLite file (not a Durable Object
316
- * case) are not covered; serialize those yourself.
317
- */
298
+ /** Sql store, with keys stored losslessly; see {@link encodeStorageKey}. */
318
299
  declare const createSqlStore: (options: SqlStoreOptions) => RateLimitStore;
319
300
  /**
320
301
  * The READ slice — everything the store needs to answer `RateLimiter.getValue`
@@ -383,58 +364,7 @@ interface ReadOnlyDatabaseStoreOptions extends DatabaseStoreLocation {
383
364
  /** The Lunora ORM reader — `ctx.db` inside a query. */
384
365
  db: RateLimitDatabaseReader;
385
366
  }
386
- /**
387
- * Store backed by a Lunora table through `ctx.db`, for durable limits inside a
388
- * procedure (the procedure context exposes no raw SQL). Works on a shard-local
389
- * table and on a `.global()` one. Declare a table with the key column and its
390
- * index, e.g.
391
- *
392
- * ```ts
393
- * rateLimits: defineTable({
394
- * key: v.string(),
395
- * ts: v.number(),
396
- * value: v.number(),
397
- * prev: v.optional(v.number()),
398
- * })
399
- * .index("by_key", ["key"])
400
- * .index("by_ts", ["ts"])
401
- * ```
402
- *
403
- * **Table shape change:** `by_ts` is new. The sweep finds expired rows through it.
404
- * A table declared without it still works, but each sweep scans every row. Apps
405
- * that already declared the table add the index. The sweep deletes at most 32
406
- * expired rows per write; a reserved debt (negative `value`) is never deleted.
407
- * The ORM index cannot be partial, so debts stay in it: many old debts make each
408
- * sweep read past them. Reserves are rare, so this is accepted.
409
- *
410
- * **Ceiling:** the sweep deletes only a row whose `ts`, `value` and `prev` still match
411
- * what it read, but the framework resolves that match and deletes in two steps.
412
- * On a `.global()` table another shard can rewrite the row between them, so the
413
- * row is deleted live and its bucket resets. Closing that needs a conditional
414
- * delete on `ctx.db`, which does not exist yet. A shard-local table is not exposed:
415
- * the Durable Object's input gate holds across the sweep's storage operations.
416
- *
417
- * **Soft delete:** the sweep deletes with `ctx.db.delete`, which has no hard-delete
418
- * option. Declare the table without `.softDelete()`: a tombstoned row keeps its
419
- * deterministic id, so the next consume for that key conflicts forever.
420
- *
421
- * **Atomic against concurrent consumes.** `setIf` writes only if the row still
422
- * holds the value `get` returned: an existing row through `ctx.db.patchIf` with
423
- * that value as its `where`, a new row through an `insert` under an id derived
424
- * from the key, which a concurrent creator's insert collides with. A consume
425
- * that loses either race gets `false` back and the limiter reads and decides
426
- * again, so a limit of 1 admits one caller however many arrive together — on a
427
- * `.global()` table too, where D1 calls do not hold the Durable Object's input
428
- * gate.
429
- *
430
- * **Consumption commits with the procedure.** A mutation's `ctx.db` writes ride
431
- * its storage transaction, so a handler that throws after `limit()` rolls the
432
- * consumed unit back with everything else — inside a mutation this store counts
433
- * successful calls, not attempts. To charge every attempt (a login limiter),
434
- * consume from an action, where each write commits on its own, or return a
435
- * failure value from the mutation instead of throwing. A `.global()` table's
436
- * row lives in D1, outside the DO transaction, so there the unit stays spent.
437
- */
367
+ /** Database store, with keys stored losslessly; see {@link encodeStorageKey}. */
438
368
  declare const createDatabaseStore: (options: DatabaseStoreOptions) => RateLimitStore;
439
369
  /**
440
370
  * Read-only counterpart to {@link createDatabaseStore}, for a query context.
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{availableAt as o,evaluate as a}from"./packem_shared/availableAt-BhJ1lMBZ.mjs";import{default as i}from"./packem_shared/dbRateLimit-DT1whze7.mjs";import{default as l}from"./packem_shared/RateLimitError-9Y5OLxpl.mjs";import{rateLimit as x}from"./packem_shared/rateLimit-CWZur6XE.mjs";import{ratelimitPlugin as c}from"./packem_shared/ratelimitPlugin-CFnDs9rj.mjs";import{RateLimiter as u}from"./packem_shared/RateLimiter-Br4e0GpC.mjs";import{createDbStore as b,createMemoryStore as n,createReadOnlyDbStore as L,createSqlStore as s}from"./packem_shared/createDbStore-UNWqFqlN.mjs";import{tokenBudget as v}from"./packem_shared/tokenBudget-CvkodZ0R.mjs";const e="0.0.0";export{l as RateLimitError,u as RateLimiter,e as VERSION,o as availableAt,b as createDbStore,n as createMemoryStore,L as createReadOnlyDbStore,s as createSqlStore,i as dbRateLimit,a as evaluate,x as rateLimit,c as ratelimitPlugin,v as tokenBudget};
1
+ import{availableAt as o,evaluate as a}from"./packem_shared/availableAt-BhJ1lMBZ.mjs";import{default as i}from"./packem_shared/dbRateLimit-CQYvD0a-.mjs";import{default as l}from"./packem_shared/RateLimitError-9Y5OLxpl.mjs";import{rateLimit as x}from"./packem_shared/rateLimit-CWZur6XE.mjs";import{ratelimitPlugin as c}from"./packem_shared/ratelimitPlugin-CFnDs9rj.mjs";import{RateLimiter as u}from"./packem_shared/RateLimiter-B4P1iyNM.mjs";import{createDbStore as b,createMemoryStore as n,createReadOnlyDbStore as L,createSqlStore as s}from"./packem_shared/createDbStore-DdoYxOaZ.mjs";import{tokenBudget as v}from"./packem_shared/tokenBudget-CvkodZ0R.mjs";const e="0.0.0";export{l as RateLimitError,u as RateLimiter,e as VERSION,o as availableAt,b as createDbStore,n as createMemoryStore,L as createReadOnlyDbStore,s as createSqlStore,i as dbRateLimit,a as evaluate,x as rateLimit,c as ratelimitPlugin,v as tokenBudget};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{retentionMs as y,availableAt as v,evaluate as N}from"./availableAt-BhJ1lMBZ.mjs";import w from"./RateLimitError-9Y5OLxpl.mjs";import{createMemoryStore as b}from"./createDbStore-DdoYxOaZ.mjs";const I=/^[\d.:a-f]+$/iu,d=i=>{const t=i.indexOf("%"),e=t===-1?i:i.slice(0,t);if(!e.includes(":")||!I.test(e))return i;let s;try{s=new URL(`http://[${e}]/`).hostname.slice(1,-1)}catch{return i}const[r="",n]=s.split("::"),a=r===""?[]:r.split(":"),l=n===void 0||n===""?[]:n.split(":"),c=[...a,...Array.from({length:8-a.length-l.length},()=>"0"),...l].map(o=>Number.parseInt(o,16));if(c.slice(0,5).every(o=>o===0)&&c[5]===65535){const[o=0,f=0]=c.slice(6);return[o>>8,o&255,f>>8,f&255].join(".")}return`${c.slice(0,4).map(o=>o.toString(16)).join(":")}::/64`},g=new RegExp("(\\p{Cs})","u"),u=i=>i.isWellFormed()?encodeURIComponent(i):i.split(g).map((t,e)=>e%2===1?`%u${(t.codePointAt(0)??0).toString(16).toUpperCase()}`:encodeURIComponent(t)).join(""),m=(i,t)=>t===void 0?u(i):`${u(i)}:${u(t)}`,E=16,L=32,p=i=>typeof i?.then=="function",R=i=>{let t=Number.NEGATIVE_INFINITY;return()=>(t=Math.max(t,i()),t)},T=i=>i?t=>d(i(t)):d,A="@lunora/ratelimit: new RateLimiter() was built with no explicit `store`, so it falls back to `createMemoryStore()` — an in-process Map. That Map is durable and correctly shared only for calls that land on the same Durable Object instance; it is NOT shared across `.shardBy(...)` shards or `.global()` replicas, and it resets when the DO instance is evicted/restarted. For a limit that must hold across any of those, pass a durable `store` (`createDbStore` or `createSqlStore`) instead. Pass `store: createMemoryStore()` explicitly once you've confirmed the in-memory default is correct here, to silence this warning.";class z{config;denyList;normalize;now;retention;store;owns;constructor(t){this.config=structuredClone(t.config);const e=new Set(Object.keys(this.config).map(s=>u(s)));this.owns=s=>e.has(s.split(":")[0]??""),this.normalize=T(t.normalize),this.denyList=new Set([...t.denyList??[]].flatMap(s=>[s,this.normalize(s)])),this.now=R(t.now??Date.now),t.store===void 0&&console.warn(A),this.store=t.store??b(),this.retention=y(Object.values(this.config));for(const[s,r]of Object.entries(this.config)){if(Object.hasOwn(r,"shards"))throw new h("INTERNAL",`rate limit "${s}": \`shards\` is no longer supported — remove it; the limit now enforces its full \`rate\` (lower \`rate\` if you raised it to offset the split)`);if(!Number.isFinite(r.period)||r.period<=0)throw new h("INTERNAL",`rate limit "${s}": period must be a positive number`);if(!Number.isFinite(r.rate)||r.rate<=0)throw new h("INTERNAL",`rate limit "${s}": rate must be a positive number`);if(r.capacity!==void 0&&(!Number.isFinite(r.capacity)||r.capacity<0))throw new h("INTERNAL",`rate limit "${s}": capacity must be a non-negative number`)}}async check(t,e={}){return this.run(t,e,!1)}async getValue(t,e={}){const s=this.resolve(t),r=this.now(),n=m(t,this.normalizeKey(e.key)),a=v(s,await this.store.get(n),r);return{config:s,ts:a.ts,value:a.value}}async limit(t,e={}){return this.run(t,e,!0)}async reset(t,e={}){this.resolve(t),await Promise.resolve(this.store.delete(m(t,this.normalizeKey(e.key))))}async decide(t,e,s){for(let r=0;r<E;r+=1){const n=this.store.get(e),a=p(n)?await n:n,l=this.now(),{status:c,value:o}=N(t,a,{...s,now:l});if(o===void 0)return c;if(this.store.setIf===void 0)return await this.store.set(e,o),await this.sweep(l),c;if(await this.store.setIf(e,o,a))return await this.sweep(l),c}return{ok:!1,reason:"rate",retryAfter:0}}async sweep(t){try{const e=this.store.sweep?.(t-this.retention,L,this.owns);p(e)&&await e}catch(e){console.warn("@lunora/ratelimit: the retention sweep failed; the consume still stands",e)}}normalizeKey(t){return t===void 0?void 0:this.normalize(t)}resolve(t){const e=this.config[t];if(!e)throw new h("INTERNAL",`rate limit "${t}" is not configured`);return e}async run(t,e,s){const r=this.resolve(t),n=this.normalizeKey(e.key);if(n!==void 0&&(this.denyList.has(n)||this.denyList.has(e.key))){const o={ok:!1,reason:"deny",retryAfter:Number.POSITIVE_INFINITY};if(e.throws)throw new w(o);return o}const a=e.count??1;if(!Number.isInteger(a)||a<=0)throw new h("INTERNAL",`rate limit "${t}": count must be a positive integer`);const l=m(t,n),c=await this.decide(r,l,{consume:s,count:a,reserve:e.reserve??!1});if(!c.ok&&e.throws)throw new w(c);return c}}export{z as RateLimiter};
@@ -0,0 +1 @@
1
+ import{LunoraError as I}from"@lunora/errors";const A=()=>{const e=new Map;let t=!0,s=Number.NEGATIVE_INFINITY;return{delete:r=>{e.delete(r)},get:r=>e.get(r),set:(r,a)=>{e.delete(r),e.set(r,a),(Number.isNaN(a.ts)||a.ts<s)&&(t=!1),s=a.ts},sweep:(r,a,c)=>{let d=0;for(const[o,u]of e){if(d>=a||t&&u.ts>r&&c?.(o)!==!1)break;d+=1,e.delete(o),(u.value<0||u.ts>r||c?.(o)===!1)&&(e.set(o,u),(Number.isNaN(u.ts)||u.ts<s)&&(t=!1))}}}},w=(e,t,...s)=>e.exec.call(e,t,...s).toArray(),S="￿",p=e=>e.isWellFormed()&&!e.startsWith(S)?e:`${S}${JSON.stringify(e)}`,h=e=>{if(!e.startsWith(S))return e;try{const t=JSON.parse(e.slice(S.length));return typeof t=="string"?t:e}catch{return e}},N=e=>{const t={delete:a=>e.delete(p(a)),get:a=>e.get(p(a)),set:(a,c)=>e.set(p(a),c)},{setIf:s,sweep:r}=e;return s&&(t.setIf=(a,c,d)=>s(p(a),c,d)),r&&(t.sweep=(a,c,d)=>r(a,c,d===void 0?void 0:o=>d(h(o)))),t},T=e=>{const{sql:t}=e,s=e.table??"_lunora_rate_limits";return w(t,`CREATE TABLE IF NOT EXISTS "${s}" (k TEXT PRIMARY KEY, value REAL NOT NULL, ts INTEGER NOT NULL, prev REAL)`),w(t,`CREATE INDEX IF NOT EXISTS "${s}_ts" ON "${s}" (ts) WHERE value >= 0`),{delete:r=>{w(t,`DELETE FROM "${s}" WHERE k = ?`,r)},sweep:(r,a,c)=>{const o=w(t,`SELECT k FROM "${s}" WHERE ts <= ? AND value >= 0 ORDER BY ts LIMIT ?`,r,a).map(({k:u})=>u).filter(u=>c?.(u)!==!1);o.length>0&&w(t,`DELETE FROM "${s}" WHERE k IN (SELECT value FROM json_each(?))`,JSON.stringify(o))},get:r=>{const c=w(t,`SELECT value, ts, prev FROM "${s}" WHERE k = ?`,r)[0];if(!c)return;const d={ts:c.ts,value:c.value};return c.prev!==null&&(d.prev=c.prev),d},set:(r,a)=>{w(t,`INSERT INTO "${s}" (k, value, ts, prev) VALUES (?, ?, ?, ?) ON CONFLICT(k) DO UPDATE SET value = excluded.value, ts = excluded.ts, prev = excluded.prev`,r,a.value,a.ts,a.prev??null)}}},D=e=>N(T(e)),m=e=>e.toString(16).padStart(2,"0"),R=async(e,t)=>{const r=[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).subarray(0,16)];r[6]=128+r[6]%16,r[8]=128+r[8]%64;const a=r.map(c=>m(c)).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`},O=e=>e?.code==="CONFLICT",y=e=>{const{db:t}=e,s=e.table??"rateLimits",r=e.keyField??"key",a=new Map;let c=!1;const d=async n=>{const i=await t.findFirst(s,{where:{[r]:n}});return a.set(n,i?i._id:void 0),i},o=async n=>(a.has(n)||await d(n),a.get(n)),u=(n,i)=>{const l={[r]:n,ts:i.ts,value:i.value};return i.prev!==void 0&&(l.prev=i.prev),l},b=async(n,i)=>{try{return a.set(n,await t.insert(s,i,{clientId:await R(s,n)})),!0}catch(l){if(O(l))return a.delete(n),!1;throw l}};return{delete:async n=>{const i=await o(n);i!==void 0&&await t.delete(s,i),a.delete(n)},get:async n=>{const i=await d(n);if(!i)return;const l={ts:i.ts,value:i.value};return i.prev!==null&&i.prev!==void 0&&(l.prev=i.prev),l},set:async(n,i)=>{const l=u(n,i);let v=await o(n);if(v===void 0){if(await b(n,l))return;await d(n),v=a.get(n)}v!==void 0&&await t.patchIf(s,v,{patch:l,where:{}})},setIf:async(n,i,l)=>{const v=u(n,i);if(l===void 0)return b(n,v);const E=await o(n);if(E===void 0)return!1;const{applied:f}=await t.patchIf(s,E,{patch:v,where:{prev:l.prev??null,ts:l.ts,value:l.value}});return f||a.delete(n),f},sweep:async(n,i,l)=>{if(t.findMany===void 0){c||(c=!0,console.warn(`@lunora/ratelimit: table "${s}" is not swept: the adapter has no findMany. Pass the framework's ctx.db.`));return}const{page:v}=await t.findMany(s,{limit:i,orderBy:[{ts:"asc"}],where:{ts:{lte:n},value:{gte:0}}}),E=v.filter(f=>l?.(String(f[r]))!==!1);await Promise.all(E.map(async f=>{await t.findFirst(s,{where:{_id:f._id,prev:f.prev??null,ts:f.ts,value:f.value}})!==null&&await t.delete(s,f._id)}))}}},L=e=>N(y(e)),k=e=>{const t=r=>{throw new I("INTERNAL",`@lunora/ratelimit: \`${r}\` needs a writable \`ctx.db\`, but this store was created with \`createReadOnlyDbStore\` (a query context). Use \`createDbStore\` from a mutation or action; a query can only call \`getValue\`/\`check\`.`)},s=L({...e,db:{delete:()=>t("delete"),findFirst:e.db.findFirst.bind(e.db),insert:()=>t("insert"),patchIf:()=>t("patchIf")}});return{delete:()=>t("reset"),get:s.get,set:()=>t("limit"),setIf:()=>t("limit")}};export{L as createDbStore,A as createMemoryStore,k as createReadOnlyDbStore,D as createSqlStore};
@@ -1 +1 @@
1
- import{rateLimit as o}from"./rateLimit-CWZur6XE.mjs";import{RateLimiter as m}from"./RateLimiter-Br4e0GpC.mjs";import{createDbStore as i}from"./createDbStore-UNWqFqlN.mjs";const f=(e,r,t={})=>o(a=>new m({config:e,store:i({db:a.db,...t.store})}),r,t);export{f as default};
1
+ import{rateLimit as o}from"./rateLimit-CWZur6XE.mjs";import{RateLimiter as m}from"./RateLimiter-B4P1iyNM.mjs";import{createDbStore as i}from"./createDbStore-DdoYxOaZ.mjs";const f=(e,r,t={})=>o(a=>new m({config:e,store:i({db:a.db,...t.store})}),r,t);export{f as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/ratelimit",
3
- "version": "1.0.0-alpha.184",
3
+ "version": "1.0.0-alpha.186",
4
4
  "description": "Rate limiting: token-bucket / fixed-window / sliding-window algorithms, deny list, pluggable stores, and procedure middleware",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1 +0,0 @@
1
- import{LunoraError as h}from"@lunora/errors";import{retentionMs as p,availableAt as y,evaluate as v}from"./availableAt-BhJ1lMBZ.mjs";import f from"./RateLimitError-9Y5OLxpl.mjs";import{createMemoryStore as I}from"./createDbStore-UNWqFqlN.mjs";const b=/^[\d.:a-f]+$/iu,w=r=>{const t=r.indexOf("%"),e=t===-1?r:r.slice(0,t);if(!e.includes(":")||!b.test(e))return r;let s;try{s=new URL(`http://[${e}]/`).hostname.slice(1,-1)}catch{return r}const[i="",n]=s.split("::"),a=i===""?[]:i.split(":"),l=n===void 0||n===""?[]:n.split(":"),c=[...a,...Array.from({length:8-a.length-l.length},()=>"0"),...l].map(o=>Number.parseInt(o,16));if(c.slice(0,5).every(o=>o===0)&&c[5]===65535){const[o=0,m=0]=c.slice(6);return[o>>8,o&255,m>>8,m&255].join(".")}return`${c.slice(0,4).map(o=>o.toString(16)).join(":")}::/64`},u=(r,t)=>t===void 0?encodeURIComponent(r):`${encodeURIComponent(r)}:${encodeURIComponent(t)}`,N=16,g=32,d=r=>typeof r?.then=="function",L=r=>{let t=Number.NEGATIVE_INFINITY;return()=>(t=Math.max(t,r()),t)},R=r=>r?t=>w(r(t)):w,T="@lunora/ratelimit: new RateLimiter() was built with no explicit `store`, so it falls back to `createMemoryStore()` — an in-process Map. That Map is durable and correctly shared only for calls that land on the same Durable Object instance; it is NOT shared across `.shardBy(...)` shards or `.global()` replicas, and it resets when the DO instance is evicted/restarted. For a limit that must hold across any of those, pass a durable `store` (`createDbStore` or `createSqlStore`) instead. Pass `store: createMemoryStore()` explicitly once you've confirmed the in-memory default is correct here, to silence this warning.";class M{config;denyList;normalize;now;retention;store;owns;constructor(t){this.config=structuredClone(t.config);const e=new Set(Object.keys(this.config).map(s=>encodeURIComponent(s)));this.owns=s=>e.has(s.split(":")[0]??""),this.normalize=R(t.normalize),this.denyList=new Set([...t.denyList??[]].flatMap(s=>[s,this.normalize(s)])),this.now=L(t.now??Date.now),t.store===void 0&&console.warn(T),this.store=t.store??I(),this.retention=p(Object.values(this.config));for(const[s,i]of Object.entries(this.config)){if(Object.hasOwn(i,"shards"))throw new h("INTERNAL",`rate limit "${s}": \`shards\` is no longer supported — remove it; the limit now enforces its full \`rate\` (lower \`rate\` if you raised it to offset the split)`);if(!Number.isFinite(i.period)||i.period<=0)throw new h("INTERNAL",`rate limit "${s}": period must be a positive number`);if(!Number.isFinite(i.rate)||i.rate<=0)throw new h("INTERNAL",`rate limit "${s}": rate must be a positive number`);if(i.capacity!==void 0&&(!Number.isFinite(i.capacity)||i.capacity<0))throw new h("INTERNAL",`rate limit "${s}": capacity must be a non-negative number`)}}async check(t,e={}){return this.run(t,e,!1)}async getValue(t,e={}){const s=this.resolve(t),i=this.now(),n=u(t,this.normalizeKey(e.key)),a=y(s,await this.store.get(n),i);return{config:s,ts:a.ts,value:a.value}}async limit(t,e={}){return this.run(t,e,!0)}async reset(t,e={}){this.resolve(t),await Promise.resolve(this.store.delete(u(t,this.normalizeKey(e.key))))}async decide(t,e,s){for(let i=0;i<N;i+=1){const n=this.store.get(e),a=d(n)?await n:n,l=this.now(),{status:c,value:o}=v(t,a,{...s,now:l});if(o===void 0)return c;if(this.store.setIf===void 0)return await this.store.set(e,o),await this.sweep(l),c;if(await this.store.setIf(e,o,a))return await this.sweep(l),c}return{ok:!1,reason:"rate",retryAfter:0}}async sweep(t){try{const e=this.store.sweep?.(t-this.retention,g,this.owns);d(e)&&await e}catch(e){console.warn("@lunora/ratelimit: the retention sweep failed; the consume still stands",e)}}normalizeKey(t){return t===void 0?void 0:this.normalize(t)}resolve(t){const e=this.config[t];if(!e)throw new h("INTERNAL",`rate limit "${t}" is not configured`);return e}async run(t,e,s){const i=this.resolve(t),n=this.normalizeKey(e.key);if(n!==void 0&&(this.denyList.has(n)||this.denyList.has(e.key))){const o={ok:!1,reason:"deny",retryAfter:Number.POSITIVE_INFINITY};if(e.throws)throw new f(o);return o}const a=e.count??1;if(!Number.isInteger(a)||a<=0)throw new h("INTERNAL",`rate limit "${t}": count must be a positive integer`);const l=u(t,n),c=await this.decide(i,l,{consume:s,count:a,reserve:e.reserve??!1});if(!c.ok&&e.throws)throw new f(c);return c}}export{M as RateLimiter};
@@ -1 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";const R=()=>{const s=new Map;let e=!0,r=Number.NEGATIVE_INFINITY;return{delete:t=>{s.delete(t)},get:t=>s.get(t),set:(t,n)=>{s.delete(t),s.set(t,n),(Number.isNaN(n.ts)||n.ts<r)&&(e=!1),r=n.ts},sweep:(t,n,l)=>{let u=0;for(const[o,d]of s){if(u>=n||e&&d.ts>t&&l?.(o)!==!1)break;u+=1,s.delete(o),(d.value<0||d.ts>t||l?.(o)===!1)&&(s.set(o,d),(Number.isNaN(d.ts)||d.ts<r)&&(e=!1))}}}},E=(s,e,...r)=>s.exec.call(s,e,...r).toArray(),O=s=>{const{sql:e}=s,r=s.table??"_lunora_rate_limits";return E(e,`CREATE TABLE IF NOT EXISTS "${r}" (k TEXT PRIMARY KEY, value REAL NOT NULL, ts INTEGER NOT NULL, prev REAL)`),E(e,`CREATE INDEX IF NOT EXISTS "${r}_ts" ON "${r}" (ts) WHERE value >= 0`),{delete:t=>{E(e,`DELETE FROM "${r}" WHERE k = ?`,t)},sweep:(t,n,l)=>{const o=E(e,`SELECT k FROM "${r}" WHERE ts <= ? AND value >= 0 ORDER BY ts LIMIT ?`,t,n).map(({k:d})=>d).filter(d=>l?.(d)!==!1);o.length>0&&E(e,`DELETE FROM "${r}" WHERE k IN (SELECT value FROM json_each(?))`,JSON.stringify(o))},get:t=>{const l=E(e,`SELECT value, ts, prev FROM "${r}" WHERE k = ?`,t)[0];if(!l)return;const u={ts:l.ts,value:l.value};return l.prev!==null&&(u.prev=l.prev),u},set:(t,n)=>{E(e,`INSERT INTO "${r}" (k, value, ts, prev) VALUES (?, ?, ?, ?) ON CONFLICT(k) DO UPDATE SET value = excluded.value, ts = excluded.ts, prev = excluded.prev`,t,n.value,n.ts,n.prev??null)}}},N=s=>s.toString(16).padStart(2,"0"),I=async(s,e)=>{const t=[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${s}\0${e}`))).subarray(0,16)];t[6]=128+t[6]%16,t[8]=128+t[8]%64;const n=t.map(l=>N(l)).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`},T=s=>s?.code==="CONFLICT",m=s=>{const{db:e}=s,r=s.table??"rateLimits",t=s.keyField??"key",n=new Map;let l=!1;const u=async a=>{const i=await e.findFirst(r,{where:{[t]:a}});return n.set(a,i?i._id:void 0),i},o=async a=>(n.has(a)||await u(a),n.get(a)),d=(a,i)=>{const c={[t]:a,ts:i.ts,value:i.value};return i.prev!==void 0&&(c.prev=i.prev),c},p=async(a,i)=>{try{return n.set(a,await e.insert(r,i,{clientId:await I(r,a)})),!0}catch(c){if(T(c))return n.delete(a),!1;throw c}};return{delete:async a=>{const i=await o(a);i!==void 0&&await e.delete(r,i),n.delete(a)},get:async a=>{const i=await u(a);if(!i)return;const c={ts:i.ts,value:i.value};return i.prev!==null&&i.prev!==void 0&&(c.prev=i.prev),c},set:async(a,i)=>{const c=d(a,i);let v=await o(a);if(v===void 0){if(await p(a,c))return;await u(a),v=n.get(a)}v!==void 0&&await e.patchIf(r,v,{patch:c,where:{}})},setIf:async(a,i,c)=>{const v=d(a,i);if(c===void 0)return p(a,v);const w=await o(a);if(w===void 0)return!1;const{applied:f}=await e.patchIf(r,w,{patch:v,where:{prev:c.prev??null,ts:c.ts,value:c.value}});return f||n.delete(a),f},sweep:async(a,i,c)=>{if(e.findMany===void 0){l||(l=!0,console.warn(`@lunora/ratelimit: table "${r}" is not swept: the adapter has no findMany. Pass the framework's ctx.db.`));return}const{page:v}=await e.findMany(r,{limit:i,orderBy:[{ts:"asc"}],where:{ts:{lte:a},value:{gte:0}}}),w=v.filter(f=>c?.(String(f[t]))!==!1);await Promise.all(w.map(async f=>{await e.findFirst(r,{where:{_id:f._id,prev:f.prev??null,ts:f.ts,value:f.value}})!==null&&await e.delete(r,f._id)}))}}},L=s=>{const e=t=>{throw new b("INTERNAL",`@lunora/ratelimit: \`${t}\` needs a writable \`ctx.db\`, but this store was created with \`createReadOnlyDbStore\` (a query context). Use \`createDbStore\` from a mutation or action; a query can only call \`getValue\`/\`check\`.`)},r=m({...s,db:{delete:()=>e("delete"),findFirst:s.db.findFirst.bind(s.db),insert:()=>e("insert"),patchIf:()=>e("patchIf")}});return{delete:()=>e("reset"),get:r.get,set:()=>e("limit"),setIf:()=>e("limit")}};export{m as createDbStore,R as createMemoryStore,L as createReadOnlyDbStore,O as createSqlStore};