@connextar/house 0.22.3 → 0.23.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 (114) hide show
  1. package/README.md +570 -60
  2. package/dist/admin/index.d.ts +2 -2
  3. package/dist/admin/index.d.ts.map +1 -1
  4. package/dist/admin/index.js +2 -2
  5. package/dist/admin/index.js.map +1 -1
  6. package/dist/admin/proof.d.ts +49 -9
  7. package/dist/admin/proof.d.ts.map +1 -1
  8. package/dist/admin/proof.js +83 -4
  9. package/dist/admin/proof.js.map +1 -1
  10. package/dist/admin/second-factor.d.ts +3 -1
  11. package/dist/admin/second-factor.d.ts.map +1 -1
  12. package/dist/admin/second-factor.js +3 -2
  13. package/dist/admin/second-factor.js.map +1 -1
  14. package/dist/admin/view-as.d.ts +37 -5
  15. package/dist/admin/view-as.d.ts.map +1 -1
  16. package/dist/admin/view-as.js +67 -6
  17. package/dist/admin/view-as.js.map +1 -1
  18. package/dist/analytics/browser.d.ts +108 -0
  19. package/dist/analytics/browser.d.ts.map +1 -0
  20. package/dist/analytics/browser.js +319 -0
  21. package/dist/analytics/browser.js.map +1 -0
  22. package/dist/analytics/client-index.d.ts +6 -0
  23. package/dist/analytics/client-index.d.ts.map +1 -0
  24. package/dist/analytics/client-index.js +6 -0
  25. package/dist/analytics/client-index.js.map +1 -0
  26. package/dist/analytics/config.d.ts +50 -0
  27. package/dist/analytics/config.d.ts.map +1 -0
  28. package/dist/analytics/config.js +39 -0
  29. package/dist/analytics/config.js.map +1 -0
  30. package/dist/analytics/index.d.ts +10 -0
  31. package/dist/analytics/index.d.ts.map +1 -0
  32. package/dist/analytics/index.js +10 -0
  33. package/dist/analytics/index.js.map +1 -0
  34. package/dist/analytics/ingest.d.ts +30 -0
  35. package/dist/analytics/ingest.d.ts.map +1 -0
  36. package/dist/analytics/ingest.js +64 -0
  37. package/dist/analytics/ingest.js.map +1 -0
  38. package/dist/analytics/react-index.d.ts +6 -0
  39. package/dist/analytics/react-index.d.ts.map +1 -0
  40. package/dist/analytics/react-index.js +6 -0
  41. package/dist/analytics/react-index.js.map +1 -0
  42. package/dist/analytics/react.d.ts +75 -0
  43. package/dist/analytics/react.d.ts.map +1 -0
  44. package/dist/analytics/react.js +159 -0
  45. package/dist/analytics/react.js.map +1 -0
  46. package/dist/analytics/redact.d.ts +35 -0
  47. package/dist/analytics/redact.d.ts.map +1 -0
  48. package/dist/analytics/redact.js +109 -0
  49. package/dist/analytics/redact.js.map +1 -0
  50. package/dist/analytics/server-index.d.ts +6 -0
  51. package/dist/analytics/server-index.d.ts.map +1 -0
  52. package/dist/analytics/server-index.js +6 -0
  53. package/dist/analytics/server-index.js.map +1 -0
  54. package/dist/analytics/server.d.ts +89 -0
  55. package/dist/analytics/server.d.ts.map +1 -0
  56. package/dist/analytics/server.js +211 -0
  57. package/dist/analytics/server.js.map +1 -0
  58. package/dist/jobs/idle.d.ts +49 -0
  59. package/dist/jobs/idle.d.ts.map +1 -0
  60. package/dist/jobs/idle.js +61 -0
  61. package/dist/jobs/idle.js.map +1 -0
  62. package/dist/jobs/index.d.ts +2 -1
  63. package/dist/jobs/index.d.ts.map +1 -1
  64. package/dist/jobs/index.js +2 -1
  65. package/dist/jobs/index.js.map +1 -1
  66. package/dist/jobs/next-index.d.ts +5 -0
  67. package/dist/jobs/next-index.d.ts.map +1 -0
  68. package/dist/jobs/next-index.js +5 -0
  69. package/dist/jobs/next-index.js.map +1 -0
  70. package/dist/jobs/next.d.ts +25 -0
  71. package/dist/jobs/next.d.ts.map +1 -0
  72. package/dist/jobs/next.js +51 -0
  73. package/dist/jobs/next.js.map +1 -0
  74. package/dist/jobs/prisma-index.d.ts +6 -0
  75. package/dist/jobs/prisma-index.d.ts.map +1 -0
  76. package/dist/jobs/prisma-index.js +6 -0
  77. package/dist/jobs/prisma-index.js.map +1 -0
  78. package/dist/jobs/prisma.d.ts +77 -0
  79. package/dist/jobs/prisma.d.ts.map +1 -0
  80. package/dist/jobs/prisma.js +92 -0
  81. package/dist/jobs/prisma.js.map +1 -0
  82. package/dist/jobs/scheduler.d.ts +7 -0
  83. package/dist/jobs/scheduler.d.ts.map +1 -1
  84. package/dist/jobs/scheduler.js +10 -0
  85. package/dist/jobs/scheduler.js.map +1 -1
  86. package/dist/rate-limit/better-auth.d.ts +50 -0
  87. package/dist/rate-limit/better-auth.d.ts.map +1 -0
  88. package/dist/rate-limit/better-auth.js +64 -0
  89. package/dist/rate-limit/better-auth.js.map +1 -0
  90. package/dist/rate-limit/index.d.ts +13 -0
  91. package/dist/rate-limit/index.d.ts.map +1 -0
  92. package/dist/rate-limit/index.js +13 -0
  93. package/dist/rate-limit/index.js.map +1 -0
  94. package/dist/rate-limit/keys.d.ts +45 -0
  95. package/dist/rate-limit/keys.d.ts.map +1 -0
  96. package/dist/rate-limit/keys.js +95 -0
  97. package/dist/rate-limit/keys.js.map +1 -0
  98. package/dist/rate-limit/limiter.d.ts +114 -0
  99. package/dist/rate-limit/limiter.d.ts.map +1 -0
  100. package/dist/rate-limit/limiter.js +166 -0
  101. package/dist/rate-limit/limiter.js.map +1 -0
  102. package/dist/rate-limit/prisma-index.d.ts +6 -0
  103. package/dist/rate-limit/prisma-index.d.ts.map +1 -0
  104. package/dist/rate-limit/prisma-index.js +6 -0
  105. package/dist/rate-limit/prisma-index.js.map +1 -0
  106. package/dist/rate-limit/prisma.d.ts +116 -0
  107. package/dist/rate-limit/prisma.d.ts.map +1 -0
  108. package/dist/rate-limit/prisma.js +79 -0
  109. package/dist/rate-limit/prisma.js.map +1 -0
  110. package/dist/rate-limit/store.d.ts +27 -0
  111. package/dist/rate-limit/store.d.ts.map +1 -0
  112. package/dist/rate-limit/store.js +28 -0
  113. package/dist/rate-limit/store.js.map +1 -0
  114. package/package.json +36 -1
@@ -0,0 +1,114 @@
1
+ import type { RateLimitStore } from "./store.js";
2
+ /**
3
+ * A fixed-window limiter over the app's own table — the one every app with a `rate_limit` table wrote, eleven times.
4
+ *
5
+ * Each copy had one thing the others lacked, and the union is here: AltEd's per-rule `failClosed`, variable cost and
6
+ * "everyone" ceilings; Quickie's long keys hashed rather than refused, private keys made unreadable, a `usage` that
7
+ * reads without spending, and IPv6 counted per /64; PharmaLine's read that fails closed. All but PharmaLine failed open
8
+ * on every database error, including the long-key one that turned a limit off.
9
+ *
10
+ * Windows are fixed and aligned to the epoch — `windowAt` is `now` rounded down to `windowMs` — so a daily rule's day
11
+ * is the UTC day, every app's rows keep counting, and two instances agree on a window without talking.
12
+ */
13
+ export interface RateLimitRule {
14
+ /** Most uses in one window. */
15
+ limit: number;
16
+ windowMs: number;
17
+ /**
18
+ * When the count cannot be read or written: refuse (`true`) or allow (default). Fail closed where a use spends
19
+ * money or reaches someone — a paid model call, an email to a stranger, a code check — and open where a refusal
20
+ * would only stop somebody reading their own page while the database is down.
21
+ */
22
+ failClosed?: boolean;
23
+ /**
24
+ * A ceiling over every caller together, checked after the caller's own: "300 class requests a day across the whole
25
+ * site, 5 each". Its own key, a limit, and a window (the rule's, unless given).
26
+ */
27
+ everyone?: {
28
+ key: string;
29
+ limit: number;
30
+ windowMs?: number;
31
+ };
32
+ }
33
+ export interface RateLimitResult {
34
+ allowed: boolean;
35
+ /** Uses left in the window that decided — the caller's, or everyone's when that ceiling refused. */
36
+ remaining: number;
37
+ limit: number;
38
+ /** When the deciding window ends. */
39
+ resetAt: Date;
40
+ /** Seconds until then, at least 1. */
41
+ retryAfter: number;
42
+ /** Which limit refused: the caller's own, or the ceiling over everyone. Absent when allowed. */
43
+ refusedBy?: "caller" | "everyone";
44
+ /** The count could not be read or written, and the rule's `failClosed` decided. */
45
+ failed?: true;
46
+ }
47
+ export interface RateLimitUsage {
48
+ /** Spent in the current window, at most `limit`. */
49
+ used: number;
50
+ limit: number;
51
+ remaining: number;
52
+ resetAt: Date;
53
+ /** The ceiling over everyone, when the rule has one. */
54
+ everyone?: {
55
+ used: number;
56
+ limit: number;
57
+ remaining: number;
58
+ resetAt: Date;
59
+ };
60
+ /** The count could not be read: `used` is the whole limit under `failClosed`, nothing otherwise. */
61
+ failed?: true;
62
+ }
63
+ export interface RateLimiterLogger {
64
+ error(message: string, ...detail: unknown[]): void;
65
+ }
66
+ export interface AutoPruneOptions {
67
+ /** The chance, from 0 to 1, that an allowed `consume` prunes afterwards. FB Web's 0.01. */
68
+ chance: number;
69
+ olderThanMs?: number;
70
+ batch?: number;
71
+ /** Run the prune after the response: Next's `after`. Default: started and not awaited, errors logged. */
72
+ schedule?: (task: () => Promise<void>) => void;
73
+ }
74
+ export interface RateLimiterOptions {
75
+ store: RateLimitStore;
76
+ /** For `privateKey`. At least 32 characters; the app's `BETTER_AUTH_SECRET` serves. */
77
+ secret?: string;
78
+ /** The `key` column's width. Default 200; longer keys are stored hashed (`storedKey`). */
79
+ maxKeyLength?: number;
80
+ /** For apps with no job to prune from (KRP, MAS, FB Web, Tracker C): prune now and then, as windows are spent. */
81
+ autoPrune?: AutoPruneOptions;
82
+ logger?: RateLimiterLogger;
83
+ /** For tests. */
84
+ now?: () => number;
85
+ /** For tests of `autoPrune`. */
86
+ random?: () => number;
87
+ }
88
+ export interface PruneOptions {
89
+ /** Windows that started longer ago than this go. Default seven days — longer than any rule's window. */
90
+ olderThanMs?: number;
91
+ /** At most this many a call. Default 1,000. */
92
+ batch?: number;
93
+ }
94
+ export interface RateLimiter {
95
+ /** Spend `amount` (default 1) of the key's window and say whether it was allowed. Never throws for the store. */
96
+ consume(key: string, rule: RateLimitRule, amount?: number): Promise<RateLimitResult>;
97
+ /** How much of the window is spent, without spending any — for a page that shows a budget. */
98
+ usage(key: string, rule: RateLimitRule): Promise<RateLimitUsage>;
99
+ /** `prefix:` and an HMAC of the parts, keyed by `secret` — for an email address or a token in a key. */
100
+ privateKey(prefix: string, ...parts: string[]): string;
101
+ /** Delete old windows, at most a batch a call. For the app's housekeeping job. */
102
+ prune(options?: PruneOptions): Promise<number>;
103
+ }
104
+ export declare const DEFAULT_RATE_LIMIT_RETENTION_MS: number;
105
+ export declare const DEFAULT_RATE_LIMIT_PRUNE_BATCH = 1000;
106
+ /** Checks a rule table where it is declared, so a typo is found when the module loads rather than in a refusal. */
107
+ export declare function defineRateLimits<T extends Record<string, RateLimitRule>>(rules: T): T;
108
+ export declare function createRateLimiter(options: RateLimiterOptions): RateLimiter;
109
+ /**
110
+ * The standard headers for a limited response: `x-ratelimit-limit`, `-remaining` and `-reset` (epoch seconds), and
111
+ * `retry-after` (seconds) when refused.
112
+ */
113
+ export declare function rateLimitHeaders(result: RateLimitResult): Record<string, string>;
114
+ //# sourceMappingURL=limiter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limiter.d.ts","sourceRoot":"","sources":["../../src/rate-limit/limiter.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD;;;;;;;;;;GAUG;AAEH,MAAM,WAAW,aAAa;IAC5B,+BAA+B;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;OAGG;IACH,QAAQ,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC9D;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,OAAO,CAAC;IACjB,oGAAoG;IACpG,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,qCAAqC;IACrC,OAAO,EAAE,IAAI,CAAC;IACd,sCAAsC;IACtC,UAAU,EAAE,MAAM,CAAC;IACnB,gGAAgG;IAChG,SAAS,CAAC,EAAE,QAAQ,GAAG,UAAU,CAAC;IAClC,mFAAmF;IACnF,MAAM,CAAC,EAAE,IAAI,CAAC;CACf;AAED,MAAM,WAAW,cAAc;IAC7B,oDAAoD;IACpD,IAAI,EAAE,MAAM,C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AiH;IACjH,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IACrF,8FAA8F;IAC9F,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;IACjE,wGAAwG;IACxG,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IACvD,kFAAkF;IAClF,KAAK,CAAC,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAChD;AAED,eAAO,MAAM,+BAA+B,QAA0B,CAAC;AACvE,eAAO,MAAM,8BAA8B,OAAO,CAAC;AAEnD,mHAAmH;AACnH,wBAAgB,gBAAgB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAIrF;AAiBD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,WAAW,CAmI1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQhF"}
@@ -0,0 +1,166 @@
1
+ import { DEFAULT_MAX_KEY_LENGTH, privateKey, storedKey } from "./keys.js";
2
+ export const DEFAULT_RATE_LIMIT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
3
+ export const DEFAULT_RATE_LIMIT_PRUNE_BATCH = 1000;
4
+ /** Checks a rule table where it is declared, so a typo is found when the module loads rather than in a refusal. */
5
+ export function defineRateLimits(rules) {
6
+ const problems = Object.entries(rules).flatMap(([name, rule]) => ruleProblems(rule).map((p) => `${name}: ${p}`));
7
+ if (problems.length)
8
+ throw new Error(`[rate-limit] ${problems.join("; ")}`);
9
+ return rules;
10
+ }
11
+ function ruleProblems(rule) {
12
+ const problems = [];
13
+ if (!Number.isInteger(rule?.limit) || rule.limit < 1)
14
+ problems.push("limit must be a whole number, at least 1");
15
+ if (!Number.isFinite(rule?.windowMs) || rule.windowMs < 1000)
16
+ problems.push("windowMs must be at least 1000");
17
+ if (rule?.everyone) {
18
+ const e = rule.everyone;
19
+ if (!e.key)
20
+ problems.push("everyone needs a key");
21
+ if (!Number.isInteger(e.limit) || e.limit < 1)
22
+ problems.push("everyone.limit must be a whole number, at least 1");
23
+ if (e.windowMs !== undefined && (!Number.isFinite(e.windowMs) || e.windowMs < 1000)) {
24
+ problems.push("everyone.windowMs must be at least 1000");
25
+ }
26
+ }
27
+ return problems;
28
+ }
29
+ export function createRateLimiter(options) {
30
+ const { store } = options;
31
+ const now = options.now ?? Date.now;
32
+ const random = options.random ?? Math.random;
33
+ const logger = options.logger ?? console;
34
+ const maxKeyLength = options.maxKeyLength ?? DEFAULT_MAX_KEY_LENGTH;
35
+ if (!Number.isInteger(maxKeyLength) || maxKeyLength < 110) {
36
+ throw new Error("[rate-limit] maxKeyLength must be at least 110, the length of a hashed key.");
37
+ }
38
+ const windowOf = (windowMs, at) => {
39
+ const windowAt = new Date(Math.floor(at / windowMs) * windowMs);
40
+ const resetAt = new Date(windowAt.getTime() + windowMs);
41
+ return { windowAt, resetAt, retryAfter: Math.max(1, Math.ceil((resetAt.getTime() - at) / 1000)) };
42
+ };
43
+ async function spend(key, rule, amount, at) {
44
+ const { windowAt, resetAt, retryAfter } = windowOf(rule.windowMs, at);
45
+ const stored = storedKey(key, maxKeyLength);
46
+ try {
47
+ const count = await store.increment(stored, windowAt, amount);
48
+ const allowed = count <= rule.limit;
49
+ return {
50
+ allowed,
51
+ remaining: Math.max(0, rule.limit - count),
52
+ limit: rule.limit,
53
+ resetAt,
54
+ retryAfter,
55
+ ...(allowed ? {} : { refusedBy: "caller" }),
56
+ };
57
+ }
58
+ catch (error) {
59
+ logger.error(`[rate-limit] failing ${rule.failClosed ? "closed" : "open"} for ${stored}`, error);
60
+ return {
61
+ allowed: !rule.failClosed,
62
+ remaining: rule.failClosed ? 0 : rule.limit,
63
+ limit: rule.limit,
64
+ resetAt,
65
+ retryAfter,
66
+ failed: true,
67
+ ...(rule.failClosed ? { refusedBy: "caller" } : {}),
68
+ };
69
+ }
70
+ }
71
+ async function read(key, rule, at) {
72
+ const { windowAt, resetAt } = windowOf(rule.windowMs, at);
73
+ try {
74
+ const count = await store.read(storedKey(key, maxKeyLength), windowAt);
75
+ const used = Math.min(count, rule.limit);
76
+ return { used, limit: rule.limit, remaining: rule.limit - used, resetAt };
77
+ }
78
+ catch (error) {
79
+ logger.error(`[rate-limit] could not read ${storedKey(key, maxKeyLength)}`, error);
80
+ const used = rule.failClosed ? rule.limit : 0;
81
+ return { used, limit: rule.limit, remaining: rule.limit - used, resetAt, failed: true };
82
+ }
83
+ }
84
+ function maybePrune() {
85
+ const auto = options.autoPrune;
86
+ if (!auto || !(random() < auto.chance))
87
+ return;
88
+ const task = async () => {
89
+ try {
90
+ await prune({ olderThanMs: auto.olderThanMs, batch: auto.batch });
91
+ }
92
+ catch (error) {
93
+ logger.error("[rate-limit] pruning old windows failed", error);
94
+ }
95
+ };
96
+ if (auto.schedule)
97
+ auto.schedule(task);
98
+ else
99
+ void task();
100
+ }
101
+ async function prune(pruneOptions = {}) {
102
+ const olderThanMs = pruneOptions.olderThanMs ?? DEFAULT_RATE_LIMIT_RETENTION_MS;
103
+ const batch = pruneOptions.batch ?? DEFAULT_RATE_LIMIT_PRUNE_BATCH;
104
+ if (!Number.isFinite(olderThanMs) || olderThanMs < 60 * 60 * 1000) {
105
+ throw new Error("[rate-limit] prune's olderThanMs must be at least an hour.");
106
+ }
107
+ if (!Number.isInteger(batch) || batch < 1)
108
+ throw new Error("[rate-limit] prune's batch must be at least 1.");
109
+ return store.prune(new Date(now() - olderThanMs), batch);
110
+ }
111
+ return {
112
+ async consume(key, rule, amount = 1) {
113
+ const problems = ruleProblems(rule);
114
+ if (problems.length)
115
+ throw new Error(`[rate-limit] ${problems.join("; ")}`);
116
+ if (!Number.isInteger(amount) || amount < 1)
117
+ throw new Error("[rate-limit] amount must be a whole number, at least 1.");
118
+ const at = now();
119
+ const own = await spend(key, rule, amount, at);
120
+ if (!own.allowed || !rule.everyone) {
121
+ if (own.allowed && !own.failed)
122
+ maybePrune();
123
+ return own;
124
+ }
125
+ const everyone = await spend(rule.everyone.key, { limit: rule.everyone.limit, windowMs: rule.everyone.windowMs ?? rule.windowMs, failClosed: rule.failClosed }, amount, at);
126
+ if (!everyone.allowed)
127
+ return { ...everyone, refusedBy: "everyone" };
128
+ if (!own.failed && !everyone.failed)
129
+ maybePrune();
130
+ return everyone.failed && !own.failed ? { ...own, failed: true } : own;
131
+ },
132
+ async usage(key, rule) {
133
+ const problems = ruleProblems(rule);
134
+ if (problems.length)
135
+ throw new Error(`[rate-limit] ${problems.join("; ")}`);
136
+ const at = now();
137
+ const own = await read(key, rule, at);
138
+ if (!rule.everyone)
139
+ return own;
140
+ const everyone = await read(rule.everyone.key, { limit: rule.everyone.limit, windowMs: rule.everyone.windowMs ?? rule.windowMs, failClosed: rule.failClosed }, at);
141
+ const { failed: everyoneFailed, ...ceiling } = everyone;
142
+ return { ...own, everyone: ceiling, ...(everyoneFailed ? { failed: true } : {}) };
143
+ },
144
+ privateKey(prefix, ...parts) {
145
+ if (!options.secret)
146
+ throw new Error("[rate-limit] privateKey needs the limiter's `secret`.");
147
+ return privateKey(options.secret, prefix, ...parts);
148
+ },
149
+ prune,
150
+ };
151
+ }
152
+ /**
153
+ * The standard headers for a limited response: `x-ratelimit-limit`, `-remaining` and `-reset` (epoch seconds), and
154
+ * `retry-after` (seconds) when refused.
155
+ */
156
+ export function rateLimitHeaders(result) {
157
+ const headers = {
158
+ "x-ratelimit-limit": String(result.limit),
159
+ "x-ratelimit-remaining": String(result.remaining),
160
+ "x-ratelimit-reset": String(Math.floor(result.resetAt.getTime() / 1000)),
161
+ };
162
+ if (!result.allowed)
163
+ headers["retry-after"] = String(result.retryAfter);
164
+ return headers;
165
+ }
166
+ //# sourceMappingURL=limiter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limiter.js","sourceRoot":"","sources":["../../src/rate-limit/limiter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAyG1E,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AACvE,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAEnD,mHAAmH;AACnH,MAAM,UAAU,gBAAgB,CAA0C,KAAQ;IAChF,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;IACjH,IAAI,QAAQ,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC5E,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,YAAY,CAAC,IAAmB;IACvC,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC;QAAE,QAAQ,CAAC,IAAI,CAAC,0CAA0C,CAAC,CAAC;IAChH,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,GAAG,IAAI;QAAE,QAAQ,CAAC,IAAI,CAA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AAC,CAAC,EAAE,CAAC,EAAE,CAAC;QAC7F,CAAC;QAED,UAAU,CAAC,MAAM,EAAE,GAAG,KAAK;YACzB,IAAI,CAAC,OAAO,CAAC,MAAM;gBAAE,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;YAC9F,OAAO,UAAU,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC,CAAC;QACtD,CAAC;QAED,KAAK;KACN,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,MAAuB;IACtD,MAAM,OAAO,GAA2B;QACtC,mBAAmB,EAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC;QACzC,uBAAuB,EAAE,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC;QACjD,mBAAmB,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;KACzE,CAAC;IACF,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAO,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IACxE,OAAO,OAAO,CAAC;AACjB,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@connextar/house/rate-limit/prisma` — the store over the `RateLimit` model every app has. Imports nothing: the
3
+ * Prisma client is passed in.
4
+ */
5
+ export { incrementSql, prismaRateLimitStore, type PrismaRateLimitStoreOptions, type RateLimitDelegate, type RateLimitSql, } from "./prisma.js";
6
+ //# sourceMappingURL=prisma-index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma-index.d.ts","sourceRoot":"","sources":["../../src/rate-limit/prisma-index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,KAAK,2BAA2B,EAChC,KAAK,iBAAiB,EACtB,KAAK,YAAY,GAClB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * `@connextar/house/rate-limit/prisma` — the store over the `RateLimit` model every app has. Imports nothing: the
3
+ * Prisma client is passed in.
4
+ */
5
+ export { incrementSql, prismaRateLimitStore, } from "./prisma.js";
6
+ //# sourceMappingURL=prisma-index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma-index.js","sourceRoot":"","sources":["../../src/rate-limit/prisma-index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,YAAY,EACZ,oBAAoB,GAIrB,MAAM,aAAa,CAAC"}
@@ -0,0 +1,116 @@
1
+ import type { RateLimitStore } from "./store.js";
2
+ /**
3
+ * The `RateLimitStore` over the `RateLimit` model every app already has — so adopting the limiter needs no migration.
4
+ *
5
+ * The shape is one everywhere: `key`, `windowAt` (`window_at`), `count`, a string `id` with no database default, unique
6
+ * on `(key, windowAt)` under Prisma's name `key_windowAt`. The exceptions are configuration: AltEd's `key` is `TEXT`
7
+ * where the rest are `VARCHAR(200)` (the limiter hashes long keys either way); PharmaLine, Tracker C and the Stripe
8
+ * gateway carry a nullable `last_request` for Better Auth's old get/set rows, left NULL here; Canisters' table is
9
+ * `"RateLimit"` with a `"windowAt"` column; MAS keeps the model in MongoDB, where there is no SQL.
10
+ *
11
+ * **On Postgres, pass `sql`** (the Prisma client) and the count is one statement:
12
+ * `INSERT … ON CONFLICT ("key", "window_at") DO UPDATE SET "count" = "count" + n RETURNING "count"`. Atomic, and it never
13
+ * raises. Every app's own copy used `upsert` and, when two requests raced to create the same window, caught the unique
14
+ * violation and retried with `update` — the job claims' P2002 lesson again: Postgres logs each of those as an error.
15
+ * **Without `sql`** (MongoDB) it is the apps' upsert and retry.
16
+ *
17
+ * Typed structurally, so the package imports no Prisma: `runs: prisma.rateLimit`, `sql: prisma`.
18
+ */
19
+ export interface RateLimitDelegate {
20
+ upsert(args: {
21
+ where: Record<string, {
22
+ key: string;
23
+ windowAt: Date;
24
+ }>;
25
+ create: {
26
+ key: string;
27
+ windowAt: Date;
28
+ count: number;
29
+ };
30
+ update: {
31
+ count: {
32
+ increment: number;
33
+ };
34
+ };
35
+ select: {
36
+ count: true;
37
+ };
38
+ }): Promise<{
39
+ count: number;
40
+ }>;
41
+ update(args: {
42
+ where: Record<string, {
43
+ key: string;
44
+ windowAt: Date;
45
+ }>;
46
+ data: {
47
+ count: {
48
+ increment: number;
49
+ };
50
+ };
51
+ select: {
52
+ count: true;
53
+ };
54
+ }): Promise<{
55
+ count: number;
56
+ }>;
57
+ findUnique(args: {
58
+ where: Record<string, {
59
+ key: string;
60
+ windowAt: Date;
61
+ }>;
62
+ select: {
63
+ count: true;
64
+ };
65
+ }): Promise<{
66
+ count: number;
67
+ } | null>;
68
+ findMany(args: {
69
+ where: {
70
+ windowAt: {
71
+ lt: Date;
72
+ };
73
+ };
74
+ select: {
75
+ id: true;
76
+ };
77
+ orderBy: {
78
+ windowAt: "asc";
79
+ };
80
+ take: number;
81
+ }): Promise<{
82
+ id: string;
83
+ }[]>;
84
+ deleteMany(args: {
85
+ where: {
86
+ id: {
87
+ in: string[];
88
+ };
89
+ };
90
+ }): Promise<{
91
+ count: number;
92
+ }>;
93
+ }
94
+ export interface RateLimitSql {
95
+ $queryRawUnsafe<T = unknown>(query: string, ...values: unknown[]): Promise<T>;
96
+ }
97
+ export interface PrismaRateLimitStoreOptions {
98
+ /** `prisma.rateLimit`. */
99
+ model: RateLimitDelegate;
100
+ /** `prisma`, on Postgres: the count becomes one `INSERT … ON CONFLICT`. Leave it out on MongoDB. */
101
+ sql?: RateLimitSql;
102
+ /** The table and columns in the database, for `sql`. Default `rate_limit` with `id`, `key`, `window_at`, `count`. */
103
+ table?: string;
104
+ columns?: Partial<Record<"id" | "key" | "windowAt" | "count", string>>;
105
+ /** Prisma's name for the `(key, windowAt)` unique. Default `key_windowAt`. */
106
+ uniqueName?: string;
107
+ /** For the new row's `id`. Default a random UUID — the column is text; Prisma's cuid is not needed to read it. */
108
+ newId?: () => string;
109
+ }
110
+ /**
111
+ * The statement, for a table that is not the reference one. The window goes in as an ISO string and is turned into a
112
+ * UTC timestamp in SQL, as Prisma stores `DateTime` — so a database session in another time zone cannot shift it.
113
+ */
114
+ export declare function incrementSql(table?: string, columns?: PrismaRateLimitStoreOptions["columns"]): string;
115
+ export declare function prismaRateLimitStore(options: PrismaRateLimitStoreOptions): RateLimitStore;
116
+ //# sourceMappingURL=prisma.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma.d.ts","sourceRoot":"","sources":["../../src/rate-limit/prisma.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,IAAI,EAAE;QACX,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,IAAI,CAAA;SAAE,CAAC,CAAC;QACvD,MAAM,EAAE;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,IAAI,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,CAAC;QACvD,MAAM,EAAE;YAAE,KAAK,EAAE;gBAAE,SAAS,EAAE,MAAM,CAAA;aAAE,CAAA;SAAE,CAAC;QACzC,MAAM,EAAE;YAAE,KAAK,EAAE,IAAI,CAAA;SAAE,CAAC;KACzB,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC/B,MAAM,CAAC,IAAI,EAAE;QACX,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE;YAAE,GAAG,EAAE,MAAM,CAAC;YAAC,QAAQ,EAAE,IAAI,CAAA;SAAE,CAAC,CAAC;QACvD,IAAI,EAAE;YAAE,KAAK,EAAE;gBAAE,SAAS,EAAE,MAAM,CAAA;aAAE,CAAA;SAAE,CAAC;QACvC,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G;IACpG,GAAG,CAAC,EAAE,YAAY,CAAC;IACnB,qHAAqH;IACrH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,IAAI,GAAG,KAAK,GAAG,UAAU,GAAG,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;IACvE,8EAA8E;IAC9E,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kHAAkH;IAClH,KAAK,CAAC,EAAE,MAAM,MAAM,CAAC;CACtB;AASD;;;GAGG;AACH,wBAAgB,YAAY,CAAC,KAAK,SAAe,EAAE,OAAO,GAAE,2BAA2B,CAAC,SAAS,CAAM,GAAG,MAAM,CAU/G;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,cAAc,CA6DzF"}
@@ -0,0 +1,79 @@
1
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]{0,62}$/;
2
+ function quoted(name) {
3
+ if (!IDENTIFIER.test(name))
4
+ throw new Error(`[rate-limit] "${name}" is not a plain SQL identifier.`);
5
+ return `"${name}"`;
6
+ }
7
+ /**
8
+ * The statement, for a table that is not the reference one. The window goes in as an ISO string and is turned into a
9
+ * UTC timestamp in SQL, as Prisma stores `DateTime` — so a database session in another time zone cannot shift it.
10
+ */
11
+ export function incrementSql(table = "rate_limit", columns = {}) {
12
+ const t = quoted(table);
13
+ const id = quoted(columns.id ?? "id");
14
+ const key = quoted(columns.key ?? "key");
15
+ const windowAt = quoted(columns.windowAt ?? "window_at");
16
+ const count = quoted(columns.count ?? "count");
17
+ return `INSERT INTO ${t} (${id}, ${key}, ${windowAt}, ${count})
18
+ VALUES ($1, $2, ($3::timestamptz AT TIME ZONE 'UTC'), $4)
19
+ ON CONFLICT (${key}, ${windowAt}) DO UPDATE SET ${count} = ${t}.${count} + EXCLUDED.${count}
20
+ RETURNING ${count} AS "count"`;
21
+ }
22
+ export function prismaRateLimitStore(options) {
23
+ const { model, sql } = options;
24
+ const unique = options.uniqueName ?? "key_windowAt";
25
+ const newId = options.newId ?? (() => globalThis.crypto.randomUUID());
26
+ const statement = sql ? incrementSql(options.table, options.columns) : null;
27
+ const where = (key, windowAt) => ({ [unique]: { key, windowAt } });
28
+ return {
29
+ async increment(key, windowAt, amount) {
30
+ if (sql && statement) {
31
+ const rows = await sql.$queryRawUnsafe(statement, newId(), key, windowAt.toISOString(), amount);
32
+ const count = rows[0]?.count;
33
+ if (count === undefined)
34
+ throw new Error("[rate-limit] the count was not returned.");
35
+ return Number(count);
36
+ }
37
+ try {
38
+ const row = await model.upsert({
39
+ where: where(key, windowAt),
40
+ create: { key, windowAt, count: amount },
41
+ update: { count: { increment: amount } },
42
+ select: { count: true },
43
+ });
44
+ return row.count;
45
+ }
46
+ catch (error) {
47
+ // Two first requests in one window race to create it; the loser's retry lands on the update.
48
+ try {
49
+ const row = await model.update({
50
+ where: where(key, windowAt),
51
+ data: { count: { increment: amount } },
52
+ select: { count: true },
53
+ });
54
+ return row.count;
55
+ }
56
+ catch {
57
+ throw error;
58
+ }
59
+ }
60
+ },
61
+ async read(key, windowAt) {
62
+ const row = await model.findUnique({ where: where(key, windowAt), select: { count: true } });
63
+ return row?.count ?? 0;
64
+ },
65
+ async prune(before, limit) {
66
+ const rows = await model.findMany({
67
+ where: { windowAt: { lt: before } },
68
+ select: { id: true },
69
+ orderBy: { windowAt: "asc" },
70
+ take: limit,
71
+ });
72
+ if (!rows.length)
73
+ return 0;
74
+ const { count } = await model.deleteMany({ where: { id: { in: rows.map((row) => row.id) } } });
75
+ return count;
76
+ },
77
+ };
78
+ }
79
+ //# sourceMappingURL=prisma.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma.js","sourceRoot":"","sources":["../../src/rate-limit/prisma.ts"],"names":[],"mappings":"AA+DA,MAAM,UAAU,GAAG,+BAA+B,CAAC;AAEnD,SAAS,MAAM,CAAC,IAAY;IAC1B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CA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AAK,EAAE,IAAI,EAAE;qBACxB,CAAC,CAAC;oBACH,OAAO,GAAG,CAAC,KAAK,CAAC;gBACnB,CAAC;gBAAC,MAAM,CAAC;oBACP,MAAM,KAAK,CAAC;gBACd,CAAC;YACH,CAAC;QACH,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,QAAQ;YACtB,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;YAC7F,OAAO,GAAG,EAAE,KAAK,IAAI,CAAC,CAAC;QACzB,CAAC;QAED,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK;YACvB,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,QAAQ,CAAC;gBAChC,KAAK,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE;gBACnC,MAAM,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE;gBACpB,OAAO,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE;gBAC5B,IAAI,EAAE,KAAK;aACZ,CAAC,CAAC;YACH,IAAI,CAAC,IAAI,CAAC,MAAM;gBAAE,OAAO,CAAC,CAAC;YAC3B,MAAM,EAAE,KAAK,EAAE,GAAG,MAAM,KAAK,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;YAC/F,OAAO,KAAK,CAAC;QACf,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Where windows are counted — the app's table, behind this interface, as `jobs` keeps its ledger.
3
+ *
4
+ * The package owns no schema. Ten apps already have a `rate_limit` table of one shape (`key`, `window_at`, `count`,
5
+ * unique on the first two) and MAS keeps the same model in MongoDB; `@connextar/house/rate-limit/prisma` is the
6
+ * adapter for all of them, so adopting the limiter needs no migration.
7
+ */
8
+ export interface RateLimitStore {
9
+ /**
10
+ * Add `amount` to the window `(key, windowAt)`, creating it at `amount`, and resolve with its count afterwards —
11
+ * in one atomic step, so two requests at once can never both read the count before either adds to it.
12
+ */
13
+ increment(key: string, windowAt: Date, amount: number): Promise<number>;
14
+ /** The window's count, or 0 when there is none. Never writes. */
15
+ read(key: string, windowAt: Date): Promise<number>;
16
+ /** Delete at most `limit` windows that started before `before`, oldest first, and resolve with how many went. */
17
+ prune(before: Date, limit: number): Promise<number>;
18
+ }
19
+ /** The whole contract in memory — for tests, the app's included. */
20
+ export declare function memoryRateLimitStore(): RateLimitStore & {
21
+ windows: Map<string, {
22
+ key: string;
23
+ windowAt: Date;
24
+ count: number;
25
+ }>;
26
+ };
27
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/rate-limit/store.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACxE,iEAAiE;IACjE,IAAI,CAAC,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACnD,iHAAiH;IACjH,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CACrD;AAED,oEAAoE;AACpE,wBAAgB,oBAAoB,IAAI,cAAc,GAAG;IACvD,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,IAAI,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACtE,CAwBA"}
@@ -0,0 +1,28 @@
1
+ /** The whole contract in memory — for tests, the app's included. */
2
+ export function memoryRateLimitStore() {
3
+ const windows = new Map();
4
+ const id = (key, windowAt) => `${windowAt.getTime()}\u0000${key}`;
5
+ return {
6
+ windows,
7
+ async increment(key, windowAt, amount) {
8
+ const at = id(key, windowAt);
9
+ const row = windows.get(at) ?? { key, windowAt, count: 0 };
10
+ row.count += amount;
11
+ windows.set(at, row);
12
+ return row.count;
13
+ },
14
+ async read(key, windowAt) {
15
+ return windows.get(id(key, windowAt))?.count ?? 0;
16
+ },
17
+ async prune(before, limit) {
18
+ const doomed = [...windows.entries()]
19
+ .filter(([, row]) => row.windowAt.getTime() < before.getTime())
20
+ .sort(([, a], [, b]) => a.windowAt.getTime() - b.windowAt.getTime())
21
+ .slice(0, limit);
22
+ for (const [at] of doomed)
23
+ windows.delete(at);
24
+ return doomed.length;
25
+ },
26
+ };
27
+ }
28
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/rate-limit/store.ts"],"names":[],"mappings":"AAmBA,oEAAoE;AACpE,MAAM,UAAU,oBAAoB;IAGlC,MAAM,OAAO,GAAG,IAAI,GAAG,EAA0D,CAAC;IAClF,MAAM,EAAE,GAAG,CAAC,GAAW,EAAE,QAAc,EAAE,EAAE,CAAC,GAAG,QAAQ,CAAC,OAAO,EAAE,SAAS,GAAG,EAAE,CAAC;IAChF,OAAO;QACL,OAAO;QACP,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM;YACnC,MAAM,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;YAC7B,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,EAA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