@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
@@ -1,4 +1,5 @@
1
- import { t as BaerlyError } from "./errors-DOdL95kK.js";
1
+ import { n as CURRENT_JSON_CONTENT_TYPE } from "./constants-CfeMWQWk.js";
2
+ import { t as BaerlyError } from "./errors-Dfa3p78c.js";
2
3
  //#region packages/protocol/src/bytes.ts
3
4
  /**
4
5
  * UTF-8 JSON byte helpers — names the encode/decode idiom used by
@@ -7,205 +8,6 @@ import { t as BaerlyError } from "./errors-DOdL95kK.js";
7
8
  const encodeJsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value));
8
9
  const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
9
10
  //#endregion
10
- //#region packages/protocol/src/constants.ts
11
- /**
12
- * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key
13
- * over this fails the PUT with an opaque provider 400; baerly surfaces
14
- * it early as InvalidConfig. See docs/spec/storage-compatibility.md.
15
- */
16
- const MAX_KEY_BYTES = 1024;
17
- /**
18
- * Backoff (in milliseconds) inserted between LIST attempts when S3
19
- * returns 429 (rate-limited).
20
- */
21
- const RATE_LIMIT_BACKOFF_MILLIS = 1e3;
22
- /**
23
- * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):
24
- * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`
25
- * (rather than silently truncating reads). A runaway alarm only — the
26
- * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means
27
- * maintenance is off or the collection is far past graduation.
28
- *
29
- * @see packages/server/src/log-tail.ts (`probeTailFrom`)
30
- */
31
- const LOG_FORWARD_PROBE_CAP = 1e5;
32
- /**
33
- * MIME type written for `current.json` PUTs. S3 round-trips this on
34
- * subsequent GETs; useful for diagnostics when staring at a bucket
35
- * via the AWS console.
36
- *
37
- * @see packages/protocol/src/coordination/current-json.ts
38
- */
39
- const CURRENT_JSON_CONTENT_TYPE = "application/json";
40
- /**
41
- * MIME type written for `gc/pending.json` PUTs.
42
- *
43
- * @see packages/protocol/src/coordination/gc-pending.ts
44
- */
45
- const GC_PENDING_CONTENT_TYPE = "application/json";
46
- /**
47
- * Default grace period between "marking" a key for GC and "sweeping"
48
- * (deleting) it. 7 days, chosen to span the worst plausible writer-
49
- * retry window (a paused-process writer that resumes hours later
50
- * should still find its idempotency anchor on the bucket). The
51
- * `runGc()` function accepts an override for tests.
52
- *
53
- * Why 7 days specifically:
54
- * - **1 day is too aggressive for batch workloads.** Worker isolate
55
- * scheduling pauses, cross-region replication lag, and
56
- * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly
57
- * exceed an hour under pathological conditions.
58
- * - **30 days is conservative beyond the worst plausible pause.**
59
- * Doubles `gc/pending.json` size at steady state and slows
60
- * visibility into "did GC actually run?" by 4×.
61
- * - **7 days spans the realistic upper bound** — long-running batch
62
- * jobs, multi-region propagation delays, queue backlogs, and
63
- * downstream outages the writer is retrying through. The protocol
64
- * is unaffected by the choice of value within the [hours, weeks]
65
- * range; this constant is the operator-tunable knob.
66
- *
67
- * Production code MUST NOT call `runGc` with `graceMillis` below the
68
- * default outside maintenance windows — going below the longest
69
- * plausible writer-retry latency risks deleting an anchor a writer
70
- * is about to find on retry. Test code that sets `graceMillis: 0` is
71
- * exercising the sweep path deliberately, not modelling production.
72
- *
73
- * @see packages/server/src/gc.ts
74
- */
75
- const GC_GRACE_PERIOD_MILLIS = 10080 * 60 * 1e3;
76
- /**
77
- * Cap on candidates kept in `gc/pending.json` to bound the size of
78
- * the file. The compactor marks at most this many candidates per
79
- * pass; subsequent passes pick up the rest. Larger collections will
80
- * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which
81
- * is acceptable.
82
- *
83
- * @see packages/server/src/gc.ts
84
- */
85
- const GC_MAX_PENDING_CANDIDATES = 1e3;
86
- /**
87
- * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also
88
- * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.
89
- *
90
- * @see packages/server/src/maintenance.ts
91
- */
92
- const MAINTENANCE_MIN_LIVE_BYTES = 64 * 1024;
93
- /**
94
- * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized
95
- * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable
96
- * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).
97
- *
98
- * @see docs/about/graduation.md
99
- * @see packages/server/src/maintenance.ts
100
- */
101
- const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT = 512 * 1024;
102
- /**
103
- * The largest snapshot a Cloudflare **free-tier** isolate can safely
104
- * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN
105
- * THRESHOLD, not a runtime cap: an operator who raises
106
- * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker
107
- * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets
108
- * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently
109
- * never advances `log_seq_start` and the tail grows unbounded.
110
- *
111
- * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default
112
- * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget
113
- * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the
114
- * point where one-shot rebuild fills the budget with little margin, so
115
- * anything strictly larger is no longer free-tier-safe. On CF **paid**
116
- * (raised CPU limits), Node, or once §11 chunked snapshots land, a
117
- * larger ceiling is fine — hence this is a one-time `console.warn` at
118
- * handler init, NOT a hard rejection.
119
- *
120
- * @see packages/adapter-cloudflare/src/worker.ts
121
- * @see packages/server/src/maintenance.ts
122
- * @see docs/about/graduation.md
123
- */
124
- const CF_FREE_MAX_SAFE_FOLD_BYTES = 1024 * 1024;
125
- /**
126
- * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry
127
- * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021
128
- * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench
129
- * landed; paid recalibration deferred.
130
- *
131
- * @see docs/about/graduation.md
132
- * @see packages/server/src/maintenance.ts
133
- */
134
- const MAINTENANCE_MAX_FOLD_ROWS = 2048;
135
- /** CF-free profile; the absent-context default. */
136
- const MAINTENANCE_PROFILE_CF_FREE = {
137
- gcInterval: 4,
138
- gcMaxMarks: 20,
139
- gcMaxSweeps: 10,
140
- maxFoldEntriesPerPass: 20,
141
- maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
142
- maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
143
- };
144
- /** Node profile; 10× CF-free caps. */
145
- const MAINTENANCE_PROFILE_NODE = {
146
- gcInterval: 2,
147
- gcMaxMarks: 200,
148
- gcMaxSweeps: 100,
149
- maxFoldEntriesPerPass: 200,
150
- maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,
151
- maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS
152
- };
153
- /**
154
- * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate
155
- * memory — CF recycles isolates). ~once per this many writes.
156
- *
157
- * @see packages/protocol/src/coordination/current-json.ts
158
- * @see packages/server/src/maintenance.ts
159
- */
160
- const MAINTENANCE_WARN_INTERVAL_WRITES = 1e3;
161
- /**
162
- * Placeholder for `CurrentJson.snapshot === null` in the
163
- * `_meta.manifest_pointer` cursor emitted on read responses. The
164
- * wire format is `"<snapshot>@<tail_hint>"`, and `null` snapshots
165
- * serialise as this literal so the cursor is never empty and stays
166
- * byte-stable when destructured by operators.
167
- *
168
- * @see packages/server/src/contract.ts (HttpOkMeta)
169
- */
170
- const MANIFEST_POINTER_EMPTY_SNAPSHOT = "none";
171
- /**
172
- * Keys that must never propagate through {@link merge}: assigning to
173
- * them on a plain object pollutes the prototype chain. The literal
174
- * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)
175
- * and bypasses `Object.keys`, but `JSON.parse('{"__proto__":...}')`
176
- * produces a real own property — which is exactly how a malicious
177
- * HTTP PATCH body would arrive on the wire.
178
- *
179
- * Lifted to a constant so every iteration path that touches a
180
- * caller-supplied object can re-use the same defence without
181
- * duplicating the keyword list.
182
- *
183
- * @see packages/protocol/src/json.ts (merge)
184
- * @see docs/spec/json-merge-patch.md
185
- */
186
- const FORBIDDEN_MERGE_KEYS = new Set([
187
- "__proto__",
188
- "constructor",
189
- "prototype"
190
- ]);
191
- /**
192
- * Locked error wording for the "no auth configured" failure mode. The
193
- * adapter throws this when neither `config.auth` nor `verifier:`
194
- * resolves a real `Verifier`. Pinned via a regression test so future
195
- * refactors do not drift the operator-facing wording.
196
- *
197
- * Consumed by:
198
- * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)
199
- * - `packages/adapter-node/src/server.ts` (first-fetch throw)
200
- * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)
201
- */
202
- const NO_AUTH_CONFIGURED_MESSAGE = "baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.";
203
- /**
204
- * Locked error wording for `auth: "shared-secret"` + missing env var.
205
- * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.
206
- */
207
- const SHARED_SECRET_MISSING_MESSAGE = "baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.";
208
- //#endregion
209
11
  //#region packages/protocol/src/coordination/current-json.ts
210
12
  /**
211
13
  * `current.json` — the per-collection compaction-state control object —
@@ -346,12 +148,12 @@ const encodeJson = (json) => encodeJsonBytes(json);
346
148
  * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws
347
149
  * `BaerlyError{code:"InvalidResponse"}` rather than coercing. Tolerant
348
150
  * reader: unknown keys ignored, new required fields bump
349
- * `schema_version` (move (b), ADR-007).
151
+ * `schema_version` (move (b), ADR-003).
350
152
  */
351
153
  const assertCurrentJson = (parsed, key) => {
352
154
  if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: parsed body is not an object`);
353
155
  const r = parsed;
354
- if (r["schema_version"] === 1 || r["schema_version"] === 2) throw new BaerlyError("InvalidResponse", `current.json at ${key} is a pre-single-write-commit current.json; re-provision the bucket. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`);
156
+ if (r["schema_version"] === 1 || r["schema_version"] === 2) throw new BaerlyError("InvalidResponse", `current.json at ${key} uses schema v${String(r["schema_version"])} from a pre-0.3.0 internal build; this build requires schema v3. Dump/restore with the old build, or re-provision scratch/local buckets.`);
355
157
  if (r["schema_version"] !== 3) throw new BaerlyError("InvalidResponse", `current.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; this build requires 3. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \`rm -rf .baerly-data\`) or recreate the R2/S3 bucket, then retry.`);
356
158
  if (!(typeof r["snapshot"] === "string" || r["snapshot"] === null)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot must be string|null`);
357
159
  if (typeof r["tail_hint"] !== "number" || !Number.isInteger(r["tail_hint"]) || r["tail_hint"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: tail_hint must be a non-negative integer`);
@@ -383,6 +185,6 @@ const translateCasError = (e, key) => {
383
185
  return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, e);
384
186
  };
385
187
  //#endregion
386
- export { NO_AUTH_CONFIGURED_MESSAGE as _, CF_FREE_MAX_SAFE_FOLD_BYTES as a, decodeJsonBytes as b, GC_MAX_PENDING_CANDIDATES as c, MAINTENANCE_MIN_LIVE_BYTES as d, MAINTENANCE_PROFILE_CF_FREE as f, MAX_KEY_BYTES as g, MANIFEST_POINTER_EMPTY_SNAPSHOT as h, readCurrentJson as i, GC_PENDING_CONTENT_TYPE as l, MAINTENANCE_WARN_INTERVAL_WRITES as m, createCurrentJson as n, FORBIDDEN_MERGE_KEYS as o, MAINTENANCE_PROFILE_NODE as p, logSeqStartOf as r, GC_GRACE_PERIOD_MILLIS as s, casUpdateCurrentJson as t, LOG_FORWARD_PROBE_CAP as u, RATE_LIMIT_BACKOFF_MILLIS as v, encodeJsonBytes as x, SHARED_SECRET_MISSING_MESSAGE as y };
188
+ export { decodeJsonBytes as a, readCurrentJson as i, createCurrentJson as n, encodeJsonBytes as o, logSeqStartOf as r, casUpdateCurrentJson as t };
387
189
 
388
- //# sourceMappingURL=current-json-DsN7FNY1.js.map
190
+ //# sourceMappingURL=current-json-C6nhPOm1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"current-json-C6nhPOm1.js","names":[],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n","/**\n * `current.json` — the per-collection compaction-state control object —\n * and its embedded, currently dormant {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps snapshot\n * generations by CAS-writing this object; the Writer reads it on every\n * commit to find the snapshot pointer and a non-authoritative\n * tail-probe floor. The numbered log create mints the next integer\n * `seq`; no commit-path code CAS-advances `current.json`.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `3`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 3;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Non-authoritative monotone lower bound on the committed log tail.\n * The authoritative tail is discovered by forward-probe (log-tail.ts);\n * never trust this as the head. Durable advancement is owned by\n * compaction folds, write-tick tail refreshes, and explicit\n * operator/import paths; ordinary writer commits do not refresh it.\n */\n tail_hint: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, tail_hint)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= tail_hint`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /**\n * Row count of the snapshot (= compactor `base.size`, free). With\n * `tail_hint - log_seq_start` (trusted tail entries) this gives the\n * fold's entry count for the ENTRY ceiling `E`. Seeded 0.\n */\n snapshot_rows: number;\n\n /**\n * Optional compactor-stamped mean folded-entry byte size. Maintenance\n * derives live-tail bytes as `entry_count × mean_entry_bytes` without\n * an exact stored counter; absent until first fold.\n */\n mean_entry_bytes?: number;\n\n /**\n * Baseline for rate-limiting the graduation defer-warn off SHARED\n * durable state, not per-isolate memory. The warn fires when the\n * observed/probed tail minus `last_warned_seq` reaches\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes\n * `last_warned_seq` to the observed/probed tail. Absent → 0.\n */\n last_warned_seq?: number;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and is not\n * consumed by the current kernel. Log entries are not stamped with this\n * epoch; the fence is dormant authority metadata, not a reader replay\n * filter.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. In the earlier two-write commit design, every commit checked\n * the epoch before continuing under `current.json` authority. Under\n * single-write commit no production path reads or writes the fence.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Under single-write commit this is retained\n * as an explicit admin/testing primitive only; no production commit\n * path claims or verifies the fence.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the dormant write fence by bumping `epoch` and\n * stamping `claimed_at` from `StoragePutResult.serverDate`. Under\n * single-write commit there is no production commit-path call site;\n * this is retained for explicit admin/testing workflows and future\n * rotation designs.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // Stryker disable next-line ConditionalExpression: `→true` spreads `{lease_until: undefined}` which JSON.stringify omits, so the stored bytes are identical to the normal `→false` path (no key emitted). Genuine equivalent mutant.\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, tail_hint)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-003).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1 || r[\"schema_version\"] === 2) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} uses schema v${String(r[\"schema_version\"])} from a pre-0.3.0 internal build; this build requires schema v${CURRENT_JSON_SCHEMA_VERSION}. Dump/restore with the old build, or re-provision scratch/local buckets.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; this build requires ${CURRENT_JSON_SCHEMA_VERSION}. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \\`rm -rf .baerly-data\\`) or recreate the R2/S3 bucket, then retry.`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"tail_hint\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"tail_hint\"] < 0` → false is subsumed by the downstream `log_seq_start > tail_hint` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_tail_hint always fires); (3) StringLiteral \"tail_hint\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (\n typeof r[\"tail_hint\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_hint\"]) ||\n r[\"tail_hint\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_hint must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"tail_hint\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > tail_hint ${String(r[\"tail_hint\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: `typeof f[\"epoch\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof guard fully subsumed.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_rows\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: `typeof r[\"last_warned_seq\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n if (\n r[\"mean_entry_bytes\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: typeof → false is subsumed by !Number.isInteger.\n (typeof r[\"mean_entry_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"mean_entry_bytes\"]) ||\n r[\"mean_entry_bytes\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n"],"mappings":";;;;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC;AAEhD,MAAa,mBAAgC,UAC3C,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACiM5C,eAAsB,gBACpB,SACA,KACA,MACiC;CACjC,MAAM,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI;CACvC,IAAI,QAAQ,MACV,OAAO;CAET,MAAM,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,IAAI,IAAI;CAC9C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,IAAI;CAC1B,SAAS,OAAO;EACd,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,2BACvB,KACF;CACF;CACA,OAAO;EAAE,MAAM,kBAAkB,QAAQ,GAAG;EAAG,MAAM,IAAI;CAAK;AAChE;;;;;;;;;;;AAYA,eAAsB,kBACpB,SACA,KACA,SACA,MAC0B;CAE1B,kBAAkB,SAAS,GAAG;CAC9B,MAAM,OAAO,WAAW,OAAO;CAC/B,MAAM,UAA6B;EACjC,aAAa;EACb,aAAa;EACb,GAAI,MAAM,WAAW,KAAA,KAAa,EAAE,QAAQ,KAAK,OAAO;CAC1D;CACA,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,QAAQ,IAAI,KAAK,MAAM,OAAO;CAC/C,SAAS,OAAO;EACd,MAAM,kBAAkB,OAAO,GAAG;CACpC;CACA,OAAO;EAAE,MAAM;E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zB;CAEF,IACE,EAAE,uBAAuB,KAAA,MAExB,OAAO,EAAE,uBAAuB,YAC/B,CAAC,OAAO,UAAU,EAAE,kBAAkB,KACtC,EAAE,qBAAqB,IAEzB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,4DACzB;CAEF,IACE,EAAE,wBAAwB,KAAA,MAEzB,OAAO,EAAE,wBAAwB,YAChC,CAAC,OAAO,UAAU,EAAE,mBAAmB,KACvC,EAAE,sBAAsB,IAE1B,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,6DACzB;CAEF,OAAO;AACT;;;;;;;;AASA,MAAM,qBAAqB,GAAY,QAA6B;CAClE,IAAI,aAAa,eAAe,EAAE,SAAS,YACzC,OAAO,IAAI,YAAY,YAAY,4BAA4B,IAAI,IAAI,EAAE,WAAW,CAAC;CAEvF,IAAI,aAAa,aACf,OAAO;CAET,OAAO,IAAI,YAAY,mBAAmB,yBAAyB,IAAI,WAAW,OAAO,CAAC,KAAK,CAAC;AAClG"}
@@ -1,5 +1,5 @@
1
- import { a as CollectionNames, d as IndexDefinition, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig, u as SchemaValidator } from "./app-config-BIzyAKzy.js";
2
- import { c as Collection, h as Storage, m as CurrentJsonRead, n as LogEntry } from "./index-DW7GT6M2.js";
1
+ import { a as CollectionNames, d as IndexDefinition, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig, u as SchemaValidator } from "./app-config-DyiFK3_k.js";
2
+ import { f as CurrentJsonRead, n as LogEntry, o as Collection, p as Storage } from "./index-BYk9oCNf.js";
3
3
  //#region packages/server/src/schema.d.ts
4
4
  /**
5
5
  * Run a validator and throw `BaerlyError{code:"SchemaError"}` on failure.
@@ -251,4 +251,4 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
251
251
  }
252
252
  //#endregion
253
253
  export { validateOrThrow as n, Db as t };
254
- //# sourceMappingURL=db-CCT6tDfY.d.ts.map
254
+ //# sourceMappingURL=db-DsPkOVEH.d.ts.map
@@ -1,5 +1,5 @@
1
- import { t as loadAppConfig } from "./config-CGyBopy3.js";
2
- import { t as deployCloudflare } from "./cloudflare-Cn2ibODt.js";
1
+ import { t as loadAppConfig } from "./config-1tv0-Yzm.js";
2
+ import { t as deployCloudflare } from "./cloudflare-DzKBrUlg.js";
3
3
  import { a as setJsonMode, n as emitError, o as BaerlyError, r as emitSuccess, s as defineCommand } from "./baerly.js";
4
4
  //#region src/deploy.ts
5
5
  /**
@@ -35,7 +35,7 @@ const DEPLOY_ARGS = {
35
35
  valueHint: "s3://bucket/prefix"
36
36
  }
37
37
  };
38
- const KNOWN_KEYS = new Set([
38
+ const KNOWN_KEYS = /* @__PURE__ */ new Set([
39
39
  "target",
40
40
  "json",
41
41
  "probeBucket",
@@ -87,4 +87,4 @@ const deploy = defineCommand({
87
87
  //#endregion
88
88
  export { deploy };
89
89
 
90
- //# sourceMappingURL=deploy-BKKyGlSJ.js.map
90
+ //# sourceMappingURL=deploy-DonTr-CV.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deploy-BKKyGlSJ.js","names":[],"sources":["../packages/cli/src/deploy.ts"],"sourcesContent":["/**\n * `baerly deploy` — citty dispatcher.\n *\n * Reads `baerly.config.ts:target` and routes to the matching\n * deploy backend. Today: `cloudflare` only — the `node` example\n * embodies its deployment shape directly (self-host via `node\n * server.js` after your PaaS or container build), so `baerly\n * deploy` rejects `target: \"node\"` with an actionable InvalidConfig.\n *\n * Exit-code contract (standard CLI shape):\n * - 0 success.\n * - 1 user error (InvalidConfig, missing config, unknown target).\n * - 2 storage / external error (NetworkError, Wrangler returned\n * non-zero, anything non-BaerlyError).\n * - 3 protocol invariant (Conflict, Internal, InvalidResponse —\n * should not happen here unless someone hand-edited mid-flight).\n */\n\nimport { defineCommand, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { deployCloudflare } from \"./deploy/cloudflare.ts\";\nimport { emitError, emitSuccess, setJsonMode } from \"./output.ts\";\n\nconst DEPLOY_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).',\n valueHint: \"cloudflare\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n probeBucket: {\n type: \"string\",\n description:\n \"Run a live CAS preflight against this bucket URI before deploying (s3://, file:///, memory://); aborts non-zero if the backend fails the conditional-write / exactly-one-winner probe. Same check as `baerly doctor --bucket`.\",\n valueHint: \"s3://bucket/prefix\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\n \"target\",\n \"json\",\n \"probeBucket\",\n \"probe-bucket\",\n \"_\",\n]);\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst handleDeploy = async (args: ParsedArgs<typeof DEPLOY_ARGS>): Promise<number> => {\n setJsonMode(args.json === true);\n try {\n for (const k of Object.keys(args)) {\n if (!KNOWN_KEYS.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly deploy: unknown flag --${k}`);\n }\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const probeBucketUri =\n typeof args.probeBucket === \"string\" && args.probeBucket.length > 0\n ? args.probeBucket\n : undefined;\n const exit = await deployCloudflare(config, { probeBucketUri });\n if (exit === 0) {\n emitSuccess({ command: \"deploy\", status: \"ok\", target });\n }\n return exit;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. ` +\n `Self-host: \\`node server.js\\` after your PaaS or container build. ` +\n `Cloudflare Workers is the only managed deploy backend today.`,\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(\"deploy\", error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(\"deploy\", \"Unknown\", (error as Error).message);\n return 2;\n }\n};\n\n/** citty `defineCommand` block for `baerly deploy`. */\nexport const deploy = defineCommand({\n meta: {\n name: \"deploy\",\n description: \"Deploy this baerly app. Dispatches by baerly.config.ts:target.\",\n },\n args: DEPLOY_ARGS,\n run: async ({ args }) => {\n const code = await handleDeploy(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\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 runDeploy = async (argv: readonly string[]): Promise<number> => {\n const { parseArgs } = await import(\"citty\");\n let parsed: ParsedArgs<typeof DEPLOY_ARGS>;\n try {\n parsed = parseArgs<typeof DEPLOY_ARGS>(argv as string[], DEPLOY_ARGS);\n } catch (error) {\n setJsonMode(argv.includes(\"--json\"));\n emitError(\"deploy\", \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return handleDeploy(parsed);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,aAAa;EACX,MAAM;EACN,aACE;EACF,WAAW;CACb;AACF;AAEA,MAAM,aAAkC,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;AAEA,MAAM,eAAe,OAAO,SAA0D;CACpF,YAAY,KAAK,SAAS,IAAI;CAC9B,IAAI;EACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,WAAW,IAAI,CAAC,GACnB,MAAM,IAAI,YAAY,iBAAiB,iCAAiC,GAAG;EAG/E,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAK3B,MAAM,OAAO,MAAM,iBAAiB,QAAQ,EAAE,gBAH5C,OAAO,KAAK,gBAAgB,YAAY,KAAK,YAAY,SAAS,IAC9D,KAAK,cACL,KAAA,EACuD,CAAC;GAC9D,IAAI,SAAS,GACX,YAAY;IAAE,SAAS;IAAU,QAAQ;IAAM;GAAO,CAAC;GAEzD,OAAO;EACT;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,uJAGlD;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,aAAa;GAChC,UAAU,UAAU,MAAM,MAAM,MAAM,OAAO;GAC7C,OAAO,gBAAgB,MAAM,IAAI;EACnC;EACA,UAAU,UAAU,WAAY,MAAgB,OAAO;EACvD,OAAO;CACT;AACF;;AAGA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,OAAO,MAAM,aAAa,IAAI;EACpC,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;CAErB;AACF,CAAC"}
1
+ {"version":3,"file":"deploy-DonTr-CV.js","names":[],"sources":["../packages/cli/src/deploy.ts"],"sourcesContent":["/**\n * `baerly deploy` — citty dispatcher.\n *\n * Reads `baerly.config.ts:target` and routes to the matching\n * deploy backend. Today: `cloudflare` only — the `node` example\n * embodies its deployment shape directly (self-host via `node\n * server.js` after your PaaS or container build), so `baerly\n * deploy` rejects `target: \"node\"` with an actionable InvalidConfig.\n *\n * Exit-code contract (standard CLI shape):\n * - 0 success.\n * - 1 user error (InvalidConfig, missing config, unknown target).\n * - 2 storage / external error (NetworkError, Wrangler returned\n * non-zero, anything non-BaerlyError).\n * - 3 protocol invariant (Conflict, Internal, InvalidResponse —\n * should not happen here unless someone hand-edited mid-flight).\n */\n\nimport { defineCommand, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { deployCloudflare } from \"./deploy/cloudflare.ts\";\nimport { emitError, emitSuccess, setJsonMode } from \"./output.ts\";\n\nconst DEPLOY_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).',\n valueHint: \"cloudflare\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n probeBucket: {\n type: \"string\",\n description:\n \"Run a live CAS preflight against this bucket URI before deploying (s3://, file:///, memory://); aborts non-zero if the backend fails the conditional-write / exactly-one-winner probe. Same check as `baerly doctor --bucket`.\",\n valueHint: \"s3://bucket/prefix\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\n \"target\",\n \"json\",\n \"probeBucket\",\n \"probe-bucket\",\n \"_\",\n]);\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst handleDeploy = async (args: ParsedArgs<typeof DEPLOY_ARGS>): Promise<number> => {\n setJsonMode(args.json === true);\n try {\n for (const k of Object.keys(args)) {\n if (!KNOWN_KEYS.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly deploy: unknown flag --${k}`);\n }\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const probeBucketUri =\n typeof args.probeBucket === \"string\" && args.probeBucket.length > 0\n ? args.probeBucket\n : undefined;\n const exit = await deployCloudflare(config, { probeBucketUri });\n if (exit === 0) {\n emitSuccess({ command: \"deploy\", status: \"ok\", target });\n }\n return exit;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. ` +\n `Self-host: \\`node server.js\\` after your PaaS or container build. ` +\n `Cloudflare Workers is the only managed deploy backend today.`,\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(\"deploy\", error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(\"deploy\", \"Unknown\", (error as Error).message);\n return 2;\n }\n};\n\n/** citty `defineCommand` block for `baerly deploy`. */\nexport const deploy = defineCommand({\n meta: {\n name: \"deploy\",\n description: \"Deploy this baerly app. Dispatches by baerly.config.ts:target.\",\n },\n args: DEPLOY_ARGS,\n run: async ({ args }) => {\n const code = await handleDeploy(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\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 runDeploy = async (argv: readonly string[]): Promise<number> => {\n const { parseArgs } = await import(\"citty\");\n let parsed: ParsedArgs<typeof DEPLOY_ARGS>;\n try {\n parsed = parseArgs<typeof DEPLOY_ARGS>(argv as string[], DEPLOY_ARGS);\n } catch (error) {\n setJsonMode(argv.includes(\"--json\"));\n emitError(\"deploy\", \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return handleDeploy(parsed);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,aAAa;EACX,MAAM;EACN,aACE;EACF,WAAW;CACb;AACF;AAEA,MAAM,6BAAkC,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;AAEA,MAAM,eAAe,OAAO,SAA0D;CACpF,YAAY,KAAK,SAAS,IAAI;CAC9B,IAAI;EACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,WAAW,IAAI,CAAC,GACnB,MAAM,IAAI,YAAY,iBAAiB,iCAAiC,GAAG;EAG/E,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAK3B,MAAM,OAAO,MAAM,iBAAiB,QAAQ,EAAE,gBAH5C,OAAO,KAAK,gBAAgB,YAAY,KAAK,YAAY,SAAS,IAC9D,KAAK,cACL,KAAA,EACuD,CAAC;GAC9D,IAAI,SAAS,GACX,YAAY;IAAE,SAAS;IAAU,QAAQ;IAAM;GAAO,CAAC;GAEzD,OAAO;EACT;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,uJAGlD;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,aAAa;GAChC,UAAU,UAAU,MAAM,MAAM,MAAM,OAAO;GAC7C,OAAO,gBAAgB,MAAM,IAAI;EACnC;EACA,UAAU,UAAU,WAAY,MAAgB,OAAO;EACvD,OAAO;CACT;AACF;;AAGA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,OAAO,MAAM,aAAa,IAAI;EACpC,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;CAErB;AACF,CAAC"}
@@ -1,7 +1,7 @@
1
- import { n as BaerlyAppConfig } from "./app-config-BIzyAKzy.js";
2
- import { r as Verifier } from "./index-DW7GT6M2.js";
1
+ import { n as BaerlyAppConfig } from "./app-config-DyiFK3_k.js";
2
+ import { r as Verifier } from "./index-BYk9oCNf.js";
3
3
  import { t as DevBannerHint } from "./dev-banner-CWHIk8tH.js";
4
- import { t as Db } from "./db-CCT6tDfY.js";
4
+ import { t as Db } from "./db-DsPkOVEH.js";
5
5
  import { Plugin } from "vite";
6
6
 
7
7
  //#region packages/dev/src/vite-plugin.d.ts
@@ -36,8 +36,12 @@ interface BaerlyDevOptions {
36
36
  * staging IdP, or any custom auth shape.
37
37
  */
38
38
  readonly verifier?: Verifier;
39
- /** Absolute path to the data directory for LocalFsStorage. */
40
- readonly dataDir: string;
39
+ /**
40
+ * Absolute path to the data directory for LocalFsStorage.
41
+ * **Optional** — defaults to `<vite root>/.baerly-data`, so the dev
42
+ * server runs zero-config.
43
+ */
44
+ readonly dataDir?: string;
41
45
  /** Optional async seed callback, invoked after ensureTable, before mount. */
42
46
  readonly seed?: (db: Db) => Promise<void>;
43
47
  /** Extra hints appended to the dev banner. */
package/dist/dev-vite.js CHANGED
@@ -1,6 +1,7 @@
1
- import { n as resolveVerifier, t as Db } from "./src-Db4-qVtM.js";
2
- import { i as printDevBanner, n as ensureTable, t as LocalFsStorage } from "./src-CWpkSbvJ.js";
3
- import { n as getRequestListener, t as baerlyNode } from "./src-D24wDpzR.js";
1
+ import { n as resolveVerifier, t as Db } from "./src-CYHFDrKz.js";
2
+ import { n as getRequestListener, t as baerlyNode } from "./src-D__mHQmQ.js";
3
+ import { i as printDevBanner, n as ensureTable, t as LocalFsStorage } from "./src-DYZ4H1aF.js";
4
+ import { resolve } from "node:path";
4
5
  import { existsSync, readFileSync } from "node:fs";
5
6
  //#region packages/dev/src/vite-plugin.ts
6
7
  const isV1Path = (url) => url === "/v1" || url.startsWith("/v1/") || url.startsWith("/v1?");
@@ -158,7 +159,7 @@ function baerlyDev(opts) {
158
159
  const tenant = opts.config.tenant;
159
160
  const tables = Object.keys(opts.config.collections);
160
161
  const ready = (async () => {
161
- const storage = new LocalFsStorage({ root: opts.dataDir });
162
+ const storage = new LocalFsStorage({ root: opts.dataDir ?? resolve(server.config.root, ".baerly-data") });
162
163
  for (const table of tables) await ensureTable(storage, {
163
164
  app,
164
165
  tenant,
@@ -1 +1 @@
1
- {"version":3,"file":"dev-vite.js","names":[],"sources":["../packages/dev/src/vite-plugin.ts"],"sourcesContent":["import type { AddressInfo } from \"node:net\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport type { Plugin } from \"vite\";\nimport { baerlyNode } from \"@baerly/adapter-node\";\nimport type { BaerlyAppConfig, Verifier } from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { type DevBannerHint, printDevBanner } from \"./dev-banner.ts\";\nimport { ensureTable } from \"./ensure-table.ts\";\nimport { LocalFsStorage } from \"./local-fs.ts\";\n\nexport interface BaerlyDevOptions {\n /**\n * The project's `baerly.config.ts`. `app`, `tenant`, `auth`, and the\n * table set (`Object.keys(config.collections)`) are derived from it.\n * Per-collection schemas/indexes flow through to the in-process\n * listener the same way `baerlyNode` / `baerlyWorker` pipe them.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Shared-secret token. **Optional.** Required only when\n * `config.auth === \"shared-secret\"` and `verifier` is unset — in\n * that branch, clients must send `Authorization: Bearer <secret>`\n * AND the middleware injects the same bearer server-side before\n * forwarding to the in-process listener.\n *\n * Ignored when `config.auth === \"none\"` (no bearer to inject) or\n * when `verifier` is supplied (the operator owns the auth seam).\n *\n * Throwing the symmetric `InvalidConfig` on a misconfig matches\n * production behaviour: forgetting `SHARED_SECRET` in dev fails\n * fast at `vite dev` startup with the same locked wording the\n * adapter would emit.\n */\n readonly secret?: string;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides both\n * `config.auth` and `secret` (same precedence as the production\n * adapter factories). Use for dev-mode JWT validation against a\n * staging IdP, or any custom auth shape.\n */\n readonly verifier?: Verifier;\n /** Absolute path to the data directory for LocalFsStorage. */\n readonly dataDir: string;\n /** Optional async seed callback, invoked after ensureTable, before mount. */\n readonly seed?: (db: Db) => Promise<void>;\n /** Extra hints appended to the dev banner. */\n readonly hints?: readonly DevBannerHint[];\n /** Set to false to suppress the dev banner. Default: true. */\n readonly banner?: boolean;\n}\n\nconst isV1Path = (url: string): boolean =>\n url === \"/v1\" || url.startsWith(\"/v1/\") || url.startsWith(\"/v1?\");\n\n/**\n * Inject `Authorization: ${value}` into a Node `IncomingMessage` such\n * that BOTH the parsed (`req.headers`) and the wire-form (`req.rawHeaders`)\n * views agree.\n *\n * Why both: `req.headers` is the parsed-and-lowercased JS map most\n * connect-style middleware reads, but Node→Fetch bridges typically\n * rebuild the Fetch `Headers` from `req.rawHeaders` (the original\n * `[name, value, name, value, …]` wire array) to preserve case and\n * multi-value semantics. `@cloudflare/vite-plugin`'s `createHeaders()`\n * does exactly that — so mutating `req.headers` alone silently drops\n * the bearer token when the in-process Worker receives the request.\n * Treat any new injection in this file as obligated to touch both.\n */\nconst injectAuthorizationHeader = (\n req: {\n headers: Record<string, string | string[] | undefined>;\n rawHeaders?: string[];\n },\n value: string,\n): void => {\n req.headers[\"authorization\"] = value;\n const raw = req.rawHeaders;\n if (raw === undefined) {\n return;\n }\n for (let i = 0; i < raw.length; i += 2) {\n if (raw[i]!.toLowerCase() === \"authorization\") {\n raw[i + 1] = value;\n return;\n }\n }\n raw.push(\"Authorization\", value);\n};\n\nexport interface BaerlyDevAuthOptions {\n /** Bearer token to inject on matched paths. */\n readonly secret: string;\n /**\n * Pathname prefixes to match. Default `[\"/v1\", \"/api\"]` — the\n * baerly cascade lives at `/v1/*`, and `/api/*` is the canonical\n * namespace for custom Worker routes (the \"wrap `baerly.fetch!`\"\n * recipe in the scaffold's AGENTS.md). Covering both by default\n * closes a recurring \"added a custom route, browser silently 401s\"\n * trap: agents typically edit `src/server/index.ts` without touching\n * `vite.config.ts`, so a `\"/v1\"`-only default leaves their new route\n * unauthenticated in `vite dev` and `pnpm verify` is silent on it.\n *\n * Override when you mount under a different namespace, or pass\n * `prefix: \"/v1\"` to opt out of `/api/*` injection entirely (rare —\n * the bearer is a harmless extra header on unmatched routes).\n */\n readonly prefix?: string | readonly string[];\n}\n\nconst normalisePrefixes = (prefix: string | readonly string[] | undefined): readonly string[] => {\n if (prefix === undefined) {\n return [\"/v1\", \"/api\"];\n }\n if (typeof prefix === \"string\") {\n return [prefix];\n }\n return prefix;\n};\n\nconst matchesAnyPrefix = (url: string, prefixes: readonly string[]): boolean => {\n for (const prefix of prefixes) {\n if (url === prefix || url.startsWith(`${prefix}/`) || url.startsWith(`${prefix}?`)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Vite dev plugin: inject `Authorization: Bearer ${secret}` on every\n * request whose URL starts with one of `prefix` (default\n * `[\"/v1\", \"/api\"]`). Use this to keep the bearer token out of the\n * SPA bundle — the browser sends the request, Vite's middleware adds\n * the header, and the upstream handler (in-process worker or proxied\n * Node server) sees an authenticated request.\n *\n * **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the\n * default `prefix` also covers `/api/*` because that's the canonical\n * namespace for the \"wrap `baerly.fetch!`\" recipe (a server-side\n * endpoint the SPA client can't run on its own, e.g. an endpoint\n * that fans a write across several documents server-side). If you\n * mount under a different namespace, override:\n *\n * ```ts\n * baerlyDevAuth({ secret, prefix: [\"/v1\", \"/internal\"] });\n * ```\n *\n * The bearer is dev-only convenience — production deploys put the\n * SPA, the baerly cascade, AND your custom routes behind the same\n * tenant boundary (CF Access, an upstream JWT, …), so this matters\n * exclusively while `vite dev` is the front door.\n *\n * @example\n * ```ts\n * import { baerlyDevAuth, loadDevVars } from \"@gusto/baerly-storage/dev/vite\";\n *\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * baerlyDevAuth({ secret: SHARED_SECRET ?? \"\" }),\n * ],\n * });\n * ```\n */\nexport function baerlyDevAuth(opts: BaerlyDevAuthOptions): Plugin {\n if (opts.secret === \"\") {\n throw new Error(\n \"baerlyDevAuth: secret must be non-empty. Set SHARED_SECRET in .dev.vars / .env.\",\n );\n }\n const prefixes: readonly string[] = normalisePrefixes(opts.prefix);\n return {\n name: \"baerly-dev-auth\",\n apply: \"serve\",\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n const url = req.url ?? \"\";\n if (matchesAnyPrefix(url, prefixes)) {\n injectAuthorizationHeader(req, `Bearer ${opts.secret}`);\n }\n next();\n });\n },\n };\n}\n\n/**\n * Parse a `.dev.vars` / `.env` file and return the values for the\n * requested `keys`. Supports `KEY=value`, `# comments`, blank lines,\n * and single- or double-quoted values. Keys missing from the file\n * (or the whole file when it does not exist) come back as\n * `undefined` — fall back with `??` at the call site.\n *\n * The return type is `Record<K, string | undefined>` where `K` is\n * the union of literal key names you pass in, so property access\n * works under strict `noPropertyAccessFromIndexSignature`:\n *\n * ```ts\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * // ^? string | undefined\n * ```\n */\nexport function loadDevVars<K extends string>(\n path: string,\n ...keys: readonly K[]\n): Record<K, string | undefined> {\n const out = {} as Record<K, string | undefined>;\n for (const key of keys) {\n out[key] = undefined;\n }\n if (!existsSync(path)) {\n return out;\n }\n const wanted = new Set<string>(keys);\n for (const rawLine of readFileSync(path, \"utf8\").split(\"\\n\")) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) {\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n if (!wanted.has(key)) {\n continue;\n }\n let value = line.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n out[key as K] = value;\n }\n return out;\n}\n\n/**\n * Resolution order for the in-process verifier (mirrors\n * `baerlyNode` / `baerlyWorker`):\n *\n * 1. `opts.verifier` set → use as-is.\n * 2. else `opts.config.auth === \"shared-secret\"` → require\n * `opts.secret`; build `sharedSecret({ secret, tenantPrefix:\n * config.tenant })`. Throws `BaerlyError(\"InvalidConfig\", ...)`\n * at Vite startup when `opts.secret` is empty/unset — same\n * locked wording the production adapter would emit.\n * 3. else `opts.config.auth === \"none\"` → pin every request to\n * `config.tenant`; no header check.\n *\n * Bearer injection on `/v1/*` only fires in branch 2 (and only when\n * branch 1 didn't win) — the dev convenience that lets the SPA call\n * the listener without putting the secret in the browser bundle.\n * Branch 3 leaves the `Authorization` header alone.\n *\n * Verifier resolution happens eagerly at factory time so a misconfig\n * fails Vite startup, not the first `/v1/*` round-trip.\n */\nexport function baerlyDev(opts: BaerlyDevOptions): Plugin {\n // Resolution order: opts.verifier → config.auth.shared-secret →\n // config.auth.none → throw. Mirrors `baerlyWorker` / `baerlyNode`.\n // The synthetic `readEnv` hoists `opts.secret` to `SHARED_SECRET`\n // so the same resolver works — `baerlyDev` takes the secret as a\n // typed option rather than reading `process.env` directly.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config: opts.config,\n readEnv: (k) => (k === \"SHARED_SECRET\" ? opts.secret : process.env[k]),\n });\n\n // Bearer injection only matters in the shared-secret branch (and\n // only when no override owns auth). For \"none\" or any custom\n // verifier, the `Authorization` header reaches the listener\n // unchanged.\n const bearerForInjection: string | undefined =\n opts.verifier === undefined && opts.config.auth === \"shared-secret\" ? opts.secret : undefined;\n\n return {\n name: \"baerly-dev\",\n apply: \"serve\",\n configureServer(server) {\n // Mount in the configureServer body (not a post-hook) so the\n // middleware runs BEFORE Vite's internal SPA history fallback.\n // Otherwise /v1/* requests get caught by the SPA fallback and\n // served the index.html shell.\n const app = opts.config.app;\n const tenant = opts.config.tenant;\n const tables = Object.keys(opts.config.collections);\n const ready = (async () => {\n const storage = new LocalFsStorage({ root: opts.dataDir });\n for (const table of tables) {\n await ensureTable(storage, { app, tenant, table });\n }\n if (opts.seed !== undefined) {\n const db = Db.create({ storage, app, tenant, config: opts.config });\n await opts.seed(db);\n }\n const requestHandler = baerlyNode({\n config: opts.config,\n storage,\n verifier,\n }).fetch;\n return getRequestListener(requestHandler);\n })();\n\n // Surface setup failures eagerly; without this an unhandled\n // rejection would silently kill the dev server.\n ready.catch((error: unknown) => {\n console.error(\"[baerly-dev] setup failed:\", error);\n });\n\n server.middlewares.use((req, res, next) => {\n const url = req.url;\n if (url === undefined || !isV1Path(url)) {\n next();\n return;\n }\n // Inject the bearer token server-side so the SPA never sees\n // the secret. Only runs for `config.auth === \"shared-secret\"`\n // without a `verifier:` override — otherwise the header\n // reaches the listener unchanged. Mutates both `req.headers`\n // and `req.rawHeaders` — see `injectAuthorizationHeader`'s\n // JSDoc.\n if (bearerForInjection !== undefined) {\n injectAuthorizationHeader(req, `Bearer ${bearerForInjection}`);\n }\n ready.then(\n (listener) => {\n listener(req as never, res as never);\n },\n (error: unknown) => {\n res.statusCode = 503;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"baerly-dev setup failed\", message: String(error) }));\n },\n );\n });\n\n if (opts.banner !== false) {\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n const port =\n typeof address === \"object\" && address !== null\n ? (address as AddressInfo).port\n : undefined;\n const url = port !== undefined ? `http://localhost:${port}/` : \"http://localhost/\";\n printDevBanner({\n name: opts.config.app,\n primaryUrl: { label: \"App\", url },\n ...(opts.hints !== undefined && { hints: opts.hints }),\n });\n });\n }\n },\n };\n}\n"],"mappings":";;;;;AAoDA,MAAM,YAAY,QAChB,QAAQ,SAAS,IAAI,WAAW,MAAM,KAAK,IAAI,WAAW,MAAM;;;;;;;;;;;;;;;AAgBlE,MAAM,6BACJ,KAIA,UACS;CACT,IAAI,QAAQ,mBAAmB;CAC/B,MAAM,MAAM,IAAI;CAChB,IAAI,QAAQ,KAAA,GACV;CAEF,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GACnC,IAAI,IAAI,EAAE,CAAE,YAAY,MAAM,iBAAiB;EAC7C,IAAI,IAAI,KAAK;EACb;CACF;CAEF,IAAI,KAAK,iBAAiB,KAAK;AACjC;AAsBA,MAAM,qBAAqB,WAAsE;CAC/F,IAAI,WAAW,KAAA,GACb,OAAO,CAAC,OAAO,MAAM;CAEvB,IAAI,OAAO,WAAW,UACpB,OAAO,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,IAAI,uBAAuB,KAAA,GACzB,0BAA0B,KAAK,UAAU,oBAAoB;IAE/D,MAAM,MACH,aAAa;KACZ,SAAS,KAAc,GAAY;IACrC,IACC,UAAmB;KAClB,IAAI,aAAa;KACjB,IAAI,UAAU,gBAAgB,kBAAkB;KAChD,IAAI,IAAI,KAAK,UAAU;MAAE,OAAO;MAA2B,SAAS,OAAO,KAAK;KAAE,CAAC,CAAC;IACtF,CACF;GACF,CAAC;GAED,IAAI,KAAK,WAAW,OAClB,OAAO,YAAY,KAAK,mBAAmB;IACzC,MAAM,UAAU,OAAO,YAAY,QAAQ;IAC3C,MAAM,OACJ,OAAO,YAAY,YAAY,YAAY,OACtC,QAAwB,OACzB,KAAA;IACN,MAAM,MAAM,SAAS,KAAA,IAAY,oBAAoB,KAAK,KAAK;IAC/D,eAAe;KACb,MAAM,KAAK,OAAO;KAClB,YAAY;MAAE,OAAO;MAAO;KAAI;KAChC,GAAI,KAAK,UAAU,KAAA,KAAa,EAAE,OAAO,KAAK,MAAM;IACtD,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
1
+ {"version":3,"file":"dev-vite.js","names":[],"sources":["../packages/dev/src/vite-plugin.ts"],"sourcesContent":["import type { AddressInfo } from \"node:net\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { getRequestListener } from \"@hono/node-server\";\nimport type { Plugin } from \"vite\";\nimport { baerlyNode } from \"@baerly/adapter-node\";\nimport type { BaerlyAppConfig, Verifier } from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { type DevBannerHint, printDevBanner } from \"./dev-banner.ts\";\nimport { ensureTable } from \"./ensure-table.ts\";\nimport { LocalFsStorage } from \"./local-fs.ts\";\n\nexport interface BaerlyDevOptions {\n /**\n * The project's `baerly.config.ts`. `app`, `tenant`, `auth`, and the\n * table set (`Object.keys(config.collections)`) are derived from it.\n * Per-collection schemas/indexes flow through to the in-process\n * listener the same way `baerlyNode` / `baerlyWorker` pipe them.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Shared-secret token. **Optional.** Required only when\n * `config.auth === \"shared-secret\"` and `verifier` is unset — in\n * that branch, clients must send `Authorization: Bearer <secret>`\n * AND the middleware injects the same bearer server-side before\n * forwarding to the in-process listener.\n *\n * Ignored when `config.auth === \"none\"` (no bearer to inject) or\n * when `verifier` is supplied (the operator owns the auth seam).\n *\n * Throwing the symmetric `InvalidConfig` on a misconfig matches\n * production behaviour: forgetting `SHARED_SECRET` in dev fails\n * fast at `vite dev` startup with the same locked wording the\n * adapter would emit.\n */\n readonly secret?: string;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides both\n * `config.auth` and `secret` (same precedence as the production\n * adapter factories). Use for dev-mode JWT validation against a\n * staging IdP, or any custom auth shape.\n */\n readonly verifier?: Verifier;\n /**\n * Absolute path to the data directory for LocalFsStorage.\n * **Optional** — defaults to `<vite root>/.baerly-data`, so the dev\n * server runs zero-config.\n */\n readonly dataDir?: string;\n /** Optional async seed callback, invoked after ensureTable, before mount. */\n readonly seed?: (db: Db) => Promise<void>;\n /** Extra hints appended to the dev banner. */\n readonly hints?: readonly DevBannerHint[];\n /** Set to false to suppress the dev banner. Default: true. */\n readonly banner?: boolean;\n}\n\nconst isV1Path = (url: string): boolean =>\n url === \"/v1\" || url.startsWith(\"/v1/\") || url.startsWith(\"/v1?\");\n\n/**\n * Inject `Authorization: ${value}` into a Node `IncomingMessage` such\n * that BOTH the parsed (`req.headers`) and the wire-form (`req.rawHeaders`)\n * views agree.\n *\n * Why both: `req.headers` is the parsed-and-lowercased JS map most\n * connect-style middleware reads, but Node→Fetch bridges typically\n * rebuild the Fetch `Headers` from `req.rawHeaders` (the original\n * `[name, value, name, value, …]` wire array) to preserve case and\n * multi-value semantics. `@cloudflare/vite-plugin`'s `createHeaders()`\n * does exactly that — so mutating `req.headers` alone silently drops\n * the bearer token when the in-process Worker receives the request.\n * Treat any new injection in this file as obligated to touch both.\n */\nconst injectAuthorizationHeader = (\n req: {\n headers: Record<string, string | string[] | undefined>;\n rawHeaders?: string[];\n },\n value: string,\n): void => {\n req.headers[\"authorization\"] = value;\n const raw = req.rawHeaders;\n if (raw === undefined) {\n return;\n }\n for (let i = 0; i < raw.length; i += 2) {\n if (raw[i]!.toLowerCase() === \"authorization\") {\n raw[i + 1] = value;\n return;\n }\n }\n raw.push(\"Authorization\", value);\n};\n\nexport interface BaerlyDevAuthOptions {\n /** Bearer token to inject on matched paths. */\n readonly secret: string;\n /**\n * Pathname prefixes to match. Default `[\"/v1\", \"/api\"]` — the\n * baerly cascade lives at `/v1/*`, and `/api/*` is the canonical\n * namespace for custom Worker routes (the \"wrap `baerly.fetch!`\"\n * recipe in the scaffold's AGENTS.md). Covering both by default\n * closes a recurring \"added a custom route, browser silently 401s\"\n * trap: agents typically edit `src/server/index.ts` without touching\n * `vite.config.ts`, so a `\"/v1\"`-only default leaves their new route\n * unauthenticated in `vite dev` and `pnpm verify` is silent on it.\n *\n * Override when you mount under a different namespace, or pass\n * `prefix: \"/v1\"` to opt out of `/api/*` injection entirely (rare —\n * the bearer is a harmless extra header on unmatched routes).\n */\n readonly prefix?: string | readonly string[];\n}\n\nconst normalisePrefixes = (prefix: string | readonly string[] | undefined): readonly string[] => {\n if (prefix === undefined) {\n return [\"/v1\", \"/api\"];\n }\n if (typeof prefix === \"string\") {\n return [prefix];\n }\n return prefix;\n};\n\nconst matchesAnyPrefix = (url: string, prefixes: readonly string[]): boolean => {\n for (const prefix of prefixes) {\n if (url === prefix || url.startsWith(`${prefix}/`) || url.startsWith(`${prefix}?`)) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Vite dev plugin: inject `Authorization: Bearer ${secret}` on every\n * request whose URL starts with one of `prefix` (default\n * `[\"/v1\", \"/api\"]`). Use this to keep the bearer token out of the\n * SPA bundle — the browser sends the request, Vite's middleware adds\n * the header, and the upstream handler (in-process worker or proxied\n * Node server) sees an authenticated request.\n *\n * **Custom Worker routes.** `baerlyWorker` only sees `/v1/*`; the\n * default `prefix` also covers `/api/*` because that's the canonical\n * namespace for the \"wrap `baerly.fetch!`\" recipe (a server-side\n * endpoint the SPA client can't run on its own, e.g. an endpoint\n * that fans a write across several documents server-side). If you\n * mount under a different namespace, override:\n *\n * ```ts\n * baerlyDevAuth({ secret, prefix: [\"/v1\", \"/internal\"] });\n * ```\n *\n * The bearer is dev-only convenience — production deploys put the\n * SPA, the baerly cascade, AND your custom routes behind the same\n * tenant boundary (CF Access, an upstream JWT, …), so this matters\n * exclusively while `vite dev` is the front door.\n *\n * @example\n * ```ts\n * import { baerlyDevAuth, loadDevVars } from \"@gusto/baerly-storage/dev/vite\";\n *\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * export default defineConfig({\n * plugins: [\n * cloudflare(),\n * baerlyDevAuth({ secret: SHARED_SECRET ?? \"\" }),\n * ],\n * });\n * ```\n */\nexport function baerlyDevAuth(opts: BaerlyDevAuthOptions): Plugin {\n if (opts.secret === \"\") {\n throw new Error(\n \"baerlyDevAuth: secret must be non-empty. Set SHARED_SECRET in .dev.vars / .env.\",\n );\n }\n const prefixes: readonly string[] = normalisePrefixes(opts.prefix);\n return {\n name: \"baerly-dev-auth\",\n apply: \"serve\",\n configureServer(server) {\n server.middlewares.use((req, _res, next) => {\n const url = req.url ?? \"\";\n if (matchesAnyPrefix(url, prefixes)) {\n injectAuthorizationHeader(req, `Bearer ${opts.secret}`);\n }\n next();\n });\n },\n };\n}\n\n/**\n * Parse a `.dev.vars` / `.env` file and return the values for the\n * requested `keys`. Supports `KEY=value`, `# comments`, blank lines,\n * and single- or double-quoted values. Keys missing from the file\n * (or the whole file when it does not exist) come back as\n * `undefined` — fall back with `??` at the call site.\n *\n * The return type is `Record<K, string | undefined>` where `K` is\n * the union of literal key names you pass in, so property access\n * works under strict `noPropertyAccessFromIndexSignature`:\n *\n * ```ts\n * const { SHARED_SECRET } = loadDevVars(\".dev.vars\", \"SHARED_SECRET\");\n * // ^? string | undefined\n * ```\n */\nexport function loadDevVars<K extends string>(\n path: string,\n ...keys: readonly K[]\n): Record<K, string | undefined> {\n const out = {} as Record<K, string | undefined>;\n for (const key of keys) {\n out[key] = undefined;\n }\n if (!existsSync(path)) {\n return out;\n }\n const wanted = new Set<string>(keys);\n for (const rawLine of readFileSync(path, \"utf8\").split(\"\\n\")) {\n const line = rawLine.trim();\n if (line === \"\" || line.startsWith(\"#\")) {\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) {\n continue;\n }\n const key = line.slice(0, eq).trim();\n if (!wanted.has(key)) {\n continue;\n }\n let value = line.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n out[key as K] = value;\n }\n return out;\n}\n\n/**\n * Resolution order for the in-process verifier (mirrors\n * `baerlyNode` / `baerlyWorker`):\n *\n * 1. `opts.verifier` set → use as-is.\n * 2. else `opts.config.auth === \"shared-secret\"` → require\n * `opts.secret`; build `sharedSecret({ secret, tenantPrefix:\n * config.tenant })`. Throws `BaerlyError(\"InvalidConfig\", ...)`\n * at Vite startup when `opts.secret` is empty/unset — same\n * locked wording the production adapter would emit.\n * 3. else `opts.config.auth === \"none\"` → pin every request to\n * `config.tenant`; no header check.\n *\n * Bearer injection on `/v1/*` only fires in branch 2 (and only when\n * branch 1 didn't win) — the dev convenience that lets the SPA call\n * the listener without putting the secret in the browser bundle.\n * Branch 3 leaves the `Authorization` header alone.\n *\n * Verifier resolution happens eagerly at factory time so a misconfig\n * fails Vite startup, not the first `/v1/*` round-trip.\n */\nexport function baerlyDev(opts: BaerlyDevOptions): Plugin {\n // Resolution order: opts.verifier → config.auth.shared-secret →\n // config.auth.none → throw. Mirrors `baerlyWorker` / `baerlyNode`.\n // The synthetic `readEnv` hoists `opts.secret` to `SHARED_SECRET`\n // so the same resolver works — `baerlyDev` takes the secret as a\n // typed option rather than reading `process.env` directly.\n const verifier = resolveVerifier({\n factoryVerifier: opts.verifier,\n config: opts.config,\n readEnv: (k) => (k === \"SHARED_SECRET\" ? opts.secret : process.env[k]),\n });\n\n // Bearer injection only matters in the shared-secret branch (and\n // only when no override owns auth). For \"none\" or any custom\n // verifier, the `Authorization` header reaches the listener\n // unchanged.\n const bearerForInjection: string | undefined =\n opts.verifier === undefined && opts.config.auth === \"shared-secret\" ? opts.secret : undefined;\n\n return {\n name: \"baerly-dev\",\n apply: \"serve\",\n configureServer(server) {\n // Mount in the configureServer body (not a post-hook) so the\n // middleware runs BEFORE Vite's internal SPA history fallback.\n // Otherwise /v1/* requests get caught by the SPA fallback and\n // served the index.html shell.\n const app = opts.config.app;\n const tenant = opts.config.tenant;\n const tables = Object.keys(opts.config.collections);\n const ready = (async () => {\n const storage = new LocalFsStorage({\n root: opts.dataDir ?? resolve(server.config.root, \".baerly-data\"),\n });\n for (const table of tables) {\n await ensureTable(storage, { app, tenant, table });\n }\n if (opts.seed !== undefined) {\n const db = Db.create({ storage, app, tenant, config: opts.config });\n await opts.seed(db);\n }\n const requestHandler = baerlyNode({\n config: opts.config,\n storage,\n verifier,\n }).fetch;\n return getRequestListener(requestHandler);\n })();\n\n // Surface setup failures eagerly; without this an unhandled\n // rejection would silently kill the dev server.\n ready.catch((error: unknown) => {\n console.error(\"[baerly-dev] setup failed:\", error);\n });\n\n server.middlewares.use((req, res, next) => {\n const url = req.url;\n if (url === undefined || !isV1Path(url)) {\n next();\n return;\n }\n // Inject the bearer token server-side so the SPA never sees\n // the secret. Only runs for `config.auth === \"shared-secret\"`\n // without a `verifier:` override — otherwise the header\n // reaches the listener unchanged. Mutates both `req.headers`\n // and `req.rawHeaders` — see `injectAuthorizationHeader`'s\n // JSDoc.\n if (bearerForInjection !== undefined) {\n injectAuthorizationHeader(req, `Bearer ${bearerForInjection}`);\n }\n ready.then(\n (listener) => {\n listener(req as never, res as never);\n },\n (error: unknown) => {\n res.statusCode = 503;\n res.setHeader(\"content-type\", \"application/json\");\n res.end(JSON.stringify({ error: \"baerly-dev setup failed\", message: String(error) }));\n },\n );\n });\n\n if (opts.banner !== false) {\n server.httpServer?.once(\"listening\", () => {\n const address = server.httpServer?.address();\n const port =\n typeof address === \"object\" && address !== null\n ? (address as AddressInfo).port\n : undefined;\n const url = port !== undefined ? `http://localhost:${port}/` : \"http://localhost/\";\n printDevBanner({\n name: opts.config.app,\n primaryUrl: { label: \"App\", url },\n ...(opts.hints !== undefined && { hints: opts.hints }),\n });\n });\n }\n },\n };\n}\n"],"mappings":";;;;;;AAyDA,MAAM,YAAY,QAChB,QAAQ,SAAS,IAAI,WAAW,MAAM,KAAK,IAAI,WAAW,MAAM;;;;;;;;;;;;;;;AAgBlE,MAAM,6BACJ,KAIA,UACS;CACT,IAAI,QAAQ,mBAAmB;CAC/B,MAAM,MAAM,IAAI;CAChB,IAAI,QAAQ,KAAA,GACV;CAEF,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GACnC,IAAI,IAAI,EAAE,CAAE,YAAY,MAAM,iBAAiB;EAC7C,IAAI,IAAI,KAAK;EACb;CACF;CAEF,IAAI,KAAK,iBAAiB,KAAK;AACjC;AAsBA,MAAM,qBAAqB,WAAsE;CAC/F,IAAI,WAAW,KAAA,GACb,OAAO,CAAC,OAAO,MAAM;CAEvB,IAAI,OAAO,WAAW,UACpB,OAAO,CAAC,MAAM;CAEhB,OAAO;AACT;AAEA,MAAM,oBAAoB,KAAa,aAAyC;CAC9E,KAAK,MAAM,UAAU,UACnB,IAAI,QAAQ,UAAU,IAAI,WAAW,GAAG,OAAO,EAAE,KAAK,IAAI,WAAW,GAAG,OAAO,EAAE,GAC/E,OAAO;CAGX,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,cAAc,MAAoC;CAChE,IAAI,KAAK,WAAW,IAClB,MAAM,IAAI,MACR,iFACF;CAEF,MAAM,WAA8B,kBAAkB,KAAK,MAAM;CACjE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AAM,UAAU,OAAO,YAAY,QAAQ;IAC3C,MAAM,OACJ,OAAO,YAAY,YAAY,YAAY,OACtC,QAAwB,OACzB,KAAA;IACN,MAAM,MAAM,SAAS,KAAA,IAAY,oBAAoB,KAAK,KAAK;IAC/D,eAAe;KACb,MAAM,KAAK,OAAO;KAClB,YAAY;MAAE,OAAO;MAAO;KAAI;KAChC,GAAI,KAAK,UAAU,KAAA,KAAa,EAAE,OAAO,KAAK,MAAM;IACtD,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
package/dist/dev.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { n as DevBannerOpts, r as printDevBanner, t as DevBannerHint } from "./dev-banner-CWHIk8tH.js";
2
- import { a as renderDevLanding, i as DevLandingOptions, n as LocalFsStorageOptions, r as ensureTable, t as LocalFsStorage } from "./index-DnBGSeuU.js";
2
+ import { a as renderDevLanding, i as DevLandingOptions, n as LocalFsStorageOptions, r as ensureTable, t as LocalFsStorage } from "./index-0rZcMBwy.js";
3
3
  export { type DevBannerHint, type DevBannerOpts, type DevLandingOptions, LocalFsStorage, LocalFsStorageOptions, ensureTable, printDevBanner, renderDevLanding };
package/dist/dev.js CHANGED
@@ -1,2 +1,2 @@
1
- import { i as printDevBanner, n as ensureTable, r as renderDevLanding, t as LocalFsStorage } from "./src-CWpkSbvJ.js";
1
+ import { i as printDevBanner, n as ensureTable, r as renderDevLanding, t as LocalFsStorage } from "./src-DYZ4H1aF.js";
2
2
  export { LocalFsStorage, ensureTable, printDevBanner, renderDevLanding };
@@ -1,7 +1,7 @@
1
- import { g as SHARED_SECRET_MISSING_MESSAGE, r as parseBucketUri, t as loadAppConfig } from "./config-CGyBopy3.js";
2
- import { a as defaultRunner, i as parse, n as ensureBindings, o as doctorCas, r as parseR2Bindings } from "./cloudflare-Cn2ibODt.js";
1
+ import { _ as SHARED_SECRET_MISSING_MESSAGE, r as parseBucketUri, t as loadAppConfig } from "./config-1tv0-Yzm.js";
2
+ import { a as defaultRunner, i as parse, n as ensureBindings, o as doctorCas, r as parseR2Bindings } from "./cloudflare-DzKBrUlg.js";
3
3
  import { i as isJsonMode, o as BaerlyError, t as color } from "./baerly.js";
4
- import { n as defineBaerlySubcommand } from "./subcommand-CP9NY2J4.js";
4
+ import { i as JSON_ARG, s as defineBaerlySubcommand } from "./subcommand-DoDA-K7d.js";
5
5
  import { resolve } from "node:path";
6
6
  import { existsSync, readFileSync } from "node:fs";
7
7
  //#region src/doctor/cloudflare.ts
@@ -270,10 +270,7 @@ const DOCTOR_ARGS = {
270
270
  type: "boolean",
271
271
  description: "Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual)."
272
272
  },
273
- json: {
274
- type: "boolean",
275
- description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
276
- }
273
+ json: JSON_ARG
277
274
  };
278
275
  const SEVERITY_GLYPH = {
279
276
  ok: "✓",
@@ -346,4 +343,4 @@ bundle.run;
346
343
  //#endregion
347
344
  export { doctor };
348
345
 
349
- //# sourceMappingURL=doctor-BVU4GNXN.js.map
346
+ //# sourceMappingURL=doctor-DSIyCDg_.js.map