@gusto/baerly-storage 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-ypCm3zjt.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +9 -14
  53. package/dist/dev-vite.js +11 -10
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/{gcs-admin-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-DP3ClvcA.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-C4qgiXSg.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/{sha256-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-BV68pqwJ.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-BMZR8o6U.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -0,0 +1,196 @@
1
+ import { a as isJsonMode, r as emitSuccess, s as BaerlyError } from "./baerly.js";
2
+ import { C as MAINTENANCE_PROFILE_NODE, S as MAINTENANCE_PROFILE_CF_PAID, n as parseBucketUri, x as MAINTENANCE_PROFILE_CF_FREE } from "./config-DEzInG6M.js";
3
+ import { c as readCurrentJson } from "./current-json-CC6lE4Aj.js";
4
+ import { r as probeTailFrom } from "./log-tail-DWJbneBF.js";
5
+ import { n as isFoldViable, r as parseMaintenanceEnv } from "./maintenance-Dd-Yakqj.js";
6
+ import { n as loadMaterialisedView } from "./plan-BvQbaNMe.js";
7
+ import { a as TENANT_ARG, c as defineBaerlySubcommand, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, t as APP_ARG } from "./subcommand-BLoF66dG.js";
8
+ // src/inspect.ts
9
+ const INSPECT_ARGS = {
10
+ bucket: BUCKET_ARG,
11
+ app: APP_ARG,
12
+ tenant: TENANT_ARG,
13
+ collection: COLLECTION_ARG,
14
+ profile: {
15
+ type: "enum",
16
+ options: [
17
+ "cf-free",
18
+ "cf-paid",
19
+ "node"
20
+ ],
21
+ required: false,
22
+ description: "Host profile for the fold_gate verdict: cf-free | cf-paid | node. Default: all three."
23
+ },
24
+ json: {
25
+ ...JSON_ARG,
26
+ description: `${JSON_ARG.description}. A storage-format diagnostic: fields follow the storage format and can change in any release`
27
+ }
28
+ };
29
+ /** The host profiles `BAERLY_MAINTENANCE_PROFILE` / the adapters select, keyed by name. */
30
+ const HOST_PROFILES = {
31
+ "cf-free": MAINTENANCE_PROFILE_CF_FREE,
32
+ "cf-paid": MAINTENANCE_PROFILE_CF_PAID,
33
+ node: MAINTENANCE_PROFILE_NODE
34
+ };
35
+ /**
36
+ * The write-tick runner's pre-fold projection (`isFoldViable`), evaluated
37
+ * off stored figures for one profile. Bytes is labelled first, matching
38
+ * the runner's `dimension` label.
39
+ */
40
+ const foldGateVerdict = (cur, liveLogTail, profile, maxFoldBytes) => {
41
+ const ceilingBytes = maxFoldBytes ?? profile.maxFoldBytes;
42
+ const ceilingRows = profile.maxFoldRows;
43
+ let verdict = "open";
44
+ if (!isFoldViable(cur.snapshot_bytes, cur.snapshot_rows, {
45
+ maxFoldBytes: ceilingBytes,
46
+ maxFoldRows: ceilingRows
47
+ })) verdict = cur.snapshot_bytes <= ceilingBytes ? "closed:rows" : "closed:bytes";
48
+ return {
49
+ verdict,
50
+ ceiling_bytes: ceilingBytes,
51
+ ceiling_rows: ceilingRows,
52
+ retention_stalled: verdict !== "open" && liveLogTail >= 50
53
+ };
54
+ };
55
+ /** Stderr warning for a maintenance env value the adapters would reject. */
56
+ const warnRejectedEnv = (error) => {
57
+ const message = error instanceof Error ? error.message : String(error);
58
+ process.stderr.write(`baerly inspect: warning: ${message} — the adapters reject this value with InvalidConfig on every request that reads it.\n`);
59
+ };
60
+ /**
61
+ * The maintenance env as `inspect` reports it, read from the CLI's own
62
+ * environment. Each variable goes through {@link parseMaintenanceEnv} on its
63
+ * own, so a value the adapters would reject (`BAERLY_MAINTENANCE_DISABLE=off`,
64
+ * a non-positive `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`) becomes a stderr warning
65
+ * rather than failing a read-only report, and never masks the other variable.
66
+ * A rejected `MAX_FOLD_BYTES` falls back to each profile's default `C`.
67
+ */
68
+ const readInspectMaintenanceEnv = (readEnv) => {
69
+ const only = (key) => (k) => k === key ? readEnv(k) : void 0;
70
+ let maxFoldBytes;
71
+ try {
72
+ maxFoldBytes = parseMaintenanceEnv(only("BAERLY_MAINTENANCE_MAX_FOLD_BYTES")).maxFoldBytes;
73
+ } catch (error) {
74
+ warnRejectedEnv(error);
75
+ }
76
+ let maintenance;
77
+ try {
78
+ maintenance = parseMaintenanceEnv(only("BAERLY_MAINTENANCE_DISABLE")).disabled ? "disabled" : "enabled";
79
+ } catch (error) {
80
+ warnRejectedEnv(error);
81
+ maintenance = "invalid-config";
82
+ }
83
+ return {
84
+ maxFoldBytes,
85
+ maintenance
86
+ };
87
+ };
88
+ const countListEntries = async (storage, prefix) => {
89
+ let count = 0;
90
+ const keys = [];
91
+ for await (const entry of storage.list(prefix)) {
92
+ count++;
93
+ keys.push(entry.key);
94
+ }
95
+ return {
96
+ count,
97
+ keys
98
+ };
99
+ };
100
+ const renderText = (r, collection) => {
101
+ const lines = [];
102
+ lines.push(`baerly inspect ${collection}`);
103
+ lines.push(` current.json: ${r.currentJsonKey}`);
104
+ lines.push(` schema_version: ${r.schema_version}`);
105
+ lines.push(` tail_hint (stored): ${r.tail_hint}`);
106
+ lines.push(` discovered_tail: ${r.discovered_tail}`);
107
+ lines.push(` log_seq_start: ${r.log_seq_start}`);
108
+ lines.push(` live_log_tail: ${r.live_log_tail}`);
109
+ lines.push(` snapshot: ${r.snapshot ?? "(none)"}`);
110
+ lines.push(` snapshot_bytes: ${r.snapshot_bytes}`);
111
+ lines.push(` snapshot_rows: ${r.snapshot_rows}`);
112
+ for (const [name, g] of Object.entries(r.fold_gate)) {
113
+ const label = `fold_gate (${name}):`.padEnd(21);
114
+ const stalled = g.retention_stalled ? " retention_stalled" : "";
115
+ lines.push(` ${label}${g.verdict} (C=${g.ceiling_bytes} E=${g.ceiling_rows})${stalled}`);
116
+ }
117
+ lines.push(` maintenance: ${r.maintenance}`);
118
+ lines.push(` writer_fence: epoch=${r.writer_fence.epoch} owner=${JSON.stringify(r.writer_fence.owner)} claimed_at=${JSON.stringify(r.writer_fence.claimed_at)}`);
119
+ lines.push(` materialised_rows: ${r.materialised_rows}`);
120
+ lines.push(` status: ${r.status}`);
121
+ if (r.errors.length > 0) for (const e of r.errors) lines.push(` error: ${e}`);
122
+ return lines.join("\n") + "\n";
123
+ };
124
+ const bundle = defineBaerlySubcommand({
125
+ name: "inspect",
126
+ meta: { description: "Read-only summary of one collection's snapshot + log state." },
127
+ args: INSPECT_ARGS,
128
+ handler: async (args, ctx) => {
129
+ const bucket = await parseBucketUri(args.bucket);
130
+ const { app, tenant } = await ctx.resolveAppTenant({
131
+ app: args.app,
132
+ tenant: args.tenant
133
+ });
134
+ assertCollectionArg(args.collection, "baerly inspect");
135
+ const collectionPrefix = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}`;
136
+ const currentJsonKey = `${collectionPrefix}/current.json`;
137
+ const read = await readCurrentJson(bucket.storage, currentJsonKey);
138
+ if (read === null) throw new BaerlyError("InvalidConfig", `baerly inspect: current.json not found at ${currentJsonKey}`);
139
+ const cur = read.json;
140
+ const log_seq_start = cur.log_seq_start ?? 0;
141
+ const discoveredTail = (await probeTailFrom(bucket.storage, collectionPrefix, Math.max(log_seq_start, cur.tail_hint))).tail;
142
+ const errors = [];
143
+ let materialisedRows = 0;
144
+ try {
145
+ materialisedRows = (await loadMaterialisedView({
146
+ storage: bucket.storage,
147
+ currentJsonKey,
148
+ collection: args.collection
149
+ }))?.size ?? 0;
150
+ } catch (error) {
151
+ if (error instanceof BaerlyError) errors.push(`${error.code}: ${error.message}`);
152
+ else errors.push(error.message);
153
+ }
154
+ try {
155
+ const snapshotPrefix = `${collectionPrefix}/snapshot/`;
156
+ const { keys } = await countListEntries(bucket.storage, snapshotPrefix);
157
+ for (const k of keys) if (cur.snapshot !== k) errors.push(`orphan snapshot: ${k}`);
158
+ } catch (error) {
159
+ if (error instanceof BaerlyError) errors.push(`${error.code}: ${error.message}`);
160
+ }
161
+ const liveLogTail = discoveredTail - log_seq_start;
162
+ const { maxFoldBytes, maintenance } = readInspectMaintenanceEnv((k) => process.env[k]);
163
+ const profileNames = args.profile === void 0 ? Object.keys(HOST_PROFILES) : [args.profile];
164
+ const foldGate = {};
165
+ for (const name of profileNames) foldGate[name] = foldGateVerdict(cur, liveLogTail, HOST_PROFILES[name], maxFoldBytes);
166
+ const result = {
167
+ currentJsonKey,
168
+ schema_version: cur.schema_version,
169
+ tail_hint: cur.tail_hint,
170
+ discovered_tail: discoveredTail,
171
+ log_seq_start,
172
+ live_log_tail: liveLogTail,
173
+ snapshot: cur.snapshot,
174
+ snapshot_bytes: cur.snapshot_bytes,
175
+ snapshot_rows: cur.snapshot_rows,
176
+ fold_gate: foldGate,
177
+ maintenance,
178
+ writer_fence: cur.writer_fence,
179
+ materialised_rows: materialisedRows,
180
+ status: errors.length === 0 ? "ok" : "error",
181
+ errors
182
+ };
183
+ if (isJsonMode()) emitSuccess({
184
+ command: "inspect",
185
+ ...result
186
+ });
187
+ else process.stdout.write(renderText(result, args.collection));
188
+ return 0;
189
+ }
190
+ });
191
+ /** citty `defineCommand` block for `baerly inspect`. */
192
+ const inspect = bundle.cmd;
193
+ bundle.run;
194
+ export { inspect };
195
+
196
+ //# sourceMappingURL=inspect-BTsVYZKd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspect-BTsVYZKd.js","names":[],"sources":["../packages/cli/src/inspect.ts"],"sourcesContent":["/**\n * `baerly inspect` — read-only summary for one collection.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --profile Optional host profile (cf-free | cf-paid | node) for the\n * fold_gate verdict. Default: report all three.\n * --json JSON envelope. A storage-format diagnostic, not a stable\n * contract: its fields name format internals and change\n * with the format, release to release.\n *\n * Reports, per-collection:\n * - currentJsonKey path.\n * - schema_version, tail_hint, log_seq_start (default 0).\n * - live_log_tail (= tail_hint - log_seq_start).\n * - snapshot key (or null).\n * - snapshot_bytes / snapshot_rows (the fold-ceiling inputs C / E\n * are compared against; see graduation.md).\n * - fold_gate, per host profile: `open`, `closed:bytes`, or\n * `closed:rows` — the write-tick runner's pre-fold projection\n * (`snapshot_bytes <= C && snapshot_rows <= E`)\n * against that profile's ceilings, with `C` overridden by\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` from the CLI's environment. Plus\n * `retention_stalled`: the gate is closed and the live tail has\n * reached the write-tick fold floor, so the tail and log retention\n * are frozen. The CLI cannot know the host, hence one verdict per\n * profile. A collection whose stored snapshot is under `C` but whose\n * next rebuild would exceed it reads `open` here; the runner's\n * `fold_deferred` warning (gate `rebuild`) is that case's signal.\n * - writer_fence (epoch, owner, claimed_at).\n * - materialised row count (via export/loadMaterialisedView).\n * - well-formed status: \"ok\" or \"error\" with an `errors` array.\n *\n * For projected monthly Class A / $ trajectories, use\n * `baerly cost --bucket=<uri> --collection=<name>` — the projection\n * used to live as a footer here but moved to its own verb so inspect\n * stays a glance command (no GET-storm over the trailing log sample).\n *\n * Cost shape:\n * 1 GET current.json\n * + 1 GET snapshot (if any)\n * + N GETs log tail (= tail_hint - log_seq_start)\n * + 1 LIST snapshot/ prefix (orphan detection)\n *\n * Never mutates anything.\n *\n * Exit codes:\n * 0 — inspection ran (status may be \"ok\" or \"error\"; both exit 0).\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant / conflict (WriteConflict / AlreadyExists /\n * Internal / InvalidResponse / AmbiguousCommit).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport {\n BaerlyError,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_PROFILE_CF_PAID,\n MAINTENANCE_PROFILE_NODE,\n readCurrentJson,\n type CurrentJson,\n type Storage,\n WRITE_TICK_MIN_ENTRIES_TO_COMPACT,\n} from \"@baerly/protocol\";\nimport { probeTailFrom } from \"@baerly/server/_internal/kernel\";\nimport {\n isFoldViable,\n type MaintenanceProfile,\n parseMaintenanceEnv,\n} from \"@baerly/server/_internal/maintenance\";\nimport { loadMaterialisedView } from \"./export/index.ts\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"./output.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"./subcommand.ts\";\n\nconst INSPECT_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n profile: {\n type: \"enum\",\n options: [\"cf-free\", \"cf-paid\", \"node\"],\n required: false,\n description:\n \"Host profile for the fold_gate verdict: cf-free | cf-paid | node. Default: all three.\",\n },\n json: {\n ...JSON_ARG,\n description: `${JSON_ARG.description}. A storage-format diagnostic: fields follow the storage format and can change in any release`,\n },\n} as const satisfies ArgsDef;\n\n/** The host profiles `BAERLY_MAINTENANCE_PROFILE` / the adapters select, keyed by name. */\nconst HOST_PROFILES = {\n \"cf-free\": MAINTENANCE_PROFILE_CF_FREE,\n \"cf-paid\": MAINTENANCE_PROFILE_CF_PAID,\n node: MAINTENANCE_PROFILE_NODE,\n} as const satisfies Record<string, MaintenanceProfile>;\n\ntype HostProfileName = keyof typeof HOST_PROFILES;\n\ninterface FoldGateVerdict {\n verdict: \"open\" | \"closed:bytes\" | \"closed:rows\";\n /** `C` for this profile, after any `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` override. */\n ceiling_bytes: number;\n /** `E` for this profile (no env override exists). */\n ceiling_rows: number;\n /** Gate closed AND the live tail has reached the write-tick fold floor. */\n retention_stalled: boolean;\n}\n\n/**\n * The write-tick runner's pre-fold projection (`isFoldViable`), evaluated\n * off stored figures for one profile. Bytes is labelled first, matching\n * the runner's `dimension` label.\n */\nconst foldGateVerdict = (\n cur: CurrentJson,\n liveLogTail: number,\n profile: MaintenanceProfile,\n maxFoldBytes: number | undefined,\n): FoldGateVerdict => {\n const ceilingBytes = maxFoldBytes ?? profile.maxFoldBytes;\n const ceilingRows = profile.maxFoldRows;\n let verdict: FoldGateVerdict[\"verdict\"] = \"open\";\n if (\n !isFoldViable(cur.snapshot_bytes, cur.snapshot_rows, {\n maxFoldBytes: ceilingBytes,\n maxFoldRows: ceilingRows,\n })\n ) {\n verdict = cur.snapshot_bytes <= ceilingBytes ? \"closed:rows\" : \"closed:bytes\";\n }\n return {\n verdict,\n ceiling_bytes: ceilingBytes,\n ceiling_rows: ceilingRows,\n retention_stalled: verdict !== \"open\" && liveLogTail >= WRITE_TICK_MIN_ENTRIES_TO_COMPACT,\n };\n};\n\n/** Stderr warning for a maintenance env value the adapters would reject. */\nconst warnRejectedEnv = (error: unknown): void => {\n const message = error instanceof Error ? error.message : String(error);\n process.stderr.write(\n `baerly inspect: warning: ${message} — the adapters reject this value with InvalidConfig on every request that reads it.\\n`,\n );\n};\n\n/**\n * The maintenance env as `inspect` reports it, read from the CLI's own\n * environment. Each variable goes through {@link parseMaintenanceEnv} on its\n * own, so a value the adapters would reject (`BAERLY_MAINTENANCE_DISABLE=off`,\n * a non-positive `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`) becomes a stderr warning\n * rather than failing a read-only report, and never masks the other variable.\n * A rejected `MAX_FOLD_BYTES` falls back to each profile's default `C`.\n */\nconst readInspectMaintenanceEnv = (\n readEnv: (key: string) => string | undefined,\n): { maxFoldBytes: number | undefined; maintenance: InspectResult[\"maintenance\"] } => {\n const only =\n (key: string) =>\n (k: string): string | undefined =>\n k === key ? readEnv(k) : undefined;\n let maxFoldBytes: number | undefined;\n try {\n maxFoldBytes = parseMaintenanceEnv(only(\"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\")).maxFoldBytes;\n } catch (error) {\n warnRejectedEnv(error);\n }\n let maintenance: InspectResult[\"maintenance\"];\n try {\n maintenance = parseMaintenanceEnv(only(\"BAERLY_MAINTENANCE_DISABLE\")).disabled\n ? \"disabled\"\n : \"enabled\";\n } catch (error) {\n warnRejectedEnv(error);\n maintenance = \"invalid-config\";\n }\n return { maxFoldBytes, maintenance };\n};\n\nconst countListEntries = async (\n storage: Storage,\n prefix: string,\n): Promise<{ count: number; keys: string[] }> => {\n let count = 0;\n const keys: string[] = [];\n for await (const entry of storage.list(prefix)) {\n count++;\n keys.push(entry.key);\n }\n return { count, keys };\n};\n\ninterface InspectResult {\n currentJsonKey: string;\n schema_version: number;\n /** The stored, compactor-advanced lower-bound hint (`current.json.tail_hint`). */\n tail_hint: number;\n /** The TRUE committed tail, discovered by forward-probe past `tail_hint`. */\n discovered_tail: number;\n log_seq_start: number;\n live_log_tail: number;\n snapshot: string | null;\n snapshot_bytes: number;\n snapshot_rows: number;\n fold_gate: Partial<Record<HostProfileName, FoldGateVerdict>>;\n /**\n * In-band fold/GC per `BAERLY_MAINTENANCE_DISABLE` in the CLI's environment.\n * `invalid-config`: a value outside the closed vocabulary, which the\n * adapters reject.\n */\n maintenance: \"enabled\" | \"disabled\" | \"invalid-config\";\n writer_fence: CurrentJson[\"writer_fence\"];\n materialised_rows: number;\n status: \"ok\" | \"error\";\n errors: string[];\n}\n\nconst renderText = (r: InspectResult, collection: string): string => {\n const lines: string[] = [];\n lines.push(`baerly inspect ${collection}`);\n lines.push(` current.json: ${r.currentJsonKey}`);\n lines.push(` schema_version: ${r.schema_version}`);\n lines.push(` tail_hint (stored): ${r.tail_hint}`);\n lines.push(` discovered_tail: ${r.discovered_tail}`);\n lines.push(` log_seq_start: ${r.log_seq_start}`);\n lines.push(` live_log_tail: ${r.live_log_tail}`);\n lines.push(` snapshot: ${r.snapshot ?? \"(none)\"}`);\n lines.push(` snapshot_bytes: ${r.snapshot_bytes}`);\n lines.push(` snapshot_rows: ${r.snapshot_rows}`);\n for (const [name, g] of Object.entries(r.fold_gate)) {\n const label = `fold_gate (${name}):`.padEnd(21);\n const stalled = g.retention_stalled ? \" retention_stalled\" : \"\";\n lines.push(` ${label}${g.verdict} (C=${g.ceiling_bytes} E=${g.ceiling_rows})${stalled}`);\n }\n lines.push(` maintenance: ${r.maintenance}`);\n lines.push(\n ` writer_fence: epoch=${r.writer_fence.epoch} owner=${JSON.stringify(r.writer_fence.owner)} claimed_at=${JSON.stringify(r.writer_fence.claimed_at)}`,\n );\n lines.push(` materialised_rows: ${r.materialised_rows}`);\n lines.push(` status: ${r.status}`);\n if (r.errors.length > 0) {\n for (const e of r.errors) {\n lines.push(` error: ${e}`);\n }\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"inspect\",\n meta: {\n description: \"Read-only summary of one collection's snapshot + log state.\",\n },\n args: INSPECT_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly inspect\");\n const collectionPrefix = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}`;\n const currentJsonKey = `${collectionPrefix}/current.json`;\n\n const read = await readCurrentJson(bucket.storage, currentJsonKey);\n if (read === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly inspect: current.json not found at ${currentJsonKey}`,\n );\n }\n const cur = read.json;\n const log_seq_start = cur.log_seq_start ?? 0;\n // Discover the TRUE tail by forward-probe — under single-write commit\n // the stored `tail_hint` is only a lower bound (compactor-advanced),\n // so an accurate operator summary must probe past it.\n const tailProbe = await probeTailFrom(\n bucket.storage,\n collectionPrefix,\n Math.max(log_seq_start, cur.tail_hint),\n );\n const discoveredTail = tailProbe.tail;\n\n const errors: string[] = [];\n let materialisedRows = 0;\n try {\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n materialisedRows = view?.size ?? 0;\n } catch (error) {\n if (error instanceof BaerlyError) {\n errors.push(`${error.code}: ${error.message}`);\n } else {\n errors.push((error as Error).message);\n }\n }\n\n // Orphan-snapshot detection: list every file under <collectionPrefix>/snapshot/\n // and flag anything that isn't the currently-pointed-at snapshot.\n try {\n const snapshotPrefix = `${collectionPrefix}/snapshot/`;\n const { keys } = await countListEntries(bucket.storage, snapshotPrefix);\n for (const k of keys) {\n if (cur.snapshot !== k) {\n errors.push(`orphan snapshot: ${k}`);\n }\n }\n } catch (error) {\n if (error instanceof BaerlyError) {\n errors.push(`${error.code}: ${error.message}`);\n }\n }\n\n const liveLogTail = discoveredTail - log_seq_start;\n const { maxFoldBytes, maintenance } = readInspectMaintenanceEnv((k) => process.env[k]);\n const profileNames: readonly HostProfileName[] =\n args.profile === undefined\n ? (Object.keys(HOST_PROFILES) as HostProfileName[])\n : [args.profile as HostProfileName];\n const foldGate: InspectResult[\"fold_gate\"] = {};\n for (const name of profileNames) {\n foldGate[name] = foldGateVerdict(cur, liveLogTail, HOST_PROFILES[name], maxFoldBytes);\n }\n\n const result: InspectResult = {\n currentJsonKey,\n schema_version: cur.schema_version,\n tail_hint: cur.tail_hint,\n discovered_tail: discoveredTail,\n log_seq_start,\n live_log_tail: liveLogTail,\n snapshot: cur.snapshot,\n snapshot_bytes: cur.snapshot_bytes,\n snapshot_rows: cur.snapshot_rows,\n fold_gate: foldGate,\n maintenance,\n writer_fence: cur.writer_fence,\n materialised_rows: materialisedRows,\n status: errors.length === 0 ? \"ok\" : \"error\",\n errors,\n };\n\n if (isJsonMode()) {\n emitSuccess({ command: \"inspect\", ...result });\n } else {\n process.stdout.write(renderText(result, args.collection));\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly inspect`. */\nexport const inspect = 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 runInspect = bundle.run;\n"],"mappings":";;;;;;;;AAuFA,MAAM,eAA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iBAAiB;EACrC,MAAM,EAAE,cAAc,gBAAgB,2BAA2B,MAAM,QAAQ,IAAI,EAAE;EACrF,MAAM,eACJ,KAAK,YAAY,KAAA,IACZ,OAAO,KAAK,aAAa,IAC1B,CAAC,KAAK,OAA0B;EACtC,MAAM,WAAuC,CAAC;EAC9C,KAAK,MAAM,QAAQ,cACjB,SAAS,QAAQ,gBAAgB,KAAK,aAAa,cAAc,OAAO,YAAY;EAGtF,MAAM,SAAwB;GAC5B;GACA,gBAAgB,IAAI;GACpB,WAAW,IAAI;GACf,iBAAiB;GACjB;GACA,eAAe;GACf,UAAU,IAAI;GACd,gBAAgB,IAAI;GACpB,eAAe,IAAI;GACnB,WAAW;GACX;GACA,cAAc,IAAI;GAClB,mBAAmB;GACnB,QAAQ,OAAO,WAAW,IAAI,OAAO;GACrC;EACF;EAEA,IAAI,WAAW,GACb,YAAY;GAAE,SAAS;GAAW,GAAG;EAAO,CAAC;OAE7C,QAAQ,OAAO,MAAM,WAAW,QAAQ,KAAK,UAAU,CAAC;EAE1D,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOJ,OAAO"}
@@ -1,5 +1,5 @@
1
- import { t as BaerlyError } from "./errors-Dfa3p78c.js";
2
- //#region packages/protocol/src/storage/key.ts
1
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
2
+ // packages/protocol/src/storage/key.ts
3
3
  /**
4
4
  * Validate a raw {@link Storage} object key against the portable baerly key
5
5
  * grammar before it is used to address an object. A key MUST be non-empty
@@ -29,7 +29,6 @@ function assertValidStorageKey(key) {
29
29
  if (key.length === 0) throw new BaerlyError("InvalidConfig", "storage key must be a non-empty string");
30
30
  for (const segment of key.split("/")) if (segment === "." || segment === "..") throw new BaerlyError("InvalidConfig", `storage key may not contain a "." or ".." path segment — RFC 3986 dot-segment removal makes it unaddressable over the S3/R2 HTTP API: ${JSON.stringify(key)}`);
31
31
  }
32
- //#endregion
33
32
  export { assertValidStorageKey as t };
34
33
 
35
- //# sourceMappingURL=key-Di6yyxFu.js.map
34
+ //# sourceMappingURL=key-C4FPZ9Io.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"key-Di6yyxFu.js","names":[],"sources":["../packages/protocol/src/storage/key.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\n\n/**\n * Validate a raw {@link Storage} object key against the portable baerly key\n * grammar before it is used to address an object. A key MUST be non-empty\n * and `/`-delimited, with **no path segment equal to `.` or `..`**.\n *\n * The dot-segment rule is not a vendor quirk — it is a *client-side*\n * universal: RFC 3986 §5.2.4 \"remove dot segments\" is mandatory for every\n * conformant URL parser, so `<endpoint>/<bucket>/.` normalizes to\n * `<endpoint>/<bucket>/` and `<endpoint>/<bucket>/..` escapes the bucket\n * entirely — *before* the request is signed or sent, in TypeScript, Go,\n * Rust, Python, or any language a `Storage` port is written in. Such a key\n * cannot be addressed over the S3/R2 HTTP API regardless of backend; a bare\n * `.` PUT surfaces as a confusing bucket-root 403 rather than a clear\n * rejection. The kernel never emits such keys (caller-controlled segments\n * are already screened by `assertPathSegment` one layer up), so this is the\n * boundary guard that makes every adapter reject them *identically* and\n * gives ports a single, testable contract.\n *\n * Thrown as `BaerlyError{code:\"InvalidConfig\"}` to match the sibling\n * key/segment guards (`assertKeyWithinLimit`, `assertPathSegment`). The\n * full-key 1024-byte ceiling is enforced separately on the write path\n * (`assertKeyWithinLimit`), where multi-segment keys are assembled.\n *\n * @see docs/spec/storage-compatibility.md — \"Key namespace\"\n */\nexport function assertValidStorageKey(key: string): void {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"storage key must be a non-empty string\");\n }\n for (const segment of key.split(\"/\")) {\n if (segment === \".\" || segment === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `storage key may not contain a \".\" or \"..\" path segment — RFC 3986 dot-segment ` +\n `removal makes it unaddressable over the S3/R2 HTTP API: ${JSON.stringify(key)}`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,sBAAsB,KAAmB;CACvD,IAAI,IAAI,WAAW,GACjB,MAAM,IAAI,YAAY,iBAAiB,wCAAwC;CAEjF,KAAK,MAAM,WAAW,IAAI,MAAM,GAAG,GACjC,IAAI,YAAY,OAAO,YAAY,MACjC,MAAM,IAAI,YACR,iBACA,yIAC6D,KAAK,UAAU,GAAG,GACjF;AAGN"}
1
+ {"version":3,"file":"key-C4FPZ9Io.js","names":[],"sources":["../packages/protocol/src/storage/key.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\n\n/**\n * Validate a raw {@link Storage} object key against the portable baerly key\n * grammar before it is used to address an object. A key MUST be non-empty\n * and `/`-delimited, with **no path segment equal to `.` or `..`**.\n *\n * The dot-segment rule is not a vendor quirk — it is a *client-side*\n * universal: RFC 3986 §5.2.4 \"remove dot segments\" is mandatory for every\n * conformant URL parser, so `<endpoint>/<bucket>/.` normalizes to\n * `<endpoint>/<bucket>/` and `<endpoint>/<bucket>/..` escapes the bucket\n * entirely — *before* the request is signed or sent, in TypeScript, Go,\n * Rust, Python, or any language a `Storage` port is written in. Such a key\n * cannot be addressed over the S3/R2 HTTP API regardless of backend; a bare\n * `.` PUT surfaces as a confusing bucket-root 403 rather than a clear\n * rejection. The kernel never emits such keys (caller-controlled segments\n * are already screened by `assertPathSegment` one layer up), so this is the\n * boundary guard that makes every adapter reject them *identically* and\n * gives ports a single, testable contract.\n *\n * Thrown as `BaerlyError{code:\"InvalidConfig\"}` to match the sibling\n * key/segment guards (`assertKeyWithinLimit`, `assertPathSegment`). The\n * full-key 1024-byte ceiling is enforced separately on the write path\n * (`assertKeyWithinLimit`), where multi-segment keys are assembled.\n *\n * @see docs/spec/storage-compatibility.md — \"Key namespace\"\n */\nexport function assertValidStorageKey(key: string): void {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"storage key must be a non-empty string\");\n }\n for (const segment of key.split(\"/\")) {\n if (segment === \".\" || segment === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `storage key may not contain a \".\" or \"..\" path segment — RFC 3986 dot-segment ` +\n `removal makes it unaddressable over the S3/R2 HTTP API: ${JSON.stringify(key)}`,\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,sBAAsB,KAAmB;CACvD,IAAI,IAAI,WAAW,GACjB,MAAM,IAAI,YAAY,iBAAiB,wCAAwC;CAEjF,KAAK,MAAM,WAAW,IAAI,MAAM,GAAG,GACjC,IAAI,YAAY,OAAO,YAAY,MACjC,MAAM,IAAI,YACR,iBACA,yIAC6D,KAAK,UAAU,GAAG,GACjF;AAGN"}
@@ -0,0 +1,192 @@
1
+ import { t as BaerlyError } from "./errors-7Rk1HGCE.js";
2
+ // packages/protocol/src/storage/ledger.ts
3
+ /**
4
+ * Capacity a caller holds on a {@link RequestLedger} for calls it is about
5
+ * to issue (from {@link RequestLedger.hold}). Calls made with the hold
6
+ * active (passed to {@link RequestLedger.acquire}; `retryStorageCall` passes
7
+ * {@link currentRequestHold}) draw on it first; every other call in the
8
+ * invocation sees the ledger's room net of it, so concurrent work cannot
9
+ * spend it. Release it once the holder's calls are done; the unspent part
10
+ * returns to the ledger.
11
+ */
12
+ var RequestHold = class {
13
+ #ledger;
14
+ #left;
15
+ /** @internal Created by {@link RequestLedger.hold}. */
16
+ constructor(ledger, amount) {
17
+ this.#ledger = ledger;
18
+ this.#left = amount;
19
+ }
20
+ /** Held requests not yet spent. */
21
+ get left() {
22
+ return this.#left;
23
+ }
24
+ /** @internal `true` when this hold is on `ledger` and has room left. */
25
+ covers(ledger) {
26
+ return this.#ledger === ledger && this.#left > 0;
27
+ }
28
+ /** @internal Spend one held request. */
29
+ spend() {
30
+ this.#left -= 1;
31
+ }
32
+ /** Return the unspent part to the ledger. Idempotent. */
33
+ release() {
34
+ const left = this.#left;
35
+ this.#left = 0;
36
+ this.#ledger.unhold(left);
37
+ }
38
+ };
39
+ /** Limits that count every request and never refuse one (Node, and any host without a per-invocation cap). */
40
+ const UNLIMITED_REQUESTS = {
41
+ internal: 1e400,
42
+ external: 1e400
43
+ };
44
+ /**
45
+ * Per-invocation storage request budget. The adapter creates one per
46
+ * invocation (an HTTP request, a cron tick) and the server carries it on
47
+ * the observability context, so everything that invocation runs,
48
+ * `ctx.waitUntil` work included, charges the same ledger.
49
+ *
50
+ * `retryStorageCall` charges one request before every attempt, so adapter
51
+ * retries and `list` pages are charged as they are issued. A request that
52
+ * does not fit is refused before it is sent: {@link acquire} throws
53
+ * `CapacityExceeded` whose cause carries `refused: true`, which ends the
54
+ * retry loop at once and keeps `notApplied` on a create. Charging is
55
+ * synchronous, so a `Promise.all` fan-out can never issue past the limit.
56
+ *
57
+ * Calls outside `retryStorageCall` (the verifier's JWKS fetch, GCS
58
+ * signing, app code in the same Worker) are not charged; the limits keep
59
+ * a margin below the platform cap for them.
60
+ */
61
+ var RequestLedger = class {
62
+ limits;
63
+ #internal = 0;
64
+ #external = 0;
65
+ #cache = 0;
66
+ #storagePool;
67
+ #held = 0;
68
+ constructor(limits = UNLIMITED_REQUESTS) {
69
+ this.limits = limits;
70
+ }
71
+ /** Requests charged so far. */
72
+ get charged() {
73
+ return {
74
+ internal: this.#internal,
75
+ external: this.#external,
76
+ cache: this.#cache
77
+ };
78
+ }
79
+ /**
80
+ * Requests still allowed on `pool` to a caller without a hold: the room
81
+ * left, net of active holds. An external request also needs room in
82
+ * `internal`.
83
+ */
84
+ remaining(pool) {
85
+ return this.#room(pool) - this.#held;
86
+ }
87
+ /** Requests held by active holds, not yet spent. */
88
+ get held() {
89
+ return this.#held;
90
+ }
91
+ /**
92
+ * Hold `amount` requests for the caller's next calls; see
93
+ * {@link RequestHold}. The caller checks {@link storageRemaining} first:
94
+ * a hold never refuses, and one larger than the room left only blocks
95
+ * other callers sooner.
96
+ */
97
+ hold(amount) {
98
+ this.#held += amount;
99
+ return new RequestHold(this, amount);
100
+ }
101
+ /** @internal Return `amount` unspent held requests (`RequestHold.release`). */
102
+ unhold(amount) {
103
+ this.#held -= amount;
104
+ }
105
+ #room(pool) {
106
+ const internal = this.limits.internal - this.#internal;
107
+ return pool === "internal" ? internal : Math.min(internal, this.limits.external - this.#external);
108
+ }
109
+ /**
110
+ * Requests still allowed, net of active holds, on the pool this
111
+ * invocation's storage calls draw on: `external` once any storage call charged it, else `internal`
112
+ * once one charged that, else `Infinity` (no storage call has been
113
+ * charged, so the storage in use does not charge this ledger). A caller
114
+ * that must keep room for its next calls, such as the writer's
115
+ * commit-resolution reserve, checks this after its first storage call.
116
+ * Cache API calls do not count as storage calls here.
117
+ */
118
+ storageRemaining() {
119
+ return this.#storagePool === void 0 ? 1e400 : this.remaining(this.#storagePool);
120
+ }
121
+ /**
122
+ * Charge one request to `pool`, or refuse it before it is sent. With an
123
+ * active `hold` on this ledger the request draws on it (it needs only
124
+ * room left in `pool`); otherwise it needs room net of active holds.
125
+ *
126
+ * @throws BaerlyError code="CapacityExceeded", cause `{ refused: true }`,
127
+ * when `pool` has no room. Nothing is charged.
128
+ */
129
+ acquire(pool, hold) {
130
+ if (this.#storagePool !== "external") this.#storagePool = pool;
131
+ const held = hold?.covers(this) === true;
132
+ if ((held ? this.#room(pool) : this.remaining(pool)) < 1) {
133
+ const limit = pool === "internal" ? this.limits.internal : this.limits.external;
134
+ throw new BaerlyError("CapacityExceeded", `this request has issued its limit of ${String(limit)} ${pool} storage calls, so the next call was not sent; the work this request needs does not fit in one request on this host`, { cause: {
135
+ refused: true,
136
+ pool,
137
+ limit
138
+ } });
139
+ }
140
+ if (held) {
141
+ hold.spend();
142
+ this.#held -= 1;
143
+ }
144
+ this.#charge(pool);
145
+ }
146
+ /**
147
+ * Legacy internal accounting seam; no production Worker caller.
148
+ * Charge one optional Cache API call when it fits: room in `external`
149
+ * and fewer than {@link CF_CACHE_API_MAX_CALLS} cache calls so far.
150
+ * Returns `false`, charging nothing, when it does not; the caller skips
151
+ * the cache call. With `required`, the call is charged whether or not
152
+ * it fits and always returns `true`. Tests use this to model an
153
+ * unrefusable call consuming the platform margin.
154
+ */
155
+ chargeCacheCall(required = false) {
156
+ if (!required && (this.#cache >= 3 || this.remaining("external") < 1)) return false;
157
+ this.#cache += 1;
158
+ this.#charge("external");
159
+ return true;
160
+ }
161
+ #charge(pool) {
162
+ this.#internal += 1;
163
+ if (pool === "external") this.#external += 1;
164
+ }
165
+ };
166
+ let resolveLedger = () => void 0;
167
+ /**
168
+ * Register how {@link currentRequestLedger} finds the active ledger. The
169
+ * server registers its observability context here, so adapters, which
170
+ * import only this package, charge the ledger of the invocation they run
171
+ * in. One resolver per process; a later call replaces it.
172
+ */
173
+ const setRequestLedgerResolver = (resolver) => {
174
+ resolveLedger = resolver;
175
+ };
176
+ /** The ledger of the active invocation, or `undefined` outside one (nothing is charged). */
177
+ const currentRequestLedger = () => resolveLedger();
178
+ let resolveHold = () => void 0;
179
+ /**
180
+ * Register how {@link currentRequestHold} finds the active hold, as
181
+ * {@link setRequestLedgerResolver} does for the ledger. The server scopes a
182
+ * hold to the async context of the work it covers, so work started outside
183
+ * that context (a `ctx.waitUntil` tick) never draws on it.
184
+ */
185
+ const setRequestHoldResolver = (resolver) => {
186
+ resolveHold = resolver;
187
+ };
188
+ /** The hold active in this async context, if any; `retryStorageCall` charges against it. */
189
+ const currentRequestHold = () => resolveHold();
190
+ export { setRequestLedgerResolver as a, setRequestHoldResolver as i, currentRequestHold as n, currentRequestLedger as r, RequestLedger as t };
191
+
192
+ //# sourceMappingURL=ledger-Dj_bGgo0.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger-Dj_bGgo0.js","names":[],"sources":["../packages/protocol/src/storage/ledger.ts"],"sourcesContent":["import { CF_CACHE_API_MAX_CALLS } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\n\n/**\n * A request pool on a {@link RequestLedger}. `internal` is charged for\n * every storage call. `external` is charged as well for a call that\n * leaves through `fetch` (S3 over HTTP, GCS). The legacy cache-accounting\n * seam also charges both pools; the production Worker never calls it.\n * Charging an external call to both pools is safe whether\n * the host keeps one combined counter or two separate ones.\n */\nexport type RequestPool = \"internal\" | \"external\";\n\n/**\n * Capacity a caller holds on a {@link RequestLedger} for calls it is about\n * to issue (from {@link RequestLedger.hold}). Calls made with the hold\n * active (passed to {@link RequestLedger.acquire}; `retryStorageCall` passes\n * {@link currentRequestHold}) draw on it first; every other call in the\n * invocation sees the ledger's room net of it, so concurrent work cannot\n * spend it. Release it once the holder's calls are done; the unspent part\n * returns to the ledger.\n */\nexport class RequestHold {\n readonly #ledger: RequestLedger;\n #left: number;\n\n /** @internal Created by {@link RequestLedger.hold}. */\n constructor(ledger: RequestLedger, amount: number) {\n this.#ledger = ledger;\n this.#left = amount;\n }\n\n /** Held requests not yet spent. */\n get left(): number {\n return this.#left;\n }\n\n /** @internal `true` when this hold is on `ledger` and has room left. */\n covers(ledger: RequestLedger): boolean {\n return this.#ledger === ledger && this.#left > 0;\n }\n\n /** @internal Spend one held request. */\n spend(): void {\n this.#left -= 1;\n }\n\n /** Return the unspent part to the ledger. Idempotent. */\n release(): void {\n const left = this.#left;\n this.#left = 0;\n this.#ledger.unhold(left);\n }\n}\n\n/** Per-pool request limits. `Infinity` counts without ever refusing. */\nexport interface RequestLedgerLimits {\n readonly internal: number;\n readonly external: number;\n}\n\n/** Requests charged so far, per pool, plus Cache API calls (also in `external`). */\nexport interface RequestLedgerCharges {\n readonly internal: number;\n readonly external: number;\n readonly cache: number;\n}\n\n/** Limits that count every request and never refuse one (Node, and any host without a per-invocation cap). */\nexport const UNLIMITED_REQUESTS: RequestLedgerLimits = { internal: Infinity, external: Infinity };\n\n/**\n * Per-invocation storage request budget. The adapter creates one per\n * invocation (an HTTP request, a cron tick) and the server carries it on\n * the observability context, so everything that invocation runs,\n * `ctx.waitUntil` work included, charges the same ledger.\n *\n * `retryStorageCall` charges one request before every attempt, so adapter\n * retries and `list` pages are charged as they are issued. A request that\n * does not fit is refused before it is sent: {@link acquire} throws\n * `CapacityExceeded` whose cause carries `refused: true`, which ends the\n * retry loop at once and keeps `notApplied` on a create. Charging is\n * synchronous, so a `Promise.all` fan-out can never issue past the limit.\n *\n * Calls outside `retryStorageCall` (the verifier's JWKS fetch, GCS\n * signing, app code in the same Worker) are not charged; the limits keep\n * a margin below the platform cap for them.\n */\nexport class RequestLedger {\n readonly limits: RequestLedgerLimits;\n #internal = 0;\n #external = 0;\n #cache = 0;\n // The strictest pool an `acquire` has charged: storage calls run through\n // one adapter per invocation, so this is the pool they draw on.\n #storagePool: RequestPool | undefined;\n // Unspent requests of every active `RequestHold`.\n #held = 0;\n\n constructor(limits: RequestLedgerLimits = UNLIMITED_REQUESTS) {\n this.limits = limits;\n }\n\n /** Requests charged so far. */\n get charged(): RequestLedgerCharges {\n return { internal: this.#internal, external: this.#external, cache: this.#cache };\n }\n\n /**\n * Requests still allowed on `pool` to a caller without a hold: the room\n * left, net of active holds. An external request also needs room in\n * `internal`.\n */\n remaining(pool: RequestPool): number {\n return this.#room(pool) - this.#held;\n }\n\n /** Requests held by active holds, not yet spent. */\n get held(): number {\n return this.#held;\n }\n\n /**\n * Hold `amount` requests for the caller's next calls; see\n * {@link RequestHold}. The caller checks {@link storageRemaining} first:\n * a hold never refuses, and one larger than the room left only blocks\n * other callers sooner.\n */\n hold(amount: number): RequestHold {\n this.#held += amount;\n return new RequestHold(this, amount);\n }\n\n /** @internal Return `amount` unspent held requests (`RequestHold.release`). */\n unhold(amount: number): void {\n this.#held -= amount;\n }\n\n #room(pool: RequestPool): number {\n const internal = this.limits.internal - this.#internal;\n return pool === \"internal\"\n ? internal\n : Math.min(internal, this.limits.external - this.#external);\n }\n\n /**\n * Requests still allowed, net of active holds, on the pool this\n * invocation's storage calls draw on: `external` once any storage call charged it, else `internal`\n * once one charged that, else `Infinity` (no storage call has been\n * charged, so the storage in use does not charge this ledger). A caller\n * that must keep room for its next calls, such as the writer's\n * commit-resolution reserve, checks this after its first storage call.\n * Cache API calls do not count as storage calls here.\n */\n storageRemaining(): number {\n return this.#storagePool === undefined ? Infinity : this.remaining(this.#storagePool);\n }\n\n /**\n * Charge one request to `pool`, or refuse it before it is sent. With an\n * active `hold` on this ledger the request draws on it (it needs only\n * room left in `pool`); otherwise it needs room net of active holds.\n *\n * @throws BaerlyError code=\"CapacityExceeded\", cause `{ refused: true }`,\n * when `pool` has no room. Nothing is charged.\n */\n acquire(pool: RequestPool, hold?: RequestHold): void {\n if (this.#storagePool !== \"external\") {\n this.#storagePool = pool;\n }\n const held = hold?.covers(this) === true;\n if ((held ? this.#room(pool) : this.remaining(pool)) < 1) {\n const limit = pool === \"internal\" ? this.limits.internal : this.limits.external;\n throw new BaerlyError(\n \"CapacityExceeded\",\n `this request has issued its limit of ${String(limit)} ${pool} storage calls, so the next call was not sent; the work this request needs does not fit in one request on this host`,\n // The HTTP envelope fills in the code's canonical resolution.\n { cause: { refused: true, pool, limit } },\n );\n }\n if (held) {\n hold!.spend();\n this.#held -= 1;\n }\n this.#charge(pool);\n }\n\n /**\n * Legacy internal accounting seam; no production Worker caller.\n * Charge one optional Cache API call when it fits: room in `external`\n * and fewer than {@link CF_CACHE_API_MAX_CALLS} cache calls so far.\n * Returns `false`, charging nothing, when it does not; the caller skips\n * the cache call. With `required`, the call is charged whether or not\n * it fits and always returns `true`. Tests use this to model an\n * unrefusable call consuming the platform margin.\n */\n chargeCacheCall(required = false): boolean {\n if (!required && (this.#cache >= CF_CACHE_API_MAX_CALLS || this.remaining(\"external\") < 1)) {\n return false;\n }\n this.#cache += 1;\n this.#charge(\"external\");\n return true;\n }\n\n #charge(pool: RequestPool): void {\n this.#internal += 1;\n if (pool === \"external\") {\n this.#external += 1;\n }\n }\n}\n\nlet resolveLedger: () => RequestLedger | undefined = () => undefined;\n\n/**\n * Register how {@link currentRequestLedger} finds the active ledger. The\n * server registers its observability context here, so adapters, which\n * import only this package, charge the ledger of the invocation they run\n * in. One resolver per process; a later call replaces it.\n */\nexport const setRequestLedgerResolver = (resolver: () => RequestLedger | undefined): void => {\n resolveLedger = resolver;\n};\n\n/** The ledger of the active invocation, or `undefined` outside one (nothing is charged). */\nexport const currentRequestLedger = (): RequestLedger | undefined => resolveLedger();\n\nlet resolveHold: () => RequestHold | undefined = () => undefined;\n\n/**\n * Register how {@link currentRequestHold} finds the active hold, as\n * {@link setRequestLedgerResolver} does for the ledger. The server scopes a\n * hold to the async context of the work it covers, so work started outside\n * that context (a `ctx.waitUntil` tick) never draws on it.\n */\nexport const setRequestHoldResolver = (resolver: () => RequestHold | undefined): void => {\n resolveHold = resolver;\n};\n\n/** The hold active in this async context, if any; `retryStorageCall` charges against it. */\nexport const currentRequestHold = (): RequestHold | undefined => resolveHold();\n"],"mappings":";;;;;;;;;;;AAsBA,IAAa,cAAb,MAAyB;CACd;CACT;;CAGA,YAAY,QAAuB,QAAgB;EACjD,KAAK,UAAU;EACf,KAAK,QAAQ;CACf;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK;CACd;;CAGA,OAAO,QAAgC;EACrC,OAAO,KAAK,YAAY,UAAU,KAAK,QAAQ;CACjD;;CAGA,QAAc;EACZ,KAAK,SAAS;CAChB;;CAGA,UAAgB;EACd,MAAM,OAAO,KAAK;EAClB,KAAK,QAAQ;EACb,KAAK,QAAQ,OAAO,IAAI;CAC1B;AACF;;AAgBA,MAAa,qBAA0C;CAAE,UAAU;CAAU,UAAU;AAAS;;;;;;;;;;;;;;;;;;AAmBhG,IAAa,gBAAb,MAA2B;CAChB;CACT,YAAY;CACZ,YAAY;CACZ,SAAS;CAGT;CAEA,QAAQ;CAER,YAAY,SAA8B,oBAAoB;EAC5D,KAAK,SAAS;CAChB;;CAGA,IAAI,UAAgC;EAClC,OAAO;GAAE,UAAU,KAAK;GAAW,UAAU,KAAK;GAAW,OAAO,KAAK;EAAO;CAClF;;;;;;CAOA,UAAU,MAA2B;EACnC,OAAO,KAAK,MAAM,IAAI,IAAI,KAAK;CACjC;;CAGA,IAAI,OAAe;EACjB,OAAO,KAAK;CACd;;;;;;;CAQA,KA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I,oBAAmD,KAAA;;;;;;;AAQvD,MAAa,0BAA0B,aAAkD;CACvF,cAAc;AAChB;;AAGA,MAAa,2BAAoD,YAAY"}
@@ -0,0 +1,47 @@
1
+ // src/legacy-names.ts
2
+ /** The roles whose name is not NFC, in `app`, `tenant`, `collection` order. */
3
+ const nonNfcNames = (names) => [
4
+ "app",
5
+ "tenant",
6
+ "collection"
7
+ ].filter((role) => names[role] !== names[role].normalize("NFC"));
8
+ /**
9
+ * The roles whose name holds an unpaired UTF-16 surrogate, in `app`,
10
+ * `tenant`, `collection` order. `normalize("NFC")` leaves a lone
11
+ * surrogate in place, so {@link nonNfcNames} never flags one.
12
+ */
13
+ const illFormedNames = (names) => [
14
+ "app",
15
+ "tenant",
16
+ "collection"
17
+ ].filter((role) => !names[role].isWellFormed());
18
+ /** Classify a collection's live `_id`s for the migration preflight. */
19
+ const legacyIdReport = (ids) => {
20
+ const nonNfc = [];
21
+ const illFormed = [];
22
+ const byNfc = /* @__PURE__ */ new Map();
23
+ for (const id of ids) {
24
+ const nfc = id.normalize("NFC");
25
+ if (nfc !== id) nonNfc.push(id);
26
+ if (!id.isWellFormed()) illFormed.push(id);
27
+ const group = byNfc.get(nfc);
28
+ if (group === void 0) byNfc.set(nfc, [id]);
29
+ else group.push(id);
30
+ }
31
+ const twins = [...byNfc.values()].filter((g) => g.length > 1).map((g) => g.toSorted()).toSorted((a, b) => a[0] < b[0] ? -1 : 1);
32
+ return {
33
+ non_nfc_ids: nonNfc.toSorted(),
34
+ ill_formed_ids: illFormed.toSorted(),
35
+ twin_ids: twins
36
+ };
37
+ };
38
+ /**
39
+ * Resolution text shared by the fsck finding and the dump warning.
40
+ */
41
+ const LEGACY_NAME_MIGRATION = "the SDK refuses non-NFC names; migrate legacy data with `baerly admin dump` then `baerly admin restore` under an NFC name that is not canonically equivalent to the original";
42
+ const LEGACY_ID_MIGRATION = "before `baerly admin restore`, give each listed row a fresh NFC _id that is not canonically equivalent to any original";
43
+ const LEGACY_ILL_FORMED_NAME_MIGRATION = "the SDK refuses names with an unpaired UTF-16 surrogate, and the CLI cannot pass one; with the code that wrote the data, still on a release that accepts the name, copy each row to a collection under a fresh well-formed NFC name, not name.toWellFormed(), which can address the original objects on R2";
44
+ const LEGACY_ILL_FORMED_ID_MIGRATION = "before `baerly admin restore`, give each listed row a well-formed _id (no unpaired UTF-16 surrogate)";
45
+ export { illFormedNames as a, LEGACY_NAME_MIGRATION as i, LEGACY_ILL_FORMED_ID_MIGRATION as n, legacyIdReport as o, LEGACY_ILL_FORMED_NAME_MIGRATION as r, nonNfcNames as s, LEGACY_ID_MIGRATION as t };
46
+
47
+ //# sourceMappingURL=legacy-names-DgZBtgOh.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy-names-DgZBtgOh.js","names":[],"sources":["../packages/cli/src/legacy-names.ts"],"sourcesContent":["/**\n * Migration preflight for data an earlier release stored under names or\n * `_id`s that are not in Unicode Normalization Form C, or under names or\n * `_id`s with an unpaired UTF-16 surrogate. Pure; `admin fsck`\n * reports {@link nonNfcNames}, {@link illFormedNames}, and the\n * `ill_formed_ids` of {@link legacyIdReport} over its snapshot, and\n * `admin dump` reports every helper over the live row set.\n *\n * R2 stores canonically-equivalent keys as one object, so a non-NFC name\n * shares its key prefix with the NFC spelling there. Two rows whose `_id`s\n * are canonically equivalent (\"twins\") are distinct rows the SDK can no\n * longer write, since it accepts only the NFC spelling of an `_id`.\n */\n\n/** A name role a bucket key interpolates. */\nexport type NameRole = \"app\" | \"tenant\" | \"collection\";\n\n/** The roles whose name is not NFC, in `app`, `tenant`, `collection` order. */\nexport const nonNfcNames = (names: Readonly<Record<NameRole, string>>): NameRole[] =>\n ([\"app\", \"tenant\", \"collection\"] as const).filter(\n (role) => names[role] !== names[role].normalize(\"NFC\"),\n );\n\n/**\n * The roles whose name holds an unpaired UTF-16 surrogate, in `app`,\n * `tenant`, `collection` order. `normalize(\"NFC\")` leaves a lone\n * surrogate in place, so {@link nonNfcNames} never flags one.\n */\nexport const illFormedNames = (names: Readonly<Record<NameRole, string>>): NameRole[] =>\n ([\"app\", \"tenant\", \"collection\"] as const).filter((role) => !names[role].isWellFormed());\n\n/**\n * Non-NFC `_id`s, `_id`s with an unpaired UTF-16 surrogate, and groups of\n * `_id`s that share one NFC form.\n */\nexport interface LegacyIdReport {\n /** Every `_id` that is not NFC, sorted. */\n readonly non_nfc_ids: string[];\n /** Every `_id` with an unpaired UTF-16 surrogate (`!id.isWellFormed()`), sorted. */\n readonly ill_formed_ids: string[];\n /** Each group of two or more canonically-equivalent `_id`s, members sorted, groups sorted. */\n readonly twin_ids: string[][];\n}\n\n/** Classify a collection's live `_id`s for the migration preflight. */\nexport const legacyIdReport = (ids: Iterable<string>): LegacyIdReport => {\n const nonNfc: string[] = [];\n const illFormed: string[] = [];\n const byNfc = new Map<string, string[]>();\n for (const id of ids) {\n const nfc = id.normalize(\"NFC\");\n if (nfc !== id) {\n nonNfc.push(id);\n }\n if (!id.isWellFormed()) {\n illFormed.push(id);\n }\n const group = byNfc.get(nfc);\n if (group === undefined) {\n byNfc.set(nfc, [id]);\n } else {\n group.push(id);\n }\n }\n const twins = [...byNfc.values()]\n .filter((g) => g.length > 1)\n .map((g) => g.toSorted())\n // Groups are disjoint, so their first members never tie.\n .toSorted((a, b) => (a[0]! < b[0]! ? -1 : 1));\n return { non_nfc_ids: nonNfc.toSorted(), ill_formed_ids: illFormed.toSorted(), twin_ids: twins };\n};\n\n/**\n * Resolution text shared by the fsck finding and the dump warning.\n */\nexport const LEGACY_NAME_MIGRATION =\n \"the SDK refuses non-NFC names; migrate legacy data with `baerly admin dump` then `baerly admin restore` under an NFC name that is not canonically equivalent to the original\";\n\nexport const LEGACY_ID_MIGRATION =\n \"before `baerly admin restore`, give each listed row a fresh NFC _id that is not canonically equivalent to any original\";\n\nexport const LEGACY_ILL_FORMED_NAME_MIGRATION =\n \"the SDK refuses names with an unpaired UTF-16 surrogate, and the CLI cannot pass one; with the code that wrote the data, still on a release that accepts the name, copy each row to a collection under a fresh well-formed NFC name, not name.toWellFormed(), which can address the original objects on R2\";\n\nexport const LEGACY_ILL_FORMED_ID_MIGRATION =\n \"before `baerly admin restore`, give each listed row a well-formed _id (no unpaired UTF-16 surrogate)\";\n"],"mappings":";;AAkBA,MAAa,eAAe,UACzB;CAAC;CAAO;CAAU;AAAY,CAAC,CAAW,QACxC,SAAS,MAAM,UAAU,MAAM,KAAK,CAAC,UAAU,KAAK,CACvD;;;;;;AAOF,MAAa,kBAAkB,UAC5B;CAAC;CAAO;CAAU;AAAY,CAAC,CAAW,QAAQ,SAAS,CAAC,MAAM,KAAK,CAAC,aAAa,CAAC;;AAgBzF,MAAa,kBAAkB,QAA0C;CACvE,MAAM,SAAmB,CAAC;CAC1B,MAAM,YAAsB,CAAC;CAC7B,MAAM,wBAAQ,IAAI,IAAsB;CACxC,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,MAAM,GAAG,UAAU,KAAK;EAC9B,IAAI,QAAQ,IACV,OAAO,KAAK,EAAE;EAEhB,IAAI,CAAC,GAAG,aAAa,GACnB,UAAU,KAAK,EAAE;EAEnB,MAAM,QAAQ,MAAM,IAAI,GAAG;EAC3B,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,KAAK,CAAC,EAAE,CAAC;OAEnB,MAAM,KAAK,EAAE;CAEjB;CACA,MAAM,QAAQ,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC,CAC9B,QAAQ,MAAM,EAAE,SAAS,CAAC,CAAC,CAC3B,KAAK,MAAM,EAAE,SAAS,CAAC,CAAC,CAExB,UAAU,GAAG,MAAO,EAAE,KAAM,EAAE,KAAM,KAAK,CAAE;CAC9C,OAAO;EAAE,aAAa,OAAO,SAAS;EAAG,gBAAgB,UAAU,SAAS;EAAG,UAAU;CAAM;AACjG;;;;AAKA,MAAa,wBACX;AAEF,MAAa,sBACX;AAEF,MAAa,mCACX;AAEF,MAAa,iCACX"}
@@ -0,0 +1,94 @@
1
+ import { f as DocumentData, m as JSONValue } from "./app-config-C6qW7m8S.js";
2
+ /**
3
+ * Debezium-style JSON CDC envelope using pgoutput's message-tag (`I`/`U`/`D`) vocabulary. One per mutation.
4
+ *
5
+ * `LogEntry` is now a public, versionless/additive-only wire contract:
6
+ * 0.3.0 is the public early-access baseline. It is still pre-1.0 and
7
+ * soaking, so breaking changes remain possible, but only through an
8
+ * explicit compatibility decision, changelog/migration notes, and a
9
+ * versioned release. Assume external consumers may exist; do not
10
+ * silently rename, remove, or repurpose fields. Consumers must ignore
11
+ * unknown keys; new optional fields can be added in compatible releases.
12
+ *
13
+ * Field requirement matrix:
14
+ * - Always: `lsn`, `commit_ts`, `op`, `collection`, `session`,
15
+ * `seq`.
16
+ * - For I/U/D: `doc_id`.
17
+ * - For I/U: `after` (full post-image).
18
+ * - Optional: `before` (when `replica_identity === "FULL"`), `key_old`
19
+ * (U/D when `replica_identity !== "PATCH_ONLY"`), `origin`.
20
+ *
21
+ * @see docs/spec/log-entry-shape.md
22
+ */
23
+ interface LogEntry {
24
+ /**
25
+ * Opaque, monotonic, lex-asc cursor. Shape is
26
+ * `<base32-time>_<session>_<seq>` — minted inside
27
+ * `Writer.commit` (see
28
+ * `packages/server/src/writer.ts`) from `timestamp()` +
29
+ * the per-commit `session` + `countKey(seq)`.
30
+ *
31
+ * This is NOT what a `/v1/since` client acks: that boundary pairs
32
+ * the LSN with the manifest's `generation` (see `cursor.ts`), so the
33
+ * token may be `<generation>.<lsn>`. Treat `next_cursor` as opaque.
34
+ *
35
+ * When you have a `LogEntry` in hand, prefer the structured
36
+ * `session` / `seq` fields below over parsing this string. The
37
+ * one place that *does* need to crack it open is the
38
+ * `/v1/since` boundary, where a client resumes from an opaque
39
+ * `next_cursor` and no `LogEntry` is in scope — that path uses
40
+ * `lsnParts` (the kernel-blessed parser) rather than ad-hoc
41
+ * `split("_")`.
42
+ */
43
+ lsn: string;
44
+ /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */
45
+ commit_ts: string;
46
+ /** Insert / Update / Delete. */
47
+ op: "I" | "U" | "D";
48
+ /**
49
+ * Collection name — the pgoutput RELATION analogue. Today this is
50
+ * the collection bound to the `current.json` whose `tail_hint` minted
51
+ * the entry. The table API makes collections first-class.
52
+ */
53
+ collection: string;
54
+ /**
55
+ * The document key (`ref.key`). Required for every op — `op` is
56
+ * `I | U | D` and all three carry it — so the wire type is required,
57
+ * not optional, matching `log-entry-shape.md`.
58
+ */
59
+ doc_id: string;
60
+ /** Required for I, U. The post-image (Debezium's `after`). */
61
+ after?: DocumentData;
62
+ /**
63
+ * The pre-image (Debezium's `before`). Present iff the
64
+ * collection's `replica_identity` is `FULL`. ~2× log size on
65
+ * update-heavy collections; off by default.
66
+ */
67
+ before?: DocumentData;
68
+ /**
69
+ * Pre-image of the primary key. U/D always carry this when
70
+ * `replica_identity` is not `PATCH_ONLY`. (For baerly-storage today,
71
+ * `_id` is the only PK.)
72
+ */
73
+ key_old?: {
74
+ readonly [pk: string]: JSONValue;
75
+ };
76
+ /** ORIGIN analogue — the writer session id. */
77
+ origin?: string;
78
+ /**
79
+ * Causal metadata (baerly-storage-only; no pgoutput analogue). The
80
+ * session id that built the `lsn`. Surfaces here so consumers
81
+ * can dedupe / order without parsing the cursor.
82
+ */
83
+ session: string;
84
+ /**
85
+ * The `log/<seq>` slot this entry occupies — the integer in its
86
+ * `log/<seq>.json` key, minted by `Writer.commit` as the forward-probed
87
+ * collection-log tail (the winning `If-None-Match: "*"` create). One
88
+ * entry per `session`, so this is a per-collection slot, not a
89
+ * per-session counter. Also encoded (descending base-32) as the LSN's
90
+ * third segment — see `lsnParts`.
91
+ */
92
+ seq: number;
93
+ }
94
+ export { LogEntry as t };