ovr 6.2.4 → 7.0.0-next.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.
Files changed (136) hide show
  1. package/README.md +3 -1
  2. package/dist/app/index.d.ts +51 -7
  3. package/dist/app/index.d.ts.map +1 -1
  4. package/dist/app/index.js +163 -28
  5. package/dist/auth/auth-data.d.ts +26 -0
  6. package/dist/auth/auth-data.d.ts.map +1 -0
  7. package/dist/auth/auth-data.js +42 -0
  8. package/dist/auth/cbor.d.ts +50 -0
  9. package/dist/auth/cbor.d.ts.map +1 -0
  10. package/dist/auth/cbor.js +200 -0
  11. package/dist/auth/client-source.d.ts +3 -0
  12. package/dist/auth/client-source.d.ts.map +1 -0
  13. package/dist/auth/client-source.js +3 -0
  14. package/dist/auth/client.d.ts +3 -0
  15. package/dist/auth/client.d.ts.map +1 -0
  16. package/dist/auth/client.js +186 -0
  17. package/dist/auth/configure.d.ts +28 -0
  18. package/dist/auth/configure.d.ts.map +1 -0
  19. package/dist/auth/configure.js +228 -0
  20. package/dist/auth/der.d.ts +6 -0
  21. package/dist/auth/der.d.ts.map +1 -0
  22. package/dist/auth/der.js +36 -0
  23. package/dist/auth/index.d.ts +242 -0
  24. package/dist/auth/index.d.ts.map +1 -0
  25. package/dist/auth/index.js +152 -0
  26. package/dist/auth/issue.d.ts +36 -0
  27. package/dist/auth/issue.d.ts.map +1 -0
  28. package/dist/auth/issue.js +47 -0
  29. package/dist/auth/metadata.d.ts +22 -0
  30. package/dist/auth/metadata.d.ts.map +1 -0
  31. package/dist/auth/metadata.js +134 -0
  32. package/dist/auth/oauth.d.ts +29 -0
  33. package/dist/auth/oauth.d.ts.map +1 -0
  34. package/dist/auth/oauth.js +724 -0
  35. package/dist/auth/passkey.d.ts +101 -0
  36. package/dist/auth/passkey.d.ts.map +1 -0
  37. package/dist/auth/passkey.js +393 -0
  38. package/dist/auth/state.d.ts +49 -0
  39. package/dist/auth/state.d.ts.map +1 -0
  40. package/dist/auth/state.js +184 -0
  41. package/dist/auth/storage.d.ts +193 -0
  42. package/dist/auth/storage.d.ts.map +1 -0
  43. package/dist/auth/storage.js +410 -0
  44. package/dist/auth/token.d.ts +12 -0
  45. package/dist/auth/token.d.ts.map +1 -0
  46. package/dist/auth/token.js +39 -0
  47. package/dist/context/index.d.ts +86 -16
  48. package/dist/context/index.d.ts.map +1 -1
  49. package/dist/context/index.js +166 -42
  50. package/dist/cookie/index.d.ts +3 -0
  51. package/dist/cookie/index.d.ts.map +1 -1
  52. package/dist/cookie/index.js +1 -0
  53. package/dist/database/index.d.ts +262 -0
  54. package/dist/database/index.d.ts.map +1 -0
  55. package/dist/database/index.js +807 -0
  56. package/dist/form/index.d.ts +699 -0
  57. package/dist/form/index.d.ts.map +1 -0
  58. package/dist/form/index.js +901 -0
  59. package/dist/index.d.ts +10 -3
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +9 -3
  62. package/dist/jsx/elements.d.ts +28 -2
  63. package/dist/jsx/elements.d.ts.map +1 -1
  64. package/dist/jsx/index.d.ts +20 -4
  65. package/dist/jsx/index.d.ts.map +1 -1
  66. package/dist/jsx/index.js +6 -65
  67. package/dist/limiter/index.d.ts +65 -0
  68. package/dist/limiter/index.d.ts.map +1 -0
  69. package/dist/limiter/index.js +157 -0
  70. package/dist/markdown/index.d.ts +61 -0
  71. package/dist/markdown/index.d.ts.map +1 -0
  72. package/dist/markdown/index.js +1160 -0
  73. package/dist/markup/index.d.ts +188 -0
  74. package/dist/markup/index.d.ts.map +1 -0
  75. package/dist/markup/index.js +718 -0
  76. package/dist/mcp/index.d.ts +73 -0
  77. package/dist/mcp/index.d.ts.map +1 -0
  78. package/dist/mcp/index.js +988 -0
  79. package/dist/middleware/index.d.ts +3 -4
  80. package/dist/middleware/index.d.ts.map +1 -1
  81. package/dist/multipart/index.d.ts +53 -7
  82. package/dist/multipart/index.d.ts.map +1 -1
  83. package/dist/multipart/index.js +332 -124
  84. package/dist/route/index.d.ts +226 -80
  85. package/dist/route/index.d.ts.map +1 -1
  86. package/dist/route/index.js +239 -99
  87. package/dist/schema/index.d.ts +307 -734
  88. package/dist/schema/index.d.ts.map +1 -1
  89. package/dist/schema/index.js +783 -1050
  90. package/dist/table/index.d.ts +132 -0
  91. package/dist/table/index.d.ts.map +1 -0
  92. package/dist/table/index.js +188 -0
  93. package/dist/trie/index.js +4 -4
  94. package/dist/util/index.d.ts +37 -5
  95. package/dist/util/index.d.ts.map +1 -1
  96. package/dist/util/index.js +156 -41
  97. package/package.json +11 -4
  98. package/src/app/index.ts +230 -42
  99. package/src/auth/auth-data.ts +56 -0
  100. package/src/auth/cbor.ts +231 -0
  101. package/src/auth/client-source.ts +3 -0
  102. package/src/auth/client.ts +205 -0
  103. package/src/auth/configure.ts +279 -0
  104. package/src/auth/der.ts +35 -0
  105. package/src/auth/index.ts +387 -0
  106. package/src/auth/issue.ts +52 -0
  107. package/src/auth/metadata.ts +149 -0
  108. package/src/auth/oauth.ts +882 -0
  109. package/src/auth/passkey.ts +556 -0
  110. package/src/auth/state.ts +213 -0
  111. package/src/auth/storage.ts +572 -0
  112. package/src/auth/token.ts +67 -0
  113. package/src/context/index.ts +240 -65
  114. package/src/cookie/index.ts +3 -0
  115. package/src/database/index.ts +1193 -0
  116. package/src/form/index.ts +1720 -0
  117. package/src/index.ts +10 -3
  118. package/src/jsx/elements.ts +45 -25
  119. package/src/jsx/index.ts +24 -69
  120. package/src/limiter/index.ts +221 -0
  121. package/src/markdown/index.ts +1322 -0
  122. package/src/markup/index.ts +853 -0
  123. package/src/mcp/conformance.2025-11-25.yml +39 -0
  124. package/src/mcp/conformance.2026-07-28.yml +56 -0
  125. package/src/mcp/index.ts +1262 -0
  126. package/src/middleware/index.ts +5 -6
  127. package/src/multipart/index.ts +410 -158
  128. package/src/route/index.ts +559 -278
  129. package/src/schema/index.ts +1542 -2256
  130. package/src/table/index.ts +387 -0
  131. package/src/trie/index.ts +4 -4
  132. package/src/util/index.ts +163 -49
  133. package/dist/render/index.d.ts +0 -79
  134. package/dist/render/index.d.ts.map +0 -1
  135. package/dist/render/index.js +0 -257
  136. package/src/render/index.ts +0 -314
package/src/index.ts CHANGED
@@ -1,7 +1,14 @@
1
1
  export { App } from "./app/index.js";
2
- export { JSX } from "./jsx/index.js";
2
+ export { Auth } from "./auth/index.js";
3
+ export { Database } from "./database/index.js";
4
+ export { Limiter } from "./limiter/index.js";
5
+ export { Mcp } from "./mcp/index.js";
6
+ export type { JSX } from "./jsx/index.js";
3
7
  export type { Middleware } from "./middleware/index.js";
4
8
  export { Multipart } from "./multipart/index.js";
5
- export { Render } from "./render/index.js";
9
+ export { Markup } from "./markup/index.js";
10
+ export { Markdown } from "./markdown/index.js";
6
11
  export { Route } from "./route/index.js";
7
- export { Field, Form, Schema } from "./schema/index.js";
12
+ export { Table } from "./table/index.js";
13
+ export { Field } from "./form/index.js";
14
+ export { Schema } from "./schema/index.js";
@@ -328,6 +328,8 @@ type FieldsetAttributes = Attributes<{
328
328
  disabled: boolean;
329
329
  form: string;
330
330
  name: string;
331
+ /** WebMCP description of a radio group for browser agents */
332
+ toolparamdescription: string;
331
333
  }>;
332
334
 
333
335
  type FormAttributes = Attributes<{
@@ -350,6 +352,12 @@ type FormAttributes = Attributes<{
350
352
  method: SharedAttributes["method"];
351
353
  novalidate: boolean;
352
354
  target: SharedAttributes["target"];
355
+ /** [WebMCP](https://developer.chrome.com/docs/ai/webmcp/declarative-api) tool name for browser agents */
356
+ toolname: string;
357
+ /** WebMCP tool description, required with `toolname` */
358
+ tooldescription: string;
359
+ /** Lets a browser agent submit the form without the user clicking */
360
+ toolautosubmit: boolean;
353
361
  }>;
354
362
 
355
363
  type HtmlAttributes = Attributes<{ xmlns: string }>;
@@ -445,6 +453,8 @@ type InputAttributes = Attributes<
445
453
  value: string | number;
446
454
  webkitdirectory: boolean;
447
455
  width: string;
456
+ /** WebMCP parameter description for browser agents */
457
+ toolparamdescription: string;
448
458
  },
449
459
  never
450
460
  >;
@@ -607,6 +617,8 @@ type SelectAttributes = Attributes<{
607
617
  name: string;
608
618
  required: boolean;
609
619
  size: string | number;
620
+ /** WebMCP parameter description for browser agents */
621
+ toolparamdescription: string;
610
622
  }>;
611
623
 
612
624
  type SlotAttributes = Attributes<{ name: string }>;
@@ -656,6 +668,8 @@ type TextareaAttributes = Attributes<{
656
668
  required: boolean;
657
669
  rows: string | number;
658
670
  wrap: "hard" | "soft" | "off";
671
+ /** WebMCP parameter description for browser agents */
672
+ toolparamdescription: string;
659
673
  }>;
660
674
 
661
675
  type ThAttributes = Attributes<{
@@ -697,6 +711,12 @@ type VideoAttributes = Attributes<{
697
711
  }>;
698
712
 
699
713
  // XML
714
+ /**
715
+ * Attributes of an XML element.
716
+ *
717
+ * @template P Element attributes
718
+ * @template Children Children the element accepts
719
+ */
700
720
  type XMLAttributes<
701
721
  P extends JSX.Props = JSX.Props,
702
722
  Children = JSX.Element,
@@ -730,6 +750,12 @@ type AtomLinkAttributes = {
730
750
 
731
751
  // SVG
732
752
  // SVG
753
+ /**
754
+ * Attributes of an SVG element.
755
+ *
756
+ * @template P Element attributes
757
+ * @template Children Children the element accepts
758
+ */
733
759
  type SvgAttributes<
734
760
  P extends JSX.Props = JSX.Props,
735
761
  Children = JSX.Element,
@@ -867,32 +893,26 @@ type SvgImageAttributes = SvgAttributes<{
867
893
  preserveAspectRatio: SvgRootAttributes["preserveAspectRatio"];
868
894
  }>;
869
895
 
870
- type SvgLinearGradientAttributes = SvgAttributes<
871
- {
872
- x1: string | number;
873
- y1: string | number;
874
- x2: string | number;
875
- y2: string | number;
876
- gradientUnits: "userSpaceOnUse" | "objectBoundingBox";
877
- gradientTransform: string;
878
- spreadMethod: "pad" | "reflect" | "repeat";
879
- },
880
- undefined
881
- >;
896
+ type SvgLinearGradientAttributes = SvgAttributes<{
897
+ x1: string | number;
898
+ y1: string | number;
899
+ x2: string | number;
900
+ y2: string | number;
901
+ gradientUnits: "userSpaceOnUse" | "objectBoundingBox";
902
+ gradientTransform: string;
903
+ spreadMethod: "pad" | "reflect" | "repeat";
904
+ }>;
882
905
 
883
- type SvgRadialGradientAttributes = SvgAttributes<
884
- {
885
- cx: string | number;
886
- cy: string | number;
887
- r: string | number;
888
- fx: string | number;
889
- fy: string | number;
890
- gradientUnits: "userSpaceOnUse" | "objectBoundingBox";
891
- gradientTransform: string;
892
- spreadMethod: "pad" | "reflect" | "repeat";
893
- },
894
- undefined
895
- >;
906
+ type SvgRadialGradientAttributes = SvgAttributes<{
907
+ cx: string | number;
908
+ cy: string | number;
909
+ r: string | number;
910
+ fx: string | number;
911
+ fy: string | number;
912
+ gradientUnits: "userSpaceOnUse" | "objectBoundingBox";
913
+ gradientTransform: string;
914
+ spreadMethod: "pad" | "reflect" | "repeat";
915
+ }>;
896
916
 
897
917
  type SvgStopAttributes = SvgAttributes<
898
918
  {
package/src/jsx/index.ts CHANGED
@@ -1,8 +1,18 @@
1
- import { Render } from "../render/index.js";
1
+ import { Element, type Markup } from "../markup/index.js";
2
2
  import type { IntrinsicElements as IE } from "./elements.js";
3
3
 
4
4
  export namespace JSX {
5
+ /**
6
+ * `T`, or a promise of it.
7
+ *
8
+ * @template T Value
9
+ */
5
10
  type MaybePromise<T> = T | Promise<T>;
11
+ /**
12
+ * `T`, or a function returning it.
13
+ *
14
+ * @template T Value
15
+ */
6
16
  type MaybeFunction<T> = T | (() => T);
7
17
 
8
18
  /** Standard HTML elements */
@@ -26,90 +36,35 @@ export namespace JSX {
26
36
 
27
37
  /** Unknown component props */
28
38
  export type Props = Record<string, JSX.Element>;
29
- }
30
39
 
31
- /** ovr JSX */
32
- export class JSX {
33
40
  /**
34
- * These are the HTML tags that do not require a closing tag.
35
- *
36
- * [MDN Reference](https://developer.mozilla.org/en-US/docs/Glossary/Void_element#self-closing_tags)
41
+ * What a tag can be: an element's name, or a component, which is a
42
+ * function. A class is not one, so `<Form />` with the `Form` class is a
43
+ * type error instead of failing as it renders.
37
44
  */
38
- static readonly #void = new Set([
39
- "area",
40
- "base",
41
- "br",
42
- "col",
43
- "embed",
44
- "hr",
45
- "img",
46
- "input",
47
- "link",
48
- "meta",
49
- "source",
50
- "track",
51
- "wbr",
52
- "xml",
53
- ]);
45
+ export type ElementType = string | ((props: any) => unknown);
46
+ }
54
47
 
48
+ /** ovr JSX */
49
+ export class JSX {
55
50
  /**
56
51
  * The main function of the JSX transform cycle, each time JSX is encountered
57
52
  * it is passed into `jsx` to be resolved.
58
53
  *
54
+ * @template P Props of the element or component
59
55
  * @param tag tag name or function component
60
56
  * @param props object containing all the properties and attributes passed to the element or component
61
- * @yields `Chunk`s of HTML
57
+ * @returns Generator of the element's `Chunk`s of HTML
62
58
  */
63
- static async *jsx<P extends JSX.Props = JSX.Props>(
59
+ static jsx<P extends JSX.Props = JSX.Props>(
64
60
  tag: ((props: P) => JSX.Element) | string,
65
61
  props: P,
66
- ): AsyncGenerator<Render.Chunk, void, unknown> {
62
+ ): AsyncGenerator<Markup.Chunk, void, unknown> {
67
63
  // this function doesn't need to be called recursively
68
64
  // JSX will be transformed into `jsx()` function calls automatically
69
65
 
70
- if (typeof tag === "function") {
71
- // component or fragment
72
- yield* new Render(tag(props));
73
- return;
74
- }
75
-
76
- // intrinsic element
77
- // faster to concatenate attributes than to yield them as separate chunks
78
- let opening = tag;
79
-
80
- for (const key in props) {
81
- // more memory efficient to skip children instead of destructuring and using ...rest
82
- if (key === "children") continue;
83
-
84
- const value = props[key];
85
-
86
- if (value === true) {
87
- // just put the key without the value
88
- opening += ` ${key}`;
89
- } else if (typeof value === "string") {
90
- opening += ` ${key}="${Render.escape(value, true)}"`;
91
- } else if (typeof value === "number" || typeof value === "bigint") {
92
- opening += ` ${key}="${value}"`;
93
- }
94
- // otherwise, don't include the attribute
95
- }
96
-
97
- if (tag === "html") {
98
- yield Render.html(`<!doctype html><${opening}>`);
99
- } else if (tag === "xml") {
100
- yield Render.html(`<?${opening}?>`);
101
- } else {
102
- yield Render.html(`<${opening}>`);
103
- }
104
-
105
- // if children and a void element, render it like normal
106
- // to account for cases like XML <link>content</link>
107
- // assumes the user knows what they are doing
108
- if (props.children == null && JSX.#void.has(tag)) return;
109
-
110
- yield* new Render(props.children);
111
-
112
- yield Render.html(`</${tag}>`);
66
+ // a component is called, and an element's markup built, when it is rendered
67
+ return new Element(tag, props);
113
68
  }
114
69
 
115
70
  /**
@@ -0,0 +1,221 @@
1
+ import type { Context as ContextType } from "../context/index.js";
2
+ import { type Database, owned } from "../database/index.js";
3
+ import type { Middleware } from "../middleware/index.js";
4
+ import { Schema } from "../schema/index.js";
5
+ import { Table } from "../table/index.js";
6
+ import { Codec, Time, noStore } from "../util/index.js";
7
+
8
+ /**
9
+ * Internal to ovr, which counts each client this way.
10
+ *
11
+ * @param value Client IP
12
+ * @returns The IPv4 address, or the IPv6 /64 network, one home or office
13
+ */
14
+ export function network(value: string | undefined) {
15
+ if (!value || value.length > 64 || !/^[\da-f:.]+$/i.test(value)) return;
16
+ if (!value.includes(":")) {
17
+ const octets = value.split(".");
18
+
19
+ return octets.length === 4 &&
20
+ octets.every((v) => /^(0|[1-9]\d{0,2})$/.test(v) && Number(v) <= 255)
21
+ ? value
22
+ : undefined;
23
+ }
24
+ let host: string;
25
+ try {
26
+ host = new URL(`http://[${value}]`).hostname;
27
+ } catch {
28
+ return;
29
+ }
30
+ const [head = "", tail = ""] = host.slice(1, -1).split("::");
31
+ const first = head ? head.split(":") : [];
32
+ const last = tail ? tail.split(":") : [];
33
+ const groups: string[] = [
34
+ ...first,
35
+ ...Array<string>(8 - first.length - last.length).fill("0"),
36
+ ...last,
37
+ ];
38
+ // IPv4-mapped IPv6 addresses share their IPv4 budget, rather than one giant ::ffff /64 bucket.
39
+ if (groups.slice(0, 5).every((v) => v === "0") && groups[5] === "ffff") {
40
+ const high = parseInt(groups[6]!, 16);
41
+ const low = parseInt(groups[7]!, 16);
42
+ return [high >> 8, high & 255, low >> 8, low & 255].join(".");
43
+ }
44
+ return (
45
+ groups
46
+ .map((v, i) => (i < 4 ? parseInt(v, 16).toString(16) : "0"))
47
+ .join(":") + "/64"
48
+ );
49
+ }
50
+
51
+ export namespace Limiter {
52
+ /**
53
+ * Request capabilities available before parsing a body, including the
54
+ * session, so a `key` can count each signed-in user.
55
+ */
56
+ export type Context = Pick<
57
+ ContextType,
58
+ "req" | "url" | "ip" | "cookie" | "res" | "session"
59
+ >;
60
+ /** A token bucket allows an initial burst, then replenishes continuously. */
61
+ export interface Policy {
62
+ readonly limit: number;
63
+ readonly interval: number;
64
+ }
65
+ /** Shared Postgres storage, with a default policy of 60 requests per minute. */
66
+ export interface Options extends Partial<Policy> {
67
+ /** Database containing `Limiter.table`, shared by every instance. */
68
+ readonly database: Database & {
69
+ readonly [Name in (typeof Limiter.table)["name"]]: typeof Limiter.table;
70
+ };
71
+ /** Override trusted-IP keying, for example with an authenticated user ID. Missing keys fail closed. */
72
+ readonly key?: (
73
+ c: Context,
74
+ ) => string | undefined | Promise<string | undefined>;
75
+ }
76
+ }
77
+
78
+ /** Internal failure to apply a rate limit; callers must not admit the request. */
79
+ export class LimitIssue extends Error {}
80
+
81
+ /** Token buckets stored in Postgres, usable by authentication and ordinary route middleware. */
82
+ export class Limiter {
83
+ /**
84
+ * Token buckets shared by every limiter, include it in the database's
85
+ * tables. `database.migrate` then creates it, `Auth.tables` already includes it.
86
+ */
87
+ static readonly table = new Table("rate_limits", {
88
+ key: Schema.string(),
89
+ tokens: Schema.number(),
90
+ time: Schema.number().int(),
91
+ expiration: Schema.number().int(),
92
+ });
93
+
94
+ static {
95
+ // a version never changes, later changes ship as new versions
96
+ owned.set(Limiter.table, [
97
+ {
98
+ id: "rate_limits:1",
99
+ sql: `CREATE TABLE rate_limits (
100
+ key text PRIMARY KEY,
101
+ tokens double precision NOT NULL,
102
+ time bigint NOT NULL,
103
+ expiration bigint NOT NULL
104
+ );
105
+ CREATE INDEX rate_limits_expiration ON rate_limits (expiration);`,
106
+ },
107
+ ]);
108
+ }
109
+
110
+ readonly #name;
111
+ readonly #options;
112
+ #pruned = 0;
113
+
114
+ /**
115
+ * Create a policy backed by the application's database.
116
+ *
117
+ * @param name Stable name of the policy's buckets. Limiters with the same name and policy share them, across every server using the database.
118
+ */
119
+ constructor(name: string, options: Limiter.Options) {
120
+ this.#options = { limit: 60, interval: Time.minute, ...options };
121
+ this.#name = name;
122
+ }
123
+
124
+ /** Admit a request or return its retry deadline. Scopes have independent budgets. */
125
+ async check(c: Limiter.Context, scope = ""): Promise<true | Date> {
126
+ const identity = this.#options.key
127
+ ? await this.#options.key(c)
128
+ : network(c.ip);
129
+ if (typeof identity !== "string" || !identity || identity.length > 1024)
130
+ throw new LimitIssue(
131
+ "Rate limiting requires a trusted client IP in App.fetch(request, { ip }), or an explicit authenticated key",
132
+ );
133
+ const { limit, interval } = this.#options;
134
+ // Different policies cannot interpret the same stored token balance
135
+ // differently. Hashed, so a long name, scope, or identity always fits
136
+ // in the primary key's index.
137
+ const retry = await this.#consume(
138
+ Codec.Base64Url.encode(
139
+ new Uint8Array(
140
+ await crypto.subtle.digest(
141
+ "SHA-256",
142
+ Codec.encode(
143
+ JSON.stringify([this.#name, limit, interval, scope, identity]),
144
+ ),
145
+ ),
146
+ ),
147
+ ),
148
+ );
149
+ if (retry === true) return true;
150
+ const now = Date.now();
151
+ return new Date(
152
+ Math.min(now + 3600000, Math.max(now + 1000, Math.ceil(retry))),
153
+ );
154
+ }
155
+
156
+ /**
157
+ * Mount globally with app.use(), or on selected routes. A missing identity
158
+ * or storage failure throws, so the app's error handling sees it and the
159
+ * request is not admitted.
160
+ */
161
+ readonly middleware: Middleware = async (c, next) => {
162
+ const result = await this.check(c);
163
+ if (result === true) return next();
164
+ noStore(c.res.headers);
165
+ c.res.headers.set(
166
+ "retry-after",
167
+ String(Math.max(1, Math.ceil((result.getTime() - Date.now()) / 1000))),
168
+ );
169
+ c.text("Too many requests. Try again later.", 429);
170
+ };
171
+
172
+ /**
173
+ * Atomically refill and consume a token, in one statement when admitted.
174
+ *
175
+ * @param key Bucket key
176
+ * @returns `true` when admitted, otherwise the retry time in milliseconds
177
+ */
178
+ async #consume(key: string) {
179
+ const { database: db, limit, interval } = this.#options;
180
+ const table = Limiter.table;
181
+ const now = Date.now();
182
+
183
+ // either direction, so a clock moving back cannot stop pruning
184
+ if (Math.abs(now - this.#pruned) >= Time.minute) {
185
+ this.#pruned = now;
186
+ await db.sql`DELETE FROM ${table} WHERE expiration <= ${now}`;
187
+ }
188
+
189
+ // expired buckets start full, others refill continuously since their last use
190
+ const tokens = db.sql`CASE WHEN l.expiration > ${now}::bigint
191
+ THEN LEAST(${limit}::float8, l.tokens + GREATEST(0, ${now}::bigint - l.time) * ${limit}::float8 / ${interval}::float8)
192
+ ELSE ${limit}::float8 END`;
193
+ const admitted = await db.sql`
194
+ INSERT INTO ${table} AS l (key, tokens, time, expiration)
195
+ VALUES (${key}, ${limit - 1}, ${now}, ${now + interval})
196
+ ON CONFLICT (key) DO UPDATE SET
197
+ tokens = ${tokens} - 1,
198
+ time = GREATEST(${now}::bigint, l.time),
199
+ expiration = ${now + interval}
200
+ WHERE ${tokens} >= 1
201
+ RETURNING 1
202
+ `;
203
+
204
+ if (admitted.length) return true;
205
+
206
+ const [bucket] = await db.sql`
207
+ SELECT * FROM ${table} WHERE key = ${key}
208
+ `.parse(Limiter.table);
209
+ const available =
210
+ !bucket || bucket.expiration <= now
211
+ ? limit
212
+ : Math.min(
213
+ limit,
214
+ bucket.tokens + (Math.max(0, now - bucket.time) * limit) / interval,
215
+ );
216
+
217
+ return (
218
+ now + Math.max(1000, Math.ceil(((1 - available) * interval) / limit))
219
+ );
220
+ }
221
+ }