@gusto/baerly-storage 0.2.0 → 0.4.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/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +176 -70
- package/dist/API.md +213 -139
- package/dist/CHANGELOG.md +434 -0
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +238 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +301 -301
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
- package/dist/cloudflare-DzKBrUlg.js.map +1 -0
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +59 -26
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/current-json-C6nhPOm1.js +190 -0
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
- package/dist/deploy-DonTr-CV.js.map +1 -0
- package/dist/dev-vite.d.ts +11 -7
- package/dist/dev-vite.js +7 -6
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
- package/dist/doctor-DSIyCDg_.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
- package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
- package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
- package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
- package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +176 -68
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
- package/dist/plan-a7PJHBCy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/restore-R-4rbciV.js +778 -0
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/subcommand-DoDA-K7d.js +197 -0
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +77 -42
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js +0 -354
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js +0 -771
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js +0 -6236
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js +0 -5122
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
- package/dist/usage-CLjirdD-.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { n as CURRENT_JSON_CONTENT_TYPE } from "./constants-CfeMWQWk.js";
|
|
2
|
+
import { t as BaerlyError } from "./errors-Dfa3p78c.js";
|
|
3
|
+
//#region packages/protocol/src/bytes.ts
|
|
4
|
+
/**
|
|
5
|
+
* UTF-8 JSON byte helpers — names the encode/decode idiom used by
|
|
6
|
+
* every content body, log entry, snapshot, and current.json payload.
|
|
7
|
+
*/
|
|
8
|
+
const encodeJsonBytes = (value) => new TextEncoder().encode(JSON.stringify(value));
|
|
9
|
+
const decodeJsonBytes = (bytes) => JSON.parse(new TextDecoder().decode(bytes));
|
|
10
|
+
//#endregion
|
|
11
|
+
//#region packages/protocol/src/coordination/current-json.ts
|
|
12
|
+
/**
|
|
13
|
+
* `current.json` — the per-collection compaction-state control object —
|
|
14
|
+
* and its embedded, currently dormant {@link WriterFence} epoch token.
|
|
15
|
+
*
|
|
16
|
+
* A dedicated `coordination/` namespace (parallel to `storage/`) holds
|
|
17
|
+
* primitives whose contract is "atomic agreement over a small JSON
|
|
18
|
+
* object" rather than "byte I/O." Future siblings (compactor
|
|
19
|
+
* manifest, sweeper checkpoint) join here, not at the top
|
|
20
|
+
* level. The module lives inside `@baerly/protocol` because it is pure
|
|
21
|
+
* (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,
|
|
22
|
+
* no implicit globals) and must remain Worker-bundleable — every byte
|
|
23
|
+
* of network traffic threads through the {@link Storage} seam.
|
|
24
|
+
*
|
|
25
|
+
* Contract surface:
|
|
26
|
+
* - {@link readCurrentJson} — fetch + parse + validate
|
|
27
|
+
* - {@link createCurrentJson} — create-only (CAS via `If-None-Match:"*"`)
|
|
28
|
+
* - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)
|
|
29
|
+
* - {@link claimWriter} — bump epoch + stamp server-clock claim time
|
|
30
|
+
*
|
|
31
|
+
* Why the two-round-trip claim protocol: `claimed_at` MUST come from
|
|
32
|
+
* `StoragePutResult.serverDate` (the single shared clock across
|
|
33
|
+
* instances), not the local clock. `serverDate` is only known *after*
|
|
34
|
+
* the CAS PUT lands, so {@link claimWriter} writes the record with
|
|
35
|
+
* `claimed_at: ""` first, then overwrites itself with the correct
|
|
36
|
+
* `serverDate.toISOString()` in a second CAS. The epoch bump is
|
|
37
|
+
* already durable from the first put either way; a peer landing
|
|
38
|
+
* between the two writes loses cleanly with `Conflict`.
|
|
39
|
+
*
|
|
40
|
+
* Why CAS errors are wrapped: every in-tree {@link Storage} impl
|
|
41
|
+
* surfaces a lost CAS as `BaerlyError{code:"Conflict"}`. Downstream
|
|
42
|
+
* callers — the Writer, the compactor, the sweeper —
|
|
43
|
+
* discriminate by `code` to decide whether to retry.
|
|
44
|
+
* We re-wrap here only to add the `current.json at <key>` location
|
|
45
|
+
* context to the message; the `code` is unchanged.
|
|
46
|
+
*/
|
|
47
|
+
/**
|
|
48
|
+
* Read + parse `current.json` at `key`. Returns `null` on not-found.
|
|
49
|
+
*
|
|
50
|
+
* @throws BaerlyError{code:"InvalidResponse"} — body is not valid
|
|
51
|
+
* JSON, or `schema_version` is unknown, or the shape fails
|
|
52
|
+
* the runtime guard.
|
|
53
|
+
*/
|
|
54
|
+
async function readCurrentJson(storage, key, opts) {
|
|
55
|
+
const got = await storage.get(key, opts);
|
|
56
|
+
if (got === null) return null;
|
|
57
|
+
const text = new TextDecoder().decode(got.body);
|
|
58
|
+
let parsed;
|
|
59
|
+
try {
|
|
60
|
+
parsed = JSON.parse(text);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
throw new BaerlyError("InvalidResponse", `current.json at ${key}: body is not valid JSON`, error);
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
json: assertCurrentJson(parsed, key),
|
|
66
|
+
etag: got.etag
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Create `current.json` if-and-only-if it does not exist (S3
|
|
71
|
+
* `If-None-Match: "*"`). Use this once per collection at provisioning
|
|
72
|
+
* time; subsequent updates go through {@link casUpdateCurrentJson}.
|
|
73
|
+
*
|
|
74
|
+
* @throws BaerlyError{code:"Conflict"} — the key already exists.
|
|
75
|
+
* Caller decides whether to read + reconcile or surface.
|
|
76
|
+
* @throws BaerlyError{code:"InvalidResponse"} — `initial` fails the
|
|
77
|
+
* runtime shape guard.
|
|
78
|
+
*/
|
|
79
|
+
async function createCurrentJson(storage, key, initial, opts) {
|
|
80
|
+
assertCurrentJson(initial, key);
|
|
81
|
+
const body = encodeJson(initial);
|
|
82
|
+
const putOpts = {
|
|
83
|
+
ifNoneMatch: "*",
|
|
84
|
+
contentType: CURRENT_JSON_CONTENT_TYPE,
|
|
85
|
+
...opts?.signal !== void 0 && { signal: opts.signal }
|
|
86
|
+
};
|
|
87
|
+
let result;
|
|
88
|
+
try {
|
|
89
|
+
result = await storage.put(key, body, putOpts);
|
|
90
|
+
} catch (error) {
|
|
91
|
+
throw translateCasError(error, key);
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
json: initial,
|
|
95
|
+
etag: result.etag
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Read-modify-write `current.json` under CAS. The `mutator` receives
|
|
100
|
+
* a deep clone of the current parsed JSON (mutate freely) and returns
|
|
101
|
+
* the new state. The new state is written with `If-Match:
|
|
102
|
+
* <currentEtag>`; on conflict, throws.
|
|
103
|
+
*
|
|
104
|
+
* `mutator` MUST be synchronous and deterministic — it may be called
|
|
105
|
+
* multiple times if the caller wraps this in a retry loop, so it
|
|
106
|
+
* must not have side effects.
|
|
107
|
+
*
|
|
108
|
+
* @throws BaerlyError{code:"Conflict"} — another writer landed a write
|
|
109
|
+
* between this function's read and write. Caller decides
|
|
110
|
+
* whether to retry (read + remutate + rewrite).
|
|
111
|
+
* @throws BaerlyError{code:"InvalidResponse"} — `key` does not exist
|
|
112
|
+
* (use {@link createCurrentJson} instead) or body doesn't
|
|
113
|
+
* parse / fails the shape guard.
|
|
114
|
+
*/
|
|
115
|
+
async function casUpdateCurrentJson(storage, key, mutator, opts) {
|
|
116
|
+
const existing = await readCurrentJson(storage, key, opts);
|
|
117
|
+
if (existing === null) throw new BaerlyError("InvalidResponse", `current.json at ${key} does not exist; use createCurrentJson first`);
|
|
118
|
+
const next = mutator(structuredClone(existing.json));
|
|
119
|
+
assertCurrentJson(next, key);
|
|
120
|
+
const body = encodeJson(next);
|
|
121
|
+
const putOpts = {
|
|
122
|
+
ifMatch: existing.etag,
|
|
123
|
+
contentType: CURRENT_JSON_CONTENT_TYPE,
|
|
124
|
+
...opts?.signal !== void 0 && { signal: opts.signal }
|
|
125
|
+
};
|
|
126
|
+
let result;
|
|
127
|
+
try {
|
|
128
|
+
result = await storage.put(key, body, putOpts);
|
|
129
|
+
} catch (error) {
|
|
130
|
+
throw translateCasError(error, key);
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
json: next,
|
|
134
|
+
etag: result.etag
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Read `current.json.log_seq_start` — the low-water mark of the live
|
|
139
|
+
* log range `[log_seq_start, tail_hint)`. The field is always present
|
|
140
|
+
* on disk (every `createCurrentJson` write seeds it; the compactor
|
|
141
|
+
* advances it on every fold); this helper exists to document intent
|
|
142
|
+
* at call sites that walk the log range or assert the snapshot
|
|
143
|
+
* invariants.
|
|
144
|
+
*/
|
|
145
|
+
const logSeqStartOf = (c) => c.log_seq_start;
|
|
146
|
+
const encodeJson = (json) => encodeJsonBytes(json);
|
|
147
|
+
/**
|
|
148
|
+
* Runtime guard for `parsed` to be a {@link CurrentJson}. Throws
|
|
149
|
+
* `BaerlyError{code:"InvalidResponse"}` rather than coercing. Tolerant
|
|
150
|
+
* reader: unknown keys ignored, new required fields bump
|
|
151
|
+
* `schema_version` (move (b), ADR-003).
|
|
152
|
+
*/
|
|
153
|
+
const assertCurrentJson = (parsed, key) => {
|
|
154
|
+
if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: parsed body is not an object`);
|
|
155
|
+
const r = parsed;
|
|
156
|
+
if (r["schema_version"] === 1 || r["schema_version"] === 2) throw new BaerlyError("InvalidResponse", `current.json at ${key} uses schema v${String(r["schema_version"])} from a pre-0.3.0 internal build; this build requires schema v3. Dump/restore with the old build, or re-provision scratch/local buckets.`);
|
|
157
|
+
if (r["schema_version"] !== 3) throw new BaerlyError("InvalidResponse", `current.json at ${key}: unsupported schema_version ${String(r["schema_version"])}; this build requires 3. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \`rm -rf .baerly-data\`) or recreate the R2/S3 bucket, then retry.`);
|
|
158
|
+
if (!(typeof r["snapshot"] === "string" || r["snapshot"] === null)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot must be string|null`);
|
|
159
|
+
if (typeof r["tail_hint"] !== "number" || !Number.isInteger(r["tail_hint"]) || r["tail_hint"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: tail_hint must be a non-negative integer`);
|
|
160
|
+
if (typeof r["log_seq_start"] !== "number" || !Number.isInteger(r["log_seq_start"]) || r["log_seq_start"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start must be a non-negative integer`);
|
|
161
|
+
if (r["log_seq_start"] > r["tail_hint"]) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_seq_start ${String(r["log_seq_start"])} > tail_hint ${String(r["tail_hint"])}`);
|
|
162
|
+
const fence = r["writer_fence"];
|
|
163
|
+
if (fence === null || typeof fence !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence missing`);
|
|
164
|
+
const f = fence;
|
|
165
|
+
if (typeof f["epoch"] !== "number" || !Number.isInteger(f["epoch"]) || f["epoch"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.epoch must be a non-negative integer`);
|
|
166
|
+
if (typeof f["owner"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.owner must be a string`);
|
|
167
|
+
if (typeof f["claimed_at"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.claimed_at must be a string`);
|
|
168
|
+
if (f["lease_until"] !== void 0 && typeof f["lease_until"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.lease_until must be string if present`);
|
|
169
|
+
if (typeof r["snapshot_bytes"] !== "number" || !Number.isInteger(r["snapshot_bytes"]) || r["snapshot_bytes"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_bytes must be a non-negative integer`);
|
|
170
|
+
if (typeof r["snapshot_rows"] !== "number" || !Number.isInteger(r["snapshot_rows"]) || r["snapshot_rows"] < 0) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot_rows must be a non-negative integer`);
|
|
171
|
+
if (r["last_warned_seq"] !== void 0 && (typeof r["last_warned_seq"] !== "number" || !Number.isInteger(r["last_warned_seq"]) || r["last_warned_seq"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: last_warned_seq must be a non-negative integer if present`);
|
|
172
|
+
if (r["mean_entry_bytes"] !== void 0 && (typeof r["mean_entry_bytes"] !== "number" || !Number.isInteger(r["mean_entry_bytes"]) || r["mean_entry_bytes"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`);
|
|
173
|
+
return parsed;
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Wrap a storage-level error with `current.json at <key>` location
|
|
177
|
+
* context. `Conflict` (the storage layer's CAS-lost signal) is
|
|
178
|
+
* re-thrown with an annotated message; other `BaerlyError`s pass
|
|
179
|
+
* through; non-`BaerlyError` falls through as `InvalidResponse` (in
|
|
180
|
+
* practice unreachable — every in-tree `Storage` impl wraps).
|
|
181
|
+
*/
|
|
182
|
+
const translateCasError = (e, key) => {
|
|
183
|
+
if (e instanceof BaerlyError && e.code === "Conflict") return new BaerlyError("Conflict", `current.json CAS lost at ${key}: ${e.message}`, e);
|
|
184
|
+
if (e instanceof BaerlyError) return e;
|
|
185
|
+
return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, e);
|
|
186
|
+
};
|
|
187
|
+
//#endregion
|
|
188
|
+
export { decodeJsonBytes as a, readCurrentJson as i, createCurrentJson as n, encodeJsonBytes as o, logSeqStartOf as r, casUpdateCurrentJson as t };
|
|
189
|
+
|
|
190
|
+
//# sourceMappingURL=current-json-C6nhPOm1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"current-json-C6nhPOm1.js","names":[],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n","/**\n * `current.json` — the per-collection compaction-state control object —\n * and its embedded, currently dormant {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps snapshot\n * generations by CAS-writing this object; the Writer reads it on every\n * commit to find the snapshot pointer and a non-authoritative\n * tail-probe floor. The numbered log create mints the next integer\n * `seq`; no commit-path code CAS-advances `current.json`.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `3`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 3;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Non-authoritative monotone lower bound on the committed log tail.\n * The authoritative tail is discovered by forward-probe (log-tail.ts);\n * never trust this as the head. Durable advancement is owned by\n * compaction folds, write-tick tail refreshes, and explicit\n * operator/import paths; ordinary writer commits do not refresh it.\n */\n tail_hint: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, tail_hint)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= tail_hint`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /**\n * Row count of the snapshot (= compactor `base.size`, free). With\n * `tail_hint - log_seq_start` (trusted tail entries) this gives the\n * fold's entry count for the ENTRY ceiling `E`. Seeded 0.\n */\n snapshot_rows: number;\n\n /**\n * Optional compactor-stamped mean folded-entry byte size. Maintenance\n * derives live-tail bytes as `entry_count × mean_entry_bytes` without\n * an exact stored counter; absent until first fold.\n */\n mean_entry_bytes?: number;\n\n /**\n * Baseline for rate-limiting the graduation defer-warn off SHARED\n * durable state, not per-isolate memory. The warn fires when the\n * observed/probed tail minus `last_warned_seq` reaches\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes\n * `last_warned_seq` to the observed/probed tail. Absent → 0.\n */\n last_warned_seq?: number;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and is not\n * consumed by the current kernel. Log entries are not stamped with this\n * epoch; the fence is dormant authority metadata, not a reader replay\n * filter.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. In the earlier two-write commit design, every commit checked\n * the epoch before continuing under `current.json` authority. Under\n * single-write commit no production path reads or writes the fence.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Under single-write commit this is retained\n * as an explicit admin/testing primitive only; no production commit\n * path claims or verifies the fence.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the dormant write fence by bumping `epoch` and\n * stamping `claimed_at` from `StoragePutResult.serverDate`. Under\n * single-write commit there is no production commit-path call site;\n * this is retained for explicit admin/testing workflows and future\n * rotation designs.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // Stryker disable next-line ConditionalExpression: `→true` spreads `{lease_until: undefined}` which JSON.stringify omits, so the stored bytes are identical to the normal `→false` path (no key emitted). Genuine equivalent mutant.\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, tail_hint)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-003).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1 || r[\"schema_version\"] === 2) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} uses schema v${String(r[\"schema_version\"])} from a pre-0.3.0 internal build; this build requires schema v${CURRENT_JSON_SCHEMA_VERSION}. Dump/restore with the old build, or re-provision scratch/local buckets.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; this build requires ${CURRENT_JSON_SCHEMA_VERSION}. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \\`rm -rf .baerly-data\\`) or recreate the R2/S3 bucket, then retry.`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"tail_hint\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"tail_hint\"] < 0` → false is subsumed by the downstream `log_seq_start > tail_hint` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_tail_hint always fires); (3) StringLiteral \"tail_hint\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (\n typeof r[\"tail_hint\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_hint\"]) ||\n r[\"tail_hint\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_hint must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"tail_hint\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > tail_hint ${String(r[\"tail_hint\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: `typeof f[\"epoch\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof guard fully subsumed.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_rows\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: `typeof r[\"last_warned_seq\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n if (\n r[\"mean_entry_bytes\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: typeof → false is subsumed by !Number.isInteger.\n (typeof r[\"mean_entry_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"mean_entry_bytes\"]) ||\n r[\"mean_entry_bytes\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n"],"mappings":"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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as CollectionNames, d as IndexDefinition, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig, u as SchemaValidator } from "./app-config-
|
|
2
|
-
import {
|
|
1
|
+
import { a as CollectionNames, d as IndexDefinition, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig, u as SchemaValidator } from "./app-config-DyiFK3_k.js";
|
|
2
|
+
import { f as CurrentJsonRead, n as LogEntry, o as Collection, p as Storage } from "./index-BYk9oCNf.js";
|
|
3
3
|
//#region packages/server/src/schema.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Run a validator and throw `BaerlyError{code:"SchemaError"}` on failure.
|
|
@@ -37,22 +37,10 @@ interface CollectionReadContext {
|
|
|
37
37
|
/** Physical key prefix — already includes `app/<app>/tenant/<tenant>/manifests/<name>`. */
|
|
38
38
|
readonly collectionPrefix: string;
|
|
39
39
|
readonly collectionName: string;
|
|
40
|
-
/**
|
|
41
|
-
* When defined, mutation verbs (`Collection.insert`, `Query.update`,
|
|
42
|
-
* `Collection.replace`, `Query.delete`) buffer a {@link BufferedMutation}
|
|
43
|
-
* onto `txCtx.mutations` instead of calling `Writer.commit`
|
|
44
|
-
* directly. Reads ignore `txCtx` entirely — they go through
|
|
45
|
-
* `Storage` live, by design (no MVCC; see `Db.transaction`'s JSDoc
|
|
46
|
-
* in `./db.ts`). Threaded in by `Db.transaction(...)`; `undefined`
|
|
47
|
-
* outside a transaction.
|
|
48
|
-
*
|
|
49
|
-
* @internal
|
|
50
|
-
*/
|
|
51
|
-
readonly txCtx?: TxContext;
|
|
52
40
|
/**
|
|
53
41
|
* Optional StandardSchemaV1-shaped validator for this collection.
|
|
54
42
|
* When set, `runInsert`, `runUpdate`, and `runReplaceById` validate the
|
|
55
|
-
* post-image before committing
|
|
43
|
+
* post-image before committing — invalid input throws
|
|
56
44
|
* `BaerlyError{code:"SchemaError"}` carrying a `.issues` array of
|
|
57
45
|
* `{ path, message }` entries. `undefined` means no validation
|
|
58
46
|
* (today's behaviour — zero overhead).
|
|
@@ -85,48 +73,6 @@ interface CollectionReadContext {
|
|
|
85
73
|
}
|
|
86
74
|
//#endregion
|
|
87
75
|
//#region packages/server/src/db.d.ts
|
|
88
|
-
/**
|
|
89
|
-
* In-memory buffer for a single in-flight {@link Db.transaction}
|
|
90
|
-
* call. The `Collection<T>` instance passed to the transaction body holds
|
|
91
|
-
* a reference to this object; every mutation verb appends to
|
|
92
|
-
* `mutations` instead of calling `Writer.commit` directly.
|
|
93
|
-
*
|
|
94
|
-
* After the body resolves, `Db.transaction` performs ONE
|
|
95
|
-
* `Writer.commitBatch(...)` to commit every buffered mutation
|
|
96
|
-
* in a single CAS attempt.
|
|
97
|
-
*
|
|
98
|
-
* @internal — referenced by `collection.ts` and `query.ts`; not part of
|
|
99
|
-
* the public API surface for app code.
|
|
100
|
-
*/
|
|
101
|
-
interface TxContext {
|
|
102
|
-
/**
|
|
103
|
-
* The collection name the transaction is scoped to. Mutation verbs
|
|
104
|
-
* runtime-assert that their `Collection<T>`'s `name` matches this
|
|
105
|
-
* field before appending — the type system already prevents the
|
|
106
|
-
* legitimate path, this catches the bug path (a stale `Query<T>`
|
|
107
|
-
* re-attached to a different collection's transaction).
|
|
108
|
-
*/
|
|
109
|
-
readonly collection: string;
|
|
110
|
-
/**
|
|
111
|
-
* Mutations buffered in order of issuance. The commit converts
|
|
112
|
-
* each into one `CommitInput` (`Writer`'s single-mutation
|
|
113
|
-
* shape) and passes the array to `Writer.commitBatch`.
|
|
114
|
-
*/
|
|
115
|
-
readonly mutations: BufferedMutation[];
|
|
116
|
-
}
|
|
117
|
-
/**
|
|
118
|
-
* One buffered mutation. Mirrors {@link CommitInput} minus
|
|
119
|
-
* `collection` (which is constant per transaction and lives on
|
|
120
|
-
* `TxContext.collection`).
|
|
121
|
-
*
|
|
122
|
-
* @internal — only used inside the `Db.transaction` path.
|
|
123
|
-
*/
|
|
124
|
-
interface BufferedMutation {
|
|
125
|
-
readonly op: "I" | "U" | "D";
|
|
126
|
-
readonly docId: string;
|
|
127
|
-
readonly body?: DocumentData;
|
|
128
|
-
readonly origin?: string;
|
|
129
|
-
}
|
|
130
76
|
/**
|
|
131
77
|
* Runtime entry point. One `Db` per `(app, tenant)` request.
|
|
132
78
|
*
|
|
@@ -176,10 +122,14 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
176
122
|
/**
|
|
177
123
|
* Build a tenant-scoped `Db`. Throws
|
|
178
124
|
* `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
|
|
179
|
-
* is empty
|
|
125
|
+
* is empty, contains `/`, is `"."` or `".."`, contains control
|
|
126
|
+
* characters, starts with the reserved `"_"` prefix, or exceeds
|
|
127
|
+
* 256 bytes.
|
|
180
128
|
*
|
|
181
129
|
* @throws BaerlyError code="InvalidConfig" when `app` or `tenant` is
|
|
182
|
-
* empty or contains
|
|
130
|
+
* empty, contains `/`, is `"."` or `".."`, contains control
|
|
131
|
+
* characters, starts with the reserved `"_"` prefix, or exceeds
|
|
132
|
+
* 256 bytes.
|
|
183
133
|
*
|
|
184
134
|
* @example
|
|
185
135
|
* ```ts
|
|
@@ -223,8 +173,9 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
223
173
|
* `name` returns a FRESH `Collection<T>` object on each call (chain
|
|
224
174
|
* identity is intentional — modifiers return new objects).
|
|
225
175
|
*
|
|
226
|
-
* @throws BaerlyError code="InvalidConfig" when `name` is empty
|
|
227
|
-
* contains
|
|
176
|
+
* @throws BaerlyError code="InvalidConfig" when `name` is empty,
|
|
177
|
+
* contains `/`, is `"."` or `".."`, contains control characters,
|
|
178
|
+
* starts with the reserved `"_"` prefix, or exceeds 256 bytes.
|
|
228
179
|
*
|
|
229
180
|
* @example
|
|
230
181
|
* ```ts
|
|
@@ -250,54 +201,12 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
250
201
|
*
|
|
251
202
|
* Runs the same `name`-validation guard as {@link Db.collection}.
|
|
252
203
|
*
|
|
253
|
-
* @throws BaerlyError code="InvalidConfig" when `name` is empty
|
|
254
|
-
* contains
|
|
204
|
+
* @throws BaerlyError code="InvalidConfig" when `name` is empty,
|
|
205
|
+
* contains `/`, is `"."` or `".."`, contains control characters,
|
|
206
|
+
* starts with the reserved `"_"` prefix, or exceeds 256 bytes.
|
|
255
207
|
* @internal
|
|
256
208
|
*/
|
|
257
209
|
collectionReadContext(name: string): CollectionReadContext;
|
|
258
|
-
/**
|
|
259
|
-
* Atomic mutation over a single collection. The callback receives a
|
|
260
|
-
* `Collection<T>` (not a `Db`) so cross-collection writes inside a
|
|
261
|
-
* transaction are a TypeScript error at compile time — not a
|
|
262
|
-
* runtime trap. Mutation verbs (`insert`, `update`, `replace`,
|
|
263
|
-
* `delete`) buffer; reads (`first`, `all`, `count`) go through
|
|
264
|
-
* `Storage` live (no MVCC snapshot, no read-your-writes).
|
|
265
|
-
*
|
|
266
|
-
* Single-attempt: on CAS conflict throws
|
|
267
|
-
* `BaerlyError{code:"Conflict"}`. The body MAY have already run its
|
|
268
|
-
* read side-effects (no rollback of in-memory state); the write
|
|
269
|
-
* side-effects either all landed or none did. Wrap in a retry
|
|
270
|
-
* loop you wrote if you want one.
|
|
271
|
-
*
|
|
272
|
-
* Empty body (or a body that buffers nothing) resolves without
|
|
273
|
-
* touching `current.json`.
|
|
274
|
-
*
|
|
275
|
-
* @throws BaerlyError code="Conflict" — CAS lost on the collection's
|
|
276
|
-
* `current.json`. Caller decides whether to re-run the body.
|
|
277
|
-
* @throws Whatever the body throws — re-thrown as-is. The commit
|
|
278
|
-
* is skipped when the body throws.
|
|
279
|
-
* @throws BaerlyError code="InvalidConfig" — `collection` is empty or
|
|
280
|
-
* contains `/`.
|
|
281
|
-
*
|
|
282
|
-
* @remarks
|
|
283
|
-
* Single-collection by design. Cross-collection 2PC was rejected on
|
|
284
|
-
* cost grounds — multiple round-trips per commit, no native fencing
|
|
285
|
-
* primitive on S3-compatible storage, no rollback to undo a
|
|
286
|
-
* successful PUT — and because in-doubt-transaction recovery state
|
|
287
|
-
* would contradict the stateless-writer model. Applications that
|
|
288
|
-
* need cross-collection atomicity re-express it at the app layer: an
|
|
289
|
-
* idempotent move keyed off source-row state, or a single
|
|
290
|
-
* denormalized collection with a `status` column.
|
|
291
|
-
*
|
|
292
|
-
* @example
|
|
293
|
-
* ```ts
|
|
294
|
-
* await db.transaction("tickets", async (tx) => {
|
|
295
|
-
* const open = await tx.where({ status: "open" }).count();
|
|
296
|
-
* if (open < 100) await tx.insert({ title: "another", status: "open" });
|
|
297
|
-
* });
|
|
298
|
-
* ```
|
|
299
|
-
*/
|
|
300
|
-
transaction<T extends DocumentData = DocumentData>(collection: string, body: (tx: Collection<T>) => Promise<void>): Promise<void>;
|
|
301
210
|
/**
|
|
302
211
|
* Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns
|
|
303
212
|
* `null` when the collection has not been provisioned yet (no
|
|
@@ -317,7 +226,7 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
317
226
|
}): Promise<CurrentJsonRead | null>;
|
|
318
227
|
/**
|
|
319
228
|
* Read + parse one `LogEntry` by `seq` from
|
|
320
|
-
* `manifests/<collection
|
|
229
|
+
* `manifests/<collection>/log/<seq>.json`. Returns `null`
|
|
321
230
|
* when the entry is missing — this typically means the GC sweeper
|
|
322
231
|
* deleted the entry between a `readCurrentJson` and this GET (the
|
|
323
232
|
* `/v1/since` handler treats the race as silent and skips the
|
|
@@ -330,7 +239,16 @@ declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
|
330
239
|
getLogEntry(collection: string, seq: number, opts?: {
|
|
331
240
|
signal?: AbortSignal;
|
|
332
241
|
}): Promise<LogEntry | null>;
|
|
242
|
+
/**
|
|
243
|
+
* Forward-probe the TRUE committed log tail from `hint` (a lower
|
|
244
|
+
* bound, typically `tail_hint`). Backs the `/v1/since` end-bound.
|
|
245
|
+
*
|
|
246
|
+
* @internal — typed seam for the HTTP handler.
|
|
247
|
+
*/
|
|
248
|
+
probeLogTail(collection: string, hint: number, opts?: {
|
|
249
|
+
signal?: AbortSignal;
|
|
250
|
+
}): Promise<number>;
|
|
333
251
|
}
|
|
334
252
|
//#endregion
|
|
335
253
|
export { validateOrThrow as n, Db as t };
|
|
336
|
-
//# sourceMappingURL=db-
|
|
254
|
+
//# sourceMappingURL=db-DsPkOVEH.d.ts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as loadAppConfig } from "./config-
|
|
1
|
+
import { t as loadAppConfig } from "./config-1tv0-Yzm.js";
|
|
2
|
+
import { t as deployCloudflare } from "./cloudflare-DzKBrUlg.js";
|
|
2
3
|
import { a as setJsonMode, n as emitError, o as BaerlyError, r as emitSuccess, s as defineCommand } from "./baerly.js";
|
|
3
|
-
import { t as deployCloudflare } from "./cloudflare-CINJPKCW.js";
|
|
4
4
|
//#region src/deploy.ts
|
|
5
5
|
/**
|
|
6
6
|
* `baerly deploy` — citty dispatcher.
|
|
@@ -28,11 +28,18 @@ const DEPLOY_ARGS = {
|
|
|
28
28
|
json: {
|
|
29
29
|
type: "boolean",
|
|
30
30
|
description: "Emit a structured JSON envelope to stdout (success) or stderr (error)"
|
|
31
|
+
},
|
|
32
|
+
probeBucket: {
|
|
33
|
+
type: "string",
|
|
34
|
+
description: "Run a live CAS preflight against this bucket URI before deploying (s3://, file:///, memory://); aborts non-zero if the backend fails the conditional-write / exactly-one-winner probe. Same check as `baerly doctor --bucket`.",
|
|
35
|
+
valueHint: "s3://bucket/prefix"
|
|
31
36
|
}
|
|
32
37
|
};
|
|
33
|
-
const KNOWN_KEYS = new Set([
|
|
38
|
+
const KNOWN_KEYS = /* @__PURE__ */ new Set([
|
|
34
39
|
"target",
|
|
35
40
|
"json",
|
|
41
|
+
"probeBucket",
|
|
42
|
+
"probe-bucket",
|
|
36
43
|
"_"
|
|
37
44
|
]);
|
|
38
45
|
const errorToExitCode = (code) => {
|
|
@@ -47,7 +54,7 @@ const handleDeploy = async (args) => {
|
|
|
47
54
|
const config = await loadAppConfig();
|
|
48
55
|
const target = args.target ?? config.target;
|
|
49
56
|
if (target === "cloudflare") {
|
|
50
|
-
const exit = await deployCloudflare(config);
|
|
57
|
+
const exit = await deployCloudflare(config, { probeBucketUri: typeof args.probeBucket === "string" && args.probeBucket.length > 0 ? args.probeBucket : void 0 });
|
|
51
58
|
if (exit === 0) emitSuccess({
|
|
52
59
|
command: "deploy",
|
|
53
60
|
status: "ok",
|
|
@@ -80,4 +87,4 @@ const deploy = defineCommand({
|
|
|
80
87
|
//#endregion
|
|
81
88
|
export { deploy };
|
|
82
89
|
|
|
83
|
-
//# sourceMappingURL=deploy-
|
|
90
|
+
//# sourceMappingURL=deploy-DonTr-CV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"deploy-DonTr-CV.js","names":[],"sources":["../packages/cli/src/deploy.ts"],"sourcesContent":["/**\n * `baerly deploy` — citty dispatcher.\n *\n * Reads `baerly.config.ts:target` and routes to the matching\n * deploy backend. Today: `cloudflare` only — the `node` example\n * embodies its deployment shape directly (self-host via `node\n * server.js` after your PaaS or container build), so `baerly\n * deploy` rejects `target: \"node\"` with an actionable InvalidConfig.\n *\n * Exit-code contract (standard CLI shape):\n * - 0 success.\n * - 1 user error (InvalidConfig, missing config, unknown target).\n * - 2 storage / external error (NetworkError, Wrangler returned\n * non-zero, anything non-BaerlyError).\n * - 3 protocol invariant (Conflict, Internal, InvalidResponse —\n * should not happen here unless someone hand-edited mid-flight).\n */\n\nimport { defineCommand, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { deployCloudflare } from \"./deploy/cloudflare.ts\";\nimport { emitError, emitSuccess, setJsonMode } from \"./output.ts\";\n\nconst DEPLOY_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).',\n valueHint: \"cloudflare\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n probeBucket: {\n type: \"string\",\n description:\n \"Run a live CAS preflight against this bucket URI before deploying (s3://, file:///, memory://); aborts non-zero if the backend fails the conditional-write / exactly-one-winner probe. Same check as `baerly doctor --bucket`.\",\n valueHint: \"s3://bucket/prefix\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\n \"target\",\n \"json\",\n \"probeBucket\",\n \"probe-bucket\",\n \"_\",\n]);\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst handleDeploy = async (args: ParsedArgs<typeof DEPLOY_ARGS>): Promise<number> => {\n setJsonMode(args.json === true);\n try {\n for (const k of Object.keys(args)) {\n if (!KNOWN_KEYS.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly deploy: unknown flag --${k}`);\n }\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const probeBucketUri =\n typeof args.probeBucket === \"string\" && args.probeBucket.length > 0\n ? args.probeBucket\n : undefined;\n const exit = await deployCloudflare(config, { probeBucketUri });\n if (exit === 0) {\n emitSuccess({ command: \"deploy\", status: \"ok\", target });\n }\n return exit;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. ` +\n `Self-host: \\`node server.js\\` after your PaaS or container build. ` +\n `Cloudflare Workers is the only managed deploy backend today.`,\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(\"deploy\", error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(\"deploy\", \"Unknown\", (error as Error).message);\n return 2;\n }\n};\n\n/** citty `defineCommand` block for `baerly deploy`. */\nexport const deploy = defineCommand({\n meta: {\n name: \"deploy\",\n description: \"Deploy this baerly app. Dispatches by baerly.config.ts:target.\",\n },\n args: DEPLOY_ARGS,\n run: async ({ args }) => {\n const code = await handleDeploy(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDeploy = async (argv: readonly string[]): Promise<number> => {\n const { parseArgs } = await import(\"citty\");\n let parsed: ParsedArgs<typeof DEPLOY_ARGS>;\n try {\n parsed = parseArgs<typeof DEPLOY_ARGS>(argv as string[], DEPLOY_ARGS);\n } catch (error) {\n setJsonMode(argv.includes(\"--json\"));\n emitError(\"deploy\", \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return handleDeploy(parsed);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,aAAa;EACX,MAAM;EACN,aACE;EACF,WAAW;CACb;AACF;AAEA,MAAM,6BAAkC,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;AAEA,MAAM,eAAe,OAAO,SAA0D;CACpF,YAAY,KAAK,SAAS,IAAI;CAC9B,IAAI;EACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,WAAW,IAAI,CAAC,GACnB,MAAM,IAAI,YAAY,iBAAiB,iCAAiC,GAAG;EAG/E,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAK3B,MAAM,OAAO,MAAM,iBAAiB,QAAQ,EAAE,gBAH5C,OAAO,KAAK,gBAAgB,YAAY,KAAK,YAAY,SAAS,IAC9D,KAAK,cACL,KAAA,EACuD,CAAC;GAC9D,IAAI,SAAS,GACX,YAAY;IAAE,SAAS;IAAU,QAAQ;IAAM;GAAO,CAAC;GAEzD,OAAO;EACT;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,uJAGlD;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,aAAa;GAChC,UAAU,UAAU,MAAM,MAAM,MAAM,OAAO;GAC7C,OAAO,gBAAgB,MAAM,IAAI;EACnC;EACA,UAAU,UAAU,WAAY,MAAgB,OAAO;EACvD,OAAO;CACT;AACF;;AAGA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,OAAO,MAAM,aAAa,IAAI;EACpC,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;CAErB;AACF,CAAC"}
|
package/dist/dev-vite.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as BaerlyAppConfig } from "./app-config-
|
|
2
|
-
import { r as Verifier } from "./index-
|
|
1
|
+
import { n as BaerlyAppConfig } from "./app-config-DyiFK3_k.js";
|
|
2
|
+
import { r as Verifier } from "./index-BYk9oCNf.js";
|
|
3
3
|
import { t as DevBannerHint } from "./dev-banner-CWHIk8tH.js";
|
|
4
|
-
import { t as Db } from "./db-
|
|
4
|
+
import { t as Db } from "./db-DsPkOVEH.js";
|
|
5
5
|
import { Plugin } from "vite";
|
|
6
6
|
|
|
7
7
|
//#region packages/dev/src/vite-plugin.d.ts
|
|
@@ -36,8 +36,12 @@ interface BaerlyDevOptions {
|
|
|
36
36
|
* staging IdP, or any custom auth shape.
|
|
37
37
|
*/
|
|
38
38
|
readonly verifier?: Verifier;
|
|
39
|
-
/**
|
|
40
|
-
|
|
39
|
+
/**
|
|
40
|
+
* Absolute path to the data directory for LocalFsStorage.
|
|
41
|
+
* **Optional** — defaults to `<vite root>/.baerly-data`, so the dev
|
|
42
|
+
* server runs zero-config.
|
|
43
|
+
*/
|
|
44
|
+
readonly dataDir?: string;
|
|
41
45
|
/** Optional async seed callback, invoked after ensureTable, before mount. */
|
|
42
46
|
readonly seed?: (db: Db) => Promise<void>;
|
|
43
47
|
/** Extra hints appended to the dev banner. */
|
|
@@ -76,8 +80,8 @@ interface BaerlyDevAuthOptions {
|
|
|
76
80
|
* default `prefix` also covers `/api/*` because that's the canonical
|
|
77
81
|
* namespace for the "wrap `baerly.fetch!`" recipe (a server-side
|
|
78
82
|
* endpoint the SPA client can't run on its own, e.g. an endpoint
|
|
79
|
-
* that
|
|
80
|
-
* namespace, override:
|
|
83
|
+
* that fans a write across several documents server-side). If you
|
|
84
|
+
* mount under a different namespace, override:
|
|
81
85
|
*
|
|
82
86
|
* ```ts
|
|
83
87
|
* baerlyDevAuth({ secret, prefix: ["/v1", "/internal"] });
|
package/dist/dev-vite.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { n as resolveVerifier, t as Db } from "./src-
|
|
2
|
-
import {
|
|
3
|
-
import { n as
|
|
1
|
+
import { n as resolveVerifier, t as Db } from "./src-CYHFDrKz.js";
|
|
2
|
+
import { n as getRequestListener, t as baerlyNode } from "./src-BG20LZs7.js";
|
|
3
|
+
import { i as printDevBanner, n as ensureTable, t as LocalFsStorage } from "./src-DYZ4H1aF.js";
|
|
4
|
+
import { resolve } from "node:path";
|
|
4
5
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
6
|
//#region packages/dev/src/vite-plugin.ts
|
|
6
7
|
const isV1Path = (url) => url === "/v1" || url.startsWith("/v1/") || url.startsWith("/v1?");
|
|
@@ -49,8 +50,8 @@ const matchesAnyPrefix = (url, prefixes) => {
|
|
|
49
50
|
* default `prefix` also covers `/api/*` because that's the canonical
|
|
50
51
|
* namespace for the "wrap `baerly.fetch!`" recipe (a server-side
|
|
51
52
|
* endpoint the SPA client can't run on its own, e.g. an endpoint
|
|
52
|
-
* that
|
|
53
|
-
* namespace, override:
|
|
53
|
+
* that fans a write across several documents server-side). If you
|
|
54
|
+
* mount under a different namespace, override:
|
|
54
55
|
*
|
|
55
56
|
* ```ts
|
|
56
57
|
* baerlyDevAuth({ secret, prefix: ["/v1", "/internal"] });
|
|
@@ -158,7 +159,7 @@ function baerlyDev(opts) {
|
|
|
158
159
|
const tenant = opts.config.tenant;
|
|
159
160
|
const tables = Object.keys(opts.config.collections);
|
|
160
161
|
const ready = (async () => {
|
|
161
|
-
const storage = new LocalFsStorage({ root: opts.dataDir });
|
|
162
|
+
const storage = new LocalFsStorage({ root: opts.dataDir ?? resolve(server.config.root, ".baerly-data") });
|
|
162
163
|
for (const table of tables) await ensureTable(storage, {
|
|
163
164
|
app,
|
|
164
165
|
tenant,
|