@gusto/baerly-storage 0.4.1 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/API.md +3 -2
- package/dist/CHANGELOG.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/aws4fetch.esm-CXE5ZbAa.js +460 -0
- package/dist/aws4fetch.esm-CXE5ZbAa.js.map +1 -0
- package/dist/baerly.js +10 -10
- package/dist/baerly.spec.json +1 -1
- package/dist/client-react.d.ts +2 -2
- package/dist/{client-Fe8CwB73.d.ts → client-ypCm3zjt.d.ts} +2 -2
- package/dist/client.d.ts +2 -2
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-wrVYf4bb.js} +457 -56
- package/dist/cloudflare-wrVYf4bb.js.map +1 -0
- package/dist/cloudflare.d.ts +13 -10
- package/dist/cloudflare.js +6 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-1tv0-Yzm.js → config-B6nTy8e2.js} +435 -33
- package/dist/config-B6nTy8e2.js.map +1 -0
- package/dist/constants-CfeMWQWk.js.map +1 -1
- package/dist/{cost-DSMIVqzL.js → cost-_SE_SVgZ.js} +4 -4
- package/dist/{cost-DSMIVqzL.js.map → cost-_SE_SVgZ.js.map} +1 -1
- package/dist/{db-DsPkOVEH.d.ts → db-DjjthkTi.d.ts} +2 -2
- package/dist/{deploy-DonTr-CV.js → deploy-Di_Q01qx.js} +5 -5
- package/dist/deploy-Di_Q01qx.js.map +1 -0
- package/dist/dev-vite.d.ts +31 -27
- package/dist/dev-vite.js +60 -30
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/doctor-RWVRpvat.js +102 -0
- package/dist/doctor-RWVRpvat.js.map +1 -0
- package/dist/{dump-Bh5k26VQ.js → dump-m2vEYDNY.js} +4 -4
- package/dist/{dump-Bh5k26VQ.js.map → dump-m2vEYDNY.js.map} +1 -1
- package/dist/{export-DtF5tDIM.js → export-DenKwEQu.js} +4 -4
- package/dist/{export-DtF5tDIM.js.map → export-DenKwEQu.js.map} +1 -1
- package/dist/{fsck-D_djMO5D.js → fsck-2Vq-7-e2.js} +5 -5
- package/dist/{fsck-D_djMO5D.js.map → fsck-2Vq-7-e2.js.map} +1 -1
- package/dist/gcs-admin-Bx6xSNJj.d.ts +123 -0
- package/dist/gcs.d.ts +18 -0
- package/dist/gcs.js +2 -0
- package/dist/goog4-signer-Z7KnJ1su.js +321 -0
- package/dist/goog4-signer-Z7KnJ1su.js.map +1 -0
- package/dist/{http-DxM9MflO.js → http-7zT29K3P.js} +4 -4
- package/dist/{http-DxM9MflO.js.map → http-7zT29K3P.js.map} +1 -1
- package/dist/{aws4fetch.esm-p7eEzLCs.js → http-transport-BTgVCY5r.js} +24 -476
- package/dist/http-transport-BTgVCY5r.js.map +1 -0
- package/dist/http.d.ts +2 -2
- package/dist/http.js +2 -2
- package/dist/{index-BNRh23K9.d.ts → index-BHz92Acj.d.ts} +2 -2
- package/dist/{index-BYk9oCNf.d.ts → index-CEZKQsKt.d.ts} +3 -2
- package/dist/{index-B6oexfOB.d.ts → index-DP3ClvcA.d.ts} +12 -10
- package/dist/{index-0rZcMBwy.d.ts → index-uE-w2dgj.d.ts} +2 -2
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/{inspect-6WZ-pC7-.js → inspect-BpYbH1DM.js} +5 -5
- package/dist/{inspect-6WZ-pC7-.js.map → inspect-BpYbH1DM.js.map} +1 -1
- package/dist/{log-tail-D98U1JBo.js → log-tail-QWU4wlu-.js} +3 -11
- package/dist/log-tail-QWU4wlu-.js.map +1 -0
- package/dist/{maintenance-B_e0T99L.d.ts → maintenance-BGHGt2Yg.d.ts} +2 -2
- package/dist/{maintenance-B4Dki6Ig.js → maintenance-DULFcpd1.js} +4 -17
- package/dist/maintenance-DULFcpd1.js.map +1 -0
- package/dist/{maintenance-C7coQp4c.js → maintenance-fEi-UZ2o.js} +5 -11
- package/dist/maintenance-fEi-UZ2o.js.map +1 -0
- package/dist/maintenance.d.ts +1 -1
- package/dist/maintenance.js +1 -1
- package/dist/node.d.ts +22 -61
- package/dist/node.js +4 -3
- package/dist/{observability-wzs3-BL_.js → observability-Ch-VQJyE.js} +85 -27
- package/dist/{observability-wzs3-BL_.js.map → observability-Ch-VQJyE.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +1 -1
- package/dist/{plan-a7PJHBCy.js → plan-C4qgiXSg.js} +2 -2
- package/dist/{plan-a7PJHBCy.js.map → plan-C4qgiXSg.js.map} +1 -1
- package/dist/{query-rAtXNQQB.js → query-C43r-6ib.js} +2 -2
- package/dist/{query-rAtXNQQB.js.map → query-C43r-6ib.js.map} +1 -1
- package/dist/{rebuild-index-BVzQSZlm.js → rebuild-index-BH1dc1p6.js} +4 -4
- package/dist/{rebuild-index-BVzQSZlm.js.map → rebuild-index-BH1dc1p6.js.map} +1 -1
- package/dist/{restore-R-4rbciV.js → restore-D0VYWzfP.js} +5 -5
- package/dist/{restore-R-4rbciV.js.map → restore-D0VYWzfP.js.map} +1 -1
- package/dist/{runtime-spec-_GTdeSMo.js → runtime-spec--LykAdl1.js} +2 -2
- package/dist/{runtime-spec-_GTdeSMo.js.map → runtime-spec--LykAdl1.js.map} +1 -1
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DD5gDc7t.d.ts} +6 -4
- package/dist/s3.d.ts +1 -1
- package/dist/s3.js +1 -1
- package/dist/sha256-CqcKTjw9.js +22 -0
- package/dist/sha256-CqcKTjw9.js.map +1 -0
- package/dist/{src-D__mHQmQ.js → src-BMFfDUI2.js} +69 -29
- package/dist/src-BMFfDUI2.js.map +1 -0
- package/dist/{src-CYHFDrKz.js → src-DvbTEya2.js} +3 -3
- package/dist/{src-CYHFDrKz.js.map → src-DvbTEya2.js.map} +1 -1
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BV68pqwJ.js} +2 -2
- package/dist/{subcommand-DoDA-K7d.js.map → subcommand-BV68pqwJ.js.map} +1 -1
- package/dist/{usage-DBV1eQHC.js → usage-BMZR8o6U.js} +3 -3
- package/dist/{usage-DBV1eQHC.js.map → usage-BMZR8o6U.js.map} +1 -1
- package/package.json +12 -6
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/deploy-DonTr-CV.js.map +0 -1
- package/dist/doctor-DSIyCDg_.js +0 -346
- package/dist/doctor-DSIyCDg_.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/src-D__mHQmQ.js.map +0 -1
package/dist/doctor-DSIyCDg_.js
DELETED
|
@@ -1,346 +0,0 @@
|
|
|
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
|
-
import { i as isJsonMode, o as BaerlyError, t as color } from "./baerly.js";
|
|
4
|
-
import { i as JSON_ARG, s as defineBaerlySubcommand } from "./subcommand-DoDA-K7d.js";
|
|
5
|
-
import { resolve } from "node:path";
|
|
6
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
7
|
-
//#region src/doctor/cloudflare.ts
|
|
8
|
-
/**
|
|
9
|
-
* `baerly doctor --target=cloudflare` — walks the Cloudflare
|
|
10
|
-
* deploy invariants and reports. With `--fix`, remediates what
|
|
11
|
-
* can be safely auto-fixed (R2 bucket creation; secret prompts
|
|
12
|
-
* are still user-driven because `wrangler secret put` reads
|
|
13
|
-
* stdin interactively).
|
|
14
|
-
*
|
|
15
|
-
* Checks (each emitting one {@link DoctorFinding}):
|
|
16
|
-
* 1. `wrangler.jsonc` exists at the package root.
|
|
17
|
-
* 2. Each declared R2 binding exists in CF
|
|
18
|
-
* (`wrangler r2 bucket info`).
|
|
19
|
-
* 3. Each `requiredSecrets` entry is in `wrangler secret list`.
|
|
20
|
-
* 4. If `cloudflareAccess` is set in `baerly.config.ts`,
|
|
21
|
-
* `audienceTag` is 64 lowercase-hex chars and `teamDomain`
|
|
22
|
-
* is non-empty.
|
|
23
|
-
* 5. Report `triggers.crons` as optional. In-band write-triggered
|
|
24
|
-
* maintenance is the default; cron only drives an explicit
|
|
25
|
-
* `runScheduledMaintenance` sweep when the operator opts in.
|
|
26
|
-
* 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`
|
|
27
|
-
* doesn't declare a matching `routes` entry, warn.
|
|
28
|
-
*
|
|
29
|
-
* Output is a structured {@link DoctorReport} that
|
|
30
|
-
* `packages/cli/src/doctor.ts` renders as either a checklist
|
|
31
|
-
* (text mode) or a JSON envelope (`--json` mode).
|
|
32
|
-
*/
|
|
33
|
-
const rollupStatus = (findings) => {
|
|
34
|
-
let worst = "ok";
|
|
35
|
-
for (const f of findings) {
|
|
36
|
-
if (f.severity === "error") return "error";
|
|
37
|
-
if (f.severity === "warning") worst = "warning";
|
|
38
|
-
}
|
|
39
|
-
return worst;
|
|
40
|
-
};
|
|
41
|
-
/**
|
|
42
|
-
* Read the declared cron schedule from `wrangler.jsonc`. Returns
|
|
43
|
-
* `[]` when missing — caller treats empty as ok; in-band
|
|
44
|
-
* write-triggered maintenance is the default and needs no cron.
|
|
45
|
-
*/
|
|
46
|
-
const readDeclaredCrons = (wranglerPath) => {
|
|
47
|
-
const text = readFileSync(wranglerPath, "utf8");
|
|
48
|
-
const errors = [];
|
|
49
|
-
const obj = parse(text, errors, {
|
|
50
|
-
allowTrailingComma: true,
|
|
51
|
-
disallowComments: false
|
|
52
|
-
});
|
|
53
|
-
if (errors.length > 0 || obj === void 0) return [];
|
|
54
|
-
const crons = obj.triggers?.crons;
|
|
55
|
-
if (!Array.isArray(crons)) return [];
|
|
56
|
-
return crons.filter((c) => typeof c === "string");
|
|
57
|
-
};
|
|
58
|
-
/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */
|
|
59
|
-
const readDeclaredRoutePatterns = (wranglerPath) => {
|
|
60
|
-
const text = readFileSync(wranglerPath, "utf8");
|
|
61
|
-
const errors = [];
|
|
62
|
-
const obj = parse(text, errors, {
|
|
63
|
-
allowTrailingComma: true,
|
|
64
|
-
disallowComments: false
|
|
65
|
-
});
|
|
66
|
-
if (errors.length > 0 || obj === void 0) return [];
|
|
67
|
-
const routes = obj.routes;
|
|
68
|
-
if (!Array.isArray(routes)) return [];
|
|
69
|
-
return routes.map((r) => r !== null && typeof r === "object" ? r.pattern : void 0).filter((p) => typeof p === "string");
|
|
70
|
-
};
|
|
71
|
-
/** Read declared `vars` keys from `wrangler.jsonc`. */
|
|
72
|
-
const readDeclaredVarKeys = (wranglerPath) => {
|
|
73
|
-
const text = readFileSync(wranglerPath, "utf8");
|
|
74
|
-
const errors = [];
|
|
75
|
-
const obj = parse(text, errors, {
|
|
76
|
-
allowTrailingComma: true,
|
|
77
|
-
disallowComments: false
|
|
78
|
-
});
|
|
79
|
-
if (errors.length > 0 || obj === void 0 || obj.vars === void 0) return [];
|
|
80
|
-
return Object.keys(obj.vars);
|
|
81
|
-
};
|
|
82
|
-
/**
|
|
83
|
-
* Walk the Cloudflare deploy invariants. With `opts.fix === true`,
|
|
84
|
-
* remediate the auto-fixable issues (bucket creation). Secret
|
|
85
|
-
* prompts stay user-driven.
|
|
86
|
-
*/
|
|
87
|
-
const doctorCloudflare = async (config, opts = {}) => {
|
|
88
|
-
const repoRoot = opts.cwd ?? config.repoRoot;
|
|
89
|
-
const wranglerPath = resolve(repoRoot, "wrangler.jsonc");
|
|
90
|
-
const findings = [];
|
|
91
|
-
if (!existsSync(wranglerPath)) {
|
|
92
|
-
findings.push({
|
|
93
|
-
severity: "error",
|
|
94
|
-
check: "wrangler.jsonc",
|
|
95
|
-
message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,
|
|
96
|
-
fix: "Re-scaffold (npm create baerly@latest) or restore the file from git."
|
|
97
|
-
});
|
|
98
|
-
return {
|
|
99
|
-
findings,
|
|
100
|
-
status: rollupStatus(findings)
|
|
101
|
-
};
|
|
102
|
-
}
|
|
103
|
-
findings.push({
|
|
104
|
-
severity: "ok",
|
|
105
|
-
check: "wrangler.jsonc",
|
|
106
|
-
message: `${wranglerPath} found.`
|
|
107
|
-
});
|
|
108
|
-
let declared;
|
|
109
|
-
try {
|
|
110
|
-
declared = parseR2Bindings(wranglerPath);
|
|
111
|
-
} catch (error) {
|
|
112
|
-
if (error instanceof BaerlyError && error.code === "InvalidConfig") {
|
|
113
|
-
findings.push({
|
|
114
|
-
severity: "error",
|
|
115
|
-
check: "wrangler.jsonc.parse",
|
|
116
|
-
message: error.message
|
|
117
|
-
});
|
|
118
|
-
return {
|
|
119
|
-
findings,
|
|
120
|
-
status: rollupStatus(findings)
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
throw error;
|
|
124
|
-
}
|
|
125
|
-
if (opts.fix === true && opts.runner !== void 0) try {
|
|
126
|
-
await ensureBindings(opts.runner, repoRoot, wranglerPath);
|
|
127
|
-
} catch (error) {
|
|
128
|
-
findings.push({
|
|
129
|
-
severity: "error",
|
|
130
|
-
check: "r2.fix",
|
|
131
|
-
message: error instanceof Error ? error.message : "unknown error during ensureBindings"
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
if (opts.runner !== void 0) for (const { bucket_name } of declared) if ((await opts.runner.run("wrangler", [
|
|
135
|
-
"r2",
|
|
136
|
-
"bucket",
|
|
137
|
-
"info",
|
|
138
|
-
bucket_name
|
|
139
|
-
], repoRoot)).code === 0) findings.push({
|
|
140
|
-
severity: "ok",
|
|
141
|
-
check: `r2.${bucket_name}`,
|
|
142
|
-
message: `R2 bucket "${bucket_name}" exists.`
|
|
143
|
-
});
|
|
144
|
-
else findings.push({
|
|
145
|
-
severity: "error",
|
|
146
|
-
check: `r2.${bucket_name}`,
|
|
147
|
-
message: `R2 bucket "${bucket_name}" not found.`,
|
|
148
|
-
fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`
|
|
149
|
-
});
|
|
150
|
-
else findings.push({
|
|
151
|
-
severity: "info",
|
|
152
|
-
check: "r2.skip",
|
|
153
|
-
message: "no runner supplied; skipped R2 bucket probes."
|
|
154
|
-
});
|
|
155
|
-
const required = config.requiredSecrets ?? ["SHARED_SECRET"];
|
|
156
|
-
let configured = [];
|
|
157
|
-
if (opts.runner !== void 0 && required.length > 0) {
|
|
158
|
-
const r = await opts.runner.run("wrangler", ["secret", "list"], repoRoot);
|
|
159
|
-
if (r.code !== 0) findings.push({
|
|
160
|
-
severity: "warning",
|
|
161
|
-
check: "secrets",
|
|
162
|
-
message: "could not list secrets (wrangler exit non-zero); skipping check."
|
|
163
|
-
});
|
|
164
|
-
else {
|
|
165
|
-
try {
|
|
166
|
-
const parsed = JSON.parse(r.stdout);
|
|
167
|
-
if (Array.isArray(parsed)) configured = parsed.map((s) => s !== null && typeof s === "object" ? s.name : void 0).filter((n) => typeof n === "string");
|
|
168
|
-
} catch {}
|
|
169
|
-
for (const name of required) if (configured.includes(name)) findings.push({
|
|
170
|
-
severity: "ok",
|
|
171
|
-
check: `secret.${name}`,
|
|
172
|
-
message: `secret ${name} is set.`
|
|
173
|
-
});
|
|
174
|
-
else findings.push({
|
|
175
|
-
severity: "warning",
|
|
176
|
-
check: `secret.${name}`,
|
|
177
|
-
message: `secret ${name} is required but unset.`,
|
|
178
|
-
fix: `wrangler secret put ${name}`
|
|
179
|
-
});
|
|
180
|
-
}
|
|
181
|
-
} else if (required.length > 0) findings.push({
|
|
182
|
-
severity: "info",
|
|
183
|
-
check: "secrets.skip",
|
|
184
|
-
message: "no runner supplied; skipped secret checks."
|
|
185
|
-
});
|
|
186
|
-
if (config.auth === "none") findings.push({
|
|
187
|
-
severity: "warning",
|
|
188
|
-
check: "auth.none-on-deploy",
|
|
189
|
-
message: `baerly.config.ts has auth: "none" and ships to target=${JSON.stringify(config.target)}. Every request will resolve to config.tenant with no header check. Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) or change \`auth\` to "shared-secret" or pass a custom \`verifier:\` on the adapter factory.`,
|
|
190
|
-
fix: "Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`."
|
|
191
|
-
});
|
|
192
|
-
if (config.auth === "shared-secret" && opts.runner !== void 0) {
|
|
193
|
-
if (!configured.includes("SHARED_SECRET")) findings.push({
|
|
194
|
-
severity: "error",
|
|
195
|
-
check: "auth.shared-secret-missing",
|
|
196
|
-
message: SHARED_SECRET_MISSING_MESSAGE,
|
|
197
|
-
fix: "wrangler secret put SHARED_SECRET (for production) or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`)."
|
|
198
|
-
});
|
|
199
|
-
}
|
|
200
|
-
const varKeys = new Set(readDeclaredVarKeys(wranglerPath));
|
|
201
|
-
if (varKeys.has("CF_ACCESS_TEAM_DOMAIN") && varKeys.has("CF_ACCESS_AUDIENCE_TAG")) findings.push({
|
|
202
|
-
severity: "info",
|
|
203
|
-
check: "auth.cf-access-inert",
|
|
204
|
-
message: `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} but the adapter uses config.auth=${JSON.stringify(config.auth)}. To wire CF Access, pass \`verifier: cloudflareAccess({ teamDomain, audienceTag })\` on the baerlyWorker factory.`
|
|
205
|
-
});
|
|
206
|
-
if (config.cloudflareAccess !== void 0) {
|
|
207
|
-
const { teamDomain, audienceTag } = config.cloudflareAccess;
|
|
208
|
-
if (teamDomain.length === 0) findings.push({
|
|
209
|
-
severity: "error",
|
|
210
|
-
check: "cloudflareAccess.teamDomain",
|
|
211
|
-
message: "cloudflareAccess.teamDomain in baerly.config.ts is empty."
|
|
212
|
-
});
|
|
213
|
-
if (!/^[0-9a-f]{64}$/.test(audienceTag)) findings.push({
|
|
214
|
-
severity: "error",
|
|
215
|
-
check: "cloudflareAccess.audienceTag",
|
|
216
|
-
message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,
|
|
217
|
-
fix: "Copy the AUD tag from the Cloudflare Access app's configuration tab."
|
|
218
|
-
});
|
|
219
|
-
else if (teamDomain.length > 0) findings.push({
|
|
220
|
-
severity: "ok",
|
|
221
|
-
check: "cloudflareAccess",
|
|
222
|
-
message: `cloudflareAccess audience tag is well-formed; team domain "${teamDomain}".`
|
|
223
|
-
});
|
|
224
|
-
}
|
|
225
|
-
const crons = readDeclaredCrons(wranglerPath);
|
|
226
|
-
if (crons.length === 0) findings.push({
|
|
227
|
-
severity: "ok",
|
|
228
|
-
check: "triggers.crons",
|
|
229
|
-
message: "no cron triggers declared; in-band write-triggered maintenance is the default."
|
|
230
|
-
});
|
|
231
|
-
else findings.push({
|
|
232
|
-
severity: "info",
|
|
233
|
-
check: "triggers.crons",
|
|
234
|
-
message: `cron trigger${crons.length === 1 ? "" : "s"} ${crons.map((c) => JSON.stringify(c)).join(", ")} declared for opt-in scheduled maintenance; write-triggered maintenance still runs by default.`
|
|
235
|
-
});
|
|
236
|
-
if (config.domain !== void 0 && config.domain.length > 0) {
|
|
237
|
-
const patterns = readDeclaredRoutePatterns(wranglerPath);
|
|
238
|
-
const expectedPrefix = `${config.domain}/`;
|
|
239
|
-
if (!patterns.some((p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix))) findings.push({
|
|
240
|
-
severity: "warning",
|
|
241
|
-
check: "routes.domain",
|
|
242
|
-
message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,
|
|
243
|
-
fix: `Add { "pattern": "${config.domain}/*", "custom_domain": true } to wrangler.jsonc:routes.`
|
|
244
|
-
});
|
|
245
|
-
else findings.push({
|
|
246
|
-
severity: "ok",
|
|
247
|
-
check: "routes.domain",
|
|
248
|
-
message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`
|
|
249
|
-
});
|
|
250
|
-
}
|
|
251
|
-
return {
|
|
252
|
-
findings,
|
|
253
|
-
status: rollupStatus(findings)
|
|
254
|
-
};
|
|
255
|
-
};
|
|
256
|
-
//#endregion
|
|
257
|
-
//#region src/doctor.ts
|
|
258
|
-
const DOCTOR_ARGS = {
|
|
259
|
-
target: {
|
|
260
|
-
type: "string",
|
|
261
|
-
description: "Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).",
|
|
262
|
-
valueHint: "cloudflare"
|
|
263
|
-
},
|
|
264
|
-
bucket: {
|
|
265
|
-
type: "string",
|
|
266
|
-
description: "Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, file:///, or memory:// URI. Independent of --target.",
|
|
267
|
-
valueHint: "s3://bucket/prefix"
|
|
268
|
-
},
|
|
269
|
-
fix: {
|
|
270
|
-
type: "boolean",
|
|
271
|
-
description: "Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual)."
|
|
272
|
-
},
|
|
273
|
-
json: JSON_ARG
|
|
274
|
-
};
|
|
275
|
-
const SEVERITY_GLYPH = {
|
|
276
|
-
ok: "✓",
|
|
277
|
-
info: "•",
|
|
278
|
-
warning: "⚠",
|
|
279
|
-
error: "✗"
|
|
280
|
-
};
|
|
281
|
-
const colorize = (severity, glyph) => {
|
|
282
|
-
if (severity === "error") return color.red(glyph);
|
|
283
|
-
if (severity === "warning") return color.yellow(glyph);
|
|
284
|
-
if (severity === "info") return color.dim(glyph);
|
|
285
|
-
return glyph;
|
|
286
|
-
};
|
|
287
|
-
const renderReport = (label, report) => {
|
|
288
|
-
if (isJsonMode()) {
|
|
289
|
-
process.stdout.write(`${JSON.stringify({ result: {
|
|
290
|
-
command: "doctor",
|
|
291
|
-
[label.kind]: label.value,
|
|
292
|
-
...report
|
|
293
|
-
} })}\n`);
|
|
294
|
-
return;
|
|
295
|
-
}
|
|
296
|
-
process.stdout.write(`baerly doctor --${label.kind}=${label.value}\n\n`);
|
|
297
|
-
let okCount = 0;
|
|
298
|
-
let warningCount = 0;
|
|
299
|
-
let errorCount = 0;
|
|
300
|
-
for (const f of report.findings) {
|
|
301
|
-
const glyph = SEVERITY_GLYPH[f.severity] ?? "•";
|
|
302
|
-
process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\n`);
|
|
303
|
-
if (f.fix !== void 0) process.stdout.write(` fix: ${f.fix}\n`);
|
|
304
|
-
if (f.severity === "ok") okCount += 1;
|
|
305
|
-
else if (f.severity === "warning") warningCount += 1;
|
|
306
|
-
else if (f.severity === "error") errorCount += 1;
|
|
307
|
-
}
|
|
308
|
-
process.stdout.write(`\nStatus: ${errorCount} error${errorCount === 1 ? "" : "s"}, ${warningCount} warning${warningCount === 1 ? "" : "s"}, ${okCount} ok.\n`);
|
|
309
|
-
};
|
|
310
|
-
const bundle = defineBaerlySubcommand({
|
|
311
|
-
name: "doctor",
|
|
312
|
-
meta: { description: "Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target." },
|
|
313
|
-
args: DOCTOR_ARGS,
|
|
314
|
-
handler: async (args) => {
|
|
315
|
-
if (args.bucket !== void 0) {
|
|
316
|
-
const { storage, keyPrefix } = await parseBucketUri(args.bucket);
|
|
317
|
-
const report = await doctorCas(storage, keyPrefix);
|
|
318
|
-
renderReport({
|
|
319
|
-
kind: "bucket",
|
|
320
|
-
value: args.bucket
|
|
321
|
-
}, report);
|
|
322
|
-
return report.status === "error" ? 2 : 0;
|
|
323
|
-
}
|
|
324
|
-
const config = await loadAppConfig();
|
|
325
|
-
const target = args.target ?? config.target;
|
|
326
|
-
if (target === "cloudflare") {
|
|
327
|
-
const report = await doctorCloudflare(config, {
|
|
328
|
-
runner: defaultRunner(),
|
|
329
|
-
...args.fix === true && { fix: true }
|
|
330
|
-
});
|
|
331
|
-
renderReport({
|
|
332
|
-
kind: "target",
|
|
333
|
-
value: target
|
|
334
|
-
}, report);
|
|
335
|
-
return report.status === "error" ? 2 : 0;
|
|
336
|
-
}
|
|
337
|
-
throw new BaerlyError("InvalidConfig", `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. (Node variants self-validate at scaffold time; the example IS the contract.)`);
|
|
338
|
-
}
|
|
339
|
-
});
|
|
340
|
-
/** citty `defineCommand` block for `baerly doctor`. */
|
|
341
|
-
const doctor = bundle.cmd;
|
|
342
|
-
bundle.run;
|
|
343
|
-
//#endregion
|
|
344
|
-
export { doctor };
|
|
345
|
-
|
|
346
|
-
//# sourceMappingURL=doctor-DSIyCDg_.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"doctor-DSIyCDg_.js","names":[],"sources":["../packages/cli/src/doctor/cloudflare.ts","../packages/cli/src/doctor.ts"],"sourcesContent":["/**\n * `baerly doctor --target=cloudflare` — walks the Cloudflare\n * deploy invariants and reports. With `--fix`, remediates what\n * can be safely auto-fixed (R2 bucket creation; secret prompts\n * are still user-driven because `wrangler secret put` reads\n * stdin interactively).\n *\n * Checks (each emitting one {@link DoctorFinding}):\n * 1. `wrangler.jsonc` exists at the package root.\n * 2. Each declared R2 binding exists in CF\n * (`wrangler r2 bucket info`).\n * 3. Each `requiredSecrets` entry is in `wrangler secret list`.\n * 4. If `cloudflareAccess` is set in `baerly.config.ts`,\n * `audienceTag` is 64 lowercase-hex chars and `teamDomain`\n * is non-empty.\n * 5. Report `triggers.crons` as optional. In-band write-triggered\n * maintenance is the default; cron only drives an explicit\n * `runScheduledMaintenance` sweep when the operator opts in.\n * 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`\n * doesn't declare a matching `routes` entry, warn.\n *\n * Output is a structured {@link DoctorReport} that\n * `packages/cli/src/doctor.ts` renders as either a checklist\n * (text mode) or a JSON envelope (`--json` mode).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parse, type ParseError } from \"jsonc-parser\";\nimport { BaerlyError, SHARED_SECRET_MISSING_MESSAGE } from \"@baerly/protocol\";\nimport type { AppConfig } from \"../config.ts\";\nimport { ensureBindings, parseR2Bindings, type ProcessRunner } from \"../deploy/cloudflare.ts\";\n\n/** One finding from a `baerly doctor` walk. */\nexport interface DoctorFinding {\n /** Severity. `ok` / `info` don't move the overall status. */\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n /** Short check name — stable, machine-readable. */\n readonly check: string;\n /** Human-friendly description. */\n readonly message: string;\n /** Optional remediation hint. */\n readonly fix?: string;\n}\n\n/** Result of a `baerly doctor` walk. */\nexport interface DoctorReport {\n readonly findings: readonly DoctorFinding[];\n /**\n * Overall: `ok` only when every finding has severity `ok` or\n * `info`. `warning` when the worst finding is a warning. `error`\n * when any finding is an error.\n */\n readonly status: \"ok\" | \"warning\" | \"error\";\n}\n\nconst rollupStatus = (findings: readonly DoctorFinding[]): DoctorReport[\"status\"] => {\n let worst: DoctorReport[\"status\"] = \"ok\";\n for (const f of findings) {\n if (f.severity === \"error\") {\n return \"error\";\n }\n if (f.severity === \"warning\") {\n worst = \"warning\";\n }\n }\n return worst;\n};\n\n/**\n * Read the declared cron schedule from `wrangler.jsonc`. Returns\n * `[]` when missing — caller treats empty as ok; in-band\n * write-triggered maintenance is the default and needs no cron.\n */\nconst readDeclaredCrons = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { triggers?: { crons?: unknown } }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const crons = obj.triggers?.crons;\n if (!Array.isArray(crons)) {\n return [];\n }\n return crons.filter((c): c is string => typeof c === \"string\");\n};\n\n/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */\nconst readDeclaredRoutePatterns = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { routes?: unknown }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const routes = obj.routes;\n if (!Array.isArray(routes)) {\n return [];\n }\n return routes\n .map((r) =>\n r !== null && typeof r === \"object\" ? (r as { pattern?: unknown }).pattern : undefined,\n )\n .filter((p): p is string => typeof p === \"string\");\n};\n\n/** Read declared `vars` keys from `wrangler.jsonc`. */\nconst readDeclaredVarKeys = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { vars?: Record<string, unknown> }\n | undefined;\n if (errors.length > 0 || obj === undefined || obj.vars === undefined) {\n return [];\n }\n return Object.keys(obj.vars);\n};\n\n/**\n * Walk the Cloudflare deploy invariants. With `opts.fix === true`,\n * remediate the auto-fixable issues (bucket creation). Secret\n * prompts stay user-driven.\n */\nexport const doctorCloudflare = async (\n config: AppConfig,\n opts: {\n readonly runner?: ProcessRunner;\n readonly fix?: boolean;\n readonly cwd?: string;\n } = {},\n): Promise<DoctorReport> => {\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = resolve(repoRoot, \"wrangler.jsonc\");\n const findings: DoctorFinding[] = [];\n\n // 1. wrangler.jsonc presence.\n if (!existsSync(wranglerPath)) {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc\",\n message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,\n fix: \"Re-scaffold (npm create baerly@latest) or restore the file from git.\",\n });\n return { findings, status: rollupStatus(findings) };\n }\n findings.push({\n severity: \"ok\",\n check: \"wrangler.jsonc\",\n message: `${wranglerPath} found.`,\n });\n\n // 2. R2 bindings — parse first, then probe each.\n let declared: readonly { binding: string; bucket_name: string }[];\n try {\n declared = parseR2Bindings(wranglerPath);\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"InvalidConfig\") {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc.parse\",\n message: error.message,\n });\n return { findings, status: rollupStatus(findings) };\n }\n throw error;\n }\n\n if (opts.fix === true && opts.runner !== undefined) {\n // Run the same provisioning path the deploy fallback uses.\n // Any failure here surfaces as an error finding rather than\n // throwing — doctor's job is to report.\n try {\n await ensureBindings(opts.runner, repoRoot, wranglerPath);\n } catch (error) {\n findings.push({\n severity: \"error\",\n check: \"r2.fix\",\n message: error instanceof Error ? error.message : \"unknown error during ensureBindings\",\n });\n }\n }\n\n if (opts.runner !== undefined) {\n for (const { bucket_name } of declared) {\n const info = await opts.runner.run(\n \"wrangler\",\n [\"r2\", \"bucket\", \"info\", bucket_name],\n repoRoot,\n );\n if (info.code === 0) {\n findings.push({\n severity: \"ok\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" exists.`,\n });\n } else {\n findings.push({\n severity: \"error\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" not found.`,\n fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`,\n });\n }\n }\n } else {\n findings.push({\n severity: \"info\",\n check: \"r2.skip\",\n message: \"no runner supplied; skipped R2 bucket probes.\",\n });\n }\n\n // 3. requiredSecrets — best-effort.\n //\n // `configured` is lifted to the outer scope so the auth-posture\n // block below can read the deployed secret set without re-running\n // `wrangler secret list`. Empty when the runner is absent or the\n // listing call failed.\n const required = config.requiredSecrets ?? [\"SHARED_SECRET\"];\n let configured: readonly string[] = [];\n if (opts.runner !== undefined && required.length > 0) {\n const r = await opts.runner.run(\"wrangler\", [\"secret\", \"list\"], repoRoot);\n if (r.code !== 0) {\n findings.push({\n severity: \"warning\",\n check: \"secrets\",\n message: \"could not list secrets (wrangler exit non-zero); skipping check.\",\n });\n } else {\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (Array.isArray(parsed)) {\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n }\n } catch {\n // fall through with empty configured set\n }\n for (const name of required) {\n if (configured.includes(name)) {\n findings.push({\n severity: \"ok\",\n check: `secret.${name}`,\n message: `secret ${name} is set.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check: `secret.${name}`,\n message: `secret ${name} is required but unset.`,\n fix: `wrangler secret put ${name}`,\n });\n }\n }\n }\n } else if (required.length > 0) {\n findings.push({\n severity: \"info\",\n check: \"secrets.skip\",\n message: \"no runner supplied; skipped secret checks.\",\n });\n }\n\n // 7. config.auth — graduated-auth posture. Walks the typed `auth`\n // field added in `packages/protocol/src/app-config.ts`.\n // FAIL: shared-secret without SHARED_SECRET set on the worker.\n // WARN: auth: \"none\" + deploy target (operator may have a\n // network gate in front; surface it so they confirm).\n // INFO: CF Access vars present + adapter uses config.auth (auth\n // is using config.auth, CF Access env is inert).\n //\n // The presence of the typed field is guaranteed by the loader\n // (config.ts throws on omission), so we walk every loaded config\n // without an existence guard.\n if (config.auth === \"none\") {\n // Deploy-target check: \"cloudflare\" / \"node\" are the only valid\n // values, and both ship to a network-reachable runtime. We warn\n // unconditionally — the doctor's job is to surface the choice,\n // not to second-guess whether the operator's network seam (CF\n // Access, intranet ACL, Tunnel) is upstream.\n findings.push({\n severity: \"warning\",\n check: \"auth.none-on-deploy\",\n message:\n `baerly.config.ts has auth: \"none\" and ships to target=${JSON.stringify(config.target)}. ` +\n \"Every request will resolve to config.tenant with no header check. \" +\n \"Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) \" +\n 'or change `auth` to \"shared-secret\" or pass a custom `verifier:` on the adapter factory.',\n fix:\n 'Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; ' +\n 'or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`.',\n });\n }\n\n if (config.auth === \"shared-secret\" && opts.runner !== undefined) {\n // Mirror the FAIL message wording from the adapter's runtime\n // throw. Locked via `SHARED_SECRET_MISSING_MESSAGE` so doctor +\n // adapter stay in sync.\n //\n // If `configured` is still empty here, the `wrangler secret list`\n // invocation either failed (we already warned with the \"secrets\"\n // finding above) or really lists no secrets. Either way the\n // operator-facing remediation is the same.\n const requiredSecret = \"SHARED_SECRET\";\n if (!configured.includes(requiredSecret)) {\n findings.push({\n severity: \"error\",\n check: \"auth.shared-secret-missing\",\n message: SHARED_SECRET_MISSING_MESSAGE,\n fix:\n \"wrangler secret put SHARED_SECRET (for production) \" +\n \"or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`).\",\n });\n }\n }\n\n // INFO: CF Access env vars in wrangler.jsonc:vars but the adapter\n // is using `config.auth` for the verifier (so the env values are\n // inert). We can't statically parse the user's worker source —\n // surface the heuristic.\n const varKeys = new Set(readDeclaredVarKeys(wranglerPath));\n if (varKeys.has(\"CF_ACCESS_TEAM_DOMAIN\") && varKeys.has(\"CF_ACCESS_AUDIENCE_TAG\")) {\n findings.push({\n severity: \"info\",\n check: \"auth.cf-access-inert\",\n message:\n `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} ` +\n `but the adapter uses config.auth=${JSON.stringify(config.auth)}. ` +\n `To wire CF Access, pass \\`verifier: cloudflareAccess({ teamDomain, audienceTag })\\` on the baerlyWorker factory.`,\n });\n }\n\n // 4. cloudflareAccess — when configured, audience tag must be\n // 64 lowercase-hex chars.\n if (config.cloudflareAccess !== undefined) {\n const { teamDomain, audienceTag } = config.cloudflareAccess;\n if (teamDomain.length === 0) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.teamDomain\",\n message: \"cloudflareAccess.teamDomain in baerly.config.ts is empty.\",\n });\n }\n if (!/^[0-9a-f]{64}$/.test(audienceTag)) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.audienceTag\",\n message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,\n fix: \"Copy the AUD tag from the Cloudflare Access app's configuration tab.\",\n });\n } else if (teamDomain.length > 0) {\n findings.push({\n severity: \"ok\",\n check: \"cloudflareAccess\",\n message: `cloudflareAccess audience tag is well-formed; team domain \"${teamDomain}\".`,\n });\n }\n }\n\n // 5. Cron triggers — optional. In-band write-tick maintenance is\n // the default; cron only exists for an explicit out-of-band sweep.\n const crons = readDeclaredCrons(wranglerPath);\n if (crons.length === 0) {\n findings.push({\n severity: \"ok\",\n check: \"triggers.crons\",\n message: \"no cron triggers declared; in-band write-triggered maintenance is the default.\",\n });\n } else {\n findings.push({\n severity: \"info\",\n check: \"triggers.crons\",\n message:\n `cron trigger${crons.length === 1 ? \"\" : \"s\"} ${crons.map((c) => JSON.stringify(c)).join(\", \")} declared ` +\n \"for opt-in scheduled maintenance; write-triggered maintenance still runs by default.\",\n });\n }\n\n // 6. domain ↔ routes coherence.\n if (config.domain !== undefined && config.domain.length > 0) {\n const patterns = readDeclaredRoutePatterns(wranglerPath);\n const expectedPrefix = `${config.domain}/`;\n const hasMatch = patterns.some(\n (p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix),\n );\n if (!hasMatch) {\n findings.push({\n severity: \"warning\",\n check: \"routes.domain\",\n message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,\n fix: `Add { \"pattern\": \"${config.domain}/*\", \"custom_domain\": true } to wrangler.jsonc:routes.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"routes.domain\",\n message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`,\n });\n }\n }\n\n return { findings, status: rollupStatus(findings) };\n};\n","/**\n * `baerly doctor` — citty dispatcher for deploy-invariant checks.\n *\n * Two modes:\n * - `--bucket <uri>` — connect to a live bucket and probe its CAS\n * support (the protocol's load-bearing backend prerequisite). This\n * mode WRITES + deletes one throwaway sentinel; see\n * {@link doctorCas}. Independent of `baerly.config.ts` / `--target`.\n * - otherwise — reads `baerly.config.ts:target` and routes to\n * {@link doctorCloudflare} (read-only deploy-invariant checks). The\n * Node target self-validates at scaffold time — the example IS the\n * contract — so it has no doctor backend.\n *\n * Drift detection, index rebuilds, and writes/min health are separate\n * verbs:\n * - `baerly admin fsck --indexes [--fix]` — index drift.\n * - `baerly admin usage` — writes/min M-size graduation.\n * - `baerly admin rebuild-index` — single-index reconciliation.\n *\n * Renders the returned {@link DoctorReport} into either a\n * stdout checklist (text mode) or a JSON envelope (`--json`\n * mode).\n *\n * Exit-code contract (mirrors `baerly deploy`):\n * - 0 success — report status is `ok` or `warning`.\n * - 1 user error (InvalidConfig, unknown target, missing config).\n * - 2 storage / external error.\n * - 3 protocol invariant.\n *\n * A `warning` status returns exit 0 (the user can deploy; we just\n * flagged a maintenance / coherence issue). An `error` status\n * returns exit 2 unless the underlying cause was an InvalidConfig\n * (which already returned 1 via a thrown BaerlyError).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { doctorCas } from \"./doctor/cas.ts\";\nimport { doctorCloudflare, type DoctorReport } from \"./doctor/cloudflare.ts\";\nimport { defaultRunner } from \"./runner.ts\";\nimport { color, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand, JSON_ARG } from \"./subcommand.ts\";\n\nconst DOCTOR_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).',\n valueHint: \"cloudflare\",\n },\n bucket: {\n type: \"string\",\n description:\n \"Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, file:///, or memory:// URI. Independent of --target.\",\n valueHint: \"s3://bucket/prefix\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual).\",\n },\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst colorize = (severity: string, glyph: string): string => {\n if (severity === \"error\") {\n return color.red(glyph);\n }\n if (severity === \"warning\") {\n return color.yellow(glyph);\n }\n if (severity === \"info\") {\n return color.dim(glyph);\n }\n return glyph;\n};\n\nconst renderReport = (\n label: { kind: \"target\" | \"bucket\"; value: string },\n report: DoctorReport,\n): void => {\n if (isJsonMode()) {\n process.stdout.write(\n `${JSON.stringify({ result: { command: \"doctor\", [label.kind]: label.value, ...report } })}\\n`,\n );\n return;\n }\n process.stdout.write(`baerly doctor --${label.kind}=${label.value}\\n\\n`);\n let okCount = 0;\n let warningCount = 0;\n let errorCount = 0;\n for (const f of report.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? \"•\";\n process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\\n`);\n if (f.fix !== undefined) {\n process.stdout.write(` fix: ${f.fix}\\n`);\n }\n if (f.severity === \"ok\") {\n okCount += 1;\n } else if (f.severity === \"warning\") {\n warningCount += 1;\n } else if (f.severity === \"error\") {\n errorCount += 1;\n }\n }\n process.stdout.write(\n `\\nStatus: ${errorCount} error${errorCount === 1 ? \"\" : \"s\"}, ${warningCount} warning${warningCount === 1 ? \"\" : \"s\"}, ${okCount} ok.\\n`,\n );\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"doctor\",\n meta: {\n description:\n \"Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target.\",\n },\n args: DOCTOR_ARGS,\n handler: async (args) => {\n // --bucket is a standalone live-probe mode: it connects to a real\n // bucket and checks CAS, independent of baerly.config.ts / --target.\n if (args.bucket !== undefined) {\n const { storage, keyPrefix } = await parseBucketUri(args.bucket);\n const report = await doctorCas(storage, keyPrefix);\n renderReport({ kind: \"bucket\", value: args.bucket }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const report = await doctorCloudflare(config, {\n runner: defaultRunner(),\n ...(args.fix === true && { fix: true }),\n });\n renderReport({ kind: \"target\", value: target }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. ` +\n `(Node variants self-validate at scaffold time; the example IS the contract.)`,\n );\n },\n});\n\n/** citty `defineCommand` block for `baerly doctor`. */\nexport const doctor = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDoctor = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,gBAAgB,aAA+D;CACnF,IAAI,QAAgC;CACpC,KAAK,MAAM,KAAK,UAAU;EACxB,IAAI,EAAE,aAAa,SACjB,OAAO;EAET,IAAI,EAAE,aAAa,WACjB,QAAQ;CAEZ;CACA,OAAO;AACT;;;;;;AAOA,MAAM,qBAAqB,iBAA4C;CACrE,MAAM,OAAO,aAAa,cAAc,MAAM;CAC9C,MAAM,SAAuB,CAAC;CAC9B,MAAM,MAAM,MAAM,MAAM,QAAQ;EAAE,oBAAoB;EAAM,kBAAkB;CAAM,CAAC;CAGrF,IAAI,OAAO,SAAS,KAAK,QAAQ,KAAA,GAC/B,OAAO,CAAC;CAEV,MAAM,QAAQ,IAAI,UAAU;CAC5B,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,OAAO,CAAC;CAEV,OAAO,MAAM,QAAQ,MAAmB,OAAO,MAAM,QAAQ;AAC/D;;AAGA,MAAM,6BAA6B,iBAA4C;CAC7E,MAAM,OAAO,aAAa,cAAc,MAAM;CAC9C,MAAM,SAAuB,CAAC;CAC9B,MAAM,MAAM,MAAM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AAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,SAAS,MAAM,iBAAiB,QAAQ;IAC5C,QAAQ,cAAc;IACtB,GAAI,KAAK,QAAQ,QAAQ,EAAE,KAAK,KAAK;GACvC,CAAC;GACD,aAAa;IAAE,MAAM;IAAU,OAAO;GAAO,GAAG,MAAM;GACtD,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,qGAElD;CACF;AACF,CAAC;;AAGD,MAAa,SAAS,OAAO;AAOJ,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"log-tail-D98U1JBo.js","names":[],"sources":["../packages/protocol/src/coordination/current-json.ts","../packages/protocol/src/log-key.ts","../packages/protocol/src/snapshot-hash.ts","../packages/server/src/snapshot.ts","../packages/server/src/log-walk.ts","../packages/server/src/log-tail.ts"],"sourcesContent":["/**\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","/**\n * Log-object key construction — a zero-import leaf module.\n *\n * Kept separate from `log.ts` on purpose: `log.ts` carries the heavier\n * `lsn` parsing runtime (`lsnParts`, the LSN regex, `str2uintDesc`).\n * Routing `gc` / `writer` / `log-walk` through a key helper that lived in\n * `log.ts` dragged that whole module into the `maintenance.js` bundle\n * closure (+3.8 KB raw). This module imports nothing, so consumers that\n * only need the key shape pull only the key shape.\n */\n\n/** S3 path segment for log entries, under the manifest prefix. */\nexport const LOG_KEY_PREFIX = \"log\";\n\n/**\n * The single constructor for a log-object key:\n * `<manifestPrefix>/log/<seq>.json`. `manifestPrefix` is the\n * `<…>/manifests/<collection>` segment — this helper adds `/log/`.\n * Route all callers here so the key shape lives in one place.\n */\nexport const logObjectKey = (manifestPrefix: string, seq: number): string =>\n `${manifestPrefix}/${LOG_KEY_PREFIX}/${seq}.json`;\n","/**\n * SHA-256 of `bytes` as a 64-char lowercase hex string. Used to seal\n * snapshot filenames so a crashed mid-PUT can't produce a body that\n * readers consume as truth: the filename embeds the hash; readers\n * recompute on load and reject any mismatch as \"file missing.\"\n *\n * Distinct from {@link versionFromContent} (truncated to 32 chars for\n * content keys) — snapshot bodies are larger and longer-lived;\n * 256-bit collision resistance matters here.\n */\nexport const snapshotHash = async (bytes: Uint8Array): Promise<string> => {\n // Copy via fresh ArrayBuffer: tsgo narrows `Uint8Array` to\n // `Uint8Array<ArrayBufferLike>`, which `crypto.subtle.digest` rejects\n // (wants `ArrayBufferView<ArrayBuffer>`). See microsoft/TypeScript#61375\n // and `versionFromContent` in ./hashing.ts for the same workaround.\n const view = new Uint8Array(bytes.byteLength);\n view.set(bytes);\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n const out = new Uint8Array(digest);\n let hex = \"\";\n for (let i = 0; i < out.length; i++) {\n hex += out[i]!.toString(16).padStart(2, \"0\");\n }\n return hex;\n};\n","/**\n * Snapshot file shape + parse. Lifted out of `./compactor.ts` so that\n * the kernel barrel (`packages/server/src/index.ts`) — which re-exports\n * these four symbols — does not transitively pull `withObservability`\n * via `compact()`. `./compactor.ts` imports its own snapshot primitives\n * back from this module; the public API surface is unchanged.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n BaerlyError,\n decodeJsonBytes,\n type DocumentData,\n encodeJsonBytes,\n snapshotHash,\n SNAPSHOT_SCHEMA_VERSION,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Single-level snapshot at L9; the level prefix is forward-compatible\n * with future L0..L9 rolling merges without a wire change.\n */\nconst SNAPSHOT_LEVEL = 9 as const;\n\n/**\n * `minSeq` and `maxSeq` are padded to {@link SEQ_DIGITS} digits so\n * `list(prefix)` returns snapshots in seq order without needing to\n * parse the filename. 12 digits caps at ~10^12 entries per collection;\n * a real bucket hits S3's per-prefix QPS ceiling long before that.\n */\nconst SEQ_DIGITS = 12 as const;\n\nconst MAX_SEQ = 10 ** SEQ_DIGITS - 1;\n\n/**\n * Build the on-bucket key for a snapshot file. `sha256` must be the\n * lowercase hex digest of the canonical body\n * ({@link encodeSnapshotBody}); the filename embeds it so a crashed\n * mid-PUT body that doesn't match its own filename hash is rejected\n * by readers as \"missing.\"\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `minSeq`/`maxSeq` are\n * out of range or `sha256` is not 64 hex chars.\n */\nexport const snapshotKey = (\n collectionPrefix: string,\n minSeq: number,\n maxSeq: number,\n sha256: string,\n): string => {\n if (minSeq < 0 || maxSeq < 0 || minSeq > maxSeq || maxSeq > MAX_SEQ) {\n throw new BaerlyError(\"InvalidConfig\", `snapshotKey: invalid range [${minSeq}, ${maxSeq})`);\n }\n if (!/^[0-9a-f]{64}$/.test(sha256)) {\n throw new BaerlyError(\"InvalidConfig\", \"snapshotKey: sha256 must be 64 hex chars\");\n }\n const pad = (n: number): string => n.toString().padStart(SEQ_DIGITS, \"0\");\n return `${collectionPrefix}/snapshot/L${SNAPSHOT_LEVEL}/${pad(minSeq)}-${pad(maxSeq)}-${sha256}.json`;\n};\n\n/**\n * On-bucket body of a snapshot file. The reader recomputes the SHA-256\n * over the canonical serialisation ({@link encodeSnapshotBody}) and\n * rejects any mismatch with the filename hash.\n *\n * `docs` is sorted by `_id` for deterministic byte output — two\n * compactions over the same fold produce byte-identical snapshots,\n * which means same filename, which means an idempotent re-run never\n * leaves an orphan.\n */\nexport interface SnapshotBody {\n readonly schema_version: typeof SNAPSHOT_SCHEMA_VERSION;\n readonly min_seq: number;\n readonly max_seq: number;\n readonly collection: string;\n readonly docs: ReadonlyArray<{\n readonly _id: string;\n readonly body: DocumentData;\n }>;\n}\n\n/**\n * Canonical byte encoding of a {@link SnapshotBody}. Only the\n * compactor produces snapshots, and only this function does the\n * serialisation — so the byte output is deterministic for a given\n * `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical\n * filename hash).\n */\nexport const encodeSnapshotBody = (s: SnapshotBody): Uint8Array => encodeJsonBytes(s);\n\n/**\n * Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the\n * body hash against the filename, checks the schema version, and\n * cross-checks `body.collection` against the caller's expectation.\n *\n * @example\n * ```ts\n * import { loadSnapshotAsMap } from \"@gusto/baerly-storage\";\n *\n * const map =\n * srcCurrent.snapshot === null\n * ? new Map<string, DocumentData>()\n * : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, \"tickets\");\n * ```\n *\n * @throws BaerlyError code=\"Internal\" — pointer resolves to no body,\n * or the body's SHA-256 doesn't match the hash embedded in the\n * filename. (Protocol invariant violation; a corrupted snapshot\n * the reader cannot continue past.)\n * @throws BaerlyError code=\"InvalidResponse\" — body isn't valid JSON,\n * isn't an object, has an unsupported `schema_version`, or carries a\n * `collection` that doesn't match `expectedCollection`.\n */\nexport const loadSnapshotAsMap = async (\n storage: Storage,\n key: string,\n expectedCollection: string,\n signal?: AbortSignal,\n): Promise<Map<string, DocumentData>> => {\n const got = await storage.get(key, signal !== undefined ? { signal } : undefined);\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot pointer ${key} resolves to no body; protocol violation`,\n );\n }\n // Verify hash: the filename shape is\n // `<...>/snapshot/L<n>/<min>-<max>-<sha256>.json`. The sha256 is\n // the segment after the LAST `-` (the two seq fields don't contain\n // dashes), with `.json` stripped.\n const filename = key.slice(key.lastIndexOf(\"/\") + 1).replace(/\\.json$/, \"\");\n const lastDash = filename.lastIndexOf(\"-\");\n const expectedHash = filename.slice(lastDash + 1);\n const actualHash = await snapshotHash(got.body);\n if (actualHash !== expectedHash) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot ${key} body hash mismatch (got ${actualHash}); protocol violation`,\n );\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} body is not valid JSON`,\n error,\n );\n }\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `compact: snapshot ${key} body is not an object`);\n }\n const body = parsed as SnapshotBody;\n if (body.schema_version !== SNAPSHOT_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} has unsupported schema_version ${String(body.schema_version)}`,\n );\n }\n if (body.collection !== expectedCollection) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} carries collection ${body.collection}, expected ${expectedCollection}`,\n );\n }\n if (!Array.isArray(body.docs)) {\n throw new BaerlyError(\"InvalidResponse\", `compact: snapshot ${key} body.docs is not an array`);\n }\n const out = new Map<string, DocumentData>();\n for (const row of body.docs) {\n out.set(row._id, row.body);\n }\n return out;\n};\n","/**\n * Shared log-walk primitives consumed by the read path (`query.ts`),\n * the compactor (`compactor.ts`), and the optional integrity walk in\n * `Writer.#singleAttemptCommit` (`writer.ts`).\n *\n * Two operations: read one log entry, or walk a contiguous range of\n * log entries with bounded parallelism. Each kernel call site\n * previously inlined the same range-build + unbounded `Promise.all`\n * pattern; on a free-tier collection where the compactor lags the\n * tail to 50-100 entries, that fans out 50-100 concurrent GETs per\n * call — and a contended writer multiplies that by the CAS retry\n * budget. `walkLogRange` caps concurrency at\n * {@link MAX_PARALLEL_LOG_READS} so a single call costs at most that\n * many simultaneous GETs against the storage backend.\n *\n * Order invariant: results are returned in seq order regardless of\n * resolution order. The read-side fold is order-sensitive (`U` then\n * `D` on the same doc must apply in that order); callers may iterate\n * the returned array as-is.\n *\n * Signal invariant: when the caller's `AbortSignal` fires, no further\n * chunks dispatch. In-flight reads see the signal via the underlying\n * `Storage.get` call.\n */\n\nimport {\n type DocumentData,\n type LogEntry,\n type Storage,\n BaerlyError,\n decodeJsonBytes,\n logObjectKey,\n MAX_PARALLEL_LOG_READS,\n} from \"@baerly/protocol\";\n\n/**\n * Fetch a single log entry. Centralises the \"missing entry inside the\n * visible log range is a protocol-invariant violation\" rule used by\n * every caller.\n *\n * @throws BaerlyError code=\"Internal\" when the key resolves to no\n * body — a hole inside `[log_seq_start, tail_hint)` is a corruption\n * the kernel can't continue past.\n * @throws BaerlyError code=\"InvalidResponse\" when the body isn't\n * valid JSON.\n */\nexport const readLogEntry = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry> => {\n const got = await readLogEntryWithBytes(storage, key, opts);\n return got.entry;\n};\n\n/**\n * Like {@link readLogEntry}, but also surfaces `bytes` — the\n * byteLength of the STORED log-object body exactly as it was GET back\n * from storage (`got.body.byteLength`).\n *\n * The compactor uses this to sum the byte cost of the folded slice.\n * The stored body byteLength IS what the writer PUT for each entry,\n * so summing `got.body.byteLength` over the folded range yields the\n * exact cost — no re-encode, no round-trip assumption (a re-encode\n * of the parsed `LogEntry` could drift if key-order/whitespace ever\n * diverged from what was PUT).\n *\n * Same error semantics as {@link readLogEntry}.\n */\nconst readLogEntryWithBytes = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<{ entry: LogEntry; bytes: number }> => {\n const got = await storage.get(\n key,\n opts?.signal !== undefined ? { signal: opts.signal } : undefined,\n );\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `log-walk: missing log entry at ${key}; protocol invariant violation`,\n );\n }\n try {\n return { entry: decodeJsonBytes<LogEntry>(got.body), bytes: got.body.byteLength };\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `log-walk: malformed log entry at ${key}`, error);\n }\n};\n\n/**\n * Walk `[fromSeq, toSeqExclusive)` of `${logPrefix}/log/<seq>.json`\n * in chunks of {@link MAX_PARALLEL_LOG_READS} concurrent GETs.\n * Returns the materialised entries in seq order.\n *\n * Empty range (`fromSeq >= toSeqExclusive`) returns `[]` and issues\n * zero GETs.\n *\n * Same error semantics as {@link readLogEntry}: a missing entry\n * throws `Internal`, a malformed body throws `InvalidResponse`.\n */\nexport const walkLogRange = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry[]> => {\n const withBytes = await walkLogRangeWithBytes(storage, logPrefix, fromSeq, toSeqExclusive, opts);\n return withBytes.map((r) => r.entry);\n};\n\n/**\n * Like {@link walkLogRange}, but each element also carries `bytes` —\n * the STORED log-object body byteLength (see {@link readLogEntryWithBytes}).\n * Same seq-order, empty-range, error, and bounded-parallelism\n * ({@link MAX_PARALLEL_LOG_READS}) guarantees as {@link walkLogRange};\n * this is the bytes-aware core `walkLogRange` is implemented on top of.\n *\n * The compactor consumes this so it gets BOTH the parsed entries (for\n * the fold) AND the exact byte sum (for `mean_entry_bytes` stamping) from a\n * single walk.\n */\nexport const walkLogRangeWithBytes = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<Array<{ entry: LogEntry; bytes: number }>> => {\n if (fromSeq >= toSeqExclusive) {\n return [];\n }\n const total = toSeqExclusive - fromSeq;\n const out: Array<{ entry: LogEntry; bytes: number }> = Array.from({ length: total });\n for (let chunkStart = 0; chunkStart < total; chunkStart += MAX_PARALLEL_LOG_READS) {\n opts?.signal?.throwIfAborted();\n const chunkEnd = Math.min(chunkStart + MAX_PARALLEL_LOG_READS, total);\n const promises: Array<Promise<{ entry: LogEntry; bytes: number }>> = [];\n for (let i = chunkStart; i < chunkEnd; i++) {\n const seq = fromSeq + i;\n promises.push(readLogEntryWithBytes(storage, logObjectKey(logPrefix, seq), opts));\n }\n const results = await Promise.all(promises);\n for (let i = 0; i < results.length; i++) {\n out[chunkStart + i] = results[i]!;\n }\n }\n return out;\n};\n\n/**\n * Fold a sequence of `LogEntry` records onto a doc-id-keyed map,\n * applying the protocol's per-doc-replace semantics:\n *\n * - `I` / `U`: when `entry.after !== undefined`, set\n * `map.set(entry.doc_id, entry.after)`. Entries with `after ===\n * undefined` (the partial-merge writer's future patch-only shape)\n * are ignored — today's writer always emits `after`, so this is a\n * forward-compat guard, not a live branch.\n * - `D`: tombstone — `map.delete(entry.doc_id)`.\n *\n * Entries whose `collection` does not match `opts.collection`, or\n * whose `doc_id` is `undefined`, are skipped. When\n * `opts.docIdFilter` is provided, only entries whose `doc_id` is\n * present in the filter set are folded — used by the index-walk\n * read path to scope the fold to the docs the planner already\n * resolved.\n *\n * This is the canonical fold used by the read path\n * (`query.ts`) and the index reconciler (`rebuild-index.ts`).\n * Centralising it keeps the\n * \"straight `set` on I/U; tombstone on D\" protocol invariant in one place.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\nexport const foldLogEntriesOnto = <T extends DocumentData>(\n map: Map<string, T>,\n entries: Iterable<LogEntry>,\n opts: {\n readonly collection: string;\n readonly docIdFilter?: ReadonlySet<string>;\n },\n): void => {\n const { collection, docIdFilter } = opts;\n for (const entry of entries) {\n if (entry.collection !== collection) {\n continue;\n }\n if (entry.doc_id === undefined) {\n continue;\n }\n if (docIdFilter !== undefined && !docIdFilter.has(entry.doc_id)) {\n continue;\n }\n switch (entry.op) {\n case \"I\":\n case \"U\": {\n if (entry.after === undefined) {\n continue;\n }\n map.set(entry.doc_id, entry.after as T);\n break;\n }\n case \"D\": {\n map.delete(entry.doc_id);\n break;\n }\n }\n }\n};\n","/**\n * Tolerant forward-probe for the true committed log tail. The strict\n * `[log_seq_start, hint)` range is dense (a hole is corruption, owned\n * by `walkLogRange`); this owns only the tolerant `[hint, ∞)` probe,\n * where `hint` is a lower bound — the real tail may sit at or past it.\n */\n\nimport {\n type LogEntry,\n type Storage,\n BaerlyError,\n decodeJsonBytes,\n LOG_FORWARD_PROBE_CAP,\n logObjectKey,\n} from \"@baerly/protocol\";\n\n/**\n * Discover the true committed tail and fold entries in `[hint, tail)`.\n * `tail` is the first empty seq (>= hint); `entries` are the\n * LogEntries in `[hint, tail)` in seq order. `cap` bounds the walk;\n * exhausting it THROWS `Internal` (never silently truncates) — see\n * the cap-exhaustion comment below.\n */\nexport const probeTailFrom = async (\n storage: Storage,\n logPrefix: string,\n hint: number,\n opts?: { signal?: AbortSignal; cap?: number },\n): Promise<{ tail: number; entries: LogEntry[] }> => {\n const cap = opts?.cap ?? LOG_FORWARD_PROBE_CAP;\n const getOpts = opts?.signal !== undefined ? { signal: opts.signal } : undefined;\n const entries: LogEntry[] = [];\n for (let i = 0; i < cap; i++) {\n const seq = hint + i;\n const key = logObjectKey(logPrefix, seq);\n const got = await storage.get(key, getOpts);\n if (got === null) {\n return { tail: seq, entries };\n }\n try {\n entries.push(decodeJsonBytes<LogEntry>(got.body));\n } catch (error) {\n // A malformed body at an occupied slot is a protocol violation —\n // surface it as InvalidResponse (the same code readLogEntry uses)\n // rather than a raw SyntaxError leaking out of the probe.\n throw new BaerlyError(\n \"InvalidResponse\",\n `probeTailFrom: malformed log entry at ${key}: ${(error as Error).message}`,\n { cause: error },\n );\n }\n }\n // Cap exhausted without hitting a 404 — the true tail is past `cap`.\n // Returning `hint+cap` here would silently truncate every downstream\n // read (since.ts / query.ts / GC / export / rebuild-index), so we\n // THROW instead, mirroring `findLogTail`'s cap-exhaustion guard. With\n // the maintenance tick keeping `tail_hint` within\n // `MAINTENANCE_TAIL_HINT_REFRESH_WRITES` of the true tail (HR-2), this\n // is a pure runaway alarm — a >cap gap means maintenance is\n // broken/disabled (a graduation/operator concern), never normal\n // operation. No partial-accept escape hatch: no caller legitimately\n // needs to walk past the cap.\n throw new BaerlyError(\n \"Internal\",\n `probeTailFrom: forward probe exceeded ${cap} from hint ${hint} on ${logPrefix}`,\n );\n};\n\n/**\n * First empty log seq at/after `hint` — the slot a new commit creates —\n * found by galloping search (`O(log gap)` GETs vs `probeTailFrom`'s\n * `O(gap)`). Used by the writer's per-commit tail-find, where `tail_hint`\n * can lag the true tail. Position only; no bodies.\n *\n * PRECONDITION: occupancy MUST be a dense prefix from `hint` (galloping\n * assumes monotone occupied→empty; a hole ABOVE `hint` would be skipped\n * and the gallop could return a tail past live entries). Contrast\n * `probeTailFrom`, which stops at the first 404 and is hole-tolerant.\n */\nexport const findLogTail = async (\n storage: Storage,\n logPrefix: string,\n hint: number,\n opts?: { signal?: AbortSignal },\n): Promise<number> => {\n const getOpts = opts?.signal !== undefined ? { signal: opts.signal } : undefined;\n const exists = async (seq: number): Promise<boolean> =>\n (await storage.get(logObjectKey(logPrefix, seq), getOpts)) !== null;\n if (!(await exists(hint))) {\n return hint;\n }\n // Gallop to bracket the tail in `(lo, hi]` (lo occupied, hi empty).\n let lo = hint;\n let step = 1;\n let hi = hint + step;\n while (await exists(hi)) {\n lo = hi;\n step *= 2;\n hi = lo + step;\n if (step > LOG_FORWARD_PROBE_CAP) {\n throw new BaerlyError(\n \"Internal\",\n `findLogTail: galloping probe exceeded ${LOG_FORWARD_PROBE_CAP} from hint ${hint} on ${logPrefix}`,\n );\n }\n }\n while (hi - lo > 1) {\n const mid = lo + Math.floor((hi - lo) / 2);\n if (await exists(mid)) {\n lo = mid;\n } else {\n hi = mid;\n }\n }\n return hi;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,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,WAA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