@gusto/baerly-storage 0.1.1 → 0.2.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 +27 -3
- package/dist/API.md +103 -22
- package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js +11 -0
- package/dist/bytes-BXdamO3L.js.map +1 -0
- package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
- package/dist/client-react.d.ts +76 -85
- package/dist/client-react.js +95 -53
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/cloudflare.d.ts +31 -4
- package/dist/cloudflare.js +72 -6
- package/dist/cloudflare.js.map +1 -1
- package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
- package/dist/config-DVfDGyw1.js.map +1 -0
- package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
- package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
- package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
- package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
- package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
- package/dist/current-json-C-EyJqs0.js.map +1 -0
- package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
- package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
- package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
- package/dist/dev-vite.d.ts +3 -3
- package/dist/dev-vite.js +3 -3
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
- package/dist/doctor-Db-hzPmE.js.map +1 -0
- package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
- package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
- package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
- package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
- package/dist/fsck-CPPZWt9p.js.map +1 -0
- package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
- package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
- package/dist/http.d.ts +3 -3
- package/dist/http.js +1 -1
- package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
- package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
- package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
- package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +3 -3
- package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
- package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
- package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
- package/dist/maintenance-BRrThz8V.d.ts +449 -0
- package/dist/maintenance-BvOv6BMM.js +1295 -0
- package/dist/maintenance-BvOv6BMM.js.map +1 -0
- package/dist/maintenance-ClzBC1Vv.js +1895 -0
- package/dist/maintenance-ClzBC1Vv.js.map +1 -0
- package/dist/maintenance.d.ts +2 -323
- package/dist/maintenance.js +2 -2
- package/dist/node.d.ts +20 -79
- package/dist/node.js +2 -2
- package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
- package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +2 -2
- package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
- package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
- package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
- package/dist/query-BmiQy328.js.map +1 -0
- package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
- package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
- package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
- package/dist/restore-C6IcmLeA.js.map +1 -0
- package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
- package/dist/snapshot-SS8USDUF.js.map +1 -0
- package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
- package/dist/src-DU1sCMlr.js.map +1 -0
- package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
- package/dist/src-QQ7jDeL2.js.map +1 -0
- package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
- package/dist/src-zhEAmmF7.js.map +1 -0
- package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
- package/dist/subcommand-DZcHcsYp.js.map +1 -0
- package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
- package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
- package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
- package/dist/validate-DCq_0DIn.js.map +1 -0
- package/package.json +13 -6
- package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
- package/dist/config-Bsg8wgwo.js.map +0 -1
- package/dist/current-json-BkatBzF7.js.map +0 -1
- package/dist/doctor-B8h9GCN9.js.map +0 -1
- package/dist/fsck-DEz9lyCy.js.map +0 -1
- package/dist/indexes-BXn7a06a.js +0 -297
- package/dist/indexes-BXn7a06a.js.map +0 -1
- package/dist/log-walk-DIru96UT.js.map +0 -1
- package/dist/maintenance-Bn6ul9aV.js +0 -758
- package/dist/maintenance-Bn6ul9aV.js.map +0 -1
- package/dist/query-DcSbFLJt.js.map +0 -1
- package/dist/rebuild-index-C5gTXryd.js +0 -119
- package/dist/rebuild-index-C5gTXryd.js.map +0 -1
- package/dist/restore-CbKVMMpm.js.map +0 -1
- package/dist/snapshot-D7C4_FSl.js +0 -71
- package/dist/snapshot-D7C4_FSl.js.map +0 -1
- package/dist/snapshot-z_N9hpTe.js +0 -917
- package/dist/snapshot-z_N9hpTe.js.map +0 -1
- package/dist/src-Chafbw8r.js.map +0 -1
- package/dist/src-Cr9C7_tT.js.map +0 -1
- package/dist/src-n0Te1r98.js.map +0 -1
- package/dist/subcommand-BWs6K7zb.js +0 -110
- package/dist/subcommand-BWs6K7zb.js.map +0 -1
- package/dist/validate-DhH1lO8I.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-z_N9hpTe.js","names":[],"sources":["../packages/protocol/src/query/_internals.ts","../packages/protocol/src/query/matches.ts","../packages/protocol/src/query/satisfiable.ts","../packages/protocol/src/query/validate.ts","../packages/protocol/src/hashing.ts","../packages/protocol/src/snapshot-hash.ts","../packages/server/src/indexes.ts","../packages/server/src/log-walk.ts","../packages/server/src/snapshot.ts"],"sourcesContent":["/**\n * Shared helpers for the predicate algebras in `./validate.ts`,\n * `./matches.ts`, and `./merge.ts`. These exist as a single module\n * because more than one of those files uses them and duplicating\n * the implementations would drift over time.\n *\n * Only {@link deepEqualDocumentValue} is part of the public surface;\n * the comparator primitives (`compareScalar`, `sameComparableType`,\n * `formatPath`) are internal to the protocol package and imported\n * by `./validate.ts` / `./merge.ts` / `./normalize.ts` directly.\n */\n\nimport type { DocumentValue } from \"../json.ts\";\n\n/** @internal Same primitive type for comparison purposes. */\nexport const sameComparableType = (a: DocumentValue, b: DocumentValue): boolean =>\n (typeof a === \"string\" && typeof b === \"string\") ||\n (typeof a === \"number\" && typeof b === \"number\");\n\n/**\n * @internal Returns negative / zero / positive for a<b / a==b / a>b.\n */\nexport const compareScalar = (a: DocumentValue, b: DocumentValue): number => {\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n if (typeof a === \"string\" && typeof b === \"string\") {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n }\n return 0;\n};\n\n/** @internal Render a predicate path for use in error messages. */\nexport const formatPath = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? \"<root>\" : path.map((p) => JSON.stringify(p)).join(\".\");\n\n/**\n * Recursive structural equality for `DocumentValue` values. Lifted to\n * `export` so the filtered-index implication checker (in\n * `@baerly/server`'s query planner) and other callers can reuse the\n * same comparison rule the validator + merger already trust. Two\n * values `a` and `b` are equal iff:\n *\n * - they are reference-equal (covers primitives and object identity);\n * - or they are both non-`null` objects with the same key set, and\n * every value pair is recursively equal.\n *\n * Arrays are out-of-band for `DocumentValue`; this function rejects\n * them implicitly via the same key-set walk (an array reads as an\n * object with numeric-string keys plus a `length` exposure that\n * `Object.keys` happens to skip — defensive callers should still gate\n * with `Array.isArray` first).\n */\nexport const deepEqualDocumentValue = (a: DocumentValue, b: DocumentValue): boolean => {\n if (a === b) {\n return true;\n } // primitives + object identity\n if (typeof a !== \"object\" || typeof b !== \"object\") {\n return false;\n }\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n for (const key of aKeys) {\n if (!(key in b)) {\n return false;\n }\n const aSub = (a as Record<string, DocumentValue>)[key];\n const bSub = (b as Record<string, DocumentValue>)[key];\n if (aSub === undefined || bSub === undefined) {\n return false;\n }\n if (!deepEqualDocumentValue(aSub, bSub)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * Wire predicate evaluator. Walks a validated {@link PredicateWire}\n * against a `JSONObject` document and returns `true` iff every\n * clause holds. Multiple clauses across all fields AND together.\n *\n * Pre-condition: `wire` must have been returned by\n * {@link validateWire} (see `./validate.ts`). Passing an\n * un-validated wire is a caller bug; behaviour is undefined.\n *\n * Companion modules: `./validate.ts` (construction-time check),\n * `./merge.ts` (AND-merge), `./wire.ts` (types).\n */\n\nimport type { DocumentValue, JSONObject, JSONValue } from \"../json.ts\";\n\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\n/**\n * Evaluate a validated wire-form predicate against a `JSONObject`\n * document. Returns `true` iff every clause holds.\n *\n * @example\n * ```ts\n * matchesWire(\n * { clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] },\n * { status: \"open\", priority: \"p1\" },\n * ); // true\n *\n * matchesWire(\n * { clauses: [{ op: \"in\", field: \"priority\", value: [\"p1\", \"p2\"] }] },\n * { priority: \"p3\" },\n * ); // false\n *\n * matchesWire(\n * {\n * clauses: [\n * { op: \"gte\", field: \"count\", value: 1 },\n * { op: \"lt\", field: \"count\", value: 10 },\n * ],\n * },\n * { count: 5 },\n * ); // true\n * ```\n */\nexport const matchesWire = (wire: PredicateWire, doc: JSONObject): boolean => {\n for (const clause of wire.clauses) {\n const actual = lookupPath(doc, clause.field);\n if (!matchesClause(clause, actual)) {\n return false;\n }\n }\n return true;\n};\n\nconst lookupPath = (doc: JSONObject, field: string): JSONValue | undefined => {\n // Fast path: no dot → top-level lookup. Avoids allocating a split\n // array for the common case.\n if (!field.includes(\".\")) {\n return doc[field];\n }\n const segments = field.split(\".\");\n let cursor: JSONValue | undefined = doc;\n for (const segment of segments) {\n if (\n cursor === undefined ||\n cursor === null ||\n typeof cursor !== \"object\" ||\n Array.isArray(cursor)\n ) {\n // Traversal hit a primitive, null, missing key, or array\n // before consuming the path. Predicate cannot match.\n return undefined;\n }\n cursor = (cursor as JSONObject)[segment];\n }\n return cursor;\n};\n\nconst matchesClause = (clause: PredicateClause, actual: JSONValue | undefined): boolean => {\n switch (clause.op) {\n case \"eq\": {\n return matchesEq(clause.value as DocumentValue, actual);\n }\n case \"in\": {\n return matchesIn(clause.value as ReadonlyArray<DocumentValue>, actual);\n }\n case \"gt\": {\n return compareGT(actual, clause.value as DocumentValue, false);\n }\n case \"gte\": {\n return compareGT(actual, clause.value as DocumentValue, true);\n }\n case \"lt\": {\n return compareLT(actual, clause.value as DocumentValue, false);\n }\n case \"lte\": {\n return compareLT(actual, clause.value as DocumentValue, true);\n }\n }\n};\n\nconst matchesEq = (expected: DocumentValue, actual: JSONValue | undefined): boolean => {\n if (typeof expected === \"object\") {\n // Nested object equality is a sub-predicate match — open-world:\n // doc may carry extra keys. The object-form normaliser flattens\n // nested sub-predicates to dotted-path clauses on the way in, so\n // the only callers reaching this branch are callback-form\n // `q.eq(\"nested\", { ... })`.\n if (\n actual === undefined ||\n actual === null ||\n typeof actual !== \"object\" ||\n Array.isArray(actual)\n ) {\n return false;\n }\n for (const subKey of Object.keys(expected)) {\n const subExpected = (expected as Record<string, DocumentValue>)[subKey];\n if (subExpected === undefined) {\n continue;\n }\n const subActual = (actual as JSONObject)[subKey];\n if (!matchesEq(subExpected, subActual)) {\n return false;\n }\n }\n return true;\n }\n return expected === actual;\n};\n\nconst matchesIn = (\n members: ReadonlyArray<DocumentValue>,\n actual: JSONValue | undefined,\n): boolean => {\n for (const m of members) {\n if (typeof m === \"object\") {\n if (matchesEq(m, actual)) {\n return true;\n }\n } else if (m === actual) {\n return true;\n }\n }\n return false;\n};\n\nconst compareGT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual >= bound : actual > bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual >= bound : actual > bound);\n }\n // Validator forbids boolean / null / object range bounds; defensive miss.\n return false;\n};\n\nconst compareLT = (\n actual: JSONValue | undefined,\n bound: DocumentValue,\n inclusive: boolean,\n): boolean => {\n if (typeof bound === \"string\") {\n return typeof actual === \"string\" && (inclusive ? actual <= bound : actual < bound);\n }\n if (typeof bound === \"number\") {\n return typeof actual === \"number\" && (inclusive ? actual <= bound : actual < bound);\n }\n return false;\n};\n","/**\n * Per-field satisfiability check for a {@link PredicateWire}. Groups\n * clauses by field, then runs the same logic the pre-redesign\n * `assertOpObjectSatisfiable` ran on a single op-object — but\n * generalised across N clauses on the same field (the wire merger\n * concatenates lists without coalescing).\n *\n * Triggers:\n * - Two `eq` clauses on the same field with different values →\n * `InvalidConfig` (the same conflict that pre-redesign\n * `mergePredicates` threw on shared primitive keys).\n * - Range bounds with `lo > hi` (or `lo == hi` with strict on\n * either side) → `UnsatisfiablePredicate`.\n * - `eq` value outside the residual range interval or absent from\n * every `in` set on the same field → `UnsatisfiablePredicate`.\n * - `in` sets that intersect to empty across multiple clauses →\n * `UnsatisfiablePredicate`.\n *\n * Used by both `./validate.ts` (wire-arrival check) and\n * `./merge.ts` (post-merge re-check, kept in lockstep).\n */\n\nimport { BaerlyError } from \"../errors.ts\";\nimport type { DocumentValue } from \"../json.ts\";\n\nimport {\n compareScalar,\n deepEqualDocumentValue,\n formatPath,\n sameComparableType,\n} from \"./_internals.ts\";\nimport type { PredicateClause, PredicateWire } from \"./wire.ts\";\n\ninterface FieldGroup {\n readonly eqs: DocumentValue[];\n readonly ins: ReadonlyArray<DocumentValue>[];\n lo?: { value: DocumentValue; inclusive: boolean };\n hi?: { value: DocumentValue; inclusive: boolean };\n}\n\nconst groupByField = (wire: PredicateWire): Map<string, FieldGroup> => {\n const out = new Map<string, FieldGroup>();\n for (const clause of wire.clauses) {\n let group = out.get(clause.field);\n if (group === undefined) {\n group = { eqs: [], ins: [] };\n out.set(clause.field, group);\n }\n applyClause(group, clause.field, clause);\n }\n return out;\n};\n\nconst applyClause = (group: FieldGroup, field: string, clause: PredicateClause): void => {\n switch (clause.op) {\n case \"eq\": {\n group.eqs.push(clause.value as DocumentValue);\n return;\n }\n case \"in\": {\n group.ins.push(clause.value as ReadonlyArray<DocumentValue>);\n return;\n }\n case \"gt\": {\n tightenLower(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"gte\": {\n tightenLower(group, field, clause.value as DocumentValue, true);\n return;\n }\n case \"lt\": {\n tightenUpper(group, field, clause.value as DocumentValue, false);\n return;\n }\n case \"lte\": {\n tightenUpper(group, field, clause.value as DocumentValue, true);\n return;\n }\n }\n};\n\nconst tightenLower = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.lo === undefined) {\n group.lo = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.lo.value, value)) {\n // Type-incompatible bounds on the same field — the user wrote\n // (say) `q.gt(\"x\", 1).gt(\"x\", \"a\")`. Range matching is type-\n // strict at evaluation time so this is always-miss; surface\n // eagerly as `UnsatisfiablePredicate`.\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible lower bounds (${JSON.stringify(group.lo.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.lo.value, value);\n if (c < 0 || (c === 0 && inclusive === false && group.lo.inclusive === true)) {\n group.lo = { value, inclusive };\n }\n};\n\nconst tightenUpper = (\n group: FieldGroup,\n field: string,\n value: DocumentValue,\n inclusive: boolean,\n): void => {\n if (group.hi === undefined) {\n group.hi = { value, inclusive };\n return;\n }\n if (!sameComparableType(group.hi.value, value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has type-incompatible upper bounds (${JSON.stringify(group.hi.value)} vs ${JSON.stringify(value)}).`,\n );\n }\n const c = compareScalar(group.hi.value, value);\n if (c > 0 || (c === 0 && inclusive === false && group.hi.inclusive === true)) {\n group.hi = { value, inclusive };\n }\n};\n\nconst intersectInSets = (\n sets: ReadonlyArray<ReadonlyArray<DocumentValue>>,\n): ReadonlyArray<DocumentValue> => {\n if (sets.length === 0) {\n return [];\n }\n let acc: ReadonlyArray<DocumentValue> = sets[0]!;\n for (let i = 1; i < sets.length; i++) {\n const next: DocumentValue[] = [];\n for (const a of acc) {\n for (const b of sets[i]!) {\n if (deepEqualDocumentValue(a, b)) {\n next.push(a);\n break;\n }\n }\n }\n acc = next;\n }\n return acc;\n};\n\n/**\n * Check that every per-field clause group on `wire` is jointly\n * satisfiable. Throws `BaerlyError{code:\"UnsatisfiablePredicate\"}`\n * (or `\"InvalidConfig\"` for conflicting `eq` clauses) on the\n * first contradiction. Returns `void` on success.\n */\nexport const assertWireSatisfiable = (wire: PredicateWire): void => {\n const groups = groupByField(wire);\n for (const [field, group] of groups) {\n // Multiple `eq` clauses on the same field must agree.\n if (group.eqs.length > 1) {\n for (let i = 1; i < group.eqs.length; i++) {\n if (!deepEqualDocumentValue(group.eqs[0]!, group.eqs[i]!)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Conflicting equality clauses on field ${formatPath([field])} (${JSON.stringify(group.eqs[0]!)} vs ${JSON.stringify(group.eqs[i]!)}). Predicate chains must agree on shared equality.`,\n );\n }\n }\n }\n const eq = group.eqs[0];\n // Range interval must be non-empty.\n if (\n group.lo !== undefined &&\n group.hi !== undefined &&\n sameComparableType(group.lo.value, group.hi.value)\n ) {\n const c = compareScalar(group.lo.value, group.hi.value);\n if (c > 0 || (c === 0 && (!group.lo.inclusive || !group.hi.inclusive))) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty interval (lo=${JSON.stringify(group.lo.value)} ${group.lo.inclusive ? \"gte\" : \"gt\"}, hi=${JSON.stringify(group.hi.value)} ${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n // `eq` outside the residual interval / membership set.\n if (eq !== undefined) {\n if (group.lo !== undefined) {\n if (!sameComparableType(eq, group.lo.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with lower bound ${JSON.stringify(group.lo.value)} (${typeof group.lo.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.lo.value);\n if (c < 0 || (c === 0 && !group.lo.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by lower bound ${JSON.stringify(group.lo.value)} (${group.lo.inclusive ? \"gte\" : \"gt\"}).`,\n );\n }\n }\n if (group.hi !== undefined) {\n if (!sameComparableType(eq, group.hi.value)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} (${typeof eq}) is type-incompatible with upper bound ${JSON.stringify(group.hi.value)} (${typeof group.hi.value}); range ops require matching primitive types.`,\n );\n }\n const c = compareScalar(eq, group.hi.value);\n if (c > 0 || (c === 0 && !group.hi.inclusive)) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} excluded by upper bound ${JSON.stringify(group.hi.value)} (${group.hi.inclusive ? \"lte\" : \"lt\"}).`,\n );\n }\n }\n if (group.ins.length > 0) {\n for (const set of group.ins) {\n let found = false;\n for (const m of set) {\n if (deepEqualDocumentValue(eq, m)) {\n found = true;\n break;\n }\n }\n if (!found) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} eq=${JSON.stringify(eq)} not present in in() set.`,\n );\n }\n }\n }\n }\n // Multiple `in` sets must intersect non-empty.\n if (group.ins.length > 1) {\n const isect = intersectInSets(group.ins);\n if (isect.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate on field ${formatPath([field])} has empty in() intersection across multiple clauses.`,\n );\n }\n }\n }\n};\n","/**\n * Wire predicate validator. Walks a {@link PredicateWire} and throws\n * on a structurally bad clause (`BaerlyError{code:\"InvalidConfig\"}`)\n * or a per-field clause group that contradicts itself\n * (`BaerlyError{code:\"UnsatisfiablePredicate\"}`).\n *\n * The object-form normaliser at `./normalize.ts` enforces shape on\n * the way in (rejecting `$`-keys / non-scalars / null / undefined);\n * the callback builder at `./builder.ts` enforces shape via the\n * type system. This validator is the wire-arrival check: it runs\n * over already-normalised clauses, defending against raw-`fetch`\n * callers who bypass the typed seam and submit arbitrary JSON.\n *\n * Companion modules: `./matches.ts` (evaluator), `./merge.ts`\n * (AND-merge). Shared helpers live in `./_internals.ts`.\n */\n\nimport { BaerlyError } from \"../errors.ts\";\n\nimport { assertWireSatisfiable } from \"./satisfiable.ts\";\nimport type { PredicateClause, PredicateOpName, PredicateWire } from \"./wire.ts\";\n\nconst OP_NAMES: ReadonlyArray<PredicateOpName> = [\"eq\", \"gt\", \"gte\", \"lt\", \"lte\", \"in\"];\nconst RANGE_OPS: ReadonlyArray<PredicateOpName> = [\"gt\", \"gte\", \"lt\", \"lte\"];\n\n/**\n * Validate a normalised predicate wire. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` on a structurally bad clause,\n * or `BaerlyError{code:\"UnsatisfiablePredicate\"}` when a clause\n * group on one field contradicts itself.\n *\n * Returns the wire unchanged on success — callers can thread the\n * validated wire forward.\n *\n * @example\n * ```ts\n * validateWire({ clauses: [{ op: \"eq\", field: \"status\", value: \"open\" }] }); // ok\n * validateWire({ clauses: [{ op: \"in\", field: \"priority\", value: [] }] }); // throws UnsatisfiablePredicate\n * validateWire({ clauses: [{ op: \"eq\", field: \"_id\", value: \"x\" }] }); // throws InvalidConfig (top-level _id)\n * ```\n */\nexport const validateWire = (wire: PredicateWire): PredicateWire => {\n if (\n wire === null ||\n typeof wire !== \"object\" ||\n !Array.isArray((wire as { clauses?: unknown }).clauses)\n ) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate wire must be an object with a \"clauses\" array.`,\n );\n }\n for (let i = 0; i < wire.clauses.length; i++) {\n validateClause(wire.clauses[i]!, i);\n }\n assertWireSatisfiable(wire);\n return wire;\n};\n\nconst validateClause = (clause: PredicateClause, index: number): void => {\n if (clause === null || typeof clause !== \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} must be an object — got ${JSON.stringify(clause)}.`,\n );\n }\n const { op, field, value } = clause;\n if (typeof op !== \"string\" || !(OP_NAMES as ReadonlyArray<string>).includes(op)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has unsupported op ${JSON.stringify(op)} — supported: ${OP_NAMES.join(\" / \")}.`,\n );\n }\n if (typeof field !== \"string\" || field.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} has empty / non-string field.`,\n );\n }\n if (field === \"_id\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n 'Predicates may not key on \"_id\"; use .get(id) / .update(id, patch) / .replace(id, doc) / .delete(id) instead.',\n );\n }\n if (op === \"in\") {\n if (!Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) must carry an array value.`,\n );\n }\n if (value.length === 0) {\n throw new BaerlyError(\n \"UnsatisfiablePredicate\",\n `Predicate clause at index ${index} (op=\"in\", field=${JSON.stringify(field)}) has empty value array — no document can match.`,\n );\n }\n for (let i = 0; i < value.length; i++) {\n validateMemberValue(value[i], field, index, i);\n }\n return;\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${index} (op=${JSON.stringify(op)}, field=${JSON.stringify(field)}) must carry a primitive value, got an array — only op=\"in\" accepts arrays.`,\n );\n }\n if ((RANGE_OPS as ReadonlyArray<string>).includes(op)) {\n validateRangeBound(value, field, index);\n return;\n }\n validateScalar(value, field, index);\n};\n\nconst validateMemberValue = (\n value: unknown,\n field: string,\n clauseIndex: number,\n memberIndex: number,\n): void => {\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${value === null ? \"null\" : \"undefined\"} — members must be string / number / boolean / nested object.`,\n );\n }\n if (Array.isArray(value)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is an array — members must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (op=\"in\", field=${JSON.stringify(field)}) member ${memberIndex} is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateScalar = (value: unknown, field: string, clauseIndex: number): void => {\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${value === null ? \"null\" : \"undefined\"} — terminal values must be string / number / boolean / nested object.`,\n );\n }\n const t = typeof value;\n if (t === \"object\") {\n // Equality clauses against nested objects survive only via callback\n // form (the normaliser flattens object-form sub-predicates to\n // dotted-path eq clauses). Keep the structural recursion light —\n // values are sealed from the typed seam.\n return;\n }\n if (t !== \"string\" && t !== \"number\" && t !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value has unsupported type ${JSON.stringify(t)} — must be string / number / boolean / nested object.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate clause at index ${clauseIndex} (field=${JSON.stringify(field)}) value is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n\nconst validateRangeBound = (value: unknown, field: string, clauseIndex: number): void => {\n if (value === null || value === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${value === null ? \"null\" : \"undefined\"} — range bounds must be string or finite number.`,\n );\n }\n const t = typeof value;\n if (t === \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a boolean — range bounds must be string or finite number (booleans are not ordered).`,\n );\n }\n if (t === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is a nested object — range bounds must be string or finite number.`,\n );\n }\n if (t !== \"string\" && t !== \"number\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) has unsupported type ${JSON.stringify(t)} — must be string or finite number.`,\n );\n }\n if (t === \"number\" && !Number.isFinite(value as number)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`,\n );\n }\n};\n","import type { ContentVersionId } from \"./types.ts\";\n\n/**\n * Width of the {@link ContentVersionId} hex strings produced by\n * {@link versionFromContent}. 32 hex chars = 128 bits, matching the\n * information content of a v4 UUID. Collision probability with\n * N=10⁹ writes is ~3 × 10⁻²⁰; ample for a content-addressed version id.\n *\n * @see docs/spec/log-entry-shape.md §\"Content body layout\"\n */\nconst VERSION_HEX_LENGTH = 32;\n\n/**\n * Content-addressed {@link ContentVersionId}: SHA-256 of `body`,\n * lowercase hex, truncated to {@link VERSION_HEX_LENGTH}. Same body\n * bytes ⇒ same ContentVersionId — the property `Writer.commit`\n * relies on for idempotent replay (a crash-recovery rewrite of the\n * same logical value produces the same content key the manifest\n * already referenced).\n *\n * Async because {@link crypto.subtle.digest} returns an `ArrayBuffer`\n * via Promise. Workers and browsers both expose `crypto.subtle`\n * synchronously enough that the await fits naturally in the write\n * pipeline.\n *\n * @see docs/spec/log-entry-shape.md §\"Content body layout\"\n */\nexport const versionFromContent = async (body: Uint8Array): Promise<ContentVersionId> => {\n // Copy via fresh ArrayBuffer: tsgo narrows `Uint8Array` to\n // `Uint8Array<ArrayBufferLike>`, which `crypto.subtle.digest` rejects\n // (wants `ArrayBufferView<ArrayBuffer>`). See microsoft/TypeScript#61375.\n const view = new Uint8Array(body.byteLength);\n view.set(body);\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n const bytes = new Uint8Array(digest);\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i]!.toString(16).padStart(2, \"0\");\n }\n return hex.slice(0, VERSION_HEX_LENGTH) as ContentVersionId;\n};\n","/**\n * SHA-256 of `bytes` as a 64-char lowercase hex string. Used to seal\n * snapshot filenames so a crashed mid-PUT can't produce a body that\n * readers consume as truth: the filename embeds the hash; readers\n * recompute on load and reject any mismatch as \"file missing.\"\n *\n * Distinct from {@link versionFromContent} (truncated to 32 chars for\n * content keys) — snapshot bodies are larger and longer-lived;\n * 256-bit collision resistance matters here.\n */\nexport const snapshotHash = async (bytes: Uint8Array): Promise<string> => {\n // Copy via fresh ArrayBuffer: tsgo narrows `Uint8Array` to\n // `Uint8Array<ArrayBufferLike>`, which `crypto.subtle.digest` rejects\n // (wants `ArrayBufferView<ArrayBuffer>`). See microsoft/TypeScript#61375\n // and `versionFromContent` in ./hashing.ts for the same workaround.\n const view = new Uint8Array(bytes.byteLength);\n view.set(bytes);\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n const out = new Uint8Array(digest);\n let hex = \"\";\n for (let i = 0; i < out.length; i++) {\n hex += out[i]!.toString(16).padStart(2, \"0\");\n }\n return hex;\n};\n","/**\n * Secondary indexes — declarative collection-config-driven\n * index entries that the writer emits inside the same CAS fence as\n * the log entry and content body.\n *\n * The {@link IndexDefinition} TYPE lives in `@baerly/protocol`\n * (cross-platform). This module owns the runtime helpers that\n * operate on that shape:\n *\n * - {@link validateIndexDefinition} — synchronous schema check\n * for path-segment safety; thrown at `Writer` construction.\n * - {@link encodeIndexValue} — value-order-preserving base-32 of a\n * type-tagged byte stream (null/bool tag-only, numbers as sortable\n * IEEE 754, strings as raw UTF-8, objects as `JSON.stringify`\n * bytes for equality only).\n * - {@link indexKeyFor} / {@link indexKeyPrefix} — the wire-key\n * shape consumed by the writer's index PUTs and the rebuild\n * command's idempotent reconciliation.\n * - {@link projectIndexValues} / {@link allIndexKeysFor} — pure\n * projections from a doc body to the set of index keys it\n * produces under a collection's declared indexes.\n *\n * Wire shape (single-field):\n *\n * `<logPrefix>/index/<indexName>/<value-b32>/<docId>.json`\n *\n * Wire shape (composite — accepted by the encoder, not consulted by\n * the read path today):\n *\n * `<logPrefix>/index/<indexName>/<a-b32>/<b-b32>/<docId>.json`\n *\n * Body is zero bytes. Each entry is a fact (\"doc `<docId>` has\n * `<field> = <value>`\"), not data. Readers list the prefix, extract\n * the doc id from each key, then issue a content GET on each.\n *\n * Encoding is RFC-4648 base-32 (lowercase alphabet `[0-9a-v]`,\n * matching `packages/protocol/src/log.ts:str2uintDesc` style) on a\n * type-tagged byte stream (see {@link encodeIndexValue}) so that:\n *\n * - String \"5\" and number 5 produce distinct encodings\n * (type-tag prefix keeps the slots disjoint).\n * - Equal-by-value inputs produce byte-equal segments.\n * - Lex order under storage `list(prefix)` matches value order:\n * `null < false < true < number < string < object`, with\n * numeric values ordered by IEEE 754 magnitude (range walks\n * and `$in` walks over numeric fields are first-class — no\n * planner fall-back to full-scan).\n *\n * Locked: single-field indexes only on the read path. Composite\n * shape is documented and reserved (the path encoder accepts it).\n *\n * @see docs/spec/sync-protocol.md — fence model these PUTs land\n * inside (between log PUT and `current.json` CAS-advance).\n */\n\nimport {\n BaerlyError,\n type DocumentData,\n encodeJsonBytes,\n type IndexDefinition,\n matchesWire,\n validateWire,\n} from \"@baerly/protocol\";\n\nexport type { IndexDefinition };\n\n/** Path-safe segment name. */\nconst INDEX_NAME_RE = /^[a-z_][a-z0-9_]*$/;\n\n/**\n * Lowercase base-32 alphabet, RFC 4648 variant matching the\n * `packages/protocol/src/log.ts:str2uintDesc` style (`[0-9a-v]`).\n * Lex-order-preserving under storage `list(prefix)` semantics.\n */\nconst B32_ALPHABET = \"0123456789abcdefghijklmnopqrstuv\";\n\n/**\n * Reject malformed {@link IndexDefinition} shapes synchronously.\n * Thrown at writer construction so a config typo trips before any\n * write lands.\n *\n * @throws BaerlyError code=\"SchemaError\" — `name` doesn't match\n * `/^[a-z_][a-z0-9_]*$/`; `on` is the empty string or empty\n * array.\n */\nexport const validateIndexDefinition = (def: IndexDefinition): void => {\n if (!INDEX_NAME_RE.test(def.name)) {\n throw new BaerlyError(\n \"SchemaError\",\n `index.name must match /^[a-z_][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`,\n );\n }\n if (typeof def.on === \"string\") {\n if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty`);\n }\n } else if (def.on.length === 0) {\n throw new BaerlyError(\"SchemaError\", `index ${def.name}.on must be non-empty array`);\n }\n if (def.predicate !== undefined) {\n try {\n validateWire(def.predicate);\n } catch (error) {\n // Surface as SchemaError so the failure mode matches the rest\n // of validateIndexDefinition (writer-construction-time bail-out,\n // not query-time).\n if (error instanceof BaerlyError) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}.predicate is invalid: ${error.message}`,\n error,\n );\n }\n throw error;\n }\n }\n};\n\n/**\n * Type-tag bytes for the value-order-preserving wire format. The\n * tag is the LEADING byte of the encoded payload; the values are\n * picked so the type order under byte-wise lex is\n * `null < false < true < number < string < object`.\n *\n * | Type | Byte-prefix | Payload |\n * |---------|-------------|----------------------------------------------------|\n * | null | 0x10 | (none) |\n * | false | 0x20 | (none) |\n * | true | 0x21 | (none) |\n * | number | 0x30 | 8-byte sortable big-endian IEEE 754 |\n * | string | 0x40 | UTF-8 bytes of the string (no quotes, no escapes) |\n * | object | 0x50 | UTF-8 bytes of `JSON.stringify(v)` |\n *\n * Local to the encoder by design — these are wire shape, not\n * cross-package protocol constants (see `CLAUDE.md` § \"Magic\n * values\").\n */\nconst TYPE_NULL = 0x10;\nconst TYPE_FALSE = 0x20;\nconst TYPE_TRUE = 0x21;\nconst TYPE_NUMBER = 0x30;\nconst TYPE_STRING = 0x40;\nconst TYPE_OBJECT = 0x50;\n\n/**\n * Encode a JS double as an 8-byte big-endian sortable IEEE 754\n * payload. Byte-wise lex order on the result matches numeric order\n * across all finite doubles plus `±Infinity`:\n *\n * 1. Get the 8-byte big-endian view of the double.\n * 2. If the sign bit is `0` (zero or positive), flip the sign bit\n * (XOR `0x80` on byte 0) so positives sort above negatives.\n * 3. If the sign bit is `1` (negative), flip every bit in all 8\n * bytes so more-negative sorts lower.\n *\n * `NaN` has no order-preserving slot and is rejected — see the\n * `encodeIndexValue` JSDoc for the wire-contract rationale.\n * `-0` and `+0` collapse because the `n === 0 ? 0 : n` coercion below\n * forces both into the positive-zero branch before `setFloat64`.\n */\nconst encodeNumberPayload = (n: number): Uint8Array => {\n if (Number.isNaN(n)) {\n throw new BaerlyError(\n \"SchemaError\",\n `encodeIndexValue: NaN is not indexable (the byte encoding has no order-preserving slot for it)`,\n );\n }\n // Coerce `-0` to `+0` so both share the positive-zero serialisation\n // (`setFloat64(-0)` would produce `0x80 00...00` and take the\n // negative-branch all-bits-flip below, collapsing to a *different*\n // byte string than `+0`). Coercing up front keeps the wire stable.\n const buf = new ArrayBuffer(8);\n new DataView(buf).setFloat64(0, n === 0 ? 0 : n, false); // big-endian\n const bytes = new Uint8Array(buf);\n if ((bytes[0]! & 0x80) === 0) {\n // Positive (or +0): flip sign bit so positives sort above negatives.\n bytes[0] = bytes[0]! ^ 0x80;\n } else {\n // Negative: flip all bits so more-negative sorts lower.\n for (let i = 0; i < 8; i++) {\n bytes[i] = bytes[i]! ^ 0xff;\n }\n }\n return bytes;\n};\n\n/**\n * Compose the typed byte stream for one value. The leading byte is\n * the type tag (see {@link TYPE_NULL} et al.); the payload shape is\n * type-dependent. Strings are emitted as their raw UTF-8 bytes (no\n * JSON quoting / escaping) so byte-wise lex order on encoded strings\n * matches byte-wise lex order on the source UTF-8. Objects fall back\n * to `JSON.stringify` for equality only.\n */\nconst encodeBytes = (v: unknown): Uint8Array => {\n if (v === null || v === undefined) {\n return new Uint8Array([TYPE_NULL]);\n }\n if (v === false) {\n return new Uint8Array([TYPE_FALSE]);\n }\n if (v === true) {\n return new Uint8Array([TYPE_TRUE]);\n }\n if (typeof v === \"number\") {\n const payload = encodeNumberPayload(v);\n const out = new Uint8Array(1 + payload.length);\n out[0] = TYPE_NUMBER;\n out.set(payload, 1);\n return out;\n }\n if (typeof v === \"string\") {\n const utf8 = new TextEncoder().encode(v);\n const out = new Uint8Array(1 + utf8.length);\n out[0] = TYPE_STRING;\n out.set(utf8, 1);\n return out;\n }\n // Objects: equality only; insertion-order dependent (matches today's\n // contract on `JSON.stringify`-based equality).\n const utf8 = encodeJsonBytes(v);\n const out = new Uint8Array(1 + utf8.length);\n out[0] = TYPE_OBJECT;\n out.set(utf8, 1);\n return out;\n};\n\n/**\n * Encode an arbitrary `DocumentValue` value as a path-safe segment.\n *\n * Type-tagged byte stream, base-32-encoded for path safety. Lex\n * order on encoded bytes matches:\n *\n * - **Type order**: `null < false < true < number < string < object`.\n * - **Within numbers**: IEEE 754 numeric order (sortable\n * big-endian payload, sign-bit-flipped or all-bits-flipped).\n * `-Infinity` sorts lowest, `+Infinity` highest.\n * - **Within strings**: UTF-8 byte order.\n * - **Within objects**: byte-equality only (still\n * `JSON.stringify`-insertion-order dependent).\n *\n * Numbers ARE range-safe under this encoder — `9` sorts below `10`\n * as expected. The query planner's old\n * `numeric-range-on-byte-encoder` guard has been removed; range\n * walks and `$in` walks over numeric fields are routed normally.\n *\n * `NaN` throws `BaerlyError{code:\"SchemaError\"}` at write time —\n * the byte encoding has no order-preserving slot for it, and a\n * silent collapse to the `null` key (as the prior\n * `JSON.stringify`-based encoder did, since\n * `JSON.stringify(NaN) === \"null\"`) is a worse failure mode than\n * a loud reject.\n *\n * `-0` and `+0` collapse to the same encoding.\n *\n * Equal-by-value inputs (e.g. two `{a:1, b:2}` objects with the\n * same key insertion order) produce byte-equal segments;\n * structurally-different but visually-similar inputs (`\"5\"` vs `5`)\n * are kept apart by the type-tag prefix.\n *\n * String ranges remain safe: `\"2026-05-13\" < \"2026-05-14\"`\n * byte-wise matches semantic order. ISO 8601 timestamps,\n * alphabetical priorities like `\"p1\"/\"p2\"/\"p3\"`, and any\n * fixed-width string encoding are usable as range-walked indexed\n * fields.\n */\nexport const encodeIndexValue = (v: unknown): string => {\n const bytes = encodeBytes(v);\n let out = \"\";\n let bits = 0;\n let value = 0;\n for (const b of bytes) {\n value = (value << 8) | b;\n bits += 8;\n while (bits >= 5) {\n bits -= 5;\n out += B32_ALPHABET[(value >> bits) & 0x1f];\n }\n }\n if (bits > 0) {\n out += B32_ALPHABET[(value << (5 - bits)) & 0x1f];\n }\n // The type-prefix guarantees the byte stream is non-empty for every\n // input, so the \"empty → '0'\" fallback that the old encoder needed\n // is dead. Encoder output is always non-empty under the new contract.\n return out;\n};\n\n/**\n * Storage `list(prefix)` boundary for every entry under one index\n * of a collection: `<logPrefix>/index/<name>/`. Used by the rebuild\n * command's reconciliation walk and by the read-path index hint.\n */\nexport const indexKeyPrefix = (logPrefix: string, indexName: string): string =>\n `${logPrefix}/index/${indexName}/`;\n\n/**\n * Build the per-doc index key for one `(def, values, docId)`.\n *\n * Single-field: `<logPrefix>/index/<name>/<v0-b32>/<docId>.json`.\n * Composite: `<logPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<docId>.json`.\n *\n * Composite shape is accepted but the read path today only\n * consults single-field entries.\n */\nexport const indexKeyFor = (\n logPrefix: string,\n def: IndexDefinition,\n values: readonly unknown[],\n docId: string,\n): string => {\n const segments = values.map(encodeIndexValue).join(\"/\");\n return `${logPrefix}/index/${def.name}/${segments}/${docId}.json`;\n};\n\n/**\n * Project the value tuple a doc body produces under one index\n * definition. Returns `undefined` when any indexed field is\n * null / undefined / missing — no index entry for that doc under\n * that index (SQL \"NULL values don't enter the index\" semantics).\n *\n * @throws BaerlyError code=\"SchemaError\" — `on` contains a dotted\n * path, or the indexed field's value is an array. Both restrictions\n * are pre-launch; multi-value (array) indexes are a follow-up.\n */\nexport const projectIndexValues = (\n def: IndexDefinition,\n body: DocumentData | undefined,\n): readonly unknown[] | undefined => {\n if (body === undefined) {\n return undefined;\n }\n const fields = typeof def.on === \"string\" ? [def.on] : def.on;\n const values: unknown[] = [];\n for (const field of fields) {\n // Today we only support top-level fields. Dotted paths land in\n // a follow-up; throw loudly so a config typo doesn't silently\n // produce empty values.\n if (field.includes(\".\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}: dotted-path \"on\" fields not yet supported (got ${JSON.stringify(field)})`,\n );\n }\n const v = body[field];\n // null/undefined are skipped — no index entry. Mirrors SQL\n // \"NULL values don't go into a regular index\" semantics.\n if (v === null || v === undefined) {\n return undefined;\n }\n // Array values are valid in documents (RFC 7396 replacement\n // semantics) but multi-value indexes aren't supported yet — the\n // prefix-tree encoder produces one key per doc, not one per\n // element. Throw loudly so a user indexing a tag list gets a\n // clear error instead of garbage keys.\n if (Array.isArray(v)) {\n throw new BaerlyError(\n \"SchemaError\",\n `index ${def.name}: cannot index array field \"${field}\" — multi-value indexes are not supported yet`,\n );\n }\n values.push(v);\n }\n return values;\n};\n\n/**\n * Compute the full index-key set a single doc produces under every\n * declared index of its collection. Skips indexes whose projection\n * yields `undefined` (null/missing indexed field). Used by both\n * the writer (to PUT new keys) and the rebuild command (to compute\n * the expected key set across the live doc map).\n *\n * Filter-aware (T4): when `def.predicate !== undefined`, the doc\n * must satisfy `matchesWire(def.predicate, body)` or the def contributes\n * zero keys. The writer's diff `oldKeys` vs `newKeys` then covers\n * all four U-quadrants automatically — see the JSDoc on\n * `writer.ts` above the index-emission block. `body ===\n * undefined` short-circuits ahead of the filter check (no keys for\n * an unknown pre-image, regardless of filter), preserving the prior\n * D-quadrant behaviour.\n */\nexport const allIndexKeysFor = (\n logPrefix: string,\n defs: ReadonlyArray<IndexDefinition>,\n body: DocumentData | undefined,\n docId: string,\n): string[] => {\n const keys: string[] = [];\n for (const def of defs) {\n if (def.predicate !== undefined && body !== undefined) {\n if (!matchesWire(def.predicate, body)) {\n continue;\n }\n }\n const values = projectIndexValues(def, body);\n if (values !== undefined) {\n keys.push(indexKeyFor(logPrefix, def, values, docId));\n }\n }\n return keys;\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","/**\n * Snapshot file shape + parse. Lifted out of `./compactor.ts` so that\n * the kernel barrel (`packages/server/src/index.ts`) — which re-exports\n * these four symbols — does not transitively pull `withObservability`\n * via `compact()`. `./compactor.ts` imports its own snapshot primitives\n * back from this module; the public API surface is unchanged.\n *\n * @see ../../../docs/spec/sync-protocol.md\n */\n\nimport {\n BaerlyError,\n decodeJsonBytes,\n type DocumentData,\n encodeJsonBytes,\n snapshotHash,\n type Storage,\n} from \"@baerly/protocol\";\n\n/**\n * Single-level snapshot at L9; the level prefix is forward-compatible\n * with future L0..L9 rolling merges without a wire change.\n */\nexport const SNAPSHOT_LEVEL = 9 as const;\n\n/**\n * `minSeq` and `maxSeq` are padded to {@link SEQ_DIGITS} digits so\n * `list(prefix)` returns snapshots in seq order without needing to\n * parse the filename. 12 digits caps at ~10^12 entries per collection;\n * a real bucket hits S3's per-prefix QPS ceiling long before that.\n */\nexport const SEQ_DIGITS = 12 as const;\n\nconst MAX_SEQ = 10 ** SEQ_DIGITS - 1;\n\n/**\n * Build the on-bucket key for a snapshot file. `sha256` must be the\n * lowercase hex digest of the canonical body\n * ({@link encodeSnapshotBody}); the filename embeds it so a crashed\n * mid-PUT body that doesn't match its own filename hash is rejected\n * by readers as \"missing.\"\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `minSeq`/`maxSeq` are\n * out of range or `sha256` is not 64 hex chars.\n */\nexport const snapshotKey = (\n collectionPrefix: string,\n minSeq: number,\n maxSeq: number,\n sha256: string,\n): string => {\n if (minSeq < 0 || maxSeq < 0 || minSeq > maxSeq || maxSeq > MAX_SEQ) {\n throw new BaerlyError(\"InvalidConfig\", `snapshotKey: invalid range [${minSeq}, ${maxSeq})`);\n }\n if (!/^[0-9a-f]{64}$/.test(sha256)) {\n throw new BaerlyError(\"InvalidConfig\", \"snapshotKey: sha256 must be 64 hex chars\");\n }\n const pad = (n: number): string => n.toString().padStart(SEQ_DIGITS, \"0\");\n return `${collectionPrefix}/snapshot/L${SNAPSHOT_LEVEL}/${pad(minSeq)}-${pad(maxSeq)}-${sha256}.json`;\n};\n\n/**\n * On-bucket body of a snapshot file. The reader recomputes the SHA-256\n * over the canonical serialisation ({@link encodeSnapshotBody}) and\n * rejects any mismatch with the filename hash.\n *\n * `docs` is sorted by `_id` for deterministic byte output — two\n * compactions over the same fold produce byte-identical snapshots,\n * which means same filename, which means an idempotent re-run never\n * leaves an orphan.\n */\nexport interface SnapshotBody {\n readonly schema_version: 1;\n readonly min_seq: number;\n readonly max_seq: number;\n readonly collection: string;\n readonly docs: ReadonlyArray<{\n readonly _id: string;\n readonly body: DocumentData;\n }>;\n}\n\n/**\n * Canonical byte encoding of a {@link SnapshotBody}. Only the\n * compactor produces snapshots, and only this function does the\n * serialisation — so the byte output is deterministic for a given\n * `SnapshotBody` (identical input ⇒ identical bytes ⇒ identical\n * filename hash).\n */\nexport const encodeSnapshotBody = (s: SnapshotBody): Uint8Array => encodeJsonBytes(s);\n\n/**\n * Load a snapshot file as a `Map<_id, DocumentData>`. Verifies the\n * body hash against the filename, checks the schema version, and\n * cross-checks `body.collection` against the caller's expectation.\n *\n * @example\n * ```ts\n * import { loadSnapshotAsMap } from \"@gusto/baerly-storage\";\n *\n * const map =\n * srcCurrent.snapshot === null\n * ? new Map<string, DocumentData>()\n * : await loadSnapshotAsMap(src.storage, srcCurrent.snapshot, \"tickets\");\n * ```\n *\n * @throws BaerlyError code=\"Internal\" — pointer resolves to no body,\n * or the body's SHA-256 doesn't match the hash embedded in the\n * filename. (Protocol invariant violation; a corrupted snapshot\n * the reader cannot continue past.)\n * @throws BaerlyError code=\"InvalidResponse\" — body isn't valid JSON,\n * isn't an object, has an unsupported `schema_version`, or carries a\n * `collection` that doesn't match `expectedCollection`.\n */\nexport const loadSnapshotAsMap = async (\n storage: Storage,\n key: string,\n expectedCollection: string,\n signal?: AbortSignal,\n): Promise<Map<string, DocumentData>> => {\n const got = await storage.get(key, signal !== undefined ? { signal } : undefined);\n if (got === null) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot pointer ${key} resolves to no body; protocol violation`,\n );\n }\n // Verify hash: the filename shape is\n // `<...>/snapshot/L<n>/<min>-<max>-<sha256>.json`. The sha256 is\n // the segment after the LAST `-` (the two seq fields don't contain\n // dashes), with `.json` stripped.\n const filename = key.slice(key.lastIndexOf(\"/\") + 1).replace(/\\.json$/, \"\");\n const lastDash = filename.lastIndexOf(\"-\");\n const expectedHash = filename.slice(lastDash + 1);\n const actualHash = await snapshotHash(got.body);\n if (actualHash !== expectedHash) {\n throw new BaerlyError(\n \"Internal\",\n `compact: snapshot ${key} body hash mismatch (got ${actualHash}); protocol violation`,\n );\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} body is not valid JSON`,\n error,\n );\n }\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `compact: snapshot ${key} body is not an object`);\n }\n const body = parsed as SnapshotBody;\n if (body.schema_version !== 1) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} has unsupported schema_version ${String(body.schema_version)}`,\n );\n }\n if (body.collection !== expectedCollection) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `compact: snapshot ${key} carries collection ${body.collection}, expected ${expectedCollection}`,\n );\n }\n const out = new Map<string, DocumentData>();\n for (const row of body.docs) {\n out.set(row._id, row.body);\n }\n return out;\n};\n"],"mappings":";;;;AAeA,MAAa,sBAAsB,GAAkB,MAClD,OAAO,MAAM,YAAY,OAAO,MAAM,YACtC,OAAO,MAAM,YAAY,OAAO,MAAM;;;;AAKzC,MAAa,iBAAiB,GAAkB,MAA6B;CAC3E,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UACxC,OAAO,IAAI;CAEb,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU;EAClD,IAAI,IAAI,GACN,OAAO;EAET,IAAI,IAAI,GACN,OAAO;EAET,OAAO;CACT;CACA,OAAO;AACT;;AAGA,MAAa,cAAc,SACzB,KAAK,WAAW,IAAI,WAAW,KAAK,KAAK,MAAM,KAAK,UAAU,CAAC,CAAC,EAAE,KAAK,GAAG;;;;;;;;;;;;;;;;;;AAmB5E,MAA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M,IAAI,YACR,YACA,qBAAqB,IAAI,2BAA2B,WAAW,sBACjE;CAEF,IAAI;CACJ,IAAI;EACF,SAAS,gBAAgB,IAAI,IAAI;CACnC,SAAS,OAAO;EACd,MAAM,IAAI,YACR,mBACA,qBAAqB,IAAI,0BACzB,KACF;CACF;CACA,IAAI,WAAW,QAAQ,OAAO,WAAW,UACvC,MAAM,IAAI,YAAY,mBAAmB,qBAAqB,IAAI,uBAAuB;CAE3F,MAAM,OAAO;CACb,IAAI,KAAK,mBAAmB,GAC1B,MAAM,IAAI,YACR,mBACA,qBAAqB,IAAI,kCAAkC,OAAO,KAAK,cAAc,GACvF;CAEF,IAAI,KAAK,eAAe,oBACtB,MAAM,IAAI,YACR,mBACA,qBAAqB,IAAI,sBAAsB,KAAK,WAAW,aAAa,oBAC9E;CAEF,MAAM,sBAAM,IAAI,IAA0B;CAC1C,KAAK,MAAM,OAAO,KAAK,MACrB,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI;CAE3B,OAAO;AACT"}
|
package/dist/src-Chafbw8r.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"src-Chafbw8r.js","names":["#objects","#etagCounter","#nextEtag","#storage","#schemas","#indexes"],"sources":["../packages/protocol/src/storage/memory.ts","../packages/server/src/config.ts","../packages/server/src/auth/internal/none-verifier.ts","../packages/server/src/auth/internal/resolve-verifier.ts","../packages/server/src/collection.ts","../packages/server/src/db.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\nimport type {\n Storage,\n StorageGetOptions,\n StorageGetResult,\n StorageListEntry,\n StoragePutOptions,\n StoragePutResult,\n} from \"./types.ts\";\n\ninterface StoredObject {\n body: Uint8Array;\n etag: string;\n contentType?: string;\n}\n\n/**\n * In-memory `Storage`. The randomized property test runs against\n * this; it must be deterministic — no clocks beyond the caller's,\n * no randomness, no I/O.\n *\n * ETags are a monotonically increasing hex counter formatted in the\n * `\"<hex>\"` shape S3 returns (the surrounding double-quotes are part\n * of the ETag header value). Keys are stored verbatim.\n */\nexport class MemoryStorage implements Storage {\n readonly #objects = new Map<string, StoredObject>();\n #etagCounter = 0;\n\n #nextEtag(): string {\n this.#etagCounter += 1;\n return `\"${this.#etagCounter.toString(16)}\"`;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n if (opts?.ifNoneMatch !== undefined && opts.ifNoneMatch === stored.etag) {\n // 304 Not Modified — caller's cached copy is current.\n return null;\n }\n return { body: stored.body, etag: stored.etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === undefined) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (existing.etag !== opts.ifMatch) {\n throw new BaerlyError(\n \"Conflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`,\n );\n }\n }\n\n const etag = this.#nextEtag();\n this.#objects.set(key, {\n body,\n etag,\n ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned (callers like the kernel's\n // adaptive-clock loop need a value); `lastModified` is intentionally\n // *not* surfaced on `list()` — the in-memory impl has no\n // independent server clock, and pretending it does would force the\n // kernel's wall-clock cross-check against an artificially injected\n // `clockOffset`, breaking the property-based randomized tests.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n this.#objects.delete(key);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const sorted = [...this.#objects.keys()]\n .filter((k) => k.startsWith(prefix) && k > startAfter)\n .toSorted();\n let yielded = 0;\n for (const key of sorted) {\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n continue;\n } // unreachable; satisfies noUncheckedIndexedAccess\n yield { key, etag: stored.etag };\n yielded += 1;\n }\n }\n\n /**\n * Test-only: drop all objects.\n * @internal\n */\n _clear(): void {\n this.#objects.clear();\n this.#etagCounter = 0;\n }\n}\n\n// Process-singleton MemoryStorage map keyed by bucket. Tests that need\n// multiple `Db` / `Writer` instances to see each other's writes\n// against an in-memory backend reach for this via\n// {@link getOrCreateMemoryStorageForBucket}; {@link resetMemoryStorage}\n// drops every bucket between test cases.\nconst sharedPerBucket = new Map<string, MemoryStorage>();\n\n/**\n * Test isolation: drop every bucket's contents from the shared\n * memory storage used by {@link getOrCreateMemoryStorageForBucket}.\n * Direct `MemoryStorage` instances built via `new MemoryStorage()`\n * are unaffected — those are isolated by construction.\n */\nexport const resetMemoryStorage = (): void => {\n sharedPerBucket.clear();\n};\n\n/**\n * Get the process-singleton {@link MemoryStorage} for the named\n * bucket, creating one on first access. Use this when constructing\n * a `Storage` directly so multiple consumers in the same process\n * see each other's writes for the same bucket name.\n */\nexport const getOrCreateMemoryStorageForBucket = (bucket: string): MemoryStorage => {\n let s = sharedPerBucket.get(bucket);\n if (s === undefined) {\n s = new MemoryStorage();\n sharedPerBucket.set(bucket, s);\n }\n return s;\n};\n","/**\n * Runtime helpers for the `BaerlyConfig` shape.\n *\n * The type declarations (`BaerlyConfig`, `BaerlyAppConfig`,\n * `CollectionDefinition`, `CollectionNames`, `RowOf`, `UnboundConfig`,\n * `defineConfig`) live in `@baerly/protocol` — the cross-platform\n * package — so cross-platform consumers (client, scaffold\n * `baerly.config.ts`) can reference them without dragging the\n * Node-only server modules (`AsyncLocalStorage` etc.) into their\n * typecheck graph.\n *\n * This file keeps only the runtime helper `collectionsToMaps`, which\n * the Cloudflare and Node adapters call to flatten\n * `BaerlyConfig.collections` into the per-collection maps that\n * `Db.create` consumes.\n *\n * @see @baerly/protocol app-config.ts — type declarations.\n */\n\nimport type { BaerlyConfig, IndexDefinition, SchemaValidator } from \"@baerly/protocol\";\n\n/**\n * Flatten `BaerlyConfig.collections` into the per-collection\n * `schemas` and `indexes` maps that {@link Db.create} consumes at\n * runtime. Used by the Cloudflare and Node adapters to pipe a\n * single `config` object through to the writer/planner.\n *\n * Both adapters import this helper rather than inlining the loop\n * so the projection rule (drop empty index arrays; omit absent\n * schemas) stays in one place. Future `CollectionDefinition`\n * fields (lifecycle hooks, replica_identity) land here too.\n */\nexport const collectionsToMaps = (\n collections: BaerlyConfig[\"collections\"] | undefined,\n): {\n schemas: ReadonlyMap<string, SchemaValidator>;\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n} => {\n const schemas = new Map<string, SchemaValidator>();\n const indexes = new Map<string, ReadonlyArray<IndexDefinition>>();\n if (collections === undefined) {\n return { schemas, indexes };\n }\n for (const [name, def] of Object.entries(collections)) {\n if (def.schema !== undefined) {\n schemas.set(name, def.schema);\n }\n if (def.indexes !== undefined && def.indexes.length > 0) {\n indexes.set(name, def.indexes);\n }\n }\n return { schemas, indexes };\n};\n","import type { Verifier } from \"@baerly/protocol\";\n\n/**\n * Internal helper backing `config.auth === \"none\"`. Returns a\n * `Verifier` that resolves every request to the supplied\n * `tenantPrefix` with `identity: { kind: \"none\" }`. The kernel\n * NEVER reads the `Authorization` header in this mode — the network\n * seam itself is the trust boundary.\n *\n * Discriminant note: `identity.kind === \"none\"` distinguishes the\n * \"operator opted into auth=none in baerly.config.ts\" branch from the\n * bearer-token paths (`kind: \"shared-secret\"`, `kind: \"jwt\"`, etc).\n *\n * Not part of the public surface. Consumed by `baerlyWorker` /\n * `baerlyNode` resolution; the operator-facing API is the typed\n * `auth: \"none\"` field on `BaerlyAppConfig`.\n *\n * @internal\n */\nexport const noAuthVerifier = (tenantPrefix: string): Verifier => {\n return async () => ({ tenantPrefix, identity: { kind: \"none\" } });\n};\n","import {\n type BaerlyAppConfig,\n BaerlyError,\n NO_AUTH_CONFIGURED_MESSAGE,\n SHARED_SECRET_MISSING_MESSAGE,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { sharedSecret } from \"../presets/shared-secret.ts\";\nimport { noAuthVerifier } from \"./none-verifier.ts\";\n\n/**\n * Read env var lazily via a host-supplied accessor so the same\n * resolver works in CF Workers (env binding) and Node\n * (`process.env`). Returns `undefined` for an unset OR empty string —\n * both branches mean \"operator forgot to set it\".\n */\nexport type EnvAccessor = (name: string) => string | undefined;\n\n/**\n * Inputs to {@link resolveVerifier}. `factoryVerifier` is the\n * adapter-factory `verifier:` option (may be undefined). `config`\n * carries the typed `auth` posture + the `tenant` pin. `readEnv`\n * is the per-host env accessor.\n */\nexport interface ResolveVerifierInput {\n readonly factoryVerifier: Verifier | undefined;\n readonly config: BaerlyAppConfig;\n readonly readEnv: EnvAccessor;\n}\n\n/**\n * Resolve the per-request `Verifier` for an adapter factory using the\n * fixed order:\n *\n * 1. `factoryVerifier` set → use as-is (highest precedence; enables\n * env-aware construction via `cloudflareAccess(env)` etc).\n * 2. else `config.auth === \"shared-secret\"` → read `SHARED_SECRET`\n * via `readEnv`; throw `BaerlyError(\"InvalidConfig\",\n * SHARED_SECRET_MISSING_MESSAGE)` when unset/empty; else build\n * `sharedSecret({ secret, tenantPrefix: config.tenant })`.\n * 3. else `config.auth === \"none\"` → `noAuthVerifier(config.tenant)`.\n * 4. else → throw `BaerlyError(\"InvalidConfig\",\n * NO_AUTH_CONFIGURED_MESSAGE)`.\n *\n * Pure function — no I/O, no side effects beyond `sharedSecret`'s\n * own validation. Caller invokes once at adapter init time (or on\n * first fetch, depending on platform `await`-at-top-level\n * constraints).\n *\n * @throws BaerlyError code=\"InvalidConfig\" — branches 2 and 4 above.\n *\n * @internal\n */\nexport const resolveVerifier = (input: ResolveVerifierInput): Verifier => {\n if (input.factoryVerifier !== undefined) {\n return input.factoryVerifier;\n }\n if (input.config.auth === \"shared-secret\") {\n const secret = input.readEnv(\"SHARED_SECRET\");\n if (secret === undefined || secret.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", SHARED_SECRET_MISSING_MESSAGE);\n }\n return sharedSecret({ secret, tenantPrefix: input.config.tenant });\n }\n if (input.config.auth === \"none\") {\n return noAuthVerifier(input.config.tenant);\n }\n // Exhaustiveness backstop. The AuthConfig union is locked to\n // [\"none\", \"shared-secret\"]; reaching this branch means the caller\n // passed a config that has neither the typed field nor a factory\n // override. Same operator remediation as the type-level error.\n throw new BaerlyError(\"InvalidConfig\", NO_AUTH_CONFIGURED_MESSAGE);\n};\n","/**\n * `Collection<T>` factory. `Db.collection(name)` returns the result of\n * `makeCollection(ctx)` — a cheap, no-I/O handle. By-id mutations route\n * through dedicated runners: `insert` → `runInsert`,\n * `replace(id, doc)` → `runReplaceById`. `update(id, patch)` and\n * `delete(id)` forward to the predicate-form runners via a `byId`\n * wire — those Query verbs are genuinely bulk, so the by-id case is\n * just a one-row predicate.\n *\n * `Collection.insert(doc)` is the public insert path. The locked\n * `Query<T>` interface (`@baerly/protocol/src/collection-api.ts`) intentionally\n * does NOT declare `insert` — chainable inserts are out of scope.\n * For an inserted doc whose predicate-bound shape matters,\n * `db.collection(...).insert(...)` is the path; predicates are a read-\n * side concern.\n */\n\nimport {\n type Collection,\n type DocumentData,\n type OrderSpec,\n type PredicateWire,\n} from \"@baerly/protocol\";\nimport { makeQuery, runInsert, runReplaceById, type CollectionReadContext } from \"./query.ts\";\n\n/**\n * Build a `Collection<T>` bound to one `(tenant, collection)` read context.\n * Cheap: zero I/O, allocates one closure. Each modifier call returns\n * a FRESH `Query<T>` — calling `.where(p1)` and `.where(p2)` on the\n * same `Collection<T>` produces two independent chains.\n *\n * `.count()` shorthand defers to the empty-state `Query<T>.count()`\n * so the fold logic lives in one place.\n *\n * @example\n * ```ts\n * const collection = makeCollection<Ticket>({\n * storage,\n * collectionPrefix: \"app/tickets/tenant/acme/manifests/tickets\",\n * collectionName: \"tickets\",\n * });\n * const open = await collection.where({ status: \"open\" }).all();\n * ```\n *\n * @internal\n */\nexport const makeCollection = <T extends DocumentData>(\n ctx: CollectionReadContext,\n): Collection<T> => {\n // Empty seed state. Every modifier merges into a frozen copy.\n const seed = {\n wire: undefined as PredicateWire | undefined,\n order: undefined as OrderSpec<T> | undefined,\n limit: undefined as number | undefined,\n };\n // Kernel-internal `_id`-shaped wire. Bypasses `validateWire`\n // (which rejects top-level `_id`) by construction — the wire is\n // never wire-submitted; it short-circuits to `Map.get` via\n // `singleIdFromPredicate` inside `runRead`.\n const byId = (id: string) => ({\n ...seed,\n wire: { clauses: [{ op: \"eq\" as const, field: \"_id\", value: id }] } as PredicateWire,\n });\n return {\n name: ctx.collectionName,\n first: () => makeQuery<T>(ctx, seed).first(),\n all: () => makeQuery<T>(ctx, seed).all(),\n count: () => makeQuery<T>(ctx, seed).count(),\n get: (id) => makeQuery<T>(ctx, byId(id)).first(),\n where: (p) => makeQuery<T>(ctx, seed).where(p),\n order: (s) => makeQuery<T>(ctx, { ...seed, order: s }),\n limit: (n) => makeQuery<T>(ctx, { ...seed, limit: n }),\n /**\n * Insert one document. UUIDv7 auto-id when `_id` is absent or\n * empty; otherwise the caller-supplied `_id` is honoured. A\n * pre-commit existence check against the materialised collection\n * surfaces `Conflict` on duplicate `_id` without round-tripping\n * to the writer — matches the locked `Collection.insert` throws\n * contract (`@baerly/protocol/src/collection-api.ts`).\n *\n * Single-attempt per call: CAS retries (up to 8 attempts) live\n * inside `Writer.commit()`. On retry-budget exhaustion the\n * writer throws `Conflict` and we surface unchanged.\n *\n * @throws BaerlyError code=\"Conflict\" — `_id` collision (pre-commit\n * check) or CAS retry budget exhausted.\n * @throws BaerlyError code=\"SchemaError\" — from the per-collection\n * `SchemaValidator` threaded via {@link Db.collectionReadContext}.\n */\n insert: (doc) => runInsert<T>(ctx, doc),\n update: (id, patch) => makeQuery<T>(ctx, byId(id)).update(patch),\n replace: (id, doc) => runReplaceById<T>(ctx, id, doc),\n delete: (id) => makeQuery<T>(ctx, byId(id)).delete(),\n };\n};\n","import {\n type BaerlyConfig,\n BaerlyError,\n type Collection,\n type CollectionNames,\n type CurrentJsonRead,\n decodeJsonBytes,\n type DocumentData,\n type IndexDefinition,\n LOG_KEY_PREFIX,\n type LogEntry,\n readCurrentJson,\n type RowOf,\n type SchemaValidator,\n type Storage,\n type UnboundConfig,\n} from \"@baerly/protocol\";\nimport { collectionsToMaps } from \"./config.ts\";\nimport type { CollectionReadContext } from \"./query.ts\";\nimport { Writer, type CommitInput } from \"./writer.ts\";\nimport { makeCollection } from \"./collection.ts\";\n\n/**\n * In-memory buffer for a single in-flight {@link Db.transaction}\n * call. The `Collection<T>` instance passed to the transaction body holds\n * a reference to this object; every mutation verb appends to\n * `mutations` instead of calling `Writer.commit` directly.\n *\n * After the body resolves, `Db.transaction` performs ONE\n * `Writer.commitBatch(...)` to commit every buffered mutation\n * in a single CAS attempt.\n *\n * @internal — referenced by `collection.ts` and `query.ts`; not part of\n * the public API surface for app code.\n */\nexport interface TxContext {\n /**\n * The collection name the transaction is scoped to. Mutation verbs\n * runtime-assert that their `Collection<T>`'s `name` matches this\n * field before appending — the type system already prevents the\n * legitimate path, this catches the bug path (a stale `Query<T>`\n * re-attached to a different collection's transaction).\n */\n readonly collection: string;\n\n /**\n * Mutations buffered in order of issuance. The commit converts\n * each into one `CommitInput` (`Writer`'s single-mutation\n * shape) and passes the array to `Writer.commitBatch`.\n */\n readonly mutations: BufferedMutation[];\n}\n\n/**\n * One buffered mutation. Mirrors {@link CommitInput} minus\n * `collection` (which is constant per transaction and lives on\n * `TxContext.collection`).\n *\n * @internal — only used inside the `Db.transaction` path.\n */\nexport interface BufferedMutation {\n readonly op: \"I\" | \"U\" | \"D\";\n readonly docId: string;\n readonly body?: DocumentData;\n readonly origin?: string;\n}\n\n/**\n * Physical-key prefix for a `(app, tenant)` pair. Trailing slash is\n * part of the prefix so a caller's `list(\"\")` resolves to\n * `list(\"app/<app>/tenant/<tenant>/\")` and cannot enumerate a sibling\n * tenant whose name shares a prefix.\n */\nconst physicalPrefixFor = (app: string, tenant: string): string => `app/${app}/tenant/${tenant}/`;\n\n/**\n * Runtime entry point. One `Db` per `(app, tenant)` request.\n *\n * Construct via {@link Db.create} — the constructor is private so\n * callers don't accidentally bypass validation.\n *\n * **Collection provisioning.** `Db` provisions collections implicitly on\n * the first commit — the writer auto-creates the per-collection\n * `current.json` manifest with a zero-state seed, costing one extra\n * Class A PUT on the very first write per collection and zero\n * thereafter. There is no `ensureCollection` method on this class. For\n * eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures\n * that want byte-identical bytes before the first request), use\n * {@link \"@gusto/baerly-storage/dev\".ensureTable}.\n *\n * @example\n * ```ts\n * import { Db } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"tickets\",\n * tenant: \"acme-co\",\n * });\n *\n * await db.collection(\"tickets\").insert({ title: \"first ticket\", status: \"open\" });\n * const open = await db.collection(\"tickets\").where({ status: \"open\" }).all();\n * ```\n *\n * @remarks\n * **Anti-patterns** (TS compile errors, not runtime rejections):\n * - `db.collection(name).insertOne({...})` / `.insert({...})` —\n * the Mongo verb. Use `.insert(row)` (returns `{ _id }`).\n * - `db.collection(name).findOne({...})` / `.find({...})` —\n * the Mongo read verbs. Use `.get(id)` for by-id reads and\n * `.where({...}).first()` / `.all()` for predicate reads.\n * - `db.collection(name).aggregate([...])` — no pipeline stage\n * model. Compose via `.where().order().limit()` modifiers.\n * - Raw SQL strings of any shape. The kernel has no SQL parser.\n */\nexport class Db<TConfig extends BaerlyConfig = UnboundConfig> {\n readonly app: string;\n readonly tenant: string;\n /**\n * Underlying `Storage`, captured so the collection API can issue reads\n * using physical keys directly.\n */\n readonly #storage: Storage;\n /**\n * Per-collection {@link SchemaValidator}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * validation declared\" — every write proceeds at zero overhead.\n *\n * Derived from `config.collections[*].schema` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #schemas: ReadonlyMap<string, SchemaValidator>;\n /**\n * Per-collection {@link IndexDefinition}s threaded onto every\n * {@link CollectionReadContext} this `Db` mints. Empty map means \"no\n * indexes declared\" — every read falls through to the snapshot +\n * log fold path.\n *\n * Derived from `config.collections[*].indexes` via\n * {@link collectionsToMaps} at {@link Db.create} time.\n */\n readonly #indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>;\n\n private constructor(\n app: string,\n tenant: string,\n storage: Storage,\n schemas: ReadonlyMap<string, SchemaValidator>,\n indexes: ReadonlyMap<string, ReadonlyArray<IndexDefinition>>,\n ) {\n this.app = app;\n this.tenant = tenant;\n this.#storage = storage;\n this.#schemas = schemas;\n this.#indexes = indexes;\n }\n\n /**\n * Build a tenant-scoped `Db`. Throws\n * `BaerlyError{code:\"InvalidConfig\"}` if either `app` or `tenant`\n * is empty or contains `/` (the segment separator).\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `app` or `tenant` is\n * empty or contains `/`.\n *\n * @example\n * ```ts\n * const db = Db.create({ storage, app: \"tickets\", tenant: \"acme\" });\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * ```\n */\n static create<TConfig extends BaerlyConfig = UnboundConfig>(config: {\n storage: Storage;\n app: string;\n tenant: string;\n /**\n * Optional. Pass the value returned by {@link defineConfig} from\n * your `baerly.config.ts`. Two things happen:\n *\n * 1. **Types.** `db.collection(name)` narrows `name` to declared\n * collection names and infers the row type from\n * `collections[name].schema` via {@link RowOf}.\n * 2. **Runtime.** Schemas and indexes are derived from\n * `config.collections` via {@link collectionsToMaps}. Schema\n * validation and index routing are wired automatically — no\n * second hand-off step.\n *\n * @example\n * ```ts\n * import config from \"../baerly.config.ts\";\n * const db = Db.create({\n * storage: new MemoryStorage(),\n * app: \"helpdesk\",\n * tenant: \"test\",\n * config,\n * });\n * // db.collection(\"tickets\") is typed AND validates writes against\n * // the schema declared in baerly.config.ts.\n * ```\n */\n config?: TConfig;\n }): Db<TConfig> {\n const { storage, app, tenant } = config;\n assertKeySegment(app, \"app\", \"Db.create\");\n assertKeySegment(tenant, \"tenant\", \"Db.create\");\n // Always derive runtime maps from `config.collections`. Absent\n // config ⇒ empty maps (no schemas, no indexes); the kernel\n // behaves the same as a config with `collections: {}`.\n const derived =\n config.config !== undefined ? collectionsToMaps(config.config.collections) : undefined;\n return new Db<TConfig>(\n app,\n tenant,\n storage,\n derived?.schemas ?? new Map(),\n derived?.indexes ?? new Map(),\n );\n }\n\n /**\n * Typed handle for a single collection. Cheap; creates no I/O. Same\n * `name` returns a FRESH `Collection<T>` object on each call (chain\n * identity is intentional — modifiers return new objects).\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty or\n * contains `/`.\n *\n * @example\n * ```ts\n * // With a baerly.config.ts bound via Db.create({..., config}),\n * // db.collection(name) infers the row type from the declared schema —\n * // no <Ticket> generic needed.\n * const open = await db.collection(\"tickets\")\n * .where({ status: \"open\" })\n * .order({ commit_ts: \"desc\" })\n * .limit(50)\n * .all();\n * ```\n */\n // One signature. When `TConfig` extends `UnboundConfig`,\n // `CollectionNames<UnboundConfig>` widens to `string` so kernel-internal\n // paths against `Db<UnboundConfig>` still resolve without a separate\n // untyped overload. The impl signature stays widened (`Collection<any>`)\n // — the runtime never narrows; `makeCollection<DocumentData>` builds a\n // single row-agnostic handle and TypeScript handles the rest at the\n // call site.\n collection<N extends CollectionNames<TConfig>>(\n name: N,\n ): Collection<RowOf<TConfig, N> & DocumentData>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- impl signature must be wider than the public overload; with Predicate<T> typed, Collection<DocumentData> is no longer assignable to Collection<RowOf<...>&DocumentData> due to contravariance on where(). `any` widens correctly.\n collection(name: string): Collection<any> {\n return makeCollection<DocumentData>(this.collectionReadContext(name));\n }\n\n /**\n * Build a freshly-seeded {@link CollectionReadContext} for `name`. The\n * HTTP router uses this so it can drive `runAllWithMeta` directly\n * (the return shape carries the manifest-pointer cursor used to\n * pack `_meta` onto the read response envelope). Application\n * callers should keep using\n * {@link Db.collection}; the chainable terminals destructure the cursor\n * out and discard it to keep the locked `Query<T>` signature.\n *\n * Runs the same `name`-validation guard as {@link Db.collection}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when `name` is empty or\n * contains `/`.\n * @internal\n */\n collectionReadContext(name: string): CollectionReadContext {\n assertKeySegment(name, \"collection\", \"Db.collection\");\n const schema = this.#schemas.get(name);\n return {\n storage: this.#storage,\n collectionPrefix: `${physicalPrefixFor(this.app, this.tenant)}manifests/${name}`,\n collectionName: name,\n indexes: this.#indexes.get(name) ?? [],\n ...(schema !== undefined ? { schema } : {}),\n };\n }\n\n /**\n * Atomic mutation over a single collection. The callback receives a\n * `Collection<T>` (not a `Db`) so cross-collection writes inside a\n * transaction are a TypeScript error at compile time — not a\n * runtime trap. Mutation verbs (`insert`, `update`, `replace`,\n * `delete`) buffer; reads (`first`, `all`, `count`) go through\n * `Storage` live (no MVCC snapshot, no read-your-writes).\n *\n * Single-attempt: on CAS conflict throws\n * `BaerlyError{code:\"Conflict\"}`. The body MAY have already run its\n * read side-effects (no rollback of in-memory state); the write\n * side-effects either all landed or none did. Wrap in a retry\n * loop you wrote if you want one.\n *\n * Empty body (or a body that buffers nothing) resolves without\n * touching `current.json`.\n *\n * @throws BaerlyError code=\"Conflict\" — CAS lost on the collection's\n * `current.json`. Caller decides whether to re-run the body.\n * @throws Whatever the body throws — re-thrown as-is. The commit\n * is skipped when the body throws.\n * @throws BaerlyError code=\"InvalidConfig\" — `collection` is empty or\n * contains `/`.\n *\n * @remarks\n * Single-collection by design. Cross-collection 2PC was rejected on\n * cost grounds — multiple round-trips per commit, no native fencing\n * primitive on S3-compatible storage, no rollback to undo a\n * successful PUT — and because in-doubt-transaction recovery state\n * would contradict the stateless-writer model. Applications that\n * need cross-collection atomicity re-express it at the app layer: an\n * idempotent move keyed off source-row state, or a single\n * denormalized collection with a `status` column.\n *\n * @example\n * ```ts\n * await db.transaction(\"tickets\", async (tx) => {\n * const open = await tx.where({ status: \"open\" }).count();\n * if (open < 100) await tx.insert({ title: \"another\", status: \"open\" });\n * });\n * ```\n */\n async transaction<T extends DocumentData = DocumentData>(\n collection: string,\n body: (tx: Collection<T>) => Promise<void>,\n ): Promise<void> {\n assertKeySegment(collection, \"collection\", \"Db.transaction\");\n\n const txCtx: TxContext = { collection, mutations: [] };\n const collectionPrefix = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}`;\n\n // Build a Collection<T> whose mutation verbs buffer onto `txCtx`. The\n // read path ignores `txCtx` entirely (locked: no MVCC, no\n // read-your-writes inside a transaction).\n const schema = this.#schemas.get(collection);\n const indexes = this.#indexes.get(collection) ?? [];\n const tx = makeCollection<T>({\n storage: this.#storage,\n collectionPrefix,\n collectionName: collection,\n txCtx,\n indexes,\n ...(schema !== undefined ? { schema } : {}),\n });\n\n // Run the body. Reads go through Storage live; mutations append\n // to txCtx.mutations. A throw here propagates AS-IS and skips\n // the commit (txCtx.mutations is discarded).\n await body(tx);\n\n // Empty buffer — nothing to commit, nothing to throw.\n if (txCtx.mutations.length === 0) {\n return;\n }\n\n // Map BufferedMutations -> CommitInputs and fire one\n // single-attempt commitBatch. On CAS loss commitBatch throws\n // `Conflict` and we surface it unchanged.\n const inputs: CommitInput[] = [];\n for (const m of txCtx.mutations) {\n const input: CommitInput = {\n op: m.op,\n collection,\n docId: m.docId,\n ...(m.body !== undefined ? { body: m.body } : {}),\n ...(m.origin !== undefined ? { origin: m.origin } : {}),\n };\n inputs.push(input);\n }\n\n const writer = new Writer({\n storage: this.#storage,\n currentJsonKey: `${collectionPrefix}/current.json`,\n options: { indexes },\n });\n await writer.commitBatch(inputs);\n }\n\n /**\n * Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns\n * `null` when the collection has not been provisioned yet (no\n * `current.json` exists). Throws `BaerlyError{code:\"InvalidResponse\"}`\n * on a malformed body — same contract as the underlying\n * {@link readCurrentJson} helper in `@baerly/protocol`.\n *\n * Backs the `/v1/since` long-poll handler in\n * `packages/server/src/http/since.ts`; that handler needs the parsed\n * `CurrentJson` plus an ETag for the follow-up reads.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getCurrentJson(\n collection: string,\n opts?: { signal?: AbortSignal },\n ): Promise<CurrentJsonRead | null> {\n const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/current.json`;\n return readCurrentJson(this.#storage, key, opts);\n }\n\n /**\n * Read + parse one `LogEntry` by `seq` from\n * `manifests/<collection>/${LOG_KEY_PREFIX}/<seq>.json`. Returns `null`\n * when the entry is missing — this typically means the GC sweeper\n * deleted the entry between a `readCurrentJson` and this GET (the\n * `/v1/since` handler treats the race as silent and skips the\n * entry). Throws `BaerlyError{code:\"InvalidResponse\"}` on a body\n * that isn't valid JSON.\n *\n * @internal — typed seam for the HTTP handler; app code should use\n * the collection API.\n */\n async getLogEntry(\n collection: string,\n seq: number,\n opts?: { signal?: AbortSignal },\n ): Promise<LogEntry | null> {\n const key = `${physicalPrefixFor(this.app, this.tenant)}manifests/${collection}/${LOG_KEY_PREFIX}/${seq}.json`;\n const got = await this.#storage.get(key, opts);\n if (got === null) {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = decodeJsonBytes(got.body);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `log entry at ${key}: body is not valid JSON`,\n error,\n );\n }\n return parsed as LogEntry;\n }\n}\n\n/**\n * Guard a string used as a path-segment in the bucket-key encoding.\n * Rejects empty and `/`-containing values with\n * `BaerlyError{code:\"InvalidConfig\"}`. `role` and `verb` are baked\n * into the message so the caller doesn't need to format their own.\n *\n * Used by {@link Db.create} (twice — `app`, `tenant`),\n * {@link Db.collectionReadContext} (once — `name`), and\n * {@link Db.transaction} (once — `collection`).\n *\n * @internal\n */\nconst assertKeySegment = (value: string, role: string, verb: string): void => {\n if (value.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: ${role} must be non-empty (got ${JSON.stringify(value)})`,\n );\n }\n if (value.includes(\"/\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${verb}: \"/\" is reserved as the key-segment separator (got ${role}=${JSON.stringify(value)})`,\n );\n }\n};\n"],"mappings":";;;;;;;;;;;;;;AAyBA,IAAa,gBAAb,MAA8C;CAC5C,2BAAoB,IAAI,IAA0B;CAClD,eAAe;CAEf,YAAoB;EAClB,KAAKC,gBAAgB;EACrB,OAAO,IAAI,KAAKA,aAAa,SAAS,EAAE,EAAE;CAC5C;CAEA,MAAM,IAAI,KAAa,MAA4D;EACjF,MAAM,QAAQ,eAAe;EAC7B,MAAM,SAAS,KAAKD,SAAS,IAAI,GAAG;EACpC,IAAI,WAAW,KAAA,GACb,OAAO;EAET,IAAI,MAAM,gBAAgB,KAAA,KAAa,KAAK,gBAAgB,OAAO,MAEjE,OAAO;EAET,OAAO;GAAE,MAAM,OAAO;GAAM,MAAM,OAAO;EAAK;CAChD;CAEA,MAAM,IAAI,KAAa,MAAkB,MAAqD;EAC5F,MAAM,QAAQ,eAAe;EAC7B,MAAM,WAAW,KAAKA,SAAS,IAAI,GAAG;EAEtC,IAAI,MAAM,gBAAgB,OAAO,aAAa,KAAA,GAC5C,MAAM,IAAI,YACR,YACA,OAAO,IAAI,uDACb;EAEF,IAAI,MAAM,YAAY,KAAA,GAAW;GAC/B,IAAI,aAAa,KAAA,GACf,MAAM,IAAI,YACR,YACA,OAAO,IAAI,iCAAiC,KAAK,QAAQ,yBAC3D;GAEF,IAAI,SAAS,SAAS,KAAK,SACzB,MAAM,IAAI,YACR,YACA,OAAO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