@gusto/baerly-storage 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -2
- package/dist/API.md +59 -7
- 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 +3 -3
- 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":"config-Bsg8wgwo.js","names":[],"sources":["../packages/protocol/src/constants.ts","../packages/cli/src/config.ts"],"sourcesContent":["/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<next_seq>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Three Class A ops: PUT content, PUT log entry, CAS-advance\n * `current.json`. The cost-model page derives the free-tier write\n * budget from this multiplier; the phase-5 end-to-end test asserts it\n * at CI time. Changing this constant is a cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 3;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","/**\n * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.\n *\n * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`\n * but lives in `@baerly/cli` so the validator/loader doesn't depend on\n * the rolldown'd umbrella bundle. The scaffolder emits the config file;\n * the CLI reads it. Both sides agree on the wire shape (informally —\n * the duplication is small and intentional).\n *\n * Resolution order:\n * 1. `<cwd>/baerly.config.ts`\n * 2. `<cwd>/baerly.config.js`\n * 3. `<cwd>/baerly.config.mjs`\n * 4. `<cwd>/baerly.config.json`\n *\n * The `.ts` form requires the user to have a TS-aware Node entry\n * point (`tsx`, `--experimental-strip-types`, or a build step that\n * produced the `.js` alongside). If `import()` throws on the `.ts`\n * file, we re-wrap as `InvalidConfig` with a hint pointing at the\n * `.js` / `.json` fallbacks.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport {\n AUTH_CONFIG_VALUES,\n type AuthConfig,\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n} from \"@baerly/protocol\";\n\nexport interface AppConfig {\n readonly app: string;\n readonly tenant: string;\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Required. See `AuthConfig` for the per-value semantics. The loader\n * throws `BaerlyError(\"InvalidConfig\", ...)` when `auth` is missing or\n * not a member of `AUTH_CONFIG_VALUES`.\n */\n readonly auth: AuthConfig;\n readonly domain?: string;\n readonly requiredSecrets?: readonly string[];\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /** Absolute path to the repo root that contained the config. */\n readonly repoRoot: string;\n}\n\nconst CONFIG_BASENAMES: readonly string[] = [\n \"baerly.config.ts\",\n \"baerly.config.js\",\n \"baerly.config.mjs\",\n \"baerly.config.json\",\n];\n\n/**\n * Locate the first `baerly.config.*` file under `cwd`. Returns the\n * absolute path or `null` if none exists.\n *\n * Exported so the collection-aware loader (and future consumers) can\n * reuse the same resolution order without re-implementing it.\n */\nexport const locateConfig = (cwd: string): string | null => {\n for (const base of CONFIG_BASENAMES) {\n const abs = resolve(cwd, base);\n if (existsSync(abs)) {\n return abs;\n }\n }\n return null;\n};\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to\n * `process.cwd()`). Validates the required fields and the\n * locked-shape optionals; returns an `AppConfig` decorated with the\n * `repoRoot` it was loaded from.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, default\n * export missing, or any field has the wrong shape / type.\n */\nexport const loadAppConfig = async (cwd: string = process.cwd()): Promise<AppConfig> => {\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`,\n );\n }\n\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to read ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n try {\n raw = JSON.parse(text) as unknown;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to parse ${cfgPath}: ${(error as Error).message}`,\n error,\n );\n }\n } else {\n let mod: { default?: unknown };\n try {\n mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n } catch (error) {\n const hint = cfgPath.endsWith(\".ts\")\n ? \" (Node cannot import .ts directly without a TS loader — point at the compiled .js or use a .json config)\"\n : \"\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to load ${cfgPath}: ${(error as Error).message}${hint}`,\n error,\n );\n }\n raw = mod.default;\n }\n\n if (raw === undefined || typeof raw !== \"object\" || raw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`,\n );\n }\n\n const obj = raw as Record<string, unknown>;\n const app = obj[\"app\"];\n const tenant = obj[\"tenant\"];\n const target = obj[\"target\"];\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`app\\` must be a non-empty string`,\n );\n }\n if (typeof tenant !== \"string\" || tenant.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`tenant\\` must be a non-empty string`,\n );\n }\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`target\\` must be \"cloudflare\" or \"node\" (got ${JSON.stringify(target)})`,\n );\n }\n\n // `auth` is a required typed posture as of the graduated-auth\n // redesign. The widening cast to `readonly string[]` is needed\n // because `.includes` on a tuple narrows its parameter to the\n // tuple's element type; widening locally is the standard idiom.\n const authRaw = obj[\"auth\"];\n if (typeof authRaw !== \"string\" || !(AUTH_CONFIG_VALUES as readonly string[]).includes(authRaw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`auth\\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`,\n );\n }\n const auth = authRaw as AuthConfig;\n\n const domainRaw = obj[\"domain\"];\n if (domainRaw !== undefined && typeof domainRaw !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`domain\\` must be a string when set`,\n );\n }\n\n const secretsRaw = obj[\"requiredSecrets\"];\n let requiredSecrets: readonly string[] | undefined;\n if (secretsRaw !== undefined) {\n if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === \"string\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`requiredSecrets\\` must be an array of strings`,\n );\n }\n requiredSecrets = secretsRaw as readonly string[];\n }\n\n const cfaRaw = obj[\"cloudflareAccess\"];\n let cloudflareAccess: AppConfig[\"cloudflareAccess\"];\n if (cfaRaw !== undefined) {\n if (typeof cfaRaw !== \"object\" || cfaRaw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess\\` must be an object when set`,\n );\n }\n const cfa = cfaRaw as Record<string, unknown>;\n const td = cfa[\"teamDomain\"];\n const aud = cfa[\"audienceTag\"];\n if (typeof td !== \"string\" || td.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.teamDomain\\` must be a non-empty string`,\n );\n }\n if (typeof aud !== \"string\" || aud.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.audienceTag\\` must be a non-empty string`,\n );\n }\n cloudflareAccess = { teamDomain: td, audienceTag: aud };\n }\n\n return {\n app,\n tenant,\n target,\n auth,\n ...(domainRaw !== undefined && { domain: domainRaw }),\n ...(requiredSecrets !== undefined && { requiredSecrets }),\n ...(cloudflareAccess !== undefined && { cloudflareAccess }),\n repoRoot: cwd,\n };\n};\n\n/**\n * Lightweight per-collection index reflection. Mirrors the shape the\n * runtime `BaerlyConfig` carries, but only the fields the doctor needs.\n *\n * `indexes` is an empty array when the collection declared none.\n */\nexport interface LoadedCollection {\n readonly name: string;\n readonly indexes: readonly IndexDefinition[];\n}\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` AND return the parsed\n * `collections[*]` shape alongside the narrow {@link AppConfig}. Lets\n * the doctor reflect on declared indexes without forcing every consumer\n * to widen `AppConfig`. Returns `undefined` for `collections` when the\n * config doesn't declare any (the doctor downgrades the drift check to\n * a no-op `info` finding in that case).\n *\n * Re-uses {@link loadAppConfig}'s parse/validate path, so the\n * `AppConfig` invariants are still enforced.\n */\nexport const loadAppConfigWithCollections = async (\n cwd: string = process.cwd(),\n): Promise<{\n readonly config: AppConfig;\n readonly collections: readonly LoadedCollection[] | undefined;\n}> => {\n const config = await loadAppConfig(cwd);\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n return { config, collections: undefined };\n }\n\n // Re-parse the raw default-export to pluck `collections[*]`. We\n // don't validate the inner shape here — at the doctor surface,\n // anything that isn't an object is reported as \"no filtered\n // indexes\" rather than throwing, so a partially-typed config\n // doesn't fail the whole check.\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch {\n return { config, collections: undefined };\n }\n try {\n raw = JSON.parse(text);\n } catch {\n return { config, collections: undefined };\n }\n } else {\n try {\n const mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n raw = mod.default;\n } catch {\n // Node can't `import` a .ts file without a TS loader. The\n // narrow `loadAppConfig` already surfaced the InvalidConfig if\n // that path was unreadable; here we silently downgrade to\n // \"no collections\" rather than re-throw.\n return { config, collections: undefined };\n }\n }\n\n if (raw === undefined || raw === null || typeof raw !== \"object\") {\n return { config, collections: undefined };\n }\n const colsRaw = (raw as { collections?: unknown }).collections;\n if (colsRaw === undefined || colsRaw === null || typeof colsRaw !== \"object\") {\n return { config, collections: undefined };\n }\n\n const out: LoadedCollection[] = [];\n for (const [name, decl] of Object.entries(colsRaw as Record<string, unknown>)) {\n if (decl === null || typeof decl !== \"object\") {\n continue;\n }\n const indexes = (decl as { indexes?: unknown }).indexes;\n if (!Array.isArray(indexes)) {\n out.push({ name, indexes: [] });\n continue;\n }\n // Pass-through cast: the runtime IndexDefinition validation\n // lives in `@baerly/server`; the doctor only reads `name`, `on`,\n // and `predicate`, so a partial shape still gives an actionable\n // finding rather than a SchemaError throw at config-load time.\n out.push({ name, indexes: indexes as readonly IndexDefinition[] });\n }\n return { config, collections: out };\n};\n\n/**\n * Load the declared `IndexDefinition[]` for a single collection from a\n * `baerly.config.{js,mjs,json}`. Used by `baerly inspect` (key-count\n * probes) and `baerly admin rebuild-index` (resolving the `on` field).\n *\n * `.ts` configs are rejected — Node can't `import` them without a TS\n * loader; point at the compiled `.js` output instead.\n *\n * `commandName` is woven into thrown error messages so the operator\n * sees the calling command name in the prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — `.ts` extension, JSON\n * parse error, missing default export, or missing\n * `collections[collection]`.\n */\nexport const loadCollectionIndexes = async (\n configPath: string,\n collection: string,\n commandName: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const abs = configPath.startsWith(\"file://\") ? fileURLToPath(configPath) : resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `${commandName}: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n return cfg.collections?.[collection]?.indexes ?? [];\n};\n"],"mappings":";;;;;;;;;;AA0DA,MAAa,4BAAoC;;;;;;;;AA+DjD,MAAa,4BAAoC;;;;;;;;;;;;;;;;AA4HjD,MAAa,qBAAqB,CAAC,QAAQ,eAAe;;;;;AAoB1D,MAAa,gCACX;;;;;;;;;;;;;;;;;;;;;;;;ACpNF,MAAM,mBAAsC;CAC1C;CACA;CACA;CACA;AACF;;;;;;;;AASA,MAAa,gBAAgB,QAA+B;CAC1D,KAAK,MAAM,QAAQ,kBAAkB;EACnC,MAAM,MAAM,QAAQ,KAAK,IAAI;EAC7B,IAAI,WAAW,GAAG,GAChB,OAAO;CAEX;CACA,OAAO;AACT;;;;;;;;;;AAWA,MAAa,gBAAgB,OAAO,MAAc,QAAQ,IAAI,MAA0B;CACtF,MAAM,UAAU,aAAa,GAAG;CAChC,IAAI,YAAY,MACd,MAAM,IAAI,YACR,iBACA,gDAAgD,IAAI,qCACtD;CAGF,IAAI;CACJ,IAAI,QAAQ,SAAS,OAAO,GAAG;EAC7B,IAAI;EACJ,IAAI;GACF,OAAO,MAAM,SAAS,SAAS,MAAM;EACvC,SAAS,OAAO;GACd,MAAM,IAAI,YACR,iBACA,0BAA0B,QAAQ,IAAK,MAAgB,WACvD,KACF;EACF;EACA,IAAI;GACF,MAAM,KAAK,MAAM,IAAI;EACvB,SAAS,OAAO;GACd,MAAM,IAAI,YACR,iBACA,2BAA2B,QAAQ,IAAK,MAAgB,WACxD,KACF;EACF;CACF,OAAO;EACL,IAAI;EACJ,IAAI;GACF,MAAO,MAAM,OAAO,cAAc,OAAO,EAAE;EAC7C,SAAS,OAAO;GACd,MAAM,OAAO,QAAQ,SAAS,KAAK,IAC/B,6GACA;GACJ,MAAM,IAAI,YACR,iBACA,0BAA0B,QAAQ,IAAK,MAAgB,UAAU,QACjE,KACF;E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@@
|
|
|
1
|
-
{"version":3,"file":"current-json-BkatBzF7.js","names":[],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/constants.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n","/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * MIME type written for `gc/pending.json` PUTs.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Default grace period between \"marking\" a key for GC and \"sweeping\"\n * (deleting) it. 7 days, chosen to span the worst plausible writer-\n * retry window (a paused-process writer that resumes hours later\n * should still find its idempotency anchor on the bucket). The\n * `runGc()` function accepts an override for tests.\n *\n * Why 7 days specifically:\n * - **1 day is too aggressive for batch workloads.** Worker isolate\n * scheduling pauses, cross-region replication lag, and\n * {@link RATE_LIMIT_BACKOFF_MILLIS} retry cascades can plausibly\n * exceed an hour under pathological conditions.\n * - **30 days is conservative beyond the worst plausible pause.**\n * Doubles `gc/pending.json` size at steady state and slows\n * visibility into \"did GC actually run?\" by 4×.\n * - **7 days spans the realistic upper bound** — long-running batch\n * jobs, multi-region propagation delays, queue backlogs, and\n * downstream outages the writer is retrying through. The protocol\n * is unaffected by the choice of value within the [hours, weeks]\n * range; this constant is the operator-tunable knob.\n *\n * Production code MUST NOT call `runGc` with `graceMillis` below the\n * default outside maintenance windows — going below the longest\n * plausible writer-retry latency risks deleting an anchor a writer\n * is about to find on retry. Test code that sets `graceMillis: 0` is\n * exercising the sweep path deliberately, not modelling production.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_GRACE_PERIOD_MILLIS: number = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Cap on candidates kept in `gc/pending.json` to bound the size of\n * the file. The compactor marks at most this many candidates per\n * pass; subsequent passes pick up the rest. Larger collections will\n * lag GC by one pass per `GC_MAX_PENDING_CANDIDATES` orphans, which\n * is acceptable.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_MAX_PENDING_CANDIDATES: number = 1000;\n\n/**\n * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<next_seq>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Three Class A ops: PUT content, PUT log entry, CAS-advance\n * `current.json`. The cost-model page derives the free-tier write\n * budget from this multiplier; the phase-5 end-to-end test asserts it\n * at CI time. Changing this constant is a cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 3;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","/**\n * `current.json` — the per-collection CAS-protected control object — and\n * its embedded {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps\n * snapshot generations by CAS-writing this object; the\n * Writer reads it on every commit to find the snapshot\n * pointer; the sweeper reads `writer_fence` to decide which log\n * entries are eligible for GC.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION} to `2`; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `1`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 1;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Sequence number of the next log entry. Monotonic per\n * collection. The Writer reads this on commit to mint the\n * next log filename; CAS-write back with `next_seq + 1` ensures\n * no two writers pick the same sequence.\n */\n next_seq: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, next_seq)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= next_seq`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and\n * is not consumed by any ticket in this batch.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. The mechanism is the same in all three: every commit\n * checks the epoch on the control object; an entry stamped with\n * a stale epoch is discarded at replay.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Triggers per design: (a) detected\n * CAS conflict the writer wants to claim through, (b) admin\n * rotation. The sweeper discards log entries whose stamped epoch\n * is `< current.writer_fence.epoch`.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the write fence by bumping `epoch` and stamping\n * `claimed_at` from `StoragePutResult.serverDate`. The common call\n * site is \"I detected a CAS conflict during a commit and want to\n * claim the fence before retrying\"; admin rotation is the other call\n * site.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, next_seq)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing — readers\n * never silently accept an unknown shape.\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; expected ${CURRENT_JSON_SCHEMA_VERSION}`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n if (typeof r[\"next_seq\"] !== \"number\" || !Number.isInteger(r[\"next_seq\"]) || r[\"next_seq\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: next_seq must be a non-negative integer`,\n );\n }\n if (\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"next_seq\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > next_seq ${String(r[\"next_seq\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,KAAK,CAAC;AAEhD,MAAa,mBAAgC,UAC3C,KAAK,MAAM,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;;;;;;;ACiD5C,MAAa,4BAAoC;;;;;;;;AA+DjD,MAAa,4BAAoC;;;;;;AAoBjD,MAAa,0BAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B/C,MAAa,yBAAiC,QAAc,KAAK;;;;;;;;;;AAWjE,MAAa,4BAAoC;;;;;;;;;;AAWjD,MAAa,kCAA0C;;;;;;;;;;;;;;;;AAiBvD,MAAa,uBAA4C,IAAI,IAAI;CAC/D;CACA;CACA;AACF,CAAC;;;;;;;;;;;;AA2CD,MAAa,6BACX;;;;;AAMF,MAAa,gCACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC9FF,eAAsB,gBACpB,SACA,KACA,MACiC;CACjC,MAAM,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI;CACvC,IAAI,QAAQ,MACV,OAAO;CAET,MAAM,OAAO,IAAI,YAAY,EAAE,OAAO,IAAI,IAAI;CAC9C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,IAAI;CAC1B,SAAS,OAAO;EACd,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,2BACvB,KACF;CACF;CACA,OAAO;EAAE,MAAM,kBAAkB,QAAQ,GAAG;EAAG,MAAM,IAAI;CAAK;AAChE;;;;;;;;;;;AAYA,eAAsB,kBACpB,SACA,KACA,SACA,MAC0B;CAE1B,kBAAkB,SAAS,GAAG;CAC9B,MAAM,OAAO,WAAW,OAAO;CAC/B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M,IAAI,YAAY,mBAAmB,mBAAmB,IAAI,uBAAuB;CAEzF,MAAM,IAAI;CACV,IAAI,OAAO,EAAE,aAAa,YAAY,CAAC,OAAO,UAAU,EAAE,QAAQ,KAAK,EAAE,WAAW,GAClF,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,oDACzB;CAEF,IAAI,OAAO,EAAE,aAAa,UACxB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,sCACzB;CAEF,IAAI,OAAO,EAAE,kBAAkB,UAC7B,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,2CACzB;CAEF,IAAI,EAAE,mBAAmB,KAAA,KAAa,OAAO,EAAE,mBAAmB,UAChE,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,qDACzB;CAEF,OAAO;AACT;;;;;;;;AASA,MAAM,qBAAqB,GAAY,QAA6B;CAClE,IAAI,aAAa,eAAe,EAAE,SAAS,YACzC,OAAO,IAAI,YAAY,YAAY,4BAA4B,IAAI,IAAI,EAAE,WAAW,CAAC;CAEvF,IAAI,aAAa,aACf,OAAO;CAET,OAAO,IAAI,YAAY,mBAAmB,yBAAyB,IAAI,WAAW,OAAO,CAAC,KAAK,CAAC;AAClG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"doctor-B8h9GCN9.js","names":[],"sources":["../packages/cli/src/doctor/cloudflare.ts","../packages/cli/src/doctor.ts"],"sourcesContent":["/**\n * `baerly doctor --target=cloudflare` — walks the Cloudflare\n * deploy invariants and reports. With `--fix`, remediates what\n * can be safely auto-fixed (R2 bucket creation; secret prompts\n * are still user-driven because `wrangler secret put` reads\n * stdin interactively).\n *\n * Checks (each emitting one {@link DoctorFinding}):\n * 1. `wrangler.jsonc` exists at the package root.\n * 2. Each declared R2 binding exists in CF\n * (`wrangler r2 bucket info`).\n * 3. Each `requiredSecrets` entry is in `wrangler secret list`.\n * 4. If `cloudflareAccess` is set in `baerly.config.ts`,\n * `audienceTag` is 64 lowercase-hex chars and `teamDomain`\n * is non-empty.\n * 5. If `triggers.crons` is empty, warn that the maintenance\n * loop won't run.\n * 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`\n * doesn't declare a matching `routes` entry, warn.\n *\n * Output is a structured {@link DoctorReport} that\n * `packages/cli/src/doctor.ts` renders as either a checklist\n * (text mode) or a JSON envelope (`--json` mode).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parse, type ParseError } from \"jsonc-parser\";\nimport { BaerlyError, SHARED_SECRET_MISSING_MESSAGE } from \"@baerly/protocol\";\nimport type { AppConfig } from \"../config.ts\";\nimport { ensureBindings, parseR2Bindings, type ProcessRunner } from \"../deploy/cloudflare.ts\";\n\n/** One finding from a `baerly doctor` walk. */\nexport interface DoctorFinding {\n /** Severity. `ok` / `info` don't move the overall status. */\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n /** Short check name — stable, machine-readable. */\n readonly check: string;\n /** Human-friendly description. */\n readonly message: string;\n /** Optional remediation hint. */\n readonly fix?: string;\n}\n\n/** Result of a `baerly doctor` walk. */\nexport interface DoctorReport {\n readonly findings: readonly DoctorFinding[];\n /**\n * Overall: `ok` only when every finding has severity `ok` or\n * `info`. `warning` when the worst finding is a warning. `error`\n * when any finding is an error.\n */\n readonly status: \"ok\" | \"warning\" | \"error\";\n}\n\nconst rollupStatus = (findings: readonly DoctorFinding[]): DoctorReport[\"status\"] => {\n let worst: DoctorReport[\"status\"] = \"ok\";\n for (const f of findings) {\n if (f.severity === \"error\") {\n return \"error\";\n }\n if (f.severity === \"warning\") {\n worst = \"warning\";\n }\n }\n return worst;\n};\n\n/**\n * Read the declared cron schedule from `wrangler.jsonc`. Returns\n * `[]` when missing — caller treats empty as a warning.\n */\nconst readDeclaredCrons = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { triggers?: { crons?: unknown } }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const crons = obj.triggers?.crons;\n if (!Array.isArray(crons)) {\n return [];\n }\n return crons.filter((c): c is string => typeof c === \"string\");\n};\n\n/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */\nconst readDeclaredRoutePatterns = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { routes?: unknown }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const routes = obj.routes;\n if (!Array.isArray(routes)) {\n return [];\n }\n return routes\n .map((r) =>\n r !== null && typeof r === \"object\" ? (r as { pattern?: unknown }).pattern : undefined,\n )\n .filter((p): p is string => typeof p === \"string\");\n};\n\n/** Read declared `vars` keys from `wrangler.jsonc`. */\nconst readDeclaredVarKeys = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { vars?: Record<string, unknown> }\n | undefined;\n if (errors.length > 0 || obj === undefined || obj.vars === undefined) {\n return [];\n }\n return Object.keys(obj.vars);\n};\n\n/**\n * Walk the Cloudflare deploy invariants. With `opts.fix === true`,\n * remediate the auto-fixable issues (bucket creation). Secret\n * prompts stay user-driven.\n */\nexport const doctorCloudflare = async (\n config: AppConfig,\n opts: {\n readonly runner?: ProcessRunner;\n readonly fix?: boolean;\n readonly cwd?: string;\n } = {},\n): Promise<DoctorReport> => {\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = resolve(repoRoot, \"wrangler.jsonc\");\n const findings: DoctorFinding[] = [];\n\n // 1. wrangler.jsonc presence.\n if (!existsSync(wranglerPath)) {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc\",\n message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,\n fix: \"Re-scaffold (npm create baerly@latest) or restore the file from git.\",\n });\n return { findings, status: rollupStatus(findings) };\n }\n findings.push({\n severity: \"ok\",\n check: \"wrangler.jsonc\",\n message: `${wranglerPath} found.`,\n });\n\n // 2. R2 bindings — parse first, then probe each.\n let declared: readonly { binding: string; bucket_name: string }[];\n try {\n declared = parseR2Bindings(wranglerPath);\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"InvalidConfig\") {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc.parse\",\n message: error.message,\n });\n return { findings, status: rollupStatus(findings) };\n }\n throw error;\n }\n\n if (opts.fix === true && opts.runner !== undefined) {\n // Run the same provisioning path the deploy fallback uses.\n // Any failure here surfaces as an error finding rather than\n // throwing — doctor's job is to report.\n try {\n await ensureBindings(opts.runner, repoRoot, wranglerPath);\n } catch (error) {\n findings.push({\n severity: \"error\",\n check: \"r2.fix\",\n message: error instanceof Error ? error.message : \"unknown error during ensureBindings\",\n });\n }\n }\n\n if (opts.runner !== undefined) {\n for (const { bucket_name } of declared) {\n const info = await opts.runner.run(\n \"wrangler\",\n [\"r2\", \"bucket\", \"info\", bucket_name],\n repoRoot,\n );\n if (info.code === 0) {\n findings.push({\n severity: \"ok\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" exists.`,\n });\n } else {\n findings.push({\n severity: \"error\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" not found.`,\n fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`,\n });\n }\n }\n } else {\n findings.push({\n severity: \"info\",\n check: \"r2.skip\",\n message: \"no runner supplied; skipped R2 bucket probes.\",\n });\n }\n\n // 3. requiredSecrets — best-effort.\n //\n // `configured` is lifted to the outer scope so the auth-posture\n // block below can read the deployed secret set without re-running\n // `wrangler secret list`. Empty when the runner is absent or the\n // listing call failed.\n const required = config.requiredSecrets ?? [\"SHARED_SECRET\"];\n let configured: readonly string[] = [];\n if (opts.runner !== undefined && required.length > 0) {\n const r = await opts.runner.run(\"wrangler\", [\"secret\", \"list\"], repoRoot);\n if (r.code !== 0) {\n findings.push({\n severity: \"warning\",\n check: \"secrets\",\n message: \"could not list secrets (wrangler exit non-zero); skipping check.\",\n });\n } else {\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (Array.isArray(parsed)) {\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n }\n } catch {\n // fall through with empty configured set\n }\n for (const name of required) {\n if (configured.includes(name)) {\n findings.push({\n severity: \"ok\",\n check: `secret.${name}`,\n message: `secret ${name} is set.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check: `secret.${name}`,\n message: `secret ${name} is required but unset.`,\n fix: `wrangler secret put ${name}`,\n });\n }\n }\n }\n } else if (required.length > 0) {\n findings.push({\n severity: \"info\",\n check: \"secrets.skip\",\n message: \"no runner supplied; skipped secret checks.\",\n });\n }\n\n // 7. config.auth — graduated-auth posture. Walks the typed `auth`\n // field added in `packages/protocol/src/app-config.ts`.\n // FAIL: shared-secret without SHARED_SECRET set on the worker.\n // WARN: auth: \"none\" + deploy target (operator may have a\n // network gate in front; surface it so they confirm).\n // INFO: CF Access vars present + adapter uses config.auth (auth\n // is using config.auth, CF Access env is inert).\n //\n // The presence of the typed field is guaranteed by the loader\n // (config.ts throws on omission), so we walk every loaded config\n // without an existence guard.\n if (config.auth === \"none\") {\n // Deploy-target check: \"cloudflare\" / \"node\" are the only valid\n // values, and both ship to a network-reachable runtime. We warn\n // unconditionally — the doctor's job is to surface the choice,\n // not to second-guess whether the operator's network seam (CF\n // Access, intranet ACL, Tunnel) is upstream.\n findings.push({\n severity: \"warning\",\n check: \"auth.none-on-deploy\",\n message:\n `baerly.config.ts has auth: \"none\" and ships to target=${JSON.stringify(config.target)}. ` +\n \"Every request will resolve to config.tenant with no header check. \" +\n \"Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) \" +\n 'or change `auth` to \"shared-secret\" or pass a custom `verifier:` on the adapter factory.',\n fix:\n 'Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; ' +\n 'or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`.',\n });\n }\n\n if (config.auth === \"shared-secret\" && opts.runner !== undefined) {\n // Mirror the FAIL message wording from the adapter's runtime\n // throw. Locked via `SHARED_SECRET_MISSING_MESSAGE` so doctor +\n // adapter stay in sync.\n //\n // If `configured` is still empty here, the `wrangler secret list`\n // invocation either failed (we already warned with the \"secrets\"\n // finding above) or really lists no secrets. Either way the\n // operator-facing remediation is the same.\n const requiredSecret = \"SHARED_SECRET\";\n if (!configured.includes(requiredSecret)) {\n findings.push({\n severity: \"error\",\n check: \"auth.shared-secret-missing\",\n message: SHARED_SECRET_MISSING_MESSAGE,\n fix:\n \"wrangler secret put SHARED_SECRET (for production) \" +\n \"or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`).\",\n });\n }\n }\n\n // INFO: CF Access env vars in wrangler.jsonc:vars but the adapter\n // is using `config.auth` for the verifier (so the env values are\n // inert). We can't statically parse the user's worker source —\n // surface the heuristic.\n const varKeys = new Set(readDeclaredVarKeys(wranglerPath));\n if (\n varKeys.has(\"CF_ACCESS_TEAM_DOMAIN\") &&\n varKeys.has(\"CF_ACCESS_AUDIENCE_TAG\")\n ) {\n findings.push({\n severity: \"info\",\n check: \"auth.cf-access-inert\",\n message:\n `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} ` +\n `but the adapter uses config.auth=${JSON.stringify(config.auth)}. ` +\n `To wire CF Access, pass \\`verifier: cloudflareAccess({ teamDomain, audienceTag })\\` on the baerlyWorker factory.`,\n });\n }\n\n // 4. cloudflareAccess — when configured, audience tag must be\n // 64 lowercase-hex chars.\n if (config.cloudflareAccess !== undefined) {\n const { teamDomain, audienceTag } = config.cloudflareAccess;\n if (teamDomain.length === 0) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.teamDomain\",\n message: \"cloudflareAccess.teamDomain in baerly.config.ts is empty.\",\n });\n }\n if (!/^[0-9a-f]{64}$/.test(audienceTag)) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.audienceTag\",\n message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,\n fix: \"Copy the AUD tag from the Cloudflare Access app's configuration tab.\",\n });\n } else if (teamDomain.length > 0) {\n findings.push({\n severity: \"ok\",\n check: \"cloudflareAccess\",\n message: `cloudflareAccess audience tag is well-formed; team domain \"${teamDomain}\".`,\n });\n }\n }\n\n // 5. Cron triggers — empty list means the maintenance loop won't\n // run.\n const crons = readDeclaredCrons(wranglerPath);\n if (crons.length === 0) {\n findings.push({\n severity: \"warning\",\n check: \"triggers.crons\",\n message: \"no cron triggers declared; the maintenance loop will not run automatically.\",\n fix: `Add \"triggers\": { \"crons\": [\"* * * * *\"] } to ${wranglerPath}.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"triggers.crons\",\n message: `cron trigger${crons.length === 1 ? \"\" : \"s\"} ${crons.map((c) => JSON.stringify(c)).join(\", \")} declared.`,\n });\n }\n\n // 6. domain ↔ routes coherence.\n if (config.domain !== undefined && config.domain.length > 0) {\n const patterns = readDeclaredRoutePatterns(wranglerPath);\n const expectedPrefix = `${config.domain}/`;\n const hasMatch = patterns.some(\n (p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix),\n );\n if (!hasMatch) {\n findings.push({\n severity: \"warning\",\n check: \"routes.domain\",\n message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,\n fix: `Add { \"pattern\": \"${config.domain}/*\", \"custom_domain\": true } to wrangler.jsonc:routes.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"routes.domain\",\n message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`,\n });\n }\n }\n\n return { findings, status: rollupStatus(findings) };\n};\n","/**\n * `baerly doctor` — citty dispatcher for deploy-invariant checks.\n *\n * Reads `baerly.config.ts:target` and routes to\n * {@link doctorCloudflare}. The Node target self-validates at\n * scaffold time — the example IS the contract — so it has no\n * doctor backend.\n *\n * Read-only target-invariant checks only. Drift detection, index\n * rebuilds, and writes/min health are separate verbs:\n * - `baerly admin fsck --indexes [--fix]` — index drift.\n * - `baerly admin usage` — writes/min M-size graduation.\n * - `baerly admin rebuild-index` — single-index reconciliation.\n *\n * Renders the returned {@link DoctorReport} into either a\n * stdout checklist (text mode) or a JSON envelope (`--json`\n * mode).\n *\n * Exit-code contract (mirrors `baerly deploy`):\n * - 0 success — report status is `ok` or `warning`.\n * - 1 user error (InvalidConfig, unknown target, missing config).\n * - 2 storage / external error.\n * - 3 protocol invariant.\n *\n * A `warning` status returns exit 0 (the user can deploy; we just\n * flagged a maintenance / coherence issue). An `error` status\n * returns exit 2 unless the underlying cause was an InvalidConfig\n * (which already returned 1 via a thrown BaerlyError).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { doctorCloudflare, type DoctorReport } from \"./doctor/cloudflare.ts\";\nimport { defaultRunner } from \"./runner.ts\";\nimport { color, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst DOCTOR_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).',\n valueHint: \"cloudflare\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst colorize = (severity: string, glyph: string): string => {\n if (severity === \"error\") {\n return color.red(glyph);\n }\n if (severity === \"warning\") {\n return color.yellow(glyph);\n }\n if (severity === \"info\") {\n return color.dim(glyph);\n }\n return glyph;\n};\n\nconst renderReport = (target: string, report: DoctorReport): void => {\n if (isJsonMode()) {\n process.stdout.write(\n `${JSON.stringify({ result: { command: \"doctor\", target, ...report } })}\\n`,\n );\n return;\n }\n process.stdout.write(`baerly doctor --target=${target}\\n\\n`);\n let okCount = 0;\n let warningCount = 0;\n let errorCount = 0;\n for (const f of report.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? \"•\";\n process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\\n`);\n if (f.fix !== undefined) {\n process.stdout.write(` fix: ${f.fix}\\n`);\n }\n if (f.severity === \"ok\") {\n okCount += 1;\n } else if (f.severity === \"warning\") {\n warningCount += 1;\n } else if (f.severity === \"error\") {\n errorCount += 1;\n }\n }\n process.stdout.write(\n `\\nStatus: ${errorCount} error${errorCount === 1 ? \"\" : \"s\"}, ${warningCount} warning${warningCount === 1 ? \"\" : \"s\"}, ${okCount} ok.\\n`,\n );\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"doctor\",\n meta: {\n description:\n \"Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target.\",\n },\n args: DOCTOR_ARGS,\n handler: async (args) => {\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const report = await doctorCloudflare(config, {\n runner: defaultRunner(),\n ...(args.fix === true && { fix: true }),\n });\n renderReport(target, report);\n return report.status === \"error\" ? 2 : 0;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. ` +\n `(Node variants self-validate at scaffold time; the example IS the contract.)`,\n );\n },\n});\n\n/** citty `defineCommand` block for `baerly doctor`. */\nexport const doctor = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDoctor = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,gBAAgB,aAA+D;CACnF,IAAI,QAAgC;CACpC,KAAK,MAAM,KAAK,UAAU;EACxB,IAAI,EAAE,aAAa,SACjB,OAAO;EAET,IAAI,EAAE,aAAa,WACjB,QAAQ;CAEZ;CACA,OAAO;AACT;;;;;AAMA,MAAM,qBAAqB,iBAA4C;CACrE,MAAM,OAAO,aAAa,cAAc,MAAM;CAC9C,MAAM,SAAuB,CAAC;CAC9B,MAAM,MAAM,MAAM,MAAM,QAAQ;EAAE,oBAAoB;EAAM,kBAAkB;CAAM,CAAC;CAGrF,IAAI,OAAO,SAAS,KAAK,QAAQ,KAAA,GAC/B,OAAO,CAAC;CAEV,MAAM,QAAQ,IAAI,UAAU;CAC5B,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,OAAO,CAAC;CAEV,OAAO,MAAM,QAAQ,MAAmB,OAAO,MAAM,QAAQ;AAC/D;;AAGA,MAAM,6BAA6B,iBAA4C;CAC7E,MAAM,OAAO,aAAa,cAAc,MAAM;CAC9C,MAAM,SAAuB,CAAC;CAC9B,MAAM,MAAM,MAAM,MAAM,QAAQ;EAAE,oBAAoB;EAAM,kBAAkB;CAAM,CAAC;CAGrF,IAAI,OAAO,SAAS,KAAK,QAAQ,KAAA,GAC/B,OAAO,CAAC;CAEV,MAAM,SAAS,IAAI;CACnB,IAAI,CAAC,MAAM,QAAQ,MAAM,GACvB,OAAO,CAAC;CAEV,OAAO,OACJ,KAAK,MACJ,MAAM,QAAQ,OAAO,MAAM,WAAY,EAA4B,UAAU,KAAA,CAC/E,EACC,QAAQ,MAAmB,OAAO,MAAM,QAAQ;AACrD;;AAGA,MAAM,uBAAuB,iBAA4C;CACvE,MAAM,OAAO,aAAa,cAAc,MAAM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AAK,OAAO,UAAU;EAC/B,MAAM,QAAQ,eAAe,EAAE,aAAa;EAC5C,QAAQ,OAAO,MAAM,KAAK,SAAS,EAAE,UAAU,KAAK,EAAE,GAAG,EAAE,QAAQ,GAAG;EACtE,IAAI,EAAE,QAAQ,KAAA,GACZ,QAAQ,OAAO,MAAM,aAAa,EAAE,IAAI,GAAG;EAE7C,IAAI,EAAE,aAAa,MACjB,WAAW;OACN,IAAI,EAAE,aAAa,WACxB,gBAAgB;OACX,IAAI,EAAE,aAAa,SACxB,cAAc;CAElB;CACA,QAAQ,OAAO,MACb,aAAa,WAAW,QAAQ,eAAe,IAAI,KAAK,IAAI,IAAI,aAAa,UAAU,iBAAiB,IAAI,KAAK,IAAI,IAAI,QAAQ,OACnI;AACF;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aACE,yFACJ;CACA,MAAM;CACN,SAAS,OAAO,SAAS;EACvB,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,SAAS,MAAM,iBAAiB,QAAQ;IAC5C,QAAQ,cAAc;IACtB,GAAI,KAAK,QAAQ,QAAQ,EAAE,KAAK,KAAK;GACvC,CAAC;GACD,aAAa,QAAQ,MAAM;GAC3B,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,qGAElD;CACF;AACF,CAAC;;AAGD,MAAa,SAAS,OAAO;AAOJ,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fsck-DEz9lyCy.js","names":[],"sources":["../packages/cli/src/admin/fsck.ts"],"sourcesContent":["/**\n * `baerly admin fsck` — consistency walk for one collection.\n *\n * Default mode (no `--indexes`): read-only checks against the\n * snapshot + log tail.\n * 1. `current.json` exists at the expected key and parses.\n * 2. When `current.snapshot !== null`, the snapshot body's\n * SHA-256 matches the hash embedded in the filename\n * (delegated to `loadSnapshotAsMap`).\n * 3. The log range `[log_seq_start, next_seq)` has no holes —\n * every `log/<seq>.json` is present (HEAD-cheap LIST scan).\n * 4. Every entry inside the live tail is well-formed JSON with\n * the locked `op`, `collection`, `doc_id`, `schema_version`\n * fields.\n *\n * `--indexes` + `--config=<path>` mode: SKIP the snapshot + log\n * walks and ONLY check each declared index for drift via\n * `rebuildIndex(..., { dryRun: true })`. Drift is `(added > 0)`\n * (rows that should be projected but have no key on storage) or\n * `(removed > 0)` (orphan keys for rows that no longer match).\n * Read-only.\n *\n * `--indexes --fix`: same drift walk but with `dryRun: false`, so\n * `rebuildIndex` PUTs missing keys and DELETEs orphans. The findings\n * downgrade from `warning` to `info` (drift was found AND fixed in\n * one pass). `--fix` without `--indexes` is rejected — fsck has no\n * auto-fix outside the index check.\n *\n * Exit codes:\n * 0 — all checks pass.\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag,\n * `--fix` without `--indexes`).\n * 2 — Storage / Network error during the walk.\n * 3 — Protocol invariant violation surfaced by the kernel\n * (Internal / InvalidResponse) — distinguished from exit 4\n * so CI can wire fsck as a regression gate.\n * 4 — One or more findings (orphan / hole / hash-mismatch /\n * index drift). Unique to this command; the other\n * `baerly admin` subcommands reserve 0–3.\n */\n\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { type ArgsDef } from \"citty\";\nimport {\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"@baerly/server\";\nimport { rebuildIndex } from \"@baerly/server/maintenance\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst FSCK_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n config: {\n type: \"string\",\n required: false,\n description:\n \"Path to baerly.config.{js,mjs,json}. Required with --indexes; resolves index definitions.\",\n valueHint: \"path\",\n },\n indexes: {\n type: \"boolean\",\n description:\n \"Skip snapshot + log walks; check declared indexes for drift via rebuildIndex (read-only by default).\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"With --indexes, rebuild drifted indexes (PUT missing keys, DELETE orphans). Rejected without --indexes.\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\ntype Severity = \"ok\" | \"info\" | \"warning\" | \"finding\";\ninterface Finding {\n readonly severity: Severity;\n readonly check: string;\n readonly message: string;\n readonly key?: string;\n}\n\n/** Severities that count toward the exit-4 \"findings present\" status. */\nconst isFindingSeverity = (s: Severity): boolean => s === \"finding\" || s === \"warning\";\n\nconst loadConfigIndexes = async (\n configPath: string,\n collection: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const { readFile } = await import(\"node:fs/promises\");\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const pathMod = await import(\"node:path\");\n const abs = configPath.startsWith(\"file://\")\n ? fileURLToPath(configPath)\n : pathMod.resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n const def = cfg.collections?.[collection];\n return def?.indexes ?? [];\n};\n\nconst listKeys = async (storage: Storage, prefix: string): Promise<string[]> => {\n const out: string[] = [];\n for await (const entry of storage.list(prefix)) {\n out.push(entry.key);\n }\n return out.toSorted();\n};\n\nconst statusLine = (label: string, ok: boolean, detail: string): string =>\n ` ${label.padEnd(22)}${ok ? \"ok\" : \"error\"} ${detail}`.trimEnd();\n\ninterface IndexSummary {\n readonly name: string;\n readonly added: number;\n readonly removed: number;\n readonly kept: number;\n readonly rebuilt: boolean;\n}\n\nconst renderSnapshotLog = (\n collection: string,\n findings: readonly Finding[],\n context: {\n readonly logRange: readonly [number, number];\n readonly logEntriesPresent: number;\n readonly snapshotKey: string | null;\n },\n): string => {\n const lines: string[] = [];\n lines.push(`baerly admin fsck ${collection}`);\n const [from, toExcl] = context.logRange;\n const byCheck = new Map<string, Finding[]>();\n for (const f of findings) {\n const arr = byCheck.get(f.check) ?? [];\n arr.push(f);\n byCheck.set(f.check, arr);\n }\n lines.push(statusLine(\"current.json:\", (byCheck.get(\"current.json\") ?? []).length === 0, \"\"));\n lines.push(\n statusLine(\n \"snapshot hash:\",\n (byCheck.get(\"snapshot\") ?? []).length === 0,\n context.snapshotKey === null ? \"(no snapshot yet)\" : `(sha256 verified)`,\n ),\n );\n lines.push(\n statusLine(\n `log range [${from},${toExcl}):`,\n (byCheck.get(\"log\") ?? []).length === 0,\n `(${context.logEntriesPresent}/${toExcl - from} entries present)`,\n ),\n );\n lines.push(` status: ${findings.some(isFindingFinding) ? \"findings\" : \"ok\"}`);\n for (const f of findings) {\n lines.push(` ${f.check}: ${f.message}${f.key !== undefined ? ` (key=${f.key})` : \"\"}`);\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst renderIndexes = (\n collection: string,\n findings: readonly Finding[],\n summaries: readonly IndexSummary[],\n fix: boolean,\n): string => {\n const lines: string[] = [];\n lines.push(`baerly admin fsck ${collection} --indexes${fix ? \" --fix\" : \"\"}`);\n for (const s of summaries) {\n const verb = s.rebuilt ? \"rebuilt\" : \"would rebuild\";\n if (s.added === 0 && s.removed === 0) {\n lines.push(` ${s.name}: in sync (${s.kept} keys)`);\n } else {\n lines.push(` ${s.name}: ${verb} — added ${s.added}, removed ${s.removed}, kept ${s.kept}`);\n }\n }\n lines.push(` status: ${findings.some(isFindingFinding) ? \"findings\" : \"ok\"}`);\n for (const f of findings) {\n if (f.check === \"log\" || f.check === \"snapshot\" || f.check === \"current.json\") {\n continue;\n }\n lines.push(` ${f.check}: ${f.message}${f.key !== undefined ? ` (key=${f.key})` : \"\"}`);\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst isFindingFinding = (f: Finding): boolean => isFindingSeverity(f.severity);\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.fsck\",\n meta: {\n description: \"Read-only consistency walk for one collection.\",\n },\n args: FSCK_ARGS,\n handler: async (args, ctx) => {\n const indexMode = args.indexes === true;\n const fixMode = args.fix === true;\n if (fixMode && !indexMode) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin fsck: --fix is only valid with --indexes (fsck has no auto-fix outside the index check)\",\n );\n }\n if (indexMode && (args.config === undefined || args.config.length === 0)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin fsck: --indexes requires --config=<path> to resolve index definitions\",\n );\n }\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const bucket = await parseBucketUri(args.bucket);\n const collectionPrefix = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}`;\n const currentJsonKey = `${collectionPrefix}/current.json`;\n\n const findings: Finding[] = [];\n\n if (indexMode) {\n // ── Index drift mode. ──────────────────────────────────────────\n // Skip snapshot + log walks. For each declared index, call\n // `rebuildIndex(..., { dryRun: !fix })` — it returns the\n // `(added, removed, kept)` triple we need to call drift.\n const defs = await loadConfigIndexes(args.config!, args.collection);\n const summaries: IndexSummary[] = [];\n for (const def of defs) {\n const check = `index.${def.name}`;\n let result;\n try {\n result = await rebuildIndex(bucket.storage, currentJsonKey, def, {\n dryRun: !fixMode,\n });\n } catch (error) {\n findings.push({\n severity: \"finding\",\n check,\n message: `${def.name}: drift check failed: ${(error as Error).message}`,\n });\n continue;\n }\n const summary: IndexSummary = {\n name: def.name,\n added: result.added,\n removed: result.removed,\n kept: result.kept,\n rebuilt: fixMode,\n };\n summaries.push(summary);\n const drifted = result.added > 0 || result.removed > 0;\n if (!drifted) {\n findings.push({\n severity: \"ok\",\n check,\n message: `${def.name}: in sync (${result.kept} keys).`,\n });\n } else if (fixMode) {\n findings.push({\n severity: \"info\",\n check,\n message: `${def.name}: rebuilt — added ${result.added}, removed ${result.removed}, kept ${result.kept}.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check,\n message: `${def.name}: drift detected — ${result.added} missing, ${result.removed} orphaned (${result.kept} in sync).`,\n });\n }\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.fsck\",\n status: findings.some(isFindingFinding) ? \"findings\" : \"ok\",\n collection: args.collection,\n mode: fixMode ? \"indexes-fix\" : \"indexes\",\n indexes: summaries,\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.key !== undefined && { key: f.key }),\n })),\n });\n } else {\n process.stdout.write(renderIndexes(args.collection, findings, summaries, fixMode));\n }\n return findings.some(isFindingFinding) ? 4 : 0;\n }\n\n // ── Default mode. current.json + snapshot + log walks. ─────────\n const read = await readCurrentJson(bucket.storage, currentJsonKey);\n if (read === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: current.json not found at ${currentJsonKey}`,\n );\n }\n const cur = read.json;\n const logFrom = cur.log_seq_start ?? 0;\n const logToExcl = cur.next_seq;\n const snapshotKey = cur.snapshot;\n\n // ── Snapshot hash verifies (loadSnapshotAsMap throws on mismatch). ──\n if (snapshotKey !== null) {\n try {\n await loadSnapshotAsMap(bucket.storage, snapshotKey, args.collection);\n } catch (error) {\n if (\n error instanceof BaerlyError &&\n (error.code === \"Internal\" || error.code === \"InvalidResponse\")\n ) {\n findings.push({\n severity: \"finding\",\n check: \"snapshot\",\n message: error.message,\n key: snapshotKey,\n });\n } else {\n throw error;\n }\n }\n }\n\n // ── Log range [from, toExcl) has no holes; entries well-formed. ──\n // LIST the log/ prefix; expect exactly `toExcl - from` keys named\n // `${from}.json` … `${toExcl - 1}.json`. Use a single LIST so the\n // op count is O(pages) not O(range).\n const logPrefix = `${collectionPrefix}/log/`;\n const presentKeys = await listKeys(bucket.storage, logPrefix);\n const presentSeqs = new Set<number>();\n for (const key of presentKeys) {\n const tail = key.slice(logPrefix.length);\n const match = /^(\\d+)\\.json$/.exec(tail);\n if (match === null) {\n continue;\n }\n const seq = Number.parseInt(match[1]!, 10);\n if (Number.isFinite(seq)) {\n presentSeqs.add(seq);\n }\n }\n let logEntriesPresent = 0;\n for (let s = logFrom; s < logToExcl; s++) {\n if (presentSeqs.has(s)) {\n logEntriesPresent++;\n } else {\n findings.push({\n severity: \"finding\",\n check: \"log\",\n message: `missing log entry at seq ${s} inside [log_seq_start, next_seq)`,\n key: `${logPrefix}${s}.json`,\n });\n }\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.fsck\",\n status: findings.some(isFindingFinding) ? \"findings\" : \"ok\",\n collection: args.collection,\n current_json_key: currentJsonKey,\n snapshot: snapshotKey,\n log_range: { from: logFrom, to_excl: logToExcl, present: logEntriesPresent },\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.key !== undefined && { key: f.key }),\n })),\n });\n } else {\n process.stdout.write(\n renderSnapshotLog(args.collection, findings, {\n logRange: [logFrom, logToExcl],\n logEntriesPresent,\n snapshotKey,\n }),\n );\n }\n return findings.some(isFindingFinding) ? 4 : 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin fsck`. */\nexport const fsckCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runFsck = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,YAAY;CAChB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aACE;EACF,WAAW;CACb;CACA,SAAS;EACP,MAAM;EACN,aACE;CACJ;CACA,KAAK;EACH,MAAM;EACN,aACE;CACJ;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;AACF;;AAWA,MAAM,qBAAqB,MAAyB,MAAM,aAAa,MAAM;AAE7E,MAAM,oBAAoB,OACxB,YACA,eACwC;CACxC,IAAI,WAAW,SAAS,KAAK,GAC3B,MAAM,IAAI,YACR,iBACA,0EAA0E,KAAK,UAAU,UAAU,EAAE,EACvG;CAEF,IAAI;CACJ,IAAI,WAAW,SAAS,OAAO,GAAG;EAChC,MAAM,EAAE,aAAa,MAAM,OAAO;EAClC,MAAM,OAAO,MAAM,SAAS,YAAY,MAAM;EAC9C,IAAI;GACF,MAAM,KAAK,MAAM,IAAI;EACvB,SAAS,OAAO;GACd,MAAM,IAAI,YACR,iBACA,mDAAmD,KAAK,UAAU,UAAU,EAAE,IAAK,MAAgB,SACrG;EACF;CACF,OAA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,MAAM,QAAQ,gBAAgB,KAAK,IAAI;GACvC,IAAI,UAAU,MACZ;GAEF,MAAM,MAAM,OAAO,SAAS,MAAM,IAAK,EAAE;GACzC,IAAI,OAAO,SAAS,GAAG,GACrB,YAAY,IAAI,GAAG;EAEvB;EACA,IAAI,oBAAoB;EACxB,KAAK,IAAI,IAAI,SAAS,IAAI,WAAW,KACnC,IAAI,YAAY,IAAI,CAAC,GACnB;OAEA,SAAS,KAAK;GACZ,UAAU;GACV,OAAO;GACP,SAAS,4BAA4B,EAAE;GACvC,KAAK,GAAG,YAAY,EAAE;EACxB,CAAC;EAIL,IAAI,WAAW,GACb,YAAY;GACV,SAAS;GACT,QAAQ,SAAS,KAAK,gBAAgB,IAAI,aAAa;GACvD,YAAY,KAAK;GACjB,kBAAkB;GAClB,UAAU;GACV,WAAW;IAAE,MAAM;IAAS,SAAS;IAAW,SAAS;GAAkB;GAC3E,UAAU,SAAS,KAAK,OAAO;IAC7B,UAAU,EAAE;IACZ,OAAO,EAAE;IACT,SAAS,EAAE;IACX,GAAI,EAAE,QAAQ,KAAA,KAAa,EAAE,KAAK,EAAE,IAAI;GAC1C,EAAE;EACJ,CAAC;OAED,QAAQ,OAAO,MACb,kBAAkB,KAAK,YAAY,UAAU;GAC3C,UAAU,CAAC,SAAS,SAAS;GAC7B;GACA;EACF,CAAC,CACH;EAEF,OAAO,SAAS,KAAK,gBAAgB,IAAI,IAAI;CAC/C;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOP,OAAO"}
|
package/dist/indexes-BXn7a06a.js
DELETED
|
@@ -1,297 +0,0 @@
|
|
|
1
|
-
import { o as encodeJsonBytes } from "./bucket-uri-BrDEYvzy.js";
|
|
2
|
-
import { n as matchesWire, t as validateWire } from "./validate-DhH1lO8I.js";
|
|
3
|
-
import { o as BaerlyError } from "./baerly.js";
|
|
4
|
-
//#region ../server/src/indexes.ts
|
|
5
|
-
/**
|
|
6
|
-
* Secondary indexes — declarative collection-config-driven
|
|
7
|
-
* index entries that the writer emits inside the same CAS fence as
|
|
8
|
-
* the log entry and content body.
|
|
9
|
-
*
|
|
10
|
-
* The {@link IndexDefinition} TYPE lives in `@baerly/protocol`
|
|
11
|
-
* (cross-platform). This module owns the runtime helpers that
|
|
12
|
-
* operate on that shape:
|
|
13
|
-
*
|
|
14
|
-
* - {@link validateIndexDefinition} — synchronous schema check
|
|
15
|
-
* for path-segment safety; thrown at `Writer` construction.
|
|
16
|
-
* - {@link encodeIndexValue} — value-order-preserving base-32 of a
|
|
17
|
-
* type-tagged byte stream (null/bool tag-only, numbers as sortable
|
|
18
|
-
* IEEE 754, strings as raw UTF-8, objects as `JSON.stringify`
|
|
19
|
-
* bytes for equality only).
|
|
20
|
-
* - {@link indexKeyFor} / {@link indexKeyPrefix} — the wire-key
|
|
21
|
-
* shape consumed by the writer's index PUTs and the rebuild
|
|
22
|
-
* command's idempotent reconciliation.
|
|
23
|
-
* - {@link projectIndexValues} / {@link allIndexKeysFor} — pure
|
|
24
|
-
* projections from a doc body to the set of index keys it
|
|
25
|
-
* produces under a collection's declared indexes.
|
|
26
|
-
*
|
|
27
|
-
* Wire shape (single-field):
|
|
28
|
-
*
|
|
29
|
-
* `<logPrefix>/index/<indexName>/<value-b32>/<docId>.json`
|
|
30
|
-
*
|
|
31
|
-
* Wire shape (composite — accepted by the encoder, not consulted by
|
|
32
|
-
* the read path today):
|
|
33
|
-
*
|
|
34
|
-
* `<logPrefix>/index/<indexName>/<a-b32>/<b-b32>/<docId>.json`
|
|
35
|
-
*
|
|
36
|
-
* Body is zero bytes. Each entry is a fact ("doc `<docId>` has
|
|
37
|
-
* `<field> = <value>`"), not data. Readers list the prefix, extract
|
|
38
|
-
* the doc id from each key, then issue a content GET on each.
|
|
39
|
-
*
|
|
40
|
-
* Encoding is RFC-4648 base-32 (lowercase alphabet `[0-9a-v]`,
|
|
41
|
-
* matching `packages/protocol/src/log.ts:str2uintDesc` style) on a
|
|
42
|
-
* type-tagged byte stream (see {@link encodeIndexValue}) so that:
|
|
43
|
-
*
|
|
44
|
-
* - String "5" and number 5 produce distinct encodings
|
|
45
|
-
* (type-tag prefix keeps the slots disjoint).
|
|
46
|
-
* - Equal-by-value inputs produce byte-equal segments.
|
|
47
|
-
* - Lex order under storage `list(prefix)` matches value order:
|
|
48
|
-
* `null < false < true < number < string < object`, with
|
|
49
|
-
* numeric values ordered by IEEE 754 magnitude (range walks
|
|
50
|
-
* and `$in` walks over numeric fields are first-class — no
|
|
51
|
-
* planner fall-back to full-scan).
|
|
52
|
-
*
|
|
53
|
-
* Locked: single-field indexes only on the read path. Composite
|
|
54
|
-
* shape is documented and reserved (the path encoder accepts it).
|
|
55
|
-
*
|
|
56
|
-
* @see docs/spec/sync-protocol.md — fence model these PUTs land
|
|
57
|
-
* inside (between log PUT and `current.json` CAS-advance).
|
|
58
|
-
*/
|
|
59
|
-
/** Path-safe segment name. */
|
|
60
|
-
const INDEX_NAME_RE = /^[a-z_][a-z0-9_]*$/;
|
|
61
|
-
/**
|
|
62
|
-
* Lowercase base-32 alphabet, RFC 4648 variant matching the
|
|
63
|
-
* `packages/protocol/src/log.ts:str2uintDesc` style (`[0-9a-v]`).
|
|
64
|
-
* Lex-order-preserving under storage `list(prefix)` semantics.
|
|
65
|
-
*/
|
|
66
|
-
const B32_ALPHABET = "0123456789abcdefghijklmnopqrstuv";
|
|
67
|
-
/**
|
|
68
|
-
* Reject malformed {@link IndexDefinition} shapes synchronously.
|
|
69
|
-
* Thrown at writer construction so a config typo trips before any
|
|
70
|
-
* write lands.
|
|
71
|
-
*
|
|
72
|
-
* @throws BaerlyError code="SchemaError" — `name` doesn't match
|
|
73
|
-
* `/^[a-z_][a-z0-9_]*$/`; `on` is the empty string or empty
|
|
74
|
-
* array.
|
|
75
|
-
*/
|
|
76
|
-
const validateIndexDefinition = (def) => {
|
|
77
|
-
if (!INDEX_NAME_RE.test(def.name)) throw new BaerlyError("SchemaError", `index.name must match /^[a-z_][a-z0-9_]*$/; got ${JSON.stringify(def.name)}`);
|
|
78
|
-
if (typeof def.on === "string") {
|
|
79
|
-
if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty`);
|
|
80
|
-
} else if (def.on.length === 0) throw new BaerlyError("SchemaError", `index ${def.name}.on must be non-empty array`);
|
|
81
|
-
if (def.predicate !== void 0) try {
|
|
82
|
-
validateWire(def.predicate);
|
|
83
|
-
} catch (error) {
|
|
84
|
-
if (error instanceof BaerlyError) throw new BaerlyError("SchemaError", `index ${def.name}.predicate is invalid: ${error.message}`, error);
|
|
85
|
-
throw error;
|
|
86
|
-
}
|
|
87
|
-
};
|
|
88
|
-
/**
|
|
89
|
-
* Type-tag bytes for the value-order-preserving wire format. The
|
|
90
|
-
* tag is the LEADING byte of the encoded payload; the values are
|
|
91
|
-
* picked so the type order under byte-wise lex is
|
|
92
|
-
* `null < false < true < number < string < object`.
|
|
93
|
-
*
|
|
94
|
-
* | Type | Byte-prefix | Payload |
|
|
95
|
-
* |---------|-------------|----------------------------------------------------|
|
|
96
|
-
* | null | 0x10 | (none) |
|
|
97
|
-
* | false | 0x20 | (none) |
|
|
98
|
-
* | true | 0x21 | (none) |
|
|
99
|
-
* | number | 0x30 | 8-byte sortable big-endian IEEE 754 |
|
|
100
|
-
* | string | 0x40 | UTF-8 bytes of the string (no quotes, no escapes) |
|
|
101
|
-
* | object | 0x50 | UTF-8 bytes of `JSON.stringify(v)` |
|
|
102
|
-
*
|
|
103
|
-
* Local to the encoder by design — these are wire shape, not
|
|
104
|
-
* cross-package protocol constants (see `CLAUDE.md` § "Magic
|
|
105
|
-
* values").
|
|
106
|
-
*/
|
|
107
|
-
const TYPE_NULL = 16;
|
|
108
|
-
const TYPE_FALSE = 32;
|
|
109
|
-
const TYPE_TRUE = 33;
|
|
110
|
-
const TYPE_NUMBER = 48;
|
|
111
|
-
const TYPE_STRING = 64;
|
|
112
|
-
const TYPE_OBJECT = 80;
|
|
113
|
-
/**
|
|
114
|
-
* Encode a JS double as an 8-byte big-endian sortable IEEE 754
|
|
115
|
-
* payload. Byte-wise lex order on the result matches numeric order
|
|
116
|
-
* across all finite doubles plus `±Infinity`:
|
|
117
|
-
*
|
|
118
|
-
* 1. Get the 8-byte big-endian view of the double.
|
|
119
|
-
* 2. If the sign bit is `0` (zero or positive), flip the sign bit
|
|
120
|
-
* (XOR `0x80` on byte 0) so positives sort above negatives.
|
|
121
|
-
* 3. If the sign bit is `1` (negative), flip every bit in all 8
|
|
122
|
-
* bytes so more-negative sorts lower.
|
|
123
|
-
*
|
|
124
|
-
* `NaN` has no order-preserving slot and is rejected — see the
|
|
125
|
-
* `encodeIndexValue` JSDoc for the wire-contract rationale.
|
|
126
|
-
* `-0` and `+0` collapse because the `n === 0 ? 0 : n` coercion below
|
|
127
|
-
* forces both into the positive-zero branch before `setFloat64`.
|
|
128
|
-
*/
|
|
129
|
-
const encodeNumberPayload = (n) => {
|
|
130
|
-
if (Number.isNaN(n)) throw new BaerlyError("SchemaError", `encodeIndexValue: NaN is not indexable (the byte encoding has no order-preserving slot for it)`);
|
|
131
|
-
const buf = /* @__PURE__ */ new ArrayBuffer(8);
|
|
132
|
-
new DataView(buf).setFloat64(0, n === 0 ? 0 : n, false);
|
|
133
|
-
const bytes = new Uint8Array(buf);
|
|
134
|
-
if ((bytes[0] & 128) === 0) bytes[0] = bytes[0] ^ 128;
|
|
135
|
-
else for (let i = 0; i < 8; i++) bytes[i] = bytes[i] ^ 255;
|
|
136
|
-
return bytes;
|
|
137
|
-
};
|
|
138
|
-
/**
|
|
139
|
-
* Compose the typed byte stream for one value. The leading byte is
|
|
140
|
-
* the type tag (see {@link TYPE_NULL} et al.); the payload shape is
|
|
141
|
-
* type-dependent. Strings are emitted as their raw UTF-8 bytes (no
|
|
142
|
-
* JSON quoting / escaping) so byte-wise lex order on encoded strings
|
|
143
|
-
* matches byte-wise lex order on the source UTF-8. Objects fall back
|
|
144
|
-
* to `JSON.stringify` for equality only.
|
|
145
|
-
*/
|
|
146
|
-
const encodeBytes = (v) => {
|
|
147
|
-
if (v === null || v === void 0) return new Uint8Array([TYPE_NULL]);
|
|
148
|
-
if (v === false) return new Uint8Array([TYPE_FALSE]);
|
|
149
|
-
if (v === true) return new Uint8Array([TYPE_TRUE]);
|
|
150
|
-
if (typeof v === "number") {
|
|
151
|
-
const payload = encodeNumberPayload(v);
|
|
152
|
-
const out = new Uint8Array(1 + payload.length);
|
|
153
|
-
out[0] = TYPE_NUMBER;
|
|
154
|
-
out.set(payload, 1);
|
|
155
|
-
return out;
|
|
156
|
-
}
|
|
157
|
-
if (typeof v === "string") {
|
|
158
|
-
const utf8 = new TextEncoder().encode(v);
|
|
159
|
-
const out = new Uint8Array(1 + utf8.length);
|
|
160
|
-
out[0] = TYPE_STRING;
|
|
161
|
-
out.set(utf8, 1);
|
|
162
|
-
return out;
|
|
163
|
-
}
|
|
164
|
-
const utf8 = encodeJsonBytes(v);
|
|
165
|
-
const out = new Uint8Array(1 + utf8.length);
|
|
166
|
-
out[0] = TYPE_OBJECT;
|
|
167
|
-
out.set(utf8, 1);
|
|
168
|
-
return out;
|
|
169
|
-
};
|
|
170
|
-
/**
|
|
171
|
-
* Encode an arbitrary `DocumentValue` value as a path-safe segment.
|
|
172
|
-
*
|
|
173
|
-
* Type-tagged byte stream, base-32-encoded for path safety. Lex
|
|
174
|
-
* order on encoded bytes matches:
|
|
175
|
-
*
|
|
176
|
-
* - **Type order**: `null < false < true < number < string < object`.
|
|
177
|
-
* - **Within numbers**: IEEE 754 numeric order (sortable
|
|
178
|
-
* big-endian payload, sign-bit-flipped or all-bits-flipped).
|
|
179
|
-
* `-Infinity` sorts lowest, `+Infinity` highest.
|
|
180
|
-
* - **Within strings**: UTF-8 byte order.
|
|
181
|
-
* - **Within objects**: byte-equality only (still
|
|
182
|
-
* `JSON.stringify`-insertion-order dependent).
|
|
183
|
-
*
|
|
184
|
-
* Numbers ARE range-safe under this encoder — `9` sorts below `10`
|
|
185
|
-
* as expected. The query planner's old
|
|
186
|
-
* `numeric-range-on-byte-encoder` guard has been removed; range
|
|
187
|
-
* walks and `$in` walks over numeric fields are routed normally.
|
|
188
|
-
*
|
|
189
|
-
* `NaN` throws `BaerlyError{code:"SchemaError"}` at write time —
|
|
190
|
-
* the byte encoding has no order-preserving slot for it, and a
|
|
191
|
-
* silent collapse to the `null` key (as the prior
|
|
192
|
-
* `JSON.stringify`-based encoder did, since
|
|
193
|
-
* `JSON.stringify(NaN) === "null"`) is a worse failure mode than
|
|
194
|
-
* a loud reject.
|
|
195
|
-
*
|
|
196
|
-
* `-0` and `+0` collapse to the same encoding.
|
|
197
|
-
*
|
|
198
|
-
* Equal-by-value inputs (e.g. two `{a:1, b:2}` objects with the
|
|
199
|
-
* same key insertion order) produce byte-equal segments;
|
|
200
|
-
* structurally-different but visually-similar inputs (`"5"` vs `5`)
|
|
201
|
-
* are kept apart by the type-tag prefix.
|
|
202
|
-
*
|
|
203
|
-
* String ranges remain safe: `"2026-05-13" < "2026-05-14"`
|
|
204
|
-
* byte-wise matches semantic order. ISO 8601 timestamps,
|
|
205
|
-
* alphabetical priorities like `"p1"/"p2"/"p3"`, and any
|
|
206
|
-
* fixed-width string encoding are usable as range-walked indexed
|
|
207
|
-
* fields.
|
|
208
|
-
*/
|
|
209
|
-
const encodeIndexValue = (v) => {
|
|
210
|
-
const bytes = encodeBytes(v);
|
|
211
|
-
let out = "";
|
|
212
|
-
let bits = 0;
|
|
213
|
-
let value = 0;
|
|
214
|
-
for (const b of bytes) {
|
|
215
|
-
value = value << 8 | b;
|
|
216
|
-
bits += 8;
|
|
217
|
-
while (bits >= 5) {
|
|
218
|
-
bits -= 5;
|
|
219
|
-
out += B32_ALPHABET[value >> bits & 31];
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
if (bits > 0) out += B32_ALPHABET[value << 5 - bits & 31];
|
|
223
|
-
return out;
|
|
224
|
-
};
|
|
225
|
-
/**
|
|
226
|
-
* Storage `list(prefix)` boundary for every entry under one index
|
|
227
|
-
* of a collection: `<logPrefix>/index/<name>/`. Used by the rebuild
|
|
228
|
-
* command's reconciliation walk and by the read-path index hint.
|
|
229
|
-
*/
|
|
230
|
-
const indexKeyPrefix = (logPrefix, indexName) => `${logPrefix}/index/${indexName}/`;
|
|
231
|
-
/**
|
|
232
|
-
* Build the per-doc index key for one `(def, values, docId)`.
|
|
233
|
-
*
|
|
234
|
-
* Single-field: `<logPrefix>/index/<name>/<v0-b32>/<docId>.json`.
|
|
235
|
-
* Composite: `<logPrefix>/index/<name>/<v0-b32>/<v1-b32>/.../<docId>.json`.
|
|
236
|
-
*
|
|
237
|
-
* Composite shape is accepted but the read path today only
|
|
238
|
-
* consults single-field entries.
|
|
239
|
-
*/
|
|
240
|
-
const indexKeyFor = (logPrefix, def, values, docId) => {
|
|
241
|
-
const segments = values.map(encodeIndexValue).join("/");
|
|
242
|
-
return `${logPrefix}/index/${def.name}/${segments}/${docId}.json`;
|
|
243
|
-
};
|
|
244
|
-
/**
|
|
245
|
-
* Project the value tuple a doc body produces under one index
|
|
246
|
-
* definition. Returns `undefined` when any indexed field is
|
|
247
|
-
* null / undefined / missing — no index entry for that doc under
|
|
248
|
-
* that index (SQL "NULL values don't enter the index" semantics).
|
|
249
|
-
*
|
|
250
|
-
* @throws BaerlyError code="SchemaError" — `on` contains a dotted
|
|
251
|
-
* path, or the indexed field's value is an array. Both restrictions
|
|
252
|
-
* are pre-launch; multi-value (array) indexes are a follow-up.
|
|
253
|
-
*/
|
|
254
|
-
const projectIndexValues = (def, body) => {
|
|
255
|
-
if (body === void 0) return;
|
|
256
|
-
const fields = typeof def.on === "string" ? [def.on] : def.on;
|
|
257
|
-
const values = [];
|
|
258
|
-
for (const field of fields) {
|
|
259
|
-
if (field.includes(".")) throw new BaerlyError("SchemaError", `index ${def.name}: dotted-path "on" fields not yet supported (got ${JSON.stringify(field)})`);
|
|
260
|
-
const v = body[field];
|
|
261
|
-
if (v === null || v === void 0) return;
|
|
262
|
-
if (Array.isArray(v)) throw new BaerlyError("SchemaError", `index ${def.name}: cannot index array field "${field}" — multi-value indexes are not supported yet`);
|
|
263
|
-
values.push(v);
|
|
264
|
-
}
|
|
265
|
-
return values;
|
|
266
|
-
};
|
|
267
|
-
/**
|
|
268
|
-
* Compute the full index-key set a single doc produces under every
|
|
269
|
-
* declared index of its collection. Skips indexes whose projection
|
|
270
|
-
* yields `undefined` (null/missing indexed field). Used by both
|
|
271
|
-
* the writer (to PUT new keys) and the rebuild command (to compute
|
|
272
|
-
* the expected key set across the live doc map).
|
|
273
|
-
*
|
|
274
|
-
* Filter-aware (T4): when `def.predicate !== undefined`, the doc
|
|
275
|
-
* must satisfy `matchesWire(def.predicate, body)` or the def contributes
|
|
276
|
-
* zero keys. The writer's diff `oldKeys` vs `newKeys` then covers
|
|
277
|
-
* all four U-quadrants automatically — see the JSDoc on
|
|
278
|
-
* `writer.ts` above the index-emission block. `body ===
|
|
279
|
-
* undefined` short-circuits ahead of the filter check (no keys for
|
|
280
|
-
* an unknown pre-image, regardless of filter), preserving the prior
|
|
281
|
-
* D-quadrant behaviour.
|
|
282
|
-
*/
|
|
283
|
-
const allIndexKeysFor = (logPrefix, defs, body, docId) => {
|
|
284
|
-
const keys = [];
|
|
285
|
-
for (const def of defs) {
|
|
286
|
-
if (def.predicate !== void 0 && body !== void 0) {
|
|
287
|
-
if (!matchesWire(def.predicate, body)) continue;
|
|
288
|
-
}
|
|
289
|
-
const values = projectIndexValues(def, body);
|
|
290
|
-
if (values !== void 0) keys.push(indexKeyFor(logPrefix, def, values, docId));
|
|
291
|
-
}
|
|
292
|
-
return keys;
|
|
293
|
-
};
|
|
294
|
-
//#endregion
|
|
295
|
-
export { indexKeyPrefix as n, validateIndexDefinition as r, allIndexKeysFor as t };
|
|
296
|
-
|
|
297
|
-
//# sourceMappingURL=indexes-BXn7a06a.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"indexes-BXn7a06a.js","names":[],"sources":["../packages/server/src/indexes.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAM,gBAAgB;;;;;;AAOtB,MAAM,eAAe;;;;;;;;;;AAWrB,MAAa,2BAA2B,QAA+B;CACrE,IAAI,CAAC,cAAc,KAAK,IAAI,IAAI,GAC9B,MAAM,IAAI,YACR,eACA,mDAAmD,KAAK,UAAU,IAAI,IAAI,GAC5E;CAEF,IAAI,OAAO,IAAI,OAAO;MAChB,IAAI,GAAG,WAAW,GACpB,MAAM,IAAI,YAAY,eAAe,SAAS,IAAI,KAAK,sBAAsB;CAAA,OAE1E,IAAI,IAAI,GAAG,WAAW,GAC3B,MAAM,IAAI,YAAY,eAAe,SAAS,IAAI,KAAK,4BAA4B;CAErF,IAAI,IAAI,cAAc,KAAA,GACpB,IAAI;EACF,aAAa,IAAI,SAAS;CAC5B,SAAS,OAAO;EAId,IAAI,iBAAiB,aACnB,MAAM,IAAI,YACR,eACA,SAAS,IAAI,KAAK,yBAAyB,MAAM,WACjD,KACF;EAEF,MAAM;CACR;AAEJ;;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,YAAY;AAClB,MAAM,aAAa;AACnB,MAAM,YAAY;AAClB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