@gusto/baerly-storage 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +3 -2
  2. package/dist/API.md +59 -7
  3. package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
  4. package/dist/app-config.d.ts +1 -1
  5. package/dist/auth.d.ts +1 -1
  6. package/dist/baerly.js +10 -10
  7. package/dist/baerly.js.map +1 -1
  8. package/dist/bytes-BXdamO3L.js +11 -0
  9. package/dist/bytes-BXdamO3L.js.map +1 -0
  10. package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
  11. package/dist/client-react.d.ts +3 -3
  12. package/dist/client.d.ts +3 -3
  13. package/dist/cloudflare.d.ts +31 -4
  14. package/dist/cloudflare.js +72 -6
  15. package/dist/cloudflare.js.map +1 -1
  16. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  17. package/dist/config-DVfDGyw1.js.map +1 -0
  18. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  19. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  20. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  21. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  22. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  23. package/dist/current-json-C-EyJqs0.js.map +1 -0
  24. package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
  25. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  26. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  27. package/dist/dev-vite.d.ts +3 -3
  28. package/dist/dev-vite.js +3 -3
  29. package/dist/dev.d.ts +1 -1
  30. package/dist/dev.js +1 -1
  31. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  32. package/dist/doctor-Db-hzPmE.js.map +1 -0
  33. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  34. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  35. package/dist/errors-DOdL95kK.js.map +1 -1
  36. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  37. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  38. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  39. package/dist/fsck-CPPZWt9p.js.map +1 -0
  40. package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
  41. package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
  42. package/dist/http.d.ts +3 -3
  43. package/dist/http.js +1 -1
  44. package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  45. package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
  46. package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
  47. package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
  48. package/dist/index.d.ts +5 -5
  49. package/dist/index.js +3 -3
  50. package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  51. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  52. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  53. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  54. package/dist/maintenance-BvOv6BMM.js +1295 -0
  55. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  56. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  57. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  58. package/dist/maintenance.d.ts +2 -323
  59. package/dist/maintenance.js +2 -2
  60. package/dist/node.d.ts +20 -79
  61. package/dist/node.js +2 -2
  62. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  63. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  64. package/dist/observability.d.ts +2 -2
  65. package/dist/observability.js +2 -2
  66. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  67. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  68. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  69. package/dist/query-BmiQy328.js.map +1 -0
  70. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  71. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  72. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  73. package/dist/restore-C6IcmLeA.js.map +1 -0
  74. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  75. package/dist/snapshot-SS8USDUF.js.map +1 -0
  76. package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
  77. package/dist/src-DU1sCMlr.js.map +1 -0
  78. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  79. package/dist/src-QQ7jDeL2.js.map +1 -0
  80. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  81. package/dist/src-zhEAmmF7.js.map +1 -0
  82. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  83. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  84. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  85. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  86. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  87. package/dist/validate-DCq_0DIn.js.map +1 -0
  88. package/package.json +13 -6
  89. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  90. package/dist/config-Bsg8wgwo.js.map +0 -1
  91. package/dist/current-json-BkatBzF7.js.map +0 -1
  92. package/dist/doctor-B8h9GCN9.js.map +0 -1
  93. package/dist/fsck-DEz9lyCy.js.map +0 -1
  94. package/dist/indexes-BXn7a06a.js +0 -297
  95. package/dist/indexes-BXn7a06a.js.map +0 -1
  96. package/dist/log-walk-DIru96UT.js.map +0 -1
  97. package/dist/maintenance-Bn6ul9aV.js +0 -758
  98. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  99. package/dist/query-DcSbFLJt.js.map +0 -1
  100. package/dist/rebuild-index-C5gTXryd.js +0 -119
  101. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  102. package/dist/restore-CbKVMMpm.js.map +0 -1
  103. package/dist/snapshot-D7C4_FSl.js +0 -71
  104. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  105. package/dist/snapshot-z_N9hpTe.js +0 -917
  106. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  107. package/dist/src-Chafbw8r.js.map +0 -1
  108. package/dist/src-Cr9C7_tT.js.map +0 -1
  109. package/dist/src-n0Te1r98.js.map +0 -1
  110. package/dist/subcommand-BWs6K7zb.js +0 -110
  111. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  112. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"log-walk-DIru96UT.js","names":[],"sources":["../packages/protocol/src/coordination/current-json.ts","../packages/server/src/log-walk.ts"],"sourcesContent":["/**\n * `current.json` — the per-collection CAS-protected control object — and\n * its embedded {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps\n * snapshot generations by CAS-writing this object; the\n * Writer reads it on every commit to find the snapshot\n * pointer; the sweeper reads `writer_fence` to decide which log\n * entries are eligible for GC.\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} to `2`; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `1`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 1;\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 * Sequence number of the next log entry. Monotonic per\n * collection. The Writer reads this on commit to mint the\n * next log filename; CAS-write back with `next_seq + 1` ensures\n * no two writers pick the same sequence.\n */\n next_seq: 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, next_seq)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= next_seq`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and\n * is not consumed by any ticket in this batch.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. The mechanism is the same in all three: every commit\n * checks the epoch on the control object; an entry stamped with\n * a stale epoch is discarded at replay.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Triggers per design: (a) detected\n * CAS conflict the writer wants to claim through, (b) admin\n * rotation. The sweeper discards log entries whose stamped epoch\n * is `< current.writer_fence.epoch`.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the write fence by bumping `epoch` and stamping\n * `claimed_at` from `StoragePutResult.serverDate`. The common call\n * site is \"I detected a CAS conflict during a commit and want to\n * claim the fence before retrying\"; admin rotation is the other call\n * site.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, next_seq)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing — readers\n * never silently accept an unknown shape.\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\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; expected ${CURRENT_JSON_SCHEMA_VERSION}`,\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 if (typeof r[\"next_seq\"] !== \"number\" || !Number.isInteger(r[\"next_seq\"]) || r[\"next_seq\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: next_seq must be a non-negative integer`,\n );\n }\n if (\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[\"next_seq\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > next_seq ${String(r[\"next_seq\"])}`,\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 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 return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n","/**\n * Shared log-walk primitives consumed by the read path (`query.ts`),\n * the compactor (`compactor.ts`), and the optional integrity walk in\n * `Writer.#singleAttemptCommit` (`writer.ts`).\n *\n * Two operations: read one log entry, or walk a contiguous range of\n * log entries with bounded parallelism. Each kernel call site\n * previously inlined the same range-build + unbounded `Promise.all`\n * pattern; on a free-tier collection where the compactor lags the\n * tail to 50-100 entries, that fans out 50-100 concurrent GETs per\n * call — and a contended writer multiplies that by the CAS retry\n * budget. `walkLogRange` caps concurrency at\n * {@link MAX_PARALLEL_LOG_READS} so a single call costs at most that\n * many simultaneous GETs against the storage backend.\n *\n * Order invariant: results are returned in seq order regardless of\n * resolution order. The read-side fold is order-sensitive (`U` then\n * `D` on the same doc must apply in that order); callers may iterate\n * the returned array as-is.\n *\n * Signal invariant: when the caller's `AbortSignal` fires, no further\n * chunks dispatch. In-flight reads see the signal via the underlying\n * `Storage.get` call.\n */\n\nimport {\n type DocumentData,\n type LogEntry,\n type Storage,\n BaerlyError,\n decodeJsonBytes,\n MAX_PARALLEL_LOG_READS,\n} from \"@baerly/protocol\";\n\n/**\n * Fetch a single log entry. Centralises the \"missing entry inside the\n * visible log range is a protocol-invariant violation\" rule used by\n * every caller.\n *\n * @throws BaerlyError code=\"Internal\" when the key resolves to no\n * body — a hole inside `[log_seq_start, next_seq)` is a corruption\n * the kernel can't continue past.\n * @throws BaerlyError code=\"InvalidResponse\" when the body isn't\n * valid JSON.\n */\nexport const readLogEntry = async (\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry> => {\n const got = await storage.get(\n key,\n opts?.signal !== undefined ? { signal: opts.signal } : undefined,\n );\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `log-walk: missing log entry at ${key}; protocol invariant violation`,\n );\n }\n try {\n return decodeJsonBytes<LogEntry>(got.body);\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `log-walk: malformed log entry at ${key}`, error);\n }\n};\n\n/**\n * Walk `[fromSeq, toSeqExclusive)` of `${logPrefix}/log/<seq>.json`\n * in chunks of {@link MAX_PARALLEL_LOG_READS} concurrent GETs.\n * Returns the materialised entries in seq order.\n *\n * Empty range (`fromSeq >= toSeqExclusive`) returns `[]` and issues\n * zero GETs.\n *\n * Same error semantics as {@link readLogEntry}: a missing entry\n * throws `Internal`, a malformed body throws `InvalidResponse`.\n */\nexport const walkLogRange = async (\n storage: Storage,\n logPrefix: string,\n fromSeq: number,\n toSeqExclusive: number,\n opts?: { signal?: AbortSignal },\n): Promise<LogEntry[]> => {\n if (fromSeq >= toSeqExclusive) {\n return [];\n }\n const total = toSeqExclusive - fromSeq;\n const out: LogEntry[] = Array.from({ length: total });\n for (let chunkStart = 0; chunkStart < total; chunkStart += MAX_PARALLEL_LOG_READS) {\n opts?.signal?.throwIfAborted();\n const chunkEnd = Math.min(chunkStart + MAX_PARALLEL_LOG_READS, total);\n const promises: Array<Promise<LogEntry>> = [];\n for (let i = chunkStart; i < chunkEnd; i++) {\n const seq = fromSeq + i;\n promises.push(readLogEntry(storage, `${logPrefix}/log/${seq}.json`, opts));\n }\n const results = await Promise.all(promises);\n for (let i = 0; i < results.length; i++) {\n out[chunkStart + i] = results[i]!;\n }\n }\n return out;\n};\n\n/**\n * Fold a sequence of `LogEntry` records onto a doc-id-keyed map,\n * applying the protocol's per-doc-replace semantics:\n *\n * - `I` / `U`: when `entry.new !== undefined`, set\n * `map.set(entry.doc_id, entry.new)`. Entries with `new ===\n * undefined` (the partial-merge writer's future patch-only shape)\n * are ignored — today's writer always emits `new`, so this is a\n * forward-compat guard, not a live branch.\n * - `D`: tombstone — `map.delete(entry.doc_id)`.\n * - `T` / `M`: ignored. `T` (TRUNCATE) is not yet wired; `M`\n * (MESSAGE) is a marker. The emitter never produces them today.\n *\n * Entries whose `collection` does not match `opts.collection`, or\n * whose `doc_id` is `undefined`, are skipped. When\n * `opts.docIdFilter` is provided, only entries whose `doc_id` is\n * present in the filter set are folded — used by the index-walk\n * read path to scope the fold to the docs the planner already\n * resolved.\n *\n * This is the canonical fold used by the read path\n * (`query.ts`) and the index reconciler (`rebuild-index.ts`).\n * Centralising it keeps the\n * \"ignore T/M; straight `set` on I/U; tombstone on D\" protocol\n * invariant in one place.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\nexport const foldLogEntriesOnto = <T extends DocumentData>(\n map: Map<string, T>,\n entries: Iterable<LogEntry>,\n opts: {\n readonly collection: string;\n readonly docIdFilter?: ReadonlySet<string>;\n },\n): void => {\n const { collection, docIdFilter } = opts;\n for (const entry of entries) {\n if (entry.collection !== collection) {\n continue;\n }\n if (entry.doc_id === undefined) {\n continue;\n }\n if (docIdFilter !== undefined && !docIdFilter.has(entry.doc_id)) {\n continue;\n }\n switch (entry.op) {\n case \"I\":\n case \"U\": {\n if (entry.new === undefined) {\n continue;\n }\n map.set(entry.doc_id, entry.new as T);\n break;\n }\n case \"D\": {\n map.delete(entry.doc_id);\n break;\n }\n case \"T\":\n case \"M\": {\n // No-op for forward-compat shapes the writer doesn't emit today.\n break;\n }\n }\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4KA,eAAsB,gBACpB,SACA,KACA,MACiC;CACjC,MAAM,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI;CACvC,IAAI,QAAQ,MACV,OAAO;CAET,MAAM,OAAO,IAAI,YAAY,EAAE,OAAO,IAAI,IAAI;CAC9C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,IAAI;CAC1B,SAAS,OAAO;EACd,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,2BACvB,KACF;CACF;CACA,OAAO;EAAE,MAAM,kBAAkB,QAAQ,GAAG;EAAG,MAAM,IAAI;CAAK;AAChE;;;;;;;;;;;AAYA,eAAsB,kBACpB,SACA,KACA,SACA,MAC0B;CAE1B,kBAAkB,SAAS,GAAG;CAC9B,MAAM,OAAO,WAAW,OAAO;CAC/B,MAAM,UAA6B;EACjC,aAAa;EACb,aAAa;EACb,GAAI,MAAM,WAAW,KAAA,KAAa,EAAE,QAAQ,KAAK,OAAO;CAC1D;CACA,IAAI;CACJ,IAAI;EACF,SAAS,MAAM,QAAQ,IAAI,KAAK,MAAM,OAAO;CAC/C,SAAS,OAAO;EACd,MAAM,kBAAkB,OAAO,GAAG;CACpC;CACA,OAAO;EAAE,MAAM;EAAS,MAAM,OAAO;CAAK;AAC5C;;;;;;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