@vantedev/groundwork 0.0.0-stage → 0.2.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 (216) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/LICENSE +21 -0
  3. package/README.md +350 -2
  4. package/dist/api-keys/api-keys.d.ts +56 -0
  5. package/dist/api-keys/api-keys.d.ts.map +1 -0
  6. package/dist/api-keys/api-keys.js +619 -0
  7. package/dist/api-keys/api-keys.js.map +1 -0
  8. package/dist/api-keys/audit.d.ts +17 -0
  9. package/dist/api-keys/audit.d.ts.map +1 -0
  10. package/dist/api-keys/audit.js +76 -0
  11. package/dist/api-keys/audit.js.map +1 -0
  12. package/dist/api-keys/format.d.ts +32 -0
  13. package/dist/api-keys/format.d.ts.map +1 -0
  14. package/dist/api-keys/format.js +92 -0
  15. package/dist/api-keys/format.js.map +1 -0
  16. package/dist/api-keys/index.d.ts +25 -0
  17. package/dist/api-keys/index.d.ts.map +1 -0
  18. package/dist/api-keys/index.js +23 -0
  19. package/dist/api-keys/index.js.map +1 -0
  20. package/dist/api-keys/policy.d.ts +16 -0
  21. package/dist/api-keys/policy.d.ts.map +1 -0
  22. package/dist/api-keys/policy.js +95 -0
  23. package/dist/api-keys/policy.js.map +1 -0
  24. package/dist/api-keys/responses.d.ts +6 -0
  25. package/dist/api-keys/responses.d.ts.map +1 -0
  26. package/dist/api-keys/responses.js +54 -0
  27. package/dist/api-keys/responses.js.map +1 -0
  28. package/dist/api-keys/scopes.d.ts +13 -0
  29. package/dist/api-keys/scopes.d.ts.map +1 -0
  30. package/dist/api-keys/scopes.js +49 -0
  31. package/dist/api-keys/scopes.js.map +1 -0
  32. package/dist/api-keys/types.d.ts +173 -0
  33. package/dist/api-keys/types.d.ts.map +1 -0
  34. package/dist/api-keys/types.js +2 -0
  35. package/dist/api-keys/types.js.map +1 -0
  36. package/dist/audit/audit-log.d.ts +35 -0
  37. package/dist/audit/audit-log.d.ts.map +1 -0
  38. package/dist/audit/audit-log.js +277 -0
  39. package/dist/audit/audit-log.js.map +1 -0
  40. package/dist/audit/cursor.d.ts +13 -0
  41. package/dist/audit/cursor.d.ts.map +1 -0
  42. package/dist/audit/cursor.js +26 -0
  43. package/dist/audit/cursor.js.map +1 -0
  44. package/dist/audit/diff.d.ts +19 -0
  45. package/dist/audit/diff.d.ts.map +1 -0
  46. package/dist/audit/diff.js +59 -0
  47. package/dist/audit/diff.js.map +1 -0
  48. package/dist/audit/index.d.ts +25 -0
  49. package/dist/audit/index.d.ts.map +1 -0
  50. package/dist/audit/index.js +24 -0
  51. package/dist/audit/index.js.map +1 -0
  52. package/dist/audit/json.d.ts +23 -0
  53. package/dist/audit/json.d.ts.map +1 -0
  54. package/dist/audit/json.js +120 -0
  55. package/dist/audit/json.js.map +1 -0
  56. package/dist/audit/types.d.ts +118 -0
  57. package/dist/audit/types.d.ts.map +1 -0
  58. package/dist/audit/types.js +2 -0
  59. package/dist/audit/types.js.map +1 -0
  60. package/dist/idempotency/http.d.ts +27 -0
  61. package/dist/idempotency/http.d.ts.map +1 -0
  62. package/dist/idempotency/http.js +130 -0
  63. package/dist/idempotency/http.js.map +1 -0
  64. package/dist/idempotency/idempotency.d.ts +45 -0
  65. package/dist/idempotency/idempotency.d.ts.map +1 -0
  66. package/dist/idempotency/idempotency.js +302 -0
  67. package/dist/idempotency/idempotency.js.map +1 -0
  68. package/dist/idempotency/index.d.ts +25 -0
  69. package/dist/idempotency/index.d.ts.map +1 -0
  70. package/dist/idempotency/index.js +24 -0
  71. package/dist/idempotency/index.js.map +1 -0
  72. package/dist/idempotency/keys.d.ts +13 -0
  73. package/dist/idempotency/keys.d.ts.map +1 -0
  74. package/dist/idempotency/keys.js +9 -0
  75. package/dist/idempotency/keys.js.map +1 -0
  76. package/dist/idempotency/types.d.ts +92 -0
  77. package/dist/idempotency/types.d.ts.map +1 -0
  78. package/dist/idempotency/types.js +2 -0
  79. package/dist/idempotency/types.js.map +1 -0
  80. package/dist/index.d.ts +122 -0
  81. package/dist/index.d.ts.map +1 -0
  82. package/dist/index.js +201 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/internal/cidr.d.ts +21 -0
  85. package/dist/internal/cidr.d.ts.map +1 -0
  86. package/dist/internal/cidr.js +159 -0
  87. package/dist/internal/cidr.js.map +1 -0
  88. package/dist/internal/clock.d.ts +6 -0
  89. package/dist/internal/clock.d.ts.map +1 -0
  90. package/dist/internal/clock.js +4 -0
  91. package/dist/internal/clock.js.map +1 -0
  92. package/dist/internal/crypto.d.ts +44 -0
  93. package/dist/internal/crypto.d.ts.map +1 -0
  94. package/dist/internal/crypto.js +97 -0
  95. package/dist/internal/crypto.js.map +1 -0
  96. package/dist/internal/db.d.ts +14 -0
  97. package/dist/internal/db.d.ts.map +1 -0
  98. package/dist/internal/db.js +20 -0
  99. package/dist/internal/db.js.map +1 -0
  100. package/dist/internal/duration.d.ts +25 -0
  101. package/dist/internal/duration.d.ts.map +1 -0
  102. package/dist/internal/duration.js +39 -0
  103. package/dist/internal/duration.js.map +1 -0
  104. package/dist/internal/errors.d.ts +33 -0
  105. package/dist/internal/errors.d.ts.map +1 -0
  106. package/dist/internal/errors.js +29 -0
  107. package/dist/internal/errors.js.map +1 -0
  108. package/dist/internal/logger.d.ts +37 -0
  109. package/dist/internal/logger.d.ts.map +1 -0
  110. package/dist/internal/logger.js +54 -0
  111. package/dist/internal/logger.js.map +1 -0
  112. package/dist/internal/standard-schema.d.ts +49 -0
  113. package/dist/internal/standard-schema.d.ts.map +1 -0
  114. package/dist/internal/standard-schema.js +16 -0
  115. package/dist/internal/standard-schema.js.map +1 -0
  116. package/dist/internal/table.d.ts +7 -0
  117. package/dist/internal/table.d.ts.map +1 -0
  118. package/dist/internal/table.js +20 -0
  119. package/dist/internal/table.js.map +1 -0
  120. package/dist/jobs/backoff.d.ts +7 -0
  121. package/dist/jobs/backoff.d.ts.map +1 -0
  122. package/dist/jobs/backoff.js +10 -0
  123. package/dist/jobs/backoff.js.map +1 -0
  124. package/dist/jobs/index.d.ts +31 -0
  125. package/dist/jobs/index.d.ts.map +1 -0
  126. package/dist/jobs/index.js +29 -0
  127. package/dist/jobs/index.js.map +1 -0
  128. package/dist/jobs/jobs.d.ts +42 -0
  129. package/dist/jobs/jobs.d.ts.map +1 -0
  130. package/dist/jobs/jobs.js +741 -0
  131. package/dist/jobs/jobs.js.map +1 -0
  132. package/dist/jobs/types.d.ts +199 -0
  133. package/dist/jobs/types.d.ts.map +1 -0
  134. package/dist/jobs/types.js +2 -0
  135. package/dist/jobs/types.js.map +1 -0
  136. package/dist/next/client-ip.d.ts +42 -0
  137. package/dist/next/client-ip.d.ts.map +1 -0
  138. package/dist/next/client-ip.js +59 -0
  139. package/dist/next/client-ip.js.map +1 -0
  140. package/dist/next/index.d.ts +29 -0
  141. package/dist/next/index.d.ts.map +1 -0
  142. package/dist/next/index.js +29 -0
  143. package/dist/next/index.js.map +1 -0
  144. package/dist/next/jobs-route.d.ts +31 -0
  145. package/dist/next/jobs-route.d.ts.map +1 -0
  146. package/dist/next/jobs-route.js +53 -0
  147. package/dist/next/jobs-route.js.map +1 -0
  148. package/dist/next/response.d.ts +6 -0
  149. package/dist/next/response.d.ts.map +1 -0
  150. package/dist/next/response.js +25 -0
  151. package/dist/next/response.js.map +1 -0
  152. package/dist/next/route-helpers.d.ts +67 -0
  153. package/dist/next/route-helpers.d.ts.map +1 -0
  154. package/dist/next/route-helpers.js +93 -0
  155. package/dist/next/route-helpers.js.map +1 -0
  156. package/dist/rate-limit/index.d.ts +19 -0
  157. package/dist/rate-limit/index.d.ts.map +1 -0
  158. package/dist/rate-limit/index.js +18 -0
  159. package/dist/rate-limit/index.js.map +1 -0
  160. package/dist/rate-limit/limiter.d.ts +60 -0
  161. package/dist/rate-limit/limiter.d.ts.map +1 -0
  162. package/dist/rate-limit/limiter.js +147 -0
  163. package/dist/rate-limit/limiter.js.map +1 -0
  164. package/dist/rate-limit/memory-store.d.ts +23 -0
  165. package/dist/rate-limit/memory-store.d.ts.map +1 -0
  166. package/dist/rate-limit/memory-store.js +77 -0
  167. package/dist/rate-limit/memory-store.js.map +1 -0
  168. package/dist/rate-limit/policy.d.ts +31 -0
  169. package/dist/rate-limit/policy.d.ts.map +1 -0
  170. package/dist/rate-limit/policy.js +174 -0
  171. package/dist/rate-limit/policy.js.map +1 -0
  172. package/dist/rate-limit/postgres-store.d.ts +13 -0
  173. package/dist/rate-limit/postgres-store.d.ts.map +1 -0
  174. package/dist/rate-limit/postgres-store.js +129 -0
  175. package/dist/rate-limit/postgres-store.js.map +1 -0
  176. package/dist/rate-limit/redis-store.d.ts +24 -0
  177. package/dist/rate-limit/redis-store.d.ts.map +1 -0
  178. package/dist/rate-limit/redis-store.js +97 -0
  179. package/dist/rate-limit/redis-store.js.map +1 -0
  180. package/dist/rate-limit/types.d.ts +140 -0
  181. package/dist/rate-limit/types.d.ts.map +1 -0
  182. package/dist/rate-limit/types.js +2 -0
  183. package/dist/rate-limit/types.js.map +1 -0
  184. package/dist/schema/api-keys.d.ts +545 -0
  185. package/dist/schema/api-keys.d.ts.map +1 -0
  186. package/dist/schema/api-keys.js +83 -0
  187. package/dist/schema/api-keys.js.map +1 -0
  188. package/dist/schema/audit-log.d.ts +248 -0
  189. package/dist/schema/audit-log.d.ts.map +1 -0
  190. package/dist/schema/audit-log.js +56 -0
  191. package/dist/schema/audit-log.js.map +1 -0
  192. package/dist/schema/factory.d.ts +19 -0
  193. package/dist/schema/factory.d.ts.map +1 -0
  194. package/dist/schema/factory.js +39 -0
  195. package/dist/schema/factory.js.map +1 -0
  196. package/dist/schema/idempotency-keys.d.ts +178 -0
  197. package/dist/schema/idempotency-keys.d.ts.map +1 -0
  198. package/dist/schema/idempotency-keys.js +41 -0
  199. package/dist/schema/idempotency-keys.js.map +1 -0
  200. package/dist/schema/index.d.ts +61 -0
  201. package/dist/schema/index.d.ts.map +1 -0
  202. package/dist/schema/index.js +28 -0
  203. package/dist/schema/index.js.map +1 -0
  204. package/dist/schema/jobs.d.ts +487 -0
  205. package/dist/schema/jobs.d.ts.map +1 -0
  206. package/dist/schema/jobs.js +103 -0
  207. package/dist/schema/jobs.js.map +1 -0
  208. package/dist/schema/rate-limits.d.ts +108 -0
  209. package/dist/schema/rate-limits.d.ts.map +1 -0
  210. package/dist/schema/rate-limits.js +27 -0
  211. package/dist/schema/rate-limits.js.map +1 -0
  212. package/dist/testing/index.d.ts +25 -0
  213. package/dist/testing/index.d.ts.map +1 -0
  214. package/dist/testing/index.js +37 -0
  215. package/dist/testing/index.js.map +1 -0
  216. package/package.json +117 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,87 @@
1
+ # @vantedev/groundwork
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 377fc30: `audit.query({ offset })` skips that many entries, for admin pages with page numbers, with `count()` for the total. Up to 100,000, and not together with `cursor`. Unlike cursors, offsets can show an entry twice or skip one while the log grows.
8
+ - 5191063: `jobs.list({ schedule })` lists one or more schedules' runs by name, and every job record has `schedule`, the schedule's name, or `null` for an enqueued job. The jobs docs also explain why an external cron on the same period as a schedule can run it only every other time.
9
+ - 1bda996: `secret` can be a function, called once on first use: the first rate-limit check, key hash or idempotency claim. You can create `gw` at module scope when the environment isn't set during `next build`, and a worker that only cleans up or runs jobs needs no secret. A plain secret is still checked at startup, and both forms derive the same keys. The docs now say that reusing an existing app secret, such as `BETTER_AUTH_SECRET`, is safe.
10
+ - 1f1b911: `pinoLogger(logger)` adapts pino, or any logger whose methods take `(context, message)`, to groundwork's `Logger`.
11
+ - 971ef36: `apiKeys.verify()` returns the checks behind its headers. On success, `rateLimit` and `quota` (`limit`, `remaining`, `resetAt`), or `null` when the key has none. On a `rate_limited` or `quota_exceeded` failure, the check that denied it. Apps that send their own rate-limit headers no longer parse groundwork's.
12
+
13
+ ## 0.1.0
14
+
15
+ ### Minor Changes
16
+
17
+ - d6c1960: Package skeleton: ESM-only subpath exports (`@vantedev/groundwork`, `/schema`, `/rate-limit`, `/audit`, `/api-keys`, `/jobs`, `/idempotency`, `/next`, `/testing`), with `drizzle-orm` as the only peer dependency. The root entry exports `GroundworkError`, `isGroundworkError` and the shared `Duration`, `Logger`, `Clock` and `Secret` types.
18
+ - ab377d2: Rate limiting, and the table factories it stores its counters in.
19
+
20
+ - `@vantedev/groundwork/schema`: `groundworkTables({ prefix, schema })` returns Drizzle tables for your schema. The default prefix is `gw_`. When `schema` is set, the returned schema object must be exported too, so drizzle-kit generates `CREATE SCHEMA`.
21
+ - `@vantedev/groundwork/rate-limit`: `createRateLimiter()` with fixed-window and token-bucket rules.
22
+ - Each check is one SQL statement, correct under concurrency across app instances. Time comes from the database unless a `clock` is injected.
23
+ - A request whose `cost` doesn't fit is denied and uses nothing.
24
+ - Results include `RateLimit-Policy`, `RateLimit` (draft-ietf-httpapi-ratelimit-headers-11) and `Retry-After` headers.
25
+ - If the store fails or times out (default `"1s"`), rules fall back to `onError: "memory" | "allow" | "deny"`. A circuit breaker stops retrying for 5 seconds, and the outage is logged once.
26
+ - `reset()` can join a transaction. `cleanup()` deletes in batches.
27
+ - `memoryStore()` and an optional `redisStore()`, which takes any client with `eval` and adds no dependency.
28
+ - `createGroundwork({ db, tables, secret })` exposes the limiter as `gw.rateLimit`.
29
+ - `@vantedev/groundwork/testing`: `createTestClock()`.
30
+ - 8a132d1: Audit log.
31
+
32
+ - `groundworkTables()` now also returns `auditLog` (`gw_audit_log`). It is append-only: identity ids, `occurred_at` defaults to the transaction's `now()`, and every filter column is indexed together with `(occurred_at, id)`.
33
+ - `@vantedev/groundwork/audit`: `createAuditLog({ db, table, actions, entityTypes?, redact?, redactDefaults? })`.
34
+ - Actions and entity types are inferred from the config.
35
+ - `record(event, { tx })` writes inside your transaction; `recordMany` writes up to 1,000 entries in one statement, all or none.
36
+ - Events are validated before anything is sent, and recording throws rather than swallowing errors.
37
+ - `changes` and `metadata` are redacted at any depth, using `DEFAULT_REDACT` plus your rules, and normalised to JSON.
38
+ - `query()` uses keyset pagination on `(occurred_at, id)` and filters by action, actor, entity, request id, time range, literal text search, or any Drizzle `where`. It reads newest first, or oldest first with `order: "asc"`.
39
+ - `count()` takes the same filters; `prune({ olderThan })` deletes in batches.
40
+ - `diff(before, after, { ignore })` returns only the changed fields, as `[before, after]`.
41
+ - `createGroundwork({ audit: { actions } })` exposes the log as `gw.audit`.
42
+ - e7b1e91: Scoped API keys.
43
+
44
+ - `groundworkTables()` now also returns `apiKeys` (`gw_api_keys`). Only an HMAC of each key is stored, under a unique index. The table also keeps a partial index on the previous hash, used during rotation grace periods.
45
+ - `@vantedev/groundwork/api-keys`: `createApiKeys({ db, table, secret, namespace, scopes, rateLimiter })`, or `gw.apiKeys` from `createGroundwork({ apiKeys })`.
46
+ - Keys look like `<namespace>_<12 hex>_<43 base64url>` with a CRC32 checksum suffix. Typos and foreign keys are rejected without a database lookup, and keys without a checksum still verify.
47
+ - Scopes are typed from the config and can be granted as `resource:*` wildcards.
48
+ - `verify(request | headers | key, { scopes, ip, origin })` finds the key, current or within its rotation grace period, in one query.
49
+ - It returns `{ ok: true, key, headers }`, or `{ ok: false, reason, status, response }`. Reasons: `missing`, `malformed`, `invalid`, `revoked`, `expired`, `suspended`, `ip_denied`, `origin_denied`, `forbidden_scope`, `rate_limited`, `quota_exceeded`.
50
+ - The JSON response carries RFC 6750 `WWW-Authenticate` headers.
51
+ - IPv4 and IPv6 CIDR allowlists, which also match IPv4-mapped addresses, and origin allowlists.
52
+ - Per-key rate limit (default 60/min) and daily quota through the rate limiter.
53
+ - Lifecycle: `create`, `update`, `rotate({ grace })`, `suspend({ for })`, `reinstate`, `revoke`, `delete`, `get`, `list`. Every method takes `{ actor, tx }`.
54
+ - `lastUsedAt` and `lastUsedIp` are written at most once a minute, in the background (`waitUntil` hook).
55
+ - `legacyHash` keeps keys from an older system working, and upgrades each one on first use.
56
+ - `redactKeys(text)`.
57
+ - With the audit log wired, every key change is recorded as `api_key.*`, which `gw.audit` accepts automatically. `apiKeyAuditEvent()` maps events for standalone use.
58
+ - 1761981: Background jobs and schedules.
59
+
60
+ - `groundworkTables()` now also returns `jobs` (`gw_jobs`) and `jobSchedules` (`gw_job_schedules`).
61
+ - Status is checked text, not an enum, so nothing extra has to be exported.
62
+ - A partial claim index on `(priority desc, run_at, id)`, so a claim reads only the next few rows.
63
+ - A partial unique index on `(type, dedupe_key)` while a job is pending or running.
64
+ - `@vantedev/groundwork/jobs`: `createJobs({ db, table, schedulesTable, lease })`, or `gw.jobs` from `createGroundwork`.
65
+ - `define(type, { schema, run, maxAttempts, backoff, timeout, priority, onExhausted })` returns a typed handle. Payloads are typed from a Standard Schema (zod, valibot, arktype…), which also validates them, or from `run`'s parameter.
66
+ - `enqueue(payload, { tx, runAt, delay, priority, dedupeKey, maxAttempts })` returns `{ id, created }`.
67
+ - Workers claim batches with `FOR UPDATE SKIP LOCKED` in one statement. Each job is leased, and the lease is renewed while the handler runs; a dead worker's jobs come back when its lease ends. The attempt number fences out late results from a worker that lost its lease.
68
+ - Retries use capped exponential backoff with full jitter. Timeouts abort `context.signal`.
69
+ - `work({ concurrency, pollInterval, signal })` finishes running jobs on abort. `runOnce({ budgetMs, concurrency })` is for cron and HTTP triggers.
70
+ - `schedule(name, { every }, fn)`: each tick runs exactly once across instances, as a job, so it gets retries, history and health. Overlapping ticks are skipped. `trigger(name)` runs a schedule now.
71
+ - `get`, `list`, `retry`, `cancel`, `prune`, and `health()`, which reports per-type queue stats and per-schedule last success, failure and health.
72
+ - `createGroundwork` schedules `gw.rateLimit.cleanup()` hourly when rate limiting is set up.
73
+ - 5de6fdf: Idempotency keys and Next.js route helpers.
74
+
75
+ - `groundworkTables()` now also returns `idempotencyKeys` (`gw_idempotency_keys`). Keys and request fingerprints are stored as HMACs; responses are stored as JSON text.
76
+ - `@vantedev/groundwork/idempotency`: `createIdempotency({ db, table, secret, ttl, lease })`, or `gw.idempotency` from `createGroundwork`.
77
+ - `handle(request, { scope, required, ttl, fingerprint }, handler)` follows draft-ietf-httpapi-idempotency-key-header-08. A completed 2xx or 3xx response is replayed with `Idempotent-Replayed: true`; reuse with a different body, path or method is a 422; a duplicate while the first request runs is a 409; a missing (when `required`) or malformed key is a 400. Errors aren't stored, so clients can retry.
78
+ - Concurrent duplicates run the handler once. A running request holds its key with a lease that is renewed while it runs, so a crashed request frees its key within `lease` (default `"30s"`).
79
+ - `Set-Cookie` and per-request headers are never stored.
80
+ - `run({ scope, key, fingerprint }, fn)` does the same for anything that isn't an HTTP handler, and returns the stored JSON value, typed with `Jsonify<T>`.
81
+ - `cleanup()` deletes expired keys. `createGroundwork` schedules it hourly once you use `gw.jobs` (`jobs: { idempotencyCleanup: false }` turns it off).
82
+ - `@vantedev/groundwork/next`, with no dependency on `next`:
83
+ - `createRouteHelpers(gw, { trustProxy })` returns `withApiKey(scopes, handler)`, `withRateLimit(rule, key, handler)`, `withIdempotency(options, handler)` and `clientIp(request)`. Wrappers nest, and what an outer one adds (`context.apiKey`) is typed in the ones inside.
84
+ - `jobsRoute(gw, { secret, budgetMs, concurrency })`: a bearer-protected HTTP trigger for `gw.jobs.runOnce()`, for Vercel Cron and other schedulers. `?schedule=<name>` runs a schedule now.
85
+ - `getClientIp(request, { trustProxy })` reads only the header you trust: `"vercel"`, `"cloudflare"`, or `{ header, hops }` for `X-Forwarded-For` behind your own proxies. The default, `"none"`, reads nothing.
86
+ - `examples/next-app` uses every module in a Next.js 16 app.
87
+ - First public release, as `@vantedev/groundwork` (the unscoped name `groundwork` belongs to another package on npm). Import from `@vantedev/groundwork`, `@vantedev/groundwork/schema`, `@vantedev/groundwork/next` and the other subpaths. New guides cover testing your app and migrating from hand-rolled tables.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vante
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,351 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/banner-dark.svg">
5
+ <img alt="groundwork: the plumbing every Postgres app rebuilds, in your own Drizzle schema" src="docs/assets/banner-light.svg" width="100%">
6
+ </picture>
7
+
8
+ <br>
9
+
10
+ **Rate limiting, audit logs, scoped API keys, background jobs and idempotency keys for TypeScript apps on Postgres. The tables live in your Drizzle schema, every write joins your transaction, and you don't need Redis.**
11
+
12
+ <br>
13
+
14
+ [![CI](https://img.shields.io/github/actions/workflow/status/kaanxsrd/groundwork/ci.yml?branch=main&style=flat-square&label=CI&logo=githubactions&logoColor=white)](https://github.com/kaanxsrd/groundwork/actions/workflows/ci.yml)
15
+ [![npm](https://img.shields.io/npm/v/@vantedev/groundwork?style=flat-square&color=cb3837&logo=npm&logoColor=white)](https://www.npmjs.com/package/@vantedev/groundwork)
16
+ [![TypeScript strict](https://img.shields.io/badge/TypeScript-strict-3178c6?style=flat-square&logo=typescript&logoColor=white)](https://www.typescriptlang.org)
17
+ [![PostgreSQL 16+](https://img.shields.io/badge/PostgreSQL-16%2B-4169e1?style=flat-square&logo=postgresql&logoColor=white)](https://www.postgresql.org)
18
+ [![Drizzle ORM](https://img.shields.io/badge/Drizzle-native-c5f74f?style=flat-square&logo=drizzle&logoColor=black)](https://orm.drizzle.team)
19
+ [![Next.js 16](https://img.shields.io/badge/Next.js-16-000000?style=flat-square&logo=nextdotjs&logoColor=white)](docs/next.md)
20
+ [![ESM only](https://img.shields.io/badge/ESM-only-f7df1e?style=flat-square&logo=javascript&logoColor=black)](https://nodejs.org/api/esm.html)
21
+ [![Biome](https://img.shields.io/badge/lint-Biome-60a5fa?style=flat-square&logo=biome&logoColor=white)](https://biomejs.dev)
22
+ [![License: MIT](https://img.shields.io/badge/license-MIT-22c55e?style=flat-square)](LICENSE)
23
+
24
+ **[Quickstart](#quickstart)** ·
25
+ **[Docs](docs/README.md)** ·
26
+ **[Example app](examples/next-app)** ·
27
+ **[Changelog](CHANGELOG.md)** ·
28
+ **[Contributing](CONTRIBUTING.md)** ·
29
+ **[Security](SECURITY.md)**
30
+
31
+ </div>
32
+
33
+ <br>
34
+
35
+ > [!NOTE]
36
+ > **0.x:** the API can still change before 1.0. Each change is in the [changelog](CHANGELOG.md), with what to update.
37
+
38
+ ## Why
39
+
40
+ Self-hosted Next.js + Drizzle + Postgres apps keep hand-writing the same five pieces. Libraries exist for each of them, but most bring their own schema, their own migrations, a Redis server or a hosted service. groundwork works differently:
41
+
42
+ - **Your schema.** The tables are factories you export from your own Drizzle schema, and your drizzle-kit migrates them. groundwork never runs DDL.
43
+ - **Your transaction.** Pass `{ tx }`, and an audit entry or an enqueued job commits or rolls back with the change that caused it.
44
+ - **Your names, typed.** Scopes, audit actions and job payloads are declared once, and TypeScript checks every place they're used.
45
+ - **Only Postgres.** A rate-limit check is one round trip. Redis is an option for rate limits, never a requirement.
46
+ - **Secure by default.** API keys, rate-limit subjects and idempotency keys are stored as HMACs, comparisons are timing-safe, configured audit fields are redacted, and secrets never reach a log.
47
+
48
+ ## What's inside
49
+
50
+ <table>
51
+ <tr>
52
+ <td width="50%" valign="top">
53
+
54
+ **[Rate limiting](docs/rate-limiting.md)**<br>
55
+ Fixed windows and token buckets in one atomic statement, with the standard `RateLimit` headers. If the database is down it falls back to memory, or fails open or closed, as you choose.
56
+
57
+ </td>
58
+ <td width="50%" valign="top">
59
+
60
+ **[Audit log](docs/audit.md)**<br>
61
+ Typed actions recorded in your transaction, field-level diffs, redaction of secrets before they're stored, and keyset pagination that never skips a row.
62
+
63
+ </td>
64
+ </tr>
65
+ <tr>
66
+ <td width="50%" valign="top">
67
+
68
+ **[Scoped API keys](docs/api-keys.md)**<br>
69
+ Keys that secret scanners recognise, stored as HMACs. Rotation with a grace period, suspension, IP and origin allowlists, and per-key rate limits and daily quotas.
70
+
71
+ </td>
72
+ <td width="50%" valign="top">
73
+
74
+ **[Background jobs](docs/jobs.md)**<br>
75
+ Typed jobs enqueued in your transaction and claimed in batches. Leases bring back a crashed worker's jobs, retries back off with jitter, and schedules run each tick exactly once.
76
+
77
+ </td>
78
+ </tr>
79
+ <tr>
80
+ <td width="50%" valign="top">
81
+
82
+ **[Idempotency keys](docs/idempotency.md)**<br>
83
+ Safe retries per the IETF draft. A repeated request gets the stored response; a duplicate that arrives while the first is still running gets a 409 and doesn't run twice.
84
+
85
+ </td>
86
+ <td width="50%" valign="top">
87
+
88
+ **[Next.js helpers](docs/next.md)**<br>
89
+ `withApiKey`, `withRateLimit` and `withIdempotency` route wrappers that nest with full typing, a cron route for jobs, and client IPs read only from the proxy you trust.
90
+
91
+ </td>
92
+ </tr>
93
+ </table>
94
+
95
+ ## Quickstart
96
+
97
+ In a Next.js app (`npx create-next-app@latest`) with a Postgres database:
98
+
99
+ ```sh
100
+ npm install @vantedev/groundwork drizzle-orm postgres
101
+ npm install -D drizzle-kit
102
+ ```
103
+
104
+ **1. Add groundwork's tables to your Drizzle schema**, and let drizzle-kit create them. Put `DATABASE_URL` in `.env.local`, plus `GROUNDWORK_SECRET` and `CRON_SECRET`, each from `openssl rand -base64 32`.
105
+
106
+ ```ts filename="db/schema.ts"
107
+ import { groundworkTables } from "@vantedev/groundwork/schema";
108
+
109
+ export const { rateLimits, auditLog, apiKeys, jobs, jobSchedules, idempotencyKeys } =
110
+ groundworkTables();
111
+ ```
112
+
113
+ ```ts filename="drizzle.config.ts"
114
+ import { defineConfig } from "drizzle-kit";
115
+
116
+ process.loadEnvFile(".env.local");
117
+
118
+ export default defineConfig({
119
+ dialect: "postgresql",
120
+ schema: "./db/schema.ts",
121
+ out: "./drizzle",
122
+ dbCredentials: { url: process.env.DATABASE_URL ?? "" },
123
+ });
124
+ ```
125
+
126
+ ```sh
127
+ npx drizzle-kit generate
128
+ npx drizzle-kit migrate
129
+ ```
130
+
131
+ **2. Create one instance** with your own names. Audit actions, API-key scopes and job payloads are typed from here on.
132
+
133
+ ```ts filename="lib/groundwork.ts"
134
+ import { drizzle } from "drizzle-orm/postgres-js";
135
+ import { createGroundwork } from "@vantedev/groundwork";
136
+ import { createRouteHelpers } from "@vantedev/groundwork/next";
137
+ import postgres from "postgres";
138
+ import * as tables from "@/db/schema";
139
+
140
+ export const db = drizzle(postgres(process.env.DATABASE_URL ?? ""));
141
+
142
+ export const gw = createGroundwork({
143
+ db,
144
+ tables,
145
+ secret: process.env.GROUNDWORK_SECRET ?? "",
146
+ audit: { actions: ["note.create"] },
147
+ apiKeys: { namespace: "demo", scopes: { "notes:write": "Create notes" } },
148
+ });
149
+
150
+ export const { withApiKey, withIdempotency } = createRouteHelpers(gw);
151
+
152
+ export const noteCreated = gw.jobs.define("note.created", {
153
+ async run(note: { id: string }) {
154
+ console.log(`Note ${note.id} was created.`);
155
+ },
156
+ });
157
+ ```
158
+
159
+ **3. Protect a route** with a scoped API key and make it safe to retry. The audit entry and the job commit together with your write, or not at all:
160
+
161
+ ```ts filename="app/api/notes/route.ts"
162
+ import { db, gw, noteCreated, withApiKey, withIdempotency } from "@/lib/groundwork";
163
+
164
+ export const POST = withApiKey(
165
+ ["notes:write"],
166
+ withIdempotency(
167
+ { scope: (_request, { apiKey }) => `apikey:${apiKey.id}` },
168
+ async (request, { apiKey }) => {
169
+ const { text } = await request.json();
170
+ const id = crypto.randomUUID();
171
+ await db.transaction(async (tx) => {
172
+ await gw.audit.record(
173
+ { actor: { type: "api_key", id: apiKey.id }, action: "note.create", metadata: { id, text } },
174
+ { tx },
175
+ );
176
+ await noteCreated.enqueue({ id }, { tx });
177
+ });
178
+ return Response.json({ id }, { status: 201 });
179
+ },
180
+ ),
181
+ );
182
+ ```
183
+
184
+ **4. Run jobs** from a cron route (Vercel Cron sends `CRON_SECRET` for you), or with `gw.jobs.work()` in a long-running process:
185
+
186
+ ```ts filename="app/api/jobs/route.ts"
187
+ import { jobsRoute } from "@vantedev/groundwork/next";
188
+ import { gw } from "@/lib/groundwork";
189
+
190
+ export const GET = jobsRoute(gw, { secret: process.env.CRON_SECRET ?? "" });
191
+ export const POST = GET;
192
+ ```
193
+
194
+ **5. Create a key** once, from a script or your admin UI, and call the route. A retry with the same `Idempotency-Key` gets the first response back:
195
+
196
+ ```ts
197
+ const { key } = await gw.apiKeys.create({ name: "My CLI", scopes: ["notes:write"] });
198
+ ```
199
+
200
+ ```sh
201
+ curl -X POST http://localhost:3000/api/notes -H "Authorization: Bearer $KEY" -H "Idempotency-Key: $(uuidgen)" -d '{"text":"Hello"}'
202
+ ```
203
+
204
+ [`examples/next-app`](examples/next-app) uses every module, with rate limits, a schedule and an audit-log endpoint. CI builds both it and this quickstart in a fresh `create-next-app` project, then runs requests against them.
205
+
206
+ ## The modules
207
+
208
+ Each one also works on its own, without `createGroundwork`: `createRateLimiter({ db, table, secret })`, and so on.
209
+
210
+ ### Rate limiting
211
+
212
+ ```ts
213
+ const login = gw.rateLimit.rule({ name: "login:ip", limit: 5, window: "15m" });
214
+ const api = gw.rateLimit.rule({ name: "api", algorithm: "token-bucket", rate: 10, per: "1s", burst: 120 });
215
+
216
+ const result = await login.check(ip);
217
+ if (!result.allowed) return new Response("Too many attempts", { status: 429, headers: result.headers });
218
+ ```
219
+
220
+ Subjects are stored as HMACs, never as raw IPs or user ids. A batch that doesn't fit is rejected without using anything. [Docs](docs/rate-limiting.md)
221
+
222
+ ### Audit log
223
+
224
+ ```ts
225
+ await db.transaction(async (tx) => {
226
+ const [before] = await tx.select().from(posts).where(eq(posts.id, id));
227
+ const [after] = await tx.update(posts).set(input).where(eq(posts.id, id)).returning();
228
+ await gw.audit.record(
229
+ { actor: { type: "user", id: user.id }, action: "post.update", entity: { type: "post", id }, changes: diff(before, after) },
230
+ { tx },
231
+ );
232
+ });
233
+ const { entries, nextCursor } = await gw.audit.query({ entity: { type: "post", id } });
234
+ ```
235
+
236
+ `record()` only accepts the actions you declared. [Docs](docs/audit.md)
237
+
238
+ ### API keys
239
+
240
+ ```ts
241
+ const { key } = await gw.apiKeys.create({ name: "CI deploy", scopes: ["posts:write"], expiresIn: "90d" });
242
+
243
+ const auth = await gw.apiKeys.verify(request, { scopes: ["posts:write"] });
244
+ if (!auth.ok) return auth.response; // a JSON 401, 403 or 429 with the right headers
245
+ ```
246
+
247
+ The key is shown once; only its hash is stored. `rotate()` keeps the old key working for a grace period. [Docs](docs/api-keys.md)
248
+
249
+ ### Background jobs
250
+
251
+ ```ts
252
+ export const sendReceipt = gw.jobs.define("email.receipt", {
253
+ schema: z.object({ orderId: z.string() }), // or any Standard Schema
254
+ async run({ orderId }, { signal }) {
255
+ await mailer.sendReceipt(orderId, { signal });
256
+ },
257
+ });
258
+
259
+ await sendReceipt.enqueue({ orderId }, { tx, dedupeKey: `receipt:${orderId}` });
260
+ gw.jobs.schedule("reports.nightly", { every: "1d" }, () => buildReports());
261
+ await gw.jobs.work({ concurrency: 4, signal }); // or runOnce() from a cron route
262
+ ```
263
+
264
+ [Docs](docs/jobs.md)
265
+
266
+ ### Idempotency keys
267
+
268
+ ```ts
269
+ return gw.idempotency.handle(request, { scope: `user:${user.id}` }, async () => {
270
+ const order = await createOrder(await request.json());
271
+ return Response.json(order, { status: 201 });
272
+ });
273
+ ```
274
+
275
+ `run()` does the same for webhooks and anything else that isn't an HTTP handler. [Docs](docs/idempotency.md)
276
+
277
+ ### Next.js
278
+
279
+ ```ts
280
+ export const POST = withApiKey(
281
+ ["posts:write"],
282
+ withRateLimit(
283
+ postWrites,
284
+ (_request, { apiKey }) => apiKey.id,
285
+ withIdempotency({ scope: (_request, { apiKey }) => `apikey:${apiKey.id}` }, createPost),
286
+ ),
287
+ );
288
+ ```
289
+
290
+ [Docs](docs/next.md)
291
+
292
+ ## Compared with
293
+
294
+ There are good libraries for each of these pieces. groundwork's angle is having all five in your own schema and transactions. Here's when another tool fits better:
295
+
296
+ | You need | groundwork gives you | Consider instead |
297
+ | --- | --- | --- |
298
+ | Rate limiting | Fixed window and token bucket in your Postgres, hashed subjects, a memory fallback, optional Redis | [@upstash/ratelimit](https://github.com/upstash/ratelimit-js) on edge runtimes or without Postgres. [rate-limiter-flexible](https://github.com/animir/node-rate-limiter-flexible) for many more backends; its `RateLimiterDrizzle` also keeps its table in your schema (fixed window, no `tx`). |
299
+ | An audit log | Explicit, typed `record()` calls in your transaction, with diffs and redaction | [drizzle-audit](https://www.npmjs.com/package/drizzle-audit) to capture every ORM write automatically. Database triggers to also catch writes from outside your app. |
300
+ | API keys | Hashed, scoped keys in your database, with rotation grace, IP and origin allowlists and per-key limits | [Unkey](https://www.unkey.com), a hosted service with usage analytics. better-auth's [api-key plugin](https://www.npmjs.com/package/@better-auth/api-key) when keys belong to better-auth users and you need no more than it offers. |
301
+ | Background jobs | Typed jobs in your schema, enqueued in your transaction, leases, and a cron-friendly `runOnce()` | [pg-boss](https://github.com/timgit/pg-boss) or [graphile-worker](https://worker.graphile.org) for high volume, cron expressions, or job dependencies and workflows. Both bring their own schema and migrations. |
302
+ | Idempotency keys | The IETF draft's behaviour, with stored responses and crash recovery | Few libraries do this. If a payment provider is the only side effect, its own idempotency keys may be enough. |
303
+
304
+ groundwork isn't for edge runtimes, databases other than Postgres, or stacks that already run everything through Redis.
305
+
306
+ ## Requirements
307
+
308
+ - PostgreSQL 16 or newer.
309
+ - `drizzle-orm` 0.45 with any Postgres driver (`postgres`, `pg`, Neon's websocket driver…). groundwork's own statements are all single statements; passing `{ tx }` needs a driver that supports transactions. CI tests `postgres` and `pg`.
310
+ - Node.js 22+ or Bun 1.4+. ESM only.
311
+ - TypeScript 5.9+ if you use the types (CI checks 5.9, 6.0 and 7.0).
312
+ - For `@vantedev/groundwork/next`: nothing extra. It never imports `next`; CI tests it with Next.js 16.
313
+ - Optional: Redis, only for the Redis rate-limit store (tested with Redis 8, ioredis 6 and node-redis 6).
314
+
315
+ ## Documentation
316
+
317
+ | Guide | What's inside |
318
+ | --- | --- |
319
+ | [Core concepts](docs/core-concepts.md) | Durations, the app secret, errors, logging and clocks |
320
+ | [Table factories](docs/schema.md) | Putting groundwork's tables in your schema, column by column |
321
+ | [Rate limiting](docs/rate-limiting.md) | Algorithms, headers, failure modes, Redis |
322
+ | [Audit log](docs/audit.md) | Recording in transactions, diffs, redaction, querying, retention |
323
+ | [API keys](docs/api-keys.md) | Key format, scopes, verification, rotation, allowlists, per-key limits |
324
+ | [Background jobs](docs/jobs.md) | Workers, leases, retries, schedules, health |
325
+ | [Idempotency keys](docs/idempotency.md) | What's stored, status codes, crashes, `run()` |
326
+ | [Next.js helpers](docs/next.md) | Route wrappers, the jobs cron route, client IPs |
327
+ | [Testing your app](docs/testing.md) | Real Postgres, the test clock, calling routes directly |
328
+ | [Migrating](docs/migrating.md) | Moving off hand-rolled tables, module by module |
329
+ | [Example app](examples/next-app) | Every module in one Next.js 16 app |
330
+ | [Releasing](docs/releasing.md) | For maintainers: versions, provenance, trusted publishing |
331
+
332
+ ## Develop
333
+
334
+ ```sh
335
+ bun install
336
+ bun run db:up # Postgres (127.0.0.1:54330) and Redis (:63790) in Docker
337
+ bun run check # Biome, TypeScript and unit tests
338
+ bun run test # everything, including the integration tests
339
+ bun run example # the example app and this README's quickstart, built and run
340
+ ```
341
+
342
+ [CONTRIBUTING.md](CONTRIBUTING.md) explains the test harness, the migration workflow and the conventions. [PLAN.md](PLAN.md) has the roadmap and every design decision.
343
+
344
+ ## License
345
+
346
+ [MIT](LICENSE) © Vante
347
+
348
+ <div align="center">
349
+ <br>
350
+ <sub>Built to be the last time you write a rate limiter.</sub>
351
+ </div>
@@ -0,0 +1,56 @@
1
+ import type { Clock } from "../internal/clock.ts";
2
+ import { type SecretSource } from "../internal/crypto.ts";
3
+ import { type GroundworkDatabase } from "../internal/db.ts";
4
+ import { type Logger } from "../internal/logger.ts";
5
+ import type { RateLimiter } from "../rate-limit/types.ts";
6
+ import { type ApiKeysTable } from "../schema/api-keys.ts";
7
+ import type { ApiKeyEvent, ApiKeyRateLimit, ApiKeys } from "./types.ts";
8
+ export interface ApiKeysOptions<TScopes extends Record<string, string>> {
9
+ readonly db: GroundworkDatabase;
10
+ /** The `apiKeys` table from `groundworkTables()`. */
11
+ readonly table: ApiKeysTable;
12
+ /**
13
+ * The app secret, or a function that returns it on first use. Keys are stored as HMACs under a
14
+ * subkey derived from it.
15
+ */
16
+ readonly secret: SecretSource;
17
+ /** The start of every key, such as `"vnt"` for `vnt_…`. Pick something unique to your app. */
18
+ readonly namespace: string;
19
+ /** Every scope your API knows, with a description: `{ "posts:read": "Read posts" }`. */
20
+ readonly scopes: TScopes;
21
+ /** Append a CRC32 checksum to new keys (`true`, the default). Keys without one still verify. */
22
+ readonly checksum?: boolean | undefined;
23
+ /** Enforces per-key rate limits and daily quotas. Required unless `defaultRateLimit` is `null`. */
24
+ readonly rateLimiter?: RateLimiter | undefined;
25
+ /** The limit new keys get when `create()` doesn't set one. Defaults to 60 per minute. */
26
+ readonly defaultRateLimit?: ApiKeyRateLimit | null | undefined;
27
+ /**
28
+ * For keys created by a previous system: the hash it stored for a key, such as
29
+ * `(key) => createHmac("sha256", oldPepper).update(key).digest("hex")`. Such keys verify, and
30
+ * are moved to groundwork's hash the first time they're used.
31
+ */
32
+ readonly legacyHash?: ((key: string) => string) | undefined;
33
+ /** Called after every change to a key, in its transaction. `createGroundwork` uses it for the audit log. */
34
+ readonly onEvent?: ((event: ApiKeyEvent<keyof TScopes & string>) => void | Promise<void>) | undefined;
35
+ /**
36
+ * Receives background writes (`lastUsedAt`) so a serverless platform can wait for them:
37
+ * Next.js `after`, or `ctx.waitUntil`. Defaults to letting them run on their own.
38
+ */
39
+ readonly waitUntil?: ((promise: Promise<unknown>) => void) | undefined;
40
+ /** Defaults to Postgres's time. Inject one in tests. */
41
+ readonly clock?: Clock | undefined;
42
+ /** Defaults to `console` (warnings and errors only). */
43
+ readonly logger?: Logger | undefined;
44
+ }
45
+ /**
46
+ * Creates scoped API keys stored in your Postgres.
47
+ *
48
+ * ```ts
49
+ * const apiKeys = createApiKeys({ db, table, secret, namespace: "vnt", scopes: { "posts:read": "Read posts" }, rateLimiter });
50
+ * const { key } = await apiKeys.create({ name: "CI", scopes: ["posts:read"] });
51
+ * const auth = await apiKeys.verify(request, { scopes: ["posts:read"] });
52
+ * if (!auth.ok) return auth.response;
53
+ * ```
54
+ */
55
+ export declare function createApiKeys<const TScopes extends Record<string, string>>(options: ApiKeysOptions<TScopes>): ApiKeys<keyof TScopes & string>;
56
+ //# sourceMappingURL=api-keys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-keys.d.ts","sourceRoot":"","sources":["../../src/api-keys/api-keys.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAClD,OAAO,EAAc,KAAK,YAAY,EAAmB,MAAM,uBAAuB,CAAC;AACvF,OAAO,EAAE,KAAK,kBAAkB,EAAoB,MAAM,mBAAmB,CAAC;AAG9E,OAAO,EAAmC,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAErF,OAAO,KAAK,EAAE,WAAW,EAAkC,MAAM,wBAAwB,CAAC;AAC1F,OAAO,EAAmB,KAAK,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAkB3E,OAAO,KAAK,EACV,WAAW,EAEX,eAAe,EAGf,OAAO,EAOR,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,cAAc,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IACpE,QAAQ,CAAC,EAAE,EAAE,kBAAkB,CAAC;IAChC,qDAAqD;IACrD,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC;IAC7B;;;OAGG;IACH,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAC9B,8FAA8F;IAC9F,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,wFAAwF;IACxF,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;IACzB,gGAAgG;IAChG,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACxC,mGAAmG;IACnG,QAAQ,CAAC,WAAW,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IAC/C,yFAAyF;IACzF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,eAAe,GAAG,IAAI,GAAG,SAAS,CAAC;IAC/D;;;;OAIG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG,SAAS,CAAC;IAC5D,4GAA4G;IAC5G,QAAQ,CAAC,OAAO,CAAC,EACb,CAAC,CAAC,KAAK,EAAE,WAAW,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,GACtE,SAAS,CAAC;IACd;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,CAAC;IACvE,wDAAwD;IACxD,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,GAAG,SAAS,CAAC;IACnC,wDAAwD;IACxD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACtC;AA6ED;;;;;;;;;GASG;AACH,wBAAgB,aAAa,CAAC,KAAK,CAAC,OAAO,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EACxE,OAAO,EAAE,cAAc,CAAC,OAAO,CAAC,GAC/B,OAAO,CAAC,MAAM,OAAO,GAAG,MAAM,CAAC,CA8qBjC"}