@gusto/baerly-storage 0.1.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 (115) hide show
  1. package/README.md +97 -0
  2. package/dist/API.md +850 -0
  3. package/dist/app-config-Cb5dO2s9.d.ts +480 -0
  4. package/dist/app-config.d.ts +2 -0
  5. package/dist/app-config.js +8 -0
  6. package/dist/app-config.js.map +1 -0
  7. package/dist/auth.d.ts +237 -0
  8. package/dist/auth.js +1335 -0
  9. package/dist/auth.js.map +1 -0
  10. package/dist/baerly.js +761 -0
  11. package/dist/baerly.js.map +1 -0
  12. package/dist/bucket-uri-BrDEYvzy.js +4922 -0
  13. package/dist/bucket-uri-BrDEYvzy.js.map +1 -0
  14. package/dist/chunk-EAsCxrDo.js +14 -0
  15. package/dist/client-BLf3Ae5s.d.ts +233 -0
  16. package/dist/client-react.d.ts +131 -0
  17. package/dist/client-react.js +559 -0
  18. package/dist/client-react.js.map +1 -0
  19. package/dist/client.d.ts +4 -0
  20. package/dist/client.js +160 -0
  21. package/dist/client.js.map +1 -0
  22. package/dist/cloudflare-CINJPKCW.js +911 -0
  23. package/dist/cloudflare-CINJPKCW.js.map +1 -0
  24. package/dist/cloudflare.d.ts +211 -0
  25. package/dist/cloudflare.js +445 -0
  26. package/dist/cloudflare.js.map +1 -0
  27. package/dist/config-Bsg8wgwo.js +198 -0
  28. package/dist/config-Bsg8wgwo.js.map +1 -0
  29. package/dist/context-Oj7ffwD-.js +187 -0
  30. package/dist/context-Oj7ffwD-.js.map +1 -0
  31. package/dist/cost-B1WiZxlf.js +203 -0
  32. package/dist/cost-B1WiZxlf.js.map +1 -0
  33. package/dist/current-json-BkatBzF7.js +252 -0
  34. package/dist/current-json-BkatBzF7.js.map +1 -0
  35. package/dist/db-D62JguBc.d.ts +336 -0
  36. package/dist/deploy-BB-wqbhf.js +83 -0
  37. package/dist/deploy-BB-wqbhf.js.map +1 -0
  38. package/dist/dev-banner-CWHIk8tH.d.ts +26 -0
  39. package/dist/dev-vite.d.ts +146 -0
  40. package/dist/dev-vite.js +223 -0
  41. package/dist/dev-vite.js.map +1 -0
  42. package/dist/dev.d.ts +3 -0
  43. package/dist/dev.js +2 -0
  44. package/dist/doctor-B8h9GCN9.js +331 -0
  45. package/dist/doctor-B8h9GCN9.js.map +1 -0
  46. package/dist/dump-BHo_sIMZ.js +116 -0
  47. package/dist/dump-BHo_sIMZ.js.map +1 -0
  48. package/dist/errors-DOdL95kK.js +58 -0
  49. package/dist/errors-DOdL95kK.js.map +1 -0
  50. package/dist/export-Dz2PZKSR.js +423 -0
  51. package/dist/export-Dz2PZKSR.js.map +1 -0
  52. package/dist/fsck-DEz9lyCy.js +293 -0
  53. package/dist/fsck-DEz9lyCy.js.map +1 -0
  54. package/dist/http-CjUO1Bec.js +1756 -0
  55. package/dist/http-CjUO1Bec.js.map +1 -0
  56. package/dist/http.d.ts +1619 -0
  57. package/dist/http.js +2 -0
  58. package/dist/index-BGC-ENnj.d.ts +1065 -0
  59. package/dist/index-BYv0hb8M.d.ts +1457 -0
  60. package/dist/index-BquQkhJi.d.ts +112 -0
  61. package/dist/index-COsQ-Mlz.d.ts +146 -0
  62. package/dist/index.d.ts +6 -0
  63. package/dist/index.js +6 -0
  64. package/dist/indexes-BXn7a06a.js +297 -0
  65. package/dist/indexes-BXn7a06a.js.map +1 -0
  66. package/dist/indexes-DwOXkn1Y.d.ts +22 -0
  67. package/dist/inspect-x02aFWnh.js +149 -0
  68. package/dist/inspect-x02aFWnh.js.map +1 -0
  69. package/dist/log-walk-DIru96UT.js +260 -0
  70. package/dist/log-walk-DIru96UT.js.map +1 -0
  71. package/dist/maintenance-Bn6ul9aV.js +758 -0
  72. package/dist/maintenance-Bn6ul9aV.js.map +1 -0
  73. package/dist/maintenance.d.ts +323 -0
  74. package/dist/maintenance.js +2 -0
  75. package/dist/node.d.ts +422 -0
  76. package/dist/node.js +2 -0
  77. package/dist/normalize-XWY25_sG.js +133 -0
  78. package/dist/normalize-XWY25_sG.js.map +1 -0
  79. package/dist/observability-2IDYRuZK.js +2333 -0
  80. package/dist/observability-2IDYRuZK.js.map +1 -0
  81. package/dist/observability.d.ts +3 -0
  82. package/dist/observability.js +3 -0
  83. package/dist/plan-Cs17VqjU.js +224 -0
  84. package/dist/plan-Cs17VqjU.js.map +1 -0
  85. package/dist/query-DcSbFLJt.js +1880 -0
  86. package/dist/query-DcSbFLJt.js.map +1 -0
  87. package/dist/rebuild-index-C5gTXryd.js +119 -0
  88. package/dist/rebuild-index-C5gTXryd.js.map +1 -0
  89. package/dist/rebuild-index-DwXM0WfA.js +104 -0
  90. package/dist/rebuild-index-DwXM0WfA.js.map +1 -0
  91. package/dist/request-BEF_OvMh.js +72 -0
  92. package/dist/request-BEF_OvMh.js.map +1 -0
  93. package/dist/restore-CbKVMMpm.js +847 -0
  94. package/dist/restore-CbKVMMpm.js.map +1 -0
  95. package/dist/shared-secret-BJdSwpgw.js +71 -0
  96. package/dist/shared-secret-BJdSwpgw.js.map +1 -0
  97. package/dist/snapshot-D7C4_FSl.js +71 -0
  98. package/dist/snapshot-D7C4_FSl.js.map +1 -0
  99. package/dist/snapshot-z_N9hpTe.js +917 -0
  100. package/dist/snapshot-z_N9hpTe.js.map +1 -0
  101. package/dist/src-Chafbw8r.js +522 -0
  102. package/dist/src-Chafbw8r.js.map +1 -0
  103. package/dist/src-DyET_VPP.js +6199 -0
  104. package/dist/src-DyET_VPP.js.map +1 -0
  105. package/dist/src-n0Te1r98.js +352 -0
  106. package/dist/src-n0Te1r98.js.map +1 -0
  107. package/dist/subcommand-BWs6K7zb.js +110 -0
  108. package/dist/subcommand-BWs6K7zb.js.map +1 -0
  109. package/dist/usage-RVUQMLop.js +339 -0
  110. package/dist/usage-RVUQMLop.js.map +1 -0
  111. package/dist/validate-DhH1lO8I.js +377 -0
  112. package/dist/validate-DhH1lO8I.js.map +1 -0
  113. package/dist/wire-izfGZDvr.js +7 -0
  114. package/dist/wire-izfGZDvr.js.map +1 -0
  115. package/package.json +189 -0
@@ -0,0 +1,1065 @@
1
+ import { f as DocumentData, m as JSONValue, p as DocumentValue } from "./app-config-Cb5dO2s9.js";
2
+ //#region packages/protocol/src/storage/types.d.ts
3
+ /**
4
+ * Object-storage abstraction. The protocol kernel writes through
5
+ * this and only this. Implementations: in-memory (testing), S3 HTTP
6
+ * (production), R2 binding (deferred), local-fs (deferred).
7
+ *
8
+ * Cancellation: every method accepts an optional AbortSignal.
9
+ * Implementations should respect it where feasible; consumers may
10
+ * ignore it. We thread it through from the start so we don't have
11
+ * to retrofit cancellation later.
12
+ *
13
+ * Encoding: bodies are `Uint8Array` (works in Workers + Node 24+),
14
+ * not `Buffer`. Result types are `readonly` — the kernel doesn't
15
+ * mutate what storage returns.
16
+ *
17
+ * Not-found is signalled by `null` (single discriminator), not by
18
+ * throwing. Other failure modes throw `BaerlyError`.
19
+ */
20
+ interface Storage {
21
+ /**
22
+ * Fetch a single object. Returns `null` on not-found (404
23
+ * semantics). With `ifNoneMatch`, returns `null` if the current
24
+ * ETag matches (304 semantics — caller's cached copy is current).
25
+ * With `versionId`, fetches a specific historical version (only
26
+ * meaningful on a versioned S3 bucket; non-versioning impls may
27
+ * ignore). Other failure modes throw `BaerlyError`.
28
+ */
29
+ get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null>;
30
+ /**
31
+ * Write a single object. Returns the new ETag and, when the
32
+ * underlying transport surfaces it, the server's response time
33
+ * as `serverDate` (S3's `Date` header). The kernel uses
34
+ * `serverDate` to track adaptive clock-skew; impls may return
35
+ * `undefined` if no server clock is available. Use `ifMatch` for
36
+ * compare-and-swap (write only if the current ETag matches), or
37
+ * `ifNoneMatch: "*"` for create-only (write only if no object
38
+ * exists). Conflicts throw `BaerlyError` with HTTP 412 semantics.
39
+ */
40
+ put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult>;
41
+ /**
42
+ * Delete a single object. Idempotent: deleting a missing key is
43
+ * not an error.
44
+ */
45
+ delete(key: string, opts?: {
46
+ signal?: AbortSignal;
47
+ }): Promise<void>;
48
+ /**
49
+ * Lex-asc enumeration of keys with the given prefix. Pagination is
50
+ * implementation-internal; consumers iterate until exhaustion or
51
+ * `maxKeys`. `startAfter` (exclusive) is a strict-greater cursor.
52
+ */
53
+ list(prefix: string, opts?: {
54
+ startAfter?: string;
55
+ maxKeys?: number;
56
+ signal?: AbortSignal;
57
+ }): AsyncIterable<StorageListEntry>;
58
+ }
59
+ interface StorageGetOptions {
60
+ readonly ifNoneMatch?: string;
61
+ /**
62
+ * Pin to a specific historical version. Maps to S3's
63
+ * `?versionId=…` query parameter on versioned buckets. Impls that
64
+ * don't model versions may ignore.
65
+ */
66
+ readonly versionId?: string;
67
+ readonly signal?: AbortSignal;
68
+ }
69
+ interface StorageGetResult {
70
+ readonly body: Uint8Array;
71
+ readonly etag: string;
72
+ /**
73
+ * S3 `x-amz-version-id` of the returned object on versioned
74
+ * buckets; `undefined` for unversioned reads or impls without
75
+ * native versioning.
76
+ */
77
+ readonly versionId?: string;
78
+ }
79
+ interface StoragePutResult {
80
+ readonly etag: string;
81
+ /**
82
+ * Server-reported response time, used by the kernel's adaptive
83
+ * clock-skew loop. Set by HTTP-backed impls from the response
84
+ * `Date` header; in-memory impls fill in the local wall clock.
85
+ * `undefined` if no clock signal is available.
86
+ */
87
+ readonly serverDate?: Date;
88
+ /**
89
+ * S3 `x-amz-version-id` of the new object version on versioned
90
+ * buckets; `undefined` for unversioned writes or impls without
91
+ * native versioning.
92
+ */
93
+ readonly versionId?: string;
94
+ }
95
+ interface StoragePutOptions {
96
+ /** CAS guard: write only if ETag matches. */
97
+ readonly ifMatch?: string;
98
+ /** Create-only guard: write only if no object exists. */
99
+ readonly ifNoneMatch?: "*";
100
+ readonly contentType?: string;
101
+ /** Cancel mid-flight; impls should respect when feasible. */
102
+ readonly signal?: AbortSignal;
103
+ }
104
+ interface StorageListEntry {
105
+ readonly key: string;
106
+ readonly etag: string;
107
+ /**
108
+ * Server's `Last-Modified` for the listed object. The kernel's
109
+ * manifest validity check uses this to reject writes whose
110
+ * embedded base32 timestamp disagrees with the server's clock by
111
+ * more than `LAG_WINDOW_MILLIS` (defends against clock-skewed or
112
+ * adversarial writers). Impls without a server clock may return
113
+ * `undefined` and the kernel skips the cross-check.
114
+ */
115
+ readonly lastModified?: Date;
116
+ }
117
+ //#endregion
118
+ //#region packages/protocol/src/coordination/current-json.d.ts
119
+ /**
120
+ * Per-collection control object. CAS-protected. One per
121
+ * `(tenant, collection)` key — for example
122
+ * `<tenant>/<collection>/current.json`. The compactor swaps
123
+ * snapshot generations by CAS-writing this object; the
124
+ * Writer reads it on every commit to find the snapshot
125
+ * pointer; the sweeper reads `writer_fence` to decide which log
126
+ * entries are eligible for GC.
127
+ *
128
+ * The schema is forward-compatible: adding a new optional field is
129
+ * non-breaking. Renaming or removing a field requires bumping
130
+ * {@link CURRENT_JSON_SCHEMA_VERSION} to `2`; readers MUST reject
131
+ * unknown major versions with `BaerlyError{code:"InvalidResponse"}`.
132
+ */
133
+ interface CurrentJson {
134
+ /**
135
+ * Schema version. Today: `1`. Bump on any breaking change to
136
+ * field semantics; readers must reject unknown major versions
137
+ * with `BaerlyError{code:"InvalidResponse"}`.
138
+ */
139
+ schema_version: 1;
140
+ /**
141
+ * Pointer to the current snapshot generation. `null` before the
142
+ * first compaction has produced a snapshot — readers fall back
143
+ * to log-only replay. Shape is opaque-to-this-module; the
144
+ * compactor owns its interpretation.
145
+ */
146
+ snapshot: string | null;
147
+ /**
148
+ * Sequence number of the next log entry. Monotonic per
149
+ * collection. The Writer reads this on commit to mint the
150
+ * next log filename; CAS-write back with `next_seq + 1` ensures
151
+ * no two writers pick the same sequence.
152
+ */
153
+ next_seq: number;
154
+ /**
155
+ * Lowest live log sequence number. Entries with `seq < log_seq_start`
156
+ * have been folded into the snapshot at {@link snapshot} (or, if
157
+ * `snapshot === null`, have been dropped because the collection was
158
+ * truncated). Readers walk `[log_seq_start, next_seq)`. Always
159
+ * present on disk — fresh `current.json` writes via
160
+ * {@link createCurrentJson} set this to `0`; the compactor advances
161
+ * it on every fold.
162
+ *
163
+ * Invariants the compactor maintains:
164
+ * - `0 <= log_seq_start <= next_seq`
165
+ * - `log_seq_start` advances monotonically (never decreases)
166
+ * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot
167
+ * covers `[0, log_seq_start)`)
168
+ */
169
+ log_seq_start: number;
170
+ /**
171
+ * Embedded write-fence epoch. See {@link WriterFence}.
172
+ */
173
+ writer_fence: WriterFence;
174
+ }
175
+ /**
176
+ * Fence-token sub-shape embedded in {@link CurrentJson}. The
177
+ * monotonically-bumped `epoch` is the only safety-critical field —
178
+ * `owner` is informational and may be missing in older records;
179
+ * `claimed_at` is the server response date at claim time, NOT the
180
+ * local clock; `lease_until` is reserved for manual rotation and
181
+ * is not consumed by any ticket in this batch.
182
+ *
183
+ * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's
184
+ * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view
185
+ * number. The mechanism is the same in all three: every commit
186
+ * checks the epoch on the control object; an entry stamped with
187
+ * a stale epoch is discarded at replay.
188
+ */
189
+ interface WriterFence {
190
+ /**
191
+ * Monotonic unsigned integer. Bumped only by an explicit
192
+ * {@link claimWriter} call — do NOT bump on every cold start, do
193
+ * NOT bump on every commit. Triggers per design: (a) detected
194
+ * CAS conflict the writer wants to claim through, (b) admin
195
+ * rotation. The sweeper discards log entries whose stamped epoch
196
+ * is `< current.writer_fence.epoch`.
197
+ */
198
+ epoch: number;
199
+ /**
200
+ * Owner identifier — debug only, NOT consulted for safety.
201
+ * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty
202
+ * string when claim provenance is unknown (e.g. initial
203
+ * creation). Safety derives from `epoch`, not from `owner`.
204
+ */
205
+ owner: string;
206
+ /**
207
+ * ISO-8601 timestamp from the `StoragePutResult.serverDate` on
208
+ * the successful CAS PUT. **Never use `new Date()` or
209
+ * `Date.now()` to populate this field** — under multi-instance
210
+ * deployment the local clock may disagree with peers; the
211
+ * server's clock is the only one all instances share. Format
212
+ * via `serverDate.toISOString()`. The empty string `""` means
213
+ * "claim time unknown" — readers MUST treat it as such rather
214
+ * than parsing it.
215
+ */
216
+ claimed_at: string;
217
+ /**
218
+ * Optional explicit lease horizon, also ISO-8601. Reserved for
219
+ * future manual rotation workflows; current code only writes
220
+ * the field through if a caller supplies it and does not read
221
+ * it.
222
+ */
223
+ lease_until?: string;
224
+ }
225
+ /**
226
+ * Return shape from {@link readCurrentJson} et al.: the parsed JSON
227
+ * plus the ETag needed for a follow-up CAS write.
228
+ */
229
+ interface CurrentJsonRead {
230
+ readonly json: CurrentJson;
231
+ readonly etag: string;
232
+ }
233
+ //#endregion
234
+ //#region packages/protocol/src/query/builder.d.ts
235
+ /**
236
+ * Callback-form predicate builder. Methods append clauses and
237
+ * return the same builder for chaining; chained calls AND-merge.
238
+ *
239
+ * The methods on this interface ARE the supported operator surface.
240
+ * Vocabulary additions (`or`, `not`, `regex`, `ne`, `exists`, ...)
241
+ * are intentionally absent — calling them is a TS2339 compile
242
+ * error, not a runtime rejection. See ADR-002 amendment dated
243
+ * 2026-05-26 for the algebra-lock policy.
244
+ *
245
+ * @template T - the document shape the predicate is keyed against.
246
+ */
247
+ interface PredicateBuilder<T extends DocumentData = DocumentData> {
248
+ /**
249
+ * Strict equality on `field`. Use this for the in-callback
250
+ * equality clauses that the object-form would also support;
251
+ * mixing `q.eq(...)` with range / `in` clauses in one call is
252
+ * the canonical "mixed equality + range" pattern.
253
+ */
254
+ eq<K extends Path<T>>(field: K, value: PathValue<T, K>): PredicateBuilder<T>;
255
+ /**
256
+ * Strict greater. `value` must be `string` or `number`; the
257
+ * intersection at the type level rejects `boolean` / `null`
258
+ * fields at the call site (`q.gt("done", true)` is a TS error
259
+ * on a `done: boolean` field).
260
+ */
261
+ gt<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
262
+ /** Inclusive greater. See {@link gt} for the value-type constraint. */
263
+ gte<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
264
+ /** Strict less. See {@link gt} for the value-type constraint. */
265
+ lt<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
266
+ /** Inclusive less. See {@link gt} for the value-type constraint. */
267
+ lte<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;
268
+ /**
269
+ * Set membership. Empty array is `UnsatisfiablePredicate` at
270
+ * normalise time — the validator emits the error eagerly so the
271
+ * caller sees it at the `.where(...)` call site, not later.
272
+ */
273
+ in<K extends Path<T>>(field: K, values: ReadonlyArray<PathValue<T, K>>): PredicateBuilder<T>;
274
+ }
275
+ /**
276
+ * Argument shape accepted by `.where(...)`. Either the object-literal
277
+ * equality form ({@link Predicate}) or a callback that drives a
278
+ * {@link PredicateBuilder} and returns it (the chain terminator).
279
+ */
280
+ type PredicateArg<T extends DocumentData> = Predicate<T> | ((q: PredicateBuilder<T>) => PredicateBuilder<T>);
281
+ //#endregion
282
+ //#region packages/protocol/src/collection-api.d.ts
283
+ /**
284
+ * Handle on one collection. The common single-row case lives
285
+ * here as direct verbs (`get(id)`, `update(id, patch)`,
286
+ * `replace(id, doc)`, `delete(id)`) plus whole-collection reads
287
+ * (`first()`, `all()`, `count()`). For bulk-by-predicate mutation —
288
+ * or for chained `.where()` / `.order()` / `.limit()` reads — call
289
+ * the modifier verbs to get a {@link Query} back.
290
+ *
291
+ * @template T — the document shape. Documents always carry an
292
+ * auto-generated `_id` (UUIDv7); the type system
293
+ * treats `_id` as optional on `insert` (server fills
294
+ * it in) and required on read.
295
+ */
296
+ interface Collection<T extends DocumentData = DocumentData> {
297
+ readonly name: string;
298
+ /**
299
+ * First document in the whole collection or `undefined` when the
300
+ * collection is empty. Equivalent to `.where({}).first()`.
301
+ *
302
+ * @example
303
+ * ```ts
304
+ * const any = await db.collection("tickets").first();
305
+ * ```
306
+ */
307
+ first(): Promise<T | undefined>;
308
+ /**
309
+ * Every document in the whole collection. Equivalent to
310
+ * `.where({}).all()`. No implicit cap — prefer
311
+ * `.where(p).limit(n).all()` on large collections.
312
+ *
313
+ * @example
314
+ * ```ts
315
+ * const all = await db.collection("tickets").all();
316
+ * ```
317
+ */
318
+ all(): Promise<T[]>;
319
+ /**
320
+ * Count every row in the collection (equivalent to `.where({}).count()`).
321
+ *
322
+ * @example
323
+ * ```ts
324
+ * const total = await db.collection("tickets").count();
325
+ * ```
326
+ */
327
+ count(): Promise<number>;
328
+ /**
329
+ * Fetch one document by primary key. Returns `undefined` when the
330
+ * id is unknown — does not throw `NotFound`.
331
+ *
332
+ * @example
333
+ * ```ts
334
+ * const ticket = await db.collection("tickets").get(id);
335
+ * if (ticket === undefined) {
336
+ * // row not in this collection
337
+ * }
338
+ * ```
339
+ */
340
+ get(id: string): Promise<T | undefined>;
341
+ /**
342
+ * Filter rows. Two shapes:
343
+ *
344
+ * - **Object literal** — equality only. Top-level, dotted-path,
345
+ * or nested-literal sub-predicate.
346
+ * - **Callback DSL** — `q => q.eq(...).gt(...).in(...)`. The
347
+ * operator vocabulary (`eq` / `gt` / `gte` / `lt` / `lte` /
348
+ * `in`) lives here. Chained calls AND-merge inside one
349
+ * callback; chained `.where(...).where(...)` AND-merges
350
+ * across calls and across shapes.
351
+ *
352
+ * Methods that do not exist on {@link PredicateBuilder}
353
+ * (`or`, `not`, `regex`, `ne`, `exists`, ...) are intentionally
354
+ * absent — invoking them is a TS compile error.
355
+ *
356
+ * @example
357
+ * ```ts
358
+ * db.collection("tickets").where({ status: "open" }).all();
359
+ * db.collection("tickets").where({ "assignee.team": "platform" }).all();
360
+ * db.collection("tickets").where(q => q.gte("count", 1).lt("count", 10)).all();
361
+ * db.collection("tickets").where(q => q.in("status", ["open", "pending"])).all();
362
+ * db.collection("tickets")
363
+ * .where({ status: "open" })
364
+ * .where(q => q.gte("priority", 5))
365
+ * .all();
366
+ * ```
367
+ */
368
+ where(predicate: PredicateArg<T>): Query<T>;
369
+ /** Order modifier; last call wins. */
370
+ order(spec: OrderSpec<T>): Query<T>;
371
+ /** Limit modifier; last call wins. */
372
+ limit(n: number): Query<T>;
373
+ /**
374
+ * Insert a new document. UUIDv7 auto-id on `_id`; caller can
375
+ * supply `_id` and the server honours it. Returns the new id.
376
+ *
377
+ * @throws BaerlyError{code: "Conflict"} — `_id` collision on
378
+ * caller-supplied id.
379
+ * @throws BaerlyError{code: "SchemaError"} — malformed JSON, or
380
+ * schema-validation failure (when a schema is declared
381
+ * for the collection via `Db.create({ collections })`).
382
+ *
383
+ * @example
384
+ * ```ts
385
+ * const { _id } = await db.collection("tickets").insert({
386
+ * status: "open",
387
+ * title: "Ship the docs",
388
+ * });
389
+ * ```
390
+ */
391
+ insert(doc: Partial<T> & DocumentData): Promise<{
392
+ _id: string;
393
+ }>;
394
+ /**
395
+ * JSON-merge-patch (RFC 7386) applied to one row by primary key.
396
+ * For predicate-aware bulk mutation, use
397
+ * `.where(predicate).update(patch)` on {@link Query}.
398
+ *
399
+ * @throws BaerlyError{code: "Conflict"} — concurrent write lost
400
+ * the CAS race. Caller's choice whether to retry.
401
+ * @throws BaerlyError{code: "SchemaError"} — patch produced an
402
+ * invalid doc.
403
+ *
404
+ * @example
405
+ * ```ts
406
+ * const { modified } = await db.collection("tickets")
407
+ * .update(id, { status: "closed" });
408
+ * ```
409
+ */
410
+ update(id: string, patch: Partial<T>): Promise<{
411
+ modified: number;
412
+ }>;
413
+ /**
414
+ * Whole-document replace on one row by primary key. Throws
415
+ * `BaerlyError{code:"NotFound"}` when no row exists at `id`.
416
+ *
417
+ * @example
418
+ * ```ts
419
+ * await db.collection("tickets")
420
+ * .replace(id, { _id: id, status: "open", title: "Rewrite" });
421
+ * ```
422
+ */
423
+ replace(id: string, doc: T): Promise<void>;
424
+ /**
425
+ * Delete one row by primary key. Returns `{ deleted: 0 }` when the
426
+ * id is unknown rather than throwing. For predicate-aware bulk
427
+ * delete, use `.where(predicate).delete()` on {@link Query}.
428
+ *
429
+ * @example
430
+ * ```ts
431
+ * const { deleted } = await db.collection("tickets").delete(id);
432
+ * ```
433
+ */
434
+ delete(id: string): Promise<{
435
+ deleted: number;
436
+ }>;
437
+ }
438
+ /**
439
+ * Decrementing depth markers for {@link Path}'s recursion cap.
440
+ * The default of 4 means dotted paths up to `a.b.c.d.e` are legal;
441
+ * `a.b.c.d.e.f` is rejected. Keeps `tsgo` recursion bounded.
442
+ * @internal
443
+ */
444
+ type _PathDepth = [never, 0, 1, 2, 3, 4];
445
+ /**
446
+ * True when `V` is a value position that should terminate {@link Path}
447
+ * recursion. Primitives, `null`, and arrays are leaves — we do not
448
+ * descend into array indices via dotted-path keys (the runtime
449
+ * evaluator treats every segment as an object key, so `"tags.0"`
450
+ * would resolve to `arr["0"]`, which works but is poor DX).
451
+ * @internal
452
+ */
453
+ type _IsPathLeaf<V> = V extends string | number | boolean | null ? true : V extends ReadonlyArray<unknown> ? true : false;
454
+ /**
455
+ * Strip the string index signature from `T` so {@link Path} can
456
+ * iterate over named keys only. Without this, `T = DocumentData &
457
+ * UserShape` (the canonical user-doc shape across the kernel)
458
+ * collapses `keyof T` to `string` and defeats narrowing.
459
+ *
460
+ * The pattern `string extends K ? never : K` is the standard TS
461
+ * idiom: the parameter of a `[k: string]: …` signature has type
462
+ * `string`, so `string extends string` is true for it (excluded);
463
+ * any literal key like `"status"` does not extend `string`
464
+ * (kept).
465
+ * @internal
466
+ */
467
+ type _StripIndex<T> = { [K in keyof T as string extends K ? never : K]: T[K] };
468
+ /**
469
+ * Recursively-derived union of every legal dotted-path key over `T`.
470
+ * Depth-capped at 5 segments (`a.b.c.d.e` legal, `a.b.c.d.e.f` not) so
471
+ * the type checker doesn't blow recursion limits on deep schemas.
472
+ *
473
+ * When `T` is just `DocumentData` (the default — no user shape
474
+ * passed), `_StripIndex<T>` is `{}` and `_Keys<T>` is `never`. In
475
+ * that case we fall through to bare `string` keys, preserving
476
+ * today's open-keyed default behavior.
477
+ * @internal
478
+ */
479
+ type _AllPaths<T, D extends _PathDepth[number] = 4> = [D] extends [never] ? never : T extends object ? keyof _StripIndex<T> & string extends never ? string : { [K in keyof _StripIndex<T> & string]: _IsPathLeaf<T[K]> extends true ? K : K | `${K}.${_AllPaths<NonNullable<T[K]>, _PathDepth[D]>}` }[keyof _StripIndex<T> & string] : never;
480
+ /**
481
+ * Legal dotted-path keys over `T`, with the root-level `_id` filtered
482
+ * out so the top-level shape no longer accepts `{ _id: "x" }`. Nested
483
+ * `_id` paths (e.g. `"author._id"`) survive — only the bare `"_id"`
484
+ * head and any literal `"_id.<rest>"` head are excluded (no
485
+ * `_id.<rest>` shape exists today since `_id` is a string leaf, but
486
+ * the template-string guard keeps the contract intact if the doc
487
+ * shape ever changes).
488
+ *
489
+ * When `T = DocumentData` (no user-supplied shape), `_AllPaths<T>`
490
+ * degrades to bare `string` and the `Exclude<>` wrapper leaves that
491
+ * branch unchanged — open-keyed predicates still typecheck.
492
+ * @internal
493
+ */
494
+ type Path<T, D extends _PathDepth[number] = 4> = Exclude<_AllPaths<T, D>, "_id" | `_id.${string}`>;
495
+ /**
496
+ * Resolves the leaf value type at dotted path `P` through `T`.
497
+ * Paired with {@link Path} to type the value side of
498
+ * {@link Predicate}. `NonNullable` collapses optional intermediate
499
+ * fields so `"a.b"` resolves through `{ a?: { b: number } }`.
500
+ *
501
+ * Falls back to `DocumentValue` when `P` does not resolve to a
502
+ * named key — this only happens when `Path<T> = string` (no user
503
+ * shape), in which case any string is legal and the value side
504
+ * widens to `DocumentValue` to match today's default.
505
+ * @internal
506
+ */
507
+ type PathValue<T, P extends string> = P extends `${infer H}.${infer R}` ? H extends keyof T ? PathValue<NonNullable<T[H]>, R> : never : P extends keyof T ? T[P] : DocumentValue;
508
+ /**
509
+ * Recursive partial sub-predicate. The value side of a nested
510
+ * predicate clause: every nested key is optional, and recurses into
511
+ * objects. `_SubPredicate<{a: number, b: {c: string}}>` admits
512
+ * `{a: 1}`, `{b: {c: "x"}}`, and `{a: 1, b: {c: "x"}}` — the same
513
+ * open-world matching the matcher delivers at the wire level
514
+ * (`{ assignee: { team: "x" } }` matches docs where
515
+ * `assignee.team === "x"`, ignoring other keys on `assignee`).
516
+ *
517
+ * Recurses over `keyof T` directly (NOT through `Path<T>`) so the
518
+ * root-level `_id` exclusion does not propagate — a nested `_id`
519
+ * names the primary key of an embedded reference and remains
520
+ * queryable (`.where({ author: { _id: "u1" } })` typechecks).
521
+ * @internal
522
+ */
523
+ type _SubPredicate<T> = T extends object ? T extends ReadonlyArray<unknown> ? never : { readonly [K in keyof _StripIndex<T> & string]?: T[K] | _SubPredicate<T[K]> } : never;
524
+ /**
525
+ * Equality-only predicate over a document shape. Object-form
526
+ * accepts:
527
+ *
528
+ * - top-level equality: `{ status: "open" }`
529
+ * - dotted-path equality: `{ "assignee.team": "platform" }`
530
+ * - nested literal sub-predicates: `{ assignee: { team: "platform" } }`
531
+ * — the normaliser flattens to dotted-path `eq` clauses; the
532
+ * nested object may carry only a subset of keys (open-world
533
+ * matching against the document).
534
+ *
535
+ * **Operator vocabulary moved to the callback form.** Range / `in`
536
+ * / mixed eq+range queries write
537
+ * `.where(q => q.gt("priority", 5).in("status", ["open", "pending"]))`.
538
+ * The methods on {@link PredicateBuilder} ARE the supported vocabulary
539
+ * — there is no `$`-keyed object surface, so a method we did not
540
+ * write cannot be called.
541
+ *
542
+ * **No top-level boolean connectives.** `or` / `not` are
543
+ * intentionally absent. Use:
544
+ * - `q.in(field, ["a", "b"])` for OR over one field.
545
+ * - Chained `.where(p1).where(p2)` for AND across multiple
546
+ * predicates — the chain AND-merges.
547
+ *
548
+ * **Depth cap.** Dotted paths are limited to 5 segments
549
+ * (`a.b.c.d.e` legal, `a.b.c.d.e.f` not). Real doc-DB schemas rarely
550
+ * exceed 2–3 levels.
551
+ */
552
+ type Predicate<T extends DocumentData = DocumentData> = { readonly [P in Path<T>]?: PathValue<T, P> extends DocumentValue ? PathValue<T, P> | _SubPredicate<PathValue<T, P>> : DocumentValue };
553
+ /** Order specifier. Top-level fields only on day one. */
554
+ type OrderSpec<T extends DocumentData = DocumentData> = { readonly [K in keyof T]?: "asc" | "desc" };
555
+ /**
556
+ * `Collection<T>` after at least one modifier. Carries predicate /
557
+ * order / limit state forward. Modifiers compose; verbs are
558
+ * terminal. Mutation verbs here are **predicate-aware bulk** — they
559
+ * apply to every matching row. For the common single-row case
560
+ * (`{ _id }`), prefer {@link Collection.update} / {@link Collection.replace} /
561
+ * {@link Collection.delete}.
562
+ */
563
+ interface Query<T extends DocumentData = DocumentData> {
564
+ where(predicate: PredicateArg<T>): Query<T>;
565
+ order(spec: OrderSpec<T>): Query<T>;
566
+ limit(n: number): Query<T>;
567
+ /**
568
+ * First match or `undefined`. Equivalent to `.limit(1).all()[0]`.
569
+ *
570
+ * @example
571
+ * ```ts
572
+ * const oldest = await db.collection("tickets")
573
+ * .where({ status: "open" })
574
+ * .order({ commit_ts: "asc" })
575
+ * .first();
576
+ * ```
577
+ */
578
+ first(): Promise<T | undefined>;
579
+ /**
580
+ * Every matching document, respecting `order` and `limit`. No
581
+ * implicit cap — callers should always pair `.all()` with
582
+ * `.limit(n)` on large collections.
583
+ *
584
+ * @example
585
+ * ```ts
586
+ * const open = await db.collection("tickets")
587
+ * .where({ status: "open" })
588
+ * .order({ commit_ts: "desc" })
589
+ * .limit(50)
590
+ * .all();
591
+ * ```
592
+ */
593
+ all(): Promise<T[]>;
594
+ /**
595
+ * Count matching rows. Cheaper than `(await all()).length`.
596
+ *
597
+ * @example
598
+ * ```ts
599
+ * const open = await db.collection("tickets")
600
+ * .where({ status: "open" })
601
+ * .count();
602
+ * ```
603
+ */
604
+ count(): Promise<number>;
605
+ /**
606
+ * Predicate-aware bulk mutation: JSON-merge-patch (RFC 7386)
607
+ * applied to every matching doc. Atomic per row. `null` at any
608
+ * field deletes it. For the single-row case prefer
609
+ * {@link Collection.update}(id, patch).
610
+ *
611
+ * @throws BaerlyError{code: "Conflict"} — concurrent write lost
612
+ * the CAS race. Caller's choice whether to retry.
613
+ * @throws BaerlyError{code: "SchemaError"} — patch produced an
614
+ * invalid doc.
615
+ *
616
+ * @example
617
+ * ```ts
618
+ * const { modified } = await db.collection("tickets")
619
+ * .where({ status: "open" })
620
+ * .update({ status: "closed", closed_at: new Date().toISOString() });
621
+ * ```
622
+ */
623
+ update(patch: Partial<T>): Promise<{
624
+ modified: number;
625
+ }>;
626
+ /**
627
+ * Predicate-aware bulk delete: every matching document. For the
628
+ * single-row case prefer {@link Collection.delete}(id).
629
+ *
630
+ * @example
631
+ * ```ts
632
+ * const { deleted } = await db.collection("tickets")
633
+ * .where({ status: "closed" })
634
+ * .delete();
635
+ * ```
636
+ */
637
+ delete(): Promise<{
638
+ deleted: number;
639
+ }>;
640
+ }
641
+ //#endregion
642
+ //#region packages/protocol/src/errors.d.ts
643
+ /**
644
+ * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they
645
+ * survive cross-realm boundaries (e.g. a Web Worker) and so callers can
646
+ * pattern-match with grep-friendly equality.
647
+ */
648
+ type BaerlyErrorCode = /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */"InvalidConfig" /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */ | "NetworkError" /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */ | "AccessDenied" /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */ | "InvalidResponse" /** Internal invariant violation — should not be reachable. File a bug. */ | "Internal"
649
+ /**
650
+ * Document body failed schema validation. Emitted by the table-API
651
+ * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when
652
+ * the body is not valid JSON or contains an array where
653
+ * `DocumentValue` is required; also emitted when a collection has a
654
+ * declared `SchemaValidator` (via `Db.create({ collections })`) and
655
+ * the bound schema rejects the doc. In the schema-rejection case the
656
+ * error carries an `issues` array describing each failure. HTTP layer
657
+ * maps this to 422.
658
+ */
659
+ | "SchemaError"
660
+ /**
661
+ * CAS lost on `current.json`. Caller decides whether to retry.
662
+ * Surfaces in the collection API and HTTP layer.
663
+ */
664
+ | "Conflict"
665
+ /**
666
+ * `Verifier` returned no identity. HTTP server maps to 401.
667
+ * Code is reserved here so the union locks.
668
+ */
669
+ | "Unauthorized"
670
+ /**
671
+ * The addressed resource does not exist. HTTP server maps to 404.
672
+ * Emitted by the row-by-id read / update / delete handlers in
673
+ * `packages/server/src/http/router.ts` when the predicate
674
+ * `{ _id }` matches zero rows. Not a protocol invariant —
675
+ * callers may retry after creating the resource or treat as a
676
+ * miss depending on intent. The CLI maps this to the generic
677
+ * exit-2 "storage error" bucket, not the exit-3 "protocol
678
+ * invariant" bucket.
679
+ */
680
+ | "NotFound"
681
+ /**
682
+ * Request body exceeded the server's size cap. HTTP server maps
683
+ * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from
684
+ * `packages/server/src/http/router.ts`). The Node adapter
685
+ * enforces during the `node:http` stream pump so the process
686
+ * never materializes a multi-MiB body; Workers also rely on
687
+ * platform-side caps (16 MB free / 100 MB paid).
688
+ */
689
+ | "PayloadTooLarge"
690
+ /**
691
+ * A predicate is structurally well-formed but contradicts itself —
692
+ * no document can match. Emitted by `validateWire` and
693
+ * `mergePredicateWires`. Triggers:
694
+ * - `{ clauses: [{op:"in", field:"priority", value:[]}] }` (empty `in` set)
695
+ * - an `eq` clause with a value outside the residual interval
696
+ * established by range clauses on the same field
697
+ * - merging `{op:"gt", value:10}` with `{op:"lt", value:5}` on the
698
+ * same field (empty interval)
699
+ * - merging two `in` clauses on the same field with empty intersection
700
+ *
701
+ * Conflicting equality across clauses (`eq:"open"` + `eq:"closed"` on
702
+ * the same field) surfaces as `InvalidConfig` rather than this code —
703
+ * the merger treats it as a caller-side configuration bug, not an
704
+ * algebraic contradiction.
705
+ *
706
+ * The HTTP layer treats this as a 400 (caller error). The distinct
707
+ * code lets downstream code short-circuit empty-by-construction
708
+ * without re-running the validator or parsing messages.
709
+ */
710
+ | "UnsatisfiablePredicate"
711
+ /**
712
+ * A `useQuery` callback awaited a recorder terminal
713
+ * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per
714
+ * render to capture the chain shape; it cannot survive an `await`
715
+ * because the proxy doesn't proxy across microtask boundaries. The
716
+ * recorder's terminal returns a thenable whose `.then` throws this
717
+ * error synchronously, converting what would otherwise be a silent
718
+ * spinner-hang into a render-time error the hook surfaces as
719
+ * `status: "error"`. Companion `baerly/no-await-in-use-query` lint
720
+ * flags the pattern at edit time. For compound reads, use
721
+ * `Promise.all` (parallel) or compose two `useQuery` calls with
722
+ * `useQuery.skip` (dependent).
723
+ */
724
+ | "UseQueryAwaitedRecorder"
725
+ /**
726
+ * A write method (`.insert`/`.update`/`.replace`/`.delete`) was
727
+ * called on the recorder inside a `useQuery` callback. Writes
728
+ * inside reads are a programming error; the recorder rejects them
729
+ * synchronously from the discovery pass, before any I/O fires. Use
730
+ * `useMutation()` instead.
731
+ */
732
+ | "UnexpectedWriteInQuery"
733
+ /**
734
+ * A `useMutation()` callback rejected with a non-`BaerlyError`
735
+ * throwable. The hook wraps the original throw under this code so
736
+ * the `error` slot is always a `BaerlyError`; the original value
737
+ * is preserved on `.cause`.
738
+ */
739
+ | "MutationFailed";
740
+ /**
741
+ * The single error class thrown by Baerly. Discriminate by `code`, not
742
+ * `instanceof`: the code string survives `JSON.stringify` round-trips
743
+ * across Worker / iframe / postMessage realm boundaries, where each
744
+ * realm has its own `BaerlyError` constructor identity. IDB-restored
745
+ * writes can replay across realms, so `instanceof` would spuriously
746
+ * fail on a structurally-identical error from another realm.
747
+ *
748
+ * @example
749
+ * ```ts
750
+ * try {
751
+ * await db.collection("tickets").insert({ title: "hi" });
752
+ * } catch (err) {
753
+ * if (err instanceof BaerlyError && err.code === "Conflict") {
754
+ * // ... CAS lost; retry
755
+ * }
756
+ * throw err;
757
+ * }
758
+ * ```
759
+ */
760
+ declare class BaerlyError extends Error {
761
+ readonly code: BaerlyErrorCode;
762
+ readonly cause?: unknown;
763
+ /**
764
+ * Structured field-path issues, set only when `code === "SchemaError"`.
765
+ * Each entry's `path` is a dotted-key list (e.g. `["assignee", "team"]`
766
+ * or `["items", 3, "qty"]`) that targets the offending field on the
767
+ * input document. `message` is the validator-emitted human string.
768
+ *
769
+ * The HTTP layer's `mapError` renders these into the 400 body via
770
+ * the existing `HttpErrorEnvelope`; older callers that don't know
771
+ * about `issues` see a plain message-only error and stay correct.
772
+ */
773
+ readonly issues?: ReadonlyArray<{
774
+ readonly path: ReadonlyArray<string | number>;
775
+ readonly message: string;
776
+ }>;
777
+ /**
778
+ * Raw HTTP status, set only by the client-side wire decoder when
779
+ * inflating an `HttpErrorEnvelope` into this class. Server-side
780
+ * throws never set it (the HTTP layer's `mapError` derives the
781
+ * outbound status from `code`). Useful for diagnostics — e.g. to
782
+ * distinguish 404-as-"no such row" from 404-as-"route not found".
783
+ * Discriminate by `code` for behavior; reach for `status` only when
784
+ * you genuinely need the wire value.
785
+ */
786
+ readonly status?: number;
787
+ constructor(code: BaerlyErrorCode, message: string, cause?: unknown, issues?: ReadonlyArray<{
788
+ readonly path: ReadonlyArray<string | number>;
789
+ readonly message: string;
790
+ }>, status?: number);
791
+ }
792
+ //#endregion
793
+ //#region packages/protocol/src/storage/memory.d.ts
794
+ /**
795
+ * In-memory `Storage`. The randomized property test runs against
796
+ * this; it must be deterministic — no clocks beyond the caller's,
797
+ * no randomness, no I/O.
798
+ *
799
+ * ETags are a monotonically increasing hex counter formatted in the
800
+ * `"<hex>"` shape S3 returns (the surrounding double-quotes are part
801
+ * of the ETag header value). Keys are stored verbatim.
802
+ */
803
+ declare class MemoryStorage implements Storage {
804
+ #private;
805
+ get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null>;
806
+ put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult>;
807
+ delete(key: string, opts?: {
808
+ signal?: AbortSignal;
809
+ }): Promise<void>;
810
+ list(prefix: string, opts?: {
811
+ startAfter?: string;
812
+ maxKeys?: number;
813
+ signal?: AbortSignal;
814
+ }): AsyncIterable<StorageListEntry>;
815
+ /**
816
+ * Test-only: drop all objects.
817
+ * @internal
818
+ */
819
+ _clear(): void;
820
+ }
821
+ //#endregion
822
+ //#region packages/protocol/src/verifier.d.ts
823
+ /**
824
+ * Result of a successful {@link Verifier} call. Returned when the
825
+ * request carries valid credentials; replaced with `null` on
826
+ * failure.
827
+ */
828
+ interface VerifierResult {
829
+ /**
830
+ * Tenant identifier. Must be non-empty and contain no `/` (the
831
+ * key-segment separator).
832
+ */
833
+ readonly tenantPrefix: string;
834
+ /**
835
+ * Per-Verifier identity payload. Opaque to the protocol kernel;
836
+ * the caller-defined shape is whatever the Verifier factory
837
+ * chooses to return.
838
+ */
839
+ readonly identity: unknown;
840
+ }
841
+ /**
842
+ * Auth seam. Given an inbound {@link Request}, return either a
843
+ * {@link VerifierResult} (authenticated) or `null` (rejected).
844
+ *
845
+ * One function, one responsibility — auth in baerly is not a
846
+ * middleware chain. The HTTP dispatcher invokes the
847
+ * configured `Verifier` exactly once per request, before any
848
+ * `Storage` I/O, and either constructs a tenant-scoped `Db` or
849
+ * returns 401 `BaerlyError{code:"Unauthorized"}`.
850
+ *
851
+ * `Request` is the standard `globalThis.Request` — the same shape
852
+ * used by Cloudflare Workers, Node 24+, Bun, Deno, and browsers.
853
+ * The kernel does **not** depend on `node:http`, `R2Bucket`, or
854
+ * any platform binding. Preset factories that need platform
855
+ * primitives (e.g. CF Access reads the `Cf-Access-Jwt-Assertion`
856
+ * header; SigV4 verifies against a SHA-256 of the body) compose on
857
+ * top.
858
+ *
859
+ * **Workers-types caveat.** `@cloudflare/workers-types` augments the
860
+ * global `Request` with the generic parameters
861
+ * `Request<CfHostMetadata, Cf>`. A Worker `fetch` handler receives
862
+ * `req: Request<CfHostMetadata, Cf>`, but a `Verifier` declared in
863
+ * user code resolves to `Request<unknown, CfProperties<unknown>>` —
864
+ * the same runtime object, narrowed differently by the type system.
865
+ * `baerlyWorker` handles this internally; you only see it if you
866
+ * intercept routes in your own Worker `fetch` before forwarding to
867
+ * `baerlyWorker`. In that case call the verifier with a one-line
868
+ * cast: `await verifier(req as unknown as Request)`. The runtime
869
+ * shape is identical; the cast is purely a generic-narrowing nudge.
870
+ *
871
+ * **Errors.** A `Verifier` SHOULD return `null` for any
872
+ * unauthenticated outcome — missing header, bad signature, expired
873
+ * token, IP outside allowlist. It MAY throw an `BaerlyError` for
874
+ * configuration problems (the IdP's JWKS endpoint is unreachable,
875
+ * the shared-secret env var is missing). Throws propagate to the
876
+ * dispatcher, which maps them to 500 + `code:"Internal"`. The
877
+ * dispatcher distinguishes "auth said no" (null → 401) from "auth
878
+ * is broken" (throw → 500) on purpose: the first is a client
879
+ * problem, the second is an operator problem.
880
+ *
881
+ * **Idempotence.** A `Verifier` MUST be safe to call multiple times
882
+ * for the same `Request`. Preset factories that decode JWTs cache
883
+ * the result on the request via a `WeakMap` if the cost is
884
+ * material.
885
+ *
886
+ * Preset factories — `cloudflareAccess`, `bearerJwt`,
887
+ * `sharedSecret` — live in `@gusto/baerly-storage/auth`
888
+ * (`packages/server/src/auth/presets/`). The kernel owns the type;
889
+ * the server owns the factories.
890
+ *
891
+ * @example
892
+ * ```ts
893
+ * import type { Verifier } from "baerly-storage";
894
+ *
895
+ * // A trivial Verifier that pins every request to one tenant.
896
+ * // Useful for tests and single-tenant deployments instead of the
897
+ * // preset factories.
898
+ * const single: Verifier = async (_req) => ({
899
+ * tenantPrefix: "acme-co",
900
+ * identity: { kind: "static" },
901
+ * });
902
+ *
903
+ * // A Verifier that reads an `X-Tenant` header and rejects when
904
+ * // it's missing. The preset factories produce something like
905
+ * // this on top of a real IdP — never trust an `X-Tenant` header
906
+ * // in production.
907
+ * const headerOnly: Verifier = async (req) => {
908
+ * const tenant = req.headers.get("x-tenant");
909
+ * if (!tenant) return null;
910
+ * return { tenantPrefix: tenant, identity: null };
911
+ * };
912
+ * ```
913
+ */
914
+ type Verifier = (req: Request) => Promise<VerifierResult | null>;
915
+ //#endregion
916
+ //#region packages/protocol/src/log.d.ts
917
+ /**
918
+ * Postgres-logical-replication-shaped log entry. One per mutation.
919
+ *
920
+ * **Shape is fixed at this point and never changes after.** This is the
921
+ * migration contract behind `baerly export --target=postgres` — the
922
+ * keys are public, consumers ack on `lsn`, and any rename / removal is
923
+ * a major-version migration.
924
+ *
925
+ * Field requirement matrix:
926
+ * - Always: `lsn`, `commit_ts`, `op`, `collection`, `schema_version`,
927
+ * `session`, `seq`.
928
+ * - For I/U/D: `doc_id`.
929
+ * - For I/U: `new`, `patch` (equal in today's per-doc-replace model).
930
+ * - Optional: `old` (when `replica_identity === "FULL"`), `key_old`
931
+ * (U/D when `replica_identity !== "PATCH_ONLY"`), `origin`.
932
+ *
933
+ * @see docs/spec/log-entry-shape.md
934
+ */
935
+ interface LogEntry {
936
+ /**
937
+ * Opaque, monotonic, lex-asc cursor. Shape is
938
+ * `<base32-time>_<session>_<seq>` — minted inside
939
+ * `Writer.commit` (see
940
+ * `packages/server/src/writer.ts`) from `timestamp()` +
941
+ * the per-commit `session` + `countKey(seq)`. Consumers ack and
942
+ * resume from this string.
943
+ *
944
+ * When you have a `LogEntry` in hand, prefer the structured
945
+ * `session` / `seq` fields below over parsing this string. The
946
+ * one place that *does* need to crack it open is the
947
+ * `/v1/since` boundary, where a client resumes from an opaque
948
+ * `next_cursor` and no `LogEntry` is in scope — that path uses
949
+ * `lsnParts` (the kernel-blessed parser) rather than ad-hoc
950
+ * `split("_")`.
951
+ */
952
+ lsn: string;
953
+ /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */
954
+ commit_ts: string;
955
+ /**
956
+ * Insert / Update / Delete / Truncate / Message. `M` is the
957
+ * `pg_logical_emit_message` analogue — useful for app-defined
958
+ * markers like deploy boundaries, snapshots, or out-of-band
959
+ * schema announcements consumed via `schema_version`. `T`
960
+ * truncates a whole collection. Today the emitter only produces
961
+ * `I`/`U`/`D`; `T` and `M` are shape-only for forward
962
+ * compatibility.
963
+ */
964
+ op: "I" | "U" | "D" | "T" | "M";
965
+ /**
966
+ * Collection name — the pgoutput RELATION analogue. Today derived
967
+ * from the path segment immediately under the manifest prefix
968
+ * (the part of `ref.key` before the first `/`); falls back to
969
+ * `ref.bucket` for flat keys with no separator. The table API
970
+ * makes collections first-class.
971
+ */
972
+ collection: string;
973
+ /** Required for I/U/D; omitted for T (TRUNCATE) and M (MESSAGE). */
974
+ doc_id?: string;
975
+ /**
976
+ * Monotonic per collection. Schema for the doc body is announced
977
+ * out-of-band via `M` (MESSAGE) entries; this field lets the
978
+ * consumer match a log entry to the schema in effect at write
979
+ * time. Forward-only — renaming or removing the field is a
980
+ * major-version migration; bumping the value is non-breaking.
981
+ * Inlining the schema in every entry was rejected as bloat for a
982
+ * field that changes rarely. Always `0` today; reserved for a
983
+ * future schema-versioning scheme.
984
+ */
985
+ schema_version: number;
986
+ /** Required for I, U. The post-image. */
987
+ new?: DocumentData;
988
+ /**
989
+ * JSON-merge-patch (RFC 7386) form. Required for U; for I equals
990
+ * `new`. In today's per-doc-replace model `new` and `patch` are
991
+ * always equal; that changes when partial-doc merge writes land.
992
+ */
993
+ patch?: DocumentData;
994
+ /**
995
+ * The pre-image. Present iff the collection's `replica_identity`
996
+ * is `FULL`. ~2× log size on update-heavy collections; off by
997
+ * default.
998
+ */
999
+ old?: DocumentData;
1000
+ /**
1001
+ * Pre-image of the primary key. U/D always carry this when
1002
+ * `replica_identity` is not `PATCH_ONLY`. (For Baerly today,
1003
+ * `_id` is the only PK.)
1004
+ */
1005
+ key_old?: {
1006
+ readonly [pk: string]: JSONValue;
1007
+ };
1008
+ /** ORIGIN analogue — the writer session id. */
1009
+ origin?: string;
1010
+ /**
1011
+ * Causal metadata (Baerly-only; no pgoutput analogue). The
1012
+ * session id that built the `lsn`. Surfaces here so consumers
1013
+ * can dedupe / order without parsing the cursor.
1014
+ */
1015
+ session: string;
1016
+ /** Per-session sequence number embedded in the `lsn`. */
1017
+ seq: number;
1018
+ }
1019
+ //#endregion
1020
+ //#region packages/protocol/src/metrics.d.ts
1021
+ /**
1022
+ * `MetricsRecorder` — internal emission contract for the six
1023
+ * load-bearing kernel metrics. Writer / compactor / GC emit through
1024
+ * an instance of this interface; in production the instance is the
1025
+ * per-request `RequestScopedMetricsRecorder` on the active
1026
+ * `ObservabilityContext`, and emissions flow onto the canonical line
1027
+ * via `summarize()`. Tests use a local `InMemoryMetricsRecorder` and
1028
+ * wrap their workload in `runWithContext` to attach it.
1029
+ *
1030
+ * Operators do not wire a custom sink against this interface — the
1031
+ * operator's view of kernel emissions is the canonical line on
1032
+ * stdout (one JSON object per HTTP request).
1033
+ *
1034
+ * **Naming convention** matches the load-bearing metrics:
1035
+ * - `db.write.class_a_ops_per_logical_write` — histogram (p99 alert at 5).
1036
+ * Includes one Class A op per index PUT + index DELETE emitted
1037
+ * in the commit's fence. Idle-reader cost is unchanged.
1038
+ * - `db.r2.put.412_total` — counter (CAS conflict / If-Match-or-None-Match loss)
1039
+ * - `db.r2.put.429_total` — counter (R2 prefix-partition rate-limit)
1040
+ * - `db.write.index_ops_per_logical_write` — histogram.
1041
+ * `K (PUT) + L (DELETE)` per commit. Per-collection label.
1042
+ * - `db.manifest.lag_window_depth` — gauge (alert at >100)
1043
+ * - `db.gc.entries_swept_per_second` — gauge (livelock indicator when <writes/s)
1044
+ * - `db.orphan.candidate_count` — gauge (`gc/pending.json` depth)
1045
+ * - `db.compact.entries_folded` — histogram (entries folded per run)
1046
+ * - `db.gc.swept_total` — counter (labelled by reason)
1047
+ *
1048
+ * Names follow `db.<subsystem>.<metric>`, dot-separated, all-lowercase
1049
+ * snake_case segments. Labels are flat
1050
+ * `Readonly<Record<string, string>>` — no numbers, no nested objects.
1051
+ *
1052
+ * Metric emissions never throw on the hot path; the default
1053
+ * `noopMetricsRecorder` cannot throw.
1054
+ */
1055
+ interface MetricsRecorder {
1056
+ /** Monotonically-incrementing event count. */
1057
+ counter(name: string, value: number, labels?: Readonly<Record<string, string>>): void;
1058
+ /** Point-in-time value. */
1059
+ gauge(name: string, value: number, labels?: Readonly<Record<string, string>>): void;
1060
+ /** Distribution sample. */
1061
+ histogram(name: string, value: number, labels?: Readonly<Record<string, string>>): void;
1062
+ }
1063
+ //#endregion
1064
+ export { StorageListEntry as _, MemoryStorage as a, Collection as c, Query as d, PredicateArg as f, StorageGetResult as g, StorageGetOptions as h, VerifierResult as i, OrderSpec as l, Storage as m, LogEntry as n, BaerlyError as o, CurrentJsonRead as p, Verifier as r, BaerlyErrorCode as s, MetricsRecorder as t, Predicate as u, StoragePutOptions as v, StoragePutResult as y };
1065
+ //# sourceMappingURL=index-BGC-ENnj.d.ts.map