@gusto/baerly-storage 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -124
- package/dist/API.md +161 -511
- package/dist/CHANGELOG.md +1148 -307
- package/dist/RECIPES.md +398 -80
- package/dist/THIRD-PARTY-LICENSES.txt +5 -26
- package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
- package/dist/app-config.d.ts +31 -1
- package/dist/app-config.js +1 -2
- package/dist/app-config.js.map +1 -1
- package/dist/auth.d.ts +33 -28
- package/dist/auth.js +549 -985
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +130 -138
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +97 -22
- package/dist/capacity-warning-header-BlVopyiI.js +16 -0
- package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
- package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
- package/dist/client-react.d.ts +67 -20
- package/dist/client-react.js +240 -54
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +5 -4
- package/dist/client.js +51 -16
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
- package/dist/cloudflare-CKHYXccw.js.map +1 -0
- package/dist/cloudflare.d.ts +106 -71
- package/dist/cloudflare.js +334 -271
- package/dist/cloudflare.js.map +1 -1
- package/dist/code-resolution-CL_7L0wS.js +22 -0
- package/dist/code-resolution-CL_7L0wS.js.map +1 -0
- package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
- package/dist/config-DEzInG6M.js +4035 -0
- package/dist/config-DEzInG6M.js.map +1 -0
- package/dist/constants-D3GSH3tc.js +469 -0
- package/dist/constants-D3GSH3tc.js.map +1 -0
- package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
- package/dist/context-rlpSnHFA.js.map +1 -0
- package/dist/cost-B52llVDx.js +330 -0
- package/dist/cost-B52llVDx.js.map +1 -0
- package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
- package/dist/current-json-CC6lE4Aj.js.map +1 -0
- package/dist/db-plFUNTSF.d.ts +130 -0
- package/dist/db-read-seams-BSs0m1z1.js +3261 -0
- package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
- package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
- package/dist/deploy-Obj4nE-Z.js.map +1 -0
- package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
- package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
- package/dist/dev-landing-CD-si4dW.js +50 -0
- package/dist/dev-landing-CD-si4dW.js.map +1 -0
- package/dist/dev-vite.d.ts +38 -39
- package/dist/dev-vite.js +67 -36
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +3 -2
- package/dist/dev.js +2 -1
- package/dist/doctor-BA0i-YAN.js +270 -0
- package/dist/doctor-BA0i-YAN.js.map +1 -0
- package/dist/dump-D1vX8ozg.js +133 -0
- package/dist/dump-D1vX8ozg.js.map +1 -0
- package/dist/errors-7Rk1HGCE.js +160 -0
- package/dist/errors-7Rk1HGCE.js.map +1 -0
- package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
- package/dist/export-BVL2EvYE.js.map +1 -0
- package/dist/fsck-BWkPgov4.js +145 -0
- package/dist/fsck-BWkPgov4.js.map +1 -0
- package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
- package/dist/gcs.d.ts +30 -0
- package/dist/gcs.js +1 -0
- package/dist/goog4-signer-CeLIABoE.js +331 -0
- package/dist/goog4-signer-CeLIABoE.js.map +1 -0
- package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
- package/dist/http-Z5rZyYMX.js.map +1 -0
- package/dist/http-transport-DNUM8kU-.js +1299 -0
- package/dist/http-transport-DNUM8kU-.js.map +1 -0
- package/dist/http.d.ts +366 -294
- package/dist/http.js +2 -2
- package/dist/index-JJrIu1pO.d.ts +135 -0
- package/dist/index-LEgHN0qJ.d.ts +50 -0
- package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
- package/dist/index.d.ts +27 -6
- package/dist/index.js +3 -5
- package/dist/inspect-BTsVYZKd.js +196 -0
- package/dist/inspect-BTsVYZKd.js.map +1 -0
- package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
- package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
- package/dist/ledger-Dj_bGgo0.js +192 -0
- package/dist/ledger-Dj_bGgo0.js.map +1 -0
- package/dist/legacy-names-DgZBtgOh.js +47 -0
- package/dist/legacy-names-DgZBtgOh.js.map +1 -0
- package/dist/log-C9W15Dfo.d.ts +94 -0
- package/dist/log-tail-DWJbneBF.js +142 -0
- package/dist/log-tail-DWJbneBF.js.map +1 -0
- package/dist/log-walk-C-vA-WGJ.js +111 -0
- package/dist/log-walk-C-vA-WGJ.js.map +1 -0
- package/dist/maintenance-Dd-Yakqj.js +1709 -0
- package/dist/maintenance-Dd-Yakqj.js.map +1 -0
- package/dist/maintenance-DevB6z4e.js +2237 -0
- package/dist/maintenance-DevB6z4e.js.map +1 -0
- package/dist/maintenance.d.ts +100 -3
- package/dist/maintenance.js +1 -3
- package/dist/node.d.ts +130 -142
- package/dist/node.js +4 -3
- package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
- package/dist/observability-C-ISCCLE.js.map +1 -0
- package/dist/observability.d.ts +27 -3
- package/dist/observability.js +3 -3
- package/dist/path-segment-DBXG26PW.js +363 -0
- package/dist/path-segment-DBXG26PW.js.map +1 -0
- package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
- package/dist/plan-BvQbaNMe.js.map +1 -0
- package/dist/request-CRWiTrza.js +272 -0
- package/dist/request-CRWiTrza.js.map +1 -0
- package/dist/restore-U6Im8V1V.js +1467 -0
- package/dist/restore-U6Im8V1V.js.map +1 -0
- package/dist/retry-OBtLB2GC.js +126 -0
- package/dist/retry-OBtLB2GC.js.map +1 -0
- package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
- package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
- package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
- package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
- package/dist/s3.d.ts +20 -7
- package/dist/s3.js +4 -5
- package/dist/s3.js.map +1 -1
- package/dist/sha256-4FfGQNPw.js +22 -0
- package/dist/sha256-4FfGQNPw.js.map +1 -0
- package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
- package/dist/shared-secret-Vkur-8r0.js.map +1 -0
- package/dist/sigv4-sign-5IUflUD_.js +507 -0
- package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
- package/dist/snapshot-CknzkDM0.js +148 -0
- package/dist/snapshot-CknzkDM0.js.map +1 -0
- package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
- package/dist/src-Actga-bO.js.map +1 -0
- package/dist/src-D0MQfvOp.js +812 -0
- package/dist/src-D0MQfvOp.js.map +1 -0
- package/dist/src-Dr9uo3dc.js +501 -0
- package/dist/src-Dr9uo3dc.js.map +1 -0
- package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
- package/dist/subcommand-BLoF66dG.js.map +1 -0
- package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
- package/dist/time-DRxTP9iv.js.map +1 -0
- package/dist/types-suVbsEWS.d.ts +116 -0
- package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
- package/dist/usage-CPzVhrQr.js.map +1 -0
- package/dist/uuid-BuT_c404.js +333 -0
- package/dist/uuid-BuT_c404.js.map +1 -0
- package/dist/verifier-Bmlmndzo.d.ts +95 -0
- package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
- package/dist/wire-DndvKU-K.js.map +1 -0
- package/package.json +96 -69
- package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
- package/dist/bytes-BXdamO3L.js +0 -11
- package/dist/bytes-BXdamO3L.js.map +0 -1
- package/dist/cloudflare-DzKBrUlg.js.map +0 -1
- package/dist/config-1tv0-Yzm.js +0 -2693
- package/dist/config-1tv0-Yzm.js.map +0 -1
- package/dist/constants-CfeMWQWk.js +0 -222
- package/dist/constants-CfeMWQWk.js.map +0 -1
- package/dist/context-DRZ3tZ5l.js.map +0 -1
- package/dist/cost-DSMIVqzL.js +0 -203
- package/dist/cost-DSMIVqzL.js.map +0 -1
- package/dist/current-json-C6nhPOm1.js.map +0 -1
- package/dist/db-DsPkOVEH.d.ts +0 -254
- package/dist/deploy-DonTr-CV.js.map +0 -1
- package/dist/doctor-DSIyCDg_.js +0 -346
- package/dist/doctor-DSIyCDg_.js.map +0 -1
- package/dist/dump-Bh5k26VQ.js +0 -94
- package/dist/dump-Bh5k26VQ.js.map +0 -1
- package/dist/errors-Dfa3p78c.js +0 -78
- package/dist/errors-Dfa3p78c.js.map +0 -1
- package/dist/export-DtF5tDIM.js +0 -401
- package/dist/export-DtF5tDIM.js.map +0 -1
- package/dist/fsck-D_djMO5D.js +0 -279
- package/dist/fsck-D_djMO5D.js.map +0 -1
- package/dist/http-DGd5tbNs.js.map +0 -1
- package/dist/index-0rZcMBwy.d.ts +0 -115
- package/dist/index-BNRh23K9.d.ts +0 -162
- package/dist/index-BYk9oCNf.d.ts +0 -1112
- package/dist/indexes-Dn9hbGQG.d.ts +0 -22
- package/dist/inspect-6WZ-pC7-.js +0 -133
- package/dist/inspect-6WZ-pC7-.js.map +0 -1
- package/dist/log-tail-D98U1JBo.js +0 -522
- package/dist/log-tail-D98U1JBo.js.map +0 -1
- package/dist/maintenance-B4Dki6Ig.js +0 -2157
- package/dist/maintenance-B4Dki6Ig.js.map +0 -1
- package/dist/maintenance-B_e0T99L.d.ts +0 -537
- package/dist/maintenance-C7coQp4c.js +0 -1418
- package/dist/maintenance-C7coQp4c.js.map +0 -1
- package/dist/normalize-rjnZLwS4.js +0 -133
- package/dist/normalize-rjnZLwS4.js.map +0 -1
- package/dist/observability-BmflLCdF.js.map +0 -1
- package/dist/plan-a7PJHBCy.js.map +0 -1
- package/dist/query-rAtXNQQB.js +0 -1773
- package/dist/query-rAtXNQQB.js.map +0 -1
- package/dist/rebuild-index-BVzQSZlm.js +0 -81
- package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
- package/dist/request-u0M51mhJ.js +0 -72
- package/dist/request-u0M51mhJ.js.map +0 -1
- package/dist/restore-R-4rbciV.js +0 -778
- package/dist/restore-R-4rbciV.js.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
- package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
- package/dist/shared-secret-DgEicd3x.js.map +0 -1
- package/dist/src-BL_JoPTn.js.map +0 -1
- package/dist/src-CYHFDrKz.js +0 -536
- package/dist/src-CYHFDrKz.js.map +0 -1
- package/dist/src-DYZ4H1aF.js +0 -392
- package/dist/src-DYZ4H1aF.js.map +0 -1
- package/dist/subcommand-DoDA-K7d.js.map +0 -1
- package/dist/time-DUqvFMHq.js.map +0 -1
- package/dist/usage-DBV1eQHC.js.map +0 -1
- package/dist/validate-DtljsCh1.js.map +0 -1
- package/dist/wire-izfGZDvr.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"current-json-C6nhPOm1.js","names":[],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n","/**\n * `current.json` — the per-collection compaction-state control object —\n * and its embedded, currently dormant {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps snapshot\n * generations by CAS-writing this object; the Writer reads it on every\n * commit to find the snapshot pointer and a non-authoritative\n * tail-probe floor. The numbered log create mints the next integer\n * `seq`; no commit-path code CAS-advances `current.json`.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `3`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 3;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Non-authoritative monotone lower bound on the committed log tail.\n * The authoritative tail is discovered by forward-probe (log-tail.ts);\n * never trust this as the head. Durable advancement is owned by\n * compaction folds, write-tick tail refreshes, and explicit\n * operator/import paths; ordinary writer commits do not refresh it.\n */\n tail_hint: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, tail_hint)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= tail_hint`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /**\n * Row count of the snapshot (= compactor `base.size`, free). With\n * `tail_hint - log_seq_start` (trusted tail entries) this gives the\n * fold's entry count for the ENTRY ceiling `E`. Seeded 0.\n */\n snapshot_rows: number;\n\n /**\n * Optional compactor-stamped mean folded-entry byte size. Maintenance\n * derives live-tail bytes as `entry_count × mean_entry_bytes` without\n * an exact stored counter; absent until first fold.\n */\n mean_entry_bytes?: number;\n\n /**\n * Baseline for rate-limiting the graduation defer-warn off SHARED\n * durable state, not per-isolate memory. The warn fires when the\n * observed/probed tail minus `last_warned_seq` reaches\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes\n * `last_warned_seq` to the observed/probed tail. Absent → 0.\n */\n last_warned_seq?: number;\n}\n\n/**\n * Fence-token sub-shape embedded in {@link CurrentJson}. The\n * monotonically-bumped `epoch` is the only safety-critical field —\n * `owner` is informational and may be missing in older records;\n * `claimed_at` is the server response date at claim time, NOT the\n * local clock; `lease_until` is reserved for manual rotation and is not\n * consumed by the current kernel. Log entries are not stamped with this\n * epoch; the fence is dormant authority metadata, not a reader replay\n * filter.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. In the earlier two-write commit design, every commit checked\n * the epoch before continuing under `current.json` authority. Under\n * single-write commit no production path reads or writes the fence.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Under single-write commit this is retained\n * as an explicit admin/testing primitive only; no production commit\n * path claims or verifies the fence.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the dormant write fence by bumping `epoch` and\n * stamping `claimed_at` from `StoragePutResult.serverDate`. Under\n * single-write commit there is no production commit-path call site;\n * this is retained for explicit admin/testing workflows and future\n * rotation designs.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // Stryker disable next-line ConditionalExpression: `→true` spreads `{lease_until: undefined}` which JSON.stringify omits, so the stored bytes are identical to the normal `→false` path (no key emitted). Genuine equivalent mutant.\n ...(existing.json.writer_fence.lease_until !== undefined && {\n lease_until: existing.json.writer_fence.lease_until,\n }),\n },\n };\n const body = encodeJson(provisional);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n // No server clock surfaced — leave `claimed_at` empty. The epoch\n // bump is durable; safety is unaffected.\n if (result.serverDate === undefined) {\n return { json: provisional, etag: result.etag };\n }\n // Stamp the server clock through a second CAS-on-our-own-etag. A\n // peer landing between the two writes loses cleanly with Conflict\n // (the fence is safe — next claim will bump past both).\n const stamped: CurrentJson = {\n ...provisional,\n writer_fence: {\n ...provisional.writer_fence,\n claimed_at: result.serverDate.toISOString(),\n },\n };\n const stampedBody = encodeJson(stamped);\n const stampPutOpts: StoragePutOptions = {\n ifMatch: result.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let stampResult: StoragePutResult;\n try {\n stampResult = await storage.put(key, stampedBody, stampPutOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: stamped, etag: stampResult.etag };\n}\n\n/**\n * Read `current.json.log_seq_start` — the low-water mark of the live\n * log range `[log_seq_start, tail_hint)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. Tolerant\n * reader: unknown keys ignored, new required fields bump\n * `schema_version` (move (b), ADR-003).\n */\nconst assertCurrentJson = (parsed: unknown, key: string): CurrentJson => {\n if (parsed === null || typeof parsed !== \"object\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: parsed body is not an object`,\n );\n }\n const r = parsed as Record<string, unknown>;\n if (r[\"schema_version\"] === 1 || r[\"schema_version\"] === 2) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} uses schema v${String(r[\"schema_version\"])} from a pre-0.3.0 internal build; this build requires schema v${CURRENT_JSON_SCHEMA_VERSION}. Dump/restore with the old build, or re-provision scratch/local buckets.`,\n );\n }\n if (r[\"schema_version\"] !== CURRENT_JSON_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: unsupported schema_version ${String(r[\"schema_version\"])}; this build requires ${CURRENT_JSON_SCHEMA_VERSION}. This almost always means stale scratch data from a different build — wipe the local dev bucket (e.g. \\`rm -rf .baerly-data\\`) or recreate the R2/S3 bucket, then retry.`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"tail_hint\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"tail_hint\"] < 0` → false is subsumed by the downstream `log_seq_start > tail_hint` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_tail_hint always fires); (3) StringLiteral \"tail_hint\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (\n typeof r[\"tail_hint\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_hint\"]) ||\n r[\"tail_hint\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_hint must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"log_seq_start\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers anyway, making the typeof check fully subsumed.\n typeof r[\"log_seq_start\"] !== \"number\" ||\n !Number.isInteger(r[\"log_seq_start\"]) ||\n r[\"log_seq_start\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start must be a non-negative integer`,\n );\n }\n if (r[\"log_seq_start\"] > r[\"tail_hint\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > tail_hint ${String(r[\"tail_hint\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // Stryker disable next-line ConditionalExpression: `typeof f[\"epoch\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof guard fully subsumed.\n if (typeof f[\"epoch\"] !== \"number\" || !Number.isInteger(f[\"epoch\"]) || f[\"epoch\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.epoch must be a non-negative integer`,\n );\n }\n if (typeof f[\"owner\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.owner must be a string`,\n );\n }\n if (typeof f[\"claimed_at\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.claimed_at must be a string`,\n );\n }\n if (f[\"lease_until\"] !== undefined && typeof f[\"lease_until\"] !== \"string\") {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: writer_fence.lease_until must be string if present`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_bytes\"]) ||\n r[\"snapshot_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_bytes must be a non-negative integer`,\n );\n }\n if (\n // Stryker disable next-line ConditionalExpression: `typeof r[\"snapshot_rows\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"snapshot_rows\"] !== \"number\" ||\n !Number.isInteger(r[\"snapshot_rows\"]) ||\n r[\"snapshot_rows\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot_rows must be a non-negative integer`,\n );\n }\n if (\n r[\"last_warned_seq\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: `typeof r[\"last_warned_seq\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n (typeof r[\"last_warned_seq\"] !== \"number\" ||\n !Number.isInteger(r[\"last_warned_seq\"]) ||\n r[\"last_warned_seq\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: last_warned_seq must be a non-negative integer if present`,\n );\n }\n if (\n r[\"mean_entry_bytes\"] !== undefined &&\n // Stryker disable next-line ConditionalExpression: typeof → false is subsumed by !Number.isInteger.\n (typeof r[\"mean_entry_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"mean_entry_bytes\"]) ||\n r[\"mean_entry_bytes\"] < 0)\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: mean_entry_bytes must be a non-negative integer if present`,\n );\n }\n return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n"],"mappings":"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"}
|
package/dist/db-DsPkOVEH.d.ts
DELETED
|
@@ -1,254 +0,0 @@
|
|
|
1
|
-
import { a as CollectionNames, d as IndexDefinition, f as DocumentData, o as RowOf, r as BaerlyConfig, s as UnboundConfig, u as SchemaValidator } from "./app-config-DyiFK3_k.js";
|
|
2
|
-
import { f as CurrentJsonRead, n as LogEntry, o as Collection, p as Storage } from "./index-BYk9oCNf.js";
|
|
3
|
-
//#region packages/server/src/schema.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Run a validator and throw `BaerlyError{code:"SchemaError"}` on failure.
|
|
6
|
-
* On success returns the validator's output (which for transforming
|
|
7
|
-
* validators may differ from the input).
|
|
8
|
-
*
|
|
9
|
-
* Field paths are normalised to `(string | number)[]` so the wire shape
|
|
10
|
-
* is JSON-clean. Symbol keys (rare; StandardSchemaV1 permits them) are
|
|
11
|
-
* coerced to `String(sym)` — we never emit `symbol` on the wire.
|
|
12
|
-
*
|
|
13
|
-
* The thrown error's `message` carries a one-line summary
|
|
14
|
-
* (`"<collection>.<verb>: <issuesCount> field(s) failed validation: <first>"`)
|
|
15
|
-
* for stderr-readable logs; the structured `issues` are on `.issues`.
|
|
16
|
-
*/
|
|
17
|
-
declare const validateOrThrow: <TIn, TOut>(schema: SchemaValidator<TIn, TOut>, candidate: unknown, context: {
|
|
18
|
-
readonly collection: string;
|
|
19
|
-
readonly verb: "insert" | "update" | "replace";
|
|
20
|
-
}) => Promise<TOut>;
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region packages/server/src/query.d.ts
|
|
23
|
-
/**
|
|
24
|
-
* What a `Query<T>` needs to issue a read against the bucket. The
|
|
25
|
-
* `Db` builds this once and hands it to `Collection` / `Query`; the chain
|
|
26
|
-
* carries it forward unchanged.
|
|
27
|
-
*
|
|
28
|
-
* The `collectionPrefix` shape matches what `Writer` writes under —
|
|
29
|
-
* e.g. `"app/<app>/tenant/<tenant>/manifests/<name>"`. Drift between
|
|
30
|
-
* the reader and writer prefix is the most likely bug class; both
|
|
31
|
-
* compose the same string from `app`/`tenant`/`name`.
|
|
32
|
-
*
|
|
33
|
-
* @internal
|
|
34
|
-
*/
|
|
35
|
-
interface CollectionReadContext {
|
|
36
|
-
readonly storage: Storage;
|
|
37
|
-
/** Physical key prefix — already includes `app/<app>/tenant/<tenant>/manifests/<name>`. */
|
|
38
|
-
readonly collectionPrefix: string;
|
|
39
|
-
readonly collectionName: string;
|
|
40
|
-
/**
|
|
41
|
-
* Optional StandardSchemaV1-shaped validator for this collection.
|
|
42
|
-
* When set, `runInsert`, `runUpdate`, and `runReplaceById` validate the
|
|
43
|
-
* post-image before committing — invalid input throws
|
|
44
|
-
* `BaerlyError{code:"SchemaError"}` carrying a `.issues` array of
|
|
45
|
-
* `{ path, message }` entries. `undefined` means no validation
|
|
46
|
-
* (today's behaviour — zero overhead).
|
|
47
|
-
*
|
|
48
|
-
* Threaded in by {@link Db.collectionReadContext} from the per-collection
|
|
49
|
-
* map handed to {@link Db.create}; the boundary calls happen in
|
|
50
|
-
* `query.ts`, not `writer.ts`, so schemas plug in at the
|
|
51
|
-
* read/write API surface rather than at the writer layer.
|
|
52
|
-
*
|
|
53
|
-
* @internal
|
|
54
|
-
*/
|
|
55
|
-
readonly schema?: SchemaValidator;
|
|
56
|
-
/**
|
|
57
|
-
* Per-collection {@link IndexDefinition}s threaded onto every
|
|
58
|
-
* read. Consumed by `planQuery(...)` inside `runRead` to pick an
|
|
59
|
-
* index-walk plan when the predicate's equality fields cover a
|
|
60
|
-
* declared index's `on` tuple left-to-right. Empty array means
|
|
61
|
-
* "no indexes declared" — every read falls through to the
|
|
62
|
-
* snapshot + log fold path.
|
|
63
|
-
*
|
|
64
|
-
* Mirrors the shape callers build when flattening
|
|
65
|
-
* `BaerlyConfig.collections[*].indexes` into a map keyed by name
|
|
66
|
-
* before constructing the `Db`; we keep the `Db` itself library-
|
|
67
|
-
* agnostic by accepting the pre-flattened map (not the full
|
|
68
|
-
* `BaerlyConfig`).
|
|
69
|
-
*
|
|
70
|
-
* @internal
|
|
71
|
-
*/
|
|
72
|
-
readonly indexes: ReadonlyArray<IndexDefinition>;
|
|
73
|
-
}
|
|
74
|
-
//#endregion
|
|
75
|
-
//#region packages/server/src/db.d.ts
|
|
76
|
-
/**
|
|
77
|
-
* Runtime entry point. One `Db` per `(app, tenant)` request.
|
|
78
|
-
*
|
|
79
|
-
* Construct via {@link Db.create} — the constructor is private so
|
|
80
|
-
* callers don't accidentally bypass validation.
|
|
81
|
-
*
|
|
82
|
-
* **Collection provisioning.** `Db` provisions collections implicitly on
|
|
83
|
-
* the first commit — the writer auto-creates the per-collection
|
|
84
|
-
* `current.json` manifest with a zero-state seed, costing one extra
|
|
85
|
-
* Class A PUT on the very first write per collection and zero
|
|
86
|
-
* thereafter. There is no `ensureCollection` method on this class. For
|
|
87
|
-
* eager pre-warm (seed scripts, deploy-time provisioning, CI fixtures
|
|
88
|
-
* that want byte-identical bytes before the first request), use
|
|
89
|
-
* {@link "@gusto/baerly-storage/dev".ensureTable}.
|
|
90
|
-
*
|
|
91
|
-
* @example
|
|
92
|
-
* ```ts
|
|
93
|
-
* import { Db } from "@gusto/baerly-storage";
|
|
94
|
-
* import { MemoryStorage } from "@gusto/baerly-storage";
|
|
95
|
-
*
|
|
96
|
-
* const db = Db.create({
|
|
97
|
-
* storage: new MemoryStorage(),
|
|
98
|
-
* app: "tickets",
|
|
99
|
-
* tenant: "acme-co",
|
|
100
|
-
* });
|
|
101
|
-
*
|
|
102
|
-
* await db.collection("tickets").insert({ title: "first ticket", status: "open" });
|
|
103
|
-
* const open = await db.collection("tickets").where({ status: "open" }).all();
|
|
104
|
-
* ```
|
|
105
|
-
*
|
|
106
|
-
* @remarks
|
|
107
|
-
* **Anti-patterns** (TS compile errors, not runtime rejections):
|
|
108
|
-
* - `db.collection(name).insertOne({...})` / `.insert({...})` —
|
|
109
|
-
* the Mongo verb. Use `.insert(row)` (returns `{ _id }`).
|
|
110
|
-
* - `db.collection(name).findOne({...})` / `.find({...})` —
|
|
111
|
-
* the Mongo read verbs. Use `.get(id)` for by-id reads and
|
|
112
|
-
* `.where({...}).first()` / `.all()` for predicate reads.
|
|
113
|
-
* - `db.collection(name).aggregate([...])` — no pipeline stage
|
|
114
|
-
* model. Compose via `.where().order().limit()` modifiers.
|
|
115
|
-
* - Raw SQL strings of any shape. The kernel has no SQL parser.
|
|
116
|
-
*/
|
|
117
|
-
declare class Db<TConfig extends BaerlyConfig = UnboundConfig> {
|
|
118
|
-
#private;
|
|
119
|
-
readonly app: string;
|
|
120
|
-
readonly tenant: string;
|
|
121
|
-
private constructor();
|
|
122
|
-
/**
|
|
123
|
-
* Build a tenant-scoped `Db`. Throws
|
|
124
|
-
* `BaerlyError{code:"InvalidConfig"}` if either `app` or `tenant`
|
|
125
|
-
* is empty, contains `/`, is `"."` or `".."`, contains control
|
|
126
|
-
* characters, starts with the reserved `"_"` prefix, or exceeds
|
|
127
|
-
* 256 bytes.
|
|
128
|
-
*
|
|
129
|
-
* @throws BaerlyError code="InvalidConfig" when `app` or `tenant` is
|
|
130
|
-
* empty, contains `/`, is `"."` or `".."`, contains control
|
|
131
|
-
* characters, starts with the reserved `"_"` prefix, or exceeds
|
|
132
|
-
* 256 bytes.
|
|
133
|
-
*
|
|
134
|
-
* @example
|
|
135
|
-
* ```ts
|
|
136
|
-
* const db = Db.create({ storage, app: "tickets", tenant: "acme" });
|
|
137
|
-
* await db.collection("tickets").insert({ title: "hi" });
|
|
138
|
-
* ```
|
|
139
|
-
*/
|
|
140
|
-
static create<TConfig extends BaerlyConfig = UnboundConfig>(config: {
|
|
141
|
-
storage: Storage;
|
|
142
|
-
app: string;
|
|
143
|
-
tenant: string;
|
|
144
|
-
/**
|
|
145
|
-
* Optional. Pass the value returned by {@link defineConfig} from
|
|
146
|
-
* your `baerly.config.ts`. Two things happen:
|
|
147
|
-
*
|
|
148
|
-
* 1. **Types.** `db.collection(name)` narrows `name` to declared
|
|
149
|
-
* collection names and infers the row type from
|
|
150
|
-
* `collections[name].schema` via {@link RowOf}.
|
|
151
|
-
* 2. **Runtime.** Schemas and indexes are derived from
|
|
152
|
-
* `config.collections` via {@link collectionsToMaps}. Schema
|
|
153
|
-
* validation and index routing are wired automatically — no
|
|
154
|
-
* second hand-off step.
|
|
155
|
-
*
|
|
156
|
-
* @example
|
|
157
|
-
* ```ts
|
|
158
|
-
* import config from "../baerly.config.ts";
|
|
159
|
-
* const db = Db.create({
|
|
160
|
-
* storage: new MemoryStorage(),
|
|
161
|
-
* app: "helpdesk",
|
|
162
|
-
* tenant: "test",
|
|
163
|
-
* config,
|
|
164
|
-
* });
|
|
165
|
-
* // db.collection("tickets") is typed AND validates writes against
|
|
166
|
-
* // the schema declared in baerly.config.ts.
|
|
167
|
-
* ```
|
|
168
|
-
*/
|
|
169
|
-
config?: TConfig;
|
|
170
|
-
}): Db<TConfig>;
|
|
171
|
-
/**
|
|
172
|
-
* Typed handle for a single collection. Cheap; creates no I/O. Same
|
|
173
|
-
* `name` returns a FRESH `Collection<T>` object on each call (chain
|
|
174
|
-
* identity is intentional — modifiers return new objects).
|
|
175
|
-
*
|
|
176
|
-
* @throws BaerlyError code="InvalidConfig" when `name` is empty,
|
|
177
|
-
* contains `/`, is `"."` or `".."`, contains control characters,
|
|
178
|
-
* starts with the reserved `"_"` prefix, or exceeds 256 bytes.
|
|
179
|
-
*
|
|
180
|
-
* @example
|
|
181
|
-
* ```ts
|
|
182
|
-
* // With a baerly.config.ts bound via Db.create({..., config}),
|
|
183
|
-
* // db.collection(name) infers the row type from the declared schema —
|
|
184
|
-
* // no <Ticket> generic needed.
|
|
185
|
-
* const open = await db.collection("tickets")
|
|
186
|
-
* .where({ status: "open" })
|
|
187
|
-
* .order({ commit_ts: "desc" })
|
|
188
|
-
* .limit(50)
|
|
189
|
-
* .all();
|
|
190
|
-
* ```
|
|
191
|
-
*/
|
|
192
|
-
collection<N extends CollectionNames<TConfig>>(name: N): Collection<RowOf<TConfig, N> & DocumentData>;
|
|
193
|
-
/**
|
|
194
|
-
* Build a freshly-seeded {@link CollectionReadContext} for `name`. The
|
|
195
|
-
* HTTP router uses this so it can drive `runAllWithMeta` directly
|
|
196
|
-
* (the return shape carries the manifest-pointer cursor used to
|
|
197
|
-
* pack `_meta` onto the read response envelope). Application
|
|
198
|
-
* callers should keep using
|
|
199
|
-
* {@link Db.collection}; the chainable terminals destructure the cursor
|
|
200
|
-
* out and discard it to keep the locked `Query<T>` signature.
|
|
201
|
-
*
|
|
202
|
-
* Runs the same `name`-validation guard as {@link Db.collection}.
|
|
203
|
-
*
|
|
204
|
-
* @throws BaerlyError code="InvalidConfig" when `name` is empty,
|
|
205
|
-
* contains `/`, is `"."` or `".."`, contains control characters,
|
|
206
|
-
* starts with the reserved `"_"` prefix, or exceeds 256 bytes.
|
|
207
|
-
* @internal
|
|
208
|
-
*/
|
|
209
|
-
collectionReadContext(name: string): CollectionReadContext;
|
|
210
|
-
/**
|
|
211
|
-
* Read + parse this `Db`'s `manifests/<collection>/current.json`. Returns
|
|
212
|
-
* `null` when the collection has not been provisioned yet (no
|
|
213
|
-
* `current.json` exists). Throws `BaerlyError{code:"InvalidResponse"}`
|
|
214
|
-
* on a malformed body — same contract as the underlying
|
|
215
|
-
* {@link readCurrentJson} helper in `@baerly/protocol`.
|
|
216
|
-
*
|
|
217
|
-
* Backs the `/v1/since` long-poll handler in
|
|
218
|
-
* `packages/server/src/http/since.ts`; that handler needs the parsed
|
|
219
|
-
* `CurrentJson` plus an ETag for the follow-up reads.
|
|
220
|
-
*
|
|
221
|
-
* @internal — typed seam for the HTTP handler; app code should use
|
|
222
|
-
* the collection API.
|
|
223
|
-
*/
|
|
224
|
-
getCurrentJson(collection: string, opts?: {
|
|
225
|
-
signal?: AbortSignal;
|
|
226
|
-
}): Promise<CurrentJsonRead | null>;
|
|
227
|
-
/**
|
|
228
|
-
* Read + parse one `LogEntry` by `seq` from
|
|
229
|
-
* `manifests/<collection>/log/<seq>.json`. Returns `null`
|
|
230
|
-
* when the entry is missing — this typically means the GC sweeper
|
|
231
|
-
* deleted the entry between a `readCurrentJson` and this GET (the
|
|
232
|
-
* `/v1/since` handler treats the race as silent and skips the
|
|
233
|
-
* entry). Throws `BaerlyError{code:"InvalidResponse"}` on a body
|
|
234
|
-
* that isn't valid JSON.
|
|
235
|
-
*
|
|
236
|
-
* @internal — typed seam for the HTTP handler; app code should use
|
|
237
|
-
* the collection API.
|
|
238
|
-
*/
|
|
239
|
-
getLogEntry(collection: string, seq: number, opts?: {
|
|
240
|
-
signal?: AbortSignal;
|
|
241
|
-
}): Promise<LogEntry | null>;
|
|
242
|
-
/**
|
|
243
|
-
* Forward-probe the TRUE committed log tail from `hint` (a lower
|
|
244
|
-
* bound, typically `tail_hint`). Backs the `/v1/since` end-bound.
|
|
245
|
-
*
|
|
246
|
-
* @internal — typed seam for the HTTP handler.
|
|
247
|
-
*/
|
|
248
|
-
probeLogTail(collection: string, hint: number, opts?: {
|
|
249
|
-
signal?: AbortSignal;
|
|
250
|
-
}): Promise<number>;
|
|
251
|
-
}
|
|
252
|
-
//#endregion
|
|
253
|
-
export { validateOrThrow as n, Db as t };
|
|
254
|
-
//# sourceMappingURL=db-DsPkOVEH.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deploy-DonTr-CV.js","names":[],"sources":["../packages/cli/src/deploy.ts"],"sourcesContent":["/**\n * `baerly deploy` — citty dispatcher.\n *\n * Reads `baerly.config.ts:target` and routes to the matching\n * deploy backend. Today: `cloudflare` only — the `node` example\n * embodies its deployment shape directly (self-host via `node\n * server.js` after your PaaS or container build), so `baerly\n * deploy` rejects `target: \"node\"` with an actionable InvalidConfig.\n *\n * Exit-code contract (standard CLI shape):\n * - 0 success.\n * - 1 user error (InvalidConfig, missing config, unknown target).\n * - 2 storage / external error (NetworkError, Wrangler returned\n * non-zero, anything non-BaerlyError).\n * - 3 protocol invariant (Conflict, Internal, InvalidResponse —\n * should not happen here unless someone hand-edited mid-flight).\n */\n\nimport { defineCommand, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { deployCloudflare } from \"./deploy/cloudflare.ts\";\nimport { emitError, emitSuccess, setJsonMode } from \"./output.ts\";\n\nconst DEPLOY_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).',\n valueHint: \"cloudflare\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n probeBucket: {\n type: \"string\",\n description:\n \"Run a live CAS preflight against this bucket URI before deploying (s3://, file:///, memory://); aborts non-zero if the backend fails the conditional-write / exactly-one-winner probe. Same check as `baerly doctor --bucket`.\",\n valueHint: \"s3://bucket/prefix\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\n \"target\",\n \"json\",\n \"probeBucket\",\n \"probe-bucket\",\n \"_\",\n]);\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst handleDeploy = async (args: ParsedArgs<typeof DEPLOY_ARGS>): Promise<number> => {\n setJsonMode(args.json === true);\n try {\n for (const k of Object.keys(args)) {\n if (!KNOWN_KEYS.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly deploy: unknown flag --${k}`);\n }\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const probeBucketUri =\n typeof args.probeBucket === \"string\" && args.probeBucket.length > 0\n ? args.probeBucket\n : undefined;\n const exit = await deployCloudflare(config, { probeBucketUri });\n if (exit === 0) {\n emitSuccess({ command: \"deploy\", status: \"ok\", target });\n }\n return exit;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. ` +\n `Self-host: \\`node server.js\\` after your PaaS or container build. ` +\n `Cloudflare Workers is the only managed deploy backend today.`,\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(\"deploy\", error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(\"deploy\", \"Unknown\", (error as Error).message);\n return 2;\n }\n};\n\n/** citty `defineCommand` block for `baerly deploy`. */\nexport const deploy = defineCommand({\n meta: {\n name: \"deploy\",\n description: \"Deploy this baerly app. Dispatches by baerly.config.ts:target.\",\n },\n args: DEPLOY_ARGS,\n run: async ({ args }) => {\n const code = await handleDeploy(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDeploy = async (argv: readonly string[]): Promise<number> => {\n const { parseArgs } = await import(\"citty\");\n let parsed: ParsedArgs<typeof DEPLOY_ARGS>;\n try {\n parsed = parseArgs<typeof DEPLOY_ARGS>(argv as string[], DEPLOY_ARGS);\n } catch (error) {\n setJsonMode(argv.includes(\"--json\"));\n emitError(\"deploy\", \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return handleDeploy(parsed);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,aAAa;EACX,MAAM;EACN,aACE;EACF,WAAW;CACb;AACF;AAEA,MAAM,6BAAkC,IAAI,IAAI;CAC9C;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;AAEA,MAAM,eAAe,OAAO,SAA0D;CACpF,YAAY,KAAK,SAAS,IAAI;CAC9B,IAAI;EACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,WAAW,IAAI,CAAC,GACnB,MAAM,IAAI,YAAY,iBAAiB,iCAAiC,GAAG;EAG/E,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAK3B,MAAM,OAAO,MAAM,iBAAiB,QAAQ,EAAE,gBAH5C,OAAO,KAAK,gBAAgB,YAAY,KAAK,YAAY,SAAS,IAC9D,KAAK,cACL,KAAA,EACuD,CAAC;GAC9D,IAAI,SAAS,GACX,YAAY;IAAE,SAAS;IAAU,QAAQ;IAAM;GAAO,CAAC;GAEzD,OAAO;EACT;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,uJAGlD;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,aAAa;GAChC,UAAU,UAAU,MAAM,MAAM,MAAM,OAAO;GAC7C,OAAO,gBAAgB,MAAM,IAAI;EACnC;EACA,UAAU,UAAU,WAAY,MAAgB,OAAO;EACvD,OAAO;CACT;AACF;;AAGA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,OAAO,MAAM,aAAa,IAAI;EACpC,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;CAErB;AACF,CAAC"}
|