@gusto/baerly-storage 0.6.0 → 0.7.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 (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +9 -14
  53. package/dist/dev-vite.js +11 -10
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,14 +1,29 @@
1
- import { n as CURRENT_JSON_CONTENT_TYPE } from "./constants-CfeMWQWk.js";
2
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
3
- //#region packages/protocol/src/bytes.ts
1
+ import { f as CURRENT_JSON_CONTENT_TYPE } from "./config-DEzInG6M.js";
2
+ import { c as isWriteConflict, s as BaerlyError } from "./baerly.js";
3
+ // ../protocol/src/bytes.ts
4
4
  /**
5
- * UTF-8 JSON byte helpers — names the encode/decode idiom used by
6
- * every content body, log entry, snapshot, and current.json payload.
5
+ * UTF-8 JSON byte helpers — the common JSON payload encoder/decoder for
6
+ * log entries, snapshots, current.json, and other protocol payloads.
7
7
  */
8
- const encodeJsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value));
9
- const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
10
- //#endregion
11
- //#region packages/protocol/src/coordination/current-json.ts
8
+ const utf8Encoder = new TextEncoder();
9
+ const utf8Decoder$1 = new TextDecoder();
10
+ const encodeJsonBytes = (value) => utf8Encoder.encode(JSON.stringify(value));
11
+ const decodeJsonBytes = (bytes) => JSON.parse(utf8Decoder$1.decode(bytes));
12
+ // ../protocol/src/coordination/schema-version.ts
13
+ /**
14
+ * Whether `found` is an integer version above `supported`, i.e. an
15
+ * object a newer release wrote. The one predicate behind every
16
+ * "newer" decision, so a reader's message and its extra hints agree.
17
+ */
18
+ const isNewerSchemaVersion = (found, supported) => typeof found === "number" && Number.isInteger(found) && found > supported;
19
+ /**
20
+ * Message for a durable object whose `schema_version` this build does not
21
+ * read. A larger integer was written by a newer release; anything else is
22
+ * not an object this build wrote. States both versions and an app remedy;
23
+ * never names host settings or suggests deleting data.
24
+ */
25
+ const unsupportedSchemaVersionMessage = (where, found, supported) => isNewerSchemaVersion(found, supported) ? `${where}: schema_version ${found} was written by a newer baerly-storage release; this build supports schema_version ${supported}. Run that release or newer.` : `${where}: unsupported schema_version ${String(found)}; this build supports schema_version ${supported}. This object was not written by this build; restore it from a backup made by this release, or point the app at the right data.`;
26
+ // ../protocol/src/coordination/current-json.ts
12
27
  /**
13
28
  * `current.json` — the per-collection compaction-state control object —
14
29
  * and its embedded, currently dormant {@link WriterFence} epoch token.
@@ -26,24 +41,16 @@ const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
26
41
  * - {@link readCurrentJson} — fetch + parse + validate
27
42
  * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:"*"`)
28
43
  * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)
29
- * - {@link claimWriter} — bump epoch + stamp server-clock claim time
30
- *
31
- * Why the two-round-trip claim protocol: `claimed_at` MUST come from
32
- * `StoragePutResult.serverDate` (the single shared clock across
33
- * instances), not the local clock. `serverDate` is only known *after*
34
- * the CAS PUT lands, so {@link claimWriter} writes the record with
35
- * `claimed_at: ""` first, then overwrites itself with the correct
36
- * `serverDate.toISOString()` in a second CAS. The epoch bump is
37
- * already durable from the first put either way; a peer landing
38
- * between the two writes loses cleanly with `Conflict`.
44
+ * - {@link assertCurrentJsonTransition} — shared before/after admission
39
45
  *
40
46
  * Why CAS errors are wrapped: every in-tree {@link Storage} impl
41
- * surfaces a lost CAS as `BaerlyError{code:"Conflict"}`. Downstream
47
+ * surfaces a lost CAS as `BaerlyError{code:"WriteConflict"}`. Downstream
42
48
  * callers — the Writer, the compactor, the sweeper —
43
49
  * discriminate by `code` to decide whether to retry.
44
50
  * We re-wrap here only to add the `current.json at <key>` location
45
51
  * context to the message; the `code` is unchanged.
46
52
  */
53
+ const utf8Decoder = new TextDecoder();
47
54
  /**
48
55
  * Read + parse `current.json` at `key`. Returns `null` on not-found.
49
56
  *
@@ -54,12 +61,12 @@ const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
54
61
  async function readCurrentJson(storage, key, opts) {
55
62
  const got = await storage.get(key, opts);
56
63
  if (got === null) return null;
57
- const text = new TextDecoder().decode(got.body);
64
+ const text = utf8Decoder.decode(got.body);
58
65
  let parsed;
59
66
  try {
60
67
  parsed = JSON.parse(text);
61
68
  } catch (error) {
62
- throw new BaerlyError("InvalidResponse", `current.json at ${key}: body is not valid JSON`, error);
69
+ throw new BaerlyError("InvalidResponse", `current.json at ${key}: body is not valid JSON`, { cause: error });
63
70
  }
64
71
  return {
65
72
  json: assertCurrentJson(parsed, key),
@@ -67,11 +74,34 @@ async function readCurrentJson(storage, key, opts) {
67
74
  };
68
75
  }
69
76
  /**
77
+ * Mint a fresh {@link CurrentJson.generation} nonce.
78
+ *
79
+ * Twelve lowercase hex characters (≈2.8 × 10¹⁴ values) — sized so the
80
+ * birthday bound is unreachable across the truncates a bucket sees in
81
+ * its lifetime, while costing only twelve bytes on every `/v1/since`
82
+ * response. A collision would let a stale cursor resume into a
83
+ * truncated generation, which is the exact failure this field exists to
84
+ * prevent, so the margin is deliberate.
85
+ *
86
+ * `crypto.randomUUID` is universally available (Node 19+, Workerd, Bun,
87
+ * browsers) — the same source `uuid()` in `../types.ts` uses.
88
+ *
89
+ * Call this only where a collection is REPLACED, never where one is
90
+ * advanced; see {@link CurrentJson.generation} for the writer split.
91
+ */
92
+ const mintGeneration = () => crypto.randomUUID().replaceAll("-", "").slice(0, 12);
93
+ /**
94
+ * The charset {@link mintGeneration} emits and `/v1/since` accepts in
95
+ * the generation half of a cursor. Pinned so the manifest validator
96
+ * and the wire validator cannot drift.
97
+ */
98
+ const GENERATION_RE = /^[0-9a-f]+$/;
99
+ /**
70
100
  * Create `current.json` if-and-only-if it does not exist (S3
71
101
  * `If-None-Match: "*"`). Use this once per collection at provisioning
72
102
  * time; subsequent updates go through {@link casUpdateCurrentJson}.
73
103
  *
74
- * @throws BaerlyError{code:"Conflict"} — the key already exists.
104
+ * @throws BaerlyError{code:"WriteConflict"} — the key already exists.
75
105
  * Caller decides whether to read + reconcile or surface.
76
106
  * @throws BaerlyError{code:"InvalidResponse"} — `initial` fails the
77
107
  * runtime shape guard.
@@ -96,6 +126,32 @@ async function createCurrentJson(storage, key, initial, opts) {
96
126
  };
97
127
  }
98
128
  /**
129
+ * Admission control for a `current.json` state transition.
130
+ *
131
+ * Distinct from {@link assertCurrentJson}, which validates one state in
132
+ * isolation and therefore structurally cannot express a rule about a
133
+ * pair of states. Every invariant that compares before/after belongs
134
+ * here, and every writer that bypasses {@link casUpdateCurrentJson}
135
+ * MUST call it directly — "monotone by construction" is an argument
136
+ * that has to be re-made every time the writer is reimplemented, and
137
+ * it does not survive a chunk-aware compactor or a read-banking path.
138
+ *
139
+ * `Internal`, not `InvalidResponse`: the fault is a local caller's
140
+ * mutator, not a malformed storage response, and `InvalidResponse` maps
141
+ * to HTTP 502 ("storage upstream failed"), which would misattribute a
142
+ * programmer error to the bucket.
143
+ *
144
+ * @throws BaerlyError{code:"Internal"} on any violated transition rule.
145
+ * @see docs/spec/sync-protocol.md invariant 12
146
+ */
147
+ const assertCurrentJsonTransition = (before, after, key) => {
148
+ if (after.log_seq_start < before.log_seq_start) throw new BaerlyError("Internal", `current.json at ${key}: log_seq_start must not decrease (${String(before.log_seq_start)} → ${String(after.log_seq_start)})`);
149
+ const beforeDeleteFloor = logDeleteFloorOf(before);
150
+ const afterDeleteFloor = logDeleteFloorOf(after);
151
+ if (afterDeleteFloor < beforeDeleteFloor) throw new BaerlyError("Internal", `current.json at ${key}: log_delete_floor must not decrease (${String(beforeDeleteFloor)} → ${String(afterDeleteFloor)})`);
152
+ if (afterDeleteFloor > after.log_seq_start) throw new BaerlyError("Internal", `current.json at ${key}: log_delete_floor must not exceed log_seq_start (${String(afterDeleteFloor)} > ${String(after.log_seq_start)})`);
153
+ };
154
+ /**
99
155
  * Read-modify-write `current.json` under CAS. The `mutator` receives
100
156
  * a deep clone of the current parsed JSON (mutate freely) and returns
101
157
  * the new state. The new state is written with `If-Match:
@@ -105,18 +161,25 @@ async function createCurrentJson(storage, key, initial, opts) {
105
161
  * multiple times if the caller wraps this in a retry loop, so it
106
162
  * must not have side effects.
107
163
  *
108
- * @throws BaerlyError{code:"Conflict"} — another writer landed a write
164
+ * @throws BaerlyError{code:"WriteConflict"} — another writer landed a write
109
165
  * between this function's read and write. Caller decides
110
166
  * whether to retry (read + remutate + rewrite).
111
167
  * @throws BaerlyError{code:"InvalidResponse"} — `key` does not exist
112
168
  * (use {@link createCurrentJson} instead) or body doesn't
113
169
  * parse / fails the shape guard.
170
+ * @throws BaerlyError{code:"Internal"} — the mutator decreased
171
+ * `log_seq_start`, decreased `log_delete_floor`, or set
172
+ * `log_delete_floor > log_seq_start`. Equality is permitted.
173
+ * The compactor calls the same transition validator before its
174
+ * direct `If-Match` PUT; `baerly admin restore --force` is the
175
+ * deliberate truncate exemption.
114
176
  */
115
177
  async function casUpdateCurrentJson(storage, key, mutator, opts) {
116
178
  const existing = await readCurrentJson(storage, key, opts);
117
179
  if (existing === null) throw new BaerlyError("InvalidResponse", `current.json at ${key} does not exist; use createCurrentJson first`);
118
180
  const next = mutator(structuredClone(existing.json));
119
181
  assertCurrentJson(next, key);
182
+ assertCurrentJsonTransition(existing.json, next, key);
120
183
  const body = encodeJson(next);
121
184
  const putOpts = {
122
185
  ifMatch: existing.etag,
@@ -143,6 +206,22 @@ async function casUpdateCurrentJson(storage, key, mutator, opts) {
143
206
  * invariants.
144
207
  */
145
208
  const logSeqStartOf = (c) => c.log_seq_start;
209
+ /**
210
+ * Read `log_delete_floor`, defaulting an absent field to `0`. Absent
211
+ * means "no deleted prefix is certified", which is exactly what a
212
+ * pre-field bucket records even if older GC deleted sparse log objects.
213
+ */
214
+ const logDeleteFloorOf = (c) => c.log_delete_floor ?? 0;
215
+ /**
216
+ * The certified delete floor: `log_delete_floor` clamped down to
217
+ * `log_seq_start`. Every consumer of "is `seq` reclaimed" must go through
218
+ * this clamp rather than trusting the raw stored field — invariant 12
219
+ * (`docs/spec/sync-protocol.md`) allows an out-of-bound stored floor to be
220
+ * readable off disk (the single-state read guard deliberately doesn't
221
+ * reject it, so `admin restore` stays repairable), and an unclamped floor
222
+ * would report a still-live entry as already deleted.
223
+ */
224
+ const certifiedDeleteFloor = (c) => Math.min(logDeleteFloorOf(c), logSeqStartOf(c));
146
225
  const encodeJson = (json) => encodeJsonBytes(json);
147
226
  /**
148
227
  * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws
@@ -153,8 +232,11 @@ const encodeJson = (json) => encodeJsonBytes(json);
153
232
  const assertCurrentJson = (parsed, key) => {
154
233
  if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: parsed body is not an object`);
155
234
  const r = parsed;
156
- if (r["schema_version"] === 1 || r["schema_version"] === 2) throw new BaerlyError("InvalidResponse", `current.json at ${key} uses schema v${String(r["schema_version"])} from a pre-0.3.0 internal build; this build requires schema v3. Dump/restore with the old build, or re-provision scratch/local buckets.`);
157
- if (r["schema_version"] !== 3) throw new BaerlyError("InvalidResponse", `current.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; this build requires 3. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \`rm -rf .baerly-data\`) or recreate the R2/S3 bucket, then retry.`);
235
+ if (r["schema_version"] === 1 || r["schema_version"] === 2) throw new BaerlyError("InvalidResponse", `current.json at ${key} uses schema v${String(r["schema_version"])} from a release before 0.3.0; this release requires schema v3. Dump/restore with that release, or re-provision local scratch data.`);
236
+ if (r["schema_version"] !== 3) {
237
+ const base = unsupportedSchemaVersionMessage(`current.json at ${key}`, r["schema_version"], 3);
238
+ throw new BaerlyError("InvalidResponse", isNewerSchemaVersion(r["schema_version"], 3) ? base : `${base} For local dev only, stale data from another build can be cleared by deleting the local data directory (e.g. \`rm -rf .baerly-data\`).`);
239
+ }
158
240
  if (!(typeof r["snapshot"] === "string" || r["snapshot"] === null)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot must be string|null`);
159
241
  if (typeof r["tail_hint"] !== "number" || !Number.isInteger(r["tail_hint"]) || r["tail_hint"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: tail_hint must be a non-negative integer`);
160
242
  if (typeof r["log_seq_start"] !== "number" || !Number.isInteger(r["log_seq_start"]) || r["log_seq_start"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start must be a non-negative integer`);
@@ -169,22 +251,23 @@ const assertCurrentJson = (parsed, key) => {
169
251
  if (typeof r["snapshot_bytes"] !== "number" || !Number.isInteger(r["snapshot_bytes"]) || r["snapshot_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_bytes must be a non-negative integer`);
170
252
  if (typeof r["snapshot_rows"] !== "number" || !Number.isInteger(r["snapshot_rows"]) || r["snapshot_rows"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_rows must be a non-negative integer`);
171
253
  if (r["last_warned_seq"] !== void 0 && (typeof r["last_warned_seq"] !== "number" || !Number.isInteger(r["last_warned_seq"]) || r["last_warned_seq"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: last_warned_seq must be a non-negative integer if present`);
254
+ if (r["log_delete_floor"] !== void 0 && (typeof r["log_delete_floor"] !== "number" || !Number.isInteger(r["log_delete_floor"]) || r["log_delete_floor"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_delete_floor must be a non-negative integer if present`);
172
255
  if (r["mean_entry_bytes"] !== void 0 && (typeof r["mean_entry_bytes"] !== "number" || !Number.isInteger(r["mean_entry_bytes"]) || r["mean_entry_bytes"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`);
256
+ if (r["generation"] !== void 0 && (typeof r["generation"] !== "string" || !GENERATION_RE.test(r["generation"]))) throw new BaerlyError("InvalidResponse", `current.json at ${key}: generation must be a non-empty lowercase-hex string if present`);
173
257
  return parsed;
174
258
  };
175
259
  /**
176
260
  * Wrap a storage-level error with `current.json at <key>` location
177
- * context. `Conflict` (the storage layer's CAS-lost signal) is
261
+ * context. `WriteConflict` (the storage layer's CAS-lost signal) is
178
262
  * re-thrown with an annotated message; other `BaerlyError`s pass
179
263
  * through; non-`BaerlyError` falls through as `InvalidResponse` (in
180
264
  * practice unreachable — every in-tree `Storage` impl wraps).
181
265
  */
182
266
  const translateCasError = (e, key) => {
183
- if (e instanceof BaerlyError && e.code === "Conflict") return new BaerlyError("Conflict", `current.json CAS lost at ${key}: ${e.message}`, e);
267
+ if (isWriteConflict(e)) return new BaerlyError("WriteConflict", `current.json CAS lost at ${key}: ${e.message}`, { cause: e });
184
268
  if (e instanceof BaerlyError) return e;
185
- return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, e);
269
+ return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, { cause: e });
186
270
  };
187
- //#endregion
188
- export { decodeJsonBytes as a, readCurrentJson as i, createCurrentJson as n, encodeJsonBytes as o, logSeqStartOf as r, casUpdateCurrentJson as t };
271
+ export { logDeleteFloorOf as a, readCurrentJson as c, encodeJsonBytes as d, createCurrentJson as i, unsupportedSchemaVersionMessage as l, casUpdateCurrentJson as n, logSeqStartOf as o, certifiedDeleteFloor as r, mintGeneration as s, assertCurrentJsonTransition as t, decodeJsonBytes as u };
189
272
 
190
- //# sourceMappingURL=current-json-C6nhPOm1.js.map
273
+ //# sourceMappingURL=current-json-CC6lE4Aj.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"current-json-CC6lE4Aj.js","names":["utf8Decoder"],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/coordination/schema-version.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — the common JSON payload encoder/decoder for\n * log entries, snapshots, current.json, and other protocol payloads.\n */\n\nconst utf8Encoder = new TextEncoder();\n// Default options only: no `fatal`, no `ignoreBOM`, never `stream: true`, so the\n// decoder holds no state between calls and strips a leading BOM as before.\nconst utf8Decoder = new TextDecoder();\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n utf8Encoder.encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(utf8Decoder.decode(bytes)) as T;\n","/**\n * Whether `found` is an integer version above `supported`, i.e. an\n * object a newer release wrote. The one predicate behind every\n * \"newer\" decision, so a reader's message and its extra hints agree.\n */\nexport const isNewerSchemaVersion = (found: unknown, supported: number): found is number =>\n typeof found === \"number\" && Number.isInteger(found) && found > supported;\n\n/**\n * Message for a durable object whose `schema_version` this build does not\n * read. A larger integer was written by a newer release; anything else is\n * not an object this build wrote. States both versions and an app remedy;\n * never names host settings or suggests deleting data.\n */\nexport const unsupportedSchemaVersionMessage = (\n where: string,\n found: unknown,\n supported: number,\n): string =>\n isNewerSchemaVersion(found, supported)\n ? `${where}: schema_version ${found} was written by a newer baerly-storage release; this build supports schema_version ${supported}. Run that release or newer.`\n : `${where}: unsupported schema_version ${String(found)}; this build supports schema_version ${supported}. This object was not written by this build; restore it from a backup made by this release, or point the app at the right data.`;\n","/**\n * `current.json` — the per-collection compaction-state control object —\n * and its embedded, currently dormant {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link assertCurrentJsonTransition} — shared before/after admission\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"WriteConflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError, isWriteConflict } from \"../errors.ts\";\nimport { isNewerSchemaVersion, unsupportedSchemaVersionMessage } from \"./schema-version.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n// Default options only (no `stream`), so no state carries between calls.\nconst utf8Decoder = new TextDecoder();\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps snapshot\n * generations by CAS-writing this object; the Writer reads it on every\n * commit to find the snapshot pointer and a non-authoritative\n * tail-probe floor. The numbered log create mints the next integer\n * `seq`; no commit-path code CAS-advances `current.json`.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `3`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 3;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Non-authoritative monotone lower bound on the committed log tail.\n * The authoritative tail is discovered by forward-probe (log-tail.ts);\n * never trust this as the head. Durable advancement is owned by\n * compaction folds, write-tick tail refreshes, and explicit\n * operator/import paths; ordinary writer commits do not refresh it.\n */\n tail_hint: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, tail_hint)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants:\n * - `0 <= log_seq_start <= tail_hint`\n * - `log_seq_start` advances monotonically (never decreases).\n * {@link assertCurrentJsonTransition} rejects a writer that lowers\n * it; `baerly admin restore\n * --force` is the deliberate truncate exemption.\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`) — except after a `--force`\n * truncate, which resets `snapshot` to `null` while reseeding\n * the floor above any surviving old-generation log object.\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /**\n * Row count of the snapshot (= compactor `base.size`, free). With\n * `tail_hint - log_seq_start` (trusted tail entries) this gives the\n * fold's entry count for the ENTRY ceiling `E`. Seeded 0.\n */\n snapshot_rows: number;\n\n /**\n * Optional compactor-stamped mean folded-entry byte size. Maintenance\n * derives live-tail bytes as `entry_count × mean_entry_bytes` without\n * an exact stored counter; absent until first fold.\n */\n mean_entry_bytes?: number;\n\n /**\n * Baseline for rate-limiting the graduation defer-warn off SHARED\n * durable state, not per-isolate memory. The warn fires when the\n * observed/probed tail minus `last_warned_seq` reaches\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes\n * `last_warned_seq` to the observed/probed tail. Absent → the\n * collection has never warned, so its first deferral warns.\n */\n last_warned_seq?: number;\n\n /**\n * The exclusive upper bound of the contiguous log prefix certified\n * deleted. Every `log/<seq>.json` with `seq < log_delete_floor` is\n * gone from the bucket. Distinct from {@link log_seq_start}, which is the\n * lowest sequence a READER may need: the gap between them is the\n * deliberately-retained window (`LOG_RETENTION_SEQ_WINDOW`), a rate\n * limit on retirement that keeps folded entries readable for a windowed\n * commit below the floor, not the writer-retry window that\n * `GC_GRACE_PERIOD_MILLIS` covers.\n *\n * A FLOOR, not a rotation cursor. The deletable set is a contiguous\n * range over integer `seq` order that only ever grows at one end, so\n * this never wraps and never re-scans — which is why retiring stale\n * logs needs no LIST and no `gc/pending.json` entry. The window is\n * **not** a paused-writer fence — it bounds no wall-clock and no\n * commit count. The commit-path check closes that schedule instead.\n *\n * Optional because it postdates `schema_version: 3`. Absent is a\n * well-defined state meaning \"no deleted prefix is certified\" and\n * decodes to `0` via {@link logDeleteFloorOf}; a bucket written by an\n * earlier build simply starts its first retention pass from the bottom\n * of the keyspace.\n *\n * Invariants:\n * - advances monotonically (never decreases)\n * - `0 <= log_delete_floor <= log_seq_start`\n *\n * Both are transition-scoped and enforced in\n * {@link assertCurrentJsonTransition}. The single-state guard checks\n * shape only, so a retirement pass must clamp against\n * {@link log_seq_start} rather than trust this value.\n */\n log_delete_floor?: number;\n\n /**\n * Opaque non-empty generation nonce, re-minted by every writer that\n * *replaces* this collection rather than advancing it — the two\n * `baerly admin restore` seeds and the writer/dev auto-provision\n * paths. Steady-state writers (the compactor's fold CAS,\n * every {@link casUpdateCurrentJson} mutator)\n * carry it through untouched, so it changes only on truncate or\n * re-provision. Mint with {@link mintGeneration}.\n *\n * `/v1/since` pairs it with each entry's `lsn` to build the cursor it\n * hands clients, then rejects a resume whose generation no longer\n * matches. Without it, a `restore --force` that reseeds\n * `log_seq_start` BELOW the old floor (the deliberate floor exemption\n * — invariant 12 in `docs/spec/sync-protocol.md`) lets a pre-restore\n * cursor clear the `cursorSeq < log_seq_start` gate and silently skip\n * every restored row beneath it.\n *\n * Deliberately NOT `writer_fence.epoch`: the fresh-target restore\n * branch seeds `epoch: 0`, so a truncate-to-empty is indistinguishable\n * from a genuine epoch-0 collection. A counter that resets cannot\n * discriminate generations; a nonce can.\n *\n * Optional because it postdates `schema_version: 3` and buckets\n * written by earlier builds do not carry it. Absent is a well-defined\n * state, not a degraded one — it decodes to `NO_GENERATION` on both\n * sides of the comparison (see `../cursor.ts`), so a collection that\n * was never truncated keeps resuming normally.\n */\n generation?: string;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is an informational claim-time string that\n * writers seed as `\"\"` and carry through unchanged; `lease_until` is reserved for manual rotation and is not\n * consumed by the current kernel. Log entries are not stamped with this\n * epoch; the fence is dormant authority metadata, not a reader replay\n * filter.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. In the earlier two-write commit design, every commit checked\n * the epoch before continuing under `current.json` authority. Under\n * single-write commit no production path reads or writes the fence.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. No production path bumps or\n * verifies it; it is seeded at provisioning/restore and carried\n * through every transition.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * Informational claim time as an ISO-8601 string. No production\n * path stamps it: writers seed `\"\"` and carry it through. The empty\n * string means \"claim time unknown\" — readers MUST treat it as such\n * rather than parsing it, and MUST NOT derive safety from it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = utf8Decoder.decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: body is not valid JSON`, {\n cause: error,\n });\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Mint a fresh {@link CurrentJson.generation} nonce.\n *\n * Twelve lowercase hex characters (≈2.8 × 10¹⁴ values) — sized so the\n * birthday bound is unreachable across the truncates a bucket sees in\n * its lifetime, while costing only twelve bytes on every `/v1/since`\n * response. A collision would let a stale cursor resume into a\n * truncated generation, which is the exact failure this field exists to\n * prevent, so the margin is deliberate.\n *\n * `crypto.randomUUID` is universally available (Node 19+, Workerd, Bun,\n * browsers) — the same source `uuid()` in `../types.ts` uses.\n *\n * Call this only where a collection is REPLACED, never where one is\n * advanced; see {@link CurrentJson.generation} for the writer split.\n */\nexport const mintGeneration = (): string => crypto.randomUUID().replaceAll(\"-\", \"\").slice(0, 12);\n\n/**\n * The charset {@link mintGeneration} emits and `/v1/since` accepts in\n * the generation half of a cursor. Pinned so the manifest validator\n * and the wire validator cannot drift.\n */\nconst GENERATION_RE = /^[0-9a-f]+$/;\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"WriteConflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Admission control for a `current.json` state transition.\n *\n * Distinct from {@link assertCurrentJson}, which validates one state in\n * isolation and therefore structurally cannot express a rule about a\n * pair of states. Every invariant that compares before/after belongs\n * here, and every writer that bypasses {@link casUpdateCurrentJson}\n * MUST call it directly — \"monotone by construction\" is an argument\n * that has to be re-made every time the writer is reimplemented, and\n * it does not survive a chunk-aware compactor or a read-banking path.\n *\n * `Internal`, not `InvalidResponse`: the fault is a local caller's\n * mutator, not a malformed storage response, and `InvalidResponse` maps\n * to HTTP 502 (\"storage upstream failed\"), which would misattribute a\n * programmer error to the bucket.\n *\n * @throws BaerlyError{code:\"Internal\"} on any violated transition rule.\n * @see docs/spec/sync-protocol.md invariant 12\n */\nexport const assertCurrentJsonTransition = (\n before: CurrentJson,\n after: CurrentJson,\n key: string,\n): void => {\n // A regressed floor makes a stale pre-fold reader cursor pass the\n // `cursorSeq < log_seq_start` re-bootstrap check (http/since.ts)\n // instead of failing it. Equality is permitted: the `tail_hint`\n // refresh and the `last_warned_seq` stamp in maintenance.ts both hold\n // the floor fixed.\n if (after.log_seq_start < before.log_seq_start) {\n throw new BaerlyError(\n \"Internal\",\n `current.json at ${key}: log_seq_start must not decrease (${String(before.log_seq_start)} → ${String(after.log_seq_start)})`,\n );\n }\n // Same argument one floor down, and read through the accessor on BOTH\n // sides: absent means \"no deleted prefix is certified\", so a pre-field\n // manifest compares as 0 rather than as `undefined`.\n const beforeDeleteFloor = logDeleteFloorOf(before);\n const afterDeleteFloor = logDeleteFloorOf(after);\n if (afterDeleteFloor < beforeDeleteFloor) {\n throw new BaerlyError(\n \"Internal\",\n `current.json at ${key}: log_delete_floor must not decrease (${String(beforeDeleteFloor)} → ${String(afterDeleteFloor)})`,\n );\n }\n // Deleting at or above the live floor would remove an object a reader\n // walking `[log_seq_start, tail_hint)` still needs. This is the hard\n // safety line for both maintenance triggers.\n if (afterDeleteFloor > after.log_seq_start) {\n throw new BaerlyError(\n \"Internal\",\n `current.json at ${key}: log_delete_floor must not exceed log_seq_start (${String(afterDeleteFloor)} > ${String(after.log_seq_start)})`,\n );\n }\n};\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"WriteConflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n * @throws BaerlyError{code:\"Internal\"} — the mutator decreased\n * `log_seq_start`, decreased `log_delete_floor`, or set\n * `log_delete_floor > log_seq_start`. Equality is permitted.\n * The compactor calls the same transition validator before its\n * direct `If-Match` PUT; `baerly admin restore --force` is the\n * deliberate truncate exemption.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n assertCurrentJsonTransition(existing.json, next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, tail_hint)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n/**\n * Read `log_delete_floor`, defaulting an absent field to `0`. Absent\n * means \"no deleted prefix is certified\", which is exactly what a\n * pre-field bucket records even if older GC deleted sparse log objects.\n */\nexport const logDeleteFloorOf = (c: CurrentJson): number => c.log_delete_floor ?? 0;\n\n/**\n * The certified delete floor: `log_delete_floor` clamped down to\n * `log_seq_start`. Every consumer of \"is `seq` reclaimed\" must go through\n * this clamp rather than trusting the raw stored field — invariant 12\n * (`docs/spec/sync-protocol.md`) allows an out-of-bound stored floor to be\n * readable off disk (the single-state read guard deliberately doesn't\n * reject it, so `admin restore` stays repairable), and an unclamped floor\n * would report a still-live entry as already deleted.\n */\nexport const certifiedDeleteFloor = (c: CurrentJson): number =>\n Math.min(logDeleteFloorOf(c), logSeqStartOf(c));\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-003).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1 || r[\"schema_version\"] === 2) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} uses schema v${String(r[\"schema_version\"])} from a release before 0.3.0; this release requires schema v${CURRENT_JSON_SCHEMA_VERSION}. Dump/restore with that release, or re-provision local scratch data.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n const base = unsupportedSchemaVersionMessage(\n `current.json at ${key}`,\n r[\"schema_version\"],\n CURRENT_JSON_SCHEMA_VERSION,\n );\n throw new BaerlyError(\n \"InvalidResponse\",\n isNewerSchemaVersion(r[\"schema_version\"], CURRENT_JSON_SCHEMA_VERSION)\n ? base\n : `${base} For local dev only, stale data from another build can be cleared by deleting the local data directory (e.g. \\`rm -rf .baerly-data\\`).`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"tail_hint\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"tail_hint\"] < 0` → false is subsumed by the downstream `log_seq_start > tail_hint` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_tail_hint always fires); (3) StringLiteral \"tail_hint\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (\n typeof r[\"tail_hint\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_hint\"]) ||\n r[\"tail_hint\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_hint must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"tail_hint\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > tail_hint ${String(r[\"tail_hint\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n // Shape only. `log_delete_floor <= log_seq_start` is deliberately NOT\n // checked here: `readCurrentJson` sits on `admin restore`'s own path\n // (it reads `head` before it can reseed), so rejecting a single state\n // on that bound would turn an out-of-bound floor into a bucket with no\n // in-product repair path. The bound is transition-scoped in\n // {@link assertCurrentJsonTransition}, and consumers of the field\n // clamp against `log_seq_start` rather than trust it.\n if (\n r[\"log_delete_floor\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\n (typeof r[\"log_delete_floor\"] !== \"number\" ||\n !Number.isInteger(r[\"log_delete_floor\"]) ||\n r[\"log_delete_floor\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_delete_floor must be a non-negative integer if present`,\n );\n }\n if (\n r[\"mean_entry_bytes\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\n (typeof r[\"mean_entry_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"mean_entry_bytes\"]) ||\n r[\"mean_entry_bytes\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`,\n );\n }\n if (\n r[\"generation\"] !== undefined &&\n (typeof r[\"generation\"] !== \"string\" || !GENERATION_RE.test(r[\"generation\"]))\n ) {\n // Charset, not just type. `\"\"` would format a cursor as `.<lsn>`,\n // which `parseCursor` reads as generation `\"\"` rather than as the\n // `NO_GENERATION` sentinel. Anything outside `[0-9a-f]` (a `.`\n // worst of all) would mint a cursor `/v1/since` then refuses on\n // resume — the server rejecting a token it issued, which a client\n // reads as a permanently dead cursor. Matching the wire charset\n // means a manifest that reads clean here always round-trips.\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: generation must be a non-empty lowercase-hex string if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `WriteConflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (isWriteConflict(e)) {\n return new BaerlyError(\"WriteConflict\", `current.json CAS lost at ${key}: ${e.message}`, {\n cause: e,\n });\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, {\n cause: e,\n });\n};\n"],"mappings":";;;;;;;AAKA,MAAM,cAAc,IAAI,YAAY;AAGpC,MAAMA,gBAAc,IAAI,YAAY;AAEpC,MAAa,mBAAmB,UAC9B,YAAY,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ACzB;CAEF,IACE,EAAE,wBAAwB,KAAA,MAEzB,OAAO,EAAE,wBAAwB,YAChC,CAAC,OAAO,UAAU,EAAE,mBAAmB,KACvC,EAAE,sBAAsB,IAE1B,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,6DACzB;CAEF,IACE,EAAE,kBAAkB,KAAA,MACnB,OAAO,EAAE,kBAAkB,YAAY,CAAC,cAAc,KAAK,EAAE,aAAa,IAS3E,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,iEACzB;CAEF,OAAO;AACT;;;;;;;;AASA,MAAM,qBAAqB,GAAY,QAA6B;CAClE,IAAI,gBAAgB,CAAC,GACnB,OAAO,IAAI,YAAY,iBAAiB,4BAA4B,IAAI,IAAI,EAAE,WAAW,EACvF,OAAO,EACT,CAAC;CAEH,IAAI,aAAa,aACf,OAAO;CAET,OAAO,IAAI,YAAY,mBAAmB,yBAAyB,IAAI,WAAW,OAAO,CAAC,KAAK,EAC7F,OAAO,EACT,CAAC;AACH"}
@@ -0,0 +1,130 @@
1
+ import { a as CollectionNames, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig } from "./app-config-C6qW7m8S.js";
2
+ import { t as Collection } from "./collection-api-DbyhLAY8.js";
3
+ import { t as Storage } from "./types-suVbsEWS.js";
4
+ /**
5
+ * Runtime entry point. One `Db` per `(app, tenant)` request.
6
+ *
7
+ * Construct via {@link Db.create} — the constructor is private so
8
+ * callers don't accidentally bypass validation.
9
+ *
10
+ * **Collection provisioning.** `Db` provisions collections implicitly on
11
+ * the first commit — the writer auto-creates the per-collection
12
+ * `current.json` manifest with a zero-state seed, costing one extra
13
+ * Class A PUT on the very first write per collection and zero
14
+ * thereafter. There is no `ensureCollection` method on this class. For
15
+ * eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures
16
+ * that want the manifest in place before the first request), use
17
+ * {@link "@gusto/baerly-storage/dev".ensureTable}. The two seeds are
18
+ * equivalent, not byte-identical: each mints its own `generation`
19
+ * nonce. Harmless — `If-None-Match` means exactly one lands.
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * import { Db } from "@gusto/baerly-storage";
24
+ * import { MemoryStorage } from "@gusto/baerly-storage";
25
+ *
26
+ * const db = Db.create({
27
+ * storage: new MemoryStorage(),
28
+ * app: "tickets",
29
+ * tenant: "acme-co",
30
+ * });
31
+ *
32
+ * await db.collection("tickets").insert({ title: "first ticket", status: "open" });
33
+ * const open = await db.collection("tickets").where({ status: "open" }).all();
34
+ * ```
35
+ *
36
+ * @remarks
37
+ * **Anti-patterns** (TS compile errors, not runtime rejections):
38
+ * - `db.collection(name).insertOne({...})` / `.insert({...})` —
39
+ * the Mongo verb. Use `.insert(row)` (returns `{ _id }`).
40
+ * - `db.collection(name).findOne({...})` / `.find({...})` —
41
+ * the Mongo read verbs. Use `.get(id)` for by-id reads and
42
+ * `.where({...}).first()` / `.all()` for predicate reads.
43
+ * - `db.collection(name).aggregate([...])` — no pipeline stage
44
+ * model. Compose via `.where().order().limit()` modifiers.
45
+ * - Raw SQL strings of any shape. The kernel has no SQL parser.
46
+ */
47
+ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
48
+ #private;
49
+ readonly app: string;
50
+ readonly tenant: string;
51
+ private constructor();
52
+ /**
53
+ * Build a tenant-scoped `Db`. Throws
54
+ * `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
55
+ * is empty, contains `/`, is `"."` or `".."`, contains control
56
+ * characters, starts with the reserved `"_"` prefix, exceeds
57
+ * 256 bytes, contains an unpaired UTF-16 surrogate
58
+ * (`!name.isWellFormed()`), or is not in Unicode Normalization Form C
59
+ * (`name !== name.normalize("NFC")`). Names are never normalized for
60
+ * you: pass `name.normalize("NFC")`.
61
+ *
62
+ * @throws BaerlyError code="InvalidConfig" when `app`, `tenant`, or a
63
+ * `config.collections` key is empty, contains `/`, is `"."` or
64
+ * `".."`, contains control characters, starts with the reserved
65
+ * `"_"` prefix, exceeds 256 bytes, contains an unpaired surrogate,
66
+ * or is not NFC.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * const db = Db.create({ storage, app: "tickets", tenant: "acme" });
71
+ * await db.collection("tickets").insert({ title: "hi" });
72
+ * ```
73
+ */
74
+ static create<TConfig extends BaerlyConfig = UnboundConfig>(config: {
75
+ storage: Storage;
76
+ app: string;
77
+ tenant: string;
78
+ /**
79
+ * Optional. Pass the value returned by {@link defineConfig} from
80
+ * your `baerly.config.ts`. Two things happen:
81
+ *
82
+ * 1. **Types.** `db.collection(name)` narrows `name` to declared
83
+ * collection names and infers the row type from
84
+ * `collections[name].schema` via {@link RowOf}.
85
+ * 2. **Runtime.** Schemas are wired from `config.collections`
86
+ * via {@link collectionsToMaps} — no second hand-off step.
87
+ * Declared `indexes` are validated here (a malformed one throws
88
+ * `SchemaError` or `InvalidConfig`) but do not speed up reads
89
+ * or change their results or costs.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * import config from "../baerly.config.ts";
94
+ * const db = Db.create({
95
+ * storage: new MemoryStorage(),
96
+ * app: "helpdesk",
97
+ * tenant: "test",
98
+ * config,
99
+ * });
100
+ * // db.collection("tickets") is typed AND validates writes against
101
+ * // the schema declared in baerly.config.ts.
102
+ * ```
103
+ */
104
+ config?: TConfig;
105
+ }): Db<TConfig>;
106
+ /**
107
+ * Typed handle for a single collection. Cheap; creates no I/O. Same
108
+ * `name` returns a FRESH `Collection<T>` object on each call (chain
109
+ * identity is intentional — modifiers return new objects).
110
+ *
111
+ * @throws BaerlyError code="InvalidConfig" when `name` is empty,
112
+ * contains `/`, is `"."` or `".."`, contains control characters,
113
+ * starts with the reserved `"_"` prefix, exceeds 256 bytes, or is
114
+ * not in Unicode Normalization Form C.
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * // With a baerly.config.ts bound via Db.create({..., config}),
119
+ * // db.collection(name) infers the row type from the declared schema —
120
+ * // no <Ticket> generic needed.
121
+ * const open = await db.collection("tickets")
122
+ * .where({ status: "open" })
123
+ * .order({ commit_ts: "desc" })
124
+ * .limit(50)
125
+ * .all();
126
+ * ```
127
+ */
128
+ collection<N extends CollectionNames<TConfig>>(name: N): Collection<RowOf<TConfig, N> & DocumentData>;
129
+ }
130
+ export { Db as t };