@gusto/baerly-storage 0.3.0 → 0.4.1

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 (141) hide show
  1. package/README.md +157 -92
  2. package/dist/API.md +64 -32
  3. package/dist/CHANGELOG.md +301 -5
  4. package/dist/RECIPES.md +125 -0
  5. package/dist/THIRD-PARTY-LICENSES.txt +22 -96
  6. package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
  7. package/dist/app-config.d.ts +1 -1
  8. package/dist/auth.d.ts +1 -1
  9. package/dist/auth.js +13 -13
  10. package/dist/auth.js.map +1 -1
  11. package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
  12. package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
  13. package/dist/baerly.js +35 -15
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +342 -0
  16. package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
  17. package/dist/client-react.d.ts +3 -3
  18. package/dist/client-react.js +4 -4
  19. package/dist/client-react.js.map +1 -1
  20. package/dist/client.d.ts +4 -4
  21. package/dist/client.js +3 -3
  22. package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
  23. package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
  24. package/dist/cloudflare.d.ts +49 -6
  25. package/dist/cloudflare.js +55 -21
  26. package/dist/cloudflare.js.map +1 -1
  27. package/dist/config-1tv0-Yzm.js +2693 -0
  28. package/dist/config-1tv0-Yzm.js.map +1 -0
  29. package/dist/constants-CfeMWQWk.js +222 -0
  30. package/dist/constants-CfeMWQWk.js.map +1 -0
  31. package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
  32. package/dist/cost-DSMIVqzL.js.map +1 -0
  33. package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
  34. package/dist/current-json-C6nhPOm1.js.map +1 -0
  35. package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
  36. package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
  37. package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
  38. package/dist/dev-vite.d.ts +9 -5
  39. package/dist/dev-vite.js +5 -4
  40. package/dist/dev-vite.js.map +1 -1
  41. package/dist/dev.d.ts +1 -1
  42. package/dist/dev.js +1 -1
  43. package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
  44. package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
  45. package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
  46. package/dist/dump-Bh5k26VQ.js.map +1 -0
  47. package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
  48. package/dist/errors-Dfa3p78c.js.map +1 -0
  49. package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
  50. package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
  51. package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
  52. package/dist/fsck-D_djMO5D.js.map +1 -0
  53. package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
  54. package/dist/http-DxM9MflO.js.map +1 -0
  55. package/dist/http.d.ts +42 -26
  56. package/dist/http.js +3 -2
  57. package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
  58. package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
  59. package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
  60. package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
  61. package/dist/index.d.ts +6 -6
  62. package/dist/index.js +4 -4
  63. package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
  64. package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
  65. package/dist/inspect-6WZ-pC7-.js.map +1 -0
  66. package/dist/key-Di6yyxFu.js +35 -0
  67. package/dist/key-Di6yyxFu.js.map +1 -0
  68. package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
  69. package/dist/log-tail-D98U1JBo.js.map +1 -0
  70. package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
  71. package/dist/maintenance-B4Dki6Ig.js.map +1 -0
  72. package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
  73. package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
  74. package/dist/maintenance-C7coQp4c.js.map +1 -0
  75. package/dist/maintenance.d.ts +3 -3
  76. package/dist/maintenance.js +3 -3
  77. package/dist/node.d.ts +168 -65
  78. package/dist/node.js +3 -2
  79. package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
  80. package/dist/normalize-rjnZLwS4.js.map +1 -0
  81. package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
  82. package/dist/observability-wzs3-BL_.js.map +1 -0
  83. package/dist/observability.d.ts +2 -2
  84. package/dist/observability.js +1 -1
  85. package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
  86. package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
  87. package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
  88. package/dist/query-rAtXNQQB.js.map +1 -0
  89. package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
  90. package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
  91. package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
  92. package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
  93. package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
  94. package/dist/restore-R-4rbciV.js.map +1 -0
  95. package/dist/runtime-spec-_GTdeSMo.js +391 -0
  96. package/dist/runtime-spec-_GTdeSMo.js.map +1 -0
  97. package/dist/s3-http-B-z8th6O.d.ts +60 -0
  98. package/dist/s3.d.ts +47 -0
  99. package/dist/s3.js +45 -0
  100. package/dist/s3.js.map +1 -0
  101. package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
  102. package/dist/shared-secret-DgEicd3x.js.map +1 -0
  103. package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
  104. package/dist/src-CYHFDrKz.js.map +1 -0
  105. package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
  106. package/dist/src-DYZ4H1aF.js.map +1 -0
  107. package/dist/src-D__mHQmQ.js +2271 -0
  108. package/dist/src-D__mHQmQ.js.map +1 -0
  109. package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
  110. package/dist/subcommand-DoDA-K7d.js.map +1 -0
  111. package/dist/time-DUqvFMHq.js +119 -0
  112. package/dist/time-DUqvFMHq.js.map +1 -0
  113. package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
  114. package/dist/usage-DBV1eQHC.js.map +1 -0
  115. package/dist/wire-izfGZDvr.js.map +1 -1
  116. package/package.json +51 -27
  117. package/dist/config-CGyBopy3.js +0 -5326
  118. package/dist/config-CGyBopy3.js.map +0 -1
  119. package/dist/cost-BZ_MDBmn.js.map +0 -1
  120. package/dist/current-json-DsN7FNY1.js.map +0 -1
  121. package/dist/dump-DPEAKub6.js.map +0 -1
  122. package/dist/errors-DOdL95kK.js.map +0 -1
  123. package/dist/fsck-RXgLOaJG.js.map +0 -1
  124. package/dist/http-Bd4byR4n.js.map +0 -1
  125. package/dist/inspect-DhI49PSi.js.map +0 -1
  126. package/dist/log-tail-DXeDkWEp.js.map +0 -1
  127. package/dist/maintenance-CWBQpZ2y.js.map +0 -1
  128. package/dist/maintenance-C_KSkVjd.js.map +0 -1
  129. package/dist/normalize-XWY25_sG.js.map +0 -1
  130. package/dist/observability-BYd-RzEx.js.map +0 -1
  131. package/dist/query-sQNO5vU_.js.map +0 -1
  132. package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
  133. package/dist/restore-DpQYef6r.js.map +0 -1
  134. package/dist/shared-secret-BJdSwpgw.js.map +0 -1
  135. package/dist/src-CWpkSbvJ.js.map +0 -1
  136. package/dist/src-D24wDpzR.js +0 -6247
  137. package/dist/src-D24wDpzR.js.map +0 -1
  138. package/dist/src-Db4-qVtM.js.map +0 -1
  139. package/dist/subcommand-CP9NY2J4.js.map +0 -1
  140. package/dist/usage-CTfDq9HR.js.map +0 -1
  141. /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
@@ -0,0 +1,119 @@
1
+ import { t as BaerlyError } from "./errors-Dfa3p78c.js";
2
+ //#region packages/protocol/src/types.ts
3
+ /**
4
+ * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle
5
+ * `<UUID>crypto.randomUUID()` throughout the codebase.
6
+ */
7
+ const uuid = () => crypto.randomUUID();
8
+ /**
9
+ * Mint a UUIDv7 — 48-bit Unix-millis prefix + 74 bits of randomness,
10
+ * formatted as a standard 8-4-4-4-12 UUID string per RFC 9562 §5.7.
11
+ * Lex-sortable by mint time, so it pairs well with object-storage
12
+ * list semantics. Returns a branded {@link UUID}.
13
+ *
14
+ * Uses `crypto.getRandomValues` which is universally available
15
+ * (Node 19+, Workerd, Bun, browsers).
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * const id = uuidv7();
20
+ * // e.g. "01956cad-4cc8-7abc-9def-0123456789ab"
21
+ * ```
22
+ */
23
+ const uuidv7 = () => {
24
+ const millis = Date.now();
25
+ const rand = /* @__PURE__ */ new Uint8Array(10);
26
+ crypto.getRandomValues(rand);
27
+ rand[0] = rand[0] & 15 | 112;
28
+ rand[2] = rand[2] & 63 | 128;
29
+ const millisHex = millis.toString(16).padStart(12, "0");
30
+ const b = Array.from(rand, (n) => n.toString(16).padStart(2, "0")).join("");
31
+ return `${millisHex.slice(0, 8)}-${millisHex.slice(8, 12)}-${b.slice(0, 4)}-${b.slice(4, 8)}-${b.slice(8, 20)}`;
32
+ };
33
+ /**
34
+ * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).
35
+ * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to
36
+ * produce an 11-char descending base-32 string with a domain of
37
+ * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).
38
+ *
39
+ * Used together with {@link timestamp} (the descending base-32
40
+ * encoding of millis-since-epoch). See {@link uint2strDesc} for the
41
+ * lex-reversal property both rely on.
42
+ */
43
+ const countKey = (number) => uint2strDesc(number, 53);
44
+ const uint2str = (num, bits) => {
45
+ const maxBase32Length = Math.ceil(bits / 5);
46
+ return num.toString(32).padStart(maxBase32Length, "0");
47
+ };
48
+ /**
49
+ * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.
50
+ * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare
51
+ * lex against each other.
52
+ *
53
+ * **Order-reversal property:** for any pair of integers `a < b` (with
54
+ * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`
55
+ * lexicographically. Composed into an LSN of shape
56
+ * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and
57
+ * `<seq>` use this encoder), a forward `Storage.list(prefix)`
58
+ * returns log entries in reverse-causal order — newer entries first.
59
+ *
60
+ * This is the structural property the read path leans on:
61
+ * `ListObjectsV2` is forward-only on S3, but the descending encoding
62
+ * makes "fetch the K newest entries" a single bounded LIST with
63
+ * `maxKeys=K` instead of a full-population LIST + in-memory reverse.
64
+ *
65
+ * Behaviourally verified across randomized populations in
66
+ * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified
67
+ * bytes-listed reduction is in
68
+ * `docs/spec/attachments/lsn-reverse-walk-baseline.json`
69
+ * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:
70
+ * `docs/spec/sync-protocol.md` §"LSNs, wall clocks, and downstream
71
+ * consumers".
72
+ */
73
+ const uint2strDesc = (num, bits) => {
74
+ return uint2str(Math.pow(2, bits) - 1 - num, bits);
75
+ };
76
+ const str2uintDesc = (str, bits) => {
77
+ return Math.pow(2, bits) - 1 - parseInt(str, 32);
78
+ };
79
+ //#endregion
80
+ //#region packages/protocol/src/time.ts
81
+ /**
82
+ * Encode an epoch-millis instant as a lexicographically-DEScending
83
+ * base-32 key (newer sorts first). The load-bearing LSN ordering
84
+ * primitive — see {@link uint2strDesc}.
85
+ *
86
+ * `epoch` is REQUIRED and validated. There is no default: an argless
87
+ * call used to encode `0`, which descending-sorts as the most-ancient
88
+ * instant and would silently invert ordering. A non-finite, negative,
89
+ * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)
90
+ * would corrupt the key silently rather than fail loud, so it throws
91
+ * `Internal` instead — this is an invariant violation, not caller config
92
+ * (the only legitimate argument is `Date.now()`).
93
+ */
94
+ const timestamp = (epoch) => {
95
+ if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** 42) throw new BaerlyError("Internal", `timestamp(): epoch must be a non-negative integer < 2^42 (got ${epoch})`);
96
+ return uint2strDesc(epoch, 42);
97
+ };
98
+ /**
99
+ * Delay for `ms` milliseconds, with optional cancellation. If
100
+ * `signal` aborts before the delay elapses, the returned promise
101
+ * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry
102
+ * loop so shutdown can interrupt an in-flight backoff instead of
103
+ * waiting for it to complete.
104
+ */
105
+ const delay = (ms, signal) => new Promise((resolve, reject) => {
106
+ if (signal?.aborted) {
107
+ reject(signal.reason);
108
+ return;
109
+ }
110
+ const timer = setTimeout(resolve, ms);
111
+ signal?.addEventListener("abort", () => {
112
+ clearTimeout(timer);
113
+ reject(signal.reason);
114
+ }, { once: true });
115
+ });
116
+ //#endregion
117
+ export { uuid as a, str2uintDesc as i, timestamp as n, uuidv7 as o, countKey as r, delay as t };
118
+
119
+ //# sourceMappingURL=time-DUqvFMHq.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time-DUqvFMHq.js","names":[],"sources":["../packages/protocol/src/types.ts","../packages/protocol/src/time.ts"],"sourcesContent":["import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\ndeclare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. content versions are both strings, but\n * using the wrong one corrupts the per-collection log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A v4 UUID minted by this client. Used as session IDs and content\n * identifiers in non-versioned mode.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * SHA-256 content digest, lowercase hex truncated to\n * `VERSION_HEX_LENGTH` (32 chars). Minted by\n * `versionFromContent` in `useVersioning=false` mode and used as\n * the `<key>@<version>` suffix in content keys.\n *\n * The synthetic `local-${op}` placeholder used for in-flight\n * optimistic updates also wears this brand — it never round-trips\n * to S3, only flows through local optimistic state.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\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\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, COUNT_BIT_WIDTH);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"LSNs, wall clocks, and downstream\n * consumers\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. Used by `S3HttpStorage`'s retry\n * loop so shutdown can interrupt an in-flight backoff instead of\n * waiting for it to complete.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\n );\n });\n"],"mappings":";;;;;;AAwCA,MAAa,aAAmB,OAAO,WAAW;;;;;;;;;;;;;;;;AAiBlD,MAAa,eAAqB;CAChC,MAAM,SAAS,KAAK,IAAI;CACxB,MAAM,uBAAO,IAAI,WAAW,EAAE;CAC9B,OAAO,gBAAgB,IAAI;CAG3B,KAAK,KAAM,KAAK,KAAM,KAAQ;CAG9B,KAAK,KAAM,KAAK,KAAM,KAAQ;CAC9B,MAAM,YAAY,OAAO,SAAS,EAAE,CAAC,CAAC,SAAS,IAAI,GAAG;CACtD,MAAM,IAAI,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,E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
+ import { r as parseBucketUri, t as loadAppConfig } from "./config-1tv0-Yzm.js";
3
3
  import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
- import { n as defineBaerlySubcommand } from "./subcommand-CP9NY2J4.js";
5
- /** Number of trailing log entries the estimator reads per collection. */
6
- const SAMPLE_SIZE = 120;
4
+ import { a as TENANT_ARG, i as JSON_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
7
5
  /** Build the canonical `current.json` key for one collection. */
8
6
  const currentJsonKeyFor = (app, tenant, collection) => `app/${app}/tenant/${tenant}/manifests/${collection}/current.json`;
9
7
  /** Derive the `collectionPrefix` (everything before `/current.json`). */
@@ -103,7 +101,7 @@ const readCommitTsBatched = async (storage, keys) => {
103
101
  * root). Threaded through by `baerly inspect`.
104
102
  */
105
103
  const estimateWritesPerMin = async (storage, app, tenant, collection, opts = {}) => {
106
- const sampleSize = opts.sampleSize ?? SAMPLE_SIZE;
104
+ const sampleSize = opts.sampleSize ?? 120;
107
105
  const logPrefix = `${`${opts.keyPrefix ?? ""}${collectionPrefixOf(currentJsonKeyFor(app, tenant, collection))}`}/log/`;
108
106
  let allKeys;
109
107
  try {
@@ -251,22 +249,9 @@ const USAGE_ARGS = {
251
249
  description: "Override `baerly.config.ts:target`. One of \"cloudflare\" | \"node\".",
252
250
  valueHint: "target"
253
251
  },
254
- app: {
255
- type: "string",
256
- required: false,
257
- description: "Application name segment (defaults to baerly.config.ts).",
258
- valueHint: "app"
259
- },
260
- tenant: {
261
- type: "string",
262
- required: false,
263
- description: "Tenant name segment (defaults to baerly.config.ts).",
264
- valueHint: "tenant"
265
- },
266
- json: {
267
- type: "boolean",
268
- description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
269
- }
252
+ app: APP_ARG,
253
+ tenant: TENANT_ARG,
254
+ json: JSON_ARG
270
255
  };
271
256
  const SEVERITY_GLYPH = {
272
257
  ok: "✓",
@@ -336,4 +321,4 @@ bundle.run;
336
321
  //#endregion
337
322
  export { estimateWritesPerMin, usageCmd };
338
323
 
339
- //# sourceMappingURL=usage-CTfDq9HR.js.map
324
+ //# sourceMappingURL=usage-DBV1eQHC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-DBV1eQHC.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` costs ≈ N × (1 LIST + up to 120 GETs per collection)\n * — strictly linear. See `docs/spec/attachments/collection-fanout-baseline.json`\n * (`pnpm bench:collection-fanout`). Neither the ~100 figure nor the\n * >10 GB/tenant storage line is a code constant here; both are cost\n * signals documented 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 pending the follow-up work in\n * `docs/followups/agent-friendliness.md` entry 10.\n *\n * Why GET each entry instead of relying on list-time\n * `Last-Modified`: `MemoryStorage` (the test backend) intentionally\n * does NOT surface `lastModified` on `list()`, and the\n * cross-backend story stays uniform if we always read `commit_ts`\n * from the `LogEntry` body. Sample size is bounded (`SAMPLE_SIZE`\n * GETs per collection), so the cost is acceptable for an opt-in\n * operator command.\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 { BaerlyError, decodeJsonBytes, type LogEntry, type Storage } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { loadAppConfig } from \"../config.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 * List every log key under `${collectionPrefix}/log/` for one collection.\n * Returns the keys in **chronological order** (oldest seq first).\n *\n * The on-bucket key shape is `<collectionPrefix>/log/<seq>.json` where\n * `<seq>` is a base-10 integer minted by `Writer`. Lex-ascending\n * key order disagrees with numeric seq order past seq=9 (`log/10.json`\n * sorts before `log/2.json`), so we parse the trailing integer out of\n * each key and sort numerically.\n *\n * Caller is expected to slice the trailing N entries — the writes/min\n * estimator only needs the most recent sample.\n */\n// Parse the `<seq>` integer from a `<logPrefix>/<seq>.json` key. Returns\n// `NaN` when the basename isn't a finite integer (the caller filters\n// those out before sorting). Hoisted out of {@link listLogKeysSortedBySeq}\n// so a function instance isn't allocated per list entry.\nconst seqOfLogKey = (key: string): number => {\n const slash = key.lastIndexOf(\"/\");\n const dot = key.lastIndexOf(\".json\");\n if (slash === -1 || dot === -1 || dot <= slash) {\n return Number.NaN;\n }\n const seqStr = key.slice(slash + 1, dot);\n const n = Number.parseInt(seqStr, 10);\n return Number.isFinite(n) ? n : Number.NaN;\n};\n\nconst listLogKeysSortedBySeq = async (\n storage: Storage,\n logPrefix: string,\n): Promise<readonly string[]> => {\n const keys: string[] = [];\n for await (const entry of storage.list(logPrefix)) {\n keys.push(entry.key);\n }\n return keys\n .filter((k) => Number.isFinite(seqOfLogKey(k)))\n .toSorted((a, b) => seqOfLogKey(a) - seqOfLogKey(b));\n};\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(\n \"InvalidResponse\",\n `usage scan: log entry at ${key} is not valid JSON`,\n 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 the last `sampleSize` log entries (default `SAMPLE_SIZE`)\n * for `<app>/<tenant>/<collection>`, 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 listing. 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 inspect`.\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 collectionPrefix = `${keyPrefix}${collectionPrefixOf(currentJsonKeyFor(app, tenant, collection))}`;\n const logPrefix = `${collectionPrefix}/log/`;\n\n let allKeys: readonly string[];\n try {\n allKeys = await listLogKeysSortedBySeq(storage, logPrefix);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"NetworkError\",\n `usage scan: list ${logPrefix} failed: ${(error as Error).message}`,\n error,\n );\n }\n const sample = allKeys.slice(Math.max(0, allKeys.length - sampleSize));\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 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 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 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\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 // from `--bucket=<uri>`; full CF wiring is a follow-up — see\n // `docs/followups/agent-friendliness.md` entry 10.\n findings.push({\n severity: \"info\",\n check: \"usage.cloudflare\",\n message:\n \"baerly admin usage is not yet wired for --target=cloudflare. See docs/followups/agent-friendliness.md entry 10.\",\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":";;;;;AA0GA,MAAa,qBAAqB,KAAa,QAAgB,eAC7D,OAAO,IAAI,UAAU,OAAO,aAAa,WAAW;;AAGtD,MAAa,sBAAsB,mBACjC,eAAe,MAAM,GAAG,eAAe,YAAY,GAAG,CAAC;;;;;;;;;;;;;;AAmBzD,MAAM,eAAe,QAA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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"}
@@ -1 +1 @@
1
- {"version":3,"file":"wire-izfGZDvr.js","names":[],"sources":["../packages/protocol/src/query/wire.ts"],"sourcesContent":["/**\n * Wire-format predicate types. A predicate normalises to a flat list\n * of {@link PredicateClause} records; the server, client, matcher,\n * merger, and validator all consume the wire form. Object-literal\n * (`Predicate<T>`) and callback (`PredicateBuilder<T>`) forms compile\n * to this shape via `./normalize.ts` / `./builder.ts`.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/**\n * Locked operator vocabulary. Methods on {@link PredicateBuilder}\n * map 1:1 to these names; the validator rejects any other.\n *\n * `eq` — strict equality.\n * `gt` / `gte` / `lt` / `lte` — scalar range. Bounds must be `string`\n * or finite `number`. Type-mismatched actuals are always-miss.\n * `in` — set membership. Empty array → `UnsatisfiablePredicate`.\n */\nexport type PredicateOpName = \"eq\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"in\";\n\n/**\n * One clause in a normalised predicate. `field` is a top-level key\n * or a dotted path. `value` is an array iff `op === \"in\"`.\n *\n * `op: \"eq\"` on a primitive `value` is plain equality. The\n * normaliser flattens nested literal sub-predicates\n * (`{ assignee: { team: \"x\" } }`) to dotted-path `eq` clauses\n * (`{op:\"eq\", field:\"assignee.team\", value:\"x\"}`), so an `eq`\n * value at the wire level is never a nested non-primitive object\n * — only callback-form `q.eq(\"nested\", { ... })` could produce\n * one, and that requires the type system to allow it at the call\n * site.\n */\nexport interface PredicateClause {\n readonly op: PredicateOpName;\n readonly field: string;\n readonly value: DocumentValue | ReadonlyArray<DocumentValue>;\n}\n\n/**\n * Normalised predicate envelope. The wire form is a flat list of\n * clauses; multiple clauses across all fields AND together. The\n * empty wire `{ clauses: [] }` matches every document.\n *\n * Wire mirror on the HTTP surface: `?where=` carries the JSON\n * encoding of this object. See `packages/server/API.md` for the\n * literal example.\n */\nexport interface PredicateWire {\n readonly clauses: ReadonlyArray<PredicateClause>;\n}\n\n/** @internal Empty match-all wire — re-used to avoid re-allocating. */\nexport const EMPTY_PREDICATE_WIRE: PredicateWire = { clauses: [] };\n"],"mappings":";;AAsDA,MAAa,uBAAsC,EAAE,SAAS,CAAC,EAAE"}
1
+ {"version":3,"file":"wire-izfGZDvr.js","names":[],"sources":["../packages/protocol/src/query/wire.ts"],"sourcesContent":["/**\n * Wire-format predicate types. A predicate normalises to a flat list\n * of {@link PredicateClause} records; the server, client, matcher,\n * merger, and validator all consume the wire form. Object-literal\n * (`Predicate<T>`) and callback (`PredicateBuilder<T>`) forms compile\n * to this shape via `./normalize.ts` / `./builder.ts`.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/**\n * Runtime mirror of {@link PredicateOpName}. The type derives from this\n * tuple so the value is the single source of truth: the spec generator\n * and the drift gate enumerate `PREDICATE_OPS`, and tsgo rejects any\n * member added to the type-union without a matching tuple entry.\n */\nexport const PREDICATE_OPS = [\"eq\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"] as const;\n\n/**\n * Locked operator vocabulary. Methods on {@link PredicateBuilder}\n * map 1:1 to these names; the validator rejects any other.\n *\n * `eq` — strict equality.\n * `gt` / `gte` / `lt` / `lte` — scalar range. Bounds must be `string`\n * or finite `number`. Type-mismatched actuals are always-miss.\n * `in` — set membership. Empty array → `UnsatisfiablePredicate`.\n */\nexport type PredicateOpName = (typeof PREDICATE_OPS)[number];\n\n/**\n * One clause in a normalised predicate. `field` is a top-level key\n * or a dotted path. `value` is an array iff `op === \"in\"`.\n *\n * `op: \"eq\"` on a primitive `value` is plain equality. The\n * normaliser flattens nested literal sub-predicates\n * (`{ assignee: { team: \"x\" } }`) to dotted-path `eq` clauses\n * (`{op:\"eq\", field:\"assignee.team\", value:\"x\"}`), so an `eq`\n * value at the wire level is never a nested non-primitive object\n * — only callback-form `q.eq(\"nested\", { ... })` could produce\n * one, and that requires the type system to allow it at the call\n * site.\n */\nexport interface PredicateClause {\n readonly op: PredicateOpName;\n readonly field: string;\n readonly value: DocumentValue | ReadonlyArray<DocumentValue>;\n}\n\n/**\n * Normalised predicate envelope. The wire form is a flat list of\n * clauses; multiple clauses across all fields AND together. The\n * empty wire `{ clauses: [] }` matches every document.\n *\n * Wire mirror on the HTTP surface: `?where=` carries the JSON\n * encoding of this object. See `packages/server/API.md` for the\n * literal example.\n */\nexport interface PredicateWire {\n readonly clauses: ReadonlyArray<PredicateClause>;\n}\n\n/** @internal Empty match-all wire — re-used to avoid re-allocating. */\nexport const EMPTY_PREDICATE_WIRE: PredicateWire = { clauses: [] };\n"],"mappings":";;AA8DA,MAAa,uBAAsC,EAAE,SAAS,CAAC,EAAE"}
package/package.json CHANGED
@@ -1,18 +1,22 @@
1
1
  {
2
2
  "name": "@gusto/baerly-storage",
3
- "version": "0.3.0",
4
- "description": "Vendorless document database that runs over any S3-compatible storage API.",
3
+ "version": "0.4.1",
4
+ "description": "Document database for S3 and Cloudflare R2 that runs in your request handler — tiny, LLM-friendly TypeScript API, no database server",
5
5
  "keywords": [
6
+ "append-only-log",
7
+ "aws-s3",
6
8
  "cloudflare-workers",
7
- "database",
9
+ "content-addressable-storage",
8
10
  "document-database",
9
- "edge",
11
+ "edge-computing",
10
12
  "http-api",
13
+ "minio",
14
+ "multi-tenant",
11
15
  "nosql",
16
+ "object-storage",
12
17
  "r2",
13
18
  "s3",
14
19
  "s3-compatible",
15
- "self-hosted",
16
20
  "serverless",
17
21
  "typescript"
18
22
  ],
@@ -56,6 +60,10 @@
56
60
  "types": "./dist/node.d.ts",
57
61
  "import": "./dist/node.js"
58
62
  },
63
+ "./s3": {
64
+ "types": "./dist/s3.d.ts",
65
+ "import": "./dist/s3.js"
66
+ },
59
67
  "./maintenance": {
60
68
  "types": "./dist/maintenance.d.ts",
61
69
  "import": "./dist/maintenance.js"
@@ -89,32 +97,36 @@
89
97
  "access": "public"
90
98
  },
91
99
  "dependencies": {
92
- "@logtape/logtape": "2.1.3"
100
+ "@logtape/logtape": "2.2.2"
93
101
  },
94
102
  "devDependencies": {
103
+ "@arethetypeswrong/cli": "^0.18.4",
95
104
  "@changesets/cli": "^2.31.0",
96
105
  "@cloudflare/vitest-pool-workers": "0.16.14",
97
- "@cloudflare/workers-types": "^4.20260610.1",
106
+ "@cloudflare/workers-types": "^4.20260630.1",
98
107
  "@fast-check/vitest": "^0.4.1",
99
- "@hono/node-server": "^2.0.4",
108
+ "@hono/node-server": "^2.0.6",
100
109
  "@stryker-mutator/core": "9.6.1",
101
110
  "@stryker-mutator/vitest-runner": "9.6.1",
102
111
  "@testing-library/react": "^16.3.2",
103
- "@types/node": "^25.9.2",
112
+ "@types/node": "^26.0.1",
104
113
  "@types/pg": "^8.20.0",
105
114
  "@types/react": "^19.2.17",
106
115
  "@types/react-dom": "^19.2.3",
107
116
  "@typescript/native-preview": "7.0.0-dev.20260610.1",
108
117
  "@vitest/coverage-v8": "^4.1.8",
118
+ "ajv": "^8.20.0",
109
119
  "aws4fetch": "1.0.20",
110
120
  "esbuild": "^0.28.1",
111
121
  "execa": "^9.6.1",
112
122
  "fast-check": "^4.8.0",
113
- "happy-dom": "^20.10.2",
123
+ "happy-dom": "^20.10.6",
114
124
  "lefthook": "^2.1.9",
125
+ "mermaid": "^11.15.0",
115
126
  "oxfmt": "^0.54.0",
116
127
  "oxlint": "^1.69.0",
117
128
  "pg": "^8.21.0",
129
+ "publint": "^0.3.21",
118
130
  "react": "^19.2.7",
119
131
  "react-dom": "^19.2.7",
120
132
  "remark-cli": "^12.0.1",
@@ -123,13 +135,13 @@
123
135
  "rolldown": "^1.1.0",
124
136
  "rolldown-plugin-dts": "^0.25.2",
125
137
  "rollup-license-plugin": "3.2.1",
126
- "vite": "^8.0.16",
127
- "vitest": "^4.1.8",
138
+ "vite": "^8.1.2",
139
+ "vitest": "^4.1.9",
128
140
  "yaml": "2.9.0",
141
+ "@baerly/dev": "0.1.0",
142
+ "@baerly/protocol": "0.1.0",
129
143
  "@baerly/adapter-node": "0.1.0",
130
144
  "@baerly/adapter-cloudflare": "0.1.0",
131
- "@baerly/protocol": "0.1.0",
132
- "@baerly/dev": "0.1.0",
133
145
  "@baerly/client": "0.1.0",
134
146
  "@baerly/server": "0.1.0"
135
147
  },
@@ -154,7 +166,7 @@
154
166
  },
155
167
  "scripts": {
156
168
  "typecheck": "tsgo --noEmit",
157
- "pretest": "pnpm run build",
169
+ "pretest": "node scripts/build-if-needed.mjs",
158
170
  "test": "vitest run --project=default",
159
171
  "test:agent": "vitest run --project=default --reporter=minimal --silent=passed-only",
160
172
  "test:one": "pnpm run build && vitest run --project=default",
@@ -167,32 +179,41 @@
167
179
  "baerly": "node dist/baerly.js",
168
180
  "release": "node scripts/publish.mjs",
169
181
  "changeset": "changeset",
170
- "changeset:version": "changeset version && rm -f packages/create-baerly-storage/CHANGELOG.md",
171
- "format": "oxfmt tests packages",
172
- "format:check": "oxfmt --check tests packages",
182
+ "changeset:version": "changeset version && node scripts/gen-spec.ts && rm -f packages/create-baerly-storage/CHANGELOG.md",
183
+ "format": "oxfmt .",
184
+ "format:check": "oxfmt --check .",
173
185
  "lint": "oxlint tests packages",
174
186
  "test:randomize": "FC_NUM_RUNS=10000 vitest run --project=default",
175
- "test:fuzz-phase5": "FC_NUM_RUNS=10000 vitest run --project=default tests/integration/phase5-crash-fuzz.test.ts",
187
+ "test:fuzz-maintenance": "FC_NUM_RUNS=10000 vitest run --project=default tests/integration/maintenance-crash-fuzz.test.ts",
176
188
  "test:adapter-cloudflare": "ADAPTER_CLOUDFLARE=1 vitest run --project=cloudflare-pool",
177
189
  "test:http-conformance": "vitest run --project=default tests/integration/http-conformance.test.ts",
178
190
  "test:adapter-node": "MINIO=1 vitest run --project=default packages/adapter-node",
179
191
  "test:adapters": "pnpm test:adapter-cloudflare && pnpm test:adapter-node",
192
+ "test:parity": "vitest run --project=default packages/protocol/src/storage/memory.test.ts packages/dev/src/local-fs.test.ts packages/adapter-node/src/s3-http.conformance.test.ts tests/integration/collection-api.test.ts tests/integration/randomized.test.ts",
180
193
  "test:manual-e2e": "vitest run --project=default manual-e2e/cloudflare/e2e.test.ts manual-e2e/node/e2e.test.ts",
181
194
  "test:mutate": "stryker run",
182
195
  "mutate:survivors": "node scripts/mutation-survivors.mjs",
183
196
  "test:coverage:protocol": "vitest run --config stryker.vitest.config.ts --coverage --coverage.provider=v8 --coverage.include='packages/protocol/src/**/*.ts' --coverage.exclude='**/*.test.ts' --coverage.exclude='**/*.test-d.ts' --coverage.exclude='**/index.ts'",
184
197
  "gate:day-one": "vitest run --project=default tests/integration/day-one-handshake.test.ts",
198
+ "gen:spec": "node scripts/gen-spec.ts",
199
+ "gen:version-matrix": "node scripts/check-version-matrix.ts --write",
185
200
  "bundle-sizes": "node scripts/bundle-sizes.mjs",
186
- "verify": "pnpm run typecheck && pnpm run verify:examples && pnpm run lint && pnpm run format:check && node scripts/add-ts-extensions.mjs --check && node scripts/lint-use-query.mjs && node scripts/lint-package-layers.mjs && pnpm run verify:docs",
187
- "verify:agent": "tsgo --noEmit --pretty false && pnpm run verify:examples && oxlint --format=unix --quiet tests packages && pnpm run format:check && node scripts/add-ts-extensions.mjs --check && node scripts/lint-use-query.mjs && node scripts/lint-package-layers.mjs && pnpm run verify:docs",
188
- "verify:docs": "node scripts/verify-docs.mjs && remark docs --quiet --frail --no-stdout",
189
- "verify:doc-links": "remark docs --quiet --frail --no-stdout",
201
+ "check:exports": "node scripts/check-exports.mjs",
202
+ "check:publint": "node scripts/check-publint.mjs",
203
+ "verify:package": "node scripts/build-if-needed.mjs && BAERLY_SKIP_BUILD=1 pnpm run check:exports && BAERLY_SKIP_BUILD=1 pnpm run check:publint",
204
+ "verify:rest": "pnpm run verify:examples && pnpm run format:check && node scripts/add-ts-extensions.mjs --check && node scripts/lint-use-query.mjs && node scripts/lint-package-layers.mjs && node scripts/lint-format-coverage.mjs && node scripts/check-spec-drift.ts && node scripts/check-version-matrix.ts",
205
+ "verify:code": "pnpm run typecheck && pnpm run lint && pnpm run verify:rest",
206
+ "verify": "pnpm run verify:code && pnpm run verify:docs",
207
+ "verify:agent": "tsgo --noEmit --pretty false && oxlint --format=unix --quiet tests packages && pnpm run verify:rest && pnpm run verify:docs",
208
+ "verify:spec": "node scripts/check-spec-drift.ts",
209
+ "verify:version-matrix": "node scripts/check-version-matrix.ts",
210
+ "verify:docs": "node scripts/verify-docs.mjs && node scripts/verify-docs-taxonomy.mjs && remark . --quiet --frail --no-stdout && node scripts/verify-mermaid.mjs",
211
+ "verify:doc-taxonomy": "node scripts/verify-docs-taxonomy.mjs",
212
+ "verify:doc-links": "remark . --quiet --frail --no-stdout",
213
+ "verify:mermaid": "node scripts/verify-mermaid.mjs",
190
214
  "verify:examples": "pnpm --filter minimal-cloudflare typecheck && pnpm --filter minimal-node typecheck && pnpm --filter react-cloudflare typecheck && pnpm --filter react-node typecheck",
191
215
  "dev:storage": "docker compose up -d --wait",
192
216
  "dev:storage:stop": "docker compose down",
193
- "verdaccio:reset": "./scripts/verdaccio-reset.sh",
194
- "verdaccio:publish": "node scripts/verdaccio-publish.mjs",
195
- "dlx:bust-cache": "node scripts/dlx-bust-cache.mjs",
196
217
  "worktree:bootstrap": "node scripts/worktree-bootstrap.mjs",
197
218
  "bench:r2": "node --import ./bench/register-hooks.mjs bench/r2-contention.ts",
198
219
  "bench:r2:matrix": "node --import ./bench/register-hooks.mjs bench/r2-contention-matrix.ts",
@@ -202,6 +223,9 @@
202
223
  "bench:load:matrix": "node --import ./bench/register-hooks.mjs bench/load-harness/matrix.ts",
203
224
  "bench:lsn-reverse-walk": "node --import ./bench/register-hooks.mjs bench/lsn-reverse-walk.ts",
204
225
  "bench:fold-cost": "node --import ./bench/register-hooks.mjs bench/fold-cost.ts",
205
- "bench:maintenance-backlog": "node --import ./bench/register-hooks.mjs bench/maintenance-backlog.ts"
226
+ "bench:maintenance-backlog": "node --import ./bench/register-hooks.mjs bench/maintenance-backlog.ts",
227
+ "bench:amortized-write-cost": "node --import ./bench/register-hooks.mjs bench/amortized-write-cost.ts",
228
+ "bench:write-amp-stress": "node --import ./bench/register-hooks.mjs bench/write-amp-stress.ts",
229
+ "bench:collection-fanout": "node --import ./bench/register-hooks.mjs bench/collection-fanout.ts"
206
230
  }
207
231
  }