@gusto/baerly-storage 0.5.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 (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  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-Fe8CwB73.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-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  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-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  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 +38 -39
  53. package/dist/dev-vite.js +67 -36
  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-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.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-CuA9Mi3K.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 +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  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-a7PJHBCy.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-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  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-4FfGQNPw.js +22 -0
  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/sigv4-sign-5IUflUD_.js +507 -0
  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-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  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-DoDA-K7d.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-DBV1eQHC.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 +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1,38 +1,14 @@
1
- import { t as decodeJsonBytes } from "./bytes-BXdamO3L.js";
2
- import { r as parseBucketUri, t as loadAppConfig } from "./config-1tv0-Yzm.js";
3
- import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
- import { a as TENANT_ARG, i as JSON_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
1
+ import { a as isJsonMode, r as emitSuccess, s as BaerlyError } from "./baerly.js";
2
+ import { c as readCurrentJson, o as logSeqStartOf, r as certifiedDeleteFloor, u as decodeJsonBytes } from "./current-json-CC6lE4Aj.js";
3
+ import { i as logObjectKey, t as findLogTail } from "./log-tail-DWJbneBF.js";
4
+ import { n as parseBucketUri, t as loadAppConfig } from "./config-DEzInG6M.js";
5
+ import { i as LEGACY_NAME_MIGRATION, o as legacyIdReport } from "./legacy-names-DgZBtgOh.js";
6
+ import { a as TENANT_ARG, c as defineBaerlySubcommand, i as JSON_ARG, t as APP_ARG } from "./subcommand-BLoF66dG.js";
5
7
  /** Build the canonical `current.json` key for one collection. */
6
8
  const currentJsonKeyFor = (app, tenant, collection) => `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;
7
9
  /** Derive the `collectionPrefix` (everything before `/current.json`). */
8
10
  const collectionPrefixOf = (currentJsonKey) => currentJsonKey.slice(0, currentJsonKey.lastIndexOf("/"));
9
11
  /**
10
- * List every log key under `${collectionPrefix}/log/` for one collection.
11
- * Returns the keys in **chronological order** (oldest seq first).
12
- *
13
- * The on-bucket key shape is `<collectionPrefix>/log/<seq>.json` where
14
- * `<seq>` is a base-10 integer minted by `Writer`. Lex-ascending
15
- * key order disagrees with numeric seq order past seq=9 (`log/10.json`
16
- * sorts before `log/2.json`), so we parse the trailing integer out of
17
- * each key and sort numerically.
18
- *
19
- * Caller is expected to slice the trailing N entries — the writes/min
20
- * estimator only needs the most recent sample.
21
- */
22
- const seqOfLogKey = (key) => {
23
- const slash = key.lastIndexOf("/");
24
- const dot = key.lastIndexOf(".json");
25
- if (slash === -1 || dot === -1 || dot <= slash) return NaN;
26
- const seqStr = key.slice(slash + 1, dot);
27
- const n = Number.parseInt(seqStr, 10);
28
- return Number.isFinite(n) ? n : NaN;
29
- };
30
- const listLogKeysSortedBySeq = async (storage, logPrefix) => {
31
- const keys = [];
32
- for await (const entry of storage.list(logPrefix)) keys.push(entry.key);
33
- return keys.filter((k) => Number.isFinite(seqOfLogKey(k))).toSorted((a, b) => seqOfLogKey(a) - seqOfLogKey(b));
34
- };
35
- /**
36
12
  * Fetch a `LogEntry` body at `key`, returning its `commit_ts` parsed
37
13
  * to epoch-ms. Returns `null` when the object is missing (a peer may
38
14
  * have GC'd it between list and get); throws `BaerlyError` on a
@@ -46,7 +22,7 @@ const readCommitTsMs = async (storage, key) => {
46
22
  try {
47
23
  parsed = decodeJsonBytes(got.body);
48
24
  } catch (error) {
49
- throw new BaerlyError("InvalidResponse", `usage scan: log entry at ${key} is not valid JSON`, error);
25
+ throw new BaerlyError("InvalidResponse", `usage scan: log entry at ${key} is not valid JSON`, { cause: error });
50
26
  }
51
27
  if (typeof parsed.commit_ts !== "string") throw new BaerlyError("InvalidResponse", `usage scan: log entry at ${key} missing commit_ts`);
52
28
  const ms = Date.parse(parsed.commit_ts);
@@ -74,8 +50,10 @@ const readCommitTsBatched = async (storage, keys) => {
74
50
  /**
75
51
  * Estimate writes/min for one collection.
76
52
  *
77
- * Reads the last `sampleSize` log entries (default `SAMPLE_SIZE`)
78
- * for `<app>/<tenant>/<collection>`, computes
53
+ * Reads current.json, locates the true tail from
54
+ * `max(log_seq_start, tail_hint)`, then reads at most the last
55
+ * `sampleSize` retained log entries (default `SAMPLE_SIZE`) for
56
+ * `<app>/<tenant>/<collection>`. It computes
79
57
  * `(observedEntries - 1) / ((maxTs - minTs) / 60_000)`
80
58
  * minutes, compares against {@link M_SIZE_WRITES_PER_MIN_PER_COLLECTION},
81
59
  * and returns a {@link UsageVerdict}.
@@ -89,7 +67,7 @@ const readCommitTsBatched = async (storage, keys) => {
89
67
  * gracefully instead of dividing by zero.
90
68
  *
91
69
  * @throws BaerlyError code="NetworkError" — wrapped storage failure
92
- * while listing. The caller (Node doctor backend) catches and
70
+ * while locating or reading the sample. The caller (Node doctor backend) catches and
93
71
  * converts to a warning-severity finding so one bad collection
94
72
  * doesn't fail the whole scan.
95
73
  * @throws BaerlyError code="InvalidResponse" — a sampled log entry
@@ -98,19 +76,25 @@ const readCommitTsBatched = async (storage, keys) => {
98
76
  * (e.g. `s3://my-bucket/some/prefix`), pass it here (ending in
99
77
  * `/`). Defaults to `""`. Necessary for prefixed-bucket
100
78
  * correctness; ignored by `runUsageScan` (Node doctor scans the
101
- * root). Threaded through by `baerly inspect`.
79
+ * root). Threaded through by `baerly cost`.
102
80
  */
103
81
  const estimateWritesPerMin = async (storage, app, tenant, collection, opts = {}) => {
104
82
  const sampleSize = opts.sampleSize ?? 120;
105
- const logPrefix = `${`${opts.keyPrefix ?? ""}${collectionPrefixOf(currentJsonKeyFor(app, tenant, collection))}`}/log/`;
106
- let allKeys;
83
+ const currentJsonKey = `${opts.keyPrefix ?? ""}${currentJsonKeyFor(app, tenant, collection)}`;
84
+ const collectionPrefix = collectionPrefixOf(currentJsonKey);
85
+ let sample;
107
86
  try {
108
- allKeys = await listLogKeysSortedBySeq(storage, logPrefix);
87
+ const current = await readCurrentJson(storage, currentJsonKey);
88
+ const liveFloor = current === null ? 0 : logSeqStartOf(current.json);
89
+ const retainedFloor = current === null ? 0 : certifiedDeleteFloor(current.json);
90
+ const probeFloor = current === null ? 0 : Math.max(liveFloor, current.json.tail_hint);
91
+ const tail = await findLogTail(storage, collectionPrefix, probeFloor);
92
+ const sampleStart = Math.max(retainedFloor, tail - (Number.isFinite(sampleSize) && sampleSize > 0 ? Math.floor(sampleSize) : 0));
93
+ sample = Array.from({ length: tail - sampleStart }, (_, i) => logObjectKey(collectionPrefix, sampleStart + i));
109
94
  } catch (error) {
110
95
  if (error instanceof BaerlyError) throw error;
111
- throw new BaerlyError("NetworkError", `usage scan: list ${logPrefix} failed: ${error.message}`, error);
96
+ throw new BaerlyError("NetworkError", `usage scan: locate trailing sample under ${collectionPrefix}/log/ failed: ${error.message}`, { cause: error });
112
97
  }
113
- const sample = allKeys.slice(Math.max(0, allKeys.length - sampleSize));
114
98
  if (sample.length < 2) return {
115
99
  collection,
116
100
  writesPerMin: NaN,
@@ -182,7 +166,7 @@ const discoverCollections = async (storage, app, tenant) => {
182
166
  }
183
167
  } catch (error) {
184
168
  if (error instanceof BaerlyError) throw error;
185
- throw new BaerlyError("NetworkError", `usage scan: list ${prefix} failed: ${error.message}`, error);
169
+ throw new BaerlyError("NetworkError", `usage scan: list ${prefix} failed: ${error.message}`, { cause: error });
186
170
  }
187
171
  return [...names].toSorted();
188
172
  };
@@ -202,6 +186,7 @@ const discoverCollections = async (storage, app, tenant) => {
202
186
  */
203
187
  const runUsageScan = async (context, storage, findings) => {
204
188
  let collections;
189
+ for (const role of ["app", "tenant"]) if (context[role] !== context[role].normalize("NFC")) findings.push(nonNfcNameFinding(role, context[role]));
205
190
  try {
206
191
  collections = await discoverCollections(storage, context.app, context.tenant);
207
192
  } catch (error) {
@@ -220,6 +205,12 @@ const runUsageScan = async (context, storage, findings) => {
220
205
  });
221
206
  return;
222
207
  }
208
+ for (const c of collections) if (c !== c.normalize("NFC")) findings.push(nonNfcNameFinding("collection", c));
209
+ for (const group of legacyIdReport(collections).twin_ids) findings.push({
210
+ severity: "warning",
211
+ check: "names",
212
+ message: `collections ${JSON.stringify(group)} have canonically-equivalent names and share one key prefix on R2: ${LEGACY_NAME_MIGRATION}`
213
+ });
223
214
  for (const c of collections) try {
224
215
  const verdict = await estimateWritesPerMin(storage, context.app, context.tenant, c);
225
216
  findings.push({
@@ -236,6 +227,11 @@ const runUsageScan = async (context, storage, findings) => {
236
227
  });
237
228
  }
238
229
  };
230
+ const nonNfcNameFinding = (role, name) => ({
231
+ severity: "warning",
232
+ check: "names",
233
+ message: `${role} name ${JSON.stringify(name)} is not NFC: ${LEGACY_NAME_MIGRATION}`
234
+ });
239
235
  const USAGE_ARGS = {
240
236
  bucket: {
241
237
  type: "string",
@@ -290,7 +286,7 @@ const bundle = defineBaerlySubcommand({
290
286
  if (target === "cloudflare") findings.push({
291
287
  severity: "info",
292
288
  check: "usage.cloudflare",
293
- message: "baerly admin usage is not yet wired for --target=cloudflare. See docs/followups/agent-friendliness.md entry 10."
289
+ message: "baerly admin usage cannot read a Workerd-side R2 binding from --target=cloudflare. Use --target=node --bucket=s3://<bucket> with your R2 S3 API credentials."
294
290
  });
295
291
  else {
296
292
  if (args.bucket === void 0 || args.bucket.length === 0) throw new BaerlyError("InvalidConfig", "baerly admin usage: --bucket=<uri> is required for --target=node");
@@ -318,7 +314,6 @@ const bundle = defineBaerlySubcommand({
318
314
  /** citty `defineCommand` block for `baerly admin usage`. */
319
315
  const usageCmd = bundle.cmd;
320
316
  bundle.run;
321
- //#endregion
322
- export { estimateWritesPerMin, usageCmd };
317
+ export { collectionPrefixOf, estimateWritesPerMin, usageCmd };
323
318
 
324
- //# sourceMappingURL=usage-DBV1eQHC.js.map
319
+ //# sourceMappingURL=usage-CPzVhrQr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-CPzVhrQr.js","names":[],"sources":["../packages/cli/src/admin/usage.ts"],"sourcesContent":["/**\n * `baerly admin usage` — all-collection writes/min health check.\n *\n * Reads the most recent `SAMPLE_SIZE` log entries for every collection\n * under `app/<app>/tenant/<tenant>/manifests/`, compares the spread of\n * their embedded `commit_ts` timestamps against the M-size operating\n * ceiling (~30 writes/min/collection — see `M_SIZE_WRITES_PER_MIN_PER_COLLECTION`\n * below and `docs/about/thesis.md`), and prints one finding per\n * collection — `info` when well under the ceiling, `warning` when\n * approaching or exceeding it.\n *\n * The ~100 collections/tenant fan-out guideline is bench-grounded:\n * `admin usage` pays one logical tenant-discovery `Storage.list`\n * iterator, which a provider may satisfy with multiple physical LIST\n * pages as the retained manifest namespace grows. Per collection it then\n * pays one current.json GET, a history-bounded tail probe, and up to 120\n * sampled log GETs. See\n * `docs/spec/attachments/collection-fanout-baseline.json` (`pnpm\n * bench:collection-fanout`). Neither the ~100 figure nor the >10 GB/tenant\n * storage line is a code constant here; both are cost signals documented\n * in `docs/about/cost-model.md`.\n *\n * Distinct from `baerly cost` (the per-table, $/month projection):\n * `cost` is a developer-facing trajectory for one table, `usage` is an\n * operator-facing M-size graduation health check across all\n * collections.\n *\n * The pure-storage half — {@link estimateWritesPerMin},\n * {@link discoverCollections}, {@link runUsageScan} — takes a\n * `Storage` handle from the caller and never reads `process.env`.\n * The CLI wrapper at the bottom of the file constructs that\n * `Storage` from `--bucket=<uri>` via `parseBucketUri`. The\n * Cloudflare target short-circuits with an info-level \"not yet\n * wired\" finding because the Node CLI cannot consume a\n * Workerd-side R2 binding.\n *\n * Why GET each sampled entry: the timestamp is the `LogEntry.commit_ts`\n * body field. `current.json` supplies the live and certified delete\n * floors and a non-authoritative tail lower bound. The shared server tail finder\n * locates the exact end with bounded probes, then the estimator reads\n * at most `SAMPLE_SIZE` bodies by numeric key. It never materializes or\n * sorts the historical log namespace.\n *\n * @see docs/about/thesis.md — M-size ceiling rationale.\n * @see docs/spec/log-entry-shape.md — `LogEntry.commit_ts` contract.\n * @see packages/server/src/compactor.ts:224-225 — `collectionPrefix` /\n * `collectionName` derivation pattern reused here.\n */\n\nimport { type ArgsDef } from \"citty\";\nimport {\n BaerlyError,\n certifiedDeleteFloor,\n decodeJsonBytes,\n type LogEntry,\n logObjectKey,\n logSeqStartOf,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { findLogTail } from \"@baerly/server/_internal/kernel\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { loadAppConfig } from \"../config.ts\";\nimport { LEGACY_NAME_MIGRATION, legacyIdReport } from \"../legacy-names.ts\";\nimport { emitSuccess, isJsonMode } from \"../output.ts\";\nimport { APP_ARG, defineBaerlySubcommand, JSON_ARG, TENANT_ARG } from \"../subcommand.ts\";\n\n/**\n * Verdict-shaped finding the scan emits. Mirrors the\n * `severity / check / message / fix?` shape that `baerly doctor` uses,\n * but doesn't depend on `doctor/cloudflare.ts` — `admin usage` runs\n * outside the doctor surface.\n */\nexport interface UsageFinding {\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n readonly check: string;\n readonly message: string;\n readonly fix?: string;\n}\n\n/**\n * M-size writes-per-minute-per-collection ceiling from\n * `docs/about/thesis.md`. Crossing this with sustained traffic\n * means operators should consider graduating the workload to a\n * graduated store via `baerly export --target=postgres|sqlite|d1`.\n */\nexport const M_SIZE_WRITES_PER_MIN_PER_COLLECTION = 30;\n\n/** Number of trailing log entries the estimator reads per collection. */\nexport const SAMPLE_SIZE = 120;\n\n/** Per-collection verdict surfaced by {@link estimateWritesPerMin}. */\nexport interface UsageVerdict {\n /** Collection name (matches `LogEntry.collection`). */\n readonly collection: string;\n /**\n * Writes per minute estimated over the sample window. `NaN` when\n * fewer than 2 entries were observed (no defensible rate).\n */\n readonly writesPerMin: number;\n /** Percent of {@link M_SIZE_WRITES_PER_MIN_PER_COLLECTION}; `NaN` propagates. */\n readonly percentOfCeiling: number;\n /**\n * Severity scaled by distance to ceiling:\n * - `< 50%` → `\"info\"`\n * - `50–99%` → `\"warning\"` (\"approaching ceiling\")\n * - `≥ 100%` → `\"warning\"` (\"exceeds ceiling — consider export\")\n *\n * Severity `warning` never bumps the doctor's exit code above 0\n * (operators can still deploy / continue while approaching the\n * ceiling).\n */\n readonly severity: \"info\" | \"warning\";\n /** Human-readable one-liner suitable for a {@link UsageFinding}. */\n readonly message: string;\n /** Empty when no remediation is meaningful (under 50%). */\n readonly fix: string;\n}\n\n/** Build the canonical `current.json` key for one collection. */\nexport const currentJsonKeyFor = (app: string, tenant: string, collection: string): string =>\n `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;\n\n/** Derive the `collectionPrefix` (everything before `/current.json`). */\nexport const collectionPrefixOf = (currentJsonKey: string): string =>\n currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n\n/**\n * Fetch a `LogEntry` body at `key`, returning its `commit_ts` parsed\n * to epoch-ms. Returns `null` when the object is missing (a peer may\n * have GC'd it between list and get); throws `BaerlyError` on a\n * malformed body so the caller can downgrade the whole collection's\n * scan to an error-level finding.\n */\nconst readCommitTsMs = async (storage: Storage, key: string): Promise<number | null> => {\n const got = await storage.get(key);\n if (got === null) {\n return null;\n }\n let parsed: LogEntry;\n try {\n parsed = decodeJsonBytes<LogEntry>(got.body);\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `usage scan: log entry at ${key} is not valid JSON`, {\n cause: error,\n });\n }\n if (typeof parsed.commit_ts !== \"string\") {\n throw new BaerlyError(\"InvalidResponse\", `usage scan: log entry at ${key} missing commit_ts`);\n }\n const ms = Date.parse(parsed.commit_ts);\n if (!Number.isFinite(ms)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `usage scan: log entry at ${key} has unparseable commit_ts ${JSON.stringify(parsed.commit_ts)}`,\n );\n }\n return ms;\n};\n\n/**\n * Read each key with bounded concurrency. Mirrors the pattern in\n * `packages/server/src/log-walk.ts` — we cap parallelism to keep a\n * single doctor pass from blowing through the storage backend's\n * connection budget. Keeps a small constant rather than reaching for\n * `MAX_PARALLEL_LOG_READS` (8) so the doctor command is gentle by\n * default.\n */\nconst PARALLEL_READS = 8;\n\nconst readCommitTsBatched = async (\n storage: Storage,\n keys: readonly string[],\n): Promise<readonly (number | null)[]> => {\n const out: (number | null)[] = Array.from({ length: keys.length });\n for (let i = 0; i < keys.length; i += PARALLEL_READS) {\n const chunk = keys.slice(i, i + PARALLEL_READS);\n const results = await Promise.all(chunk.map((k) => readCommitTsMs(storage, k)));\n for (let j = 0; j < results.length; j++) {\n out[i + j] = results[j] ?? null;\n }\n }\n return out;\n};\n\n/**\n * Estimate writes/min for one collection.\n *\n * Reads current.json, locates the true tail from\n * `max(log_seq_start, tail_hint)`, then reads at most the last\n * `sampleSize` retained log entries (default `SAMPLE_SIZE`) for\n * `<app>/<tenant>/<collection>`. It computes\n * `(observedEntries - 1) / ((maxTs - minTs) / 60_000)`\n * minutes, compares against {@link M_SIZE_WRITES_PER_MIN_PER_COLLECTION},\n * and returns a {@link UsageVerdict}.\n *\n * Edge cases:\n * - Fewer than 2 entries observable → `writesPerMin = NaN`,\n * severity `info`, no fix. Operators see \"not enough log\n * entries to estimate.\"\n * - All entries share the same `commit_ts` (e.g. a tight batch) →\n * the denominator is clamped to 1 second so the rate degrades\n * gracefully instead of dividing by zero.\n *\n * @throws BaerlyError code=\"NetworkError\" — wrapped storage failure\n * while locating or reading the sample. The caller (Node doctor backend) catches and\n * converts to a warning-severity finding so one bad collection\n * doesn't fail the whole scan.\n * @throws BaerlyError code=\"InvalidResponse\" — a sampled log entry\n * body is malformed; same caller treatment.\n * @param opts.keyPrefix - When the bucket has a non-empty key prefix\n * (e.g. `s3://my-bucket/some/prefix`), pass it here (ending in\n * `/`). Defaults to `\"\"`. Necessary for prefixed-bucket\n * correctness; ignored by `runUsageScan` (Node doctor scans the\n * root). Threaded through by `baerly cost`.\n */\nexport const estimateWritesPerMin = async (\n storage: Storage,\n app: string,\n tenant: string,\n collection: string,\n opts: { readonly sampleSize?: number; readonly keyPrefix?: string } = {},\n): Promise<UsageVerdict> => {\n const sampleSize = opts.sampleSize ?? SAMPLE_SIZE;\n const keyPrefix = opts.keyPrefix ?? \"\";\n const currentJsonKey = `${keyPrefix}${currentJsonKeyFor(app, tenant, collection)}`;\n const collectionPrefix = collectionPrefixOf(currentJsonKey);\n\n let sample: readonly string[];\n try {\n const current = await readCurrentJson(storage, currentJsonKey);\n const liveFloor = current === null ? 0 : logSeqStartOf(current.json);\n const retainedFloor = current === null ? 0 : certifiedDeleteFloor(current.json);\n const probeFloor = current === null ? 0 : Math.max(liveFloor, current.json.tail_hint);\n const tail = await findLogTail(storage, collectionPrefix, probeFloor);\n const boundedSampleSize =\n Number.isFinite(sampleSize) && sampleSize > 0 ? Math.floor(sampleSize) : 0;\n const sampleStart = Math.max(retainedFloor, tail - boundedSampleSize);\n sample = Array.from({ length: tail - sampleStart }, (_, i) =>\n logObjectKey(collectionPrefix, sampleStart + i),\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `usage scan: locate trailing sample under ${collectionPrefix}/log/ failed: ${(error as Error).message}`,\n { cause: error },\n );\n }\n if (sample.length < 2) {\n return {\n collection,\n writesPerMin: Number.NaN,\n percentOfCeiling: Number.NaN,\n severity: \"info\",\n message: `collection ${collection}: not enough log entries to estimate (saw ${sample.length}, need >= 2)`,\n fix: \"\",\n };\n }\n const commitTs = await readCommitTsBatched(storage, sample);\n const timestamps = commitTs.filter((v): v is number => v !== null);\n if (timestamps.length < 2) {\n return {\n collection,\n writesPerMin: Number.NaN,\n percentOfCeiling: Number.NaN,\n severity: \"info\",\n message: `collection ${collection}: not enough readable log entries to estimate (resolved ${timestamps.length}, need >= 2)`,\n fix: \"\",\n };\n }\n let minTs = timestamps[0]!;\n let maxTs = timestamps[0]!;\n for (const t of timestamps) {\n if (t < minTs) {\n minTs = t;\n }\n if (t > maxTs) {\n maxTs = t;\n }\n }\n // Guard the denominator: a tight batch may produce identical\n // commit_ts values; degrade to a one-second window so we never\n // divide by zero.\n const minutes = Math.max(1 / 60, (maxTs - minTs) / 60_000);\n const writesPerMin = (timestamps.length - 1) / minutes;\n const pct = (writesPerMin / M_SIZE_WRITES_PER_MIN_PER_COLLECTION) * 100;\n\n let severity: \"info\" | \"warning\" = \"info\";\n let message = `collection ${collection}: ${writesPerMin.toFixed(1)} writes/min (~${pct.toFixed(0)}% of M-size ceiling, sampled ${timestamps.length} entries)`;\n let fix = \"\";\n if (pct >= 100) {\n severity = \"warning\";\n message += \" — exceeds the M-size ceiling.\";\n fix = `consider graduating: \\`baerly export --target=postgres|sqlite|d1 --bucket=<bucket> --app=${app} --tenant=${tenant} --collection=${collection}\\``;\n } else if (pct >= 50) {\n severity = \"warning\";\n message += \" — approaching the M-size ceiling.\";\n fix = \"monitor; plan graduation via `baerly export --target=postgres|sqlite|d1`\";\n }\n return { collection, writesPerMin, percentOfCeiling: pct, severity, message, fix };\n};\n\n/**\n * Discover the set of collections under `<app>/<tenant>/manifests/`\n * by listing the bucket. Each collection is the immediate\n * subdirectory name (the segment after `manifests/` and before the\n * next `/`).\n *\n * Returns a deduped, lex-sorted list. An empty list means there are\n * no committed collections under this app/tenant yet — the caller\n * surfaces a single info finding rather than scanning per-collection.\n *\n * @throws BaerlyError code=\"NetworkError\" — wrapped list failure.\n */\nexport const discoverCollections = async (\n storage: Storage,\n app: string,\n tenant: string,\n): Promise<readonly string[]> => {\n const prefix = `app/${app}/tenant/${tenant}/manifests/`;\n const names = new Set<string>();\n try {\n for await (const entry of storage.list(prefix)) {\n const rest = entry.key.slice(prefix.length);\n const slash = rest.indexOf(\"/\");\n const name = slash === -1 ? rest : rest.slice(0, slash);\n if (name.length > 0) {\n names.add(name);\n }\n }\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `usage scan: list ${prefix} failed: ${(error as Error).message}`,\n { cause: error },\n );\n }\n return [...names].toSorted();\n};\n\n/**\n * Orchestrate the usage scan against a caller-supplied\n * {@link Storage}. The CLI wrapper handles bucket-URI construction;\n * this helper runs the shared discover → per-collection-estimate →\n * finding-push loop.\n *\n * Mutates `findings` in place. Returns when the scan completes\n * (success or per-collection failure all surface as findings). The\n * outer CLI exit code is driven by the rollup over all findings.\n *\n * Errors land as warnings (not errors) so one bad collection doesn't\n * abort the whole scan and so the operator stays deployable while a\n * single object is being investigated.\n */\nexport const runUsageScan = async (\n context: { readonly app: string; readonly tenant: string },\n storage: Storage,\n findings: UsageFinding[],\n): Promise<void> => {\n let collections: readonly string[];\n // Migration preflight: the app and tenant the scan addresses.\n for (const role of [\"app\", \"tenant\"] as const) {\n if (context[role] !== context[role].normalize(\"NFC\")) {\n findings.push(nonNfcNameFinding(role, context[role]));\n }\n }\n try {\n collections = await discoverCollections(storage, context.app, context.tenant);\n } catch (error) {\n findings.push({\n severity: \"warning\",\n check: \"usage-discover\",\n message: `could not enumerate collections under app/${context.app}/tenant/${context.tenant}/manifests/: ${error instanceof BaerlyError ? error.message : (error as Error).message}`,\n });\n return;\n }\n if (collections.length === 0) {\n findings.push({\n severity: \"info\",\n check: \"usage-empty\",\n message: `no collections found under app/${context.app}/tenant/${context.tenant}/manifests/; nothing to scan.`,\n });\n return;\n }\n // Migration preflight: discovers the collection names `fsck` / `dump`\n // can only check when told them.\n for (const c of collections) {\n if (c !== c.normalize(\"NFC\")) {\n findings.push(nonNfcNameFinding(\"collection\", c));\n }\n }\n for (const group of legacyIdReport(collections).twin_ids) {\n findings.push({\n severity: \"warning\",\n check: \"names\",\n message: `collections ${JSON.stringify(group)} have canonically-equivalent names and share one key prefix on R2: ${LEGACY_NAME_MIGRATION}`,\n });\n }\n for (const c of collections) {\n try {\n const verdict = await estimateWritesPerMin(storage, context.app, context.tenant, c);\n findings.push({\n severity: verdict.severity,\n check: `usage-${c}`,\n message: verdict.message,\n ...(verdict.fix !== \"\" && { fix: verdict.fix }),\n });\n } catch (error) {\n findings.push({\n severity: \"warning\",\n check: `usage-${c}`,\n message: `failed to estimate writes/min for ${c}: ${error instanceof BaerlyError ? error.message : (error as Error).message}`,\n });\n }\n }\n};\n\nconst nonNfcNameFinding = (role: string, name: string): UsageFinding => ({\n severity: \"warning\",\n check: \"names\",\n message: `${role} name ${JSON.stringify(name)} is not NFC: ${LEGACY_NAME_MIGRATION}`,\n});\n\n// ---------------------------------------------------------------------------\n// CLI surface — `baerly admin usage`\n// ---------------------------------------------------------------------------\n\nconst USAGE_ARGS = {\n bucket: {\n type: \"string\",\n required: false,\n description:\n \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>). Required for --target=node.\",\n valueHint: \"bucket-uri\",\n },\n target: {\n type: \"string\",\n required: false,\n description: 'Override `baerly.config.ts:target`. One of \"cloudflare\" | \"node\".',\n valueHint: \"target\",\n },\n app: APP_ARG,\n tenant: TENANT_ARG,\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<UsageFinding[\"severity\"], string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst renderText = (target: string, findings: readonly UsageFinding[]): string => {\n const lines: string[] = [];\n lines.push(`baerly admin usage --target=${target}`);\n lines.push(\"\");\n for (const f of findings) {\n lines.push(` ${SEVERITY_GLYPH[f.severity]} ${f.message}`);\n if (f.fix !== undefined && f.fix !== \"\") {\n lines.push(` fix: ${f.fix}`);\n }\n }\n let warnings = 0;\n let errors = 0;\n for (const f of findings) {\n if (f.severity === \"warning\") {\n warnings++;\n } else if (f.severity === \"error\") {\n errors++;\n }\n }\n lines.push(\"\");\n lines.push(\n `Status: ${errors} error${errors === 1 ? \"\" : \"s\"}, ${warnings} warning${warnings === 1 ? \"\" : \"s\"}.`,\n );\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.usage\",\n meta: {\n description:\n \"All-collection writes/min health check; flags collections approaching the M-size ceiling.\",\n },\n args: USAGE_ARGS,\n handler: async (args, ctx) => {\n // Avoid loading the config when --target is explicit — the CLI\n // should still work outside an app directory if the operator\n // pins target + app + tenant on the flags.\n const target = args.target ?? (await loadAppConfig().then((c) => c.target));\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin usage: unsupported --target ${JSON.stringify(target)} (one of \"cloudflare\" | \"node\")`,\n );\n }\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n\n const findings: UsageFinding[] = [];\n\n if (target === \"cloudflare\") {\n // The CLI runs in Node and can't reach a Workerd-side R2 binding\n // directly. Operators can instead use R2's S3-compatible API\n // through the Node target and an explicit bucket URI.\n findings.push({\n severity: \"info\",\n check: \"usage.cloudflare\",\n message:\n \"baerly admin usage cannot read a Workerd-side R2 binding from --target=cloudflare. Use --target=node --bucket=s3://<bucket> with your R2 S3 API credentials.\",\n });\n } else {\n if (args.bucket === undefined || args.bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin usage: --bucket=<uri> is required for --target=node\",\n );\n }\n const parsed = await parseBucketUri(args.bucket);\n await runUsageScan({ app, tenant }, parsed.storage, findings);\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.usage\",\n status: \"ok\",\n target,\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.fix !== undefined && f.fix !== \"\" && { fix: f.fix }),\n })),\n });\n } else {\n process.stdout.write(renderText(target, findings));\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin usage`. */\nexport const usageCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runUsage = bundle.run;\n"],"mappings":";;;;;;;AAwHA,MAAa,qBAAqB,KAAa,QAAgB,eAC7D,OAAO,IAAI,UAAU,OAAO,aAAa,WAAW;;AAGtD,MAAa,sBAAsB,mBACjC,eAAe,MAAM,GAAG,eAAe,YAAY,GAAG,CAAC;;;;;;;;AASzD,MAAM,iBAAiB,OAAO,SAAkB,QAAwC;CACtF,MAAM,MAAM,MAAM,QAAQ,IAAI,GAAG;CACjC,IAAI,QAAQ,MACV,OAA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KAAa,KAAK,OAAO,WAAW,GACtD,MAAM,IAAI,YACR,iBACA,kEACF;GAEF,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;GAC/C,MAAM,aAAa;IAAE;IAAK;GAAO,GAAG,OAAO,SAAS,QAAQ;EAC9D;EAEA,IAAI,WAAW,GACb,YAAY;GACV,SAAS;GACT,QAAQ;GACR;GACA,UAAU,SAAS,KAAK,OAAO;IAC7B,UAAU,EAAE;IACZ,OAAO,EAAE;IACT,SAAS,EAAE;IACX,GAAI,EAAE,QAAQ,KAAA,KAAa,EAAE,QAAQ,MAAM,EAAE,KAAK,EAAE,IAAI;GAC1D,EAAE;EACJ,CAAC;OAED,QAAQ,OAAO,MAAM,WAAW,QAAQ,QAAQ,CAAC;EAEnD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,WAAW,OAAO;AAOP,OAAO"}
@@ -0,0 +1,333 @@
1
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
2
+ // packages/protocol/src/document-input.ts
3
+ const INSERT_ID_RESOLUTION = "Pass _id as a non-empty string (for example String(value)), or omit it to have one generated.";
4
+ /**
5
+ * Reject a present, non-string `_id` on an insert. `undefined` is absent and
6
+ * `""` is a string, so both still get a generated id; `null`, numbers
7
+ * (`-0` and `NaN` included), booleans, objects and arrays throw. Checks the
8
+ * caller's own value, before anything replaces it with a generated id.
9
+ * Shared by the server's insert and the HTTP client's, so the two agree on
10
+ * which ids are generated.
11
+ *
12
+ * @throws BaerlyError code="InvalidConfig" — `id` is present and not a string.
13
+ */
14
+ const assertInsertIdType = (id) => {
15
+ if (id !== void 0 && typeof id !== "string") throw new BaerlyError("InvalidConfig", `insert: _id must be a string, got ${id === null ? "null" : typeof id}`, { resolution: INSERT_ID_RESOLUTION });
16
+ };
17
+ const NON_FINITE_RESOLUTION = "JSON cannot represent NaN or Infinity. Store a finite number or null there, or omit the field.";
18
+ const UNDEFINED_MEMBER_RESOLUTION = "JSON drops a member whose value is undefined. Omit the field, or store null.";
19
+ const UNDEFINED_ELEMENT_RESOLUTION = "JSON turns an undefined or missing array element into null. Store null there, or remove the element.";
20
+ const NON_PLAIN_RESOLUTION = "Store plain JSON: convert a Date with date.toISOString(), a Map with Object.fromEntries(map), a Set or typed array with Array.from(value), a boxed primitive with value.valueOf(), and copy a class instance's fields into a plain object.";
21
+ const NON_JSON_TYPE_RESOLUTION = "Store a string, finite number, boolean, null, plain object or array there. Convert a bigint with String(value); remove functions and symbols.";
22
+ const TO_JSON_RESOLUTION = "Remove the toJSON hook and pass its intended JSON data explicitly. Documents and patches must not customize JSON serialization.";
23
+ const CIRCULAR_RESOLUTION = "Remove the circular reference: a document is a tree of plain objects and arrays.";
24
+ const DEPTH_RESOLUTION = `Keep each document at most 100 levels deep (each object or array is a level, the document itself included): flatten nested data into compound keys or arrays of records, or move a deep subtree into rows of its own.`;
25
+ /** Inspect descriptors so even a toJSON getter is refused without running it. */
26
+ const hasJsonHook = (value) => {
27
+ for (let at = value; at !== null; at = Object.getPrototypeOf(at)) {
28
+ const descriptor = Object.getOwnPropertyDescriptor(at, "toJSON");
29
+ if (descriptor !== void 0) return !("value" in descriptor) || typeof descriptor.value === "function";
30
+ }
31
+ return false;
32
+ };
33
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
34
+ const renderSegment = (key) => {
35
+ if (typeof key === "number") return `[${key}]`;
36
+ if (key.length > 64) return `[${JSON.stringify(key.slice(0, 64))}…]`;
37
+ return IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
38
+ };
39
+ /** The keys from the root to `at`. */
40
+ const keysOf = (at) => {
41
+ const keys = [];
42
+ for (let step = at; step?.key !== void 0; step = step.parent) keys.push(step.key);
43
+ keys.reverse();
44
+ return keys;
45
+ };
46
+ /**
47
+ * The path from the root to `at`, as `a.b[2]["c d"]`. A deep path keeps
48
+ * its first and last {@link DOCUMENT_ERROR_PATH_EDGE_SEGMENTS} segments
49
+ * around a `.…` marker, so the message stays bounded.
50
+ */
51
+ const pathOf = (at) => {
52
+ const keys = keysOf(at);
53
+ const path = keys.length > 8 ? `${keys.slice(0, 4).map(renderSegment).join("")}.…${keys.slice(-4).map(renderSegment).join("")}` : keys.map(renderSegment).join("");
54
+ return path.startsWith(".") ? path.slice(1) : path;
55
+ };
56
+ const refuse = (verb, at, what, resolution) => {
57
+ const path = pathOf(at);
58
+ throw new BaerlyError("InvalidConfig", path === "" ? `${verb}: the document is ${what}` : `${verb}: document value at ${path} is ${what}`, { resolution });
59
+ };
60
+ /**
61
+ * The first container past {@link MAX_DOCUMENT_DEPTH}. `SchemaError`, not
62
+ * `InvalidConfig`: the value is valid JSON, but its shape is outside what
63
+ * a document may be. `issues` carries the full path.
64
+ */
65
+ const refuseDepth = (verb, at) => {
66
+ const message = `nests deeper than the 100-level document limit`;
67
+ throw new BaerlyError("SchemaError", `${verb}: document value at ${pathOf(at)} ${message}`, {
68
+ resolution: DEPTH_RESOLUTION,
69
+ issues: [{
70
+ path: keysOf(at),
71
+ message
72
+ }]
73
+ });
74
+ };
75
+ /**
76
+ * Reject a document (or update patch) holding a value JSON cannot store
77
+ * as written. `JSON.stringify` would silently turn `NaN` and `±Infinity`
78
+ * into `null`, drop `undefined` members, turn `undefined` or missing array
79
+ * elements into `null`, and reduce a `Date`, `Map`, typed array, boxed
80
+ * primitive or class instance to a different shape; a function, symbol or
81
+ * bigint would be dropped or throw. Each of those throws here instead,
82
+ * naming the path of the first offending value (capped, see
83
+ * {@link DOCUMENT_ERROR_PATH_EDGE_SEGMENTS}), as do circular references.
84
+ * Callable or accessor `toJSON` properties (own or inherited) are refused
85
+ * without invoking them, including on the root and on arrays. A value
86
+ * nested deeper than {@link MAX_DOCUMENT_DEPTH} levels is refused too, as
87
+ * `SchemaError`.
88
+ *
89
+ * Allowed: strings, finite numbers (`-0` included), booleans, `null` (at
90
+ * any depth), arrays, and plain objects (prototype `Object.prototype` or
91
+ * `null`). The root itself may be any object; its own
92
+ * enumerable fields are checked. A top-level `_id: undefined` counts as
93
+ * absent, as on `insert`; with `undefinedMembersAbsent`, every
94
+ * `undefined` object member does. No `null` limits are applied.
95
+ * Size is checked separately, on the whole post-image a write commits
96
+ * (`assertDocumentSize`).
97
+ *
98
+ * The input graph must remain stable until the write completes. Ordinary
99
+ * field getters are read during traversal; changing getters, proxies and
100
+ * concurrent mutation are not supported as a way to supply document data.
101
+ * This check does not snapshot the graph or execute serialization hooks.
102
+ *
103
+ * I/O-free. `insert` and `replace` call it on the caller's
104
+ * document before any storage call, and `update` on each merged
105
+ * post-image before any write; the HTTP client calls it before
106
+ * serializing (on the patch, for `update`), because the coercions above
107
+ * happen in `JSON.stringify` and a server only ever sees their result.
108
+ *
109
+ * @param verb the calling verb, used as the message prefix
110
+ * (`"insert"`, `"replace"`, `"update"`, …).
111
+ * @throws BaerlyError code="InvalidConfig" — `value` holds a value outside
112
+ * the JSON document domain. The message names its path.
113
+ * @throws BaerlyError code="SchemaError" — `value` nests an object or
114
+ * array deeper than {@link MAX_DOCUMENT_DEPTH} levels. The message names
115
+ * the limit and the (capped) path; `issues` holds the full path.
116
+ */
117
+ const assertDocumentValues = (value, verb, options) => {
118
+ const undefinedMembersAbsent = options?.undefinedMembersAbsent === true;
119
+ const pending = [{
120
+ value,
121
+ parent: void 0,
122
+ key: void 0,
123
+ depth: 1
124
+ }];
125
+ const ancestors = /* @__PURE__ */ new Set();
126
+ while (pending.length > 0) {
127
+ const next = pending.pop();
128
+ if ("exit" in next) {
129
+ ancestors.delete(next.exit);
130
+ continue;
131
+ }
132
+ const current = next.value;
133
+ if (typeof current === "string" || typeof current === "boolean" || current === null) continue;
134
+ if (typeof current === "number") {
135
+ if (Number.isFinite(current)) continue;
136
+ return refuse(verb, next, String(current), NON_FINITE_RESOLUTION);
137
+ }
138
+ if (current === void 0) {
139
+ const elementOrMember = typeof next.key === "number";
140
+ return refuse(verb, next, "undefined", elementOrMember ? UNDEFINED_ELEMENT_RESOLUTION : UNDEFINED_MEMBER_RESOLUTION);
141
+ }
142
+ if (typeof current !== "object") return refuse(verb, next, `a ${typeof current}`, NON_JSON_TYPE_RESOLUTION);
143
+ if (ancestors.has(current)) return refuse(verb, next, "a circular reference", CIRCULAR_RESOLUTION);
144
+ if (next.depth > 100) return refuseDepth(verb, next);
145
+ if (hasJsonHook(current)) return refuse(verb, next, "an object with a toJSON hook", TO_JSON_RESOLUTION);
146
+ if (Array.isArray(current)) {
147
+ ancestors.add(current);
148
+ pending.push({ exit: current });
149
+ for (let i = current.length - 1; i >= 0; i--) pending.push({
150
+ value: current[i],
151
+ parent: next,
152
+ key: i,
153
+ depth: next.depth + 1
154
+ });
155
+ continue;
156
+ }
157
+ const prototype = Object.getPrototypeOf(current);
158
+ if (next.parent !== void 0 && prototype !== Object.prototype && prototype !== null) {
159
+ const name = current.constructor?.name;
160
+ return refuse(verb, next, typeof name === "string" && name !== "" ? `a ${name}, not a plain object` : "not a plain object", NON_PLAIN_RESOLUTION);
161
+ }
162
+ ancestors.add(current);
163
+ pending.push({ exit: current });
164
+ const keys = Object.keys(current);
165
+ for (let i = keys.length - 1; i >= 0; i--) {
166
+ const key = keys[i];
167
+ const member = current[key];
168
+ if (member === void 0 && (undefinedMembersAbsent || key === "_id" && next.parent === void 0)) continue;
169
+ pending.push({
170
+ value: member,
171
+ parent: next,
172
+ key,
173
+ depth: next.depth + 1
174
+ });
175
+ }
176
+ }
177
+ };
178
+ // packages/protocol/src/query/builder.ts
179
+ /**
180
+ * Build a fresh `PredicateBuilder<T>` along with the clause-list
181
+ * cell it appends to. Internal — `./normalize.ts` drives this.
182
+ *
183
+ * @internal
184
+ */
185
+ const makeBuilder = () => {
186
+ const clauses = [];
187
+ const push = (clause) => {
188
+ clauses.push(clause);
189
+ return builder;
190
+ };
191
+ const builder = {
192
+ eq: (field, value) => push({
193
+ op: "eq",
194
+ field: String(field),
195
+ value
196
+ }),
197
+ gt: (field, value) => push({
198
+ op: "gt",
199
+ field: String(field),
200
+ value
201
+ }),
202
+ gte: (field, value) => push({
203
+ op: "gte",
204
+ field: String(field),
205
+ value
206
+ }),
207
+ lt: (field, value) => push({
208
+ op: "lt",
209
+ field: String(field),
210
+ value
211
+ }),
212
+ lte: (field, value) => push({
213
+ op: "lte",
214
+ field: String(field),
215
+ value
216
+ }),
217
+ in: (field, values) => push({
218
+ op: "in",
219
+ field: String(field),
220
+ value: [...values]
221
+ })
222
+ };
223
+ return {
224
+ builder,
225
+ clauses
226
+ };
227
+ };
228
+ /**
229
+ * Tighter wire-form type after running through the builder helper —
230
+ * not part of the public surface; `./normalize.ts` returns a plain
231
+ * {@link PredicateWire}.
232
+ *
233
+ * @internal
234
+ */
235
+ const wireFromBuilder = (cb) => {
236
+ const { builder, clauses } = makeBuilder();
237
+ cb(builder);
238
+ return { clauses };
239
+ };
240
+ // packages/protocol/src/query/normalize.ts
241
+ /**
242
+ * Object-form → wire normaliser. Walks a `Predicate<T>` object
243
+ * literal, flattens nested sub-predicates to dotted-path `eq`
244
+ * clauses, and returns a {@link PredicateWire}. Rejects any
245
+ * `$`-prefixed key as `InvalidConfig` — the operator vocabulary
246
+ * lives on the callback DSL only.
247
+ *
248
+ * Semantic invariant: a sub-predicate object (every value is itself
249
+ * an object) flattens to one `eq` clause per leaf — the same
250
+ * open-world matching today's matcher delivers at
251
+ * `./matches.ts:matchesValue` for sub-predicates.
252
+ *
253
+ * Companion modules: `./builder.ts` (callback → wire),
254
+ * `./wire.ts` (types).
255
+ */
256
+ const formatPath = (path) => path.length === 0 ? "<root>" : path.map((p) => JSON.stringify(p)).join(".");
257
+ /**
258
+ * Walk an object-literal predicate, emit one `PredicateClause[]`.
259
+ * Pure primitive values become `eq` clauses at the current path;
260
+ * nested objects recurse, flattening to dotted-path clauses.
261
+ *
262
+ * @internal Tested via the public `normalizePredicateArg` and the
263
+ * normalize.test.ts suite.
264
+ */
265
+ const normalizeObject = (obj, basePath) => {
266
+ const out = [];
267
+ for (const key of Object.keys(obj)) {
268
+ const path = [...basePath, key];
269
+ if (key.startsWith("$")) throw new BaerlyError("InvalidConfig", `Unsupported predicate operator ${JSON.stringify(key)} at ${formatPath(basePath)} — operator vocabulary moved to the callback form (.where(q => q.gt(field, value))). $-keys are not accepted in object-form predicates.`);
270
+ if (key === "__proto__" || key === "constructor" || key === "prototype") throw new BaerlyError("InvalidConfig", `Reserved key ${JSON.stringify(key)} not allowed in a predicate at ${formatPath(basePath)}.`);
271
+ const value = obj[key];
272
+ if (value === null || value === void 0) throw new BaerlyError("InvalidConfig", `Predicate value at ${formatPath(path)} is ${value === null ? "null" : "undefined"} — terminal values must be string / number / boolean / nested object.`);
273
+ if (Array.isArray(value)) throw new BaerlyError("InvalidConfig", `Predicate value at ${formatPath(path)} is an array — match nested objects with a sub-predicate or use callback form (q.in(field, values)) for set membership.`);
274
+ const t = typeof value;
275
+ if (t === "object") {
276
+ const inner = normalizeObject(value, path);
277
+ for (const c of inner) out.push(c);
278
+ continue;
279
+ }
280
+ if (t !== "string" && t !== "number" && t !== "boolean") throw new BaerlyError("InvalidConfig", `Predicate value at ${formatPath(path)} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`);
281
+ if (t === "number" && !Number.isFinite(value)) throw new BaerlyError("InvalidConfig", `Predicate value at ${formatPath(path)} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`);
282
+ out.push({
283
+ op: "eq",
284
+ field: path.join("."),
285
+ value
286
+ });
287
+ }
288
+ return out;
289
+ };
290
+ /**
291
+ * Dispatch the two-shape `.where(...)` argument to a
292
+ * {@link PredicateWire}. The object-form is walked by
293
+ * {@link normalizeObject}; the callback form is invoked with a
294
+ * fresh {@link PredicateBuilder}.
295
+ *
296
+ * @internal — every consumer (`Db.collection().where`,
297
+ * `ClientCollection.where`, `parseWhereParam`'s wire-arrival
298
+ * path) routes through this single seam so the wire
299
+ * format has exactly one parser path.
300
+ */
301
+ const normalizePredicateArg = (arg) => {
302
+ if (typeof arg === "function") return wireFromBuilder(arg);
303
+ return { clauses: normalizeObject(arg, []) };
304
+ };
305
+ // packages/protocol/src/uuid.ts
306
+ /**
307
+ * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,
308
+ * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.
309
+ * Lex-sortable by mint time, so it pairs well with object-storage
310
+ * list semantics. Returns a branded {@link UUID}.
311
+ *
312
+ * Uses `crypto.getRandomValues` which is universally available
313
+ * (Node 19+, Workerd, Bun, browsers).
314
+ *
315
+ * @example
316
+ * ```ts
317
+ * const id = uuidv7();
318
+ * // e.g. "01956cad-4cc8-7abc-9def-0123456789ab"
319
+ * ```
320
+ */
321
+ const uuidv7 = () => {
322
+ const millis = Date.now();
323
+ const rand = /* @__PURE__ */ new Uint8Array(10);
324
+ crypto.getRandomValues(rand);
325
+ rand[0] = rand[0] & 15 | 112;
326
+ rand[2] = rand[2] & 63 | 128;
327
+ const millisHex = millis.toString(16).padStart(12, "0");
328
+ const b = Array.from(rand, (n) => n.toString(16).padStart(2, "0")).join("");
329
+ return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}`;
330
+ };
331
+ export { assertInsertIdType as i, normalizePredicateArg as n, assertDocumentValues as r, uuidv7 as t };
332
+
333
+ //# sourceMappingURL=uuid-BuT_c404.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uuid-BuT_c404.js","names":[],"sources":["../packages/protocol/src/document-input.ts","../packages/protocol/src/query/builder.ts","../packages/protocol/src/query/normalize.ts","../packages/protocol/src/uuid.ts"],"sourcesContent":["import {\n DOCUMENT_ERROR_PATH_EDGE_SEGMENTS,\n DOCUMENT_ERROR_PATH_KEY_CHARS,\n MAX_DOCUMENT_DEPTH,\n} from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\n\nconst INSERT_ID_RESOLUTION =\n \"Pass _id as a non-empty string (for example String(value)), or omit it to have one generated.\";\n\n/**\n * Reject a present, non-string `_id` on an insert. `undefined` is absent and\n * `\"\"` is a string, so both still get a generated id; `null`, numbers\n * (`-0` and `NaN` included), booleans, objects and arrays throw. Checks the\n * caller's own value, before anything replaces it with a generated id.\n * Shared by the server's insert and the HTTP client's, so the two agree on\n * which ids are generated.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `id` is present and not a string.\n */\nexport const assertInsertIdType = (id: unknown): void => {\n if (id !== undefined && typeof id !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `insert: _id must be a string, got ${id === null ? \"null\" : typeof id}`,\n { resolution: INSERT_ID_RESOLUTION },\n );\n }\n};\n\nconst NON_FINITE_RESOLUTION =\n \"JSON cannot represent NaN or Infinity. Store a finite number or null there, or omit the field.\";\nconst UNDEFINED_MEMBER_RESOLUTION =\n \"JSON drops a member whose value is undefined. Omit the field, or store null.\";\nconst UNDEFINED_ELEMENT_RESOLUTION =\n \"JSON turns an undefined or missing array element into null. Store null there, or remove the element.\";\nconst NON_PLAIN_RESOLUTION =\n \"Store plain JSON: convert a Date with date.toISOString(), a Map with Object.fromEntries(map), a Set or typed array with Array.from(value), a boxed primitive with value.valueOf(), and copy a class instance's fields into a plain object.\";\nconst NON_JSON_TYPE_RESOLUTION =\n \"Store a string, finite number, boolean, null, plain object or array there. Convert a bigint with String(value); remove functions and symbols.\";\nconst TO_JSON_RESOLUTION =\n \"Remove the toJSON hook and pass its intended JSON data explicitly. Documents and patches must not customize JSON serialization.\";\nconst CIRCULAR_RESOLUTION =\n \"Remove the circular reference: a document is a tree of plain objects and arrays.\";\nconst DEPTH_RESOLUTION = `Keep each document at most ${MAX_DOCUMENT_DEPTH} levels deep (each object or array is a level, the document itself included): flatten nested data into compound keys or arrays of records, or move a deep subtree into rows of its own.`;\n\n/** Inspect descriptors so even a toJSON getter is refused without running it. */\nconst hasJsonHook = (value: object): boolean => {\n for (\n let at: object | null = value;\n at !== null;\n at = Object.getPrototypeOf(at) as object | null\n ) {\n const descriptor = Object.getOwnPropertyDescriptor(at, \"toJSON\");\n if (descriptor !== undefined) {\n // JSON looks up the first property in the chain. A non-callable\n // data value shadows any inherited hook and is ordinary JSON data.\n return !(\"value\" in descriptor) || typeof descriptor.value === \"function\";\n }\n }\n return false;\n};\n\n/** One value awaiting a check, with the link back to its parent for the error path. */\ntype Pending = {\n readonly value: unknown;\n readonly parent: Pending | undefined;\n readonly key: string | number | undefined;\n /** Levels from the root, which is level 1 (see {@link MAX_DOCUMENT_DEPTH}). */\n readonly depth: number;\n};\n\nconst IDENTIFIER = /^[A-Za-z_$][\\w$]*$/;\n\nconst renderSegment = (key: string | number): string => {\n if (typeof key === \"number\") {\n return `[${key}]`;\n }\n if (key.length > DOCUMENT_ERROR_PATH_KEY_CHARS) {\n return `[${JSON.stringify(key.slice(0, DOCUMENT_ERROR_PATH_KEY_CHARS))}…]`;\n }\n return IDENTIFIER.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;\n};\n\n/** The keys from the root to `at`. */\nconst keysOf = (at: Pending): Array<string | number> => {\n const keys: Array<string | number> = [];\n for (let step: Pending | undefined = at; step?.key !== undefined; step = step.parent) {\n keys.push(step.key);\n }\n keys.reverse();\n return keys;\n};\n\n/**\n * The path from the root to `at`, as `a.b[2][\"c d\"]`. A deep path keeps\n * its first and last {@link DOCUMENT_ERROR_PATH_EDGE_SEGMENTS} segments\n * around a `.…` marker, so the message stays bounded.\n */\nconst pathOf = (at: Pending): string => {\n const keys = keysOf(at);\n const edge = DOCUMENT_ERROR_PATH_EDGE_SEGMENTS;\n const path =\n keys.length > 2 * edge\n ? `${keys.slice(0, edge).map(renderSegment).join(\"\")}.…${keys\n .slice(-edge)\n .map(renderSegment)\n .join(\"\")}`\n : keys.map(renderSegment).join(\"\");\n return path.startsWith(\".\") ? path.slice(1) : path;\n};\n\nconst refuse = (verb: string, at: Pending, what: string, resolution: string): never => {\n const path = pathOf(at);\n throw new BaerlyError(\n \"InvalidConfig\",\n path === \"\"\n ? `${verb}: the document is ${what}`\n : `${verb}: document value at ${path} is ${what}`,\n { resolution },\n );\n};\n\n/**\n * The first container past {@link MAX_DOCUMENT_DEPTH}. `SchemaError`, not\n * `InvalidConfig`: the value is valid JSON, but its shape is outside what\n * a document may be. `issues` carries the full path.\n */\nconst refuseDepth = (verb: string, at: Pending): never => {\n const message = `nests deeper than the ${MAX_DOCUMENT_DEPTH}-level document limit`;\n throw new BaerlyError(\"SchemaError\", `${verb}: document value at ${pathOf(at)} ${message}`, {\n resolution: DEPTH_RESOLUTION,\n issues: [{ path: keysOf(at), message }],\n });\n};\n\n/** Options for {@link assertDocumentValues}. */\nexport interface DocumentValuesOptions {\n /**\n * Treat an `undefined` object member as absent rather than refusing it,\n * as an update patch does: `JSON.stringify` drops the member, which is\n * the same patch as omitting it. `undefined` array elements are still\n * refused (JSON turns them into `null`).\n */\n readonly undefinedMembersAbsent?: boolean;\n}\n\n/**\n * Reject a document (or update patch) holding a value JSON cannot store\n * as written. `JSON.stringify` would silently turn `NaN` and `±Infinity`\n * into `null`, drop `undefined` members, turn `undefined` or missing array\n * elements into `null`, and reduce a `Date`, `Map`, typed array, boxed\n * primitive or class instance to a different shape; a function, symbol or\n * bigint would be dropped or throw. Each of those throws here instead,\n * naming the path of the first offending value (capped, see\n * {@link DOCUMENT_ERROR_PATH_EDGE_SEGMENTS}), as do circular references.\n * Callable or accessor `toJSON` properties (own or inherited) are refused\n * without invoking them, including on the root and on arrays. A value\n * nested deeper than {@link MAX_DOCUMENT_DEPTH} levels is refused too, as\n * `SchemaError`.\n *\n * Allowed: strings, finite numbers (`-0` included), booleans, `null` (at\n * any depth), arrays, and plain objects (prototype `Object.prototype` or\n * `null`). The root itself may be any object; its own\n * enumerable fields are checked. A top-level `_id: undefined` counts as\n * absent, as on `insert`; with `undefinedMembersAbsent`, every\n * `undefined` object member does. No `null` limits are applied.\n * Size is checked separately, on the whole post-image a write commits\n * (`assertDocumentSize`).\n *\n * The input graph must remain stable until the write completes. Ordinary\n * field getters are read during traversal; changing getters, proxies and\n * concurrent mutation are not supported as a way to supply document data.\n * This check does not snapshot the graph or execute serialization hooks.\n *\n * I/O-free. `insert` and `replace` call it on the caller's\n * document before any storage call, and `update` on each merged\n * post-image before any write; the HTTP client calls it before\n * serializing (on the patch, for `update`), because the coercions above\n * happen in `JSON.stringify` and a server only ever sees their result.\n *\n * @param verb the calling verb, used as the message prefix\n * (`\"insert\"`, `\"replace\"`, `\"update\"`, …).\n * @throws BaerlyError code=\"InvalidConfig\" — `value` holds a value outside\n * the JSON document domain. The message names its path.\n * @throws BaerlyError code=\"SchemaError\" — `value` nests an object or\n * array deeper than {@link MAX_DOCUMENT_DEPTH} levels. The message names\n * the limit and the (capped) path; `issues` holds the full path.\n */\nexport const assertDocumentValues = (\n value: unknown,\n verb: string,\n options?: DocumentValuesOptions,\n): void => {\n const undefinedMembersAbsent = options?.undefinedMembersAbsent === true;\n // Explicit work stack, so a deep document does not consume the call\n // stack. `ancestors` holds the containers on the current root-to-node\n // path; a container reached again through its own subtree is a cycle\n // (a container shared by two branches is fine, as in JSON.stringify).\n const pending: Array<Pending | { readonly exit: object }> = [\n { value, parent: undefined, key: undefined, depth: 1 },\n ];\n const ancestors = new Set<object>();\n while (pending.length > 0) {\n const next = pending.pop()!;\n if (\"exit\" in next) {\n ancestors.delete(next.exit);\n continue;\n }\n const current = next.value;\n if (typeof current === \"string\" || typeof current === \"boolean\" || current === null) {\n continue;\n }\n if (typeof current === \"number\") {\n if (Number.isFinite(current)) {\n continue;\n }\n return refuse(verb, next, String(current), NON_FINITE_RESOLUTION);\n }\n if (current === undefined) {\n // A missing array element (a hole) reads as `undefined` too.\n const elementOrMember = typeof next.key === \"number\";\n return refuse(\n verb,\n next,\n \"undefined\",\n elementOrMember ? UNDEFINED_ELEMENT_RESOLUTION : UNDEFINED_MEMBER_RESOLUTION,\n );\n }\n if (typeof current !== \"object\") {\n return refuse(verb, next, `a ${typeof current}`, NON_JSON_TYPE_RESOLUTION);\n }\n if (ancestors.has(current)) {\n return refuse(verb, next, \"a circular reference\", CIRCULAR_RESOLUTION);\n }\n if (next.depth > MAX_DOCUMENT_DEPTH) {\n return refuseDepth(verb, next);\n }\n if (hasJsonHook(current)) {\n return refuse(verb, next, \"an object with a toJSON hook\", TO_JSON_RESOLUTION);\n }\n if (Array.isArray(current)) {\n ancestors.add(current);\n pending.push({ exit: current });\n // Pushed in reverse so the first offending element is reported first.\n for (let i = current.length - 1; i >= 0; i--) {\n pending.push({ value: current[i], parent: next, key: i, depth: next.depth + 1 });\n }\n continue;\n }\n // The root may be any object: a write copies its own enumerable fields\n // (`{ ...doc }`), so only nested values must be plain. An object from\n // another realm (a `vm` context, an iframe) fails this check too.\n const prototype: unknown = Object.getPrototypeOf(current);\n if (next.parent !== undefined && prototype !== Object.prototype && prototype !== null) {\n const name = (current as { constructor?: { name?: unknown } }).constructor?.name;\n return refuse(\n verb,\n next,\n typeof name === \"string\" && name !== \"\"\n ? `a ${name}, not a plain object`\n : \"not a plain object\",\n NON_PLAIN_RESOLUTION,\n );\n }\n ancestors.add(current);\n pending.push({ exit: current });\n const keys = Object.keys(current);\n for (let i = keys.length - 1; i >= 0; i--) {\n const key = keys[i]!;\n const member = (current as Record<string, unknown>)[key];\n if (\n member === undefined &&\n (undefinedMembersAbsent || (key === \"_id\" && next.parent === undefined))\n ) {\n continue;\n }\n pending.push({ value: member, parent: next, key, depth: next.depth + 1 });\n }\n }\n};\n","/**\n * Callback-form predicate DSL. `q.eq(\"status\", \"open\").gt(\"priority\",\n * 5)` builds a {@link PredicateWire} via methods on the\n * {@link PredicateBuilder} handle. Each method appends one\n * {@link PredicateClause} to a private list and returns the same\n * handle for chaining.\n *\n * Why a builder, not imported helpers? See {@link PredicateBuilder}\n * for the locked method vocabulary. The agent cannot call\n * `q.regex(...)` because there is no `regex` method; the compiler\n * surfaces the error before the request is sent.\n *\n * Companion modules: `./normalize.ts` (object → wire),\n * `./wire.ts` (wire types).\n */\n\nimport type { DocumentData, DocumentValue } from \"../json.ts\";\nimport type { Path, PathValue, Predicate } from \"../collection-api.ts\";\n\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\n/**\n * Callback-form predicate builder. Methods append clauses and\n * return the same builder for chaining; chained calls AND-merge.\n *\n * The methods on this interface ARE the supported operator surface.\n * Vocabulary additions (`or`, `not`, `regex`, `ne`, `exists`, ...)\n * are intentionally absent — calling them is a TS2339 compile\n * error, not a runtime rejection. The algebra is conjunction-only in\n * perpetuity — see the API surface lock in\n * docs/contributing/conventions/change-discipline.md.\n *\n * @template T - the document shape the predicate is keyed against.\n */\nexport interface PredicateBuilder<T extends DocumentData = DocumentData> {\n /**\n * Strict equality on `field`. Use this for the in-callback\n * equality clauses that the object-form would also support;\n * mixing `q.eq(...)` with range / `in` clauses in one call is\n * the canonical \"mixed equality + range\" pattern.\n */\n eq<K extends Path<T>>(field: K, value: PathValue<T, K>): PredicateBuilder<T>;\n\n /**\n * Strict greater. `value` must be `string` or `number`; the\n * intersection at the type level rejects `boolean` / `null`\n * fields at the call site (`q.gt(\"done\", true)` is a TS error\n * on a `done: boolean` field).\n */\n gt<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;\n\n /** Inclusive greater. See {@link gt} for the value-type constraint. */\n gte<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;\n\n /** Strict less. See {@link gt} for the value-type constraint. */\n lt<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;\n\n /** Inclusive less. See {@link gt} for the value-type constraint. */\n lte<K extends Path<T>>(field: K, value: PathValue<T, K> & (string | number)): PredicateBuilder<T>;\n\n /**\n * Set membership. Empty array is `UnsatisfiablePredicate` at\n * normalise time — the validator emits the error eagerly so the\n * caller sees it at the `.where(...)` call site, not later.\n */\n in<K extends Path<T>>(field: K, values: ReadonlyArray<PathValue<T, K>>): PredicateBuilder<T>;\n}\n\n/**\n * Argument shape accepted by `.where(...)`. Either the object-literal\n * equality form ({@link Predicate}) or a callback that drives a\n * {@link PredicateBuilder} and returns it (the chain terminator).\n */\nexport type PredicateArg<T extends DocumentData> =\n | Predicate<T>\n | ((q: PredicateBuilder<T>) => PredicateBuilder<T>);\n\n/**\n * Build a fresh `PredicateBuilder<T>` along with the clause-list\n * cell it appends to. Internal — `./normalize.ts` drives this.\n *\n * @internal\n */\nexport const makeBuilder = <T extends DocumentData>(): {\n builder: PredicateBuilder<T>;\n clauses: PredicateClause[];\n} => {\n const clauses: PredicateClause[] = [];\n const push = (clause: PredicateClause): PredicateBuilder<T> => {\n clauses.push(clause);\n return builder;\n };\n const builder: PredicateBuilder<T> = {\n eq: (field, value) => push({ op: \"eq\", field: String(field), value: value as DocumentValue }),\n gt: (field, value) => push({ op: \"gt\", field: String(field), value: value as DocumentValue }),\n gte: (field, value) => push({ op: \"gte\", field: String(field), value: value as DocumentValue }),\n lt: (field, value) => push({ op: \"lt\", field: String(field), value: value as DocumentValue }),\n lte: (field, value) => push({ op: \"lte\", field: String(field), value: value as DocumentValue }),\n in: (field, values) =>\n push({\n op: \"in\",\n field: String(field),\n value: [...(values as ReadonlyArray<DocumentValue>)],\n }),\n };\n return { builder, clauses };\n};\n\n/**\n * Tighter wire-form type after running through the builder helper —\n * not part of the public surface; `./normalize.ts` returns a plain\n * {@link PredicateWire}.\n *\n * @internal\n */\nexport const wireFromBuilder = <T extends DocumentData>(\n cb: (q: PredicateBuilder<T>) => PredicateBuilder<T>,\n): PredicateWire => {\n const { builder, clauses } = makeBuilder<T>();\n cb(builder);\n return { clauses };\n};\n","/**\n * Object-form → wire normaliser. Walks a `Predicate<T>` object\n * literal, flattens nested sub-predicates to dotted-path `eq`\n * clauses, and returns a {@link PredicateWire}. Rejects any\n * `$`-prefixed key as `InvalidConfig` — the operator vocabulary\n * lives on the callback DSL only.\n *\n * Semantic invariant: a sub-predicate object (every value is itself\n * an object) flattens to one `eq` clause per leaf — the same\n * open-world matching today's matcher delivers at\n * `./matches.ts:matchesValue` for sub-predicates.\n *\n * Companion modules: `./builder.ts` (callback → wire),\n * `./wire.ts` (types).\n */\n\nimport { BaerlyError } from \"../errors.ts\";\nimport type { DocumentData } from \"../json.ts\";\n\nimport { type PredicateArg, type PredicateBuilder, wireFromBuilder } from \"./builder.ts\";\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\n// Inlined so the normaliser's chunk does not pull in `_internals.ts`\n// (which carries the merger/validator's heavier comparator helpers\n// the client never executes). Keeping a tiny local copy of formatPath\n// keeps the SPA bundle's predicate footprint to normalize+wire only.\nconst formatPath = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? \"<root>\" : path.map((p) => JSON.stringify(p)).join(\".\");\n\n/**\n * Walk an object-literal predicate, emit one `PredicateClause[]`.\n * Pure primitive values become `eq` clauses at the current path;\n * nested objects recurse, flattening to dotted-path clauses.\n *\n * @internal Tested via the public `normalizePredicateArg` and the\n * normalize.test.ts suite.\n */\nexport const normalizeObject = (\n obj: DocumentData,\n basePath: ReadonlyArray<string>,\n): PredicateClause[] => {\n const out: PredicateClause[] = [];\n for (const key of Object.keys(obj)) {\n const path = [...basePath, key];\n if (key.startsWith(\"$\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Unsupported predicate operator ${JSON.stringify(key)} at ${formatPath(basePath)} — operator vocabulary moved to the callback form (.where(q => q.gt(field, value))). $-keys are not accepted in object-form predicates.`,\n );\n }\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Reserved key ${JSON.stringify(key)} not allowed in a predicate at ${formatPath(basePath)}.`,\n );\n }\n const value: unknown = (obj as Record<string, unknown>)[key];\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate value at ${formatPath(path)} is ${value === null ? \"null\" : \"undefined\"} — terminal values must be string / number / boolean / nested object.`,\n );\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate value at ${formatPath(path)} is an array — match nested objects with a sub-predicate or use callback form (q.in(field, values)) for set membership.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n // Sub-predicate — recurse, accumulating dotted path. Object-form\n // predicates have NO operator vocabulary, so a nested object is\n // unambiguously a literal sub-predicate. Empty object `{}` at a\n // nested position is a match-all sub-clause: it emits zero\n // clauses for that subtree, which matches the matcher's\n // pre-redesign behaviour for `{ assignee: {} }` (an empty\n // sub-predicate accepts any non-null object actual).\n const inner = normalizeObject(value as DocumentData, path);\n for (const c of inner) {\n out.push(c);\n }\n continue;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate value at ${formatPath(path)} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate value at ${formatPath(path)} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n out.push({ op: \"eq\", field: path.join(\".\"), value: value as string | number | boolean });\n }\n return out;\n};\n\n/**\n * Dispatch the two-shape `.where(...)` argument to a\n * {@link PredicateWire}. The object-form is walked by\n * {@link normalizeObject}; the callback form is invoked with a\n * fresh {@link PredicateBuilder}.\n *\n * @internal — every consumer (`Db.collection().where`,\n * `ClientCollection.where`, `parseWhereParam`'s wire-arrival\n * path) routes through this single seam so the wire\n * format has exactly one parser path.\n */\nexport const normalizePredicateArg = <T extends DocumentData>(\n arg: PredicateArg<T>,\n): PredicateWire => {\n if (typeof arg === \"function\") {\n return wireFromBuilder<T>(arg as (q: PredicateBuilder<T>) => PredicateBuilder<T>);\n }\n return { clauses: normalizeObject(arg as DocumentData, []) };\n};\n","import type { UUID } from \"./types.ts\";\n\n/**\n * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,\n * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.\n * Lex-sortable by mint time, so it pairs well with object-storage\n * list semantics. Returns a branded {@link UUID}.\n *\n * Uses `crypto.getRandomValues` which is universally available\n * (Node 19+, Workerd, Bun, browsers).\n *\n * @example\n * ```ts\n * const id = uuidv7();\n * // e.g. \"01956cad-4cc8-7abc-9def-0123456789ab\"\n * ```\n */\nexport const uuidv7 = (): UUID => {\n const millis = Date.now();\n const rand = new Uint8Array(10);\n crypto.getRandomValues(rand);\n // Version nibble: top 4 bits of rand[0] = 0b0111 (v7). The byte\n // sits at the start of the \"version-and-rand-a\" group below.\n rand[0] = (rand[0]! & 0x0f) | 0x70;\n // Variant bits: top 2 bits of rand[2] = 0b10 (RFC 4122 variant).\n // This byte starts the \"variant-and-rand-b\" group below.\n rand[2] = (rand[2]! & 0x3f) | 0x80;\n const millisHex = millis.toString(16).padStart(12, \"0\");\n const b = Array.from(rand, (n) => n.toString(16).padStart(2, \"0\")).join(\"\");\n return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}` as UUID;\n};\n"],"mappings":";;AAOA,MAAM,uBACJ;;;;;;;;;;;AAYF,MAAa,sBAAsB,OAAsB;CACvD,IAAI,OAAO,KAAA,KAAa,OAAO,OAAO,UACpC,MAAM,IAAI,YACR,iBACA,qCAAqC,OAAO,OAAO,SAAS,OAAO,MACnE,EAAE,YAAY,qBAAqB,CACrC;AAEJ;AAEA,MAAM,wBACJ;AACF,MAAM,8BACJ;AACF,MAAM,+BACJ;AACF,MAAM,uBACJ;AACF,MAAM,2BACJ;AACF,MAAM,qBACJ;AACF,MAAM,sBACJ;AACF,MAAM,mBAAmB;;AAGzB,MAAM,eAAe,UAA2B;CAC9C,KACE,IAAI,KAAoB,OACxB,OAAO,MACP,KAAK,OAAO,eAAe,EAAE,GAC7B;EACA,MAAM,aAAa,OAAO,yBAAyB,IAAI,QAAQ;EAC/D,IAAI,eAAe,KAAA,GAGjB,OAAO,EAAE,WAAW,eAAe,OAAO,WAAW,UAAU;CAEnE;CACA,OAAO;AACT;AAWA,MAAM,aAAa;AAEn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