@gusto/baerly-storage 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -124
- package/dist/API.md +161 -511
- package/dist/CHANGELOG.md +1148 -307
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +38 -39
- package/dist/dev-vite.js +67 -36
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
- package/dist/gcs.d.ts +30 -0
- package/dist/gcs.js +1 -0
- package/dist/goog4-signer-CeLIABoE.js +331 -0
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +130 -142
- package/dist/node.js +4 -3
- package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/sha256-4FfGQNPw.js +22 -0
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/sigv4-sign-5IUflUD_.js +507 -0
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +96 -69
- package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js +0 -2693
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-DSMIVqzL.js +0 -203
- package/dist/cost-DSMIVqzL.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DsPkOVEH.d.ts +0 -254
- 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/dump-Bh5k26VQ.js +0 -94
- package/dist/dump-Bh5k26VQ.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DtF5tDIM.js +0 -401
- package/dist/export-DtF5tDIM.js.map +0 -1
- package/dist/fsck-D_djMO5D.js +0 -279
- package/dist/fsck-D_djMO5D.js.map +0 -1
- package/dist/http-DGd5tbNs.js.map +0 -1
- package/dist/index-0rZcMBwy.d.ts +0 -115
- package/dist/index-BNRh23K9.d.ts +0 -162
- package/dist/index-BYk9oCNf.d.ts +0 -1112
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-6WZ-pC7-.js +0 -133
- package/dist/inspect-6WZ-pC7-.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js +0 -522
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js +0 -2157
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-B_e0T99L.d.ts +0 -537
- package/dist/maintenance-C7coQp4c.js +0 -1418
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-BmflLCdF.js.map +0 -1
- package/dist/plan-a7PJHBCy.js.map +0 -1
- package/dist/query-rAtXNQQB.js +0 -1773
- package/dist/query-rAtXNQQB.js.map +0 -1
- package/dist/rebuild-index-BVzQSZlm.js +0 -81
- package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-R-4rbciV.js +0 -778
- package/dist/restore-R-4rbciV.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BL_JoPTn.js.map +0 -1
- package/dist/src-CYHFDrKz.js +0 -536
- package/dist/src-CYHFDrKz.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/subcommand-DoDA-K7d.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-DBV1eQHC.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.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;CACr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a,SACxB,cAAc;CAElB;CACA,QAAQ,OAAO,MACb,aAAa,WAAW,QAAQ,eAAe,IAAI,KAAK,IAAI,IAAI,aAAa,UAAU,iBAAiB,IAAI,KAAK,IAAI,IAAI,QAAQ,OACnI;AACF;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aACE,yFACJ;CACA,MAAM;CACN,SAAS,OAAO,SAAS;EAGvB,IAAI,KAAK,WAAW,KAAA,GAAW;GAC7B,MAAM,EAAE,SAAS,cAAc,MAAM,eAAe,KAAK,MAAM;GAC/D,MAAM,SAAS,MAAM,UAAU,SAAS,SAAS;GACjD,aAAa;IAAE,MAAM;IAAU,OAAO,KAAK;GAAO,GAAG,MAAM;GAC3D,OAAO,OAAO,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"}
|
package/dist/dump-Bh5k26VQ.js
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import { r as parseBucketUri } from "./config-1tv0-Yzm.js";
|
|
2
|
-
import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
|
|
3
|
-
import { n as loadMaterialisedView } from "./plan-a7PJHBCy.js";
|
|
4
|
-
import { a as TENANT_ARG, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, s as defineBaerlySubcommand, t as APP_ARG } from "./subcommand-DoDA-K7d.js";
|
|
5
|
-
import "node:stream";
|
|
6
|
-
//#region src/admin/dump.ts
|
|
7
|
-
const DUMP_ARGS = {
|
|
8
|
-
bucket: BUCKET_ARG,
|
|
9
|
-
app: APP_ARG,
|
|
10
|
-
tenant: TENANT_ARG,
|
|
11
|
-
collection: COLLECTION_ARG,
|
|
12
|
-
json: JSON_ARG
|
|
13
|
-
};
|
|
14
|
-
/**
|
|
15
|
-
* Recursive byte-stable JSON stringifier. Object keys at every nesting
|
|
16
|
-
* level are sorted ASCII-lex; array element order is preserved as-is.
|
|
17
|
-
* Numbers must be finite (protocol forbids NaN / Infinity in bodies).
|
|
18
|
-
*/
|
|
19
|
-
const canonicalStringify = (value) => {
|
|
20
|
-
if (typeof value === "number") {
|
|
21
|
-
if (!Number.isFinite(value)) throw new BaerlyError("InvalidResponse", `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`);
|
|
22
|
-
return JSON.stringify(value);
|
|
23
|
-
}
|
|
24
|
-
if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
|
|
25
|
-
if (value === null) return "null";
|
|
26
|
-
if (Array.isArray(value)) return `[${value.map((v) => canonicalStringify(v)).join(",")}]`;
|
|
27
|
-
if (typeof value === "object") {
|
|
28
|
-
const keys = Object.keys(value).toSorted();
|
|
29
|
-
const parts = [];
|
|
30
|
-
for (const k of keys) {
|
|
31
|
-
const v = value[k];
|
|
32
|
-
if (v === void 0) continue;
|
|
33
|
-
parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);
|
|
34
|
-
}
|
|
35
|
-
return `{${parts.join(",")}}`;
|
|
36
|
-
}
|
|
37
|
-
throw new BaerlyError("InvalidResponse", `baerly admin dump: unsupported value type ${typeof value}`);
|
|
38
|
-
};
|
|
39
|
-
/**
|
|
40
|
-
* Drain rows to the supplied writable, applying back-pressure on every
|
|
41
|
-
* line. We don't `end()` the stream — the caller owns its lifecycle
|
|
42
|
-
* (`process.stdout` shouldn't be closed; a test-supplied
|
|
43
|
-
* `createWriteStream` flushes on its own `end()`).
|
|
44
|
-
*/
|
|
45
|
-
const writeToSink = async (sink, rows) => {
|
|
46
|
-
const ids = [...rows.keys()].toSorted();
|
|
47
|
-
let count = 0;
|
|
48
|
-
for (const id of ids) {
|
|
49
|
-
const body = rows.get(id);
|
|
50
|
-
if (body === void 0) continue;
|
|
51
|
-
const line = `${canonicalStringify({
|
|
52
|
-
...body,
|
|
53
|
-
_id: id
|
|
54
|
-
})}\n`;
|
|
55
|
-
if (!sink.write(line)) await new Promise((resolve) => sink.once("drain", resolve));
|
|
56
|
-
count++;
|
|
57
|
-
}
|
|
58
|
-
return count;
|
|
59
|
-
};
|
|
60
|
-
const bundle = defineBaerlySubcommand({
|
|
61
|
-
name: "admin.dump",
|
|
62
|
-
meta: { description: "Canonical NDJSON of the materialised view of one collection." },
|
|
63
|
-
args: DUMP_ARGS,
|
|
64
|
-
handler: async (args, ctx) => {
|
|
65
|
-
const bucket = await parseBucketUri(args.bucket);
|
|
66
|
-
const { app, tenant } = await ctx.resolveAppTenant({
|
|
67
|
-
app: args.app,
|
|
68
|
-
tenant: args.tenant
|
|
69
|
-
});
|
|
70
|
-
assertCollectionArg(args.collection, "baerly admin dump");
|
|
71
|
-
const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
|
|
72
|
-
const view = await loadMaterialisedView({
|
|
73
|
-
storage: bucket.storage,
|
|
74
|
-
currentJsonKey,
|
|
75
|
-
collection: args.collection
|
|
76
|
-
});
|
|
77
|
-
if (view === null) throw new BaerlyError("InvalidConfig", `baerly admin dump: current.json not found at ${currentJsonKey}`);
|
|
78
|
-
const count = await writeToSink(ctx.streams?.stdout ?? process.stdout, view);
|
|
79
|
-
emitSuccess({
|
|
80
|
-
command: "admin.dump",
|
|
81
|
-
status: "ok",
|
|
82
|
-
collection: args.collection,
|
|
83
|
-
dumped: count
|
|
84
|
-
});
|
|
85
|
-
return 0;
|
|
86
|
-
}
|
|
87
|
-
});
|
|
88
|
-
/** citty `defineCommand` block for `baerly admin dump`. */
|
|
89
|
-
const dumpCmd = bundle.cmd;
|
|
90
|
-
bundle.run;
|
|
91
|
-
//#endregion
|
|
92
|
-
export { dumpCmd };
|
|
93
|
-
|
|
94
|
-
//# sourceMappingURL=dump-Bh5k26VQ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dump-Bh5k26VQ.js","names":[],"sources":["../packages/cli/src/admin/dump.ts"],"sourcesContent":["/**\n * `baerly admin dump` — canonical NDJSON of the materialised view.\n *\n * Writes one row per line to stdout, in a strict byte-stable shape so\n * two semantically-equal collections produce byte-equal output. Tests\n * and other programmatic callers can divert the NDJSON output to a\n * file or buffer by passing `{ streams: { stdout } }` to {@link runDump}.\n *\n * Canonical NDJSON dump format:\n *\n * 1. Each row is `{\"_id\":\"<id>\",…}` (no spaces).\n * 2. Row order = ASCII-lex sort on `_id`.\n * 3. Within each row, object keys are sorted ASCII-lex\n * RECURSIVELY — every nested object's keys are sorted too.\n * 4. Numbers as their canonical `JSON.stringify` output.\n * Finite-only (the protocol forbids NaN / Infinity).\n * 5. Strings as `JSON.stringify` output (escape sequences\n * identical to `\\uXXXX` for control codes).\n * 6. One trailing newline at EOF (`\\n`, not `\\r\\n`).\n * 7. No BOM.\n *\n * The round-trip ticket (73) gates byte-equality on this format. A\n * change to any of (1)–(7) is a BREAKING change requiring a\n * round-trip schema-version bump.\n *\n * Empty collection → empty file (no trailing newline) — disambiguates\n * \"zero rows\" from \"one row with empty body\".\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --json JSON envelope (on stdout). Programmatic callers can\n * divert the NDJSON body to a separate writable via the\n * `streams.stdout` option on {@link runDump}.\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Storage / Network / Internal protocol violation.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type Writable } from \"node:stream\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type DocumentValue, type DocumentData } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"../export/index.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport {\n APP_ARG,\n assertCollectionArg,\n BUCKET_ARG,\n COLLECTION_ARG,\n defineBaerlySubcommand,\n JSON_ARG,\n TENANT_ARG,\n} from \"../subcommand.ts\";\n\nconst DUMP_ARGS = {\n bucket: BUCKET_ARG,\n app: APP_ARG,\n tenant: TENANT_ARG,\n collection: COLLECTION_ARG,\n json: JSON_ARG,\n} as const satisfies ArgsDef;\n\n/**\n * Recursive byte-stable JSON stringifier. Object keys at every nesting\n * level are sorted ASCII-lex; array element order is preserved as-is.\n * Numbers must be finite (protocol forbids NaN / Infinity in bodies).\n */\nexport const canonicalStringify = (value: DocumentValue): string => {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`,\n );\n }\n return JSON.stringify(value);\n }\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (value === null) {\n // DocumentValue excludes null at the type level, but `unknown` may\n // sneak in via the snapshot fold — be defensive.\n return \"null\";\n }\n if (Array.isArray(value)) {\n const parts = value.map((v) => canonicalStringify(v));\n return `[${parts.join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const keys = Object.keys(value).toSorted();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as Record<string, DocumentValue>)[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: unsupported value type ${typeof value}`,\n );\n};\n\n/**\n * Drain rows to the supplied writable, applying back-pressure on every\n * line. We don't `end()` the stream — the caller owns its lifecycle\n * (`process.stdout` shouldn't be closed; a test-supplied\n * `createWriteStream` flushes on its own `end()`).\n */\nconst writeToSink = async (\n sink: Writable,\n rows: ReadonlyMap<string, DocumentData>,\n): Promise<number> => {\n const ids = [...rows.keys()].toSorted();\n let count = 0;\n for (const id of ids) {\n const body = rows.get(id);\n if (body === undefined) {\n continue;\n }\n // Merge `_id` into the body so the row literal carries it. The\n // map key is authoritative; if a stale `_id` field disagrees, we\n // overwrite it.\n const row: DocumentData = { ...body, _id: id };\n const line = `${canonicalStringify(row)}\\n`;\n if (!sink.write(line)) {\n await new Promise<void>((resolve) => sink.once(\"drain\", resolve));\n }\n count++;\n }\n return count;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.dump\",\n meta: {\n description: \"Canonical NDJSON of the materialised view of one collection.\",\n },\n args: DUMP_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly admin dump\");\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin dump: current.json not found at ${currentJsonKey}`,\n );\n }\n const sink: Writable = ctx.streams?.stdout ?? process.stdout;\n const count = await writeToSink(sink, view);\n emitSuccess({\n command: \"admin.dump\",\n status: \"ok\",\n collection: args.collection,\n dumped: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin dump`. */\nexport const dumpCmd = 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 runDump = bundle.run;\n"],"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AAM,IAAI,SAAe,YAAY,KAAK,KAAK,SAAS,OAAO,CAAC;EAElE;CACF;CACA,OAAO;AACT;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aAAa,+DACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EACzF,oBAAoB,KAAK,YAAY,mBAAmB;EACxD,MAAM,iBAAiB,GAAG,OAAO,UAAU,MAAM,IAAI,UAAU,OAAO,aAAa,KAAK,WAAW;EACnG,MAAM,OAAO,MAAM,qBAAqB;GACtC,SAAS,OAAO;GAChB;GACA,YAAY,KAAK;EACnB,CAAC;EACD,IAAI,SAAS,MACX,MAAM,IAAI,YACR,iBACA,gDAAgD,gBAClD;EAGF,MAAM,QAAQ,MAAM,YADG,IAAI,SAAS,UAAU,QAAQ,QAChB,IAAI;EAC1C,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,QAAQ;EACV,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOP,OAAO"}
|
package/dist/errors-Dfa3p78c.js
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
//#region packages/protocol/src/errors.ts
|
|
2
|
-
/**
|
|
3
|
-
* Codes whose default failure class is resolved by retrying with a fresh read.
|
|
4
|
-
* Throw sites may override this when the same code is context-sensitive
|
|
5
|
-
* (notably caller-supplied `_id` collisions, which also use `Conflict`).
|
|
6
|
-
*/
|
|
7
|
-
const RETRIABLE_CODES = /* @__PURE__ */ new Set(["NetworkError", "Conflict"]);
|
|
8
|
-
/** True iff this error code's default failure class is retriable. */
|
|
9
|
-
const isRetriableCode = (code) => RETRIABLE_CODES.has(code);
|
|
10
|
-
/**
|
|
11
|
-
* The single error class thrown by baerly-storage. Discriminate by `code`, not
|
|
12
|
-
* `instanceof`: the code string survives `JSON.stringify` round-trips
|
|
13
|
-
* across Worker / iframe / postMessage realm boundaries, where each
|
|
14
|
-
* realm has its own `BaerlyError` constructor identity. IDB-restored
|
|
15
|
-
* writes can replay across realms, so `instanceof` would spuriously
|
|
16
|
-
* fail on a structurally-identical error from another realm.
|
|
17
|
-
*
|
|
18
|
-
* @example
|
|
19
|
-
* ```ts
|
|
20
|
-
* try {
|
|
21
|
-
* await db.collection("tickets").insert({ title: "hi" });
|
|
22
|
-
* } catch (err) {
|
|
23
|
-
* if (err instanceof BaerlyError && err.code === "Conflict") {
|
|
24
|
-
* // Check err.retriable; CAS can retry, duplicate _id cannot.
|
|
25
|
-
* }
|
|
26
|
-
* throw err;
|
|
27
|
-
* }
|
|
28
|
-
* ```
|
|
29
|
-
*/
|
|
30
|
-
var BaerlyError = class extends Error {
|
|
31
|
-
code;
|
|
32
|
-
cause;
|
|
33
|
-
/**
|
|
34
|
-
* Structured field-path issues, set only when `code === "SchemaError"`.
|
|
35
|
-
* Each entry's `path` is a dotted-key list (e.g. `["assignee", "team"]`
|
|
36
|
-
* or `["items", 3, "qty"]`) that targets the offending field on the
|
|
37
|
-
* input document. `message` is the validator-emitted human string.
|
|
38
|
-
*
|
|
39
|
-
* The HTTP layer's `mapError` renders these into the 400 body via
|
|
40
|
-
* the existing `HttpErrorEnvelope`; older callers that don't know
|
|
41
|
-
* about `issues` see a plain message-only error and stay correct.
|
|
42
|
-
*/
|
|
43
|
-
issues;
|
|
44
|
-
/**
|
|
45
|
-
* Raw HTTP status, set only by the client-side wire decoder when
|
|
46
|
-
* inflating an `HttpErrorEnvelope` into this class. Server-side
|
|
47
|
-
* throws never set it (the HTTP layer's `mapError` derives the
|
|
48
|
-
* outbound status from `code`). Useful for diagnostics — e.g. to
|
|
49
|
-
* distinguish 404-as-"no such row" from 404-as-"route not found".
|
|
50
|
-
* Discriminate by `code` for behavior; reach for `status` only when
|
|
51
|
-
* you genuinely need the wire value.
|
|
52
|
-
*/
|
|
53
|
-
status;
|
|
54
|
-
/** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */
|
|
55
|
-
resolution;
|
|
56
|
-
retriableOverride;
|
|
57
|
-
/**
|
|
58
|
-
* Whether this error instance is retriable. Defaults from `code`, but
|
|
59
|
-
* context-sensitive throw sites can override it.
|
|
60
|
-
*/
|
|
61
|
-
get retriable() {
|
|
62
|
-
return this.retriableOverride ?? isRetriableCode(this.code);
|
|
63
|
-
}
|
|
64
|
-
constructor(code, message, cause, issues, status, resolution, retriableOverride) {
|
|
65
|
-
super(message);
|
|
66
|
-
this.name = "BaerlyError";
|
|
67
|
-
this.code = code;
|
|
68
|
-
this.cause = cause;
|
|
69
|
-
this.retriableOverride = retriableOverride;
|
|
70
|
-
if (issues !== void 0) this.issues = issues;
|
|
71
|
-
if (status !== void 0) this.status = status;
|
|
72
|
-
if (resolution !== void 0) this.resolution = resolution;
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
//#endregion
|
|
76
|
-
export { isRetriableCode as n, BaerlyError as t };
|
|
77
|
-
|
|
78
|
-
//# sourceMappingURL=errors-Dfa3p78c.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-Dfa3p78c.js","names":[],"sources":["../packages/protocol/src/errors.ts"],"sourcesContent":["/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * Write conflicted with current state: CAS retry budget exhausted,\n * duplicate caller-supplied `_id`, or an already-existing guarded\n * storage key. Check `BaerlyError.retriable` to decide whether the\n * same logical operation should be retried.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * Runtime enumeration of every {@link BaerlyErrorCode}. The spec\n * generator and the drift gate iterate this to assert the IR lists\n * each code; the type guard in `spec/ir-schema.test.ts` fails tsgo if\n * this tuple and the union diverge. Keep order stable for deterministic\n * artifact diffs. This is the canonical code list — do not re-list\n * codes elsewhere (see RETRIABLE_CODES, the sibling retriable subset).\n */\nexport const ERROR_CODES = [\n \"InvalidConfig\",\n \"NetworkError\",\n \"AccessDenied\",\n \"InvalidResponse\",\n \"Internal\",\n \"SchemaError\",\n \"Conflict\",\n \"Unauthorized\",\n \"NotFound\",\n \"PayloadTooLarge\",\n \"UnsatisfiablePredicate\",\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n] as const satisfies readonly BaerlyErrorCode[];\n\n// Exhaustiveness guard: every union member must appear in ERROR_CODES.\n// If a code is added to BaerlyErrorCode without a tuple entry, this\n// errors at tsgo time (the union is not assignable to the tuple's union).\ntype _ErrorCodesExhaustive = [BaerlyErrorCode] extends [(typeof ERROR_CODES)[number]]\n ? true\n : [\"missing code in ERROR_CODES\", Exclude<BaerlyErrorCode, (typeof ERROR_CODES)[number]>];\n// eslint-disable-next-line no-underscore-dangle\nconst _errorCodesExhaustive: _ErrorCodesExhaustive = true;\nvoid _errorCodesExhaustive;\n\n/**\n * Codes whose default failure class is resolved by retrying with a fresh read.\n * Throw sites may override this when the same code is context-sensitive\n * (notably caller-supplied `_id` collisions, which also use `Conflict`).\n */\nexport const RETRIABLE_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"NetworkError\",\n \"Conflict\",\n]);\n\n/** True iff this error code's default failure class is retriable. */\nexport const isRetriableCode = (code: BaerlyErrorCode): boolean => RETRIABLE_CODES.has(code);\n\n/**\n * Codes raised only inside the client-side React runtime\n * (`useQuery` / `useMutation`); they never travel the HTTP wire, so the\n * machine-contract IR reports `httpStatus: null` for them — distinct\n * from a real `500` (a server-side transport/internal failure the HTTP\n * layer maps to a status). Sibling of {@link RETRIABLE_CODES}; add a\n * code here when a new client-only failure mode joins the union.\n */\nexport const CLIENT_RUNTIME_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n]);\n\n/**\n * The single error class thrown by baerly-storage. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // Check err.retriable; CAS can retry, duplicate _id cannot.\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */\n readonly resolution?: string;\n private readonly retriableOverride: boolean | undefined;\n\n /**\n * Whether this error instance is retriable. Defaults from `code`, but\n * context-sensitive throw sites can override it.\n */\n get retriable(): boolean {\n return this.retriableOverride ?? isRetriableCode(this.code);\n }\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n resolution?: string,\n retriableOverride?: boolean,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n this.retriableOverride = retriableOverride;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (resolution !== undefined) {\n this.resolution = resolution;\n }\n }\n}\n"],"mappings":";;;;;;AAsJA,MAAa,kCAAgD,IAAI,IAAqB,CACpF,gBACA,UACF,CAAC;;AAGD,MAAa,mBAAmB,SAAmC,gBAAgB,IAAI,IAAI;;;;;;;;;;;;;;;;;;;;;AAoC3F,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;;;;;;;;;;;CAWA;;;;;;;;;;CAaA;;CAEA;CACA;;;;;CAMA,IAAI,YAAqB;EACvB,OAAO,KAAK,qBAAqB,gBAAgB,KAAK,IAAI;CAC5D;CAEA,YACE,MACA,SACA,OACA,QAIA,QACA,YACA,mBACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EACb,KAAK,oBAAoB;EAEzB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,eAAe,KAAA,GACjB,KAAK,aAAa;CAEtB;AACF"}
|