@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/observability.d.ts
CHANGED
|
@@ -1,3 +1,27 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Observability — per-HTTP-request context, metrics recorder,
|
|
3
|
+
* canonical-line emission, and the logtape configuration entry point.
|
|
4
|
+
*
|
|
5
|
+
* Consumed by the HTTP router (`http/router.ts`) and both adapters
|
|
6
|
+
* (`@baerly/adapter-cloudflare`, `@baerly/adapter-node`). The
|
|
7
|
+
* high-level flow:
|
|
8
|
+
*
|
|
9
|
+
* 1. The adapter calls {@link configureObservability} once at boot.
|
|
10
|
+
* 2. Each HTTP request creates an {@link ObservabilityContext} (via
|
|
11
|
+
* {@link createObservabilityContext} or `withHttpObservability`
|
|
12
|
+
* for standalone callers that don't have an adapter-managed
|
|
13
|
+
* scope) and runs the work under {@link runWithContext}.
|
|
14
|
+
* 3. The adapter calls {@link flushCanonicalLine} at end-of-request;
|
|
15
|
+
* verifier-rejected requests call `flushUnauthorizedAndRespond`
|
|
16
|
+
* (adapter wiring on `@baerly/server/_internal/observability`).
|
|
17
|
+
* 4. Kernel emissions (Writer histograms, compactor / GC gauges,
|
|
18
|
+
* storage decorator counters) reach the per-request recorder via
|
|
19
|
+
* the ALS lookup inside emission sites
|
|
20
|
+
* (`getCurrentContext()?.recorder`). Background runs outside any
|
|
21
|
+
* HTTP scope emit to the no-op default — by design.
|
|
22
|
+
*
|
|
23
|
+
* The `@baerly/server` package re-exports its own `errorEnvelope`
|
|
24
|
+
* separately; this barrel is the observability seam only.
|
|
25
|
+
*/
|
|
26
|
+
import { _ as ObservabilityContext, a as observableStorage, b as MetricsRecorder, c as withHttpObservability, d as FriendlyLogLevel, f as ObservabilityConfig, g as LogRecord, h as Sink, i as deriveOutcome, l as CATEGORY, m as getLogger, n as getCurrentContext, o as FlushCanonicalLineOptions, p as configureObservability, r as Outcome, s as flushCanonicalLine, t as createObservabilityContext, u as CategoryName, v as ObservabilityContextInit, y as runWithContext } from "./index-RiEYj8t0.js";
|
|
27
|
+
export { CATEGORY, type CategoryName, type FlushCanonicalLineOptions, type FriendlyLogLevel, type LogRecord, type MetricsRecorder, type ObservabilityConfig, type ObservabilityContext, type ObservabilityContextInit, type Outcome, type Sink, configureObservability, createObservabilityContext, deriveOutcome, flushCanonicalLine, getCurrentContext, getLogger, observableStorage, runWithContext, withHttpObservability };
|
package/dist/observability.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as getCurrentContext, r as
|
|
3
|
-
export { CATEGORY, configureObservability, createObservabilityContext, deriveOutcome, flushCanonicalLine,
|
|
1
|
+
import { i as runWithContext } from "./context-rlpSnHFA.js";
|
|
2
|
+
import { d as configureObservability, f as getLogger, i as flushCanonicalLine, l as deriveOutcome, n as getCurrentContext, r as observableStorage, s as withHttpObservability, t as createObservabilityContext, u as CATEGORY } from "./observability-C-ISCCLE.js";
|
|
3
|
+
export { CATEGORY, configureObservability, createObservabilityContext, deriveOutcome, flushCanonicalLine, getCurrentContext, getLogger, observableStorage, runWithContext, withHttpObservability };
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
import { a as CURRENT_JSON_CONTENT_TYPE } from "./constants-D3GSH3tc.js";
|
|
2
|
+
import { i as isWriteConflict, t as BaerlyError } from "./errors-7Rk1HGCE.js";
|
|
3
|
+
// packages/protocol/src/bytes.ts
|
|
4
|
+
/**
|
|
5
|
+
* UTF-8 JSON byte helpers — the common JSON payload encoder/decoder for
|
|
6
|
+
* log entries, snapshots, current.json, and other protocol payloads.
|
|
7
|
+
*/
|
|
8
|
+
const utf8Encoder = new TextEncoder();
|
|
9
|
+
const utf8Decoder$1 = new TextDecoder();
|
|
10
|
+
const encodeJsonBytes = (value) => utf8Encoder.encode(JSON.stringify(value));
|
|
11
|
+
const decodeJsonBytes = (bytes) => JSON.parse(utf8Decoder$1.decode(bytes));
|
|
12
|
+
// packages/protocol/src/coordination/schema-version.ts
|
|
13
|
+
/**
|
|
14
|
+
* Whether `found` is an integer version above `supported`, i.e. an
|
|
15
|
+
* object a newer release wrote. The one predicate behind every
|
|
16
|
+
* "newer" decision, so a reader's message and its extra hints agree.
|
|
17
|
+
*/
|
|
18
|
+
const isNewerSchemaVersion = (found, supported) => typeof found === "number" && Number.isInteger(found) && found > supported;
|
|
19
|
+
/**
|
|
20
|
+
* Message for a durable object whose `schema_version` this build does not
|
|
21
|
+
* read. A larger integer was written by a newer release; anything else is
|
|
22
|
+
* not an object this build wrote. States both versions and an app remedy;
|
|
23
|
+
* never names host settings or suggests deleting data.
|
|
24
|
+
*/
|
|
25
|
+
const unsupportedSchemaVersionMessage = (where, found, supported) => isNewerSchemaVersion(found, supported) ? `${where}: schema_version ${found} was written by a newer baerly-storage release; this build supports schema_version ${supported}. Run that release or newer.` : `${where}: unsupported schema_version ${String(found)}; this build supports schema_version ${supported}. This object was not written by this build; restore it from a backup made by this release, or point the app at the right data.`;
|
|
26
|
+
// packages/protocol/src/coordination/current-json.ts
|
|
27
|
+
/**
|
|
28
|
+
* `current.json` — the per-collection compaction-state control object —
|
|
29
|
+
* and its embedded, currently dormant {@link WriterFence} epoch token.
|
|
30
|
+
*
|
|
31
|
+
* A dedicated `coordination/` namespace (parallel to `storage/`) holds
|
|
32
|
+
* primitives whose contract is "atomic agreement over a small JSON
|
|
33
|
+
* object" rather than "byte I/O." Future siblings (compactor
|
|
34
|
+
* manifest, sweeper checkpoint) join here, not at the top
|
|
35
|
+
* level. The module lives inside `@baerly/protocol` because it is pure
|
|
36
|
+
* (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,
|
|
37
|
+
* no implicit globals) and must remain Worker-bundleable — every byte
|
|
38
|
+
* of network traffic threads through the {@link Storage} seam.
|
|
39
|
+
*
|
|
40
|
+
* Contract surface:
|
|
41
|
+
* - {@link readCurrentJson} — fetch + parse + validate
|
|
42
|
+
* - {@link createCurrentJson} — create-only (CAS via `If-None-Match:"*"`)
|
|
43
|
+
* - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)
|
|
44
|
+
* - {@link assertCurrentJsonTransition} — shared before/after admission
|
|
45
|
+
*
|
|
46
|
+
* Why CAS errors are wrapped: every in-tree {@link Storage} impl
|
|
47
|
+
* surfaces a lost CAS as `BaerlyError{code:"WriteConflict"}`. Downstream
|
|
48
|
+
* callers — the Writer, the compactor, the sweeper —
|
|
49
|
+
* discriminate by `code` to decide whether to retry.
|
|
50
|
+
* We re-wrap here only to add the `current.json at <key>` location
|
|
51
|
+
* context to the message; the `code` is unchanged.
|
|
52
|
+
*/
|
|
53
|
+
const utf8Decoder = new TextDecoder();
|
|
54
|
+
/**
|
|
55
|
+
* Read + parse `current.json` at `key`. Returns `null` on not-found.
|
|
56
|
+
*
|
|
57
|
+
* @throws BaerlyError{code:"InvalidResponse"} — body is not valid
|
|
58
|
+
* JSON, or `schema_version` is unknown, or the shape fails
|
|
59
|
+
* the runtime guard.
|
|
60
|
+
*/
|
|
61
|
+
async function readCurrentJson(storage, key, opts) {
|
|
62
|
+
const got = await storage.get(key, opts);
|
|
63
|
+
if (got === null) return null;
|
|
64
|
+
const text = utf8Decoder.decode(got.body);
|
|
65
|
+
let parsed;
|
|
66
|
+
try {
|
|
67
|
+
parsed = JSON.parse(text);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
throw new BaerlyError("InvalidResponse", `current.json at ${key}: body is not valid JSON`, { cause: error });
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
json: assertCurrentJson(parsed, key),
|
|
73
|
+
etag: got.etag
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Mint a fresh {@link CurrentJson.generation} nonce.
|
|
78
|
+
*
|
|
79
|
+
* Twelve lowercase hex characters (≈2.8 × 10¹⁴ values) — sized so the
|
|
80
|
+
* birthday bound is unreachable across the truncates a bucket sees in
|
|
81
|
+
* its lifetime, while costing only twelve bytes on every `/v1/since`
|
|
82
|
+
* response. A collision would let a stale cursor resume into a
|
|
83
|
+
* truncated generation, which is the exact failure this field exists to
|
|
84
|
+
* prevent, so the margin is deliberate.
|
|
85
|
+
*
|
|
86
|
+
* `crypto.randomUUID` is universally available (Node 19+, Workerd, Bun,
|
|
87
|
+
* browsers) — the same source `uuid()` in `../types.ts` uses.
|
|
88
|
+
*
|
|
89
|
+
* Call this only where a collection is REPLACED, never where one is
|
|
90
|
+
* advanced; see {@link CurrentJson.generation} for the writer split.
|
|
91
|
+
*/
|
|
92
|
+
const mintGeneration = () => crypto.randomUUID().replaceAll("-", "").slice(0, 12);
|
|
93
|
+
/**
|
|
94
|
+
* The charset {@link mintGeneration} emits and `/v1/since` accepts in
|
|
95
|
+
* the generation half of a cursor. Pinned so the manifest validator
|
|
96
|
+
* and the wire validator cannot drift.
|
|
97
|
+
*/
|
|
98
|
+
const GENERATION_RE = /^[0-9a-f]+$/;
|
|
99
|
+
/**
|
|
100
|
+
* Create `current.json` if-and-only-if it does not exist (S3
|
|
101
|
+
* `If-None-Match: "*"`). Use this once per collection at provisioning
|
|
102
|
+
* time; subsequent updates go through {@link casUpdateCurrentJson}.
|
|
103
|
+
*
|
|
104
|
+
* @throws BaerlyError{code:"WriteConflict"} — the key already exists.
|
|
105
|
+
* Caller decides whether to read + reconcile or surface.
|
|
106
|
+
* @throws BaerlyError{code:"InvalidResponse"} — `initial` fails the
|
|
107
|
+
* runtime shape guard.
|
|
108
|
+
*/
|
|
109
|
+
async function createCurrentJson(storage, key, initial, opts) {
|
|
110
|
+
assertCurrentJson(initial, key);
|
|
111
|
+
const body = encodeJson(initial);
|
|
112
|
+
const putOpts = {
|
|
113
|
+
ifNoneMatch: "*",
|
|
114
|
+
contentType: CURRENT_JSON_CONTENT_TYPE,
|
|
115
|
+
...opts?.signal !== void 0 && { signal: opts.signal }
|
|
116
|
+
};
|
|
117
|
+
let result;
|
|
118
|
+
try {
|
|
119
|
+
result = await storage.put(key, body, putOpts);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
throw translateCasError(error, key);
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
json: initial,
|
|
125
|
+
etag: result.etag
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Admission control for a `current.json` state transition.
|
|
130
|
+
*
|
|
131
|
+
* Distinct from {@link assertCurrentJson}, which validates one state in
|
|
132
|
+
* isolation and therefore structurally cannot express a rule about a
|
|
133
|
+
* pair of states. Every invariant that compares before/after belongs
|
|
134
|
+
* here, and every writer that bypasses {@link casUpdateCurrentJson}
|
|
135
|
+
* MUST call it directly — "monotone by construction" is an argument
|
|
136
|
+
* that has to be re-made every time the writer is reimplemented, and
|
|
137
|
+
* it does not survive a chunk-aware compactor or a read-banking path.
|
|
138
|
+
*
|
|
139
|
+
* `Internal`, not `InvalidResponse`: the fault is a local caller's
|
|
140
|
+
* mutator, not a malformed storage response, and `InvalidResponse` maps
|
|
141
|
+
* to HTTP 502 ("storage upstream failed"), which would misattribute a
|
|
142
|
+
* programmer error to the bucket.
|
|
143
|
+
*
|
|
144
|
+
* @throws BaerlyError{code:"Internal"} on any violated transition rule.
|
|
145
|
+
* @see docs/spec/sync-protocol.md invariant 12
|
|
146
|
+
*/
|
|
147
|
+
const assertCurrentJsonTransition = (before, after, key) => {
|
|
148
|
+
if (after.log_seq_start < before.log_seq_start) throw new BaerlyError("Internal", `current.json at ${key}: log_seq_start must not decrease (${String(before.log_seq_start)} → ${String(after.log_seq_start)})`);
|
|
149
|
+
const beforeDeleteFloor = logDeleteFloorOf(before);
|
|
150
|
+
const afterDeleteFloor = logDeleteFloorOf(after);
|
|
151
|
+
if (afterDeleteFloor < beforeDeleteFloor) throw new BaerlyError("Internal", `current.json at ${key}: log_delete_floor must not decrease (${String(beforeDeleteFloor)} → ${String(afterDeleteFloor)})`);
|
|
152
|
+
if (afterDeleteFloor > after.log_seq_start) throw new BaerlyError("Internal", `current.json at ${key}: log_delete_floor must not exceed log_seq_start (${String(afterDeleteFloor)} > ${String(after.log_seq_start)})`);
|
|
153
|
+
};
|
|
154
|
+
/**
|
|
155
|
+
* Read-modify-write `current.json` under CAS. The `mutator` receives
|
|
156
|
+
* a deep clone of the current parsed JSON (mutate freely) and returns
|
|
157
|
+
* the new state. The new state is written with `If-Match:
|
|
158
|
+
* <currentEtag>`; on conflict, throws.
|
|
159
|
+
*
|
|
160
|
+
* `mutator` MUST be synchronous and deterministic — it may be called
|
|
161
|
+
* multiple times if the caller wraps this in a retry loop, so it
|
|
162
|
+
* must not have side effects.
|
|
163
|
+
*
|
|
164
|
+
* @throws BaerlyError{code:"WriteConflict"} — another writer landed a write
|
|
165
|
+
* between this function's read and write. Caller decides
|
|
166
|
+
* whether to retry (read + remutate + rewrite).
|
|
167
|
+
* @throws BaerlyError{code:"InvalidResponse"} — `key` does not exist
|
|
168
|
+
* (use {@link createCurrentJson} instead) or body doesn't
|
|
169
|
+
* parse / fails the shape guard.
|
|
170
|
+
* @throws BaerlyError{code:"Internal"} — the mutator decreased
|
|
171
|
+
* `log_seq_start`, decreased `log_delete_floor`, or set
|
|
172
|
+
* `log_delete_floor > log_seq_start`. Equality is permitted.
|
|
173
|
+
* The compactor calls the same transition validator before its
|
|
174
|
+
* direct `If-Match` PUT; `baerly admin restore --force` is the
|
|
175
|
+
* deliberate truncate exemption.
|
|
176
|
+
*/
|
|
177
|
+
async function casUpdateCurrentJson(storage, key, mutator, opts) {
|
|
178
|
+
const existing = await readCurrentJson(storage, key, opts);
|
|
179
|
+
if (existing === null) throw new BaerlyError("InvalidResponse", `current.json at ${key} does not exist; use createCurrentJson first`);
|
|
180
|
+
const next = mutator(structuredClone(existing.json));
|
|
181
|
+
assertCurrentJson(next, key);
|
|
182
|
+
assertCurrentJsonTransition(existing.json, next, key);
|
|
183
|
+
const body = encodeJson(next);
|
|
184
|
+
const putOpts = {
|
|
185
|
+
ifMatch: existing.etag,
|
|
186
|
+
contentType: CURRENT_JSON_CONTENT_TYPE,
|
|
187
|
+
...opts?.signal !== void 0 && { signal: opts.signal }
|
|
188
|
+
};
|
|
189
|
+
let result;
|
|
190
|
+
try {
|
|
191
|
+
result = await storage.put(key, body, putOpts);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
throw translateCasError(error, key);
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
json: next,
|
|
197
|
+
etag: result.etag
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Read `current.json.log_seq_start` — the low-water mark of the live
|
|
202
|
+
* log range `[log_seq_start, tail_hint)`. The field is always present
|
|
203
|
+
* on disk (every `createCurrentJson` write seeds it; the compactor
|
|
204
|
+
* advances it on every fold); this helper exists to document intent
|
|
205
|
+
* at call sites that walk the log range or assert the snapshot
|
|
206
|
+
* invariants.
|
|
207
|
+
*/
|
|
208
|
+
const logSeqStartOf = (c) => c.log_seq_start;
|
|
209
|
+
/**
|
|
210
|
+
* Read `log_delete_floor`, defaulting an absent field to `0`. Absent
|
|
211
|
+
* means "no deleted prefix is certified", which is exactly what a
|
|
212
|
+
* pre-field bucket records even if older GC deleted sparse log objects.
|
|
213
|
+
*/
|
|
214
|
+
const logDeleteFloorOf = (c) => c.log_delete_floor ?? 0;
|
|
215
|
+
/**
|
|
216
|
+
* The certified delete floor: `log_delete_floor` clamped down to
|
|
217
|
+
* `log_seq_start`. Every consumer of "is `seq` reclaimed" must go through
|
|
218
|
+
* this clamp rather than trusting the raw stored field — invariant 12
|
|
219
|
+
* (`docs/spec/sync-protocol.md`) allows an out-of-bound stored floor to be
|
|
220
|
+
* readable off disk (the single-state read guard deliberately doesn't
|
|
221
|
+
* reject it, so `admin restore` stays repairable), and an unclamped floor
|
|
222
|
+
* would report a still-live entry as already deleted.
|
|
223
|
+
*/
|
|
224
|
+
const certifiedDeleteFloor = (c) => Math.min(logDeleteFloorOf(c), logSeqStartOf(c));
|
|
225
|
+
const encodeJson = (json) => encodeJsonBytes(json);
|
|
226
|
+
/**
|
|
227
|
+
* Runtime guard for `parsed` to be a {@link CurrentJson}. Throws
|
|
228
|
+
* `BaerlyError{code:"InvalidResponse"}` rather than coercing. Tolerant
|
|
229
|
+
* reader: unknown keys ignored, new required fields bump
|
|
230
|
+
* `schema_version` (move (b), ADR-003).
|
|
231
|
+
*/
|
|
232
|
+
const assertCurrentJson = (parsed, key) => {
|
|
233
|
+
if (parsed === null || typeof parsed !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: parsed body is not an object`);
|
|
234
|
+
const r = parsed;
|
|
235
|
+
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 release before 0.3.0; this release requires schema v3. Dump/restore with that release, or re-provision local scratch data.`);
|
|
236
|
+
if (r["schema_version"] !== 3) {
|
|
237
|
+
const base = unsupportedSchemaVersionMessage(`current.json at ${key}`, r["schema_version"], 3);
|
|
238
|
+
throw new BaerlyError("InvalidResponse", isNewerSchemaVersion(r["schema_version"], 3) ? base : `${base} For local dev only, stale data from another build can be cleared by deleting the local data directory (e.g. \`rm -rf .baerly-data\`).`);
|
|
239
|
+
}
|
|
240
|
+
if (!(typeof r["snapshot"] === "string" || r["snapshot"] === null)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: snapshot must be string|null`);
|
|
241
|
+
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`);
|
|
242
|
+
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`);
|
|
243
|
+
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"])}`);
|
|
244
|
+
const fence = r["writer_fence"];
|
|
245
|
+
if (fence === null || typeof fence !== "object") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence missing`);
|
|
246
|
+
const f = fence;
|
|
247
|
+
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`);
|
|
248
|
+
if (typeof f["owner"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.owner must be a string`);
|
|
249
|
+
if (typeof f["claimed_at"] !== "string") throw new BaerlyError("InvalidResponse", `current.json at ${key}: writer_fence.claimed_at must be a string`);
|
|
250
|
+
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`);
|
|
251
|
+
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`);
|
|
252
|
+
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`);
|
|
253
|
+
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`);
|
|
254
|
+
if (r["log_delete_floor"] !== void 0 && (typeof r["log_delete_floor"] !== "number" || !Number.isInteger(r["log_delete_floor"]) || r["log_delete_floor"] < 0)) throw new BaerlyError("InvalidResponse", `current.json at ${key}: log_delete_floor must be a non-negative integer if present`);
|
|
255
|
+
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`);
|
|
256
|
+
if (r["generation"] !== void 0 && (typeof r["generation"] !== "string" || !GENERATION_RE.test(r["generation"]))) throw new BaerlyError("InvalidResponse", `current.json at ${key}: generation must be a non-empty lowercase-hex string if present`);
|
|
257
|
+
return parsed;
|
|
258
|
+
};
|
|
259
|
+
/**
|
|
260
|
+
* Wrap a storage-level error with `current.json at <key>` location
|
|
261
|
+
* context. `WriteConflict` (the storage layer's CAS-lost signal) is
|
|
262
|
+
* re-thrown with an annotated message; other `BaerlyError`s pass
|
|
263
|
+
* through; non-`BaerlyError` falls through as `InvalidResponse` (in
|
|
264
|
+
* practice unreachable — every in-tree `Storage` impl wraps).
|
|
265
|
+
*/
|
|
266
|
+
const translateCasError = (e, key) => {
|
|
267
|
+
if (isWriteConflict(e)) return new BaerlyError("WriteConflict", `current.json CAS lost at ${key}: ${e.message}`, { cause: e });
|
|
268
|
+
if (e instanceof BaerlyError) return e;
|
|
269
|
+
return new BaerlyError("InvalidResponse", `current.json write at ${key} failed: ${String(e)}`, { cause: e });
|
|
270
|
+
};
|
|
271
|
+
// packages/server/src/names.ts
|
|
272
|
+
/** Reject names in the system-reserved leading-"_" namespace. See docs/adr/003-layout-versioning-cordon.md. */
|
|
273
|
+
const assertNameNotReserved = (name, context) => {
|
|
274
|
+
if (name.startsWith("_")) throw new BaerlyError("InvalidConfig", `${context}: "${name}" is reserved — names beginning with "_" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`);
|
|
275
|
+
};
|
|
276
|
+
const utf8 = new TextEncoder();
|
|
277
|
+
const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/;
|
|
278
|
+
/**
|
|
279
|
+
* The single validation rule for every caller-controlled key segment
|
|
280
|
+
* (`_id`, `collection`, `app`, `tenant`) before it becomes a written
|
|
281
|
+
* key segment or `LocalFsStorage` path. Rejects empty / `"/"` /
|
|
282
|
+
* `"."`|`".."` / C0-C1 control / leading `"_"` (ADR-003) / `> MAX_SEGMENT_BYTES`,
|
|
283
|
+
* all as `BaerlyError{code:"InvalidConfig"}`.
|
|
284
|
+
*
|
|
285
|
+
* @param role human label for the segment ("_id" | "collection" | "app" | "tenant").
|
|
286
|
+
* @param verb optional calling-context label for the message.
|
|
287
|
+
*/
|
|
288
|
+
const assertPathSegment = (value, role, verb = "") => {
|
|
289
|
+
const where = verb === "" ? role : `${verb}: ${role}`;
|
|
290
|
+
if (value.length === 0) throw new BaerlyError("InvalidConfig", `${where} must be a non-empty string`);
|
|
291
|
+
if (value.includes("/")) throw new BaerlyError("InvalidConfig", `${where} may not contain "/": ${JSON.stringify(value)}`);
|
|
292
|
+
if (value === "." || value === "..") throw new BaerlyError("InvalidConfig", `${where} may not be "." or "..": ${JSON.stringify(value)}`);
|
|
293
|
+
if (CONTROL_CHARS.test(value)) throw new BaerlyError("InvalidConfig", `${where} may not contain control characters`);
|
|
294
|
+
if (utf8.encode(value).length > 256) throw new BaerlyError("InvalidConfig", `${where} is too long (> 256 bytes)`);
|
|
295
|
+
assertNameNotReserved(value, where);
|
|
296
|
+
};
|
|
297
|
+
/**
|
|
298
|
+
* Resolution for a non-NFC app, tenant, or collection name. Data an
|
|
299
|
+
* earlier release stored under one stays readable through the operator
|
|
300
|
+
* CLI, and is migrated by export and restore under a new name.
|
|
301
|
+
*/
|
|
302
|
+
const NAME_NFC_RESOLUTION = "Pass name.normalize(\"NFC\") for a new app, tenant, or collection name. The SDK refuses non-NFC names. Export legacy data with `baerly admin dump` and restore it with `baerly admin restore` under an NFC name that is not canonically equivalent to the original. The normalized original name is not a safe target, because R2 stores canonically-equivalent keys as one object.";
|
|
303
|
+
/**
|
|
304
|
+
* Require `value` to be in Unicode Normalization Form C
|
|
305
|
+
* (`value === value.normalize("NFC")`). R2 stores canonically-equivalent
|
|
306
|
+
* keys (NFC `é` and NFD `e` + U+0301) as one object, so two segments that
|
|
307
|
+
* differ only by normalization would address the same objects there. NFC
|
|
308
|
+
* gives each equivalence class one spelling. Case and compatibility
|
|
309
|
+
* variants (`A` / `a`, `fi` / `fi`) are distinct NFC strings and stay
|
|
310
|
+
* distinct. Shared by the `_id` write guard and {@link assertNameSegment}.
|
|
311
|
+
*
|
|
312
|
+
* @param resolution the `BaerlyError.resolution` for this segment's role.
|
|
313
|
+
* @throws BaerlyError code="InvalidConfig" — `value` is not NFC.
|
|
314
|
+
*/
|
|
315
|
+
const assertNfcSegment = (value, role, verb, resolution) => {
|
|
316
|
+
if (value !== value.normalize("NFC")) {
|
|
317
|
+
const where = verb === "" ? role : `${verb}: ${role}`;
|
|
318
|
+
throw new BaerlyError("InvalidConfig", `${where} must be in Unicode Normalization Form C: ${JSON.stringify(value)}`, { resolution });
|
|
319
|
+
}
|
|
320
|
+
};
|
|
321
|
+
/**
|
|
322
|
+
* Resolution for an app, tenant, or collection name with an unpaired
|
|
323
|
+
* surrogate.
|
|
324
|
+
*/
|
|
325
|
+
const NAME_WELL_FORMED_RESOLUTION = "Pass a name with no unpaired UTF-16 surrogate (name.isWellFormed() is true). One usually comes from slicing a string between the two halves of an emoji or other astral character; slice by code point instead.";
|
|
326
|
+
/**
|
|
327
|
+
* Require `value` to be well-formed UTF-16 (`value.isWellFormed()`): no
|
|
328
|
+
* unpaired surrogate. `encodeURIComponent` throws on one and UTF-8 has no
|
|
329
|
+
* encoding for one, so such a segment can be neither addressed over HTTP
|
|
330
|
+
* nor stored as an S3, GCS, or local-fs key. Shared by the `_id` write
|
|
331
|
+
* guard and {@link assertNameSegment}.
|
|
332
|
+
*
|
|
333
|
+
* @param resolution the `BaerlyError.resolution` for this segment's role.
|
|
334
|
+
* @throws BaerlyError code="InvalidConfig" — `value` holds an unpaired
|
|
335
|
+
* surrogate.
|
|
336
|
+
*/
|
|
337
|
+
const assertWellFormedSegment = (value, role, verb, resolution) => {
|
|
338
|
+
if (!value.isWellFormed()) {
|
|
339
|
+
const where = verb === "" ? role : `${verb}: ${role}`;
|
|
340
|
+
throw new BaerlyError("InvalidConfig", `${where} may not contain an unpaired UTF-16 surrogate: ${JSON.stringify(value)}`, { resolution });
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
/**
|
|
344
|
+
* Guard an app, tenant, or collection name that the SDK, the HTTP
|
|
345
|
+
* router, or a writing CLI verb addresses: {@link assertPathSegment},
|
|
346
|
+
* then {@link assertWellFormedSegment}, then {@link assertNfcSegment}. Names are never normalized on the
|
|
347
|
+
* caller's behalf, so two canonically-equivalent names are never merged
|
|
348
|
+
* into one. The read-only CLI verbs (`inspect`, `export`, `cost`,
|
|
349
|
+
* `admin dump`, `admin fsck`, `admin usage`) apply only
|
|
350
|
+
* {@link assertPathSegment}, which keeps a legacy non-NFC name readable
|
|
351
|
+
* and exportable.
|
|
352
|
+
*
|
|
353
|
+
* @throws BaerlyError code="InvalidConfig" — the name breaks the
|
|
354
|
+
* key-segment rule, holds an unpaired surrogate, or is not NFC.
|
|
355
|
+
*/
|
|
356
|
+
const assertNameSegment = (value, role, verb = "") => {
|
|
357
|
+
assertPathSegment(value, role, verb);
|
|
358
|
+
assertWellFormedSegment(value, role, verb, NAME_WELL_FORMED_RESOLUTION);
|
|
359
|
+
assertNfcSegment(value, role, verb, NAME_NFC_RESOLUTION);
|
|
360
|
+
};
|
|
361
|
+
export { assertNameNotReserved as a, certifiedDeleteFloor as c, logSeqStartOf as d, mintGeneration as f, encodeJsonBytes as g, decodeJsonBytes as h, assertWellFormedSegment as i, createCurrentJson as l, unsupportedSchemaVersionMessage as m, assertNfcSegment as n, assertCurrentJsonTransition as o, readCurrentJson as p, assertPathSegment as r, casUpdateCurrentJson as s, assertNameSegment as t, logDeleteFloorOf as u };
|
|
362
|
+
|
|
363
|
+
//# sourceMappingURL=path-segment-DBXG26PW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"path-segment-DBXG26PW.js","names":["utf8Decoder"],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/coordination/schema-version.ts","../packages/protocol/src/coordination/current-json.ts","../packages/server/src/names.ts","../packages/server/src/path-segment.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — the common JSON payload encoder/decoder for\n * log entries, snapshots, current.json, and other protocol payloads.\n */\n\nconst utf8Encoder = new TextEncoder();\n// Default options only: no `fatal`, no `ignoreBOM`, never `stream: true`, so the\n// decoder holds no state between calls and strips a leading BOM as before.\nconst utf8Decoder = new TextDecoder();\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n utf8Encoder.encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(utf8Decoder.decode(bytes)) as T;\n","/**\n * Whether `found` is an integer version above `supported`, i.e. an\n * object a newer release wrote. The one predicate behind every\n * \"newer\" decision, so a reader's message and its extra hints agree.\n */\nexport const isNewerSchemaVersion = (found: unknown, supported: number): found is number =>\n typeof found === \"number\" && Number.isInteger(found) && found > supported;\n\n/**\n * Message for a durable object whose `schema_version` this build does not\n * read. A larger integer was written by a newer release; anything else is\n * not an object this build wrote. States both versions and an app remedy;\n * never names host settings or suggests deleting data.\n */\nexport const unsupportedSchemaVersionMessage = (\n where: string,\n found: unknown,\n supported: number,\n): string =>\n isNewerSchemaVersion(found, supported)\n ? `${where}: schema_version ${found} was written by a newer baerly-storage release; this build supports schema_version ${supported}. Run that release or newer.`\n : `${where}: unsupported schema_version ${String(found)}; this build supports schema_version ${supported}. This object was not written by this build; restore it from a backup made by this release, or point the app at the right data.`;\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 assertCurrentJsonTransition} — shared before/after admission\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"WriteConflict\"}`. 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, isWriteConflict } from \"../errors.ts\";\nimport { isNewerSchemaVersion, unsupportedSchemaVersionMessage } from \"./schema-version.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n// Default options only (no `stream`), so no state carries between calls.\nconst utf8Decoder = new TextDecoder();\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:\n * - `0 <= log_seq_start <= tail_hint`\n * - `log_seq_start` advances monotonically (never decreases).\n * {@link assertCurrentJsonTransition} rejects a writer that lowers\n * it; `baerly admin restore\n * --force` is the deliberate truncate exemption.\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`) — except after a `--force`\n * truncate, which resets `snapshot` to `null` while reseeding\n * the floor above any surviving old-generation log object.\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 → the\n * collection has never warned, so its first deferral warns.\n */\n last_warned_seq?: number;\n\n /**\n * The exclusive upper bound of the contiguous log prefix certified\n * deleted. Every `log/<seq>.json` with `seq < log_delete_floor` is\n * gone from the bucket. Distinct from {@link log_seq_start}, which is the\n * lowest sequence a READER may need: the gap between them is the\n * deliberately-retained window (`LOG_RETENTION_SEQ_WINDOW`), a rate\n * limit on retirement that keeps folded entries readable for a windowed\n * commit below the floor, not the writer-retry window that\n * `GC_GRACE_PERIOD_MILLIS` covers.\n *\n * A FLOOR, not a rotation cursor. The deletable set is a contiguous\n * range over integer `seq` order that only ever grows at one end, so\n * this never wraps and never re-scans — which is why retiring stale\n * logs needs no LIST and no `gc/pending.json` entry. The window is\n * **not** a paused-writer fence — it bounds no wall-clock and no\n * commit count. The commit-path check closes that schedule instead.\n *\n * Optional because it postdates `schema_version: 3`. Absent is a\n * well-defined state meaning \"no deleted prefix is certified\" and\n * decodes to `0` via {@link logDeleteFloorOf}; a bucket written by an\n * earlier build simply starts its first retention pass from the bottom\n * of the keyspace.\n *\n * Invariants:\n * - advances monotonically (never decreases)\n * - `0 <= log_delete_floor <= log_seq_start`\n *\n * Both are transition-scoped and enforced in\n * {@link assertCurrentJsonTransition}. The single-state guard checks\n * shape only, so a retirement pass must clamp against\n * {@link log_seq_start} rather than trust this value.\n */\n log_delete_floor?: number;\n\n /**\n * Opaque non-empty generation nonce, re-minted by every writer that\n * *replaces* this collection rather than advancing it — the two\n * `baerly admin restore` seeds and the writer/dev auto-provision\n * paths. Steady-state writers (the compactor's fold CAS,\n * every {@link casUpdateCurrentJson} mutator)\n * carry it through untouched, so it changes only on truncate or\n * re-provision. Mint with {@link mintGeneration}.\n *\n * `/v1/since` pairs it with each entry's `lsn` to build the cursor it\n * hands clients, then rejects a resume whose generation no longer\n * matches. Without it, a `restore --force` that reseeds\n * `log_seq_start` BELOW the old floor (the deliberate floor exemption\n * — invariant 12 in `docs/spec/sync-protocol.md`) lets a pre-restore\n * cursor clear the `cursorSeq < log_seq_start` gate and silently skip\n * every restored row beneath it.\n *\n * Deliberately NOT `writer_fence.epoch`: the fresh-target restore\n * branch seeds `epoch: 0`, so a truncate-to-empty is indistinguishable\n * from a genuine epoch-0 collection. A counter that resets cannot\n * discriminate generations; a nonce can.\n *\n * Optional because it postdates `schema_version: 3` and buckets\n * written by earlier builds do not carry it. Absent is a well-defined\n * state, not a degraded one — it decodes to `NO_GENERATION` on both\n * sides of the comparison (see `../cursor.ts`), so a collection that\n * was never truncated keeps resuming normally.\n */\n generation?: string;\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 an informational claim-time string that\n * writers seed as `\"\"` and carry through unchanged; `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. No production path bumps or\n * verifies it; it is seeded at provisioning/restore and carried\n * through every transition.\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 * Informational claim time as an ISO-8601 string. No production\n * path stamps it: writers seed `\"\"` and carry it through. The empty\n * string means \"claim time unknown\" — readers MUST treat it as such\n * rather than parsing it, and MUST NOT derive safety from 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 = utf8Decoder.decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: body is not valid JSON`, {\n cause: error,\n });\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Mint a fresh {@link CurrentJson.generation} nonce.\n *\n * Twelve lowercase hex characters (≈2.8 × 10¹⁴ values) — sized so the\n * birthday bound is unreachable across the truncates a bucket sees in\n * its lifetime, while costing only twelve bytes on every `/v1/since`\n * response. A collision would let a stale cursor resume into a\n * truncated generation, which is the exact failure this field exists to\n * prevent, so the margin is deliberate.\n *\n * `crypto.randomUUID` is universally available (Node 19+, Workerd, Bun,\n * browsers) — the same source `uuid()` in `../types.ts` uses.\n *\n * Call this only where a collection is REPLACED, never where one is\n * advanced; see {@link CurrentJson.generation} for the writer split.\n */\nexport const mintGeneration = (): string => crypto.randomUUID().replaceAll(\"-\", \"\").slice(0, 12);\n\n/**\n * The charset {@link mintGeneration} emits and `/v1/since` accepts in\n * the generation half of a cursor. Pinned so the manifest validator\n * and the wire validator cannot drift.\n */\nconst GENERATION_RE = /^[0-9a-f]+$/;\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:\"WriteConflict\"} — 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 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 * Admission control for a `current.json` state transition.\n *\n * Distinct from {@link assertCurrentJson}, which validates one state in\n * isolation and therefore structurally cannot express a rule about a\n * pair of states. Every invariant that compares before/after belongs\n * here, and every writer that bypasses {@link casUpdateCurrentJson}\n * MUST call it directly — \"monotone by construction\" is an argument\n * that has to be re-made every time the writer is reimplemented, and\n * it does not survive a chunk-aware compactor or a read-banking path.\n *\n * `Internal`, not `InvalidResponse`: the fault is a local caller's\n * mutator, not a malformed storage response, and `InvalidResponse` maps\n * to HTTP 502 (\"storage upstream failed\"), which would misattribute a\n * programmer error to the bucket.\n *\n * @throws BaerlyError{code:\"Internal\"} on any violated transition rule.\n * @see docs/spec/sync-protocol.md invariant 12\n */\nexport const assertCurrentJsonTransition = (\n before: CurrentJson,\n after: CurrentJson,\n key: string,\n): void => {\n // A regressed floor makes a stale pre-fold reader cursor pass the\n // `cursorSeq < log_seq_start` re-bootstrap check (http/since.ts)\n // instead of failing it. Equality is permitted: the `tail_hint`\n // refresh and the `last_warned_seq` stamp in maintenance.ts both hold\n // the floor fixed.\n if (after.log_seq_start < before.log_seq_start) {\n throw new BaerlyError(\n \"Internal\",\n `current.json at ${key}: log_seq_start must not decrease (${String(before.log_seq_start)} → ${String(after.log_seq_start)})`,\n );\n }\n // Same argument one floor down, and read through the accessor on BOTH\n // sides: absent means \"no deleted prefix is certified\", so a pre-field\n // manifest compares as 0 rather than as `undefined`.\n const beforeDeleteFloor = logDeleteFloorOf(before);\n const afterDeleteFloor = logDeleteFloorOf(after);\n if (afterDeleteFloor < beforeDeleteFloor) {\n throw new BaerlyError(\n \"Internal\",\n `current.json at ${key}: log_delete_floor must not decrease (${String(beforeDeleteFloor)} → ${String(afterDeleteFloor)})`,\n );\n }\n // Deleting at or above the live floor would remove an object a reader\n // walking `[log_seq_start, tail_hint)` still needs. This is the hard\n // safety line for both maintenance triggers.\n if (afterDeleteFloor > after.log_seq_start) {\n throw new BaerlyError(\n \"Internal\",\n `current.json at ${key}: log_delete_floor must not exceed log_seq_start (${String(afterDeleteFloor)} > ${String(after.log_seq_start)})`,\n );\n }\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:\"WriteConflict\"} — 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 * @throws BaerlyError{code:\"Internal\"} — the mutator decreased\n * `log_seq_start`, decreased `log_delete_floor`, or set\n * `log_delete_floor > log_seq_start`. Equality is permitted.\n * The compactor calls the same transition validator before its\n * direct `If-Match` PUT; `baerly admin restore --force` is the\n * deliberate truncate exemption.\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 assertCurrentJsonTransition(existing.json, 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 * 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 * Read `log_delete_floor`, defaulting an absent field to `0`. Absent\n * means \"no deleted prefix is certified\", which is exactly what a\n * pre-field bucket records even if older GC deleted sparse log objects.\n */\nexport const logDeleteFloorOf = (c: CurrentJson): number => c.log_delete_floor ?? 0;\n\n/**\n * The certified delete floor: `log_delete_floor` clamped down to\n * `log_seq_start`. Every consumer of \"is `seq` reclaimed\" must go through\n * this clamp rather than trusting the raw stored field — invariant 12\n * (`docs/spec/sync-protocol.md`) allows an out-of-bound stored floor to be\n * readable off disk (the single-state read guard deliberately doesn't\n * reject it, so `admin restore` stays repairable), and an unclamped floor\n * would report a still-live entry as already deleted.\n */\nexport const certifiedDeleteFloor = (c: CurrentJson): number =>\n Math.min(logDeleteFloorOf(c), logSeqStartOf(c));\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 release before 0.3.0; this release requires schema v${CURRENT_JSON_SCHEMA_VERSION}. Dump/restore with that release, or re-provision local scratch data.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n const base = unsupportedSchemaVersionMessage(\n `current.json at ${key}`,\n r[\"schema_version\"],\n CURRENT_JSON_SCHEMA_VERSION,\n );\n throw new BaerlyError(\n \"InvalidResponse\",\n isNewerSchemaVersion(r[\"schema_version\"], CURRENT_JSON_SCHEMA_VERSION)\n ? base\n : `${base} For local dev only, stale data from another build can be cleared by deleting the local data directory (e.g. \\`rm -rf .baerly-data\\`).`,\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: same rationale as `log_seq_start` above.\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: same rationale as `log_seq_start` above.\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: same rationale as `log_seq_start` above.\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: same rationale as `log_seq_start` above.\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 // Shape only. `log_delete_floor <= log_seq_start` is deliberately NOT\n // checked here: `readCurrentJson` sits on `admin restore`'s own path\n // (it reads `head` before it can reseed), so rejecting a single state\n // on that bound would turn an out-of-bound floor into a bucket with no\n // in-product repair path. The bound is transition-scoped in\n // {@link assertCurrentJsonTransition}, and consumers of the field\n // clamp against `log_seq_start` rather than trust it.\n if (\n r[\"log_delete_floor\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\n (typeof r[\"log_delete_floor\"] !== \"number\" ||\n !Number.isInteger(r[\"log_delete_floor\"]) ||\n r[\"log_delete_floor\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_delete_floor must be a non-negative integer if present`,\n );\n }\n if (\n r[\"mean_entry_bytes\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: same rationale as `log_seq_start` above.\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 if (\n r[\"generation\"] !== undefined &&\n (typeof r[\"generation\"] !== \"string\" || !GENERATION_RE.test(r[\"generation\"]))\n ) {\n // Charset, not just type. `\"\"` would format a cursor as `.<lsn>`,\n // which `parseCursor` reads as generation `\"\"` rather than as the\n // `NO_GENERATION` sentinel. Anything outside `[0-9a-f]` (a `.`\n // worst of all) would mint a cursor `/v1/since` then refuses on\n // resume — the server rejecting a token it issued, which a client\n // reads as a permanently dead cursor. Matching the wire charset\n // means a manifest that reads clean here always round-trips.\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: generation must be a non-empty lowercase-hex string 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. `WriteConflict` (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 (isWriteConflict(e)) {\n return new BaerlyError(\"WriteConflict\", `current.json CAS lost at ${key}: ${e.message}`, {\n cause: e,\n });\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, {\n cause: e,\n });\n};\n","import { BaerlyError } from \"@baerly/protocol\";\n\n/** Reject names in the system-reserved leading-\"_\" namespace. See docs/adr/003-layout-versioning-cordon.md. */\nexport const assertNameNotReserved = (name: string, context: string): void => {\n if (name.startsWith(\"_\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${context}: \"${name}\" is reserved — names beginning with \"_\" are reserved for system use. See docs/adr/003-layout-versioning-cordon.md.`,\n );\n }\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { assertNameNotReserved } from \"./names.ts\";\n\n/**\n * Per-segment byte ceiling. S3 and R2 cap a full object key at 1024\n * UTF-8 bytes; a key is several segments, so this 256 leaves real prefix\n * headroom. The assembled multi-segment key sum is bounded separately on\n * the write path, not here. This is an intentional server-local *policy*\n * value (not the protocol-level S3/R2 fact `MAX_KEY_BYTES = 1024` in\n * `@baerly/protocol`'s `constants.ts`); it lives here, co-located with the\n * one rule that uses it, to keep `protocol/constants.ts` out of the\n * validator's bundle closure.\n */\nexport const MAX_SEGMENT_BYTES = 256;\nconst utf8 = new TextEncoder();\n// C0 (U+0000-U+001F) + DEL/C1 (U+007F-U+009F).\n// eslint-disable-next-line no-control-regex -- intentional control-char class\nconst CONTROL_CHARS = /[\\u0000-\\u001f\\u007f-\\u009f]/;\n\n/**\n * The single validation rule for every caller-controlled key segment\n * (`_id`, `collection`, `app`, `tenant`) before it becomes a written\n * key segment or `LocalFsStorage` path. Rejects empty / `\"/\"` /\n * `\".\"`|`\"..\"` / C0-C1 control / leading `\"_\"` (ADR-003) / `> MAX_SEGMENT_BYTES`,\n * all as `BaerlyError{code:\"InvalidConfig\"}`.\n *\n * @param role human label for the segment (\"_id\" | \"collection\" | \"app\" | \"tenant\").\n * @param verb optional calling-context label for the message.\n */\nexport const assertPathSegment = (value: string, role: string, verb = \"\"): void => {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n if (value.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", `${where} must be a non-empty string`);\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not contain \"/\": ${JSON.stringify(value)}`,\n );\n }\n if (value === \".\" || value === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not be \".\" or \"..\": ${JSON.stringify(value)}`,\n );\n }\n if (CONTROL_CHARS.test(value)) {\n throw new BaerlyError(\"InvalidConfig\", `${where} may not contain control characters`);\n }\n if (utf8.encode(value).length > MAX_SEGMENT_BYTES) {\n throw new BaerlyError(\"InvalidConfig\", `${where} is too long (> ${MAX_SEGMENT_BYTES} bytes)`);\n }\n // Leading `_` is the ADR-003 reserved namespace.\n assertNameNotReserved(value, where);\n};\n\n/**\n * Resolution for a non-NFC app, tenant, or collection name. Data an\n * earlier release stored under one stays readable through the operator\n * CLI, and is migrated by export and restore under a new name.\n */\nconst NAME_NFC_RESOLUTION =\n 'Pass name.normalize(\"NFC\") for a new app, tenant, or collection name. The SDK refuses non-NFC names. Export legacy data with `baerly admin dump` and restore it with `baerly admin restore` under an NFC name that is not canonically equivalent to the original. The normalized original name is not a safe target, because R2 stores canonically-equivalent keys as one object.';\n\n/**\n * Require `value` to be in Unicode Normalization Form C\n * (`value === value.normalize(\"NFC\")`). R2 stores canonically-equivalent\n * keys (NFC `é` and NFD `e` + U+0301) as one object, so two segments that\n * differ only by normalization would address the same objects there. NFC\n * gives each equivalence class one spelling. Case and compatibility\n * variants (`A` / `a`, `fi` / `fi`) are distinct NFC strings and stay\n * distinct. Shared by the `_id` write guard and {@link assertNameSegment}.\n *\n * @param resolution the `BaerlyError.resolution` for this segment's role.\n * @throws BaerlyError code=\"InvalidConfig\" — `value` is not NFC.\n */\nexport const assertNfcSegment = (\n value: string,\n role: string,\n verb: string,\n resolution: string,\n): void => {\n if (value !== value.normalize(\"NFC\")) {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} must be in Unicode Normalization Form C: ${JSON.stringify(value)}`,\n { resolution },\n );\n }\n};\n\n/**\n * Resolution for an app, tenant, or collection name with an unpaired\n * surrogate.\n */\nconst NAME_WELL_FORMED_RESOLUTION =\n \"Pass a name with no unpaired UTF-16 surrogate (name.isWellFormed() is true). One usually comes from slicing a string between the two halves of an emoji or other astral character; slice by code point instead.\";\n\n/**\n * Require `value` to be well-formed UTF-16 (`value.isWellFormed()`): no\n * unpaired surrogate. `encodeURIComponent` throws on one and UTF-8 has no\n * encoding for one, so such a segment can be neither addressed over HTTP\n * nor stored as an S3, GCS, or local-fs key. Shared by the `_id` write\n * guard and {@link assertNameSegment}.\n *\n * @param resolution the `BaerlyError.resolution` for this segment's role.\n * @throws BaerlyError code=\"InvalidConfig\" — `value` holds an unpaired\n * surrogate.\n */\nexport const assertWellFormedSegment = (\n value: string,\n role: string,\n verb: string,\n resolution: string,\n): void => {\n if (!value.isWellFormed()) {\n const where = verb === \"\" ? role : `${verb}: ${role}`;\n throw new BaerlyError(\n \"InvalidConfig\",\n `${where} may not contain an unpaired UTF-16 surrogate: ${JSON.stringify(value)}`,\n { resolution },\n );\n }\n};\n\n/**\n * Guard an app, tenant, or collection name that the SDK, the HTTP\n * router, or a writing CLI verb addresses: {@link assertPathSegment},\n * then {@link assertWellFormedSegment}, then {@link assertNfcSegment}. Names are never normalized on the\n * caller's behalf, so two canonically-equivalent names are never merged\n * into one. The read-only CLI verbs (`inspect`, `export`, `cost`,\n * `admin dump`, `admin fsck`, `admin usage`) apply only\n * {@link assertPathSegment}, which keeps a legacy non-NFC name readable\n * and exportable.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — the name breaks the\n * key-segment rule, holds an unpaired surrogate, or is not NFC.\n */\nexport const assertNameSegment = (value: string, role: string, verb = \"\"): void => {\n assertPathSegment(value, role, verb);\n assertWellFormedSegment(value, role, verb, NAME_WELL_FORMED_RESOLUTION);\n assertNfcSegment(value, role, verb, NAME_NFC_RESOLUTION);\n};\n"],"mappings":";;;;;;;AAKA,MAAM,cAAc,IAAI,YAAY;AAGpC,MAAMA,gBAAc,IAAI,YAAY;AAEpC,MAAa,mBAAmB,UAC9B,YAAY,OAAO,KAAK,UAAU,KAAK,CAAC;AAE1C,MAAa,mBAAgC,UAC3C,KAAK,MAAMA,cAAY,OAAO,KAAK,CAAC;;;;;;;ACTtC,MAAa,wBAAwB,OAAgB,cACnD,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,QAAQ;;;;;;;AAQlE,MAAa,mCACX,OACA,OACA,cAEA,qBAAqB,OAAO,SAAS,IACjC,GAAG,MAAM,mBAAmB,MAAM,qFAAqF,UAAU,gCACjI,GAAG,MAAM,+BAA+B,OAAO,KAAK,EAAE,uCAAuC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACa7G,MAAM,cAAc,IAAI,YAAY;;;;;;;;AAmOpC,eAAsB,gBACpB,SACA,KACA,MACiC;CACjC,MAAM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AAMA,MAAM,8BACJ;;;;;;;;;;;;AAaF,MAAa,2BACX,OACA,MACA,MACA,eACS;CACT,IAAI,CAAC,MAAM,aAAa,GAAG;EACzB,MAAM,QAAQ,SAAS,KAAK,OAAO,GAAG,KAAK,IAAI;EAC/C,MAAM,IAAI,YACR,iBACA,GAAG,MAAM,iDAAiD,KAAK,UAAU,KAAK,KAC9E,EAAE,WAAW,CACf;CACF;AACF;;;;;;;;;;;;;;AAeA,MAAa,qBAAqB,OAAe,MAAc,OAAO,OAAa;CACjF,kBAAkB,OAAO,MAAM,IAAI;CACnC,wBAAwB,OAAO,MAAM,MAAM,2BAA2B;CACtE,iBAAiB,OAAO,MAAM,MAAM,mBAAmB;AACzD"}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { s as BaerlyError } from "./baerly.js";
|
|
2
|
+
import { c as readCurrentJson } from "./current-json-CC6lE4Aj.js";
|
|
3
|
+
import { i as isOwnCollection, n as loadSnapshotAsMap } from "./snapshot-CknzkDM0.js";
|
|
4
|
+
import { r as probeTailFrom } from "./log-tail-DWJbneBF.js";
|
|
5
|
+
import { t as walkLogRange } from "./log-walk-C-vA-WGJ.js";
|
|
6
|
+
// src/export/sql-escape.ts
|
|
4
7
|
/**
|
|
5
8
|
* Quote an SQL identifier (table or column name) per the target's
|
|
6
9
|
* lexical rules. All three targets accept double-quoted identifiers
|
|
@@ -41,16 +44,16 @@ const quoteValue = (value, target) => {
|
|
|
41
44
|
}
|
|
42
45
|
throw new BaerlyError("SchemaError", `quoteValue: nested-object reached the quoter without pre-encoding — caller bug`);
|
|
43
46
|
};
|
|
44
|
-
|
|
45
|
-
//#region src/export/plan.ts
|
|
47
|
+
// src/export/plan.ts
|
|
46
48
|
const INT32_MIN = -(2 ** 31);
|
|
47
49
|
const INT32_MAX = 2 ** 31 - 1;
|
|
48
50
|
const observe = (obs, value) => {
|
|
49
51
|
if (typeof value === "string") obs.hasString = true;
|
|
50
52
|
else if (typeof value === "boolean") obs.hasBoolean = true;
|
|
51
|
-
else if (typeof value === "number")
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
else if (typeof value === "number") {
|
|
54
|
+
if (Number.isInteger(value) && value >= INT32_MIN && value <= INT32_MAX) obs.hasInteger = true;
|
|
55
|
+
else obs.hasNonInteger = true;
|
|
56
|
+
} else if (value !== null && typeof value === "object") obs.hasNestedObject = true;
|
|
54
57
|
};
|
|
55
58
|
const pickSqlType = (obs, target) => {
|
|
56
59
|
if (obs.hasNestedObject) {
|
|
@@ -200,6 +203,12 @@ const inferPlanForCollection = (params) => {
|
|
|
200
203
|
* provisioned). Returns an empty map when the collection is
|
|
201
204
|
* provisioned but holds no rows (every doc tombstoned, or no
|
|
202
205
|
* inserts yet).
|
|
206
|
+
*
|
|
207
|
+
* `recoverLegacyNames` selects only byte-identical collection names in
|
|
208
|
+
* a mixed legacy log. Snapshot identity and integrity checks remain
|
|
209
|
+
* strict: a snapshot for the other spelling cannot establish this
|
|
210
|
+
* collection's base state. Recovery never reconstructs rows an earlier
|
|
211
|
+
* compaction discarded.
|
|
203
212
|
*/
|
|
204
213
|
const loadMaterialisedView = async (params) => {
|
|
205
214
|
const { storage, currentJsonKey, collection } = params;
|
|
@@ -212,7 +221,7 @@ const loadMaterialisedView = async (params) => {
|
|
|
212
221
|
const strict = await walkLogRange(storage, collectionPrefix, logSeqStart, hint);
|
|
213
222
|
const probe = await probeTailFrom(storage, collectionPrefix, Math.max(logSeqStart, hint), params.signal !== void 0 ? { signal: params.signal } : void 0);
|
|
214
223
|
for (const entry of [...strict, ...probe.entries]) {
|
|
215
|
-
if (entry.collection
|
|
224
|
+
if (!(params.recoverLegacyNames === true ? entry.collection === collection : isOwnCollection(entry.collection, collection))) continue;
|
|
216
225
|
if (entry.doc_id === void 0) continue;
|
|
217
226
|
if (entry.op === "I" || entry.op === "U") {
|
|
218
227
|
if (entry.after !== void 0) base.set(entry.doc_id, entry.after);
|
|
@@ -220,7 +229,6 @@ const loadMaterialisedView = async (params) => {
|
|
|
220
229
|
}
|
|
221
230
|
return base;
|
|
222
231
|
};
|
|
223
|
-
//#endregion
|
|
224
232
|
export { loadMaterialisedView as n, quoteValue as r, inferPlanForCollection as t };
|
|
225
233
|
|
|
226
|
-
//# sourceMappingURL=plan-
|
|
234
|
+
//# sourceMappingURL=plan-BvQbaNMe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plan-BvQbaNMe.js","names":[],"sources":["../packages/cli/src/export/sql-escape.ts","../packages/cli/src/export/plan.ts"],"sourcesContent":["import { BaerlyError, type DocumentValue } from \"@baerly/protocol\";\nimport type { SqlTarget } from \"./types.ts\";\n\n/**\n * Quote an SQL identifier (table or column name) per the target's\n * lexical rules. All three targets accept double-quoted identifiers\n * with embedded `\"\"` for a literal quote. SQLite and Postgres are\n * case-preserving inside double quotes; D1 (sqlite-flavoured)\n * matches.\n *\n * @throws BaerlyError code=\"SchemaError\" — name is empty or contains\n * a NUL byte.\n */\nexport const quoteIdentifier = (name: string, _target: SqlTarget): string => {\n if (name.length === 0) {\n throw new BaerlyError(\"SchemaError\", \"quoteIdentifier: empty identifier\");\n }\n if (name.includes(\"\\0\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `quoteIdentifier: NUL byte in identifier ${JSON.stringify(name)}`,\n );\n }\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n};\n\n/**\n * Quote a value for inline embedding in `INSERT INTO … VALUES (…)`.\n * Targets agree on `'…'` with doubled `''` for embedded apostrophes\n * and `NULL` for SQL null. JSONB / JSON-encoded text values are\n * passed in as JSON-stringified text by the caller; this function\n * sees them as plain strings.\n *\n * @throws BaerlyError code=\"SchemaError\" — value is an unsupported\n * shape (e.g. raw `undefined` from a missing-field, which\n * {@link emitInsertStatements} pre-filters into `NULL` before\n * calling this).\n */\nexport const quoteValue = (value: DocumentValue | null, target: SqlTarget): string => {\n if (value === null) {\n return \"NULL\";\n }\n if (typeof value === \"string\") {\n return `'${value.replace(/'/g, \"''\")}'`;\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"SchemaError\",\n `quoteValue: ${String(value)} is not finite — JSON doesn't survive round-trip`,\n );\n }\n return String(value);\n }\n if (typeof value === \"boolean\") {\n if (target === \"postgres\") {\n return value ? \"true\" : \"false\";\n }\n return value ? \"1\" : \"0\";\n }\n // Nested object: caller is responsible for setting the column's\n // `jsonEncoded` flag and pre-stringifying before reaching here.\n throw new BaerlyError(\n \"SchemaError\",\n `quoteValue: nested-object reached the quoter without pre-encoding — caller bug`,\n );\n};\n","import { BaerlyError, readCurrentJson, type DocumentValue, type Storage } from \"@baerly/protocol\";\nimport { loadSnapshotAsMap, probeTailFrom, walkLogRange } from \"@baerly/server/_internal/kernel\";\nimport { isOwnCollection } from \"@baerly/server/_internal/testing\";\nimport type { ColumnPlan, ExportPlan, ExportRow, SqlTarget, SqlType } from \"./types.ts\";\nimport { quoteIdentifier } from \"./sql-escape.ts\";\n\n/**\n * Worst-case observed shape for one column across all scanned rows.\n * Drives the {@link ColumnPlan.sqlType} pick in §3's table.\n */\ninterface ColumnObservation {\n hasString: boolean;\n hasBoolean: boolean;\n hasInteger: boolean;\n /** A floating number, OR an integer that doesn't fit 32-bit signed. */\n hasNonInteger: boolean;\n hasNestedObject: boolean;\n /** Any row missing this field → column is nullable. */\n hasNull: boolean;\n}\n\nconst INT32_MIN = -(2 ** 31);\nconst INT32_MAX = 2 ** 31 - 1;\n\nconst observe = (obs: ColumnObservation, value: DocumentValue): void => {\n if (typeof value === \"string\") {\n obs.hasString = true;\n } else if (typeof value === \"boolean\") {\n obs.hasBoolean = true;\n } else if (typeof value === \"number\") {\n if (Number.isInteger(value) && value >= INT32_MIN && value <= INT32_MAX) {\n obs.hasInteger = true;\n } else {\n obs.hasNonInteger = true;\n }\n } else if (value !== null && typeof value === \"object\") {\n obs.hasNestedObject = true;\n }\n};\n\nconst pickSqlType = (\n obs: ColumnObservation,\n target: SqlTarget,\n): { sqlType: SqlType; jsonEncoded: boolean } => {\n // Nested object present, in any combination → JSON.\n if (obs.hasNestedObject) {\n if (target === \"postgres\") {\n return { sqlType: \"jsonb\", jsonEncoded: true };\n }\n return { sqlType: \"TEXT\", jsonEncoded: true };\n }\n const primitiveKinds =\n (obs.hasString ? 1 : 0) +\n (obs.hasBoolean ? 1 : 0) +\n (obs.hasInteger || obs.hasNonInteger ? 1 : 0);\n // Mixed primitives → safest superset = text.\n if (primitiveKinds > 1) {\n if (target === \"postgres\") {\n return { sqlType: \"text\", jsonEncoded: false };\n }\n return { sqlType: \"TEXT\", jsonEncoded: false };\n }\n if (obs.hasString) {\n if (target === \"postgres\") {\n return { sqlType: \"text\", jsonEncoded: false };\n }\n return { sqlType: \"TEXT\", jsonEncoded: false };\n }\n if (obs.hasBoolean) {\n if (target === \"postgres\") {\n return { sqlType: \"boolean\", jsonEncoded: false };\n }\n return { sqlType: \"INTEGER\", jsonEncoded: false };\n }\n if (obs.hasNonInteger) {\n if (target === \"postgres\") {\n return { sqlType: \"double precision\", jsonEncoded: false };\n }\n return { sqlType: \"REAL\", jsonEncoded: false };\n }\n if (obs.hasInteger) {\n if (target === \"postgres\") {\n return { sqlType: \"integer\", jsonEncoded: false };\n }\n return { sqlType: \"INTEGER\", jsonEncoded: false };\n }\n // No observed value at all (column present-but-null on every row).\n // Fall back to text — won't matter because every insert will\n // emit NULL for it.\n if (target === \"postgres\") {\n return { sqlType: \"text\", jsonEncoded: false };\n }\n return { sqlType: \"TEXT\", jsonEncoded: false };\n};\n\n/**\n * Build an {@link ExportPlan} by scanning every row in the\n * materialised view. Column order is `_id` first, then every other\n * field sorted by first-appearance order (deterministic for a given\n * input map — JavaScript Maps preserve insertion order).\n *\n * @throws BaerlyError code=\"SchemaError\" — a row body is not a\n * `DocumentData` (defensive — the type system enforces it,\n * but the snapshot reader hands us `unknown`-shaped JSON).\n */\nexport const inferPlanForCollection = (params: {\n rows: ReadonlyMap<string, ExportRow>;\n target: SqlTarget;\n table: string;\n}): ExportPlan => {\n const { rows, target, table } = params;\n const obsByField = new Map<string, ColumnObservation>();\n // Track first-appearance order so the column list is stable.\n const orderedFields: string[] = [];\n // Per-field count of rows that carried this field (non-undefined).\n // Compared against `rows.size` in the second pass — any column\n // observed on fewer than every row is nullable.\n const rowsWithField = new Map<string, number>();\n\n // First pass — accumulate observations.\n for (const [id, body] of rows) {\n if (body === null || typeof body !== \"object\") {\n throw new BaerlyError(\n \"SchemaError\",\n `inferPlanForCollection: row ${JSON.stringify(id)} body is not an object`,\n );\n }\n for (const [field, value] of Object.entries(body)) {\n if (value === undefined) {\n continue;\n }\n let obs = obsByField.get(field);\n if (obs === undefined) {\n obs = {\n hasString: false,\n hasBoolean: false,\n hasInteger: false,\n hasNonInteger: false,\n hasNestedObject: false,\n hasNull: false,\n };\n obsByField.set(field, obs);\n orderedFields.push(field);\n }\n observe(obs, value);\n rowsWithField.set(field, (rowsWithField.get(field) ?? 0) + 1);\n }\n }\n\n // Second pass — any column observed on fewer than every row is\n // nullable. A single full sweep at the end captures both \"field\n // disappears after appearing\" AND \"field first appears on the last\n // row\" (the latter was a regression hole when the back-fill was\n // inlined into the per-row loop).\n const totalRows = rows.size;\n for (const [field, obs] of obsByField) {\n if ((rowsWithField.get(field) ?? 0) < totalRows) {\n obs.hasNull = true;\n }\n }\n\n // Build the column list. `_id` first (always — protocol-locked).\n // `_id` is the map key, not a body field, so its observation comes\n // implicitly: every row has a non-empty string id → text / TEXT.\n const columns: ColumnPlan[] = [];\n const idSqlType: SqlType = target === \"postgres\" ? \"text\" : \"TEXT\";\n columns.push({\n source: \"_id\",\n identifier: quoteIdentifier(\"_id\", target),\n sqlType: idSqlType,\n // _id is special: ALWAYS NOT NULL (it's the PK).\n nullable: false,\n jsonEncoded: false,\n });\n for (const field of orderedFields) {\n if (field === \"_id\") {\n continue;\n } // _id from the body is ignored; the map key wins\n const obs = obsByField.get(field);\n if (obs === undefined) {\n continue;\n } // never observed → skip\n const { sqlType, jsonEncoded } = pickSqlType(obs, target);\n columns.push({\n source: field,\n identifier: quoteIdentifier(field, target),\n sqlType,\n nullable: obs.hasNull,\n jsonEncoded,\n });\n }\n\n return {\n target,\n table,\n tableIdentifier: quoteIdentifier(table, target),\n columns,\n rowCount: rows.size,\n };\n};\n\n/**\n * Read the live materialised view of one collection — snapshot\n * folded with the live log tail. See `loadSnapshotAsMap` in\n * `packages/server/src/snapshot.ts` for the hash-checked snapshot\n * load this builds on.\n *\n * Returns `null` when `current.json` is missing (collection not\n * provisioned). Returns an empty map when the collection is\n * provisioned but holds no rows (every doc tombstoned, or no\n * inserts yet).\n *\n * `recoverLegacyNames` selects only byte-identical collection names in\n * a mixed legacy log. Snapshot identity and integrity checks remain\n * strict: a snapshot for the other spelling cannot establish this\n * collection's base state. Recovery never reconstructs rows an earlier\n * compaction discarded.\n */\nexport const loadMaterialisedView = async (params: {\n storage: Storage;\n currentJsonKey: string;\n collection: string;\n signal?: AbortSignal;\n recoverLegacyNames?: boolean;\n}): Promise<ReadonlyMap<string, ExportRow> | null> => {\n const { storage, currentJsonKey, collection } = params;\n const read = await readCurrentJson(\n storage,\n currentJsonKey,\n params.signal !== undefined ? { signal: params.signal } : undefined,\n );\n if (read === null) {\n return null;\n }\n const collectionPrefix = currentJsonKey.slice(0, currentJsonKey.lastIndexOf(\"/\"));\n const base =\n read.json.snapshot === null\n ? new Map<string, ExportRow>()\n : await loadSnapshotAsMap(storage, read.json.snapshot, collection, params.signal);\n const hint = read.json.tail_hint;\n const logSeqStart = read.json.log_seq_start ?? 0;\n // Strict dense walk `[log_seq_start, tail_hint)` plus a tolerant\n // forward-probe `[max(log_seq_start, tail_hint), tail)` — `tail_hint`\n // is only a lower bound under single-write commit (compactor-advanced).\n const strict = await walkLogRange(storage, collectionPrefix, logSeqStart, hint);\n const probe = await probeTailFrom(\n storage,\n collectionPrefix,\n Math.max(logSeqStart, hint),\n params.signal !== undefined ? { signal: params.signal } : undefined,\n );\n for (const entry of [...strict, ...probe.entries]) {\n const own =\n params.recoverLegacyNames === true\n ? entry.collection === collection\n : isOwnCollection(entry.collection, collection);\n if (!own) {\n continue;\n }\n if (entry.doc_id === undefined) {\n continue;\n }\n if (entry.op === \"I\" || entry.op === \"U\") {\n if (entry.after !== undefined) {\n base.set(entry.doc_id, entry.after);\n }\n } else if (entry.op === \"D\") {\n base.delete(entry.doc_id);\n }\n }\n return base;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAaA,MAAa,mBAAmB,MAAc,YAA+B;CAC3E,IAAI,KAAK,WAAW,GAClB,MAAM,IAAI,YAAY,eAAe,mCAAmC;CAE1E,IAAI,KAAK,SAAS,IAAI,GACpB,MAAM,IAAI,YACR,eACA,2CAA2C,KAAK,UAAU,IAAI,GAChE;CAEF,OAAO,IAAI,KAAK,QAAQ,MAAM,MAAI,EAAE;AACtC;;;;;;;;;;;;;AAcA,MAAa,cAAc,OAA6B,WAA8B;CACpF,IAAI,UAAU,MACZ,OAAO;CAET,IAAI,OAAO,UAAU,UACnB,OAAO,IAAI,MAAM,QAAQ,MAAM,IAAI,EAAE;CAEvC,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GACxB,MAAM,IAAI,YACR,eACA,eAAe,OAAO,KAAK,EAAE,iDAC/B;EAEF,OAAO,OAAO,KAAK;CACrB;CACA,IAAI,OAAO,UAAU,WAAW;EAC9B,IAAI,WAAW,YACb,OAAO,QAAQ,SAAS;EAE1B,OAAO,QAAQ,MAAM;CACvB;CAGA,MAAM,IAAI,YACR,eACA,gFACF;AACF;;AC7CA,MAAM,YAAY,EAAE,KAAK;AACzB,MAAM,YAAY,KAAK,KAAK;AAE5B,MAAM,WAAW,KAAwB,UAA+B;CACtE,IAAI,OAAO,UAAU,UACnB,IAAI,YAAY;MACX,IAAI,OAAO,UAAU,WAC1B,IAAI,aAAa;MACZ,IAAI,OAAO,UAAU,UAAU;EACpC,IAAI,OAAO,U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