@gusto/baerly-storage 0.3.0 → 0.4.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 +157 -92
- package/dist/API.md +64 -32
- package/dist/CHANGELOG.md +295 -5
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +22 -96
- package/dist/{app-config-BIzyAKzy.d.ts → app-config-DyiFK3_k.d.ts} +43 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +13 -13
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/{client-BJXF3XJA.d.ts → client-Fe8CwB73.d.ts} +3 -3
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/{cloudflare-Cn2ibODt.js → cloudflare-DzKBrUlg.js} +2 -2
- package/dist/{cloudflare-Cn2ibODt.js.map → cloudflare-DzKBrUlg.js.map} +1 -1
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +55 -21
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/{cost-BZ_MDBmn.js → cost-DSMIVqzL.js} +42 -43
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/{current-json-DsN7FNY1.js → current-json-C6nhPOm1.js} +6 -204
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-CCT6tDfY.d.ts → db-DsPkOVEH.d.ts} +3 -3
- package/dist/{deploy-BKKyGlSJ.js → deploy-DonTr-CV.js} +4 -4
- package/dist/{deploy-BKKyGlSJ.js.map → deploy-DonTr-CV.js.map} +1 -1
- package/dist/dev-vite.d.ts +9 -5
- package/dist/dev-vite.js +5 -4
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-BVU4GNXN.js → doctor-DSIyCDg_.js} +5 -8
- package/dist/{doctor-BVU4GNXN.js.map → doctor-DSIyCDg_.js.map} +1 -1
- package/dist/{dump-DPEAKub6.js → dump-Bh5k26VQ.js} +9 -32
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-BcuCLFFe.js → export-DtF5tDIM.js} +9 -32
- package/dist/{export-BcuCLFFe.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-RXgLOaJG.js → fsck-D_djMO5D.js} +10 -33
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Bd4byR4n.js → http-DxM9MflO.js} +123 -35
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DnBGSeuU.d.ts → index-0rZcMBwy.d.ts} +2 -2
- package/dist/{index-Cmsxx-ZN.d.ts → index-B6oexfOB.d.ts} +7 -7
- package/dist/{index-BDceQQi-.d.ts → index-BNRh23K9.d.ts} +4 -4
- package/dist/{index-DW7GT6M2.d.ts → index-BYk9oCNf.d.ts} +193 -163
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-Cx7uMXm0.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-DhI49PSi.js → inspect-6WZ-pC7-.js} +10 -33
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{log-tail-DXeDkWEp.js → log-tail-D98U1JBo.js} +31 -7
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-CWBQpZ2y.js → maintenance-B4Dki6Ig.js} +77 -22
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BkhUr72A.d.ts → maintenance-B_e0T99L.d.ts} +28 -5
- package/dist/{maintenance-C_KSkVjd.js → maintenance-C7coQp4c.js} +17 -16
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -3
- package/dist/maintenance.js +3 -3
- package/dist/node.d.ts +168 -65
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-BYd-RzEx.js → observability-wzs3-BL_.js} +233 -71
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +2 -2
- package/dist/observability.js +1 -1
- package/dist/{plan-DIu_B6fy.js → plan-a7PJHBCy.js} +2 -2
- package/dist/{plan-DIu_B6fy.js.map → plan-a7PJHBCy.js.map} +1 -1
- package/dist/{query-sQNO5vU_.js → query-rAtXNQQB.js} +96 -207
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DP4CqSSs.js → rebuild-index-BVzQSZlm.js} +9 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/{restore-DpQYef6r.js → restore-R-4rbciV.js} +73 -100
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-Db4-qVtM.js → src-CYHFDrKz.js} +51 -8
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-CWpkSbvJ.js → src-DYZ4H1aF.js} +6 -5
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/{subcommand-CP9NY2J4.js → subcommand-DoDA-K7d.js} +44 -6
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CTfDq9HR.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +52 -28
- package/dist/config-CGyBopy3.js +0 -5326
- package/dist/config-CGyBopy3.js.map +0 -1
- package/dist/cost-BZ_MDBmn.js.map +0 -1
- package/dist/current-json-DsN7FNY1.js.map +0 -1
- package/dist/dump-DPEAKub6.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-RXgLOaJG.js.map +0 -1
- package/dist/http-Bd4byR4n.js.map +0 -1
- package/dist/inspect-DhI49PSi.js.map +0 -1
- package/dist/log-tail-DXeDkWEp.js.map +0 -1
- package/dist/maintenance-CWBQpZ2y.js.map +0 -1
- package/dist/maintenance-C_KSkVjd.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-BYd-RzEx.js.map +0 -1
- package/dist/query-sQNO5vU_.js.map +0 -1
- package/dist/rebuild-index-DP4CqSSs.js.map +0 -1
- package/dist/restore-DpQYef6r.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/src-CWpkSbvJ.js.map +0 -1
- package/dist/src-D24wDpzR.js +0 -6247
- package/dist/src-D24wDpzR.js.map +0 -1
- package/dist/src-Db4-qVtM.js.map +0 -1
- package/dist/subcommand-CP9NY2J4.js.map +0 -1
- package/dist/usage-CTfDq9HR.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cost-BZ_MDBmn.js","names":[],"sources":["../packages/cli/src/cost/provider.ts","../packages/cli/src/cost/project.ts","../packages/cli/src/cost.ts"],"sourcesContent":["/**\n * Provider sniffer: maps a bucket URI + optional S3 endpoint into a\n * pricing tag, and resolves that tag into a `ProviderPricing`\n * record. Pure — zero I/O.\n *\n * Detection rules (first match wins):\n * - `file://*` → \"dev\"\n * - `memory://*` → \"dev\"\n * - `s3://*` + endpoint matching `*.r2.cloudflarestorage.com` → \"r2\"\n * - `s3://*` + endpoint matching `*.amazonaws.com` → \"aws-s3\"\n * - `s3://*` + no endpoint → \"aws-s3\"\n * - everything else (Minio, Backblaze, on-prem, unknown s3 endpoint) → \"self-hosted\"\n *\n * `override` skips detection entirely — used by the\n * `baerly inspect --provider=...` CLI flag when auto-detection picks\n * wrong (e.g., a self-hosted S3 gateway in front of R2).\n */\n\nimport type { ProviderPricing } from \"./project.ts\";\n\nexport type ProviderTag = ProviderPricing[\"provider\"];\n\nexport interface DetectArgs {\n /** Raw bucket URI as passed on the CLI (s3://, file://, memory://). */\n readonly bucketUri: string;\n /** Effective S3 endpoint at parse time (typically `process.env[\"BAERLY_S3_ENDPOINT\"]`). */\n readonly s3Endpoint?: string;\n /** When set, skip detection and return this tag. */\n readonly override?: ProviderTag;\n}\n\nexport const detectProvider = (args: DetectArgs): ProviderTag => {\n if (args.override !== undefined) {\n return args.override;\n }\n if (args.bucketUri.startsWith(\"file://\")) {\n return \"dev\";\n }\n if (args.bucketUri.startsWith(\"memory://\")) {\n return \"dev\";\n }\n if (!args.bucketUri.startsWith(\"s3://\")) {\n return \"self-hosted\";\n }\n // s3:// branch — look at the endpoint.\n const endpoint = args.s3Endpoint ?? \"\";\n if (endpoint === \"\") {\n return \"aws-s3\";\n } // default AWS\n if (/\\.r2\\.cloudflarestorage\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"r2\";\n }\n if (/\\.amazonaws\\.com(:\\d+)?\\/?$/i.test(endpoint)) {\n return \"aws-s3\";\n }\n return \"self-hosted\";\n};\n\n/**\n * R2 price table.\n * Source: <https://developers.cloudflare.com/r2/pricing/> (review date 2026-05-17).\n * Change-control: pair every edit with a `docs/about/pricing-log.md` entry.\n */\nconst R2_PRICING: ProviderPricing = {\n provider: \"r2\",\n freeClassAPerMonth: 1_000_000,\n usdPerMillionClassA: 4.5,\n freeStorageGb: 10,\n usdPerGbMonth: 0.015,\n};\n\n/**\n * AWS S3 (Standard) price table.\n * Source: <https://aws.amazon.com/s3/pricing/> (review date 2026-05-17).\n * The 12-month new-account free tier is intentionally excluded\n * (most operators are past it; reporting $0 to them would lie).\n */\nconst AWS_S3_PRICING: ProviderPricing = {\n provider: \"aws-s3\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: 5,\n freeStorageGb: 0,\n usdPerGbMonth: 0.023,\n};\n\nconst SELF_HOSTED_PRICING: ProviderPricing = {\n provider: \"self-hosted\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n};\n\nconst DEV_PRICING: ProviderPricing = {\n provider: \"dev\",\n freeClassAPerMonth: 0,\n usdPerMillionClassA: Number.NaN,\n freeStorageGb: 0,\n usdPerGbMonth: Number.NaN,\n};\n\nexport const pricingFor = (provider: ProviderTag): ProviderPricing => {\n switch (provider) {\n case \"r2\": {\n return R2_PRICING;\n }\n case \"aws-s3\": {\n return AWS_S3_PRICING;\n }\n case \"self-hosted\": {\n return SELF_HOSTED_PRICING;\n }\n case \"dev\": {\n return DEV_PRICING;\n }\n }\n};\n","/**\n * Pure projection math for the `baerly inspect` cost-trajectory\n * footer. Zero I/O. Price tables live as top-level constants; every\n * change MUST be paired with a `docs/about/pricing-log.md` entry.\n *\n * Three rules:\n * 1. `classAPerMonth = writesPerMin × 60 × 24 × 30 × 3`. The `× 3`\n * is the protocol's enforced write-amp ceiling\n * (`docs/about/cost-model.md:43-44`); snapshot writes\n * amortize and are excluded from the headline.\n * 2. `projectedUsdPerMonth = 0` exactly when both `classAPerMonth\n * ≤ pricing.freeClassAPerMonth` AND `storedBytes ≤\n * pricing.freeStorageGb × 1GB`. Say `$0`, not `$0.00`. `null`\n * for self-hosted/dev (no $ model).\n * 3. Returns `null` when `writesPerMin` is non-finite (no-data case\n * from `estimateWritesPerMin`); inspect renders no footer.\n */\n\n/** R2 / AWS S3 / self-hosted / dev price table. */\nexport interface ProviderPricing {\n readonly provider: \"r2\" | \"aws-s3\" | \"self-hosted\" | \"dev\";\n /** Free-tier Class A ops per month; 0 if no free tier. */\n readonly freeClassAPerMonth: number;\n /** $/1M Class A above free tier. NaN for \"self-hosted\" / \"dev\". */\n readonly usdPerMillionClassA: number;\n /** Free-tier stored GB; 0 if no free tier. */\n readonly freeStorageGb: number;\n /** $/GB-month above free tier. NaN for \"self-hosted\" / \"dev\". */\n readonly usdPerGbMonth: number;\n}\n\n/**\n * Graduation triggers — sustained for 7 days, any one of these\n * means the workload has outgrown Baerly's positioning.\n *\n * Source: `docs/about/cost-model.md:159-163`.\n */\nexport const GRADUATION_CLASS_A_PER_MONTH = 50_000_000;\n// GRADUATION_WRITE_AMP = 6 — sustained write-amp at this level\n// suggests the workload is too bursty for the M-size positioning.\n// Not yet wired into project(); kept for the storedBytes follow-up.\n// GRADUATION_STORED_BYTES = 5 * 1024 * 1024 * 1024 — storage graduation\n// trigger (~5 GB). Not yet wired; deferred alongside write-amp gating.\n\n/** What the inspect footer renders from. */\nexport interface Trajectory {\n readonly writesPerMin: number;\n readonly classAPerMonth: number;\n /** Percent of provider's free-tier Class A budget. `null` when the provider has no free tier (aws-s3) or no $ model (self-hosted/dev). */\n readonly percentOfFreeTier: number | null;\n /** Percent of the 50M/mo graduation trigger. Always a finite number. */\n readonly percentOfGraduation: number;\n /** Projected USD/month. `0` when fully inside the free tier. `null` when the provider has no $ model (self-hosted/dev). */\n readonly projectedUsdPerMonth: number | null;\n readonly withinFreeTier: boolean;\n readonly provider: ProviderPricing[\"provider\"];\n}\n\n/**\n * Protocol write-amp ceiling: every logical write produces exactly\n * 2 Class A ops (PUT content + the committing `log/<seq>` create).\n * There is no `current.json` CAS on the commit path — the winning\n * log create IS the commit. Source: `docs/about/cost-model.md:43-44`.\n */\nconst PROTOCOL_WRITE_AMP = 2;\n\n/** Minutes per month × write-amp = Class A ops/month per write/min. */\nconst OPS_PER_WPM_PER_MONTH = 60 * 24 * 30 * PROTOCOL_WRITE_AMP;\n\n/**\n * Project a `writesPerMin` rate (typically from\n * `estimateWritesPerMin`) into a monthly cost trajectory.\n *\n * Returns `null` when `writesPerMin` is non-finite. The caller\n * (inspect) renders no footer in that case.\n */\nexport const project = (\n writesPerMin: number,\n storedBytes: number,\n pricing: ProviderPricing,\n): Trajectory | null => {\n if (!Number.isFinite(writesPerMin)) {\n return null;\n }\n\n const classAPerMonth = writesPerMin * OPS_PER_WPM_PER_MONTH;\n\n const percentOfGraduation = (classAPerMonth / GRADUATION_CLASS_A_PER_MONTH) * 100;\n\n const percentOfFreeTier =\n pricing.freeClassAPerMonth > 0 ? (classAPerMonth / pricing.freeClassAPerMonth) * 100 : null;\n\n const storedGb = storedBytes / (1024 * 1024 * 1024);\n const withinFreeTier =\n pricing.freeClassAPerMonth > 0 &&\n classAPerMonth <= pricing.freeClassAPerMonth &&\n storedGb <= pricing.freeStorageGb;\n\n let projectedUsdPerMonth: number | null;\n if (Number.isNaN(pricing.usdPerMillionClassA)) {\n projectedUsdPerMonth = null;\n } else if (withinFreeTier) {\n projectedUsdPerMonth = 0;\n } else {\n const classAOverage = Math.max(0, classAPerMonth - pricing.freeClassAPerMonth);\n const storageOverage = Math.max(0, storedGb - pricing.freeStorageGb);\n projectedUsdPerMonth =\n (classAOverage / 1_000_000) * pricing.usdPerMillionClassA +\n storageOverage * pricing.usdPerGbMonth;\n }\n\n return {\n writesPerMin,\n classAPerMonth,\n percentOfFreeTier,\n percentOfGraduation,\n projectedUsdPerMonth,\n withinFreeTier,\n provider: pricing.provider,\n };\n};\n","/**\n * `baerly cost` — projected cost trajectory for one collection.\n *\n * Sniffs the writes/min rate over the trailing log sample for one\n * collection and projects it into a free-tier-aware monthly Class A\n * + storage cost projection vs. the M-size graduation trigger\n * (50M Class A/mo). Read-only; never mutates anything.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --provider Optional. r2 | aws-s3 | self-hosted | dev. Overrides\n * the auto-detected provider (bucket URI +\n * BAERLY_S3_ENDPOINT).\n * --json JSON envelope.\n *\n * Cost shape:\n * 1 LIST log/ prefix\n * + up to 120 GETs for trailing log entries (`SAMPLE_SIZE`)\n *\n * Exit codes:\n * 0 — projection rendered.\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag,\n * insufficient log entries to estimate, dev backend).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"./output.ts\";\nimport { detectProvider, pricingFor, type ProviderTag } from \"./cost/provider.ts\";\nimport { project, type Trajectory } from \"./cost/project.ts\";\nimport { estimateWritesPerMin } from \"./admin/usage.ts\";\nimport { assertCollectionArg, defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst COST_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 provider: {\n type: \"string\",\n required: false,\n description:\n \"Override pricing provider (r2|aws-s3|self-hosted|dev). Auto-detected from bucket URI + BAERLY_S3_ENDPOINT.\",\n valueHint: \"r2|aws-s3|self-hosted|dev\",\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\n/** Compact \"1.5M\" / \"22k\" / \"842\" rendering for Class A op counts. */\nconst formatOps = (n: number): string => {\n if (n >= 1_000_000) {\n return `${(n / 1_000_000).toFixed(1)}M`;\n }\n if (n >= 1_000) {\n return `${(n / 1_000).toFixed(0)}k`;\n }\n return n.toFixed(0);\n};\n\n/** Two-line trajectory block. Three output states per design spec §4.2. */\nconst renderTrajectory = (t: Trajectory): string => {\n const wpm = t.writesPerMin.toFixed(t.writesPerMin < 10 ? 1 : 0);\n const classA = formatOps(t.classAPerMonth);\n // State 2: ops-only — provider known but no $ model. Today only\n // self-hosted reaches this (dev is filtered out upstream).\n if (t.projectedUsdPerMonth === null) {\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo`,\n ` ${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger. Self-hosted — bill model not modelled.`,\n ].join(\"\\n\");\n }\n // Only \"r2\" can reach withinFreeTier===true (aws-s3 has freeClassAPerMonth: 0).\n // self-hosted/dev are filtered upstream.\n const usd = t.withinFreeTier\n ? `~$0 (R2 free tier)`\n : `~$${t.projectedUsdPerMonth!.toFixed(2)}/mo`;\n // Invariant: withinFreeTier===true implies pricing.freeClassAPerMonth>0,\n // which in turn implies percentOfFreeTier!==null (see project.ts).\n const tail = t.withinFreeTier\n ? `${t.percentOfFreeTier!.toFixed(0)}% of free-tier Class A budget. ${t.percentOfFreeTier! < 50 ? \"Well inside the promise.\" : \"Approaching free-tier ceiling.\"}`\n : `${t.percentOfGraduation.toFixed(2)}% of 50M/mo graduation trigger.`;\n return [\n ` trajectory: ~${wpm} writes/min → ~${classA} Class A/mo → ${usd}`,\n ` ${tail}`,\n ].join(\"\\n\");\n};\n\nconst PROVIDER_TAGS: ReadonlySet<string> = new Set([\"r2\", \"aws-s3\", \"self-hosted\", \"dev\"]);\n\nconst bundle = defineBaerlySubcommand({\n name: \"cost\",\n meta: {\n description: \"Project a collection's monthly Class A + storage cost trajectory.\",\n },\n args: COST_ARGS,\n handler: async (args, ctx) => {\n if (typeof args.provider === \"string\" && args.provider.length > 0) {\n if (!PROVIDER_TAGS.has(args.provider)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: --provider must be one of r2|aws-s3|self-hosted|dev (got ${JSON.stringify(args.provider)})`,\n );\n }\n }\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly cost\");\n\n const override =\n typeof args.provider === \"string\" && args.provider.length > 0\n ? (args.provider as ProviderTag)\n : undefined;\n const provider = detectProvider({\n bucketUri: args.bucket,\n s3Endpoint: process.env[\"BAERLY_S3_ENDPOINT\"],\n override,\n });\n if (provider === \"dev\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: dev backends (file://, memory://) have no $ model; pass --provider=r2|aws-s3|self-hosted to project against one.`,\n );\n }\n\n const verdict = await estimateWritesPerMin(bucket.storage, app, tenant, args.collection, {\n keyPrefix: bucket.keyPrefix,\n });\n const trajectory = project(verdict.writesPerMin, 0, pricingFor(provider));\n if (trajectory === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly cost: not enough log entries under ${args.collection} to estimate writes/min (need >= 2)`,\n );\n }\n\n if (isJsonMode()) {\n emitSuccess({ command: \"cost\", collection: args.collection, trajectory });\n } else {\n process.stdout.write(`baerly cost ${args.collection}\\n${renderTrajectory(trajectory)}\\n`);\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly cost`. */\nexport const cost = 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 runCost = bundle.run;\n"],"mappings":";;;;;AA+BA,MAAa,kBAAkB,SAAkC;CAC/D,IAAI,KAAK,aAAa,KAAA,GACpB,OAAO,KAAK;CAEd,IAAI,KAAK,UAAU,WAAW,SAAS,GACrC,OAAO;CAET,IAAI,KAAK,UAAU,WAAW,WAAW,GACvC,OAAO;CAET,IAAI,CAAC,KAAK,UAAU,WAAW,OAAO,GACpC,OAAO;CAGT,MAAM,WAAW,KAAK,cAAc;CACpC,IAAI,aAAa,IACf,OAAO;CAET,IAAI,2CAA2C,KAAK,QAAQ,GAC1D,OAAO;CAET,IAAI,+BAA+B,KAAK,QAAQ,GAC9C,OAAO;CAET,OAAO;AACT;;;;;;AAOA,MAAM,aAA8B;CAClC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;AACjB;;;;;;;AAQA,MAAM,iBAAkC;CACtC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;AACjB;AAEA,MAAM,sBAAuC;CAC3C,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;AACjB;AAEA,MAAM,cAA+B;CACnC,UAAU;CACV,oBAAoB;CACpB,qBAAqB;CACrB,eAAe;CACf,eAAe;AACjB;AAEA,MAAa,cAAc,aAA2C;CACpE,QAAQ,UAAR;EACE,KAAK,MACH,OAAO;EAET,KAAK,UACH,OAAO;EAET,KAAK,eACH,OAAO;EAET,KAAK,OACH,OAAO;CAEX;AACF;;;;;;;;;AC/EA,MAAa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YAAY,aAAa;EAElD,MAAM,WACJ,OAAO,KAAK,aAAa,YAAY,KAAK,SAAS,SAAS,IACvD,KAAK,WACN,KAAA;EACN,MAAM,WAAW,eAAe;GAC9B,WAAW,KAAK;GAChB,YAAY,QAAQ,IAAI;GACxB;EACF,CAAC;EACD,IAAI,aAAa,OACf,MAAM,IAAI,YACR,iBACA,+HACF;EAMF,MAAM,aAAa,SAAQ,MAHL,qBAAqB,OAAO,SAAS,KAAK,QAAQ,KAAK,YAAY,EACvF,WAAW,OAAO,UACpB,CAAC,EAAA,CACkC,cAAc,GAAG,WAAW,QAAQ,CAAC;EACxE,IAAI,eAAe,MACjB,MAAM,IAAI,YACR,iBACA,6CAA6C,KAAK,WAAW,oCAC/D;EAGF,IAAI,WAAW,GACb,YAAY;GAAE,SAAS;GAAQ,YAAY,KAAK;GAAY;EAAW,CAAC;OAExE,QAAQ,OAAO,MAAM,eAAe,KAAK,WAAW,IAAI,iBAAiB,UAAU,EAAE,GAAG;EAE1F,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,OAAO,OAAO;AAOJ,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"current-json-DsN7FNY1.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 * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key\n * over this fails the PUT with an opaque provider 400; baerly surfaces\n * it early as InvalidConfig. See docs/spec/storage-compatibility.md.\n */\nexport const MAX_KEY_BYTES = 1024;\n\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 descending base-32 seq segment in every LSN\n * (`<base32-time>_<session>_<seq>`, minted in `Writer.commit`).\n * The output character width is `Math.ceil(COUNT_BIT_WIDTH / 5) = 11`.\n *\n * **Domain:** 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1). A collection\n * would need 2^53 writes before the seq counter could overflow — an\n * unreachable ceiling in practice.\n *\n * **Why 53 bits:** JavaScript numbers are IEEE-754 doubles; the safe\n * integer range is exactly [0, 2^53 − 1]. Encoding at this width keeps\n * the arithmetic in the encoder and decoder (`uint2strDesc` /\n * `str2uintDesc` in `packages/protocol/src/types.ts`) exact and\n * leaves no headroom for the negative-overflow path that manifested\n * at the old 10-bit width (domain 0..1023).\n *\n * **Ordering property:** fixed-width base-32 encoding preserves\n * descending lex order across the entire domain\n * (`countKey(a) > countKey(b)` iff `a < b`), which the reverse-walk\n * on `Storage.list` relies on.\n *\n * **Three production consumers** must all agree on this value:\n * 1. Encoder — `countKey` in `packages/protocol/src/types.ts`\n * 2. Decoder — `lsnParts` in `packages/protocol/src/log.ts`\n * 3. Validator regex — `LSN_RE` in `packages/server/src/http/since.ts`\n * (derives its `{N}` from `Math.ceil(COUNT_BIT_WIDTH / 5)`)\n *\n * The independent shape-assertion literal in\n * `tests/fixtures/collection-api-cascade.ts` is kept hand-written and\n * is NOT a consumer of this constant (importing the production\n * validator into the test that checks it would make the assertion\n * a tautology).\n *\n * Changing this constant is a protocol-breaking change — it reshapes\n * every emitted LSN cursor.\n *\n * @see packages/protocol/src/types.ts (`countKey`, `uint2strDesc`)\n * @see packages/protocol/src/log.ts (`lsnParts`, `str2uintDesc` call)\n * @see packages/server/src/http/since.ts (`LSN_RE`)\n * @see docs/spec/log-entry-shape.md\n */\nexport const COUNT_BIT_WIDTH: number = 53;\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 * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):\n * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`\n * (rather than silently truncating reads). A runaway alarm only — the\n * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means\n * maintenance is off or the collection is far past graduation.\n *\n * @see packages/server/src/log-tail.ts (`probeTailFrom`)\n */\nexport const LOG_FORWARD_PROBE_CAP: number = 100_000;\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 = 3 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 */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\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 * Bounded retry cap for the `gc/pending.json` CAS read-modify-write\n * loop in {@link casUpdateGcPending}. On `Conflict` (a concurrent GC\n * pass landed between this pass's read and its write) the loop\n * re-reads `latest` and re-applies the pure merge mutator, retrying up\n * to this many total attempts before surfacing `Conflict`. Safe to\n * retry because the mutator is pure and the sweep DELETEs are\n * idempotent and already performed; a re-merge against fresh state\n * never loses a concurrently-marked candidate. Small fixed cap — under\n * one writer per collection at steady state, contention is rare; this\n * just bounds the worst case so a pathological storm can't spin.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CAS_MAX_ATTEMPTS: number = 3;\n\n/**\n * Fold-trigger ratio: fold fires at tail ≥ R×snapshot. Pure READ-AMP / fold-frequency\n * knob — with the ceiling on the snapshot axis (Decision 3a, tail sliced) the\n * auto-maintained snapshot ceiling is S_max = C, NOT C/(1+R). R=1.0 caps steady-state\n * read-amp at ~2× and keeps compaction write-amp (≈1+1/R) moderate. See\n * docs/about/graduation.md for the derivation.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TARGET_RATIO: number = 1;\n\n/**\n * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also\n * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.\n *\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MIN_LIVE_BYTES: number = 64 * 1024;\n\n/**\n * Cold-start per-entry byte estimate for the ratio TRIGGER's derived live-tail\n * size (`estimateTailBytes`), used until the compactor stamps a real\n * `current.json.mean_entry_bytes` on the first fold. Folding too-few entries is\n * barred by Gate-1's entry-count floor (`minEntriesToCompact`), NOT by this\n * value — so over-estimating is equally safe; this is a first-fold-TIMING\n * choice. A small typical log-entry size keeps the first fold's cadence close\n * to a precisely measured path for typical entries; must be non-zero so a\n * bare `Db.create()` still bootstraps its first auto-fold (a 0 fallback leaves\n * the ratio dead pre-stamp). Large-body collections see a bounded first-fold\n * delay; after it stamps a real mean the estimate tracks the exact tail.\n *\n * @see packages/server/src/maintenance.ts (`estimateTailBytes`)\n */\n// Stryker disable next-line ArithmeticOperator: internal cold-start tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_COLD_START_ENTRY_BYTES: number = 128;\n\n/**\n * Per-tick GC budget — these are DEFAULTS (= the most-constrained tier, CF free, reusing\n * the TESTED `CLOUDFLARE_FREE_TIER` values in maintenance.ts / maintenance.budget.test.ts).\n * The adapter THREADS per-tier overrides into the context (§8.4); Node/CF-paid raise them.\n * NOT universal constants — a Node-sized value here would silently kill every CF-free fold\n * (round-4 Tier-1). gc pass ≈ 6 + maxMarks + maxSweeps subrequests (both GET/DELETE the\n * bucket — §3.1). Cadence is BOUNDARY-CROSSING (§3.1), not modulo.\n *\n * @see packages/server/src/maintenance.ts\n * @see packages/server/src/maintenance.budget.test.ts\n */\nexport const WRITE_TICK_GC_INTERVAL: number = 4; // tuned so maxSweeps/interval ≥ p (§7.1)\n\n/**\n * Fold-starvation guard (critique A): on `phasesPerTick:\"single\"`, every Nth GC-interval is a\n * HARD GC boundary the fold may NOT preempt, so a long fold-heavy drain can't starve GC to zero.\n * Stateless (seq-derived) — no per-isolate preemption counter (CF recycles isolates). At 4 a\n * sustained drain still yields ~1 GC tick per 4 GC-intervals.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const GC_STARVATION_GUARD: number = 4;\n\n/**\n * Maximum GC marks per write-tick pass (M in 6+M+S; GETs the live tail to hash).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_MARKS: number = 20;\n\n/**\n * Maximum GC sweeps per write-tick pass (S in 6+M+S; DELETE subrequests).\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_SWEEPS: number = 10;\n\n/**\n * Per-pass tail SLICE default — compact()'s maxEntriesPerRun. Fold ≤ this+3 subrequests, so\n * a large tail drains incrementally over write-ticks (Decision 3). Adapter-overridable.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_FOLD_ENTRIES_PER_PASS: number = 20;\n\n/**\n * compact()'s minEntriesToCompact, set EXPLICITLY by the runner so it agrees with Gate 1\n * rather than inheriting compact()'s silent default 100 (which would contradict the 64 KB\n * first-fold story — round-4 Tier-3). Adapter-overridable; CF-free value.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_MIN_ENTRIES_TO_COMPACT: number = 50;\n\n/**\n * Node-tier write-tick maintenance caps — a MODERATE multiple of the CF-free `WRITE_TICK_*`\n * defaults, threaded into the per-request observability context by `baerlyNode` /\n * `createFetchHandler` (§8.4). Node v1 runs maintenance INLINE on the commit path (no\n * `waitUntil`), so the cap is NOT the CF subrequest wall — it's the worst-case single-write\n * added latency. A maintenance tick only fires on a ratio/boundary trip (rare), and when it\n * does it costs ~`maxFoldEntriesPerPass` + (6 + `gcMaxMarks` + `gcMaxSweeps`) storage\n * round-trips against a co-located S3/R2 — sub-second on the occasional boundary write at a\n * 10× multiple. These are deliberately BOUNDED (10× CF-free), NOT unbounded: the deleted\n * scheduled full-tail sweep folded the entire live tail in one shot, which a 100× multiple here\n * would reintroduce as multi-second commit stalls. Raise the snapshot ceiling separately via\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; these caps slice the per-pass work, not the ceiling.\n *\n * @see packages/adapter-node/src/server.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\nexport const NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS: number = 200;\n\n/** Node-tier GC marks per pass (M in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_MARKS: number = 200;\n\n/** Node-tier GC sweeps per pass (S in 6+M+S). 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_SWEEPS: number = 100;\n\n/**\n * Node-tier GC cadence (boundary-crossing). Shorter than the CF-free `WRITE_TICK_GC_INTERVAL`\n * (4) so the per-write sweep budget keeps up: `gcMaxSweeps / gcInterval = 100 / 2 = 50`\n * comfortably clears the garbage-per-write rate `p` (the `maxSweeps/interval ≥ p` invariant,\n * §7.1) with a wide margin.\n *\n * @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS}\n */\nexport const NODE_MAINTENANCE_GC_INTERVAL: number = 2;\n\n/**\n * SNAPSHOT-rebuild ceiling `C` (the unsliceable axis — Decision 3a), memory. Default sized\n * ~5.5 ms under CF-free ~10 ms. Raise via BAERLY_MAINTENANCE_MAX_FOLD_BYTES on capable\n * hosts. Auto-maintained snapshot ceiling S_max = C. NOT snapshot+tail (tail is sliced).\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MAX_FOLD_BYTES_DEFAULT: number = 512 * 1024;\n\n/**\n * The largest snapshot a Cloudflare **free-tier** isolate can safely\n * rebuild in ONE fold under the ~10 ms CPU budget. This is the WARN\n * THRESHOLD, not a runtime cap: an operator who raises\n * `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` ABOVE this value on a free Worker\n * risks a snapshot rebuild that exceeds the ~10 ms CPU limit and gets\n * CPU-killed MID-REBUILD — the CAS never lands, so the fold silently\n * never advances `log_seq_start` and the tail grows unbounded.\n *\n * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The default\n * (512 KiB) rebuilds in ~5.5 ms under the CF-free ~10 ms budget\n * (constants.ts default JSDoc); linear-extrapolating, ~1 MiB is the\n * point where one-shot rebuild fills the budget with little margin, so\n * anything strictly larger is no longer free-tier-safe. On CF **paid**\n * (raised CPU limits), Node, or once §11 chunked snapshots land, a\n * larger ceiling is fine — hence this is a one-time `console.warn` at\n * handler init, NOT a hard rejection.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/about/graduation.md\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const CF_FREE_MAX_SAFE_FOLD_BYTES: number = 1024 * 1024;\n\n/**\n * SNAPSHOT-rebuild ceiling `E`, per-entry CPU axis: gates `snapshot_rows` (per-entry\n * parse/merge/serialize is ~half of fold CPU and scales with ROW COUNT not bytes, VLDB 2021\n * Sarkar — a tiny-doc snapshot can blow CPU under C). PROVISIONAL — bench\n * landed; paid recalibration deferred.\n *\n * @see docs/about/graduation.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_MAX_FOLD_ROWS: number = 2048;\n\n// Declared here (not the nominal server `MaintenanceProfile`) to avoid a server→protocol cycle; keep field-identical to it.\ntype MaintenanceProfileShape = Readonly<{\n gcInterval: number;\n gcMaxMarks: number;\n gcMaxSweeps: number;\n maxFoldEntriesPerPass: number;\n maxFoldBytes: number;\n maxFoldRows: number;\n}>;\n\n/** CF-free profile; the absent-context default. */\nexport const MAINTENANCE_PROFILE_CF_FREE: MaintenanceProfileShape = {\n gcInterval: WRITE_TICK_GC_INTERVAL,\n gcMaxMarks: WRITE_TICK_GC_MAX_MARKS,\n gcMaxSweeps: WRITE_TICK_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/** Node profile; 10× CF-free caps. */\nexport const MAINTENANCE_PROFILE_NODE: MaintenanceProfileShape = {\n gcInterval: NODE_MAINTENANCE_GC_INTERVAL,\n gcMaxMarks: NODE_MAINTENANCE_GC_MAX_MARKS,\n gcMaxSweeps: NODE_MAINTENANCE_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/**\n * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate\n * memory — CF recycles isolates). ~once per this many writes.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_WARN_INTERVAL_WRITES: number = 1000;\n\n/**\n * Rate-limit for the maintenance tick's `tail_hint` advance on the\n * DEFER path (HR-2). When the fold defers (snapshot over the CF-CPU-kill\n * ceiling) the compactor never stamps `tail_hint` via its Step-7 fold\n * CAS, so the gap `(true_tail − tail_hint)` would grow without bound and\n * every read would re-walk the whole live tail via `probeTailFrom`. The\n * runner therefore advances `tail_hint` toward the observed tail with a\n * best-effort `current.json` CAS — but only once per this many writes,\n * so it is NOT a per-commit `current.json` write (which is exactly what\n * single-write commit removed).\n *\n * Sized at 128: it bounds a deferring collection's worst-case\n * read-walk to ≤128 forward GETs (≈one extra read-page sweep — a\n * negligible per-read latency cost), keeps the gap two-to-three orders\n * of magnitude below {@link LOG_FORWARD_PROBE_CAP} (so the cap-throw is a\n * pure runaway guard, never reached in normal operation), and holds the\n * hint-advance CAS rate under ~1% of the commit rate (negligible\n * Class-A cost, amortized). Smaller would tighten the read-walk at a\n * higher CAS rate; larger would loosen it — 128 is the modest middle.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TAIL_HINT_REFRESH_WRITES: number = 128;\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>@<tail_hint>\"`, 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 * Two Class A ops: PUT content + the committing `log/<seq>` create\n * (`If-None-Match: \"*\"`). There is no `current.json` CAS on the commit\n * path — the winning log create IS the commit. The cost-model page\n * derives the free-tier write budget from this multiplier; the phase-5\n * end-to-end test asserts it at CI time. Changing this constant is a\n * 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 = 2;\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 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-007).\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} is a pre-single-write-commit current.json; re-provision the bucket. Pre-launch, no production buckets — delete and re-seed the local-fs/Minio/Verdaccio scratch bucket, or recreate the R2/S3 bucket.`,\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":";;;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,UAAU,KAAK,CAAC;AAEhD,MAAa,mBAAgC,UAC3C,KAAK,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC;;;;;;;;ACJ5C,MAAa,gBAAgB;;;;;AAuG7B,MAAa,4BAAoC;;;;;;;;;;AAoDjD,MAAa,wBAAgC;;;;;;;;AAsB7C,MAAa,4BAAoC;;;;;;AAoBjD,MAAa,0BAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC/C,MAAa,yBAAiC,QAAc,KAAK;;;;;;;;;;AAWjE,MAAa,4BAAoC;;;;;;;AAqCjD,MAAa,6BAAqC,KAAK;;;;;;;;;AAqHvD,MAAa,qCAA6C,MAAM;;;;;;;;;;;;;;;;;;;;;;;AAyBhE,MAAa,8BAAsC,OAAO;;;;;;;;;;AAW1D,MAAa,4BAAoC;;AAajD,MAAa,8BAAuD;CAClE,YAAA;CACA,YAAA;CACA,aAAA;CACA,uBAAA;CACA,cAAc;CACd,aAAa;AACf;;AAGA,MAAa,2BAAoD;CAC/D,YAAA;CACA,YAAA;CACA,aAAA;CACA,uBAAA;CACA,cAAc;CACd,aAAa;AACf;;;;;;;;AASA,MAAa,mCAA2C;;;;;;;;;;AAmCxD,MAAa,kCAA0C;;;;;;;;;;;;;;;;AAiBvD,MAAa,uBAA4C,IAAI,IAAI;CAC/D;CACA;CACA;AACF,CAAC;;;;;;;;;;;;AA6CD,MAAa,6BACX;;;;;AAMF,MAAa,gCACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC7XF,eAAsB,gBACpB,SACA,KACA,MACiC;CACjC,MAAM,MAAM,MAAM,QAAQ,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AI,WAAW,OAAO,CAAC,KAAK,CAAC;AAClG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dump-DPEAKub6.js","names":[],"sources":["../packages/cli/src/admin/dump.ts"],"sourcesContent":["/**\n * `baerly admin dump` — canonical NDJSON of the materialised view.\n *\n * Writes one row per line to stdout, in a strict byte-stable shape so\n * two semantically-equal collections produce byte-equal output. Tests\n * and other programmatic callers can divert the NDJSON output to a\n * file or buffer by passing `{ streams: { stdout } }` to {@link runDump}.\n *\n * Canonical NDJSON dump format:\n *\n * 1. Each row is `{\"_id\":\"<id>\",…}` (no spaces).\n * 2. Row order = ASCII-lex sort on `_id`.\n * 3. Within each row, object keys are sorted ASCII-lex\n * RECURSIVELY — every nested object's keys are sorted too.\n * 4. Numbers as their canonical `JSON.stringify` output.\n * Finite-only (the protocol forbids NaN / Infinity).\n * 5. Strings as `JSON.stringify` output (escape sequences\n * identical to `\\uXXXX` for control codes).\n * 6. One trailing newline at EOF (`\\n`, not `\\r\\n`).\n * 7. No BOM.\n *\n * The round-trip ticket (73) gates byte-equality on this format. A\n * change to any of (1)–(7) is a BREAKING change requiring a\n * round-trip schema-version bump.\n *\n * Empty collection → empty file (no trailing newline) — disambiguates\n * \"zero rows\" from \"one row with empty body\".\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --json JSON envelope (on stdout). Programmatic callers can\n * divert the NDJSON body to a separate writable via the\n * `streams.stdout` option on {@link runDump}.\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Storage / Network / Internal protocol violation.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type Writable } from \"node:stream\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type DocumentValue, type DocumentData } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"../export/index.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { assertCollectionArg, defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst DUMP_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 json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\n/**\n * Recursive byte-stable JSON stringifier. Object keys at every nesting\n * level are sorted ASCII-lex; array element order is preserved as-is.\n * Numbers must be finite (protocol forbids NaN / Infinity in bodies).\n */\nexport const canonicalStringify = (value: DocumentValue): string => {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`,\n );\n }\n return JSON.stringify(value);\n }\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (value === null) {\n // DocumentValue excludes null at the type level, but `unknown` may\n // sneak in via the snapshot fold — be defensive.\n return \"null\";\n }\n if (Array.isArray(value)) {\n const parts = value.map((v) => canonicalStringify(v));\n return `[${parts.join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const keys = Object.keys(value).toSorted();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as Record<string, DocumentValue>)[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: unsupported value type ${typeof value}`,\n );\n};\n\n/**\n * Drain rows to the supplied writable, applying back-pressure on every\n * line. We don't `end()` the stream — the caller owns its lifecycle\n * (`process.stdout` shouldn't be closed; a test-supplied\n * `createWriteStream` flushes on its own `end()`).\n */\nconst writeToSink = async (\n sink: Writable,\n rows: ReadonlyMap<string, DocumentData>,\n): Promise<number> => {\n const ids = [...rows.keys()].toSorted();\n let count = 0;\n for (const id of ids) {\n const body = rows.get(id);\n if (body === undefined) {\n continue;\n }\n // Merge `_id` into the body so the row literal carries it. The\n // map key is authoritative; if a stale `_id` field disagrees, we\n // overwrite it.\n const row: DocumentData = { ...body, _id: id };\n const line = `${canonicalStringify(row)}\\n`;\n if (!sink.write(line)) {\n await new Promise<void>((resolve) => sink.once(\"drain\", resolve));\n }\n count++;\n }\n return count;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.dump\",\n meta: {\n description: \"Canonical NDJSON of the materialised view of one collection.\",\n },\n args: DUMP_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly admin dump\");\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin dump: current.json not found at ${currentJsonKey}`,\n );\n }\n const sink: Writable = ctx.streams?.stdout ?? process.stdout;\n const count = await writeToSink(sink, view);\n emitSuccess({\n command: \"admin.dump\",\n status: \"ok\",\n collection: args.collection,\n dumped: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin dump`. */\nexport const dumpCmd = 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 runDump = bundle.run;\n"],"mappings":";;;;;;AAoDA,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,MAAM;EACJ,MAAM;EACN,aAAa;CACf;AACF;;;;;;AAOA,MAAa,sBAAsB,UAAiC;CAClE,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GACxB,MAAM,IAAI,YACR,mBACA,qDAAqD,OAAO,KAAK,EAAE,sBACrE;EAEF,OAAO,KAAK,UAAU,KAAK;CAC7B;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAChD,OAAO,KAAK,UAAU,KAAK;CAE7B,IAAI,UAAU,MAGZ,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GAErB,OAAO,IADO,MAAM,KAAK,MAAM,mBAAmB,CAAC,CACpC,CAAC,CAAC,KAAK,GAAG,EAAE;CAE7B,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS;EACzC,MAAM,QAAkB,CAAC;EACzB,KAAK,MAAM,KAAK,MAAM;GACpB,MAAM,IAAK,MAAwC;GACnD,IAAI,MAAM,KAAA,GACR;GAEF,MAAM,KAAK,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,mBAAmB,CAAC,GAAG;EAC5D;EACA,OAAO,IAAI,MAAM,KAAK,GAAG,EAAE;CAC7B;CACA,MAAM,IAAI,YACR,mBACA,6CAA6C,OAAO,OACtD;AACF;;;;;;;AAQA,MAAM,cAAc,OAClB,MACA,SACoB;CACpB,MAAM,MAAM,CAAC,GAAG,KAAK,KAAK,CAAC,CAAC,CAAC,SAAS;CACtC,IAAI,QAAQ;CACZ,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,OAAO,KAAK,IAAI,EAAE;EACxB,IAAI,SAAS,KAAA,GACX;EAMF,MAAM,OAAO,GAAG,mBAAmB;GADP,GAAG;GAAM,KAAK;EACL,CAAC,EAAE;EACxC,IAAI,CAAC,KAAK,MAAM,IAAI,GAClB,MAAM,IAAI,SAAe,YAAY,KAAK,KAAK,SAAS,OAAO,CAAC;EAElE;CACF;CACA,OAAO;AACT;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aAAa,+DACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EACzF,oBAAoB,KAAK,YAAY,mBAAmB;EACxD,MAAM,iBAAiB,GAAG,OAAO,UAAU,MAAM,IAAI,UAAU,OAAO,aAAa,KAAK,WAAW;EACnG,MAAM,OAAO,MAAM,qBAAqB;GACtC,SAAS,OAAO;GAChB;GACA,YAAY,KAAK;EACnB,CAAC;EACD,IAAI,SAAS,MACX,MAAM,IAAI,YACR,iBACA,gDAAgD,gBAClD;EAGF,MAAM,QAAQ,MAAM,YADG,IAAI,SAAS,UAAU,QAAQ,QAChB,IAAI;EAC1C,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,QAAQ;EACV,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOP,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-DOdL95kK.js","names":[],"sources":["../packages/protocol/src/errors.ts"],"sourcesContent":["/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * CAS lost on `current.json`. Caller decides whether to retry.\n * Surfaces in the collection API and HTTP layer.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * The single error class thrown by Baerly. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // ... CAS lost; retry\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgIA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;;;;;;;;;;;CAWA;;;;;;;;;;CAaA;CAEA,YACE,MACA,SACA,OACA,QAIA,QACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EAEb,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;CAElB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fsck-RXgLOaJG.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 live log range has no holes. The upper bound is derived\n * from a single LIST of `log/` plus `current.json.tail_hint`\n * (max(highest present seq + 1, tail_hint)), and every seq from\n * `log_seq_start` up to that tail must be present.\n * This is a presence/hole check by key, NOT a per-entry decode:\n * fsck does not GET and parse each `log/<seq>.json`, so it does\n * not assert every entry is well-formed JSON or carries the locked\n * `op`/`collection`/`doc_id` fields. A full decode walk is\n * intentionally omitted to keep the op count O(LIST pages); the\n * read path validates entry shape at fold time.\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 { assertCollectionArg, 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 assertCollectionArg(args.collection, \"baerly admin fsck\");\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 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, tail) has no holes (presence check only). ──\n // LIST the log/ prefix and derive the upper bound from both listed\n // keys and `tail_hint`: under single-write commit `tail_hint` is\n // normally a lower bound, but fsck must also catch an over-claimed\n // hint whose `[log_seq_start, tail_hint)` range is not actually\n // present. Use a single LIST so the op count is O(pages).\n const logPrefix = `${collectionPrefix}/log/`;\n const presentKeys = await listKeys(bucket.storage, logPrefix);\n const presentSeqs = new Set<number>();\n let maxSeq = logFrom - 1;\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 if (seq > maxSeq) {\n maxSeq = seq;\n }\n }\n }\n const logToExcl = Math.max(cur.tail_hint, maxSeq + 1);\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, tail)`,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,YAAY;CAChB,QAAQ;EACN,MAAM;EACN,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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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http-Bd4byR4n.js","names":["#matchResult","#validatedData","#getDecodedParam","#getAllDecodedParams","#getParamValue","#cachedBody","#rawRequest","#executionCtx","#notFoundHandler","#path","#matchResult","#req","#res","#preparedHeaders","#renderer","#layout","#status","#var","#newResponse","Hono","#path","#addRoute","#notFoundHandler","#clone","#dispatch","#handleError","#routes","HonoBase"],"sources":["../packages/protocol/src/log.ts","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/compose.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/request/constants.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/utils/body.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/utils/url.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/request.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/utils/html.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/context.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/router.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/utils/constants.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/hono-base.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/router/pattern-router/router.js","../node_modules/.pnpm/hono@4.12.25/node_modules/hono/dist/preset/tiny.js","../packages/server/src/http/since.ts","../packages/server/src/http/router.ts"],"sourcesContent":["import { BaerlyError } from \"./errors.ts\";\nimport type { DocumentData, JSONValue } from \"./json.ts\";\nimport { COUNT_BIT_WIDTH } from \"./constants.ts\";\nimport { str2uintDesc } from \"./types.ts\";\n\n/**\n * Debezium-style JSON CDC envelope using pgoutput's message-tag (`I`/`U`/`D`) vocabulary. One per mutation.\n *\n * **Pre-launch: the shape may still narrow.** Once the first production\n * consumer ships, this becomes a frozen migration contract behind\n * `baerly export --target=postgres` — the keys will be public, consumers\n * ack on `lsn`, and any rename / removal will be a major-version\n * migration.\n *\n * Field requirement matrix:\n * - Always: `lsn`, `commit_ts`, `op`, `collection`, `session`,\n * `seq`.\n * - For I/U/D: `doc_id`.\n * - For I/U: `after` (full post-image).\n * - Optional: `before` (when `replica_identity === \"FULL\"`), `key_old`\n * (U/D when `replica_identity !== \"PATCH_ONLY\"`), `origin`.\n *\n * @see docs/spec/log-entry-shape.md\n */\nexport interface LogEntry {\n /**\n * Opaque, monotonic, lex-asc cursor. Shape is\n * `<base32-time>_<session>_<seq>` — minted inside\n * `Writer.commit` (see\n * `packages/server/src/writer.ts`) from `timestamp()` +\n * the per-commit `session` + `countKey(seq)`. Consumers ack and\n * resume from this string.\n *\n * When you have a `LogEntry` in hand, prefer the structured\n * `session` / `seq` fields below over parsing this string. The\n * one place that *does* need to crack it open is the\n * `/v1/since` boundary, where a client resumes from an opaque\n * `next_cursor` and no `LogEntry` is in scope — that path uses\n * `lsnParts` (the kernel-blessed parser) rather than ad-hoc\n * `split(\"_\")`.\n */\n lsn: string;\n\n /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */\n commit_ts: string;\n\n /** Insert / Update / Delete. */\n op: \"I\" | \"U\" | \"D\";\n\n /**\n * Collection name — the pgoutput RELATION analogue. Today this is\n * the collection bound to the `current.json` whose `tail_hint` minted\n * the entry. The table API makes collections first-class.\n */\n collection: string;\n\n /**\n * The document key (`ref.key`). Required for every op — `op` is\n * `I | U | D` and all three carry it — so the wire type is required,\n * not optional, matching `log-entry-shape.md`.\n */\n doc_id: string;\n\n /** Required for I, U. The post-image (Debezium's `after`). */\n after?: DocumentData;\n\n /**\n * The pre-image (Debezium's `before`). Present iff the\n * collection's `replica_identity` is `FULL`. ~2× log size on\n * update-heavy collections; off by default.\n */\n before?: DocumentData;\n\n /**\n * Pre-image of the primary key. U/D always carry this when\n * `replica_identity` is not `PATCH_ONLY`. (For Baerly today,\n * `_id` is the only PK.)\n */\n key_old?: { readonly [pk: string]: JSONValue };\n\n /** ORIGIN analogue — the writer session id. */\n origin?: string;\n\n /**\n * Causal metadata (Baerly-only; no pgoutput analogue). The\n * session id that built the `lsn`. Surfaces here so consumers\n * can dedupe / order without parsing the cursor.\n */\n session: string;\n\n /** Per-session sequence number embedded in the `lsn`. */\n seq: number;\n}\n\n/**\n * Per-collection setting controlling how much pre-image data each\n * `U` / `D` entry carries.\n *\n * - `PATCH_ONLY` (default today, applied unconditionally): `U`\n * carries `{ after }`; no `before`, no `key_old`.\n * Bandwidth-cheap. SQL consumers rebuilding before-images need\n * to maintain a shadow table.\n * - `FULL`: `U` additionally carries `before` and `key_old`. ~2× log\n * size on update-heavy collections; buys true 1:1 logical\n * replication and \"previous value\" answerable from the log\n * alone.\n *\n * Per-collection opt-in is not yet wired; every collection is\n * currently `PATCH_ONLY`.\n */\nexport type ReplicaIdentity = \"PATCH_ONLY\" | \"FULL\";\n\n// `LOG_KEY_PREFIX` + `logObjectKey` live in the zero-import `log-key.ts`\n// leaf so consumers that only need the key shape don't drag this module's\n// `lsn` parsing runtime into their bundle closure (it added +3.8 KB raw to\n// `maintenance.js` when the helper lived here).\n\n/**\n * Extract the `session` and `seq` embedded in an `lsn` of shape\n * `<base32-time>_<session>_<seq>`. The seq portion is decoded as a\n * descending base-32 integer (matches `countKey` in `./types`).\n *\n * Use this at the `/v1/since` cursor-decoding boundary, where a\n * client resumes from an opaque `SinceResponse.next_cursor` and no\n * `LogEntry` is in scope. When iterating `LogEntry` records, read\n * `entry.session` / `entry.seq` directly instead.\n *\n * Throws on malformed input; callers should pass only lsns minted\n * by `Writer.commit` (see\n * `packages/server/src/writer.ts`).\n */\nexport const lsnParts = (lsn: string): { session: string; seq: number } => {\n const parts = lsn.split(\"_\");\n if (parts.length !== 3) {\n throw new BaerlyError(\"InvalidResponse\", `invalid lsn shape: ${lsn}`);\n }\n return {\n session: parts[1]!,\n seq: str2uintDesc(parts[2]!, COUNT_BIT_WIDTH),\n };\n};\n","// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n","// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n","// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n","// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n","// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * `.bytes()` parses the request body as a `Uint8Array`.\n *\n * @see {@link https://hono.dev/docs/api/request#bytes}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.bytes()\n * })\n * ```\n */\n bytes() {\n return this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * <html>\n * <body>\n * <p>{content}</p>\n * </body>\n * </html>\n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n","// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n","// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n","// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler, r.basePath);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = this.getPath(request).slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler, baseRoutePath) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = {\n basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n path,\n method,\n handler\n };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise<Response>} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n","// src/router/pattern-router/router.ts\nimport { METHOD_NAME_ALL, UnsupportedPathError } from \"../../router.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar PatternRouter = class {\n name = \"PatternRouter\";\n #routes = [];\n add(method, path, handler) {\n const endsWithWildcard = path.at(-1) === \"*\";\n if (endsWithWildcard) {\n path = path.slice(0, -2);\n }\n if (path.at(-1) === \"?\") {\n path = path.slice(0, -1);\n this.add(method, path.replace(/\\/[^/]+$/, \"\"), handler);\n }\n const parts = (path.match(/\\/?(:\\w+(?:{(?:(?:{[\\d,]+})|[^}])+})?)|\\/?[^\\/\\?]+/g) || []).map(\n (part) => {\n const match = part.match(/^\\/:([^{]+)(?:{(.*)})?/);\n return match ? `/(?<${match[1]}>${match[2] || \"[^/]+\"})` : part === \"/*\" ? \"/[^/]+\" : part.replace(/[.\\\\+*[^\\]$()]/g, \"\\\\$&\");\n }\n );\n try {\n this.#routes.push([\n new RegExp(`^${parts.join(\"\")}${endsWithWildcard ? \"\" : \"/?$\"}`),\n method,\n handler\n ]);\n } catch {\n throw new UnsupportedPathError();\n }\n }\n match(method, path) {\n const handlers = [];\n for (let i = 0, len = this.#routes.length; i < len; i++) {\n const [pattern, routeMethod, handler] = this.#routes[i];\n if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {\n const match = pattern.exec(path);\n if (match) {\n handlers.push([handler, match.groups || emptyParams]);\n }\n }\n }\n return [handlers];\n }\n};\nexport {\n PatternRouter\n};\n","// src/preset/tiny.ts\nimport { HonoBase } from \"../hono-base.js\";\nimport { PatternRouter } from \"../router/pattern-router/index.js\";\nvar Hono = class extends HonoBase {\n constructor(options = {}) {\n super(options);\n this.router = new PatternRouter();\n }\n};\nexport {\n Hono\n};\n","/**\n * Long-poll `GET /v1/since` handler core. Two exports:\n *\n * - {@link longPollSince} — the long-poll itself. Fast path first;\n * if `listEventsSince` already sees events, return immediately.\n * Otherwise race a poll loop against a 25 s wall-clock timeout and\n * return either the next batch of events or\n * `{ events: [], next_cursor: <same> }` (\"nothing changed within\n * the budget\").\n * - {@link listEventsSince} — one poll cycle. Reads `current.json`,\n * validates the caller's cursor against `log_seq_start`, discovers\n * the true tail by forward-probe, GETs each body by integer `seq`,\n * and returns the parsed `LogEntry`s in causal order.\n *\n * The handler is wired into the Hono router (`router.ts`); the\n * router itself owns request parsing and error → HTTP mapping. This\n * module owns the I/O + cursor semantics.\n *\n * Cost model. While a long-poll connection is active the per-poll\n * cost is one `Storage.get` of `current.json`, the tail\n * forward-probe GETs, plus one `Storage.get` per log entry yielded.\n * These are Class B ops, not Class A. The `< 1 Class A op / writer /\n * hour` cost-model bound (see `docs/spec/sync-protocol.md`) still\n * holds; active long-poll subscribers pay repeated Class B reads for\n * lower-latency delivery.\n */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n COUNT_BIT_WIDTH,\n type LogEntry,\n logSeqStartOf,\n lsnParts,\n} from \"@baerly/protocol\";\nimport type { Db } from \"../db.ts\";\nimport type { SinceResponse } from \"../contract.ts\";\n\n/**\n * Validation regex for an opaque LSN cursor. Matches the shape minted\n * by `Writer.commit` (see `packages/server/src/writer.ts`) and described\n * on {@link LogEntry.lsn} — `<base32-time>_<session>_<seq>` where\n * base-32 is `[0-9a-v]` and the trailing seq is a fixed-width token.\n *\n * The seq width (`{11}`) is `Math.ceil(COUNT_BIT_WIDTH / 5)` chars, derived\n * automatically from the canonical `COUNT_BIT_WIDTH` constant in\n * `packages/protocol/src/constants.ts` via the `SEQ_CHARS` computed\n * constant below — no manual update needed when `COUNT_BIT_WIDTH` changes.\n * Currently: `Math.ceil(53 / 5) = 11`.\n */\n// COUNT_BIT_WIDTH is 53; Math.ceil(53 / 5) = 11.\nconst SEQ_CHARS = Math.ceil(COUNT_BIT_WIDTH / 5); // 11\nconst LSN_RE = new RegExp(`^[0-9a-v]+_[0-9a-v]+_[0-9a-v]{${SEQ_CHARS}}$`);\n\n/**\n * Hard cap on log entries returned in a single poll cycle. 1024 is\n * comfortably above the largest expected per-poll batch under the\n * production 1 s poll interval and bounds the worst-case memory\n * footprint of the parsed-JSON array on a hostile workload.\n */\nconst DEFAULT_MAX_EVENTS = 1024;\n\n/**\n * Default 25 s long-poll budget. CF Workers cap fetch CPU at 30 s on\n * the free plan; 25 s leaves slack for header serialization plus the\n * platform's bookkeeping. Node / Bun / Deno have no comparable cap,\n * but the budget is still useful as a connection-cycling hint for\n * upstream load balancers (most idle-connection timeouts are 30-60 s).\n *\n * Per-request override is via the `timeoutMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sinceTimeoutMs` on\n * `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_TIMEOUT_MS = 25_000;\n\n/**\n * Default 1 s inner-poll interval. See module docstring for the\n * cost-model trade-off.\n *\n * Per-request override is via the `pollIntervalMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sincePollIntervalMs`\n * on `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\n\nexport interface LongPollSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n readonly pollIntervalMs?: number;\n}\n\nexport interface ListEventsSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Long-poll wrapper around {@link listEventsSince}. Returns as soon\n * as the first non-empty poll lands, or when the wall-clock timeout\n * elapses (whichever comes first). On timeout the response is\n * `{ events: [], next_cursor: <same> }` — shipped as `200`, not `304`,\n * because the response body carries the unchanged cursor the client\n * needs for the next poll cycle.\n *\n * @throws BaerlyError{code:\"SchemaError\"} — invalid cursor shape, or\n * the cursor references a log entry that has been folded into a\n * snapshot and GC'd.\n */\nexport async function longPollSince(opts: LongPollSinceOptions): Promise<SinceResponse> {\n const { db, collection, cursor, signal } = opts;\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n\n // Up-front cursor-shape validation. `listEventsSince` also checks,\n // but doing it here short-circuits the fast-path read on bad input.\n if (cursor.length > 0 && !LSN_RE.test(cursor)) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`,\n );\n }\n\n // Fast path: the first poll already sees new events.\n const initial = await listEventsSince({ db, collection, cursor, signal });\n if (initial.length > 0) {\n return { events: initial, next_cursor: initial[initial.length - 1]!.lsn };\n }\n\n // No events yet. Race a timeout against a polling loop.\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n return new Promise<SinceResponse>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let settled = false;\n\n const cleanup = (): void => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n if (signal !== undefined) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n };\n\n const settleResolve = (value: SinceResponse): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n resolve(value);\n };\n const settleReject = (err: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n reject(err);\n };\n\n function onAbort(): void {\n // Treat client disconnect as \"no events, same cursor\" — the\n // socket is gone anyway; the resolve is a no-op for response\n // serialization but keeps the promise from leaking.\n settleResolve({ events: [], next_cursor: cursor });\n }\n\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const tick = async (): Promise<void> => {\n if (settled) {\n return;\n }\n try {\n const events = await listEventsSince({ db, collection, cursor, signal });\n if (settled) {\n return;\n }\n if (events.length > 0) {\n settleResolve({ events, next_cursor: events[events.length - 1]!.lsn });\n return;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n settleResolve({ events: [], next_cursor: cursor });\n return;\n }\n const delay = Math.min(pollIntervalMs, remaining);\n timer = setTimeout(() => {\n void tick();\n }, delay);\n } catch (error) {\n settleReject(error);\n }\n };\n\n // First tick scheduled after `pollIntervalMs` (the initial fast\n // path already covered \"events present at t=0\"). Cap by the\n // remaining deadline so an early-cutoff tester with\n // `timeoutMs < pollIntervalMs` still resolves on time.\n timer = setTimeout(\n () => {\n void tick();\n },\n Math.min(pollIntervalMs, timeoutMs),\n );\n });\n}\n\n/**\n * One poll cycle: read `current.json`, derive the `seq` range to\n * scan from the cursor's embedded seq, GET each log entry by `seq`,\n * return the parsed `LogEntry`s in causal order.\n *\n * On-bucket log keys are `log/<seq>.json` — the same shape\n * `compactor` / `gc` / `rebuild-index` walk. Iterating\n * `[startSeq, endSeq)` and GET-ing each key directly avoids the\n * lex-`startAfter` hazard on integer filenames (`10.json` sorts\n * before `2.json` lex) and gives us the global causal ordering for\n * free — `seq` is monotonic across writer sessions.\n *\n * No `current.json` yet → `[]` (clients can poll a not-yet-existing\n * collection without erroring). Cursor inside `[0, log_seq_start)` →\n * `BaerlyError{code:\"SchemaError\"}`.\n */\nexport async function listEventsSince(opts: ListEventsSinceOptions): Promise<LogEntry[]> {\n const { db, collection, cursor, signal } = opts;\n\n if (cursor.length > 0 && !LSN_RE.test(cursor)) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`,\n );\n }\n\n const read = await db.getCurrentJson(collection, signalOpt(signal));\n if (read === null) {\n // No collection provisioned yet. Clients polling for a collection that\n // doesn't exist see an empty stream, NOT an error.\n return [];\n }\n const logSeqStart = logSeqStartOf(read.json);\n // End bound is the DISCOVERED tail (probe past a stale-low hint).\n // The GET loop below 404-tolerates misses, so over-bounding is safe.\n // Floor at `max(log_seq_start, tail_hint)` — same probe floor every\n // other consumer uses (the invariant `tail_hint >= log_seq_start`\n // holds, so this is consistency, not a behaviour change).\n const tail = await db.probeLogTail(\n collection,\n Math.max(logSeqStart, read.json.tail_hint),\n signalOpt(signal),\n );\n\n // Derive the seq range to scan. Empty cursor → start at\n // `log_seq_start` (the first un-snapshotted entry). Non-empty\n // cursor → start at `cursorSeq + 1`. A cursor whose seq is below\n // `log_seq_start` references an entry the compactor has folded\n // into the snapshot and the GC sweep has deleted; the client must\n // re-bootstrap from a snapshot read before resuming.\n let startSeq: number;\n if (cursor.length === 0) {\n startSeq = logSeqStart;\n } else {\n const cursorSeq = lsnParts(cursor).seq;\n if (cursorSeq < logSeqStart) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor ${JSON.stringify(cursor)} points to a log entry that has been folded into a snapshot (log_seq_start=${logSeqStart}); re-bootstrap from a snapshot read before resuming`,\n );\n }\n startSeq = cursorSeq + 1;\n }\n\n // Cap the range at the discovered `tail` (no entries past the tail\n // exist) and at `DEFAULT_MAX_EVENTS` (hard ceiling per the module\n // docstring).\n const endSeq = Math.min(tail, startSeq + DEFAULT_MAX_EVENTS);\n\n // Sequential GETs (NOT Promise.all). Long-poll is latency-bound,\n // per-poll batch is typically 0-10 entries, sequential keeps\n // memory bounded under pathological workloads.\n const entries: LogEntry[] = [];\n for (let s = startSeq; s < endSeq; s++) {\n const entry = await db.getLogEntry(collection, s, signalOpt(signal));\n if (entry === null) {\n // Race: the GC sweeper deleted this entry between\n // `getCurrentJson` and the GET. Skip; don't error.\n continue;\n }\n entries.push(entry);\n }\n\n return entries;\n}\n\n/** Pack an optional `signal` into the `{ signal? }` shape callers expect. */\nconst signalOpt = (signal: AbortSignal | undefined): { signal?: AbortSignal } | undefined =>\n signal === undefined ? undefined : { signal };\n","/**\n * HTTP dispatcher. A small Hono `app` that implements the\n * five locked CRUD routes from `contract.ts`. Mounted into both\n * adapters (`@baerly/adapter-cloudflare` and `@baerly/adapter-node`);\n * the router itself is platform-agnostic — it accepts a single\n * `Request`, dispatches against a per-request `Db`, and returns a\n * `Response` whose body follows the `HttpOkEnvelope` /\n * `HttpErrorEnvelope` shapes.\n *\n * The anonymous `GET /v1/healthz` liveness probe is served by the\n * adapters directly (see `worker.ts` / `server.ts`) — keeping it\n * upstream of the router avoids spending a `Db.create` on every\n * load-balancer probe.\n *\n * `GET /v1/since` is appended to the same factory (see `./since.ts`\n * for the long-poll core). The Cloudflare adapter wraps Worker-side\n * GETs with `caches.default` *outside* `createRouter` so the router\n * stays platform-agnostic; that wrapper EXCLUDES `/v1/since` —\n * long-poll idleness is not a cache hit.\n */\n\nimport { Hono } from \"hono/tiny\";\nimport type { Context } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport {\n type BaerlyConfig,\n BaerlyError,\n type DocumentData,\n type BaerlyErrorCode,\n EMPTY_PREDICATE_WIRE,\n type OrderSpec,\n type PredicateWire,\n validateWire,\n} from \"@baerly/protocol\";\nimport type { Db } from \"../db.ts\";\nimport {\n errorEnvelope,\n type HttpErrorEnvelope,\n type HttpOkEnvelope,\n type HttpStatus,\n type SinceResponse,\n} from \"../contract.ts\";\nimport { serializeError } from \"../observability/canonical.ts\";\nimport { CATEGORY, getLogger } from \"../observability/index.ts\";\nimport { runAllWithMeta, runByIdWithMeta } from \"../query.ts\";\nimport { longPollSince } from \"./since.ts\";\n\n/**\n * Options for {@link createRouter}.\n *\n * - `db` — single-tenant `Db` instance. The CF/Node adapters build a\n * fresh `Db` per request (after the Verifier resolves the tenant)\n * and hand it to a freshly-constructed router. The router itself\n * is stateless and per-request — `app.fetch(req)` is the only\n * entry point. The Verifier runs in the adapter (see `worker.ts` /\n * `server.ts`) before `createRouter` is called; the router itself\n * has no auth seam.\n */\nexport interface CreateRouterOptions {\n readonly db: Db<BaerlyConfig>;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Hono `app` that serves the CRUD routes:\n *\n * - `GET /v1/c/:collection/:id` → read one document.\n * - `GET /v1/c/:collection?where=<json>&order=<json>&limit=<n>` → list rows\n * matching a predicate, optionally ordered and capped.\n * - `POST /v1/c/:collection` → insert. Body: `{ doc }`. → `201 { _id }`.\n * - `PATCH /v1/c/:collection/:id` → merge-patch. Body: `{ patch }`. → `200 { modified }`.\n * - `PUT /v1/c/:collection/:id` → whole-doc replace. Body: `{ doc }`. → `200 { modified }`.\n * - `DELETE /v1/c/:collection/:id` → delete row by id. → `204`.\n * - `GET /v1/count?collection=<name>&where=<json>` → scalar `{ count: N }`.\n * - `GET /v1/since?collection=<name>&cursor=<opaque>` → long-poll log.\n *\n * @example\n * ```ts\n * import { createRouter, Db } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const db = Db.create({ storage: new MemoryStorage(), app: \"tickets\", tenant: \"acme\" });\n * const app = createRouter({ db });\n * // CF Workers:\n * export default { async fetch(req: Request) { return app.fetch(req); } };\n * ```\n */\nexport function createRouter(options: CreateRouterOptions): Hono {\n const { db, sinceTimeoutMs, sincePollIntervalMs } = options;\n const app = new Hono();\n\n // The router intentionally does NOT mount an observability\n // middleware. Production adapters (`@baerly/adapter-cloudflare`,\n // `@baerly/adapter-node`) open their own `ObservabilityContext`\n // BEFORE calling `createRouter().fetch` so they can stamp adapter-\n // owned fields (e.g. `cache_status`) before the cache wrapper\n // short-circuits. Standalone callers (tests, one-off harnesses) wrap\n // their request via `withHttpObservability` from\n // `@baerly/server`. Either way, one unit-of-work → exactly one\n // canonical line.\n\n // Read one — GET /v1/c/:collection/:id\n app.get(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { rows, manifestPointer, fresh } = await runByIdWithMeta(\n db.collectionReadContext(collection),\n id,\n );\n const row = rows[0];\n if (row === undefined) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return c.json(\n {\n data: row,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<DocumentData>,\n 200,\n );\n });\n\n // List — GET /v1/c/:collection?where=<urlencoded-json>\n app.get(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const wire = parseWhereParam(c);\n const order = parseOrder(c.req.query(\"order\"));\n const limit = parseLimit(c.req.query(\"limit\"));\n const { rows, manifestPointer, fresh } = await runAllWithMeta(\n db.collectionReadContext(collection),\n {\n wire,\n order,\n limit,\n },\n );\n return c.json(\n {\n data: rows,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<ReadonlyArray<DocumentData>>,\n 200,\n );\n });\n\n // Insert — POST /v1/c/:collection Body: { doc } → 201 { _id }\n app.post(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n const { _id } = await db\n .collection(collection)\n .insert(doc as Partial<DocumentData> & DocumentData);\n return c.json({ _id }, 201);\n });\n\n // Patch — PATCH /v1/c/:collection/:id Body: { patch }\n app.patch(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const patch = assertJsonBodyField(body, \"patch\");\n const { modified } = await db.collection(collection).update(id, patch as Partial<DocumentData>);\n if (modified === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return c.json({ modified }, 200);\n });\n\n // Replace — PUT /v1/c/:collection/:id Body: { doc }\n // Whole-document overwrite (NOT merge-patch). Missing row → 404\n // (kernel throws `NotFound` directly via `runReplaceById`); row\n // matches → emits one `op:\"U\"` log entry with the post-image,\n // dropping fields absent from `doc`.\n app.put(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n await db.collection(collection).replace(id, doc as DocumentData);\n return c.json({ modified: 1 }, 200);\n });\n\n // Delete — DELETE /v1/c/:collection/:id → 204\n app.delete(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { deleted } = await db.collection(collection).delete(id);\n if (deleted === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return new Response(null, { status: 204 });\n });\n\n // Count — GET /v1/count?collection=<name>&where=<json>\n //\n // Returns a scalar row count for the matching predicate. Avoids the\n // client downloading every row just to take `.length` (silent egress\n // burn). Engine cost is currently the same as `runAllWithMeta` — the\n // win is wire bytes; an O(snapshot+log) count path can land later\n // without touching this route.\n app.get(\"/v1/count\", async (c) => {\n const collection = c.req.query(\"collection\");\n if (collection === undefined || collection.length === 0) {\n throw new BaerlyError(\"SchemaError\", \"GET /v1/count requires ?collection=<name>\");\n }\n const wire = parseWhereParam(c);\n const { rows, manifestPointer, fresh } = await runAllWithMeta(\n db.collectionReadContext(collection),\n {\n wire,\n order: undefined,\n limit: undefined,\n },\n );\n return c.json(\n {\n data: { count: rows.length },\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<{ count: number }>,\n 200,\n );\n });\n\n // Long-poll — GET /v1/since?collection=<name>&cursor=<opaque>\n //\n // Cache-API note: the Cloudflare adapter's `caches.default` wrapper\n // explicitly EXCLUDES `/v1/since` — long-poll idleness is not a\n // cache hit. The adapter middleware MUST check the path before\n // consulting the cache. Do NOT add cache reads here.\n app.get(\"/v1/since\", async (c) => {\n // The router does NOT set `c.var.db`; the adapter resolves the\n // Verifier BEFORE `createRouter` is called and the resulting `db`\n // is captured in this closure. The handler reads it from the\n // outer scope, not from `c.var`.\n const collection = c.req.query(\"collection\");\n if (typeof collection !== \"string\" || collection.length === 0 || collection.includes(\"/\")) {\n throw new BaerlyError(\n \"SchemaError\",\n \"GET /v1/since requires a non-empty `collection` query parameter without `/`\",\n );\n }\n const cursor = c.req.query(\"cursor\") ?? \"\";\n const result = await longPollSince({\n db,\n collection,\n cursor,\n signal: c.req.raw.signal,\n timeoutMs: sinceTimeoutMs,\n pollIntervalMs: sincePollIntervalMs,\n });\n // 200 covers both \"new events present\" and \"timeout idle\" —\n // see `./since.ts` module JSDoc for why we don't use 304.\n return c.json(result satisfies SinceResponse, 200);\n });\n\n app.onError((err, c) => mapToResponse(c, err));\n\n return app;\n}\n\n/**\n * Hard cap on request-body bytes. 1 MiB — matches `S3HttpStorage`'s\n * conformance-suite default. Over-cap → `413 PayloadTooLarge`.\n *\n * The Node adapter (`@baerly/adapter-node`) imports this constant\n * and passes it to `applyBodyCap`, which wraps the request body\n * with a counting `TransformStream` so chunked uploads trip the cap\n * mid-stream rather than materialising the full buffer. The\n * router's `readJsonBody` keeps the cap as a defence-in-depth check\n * (Content-Length pre-read + post-`arrayBuffer` length) for adapters\n * whose platform doesn't pre-cap.\n *\n * @internal — exported for tests and for the Node adapter's\n * `applyBodyCap` helper. Promote to\n * `packages/protocol/src/constants.ts` only on a third cross-\n * package consumer.\n */\nexport const MAX_BODY_BYTES = 1 << 20; // 1 MiB; matches `S3HttpStorage`'s conformance-suite default.\n\n/**\n * Assert that `body[field]` is a plain object (not undefined / null /\n * array / primitive). Returns the value typed as\n * `Record<string, unknown>` so the caller's next cast doesn't need\n * another guard. Throws `BaerlyError{code:\"SchemaError\"}` with the\n * locked wording `\"Request body must be { <field>: object }\"`.\n *\n * Used by POST `/v1/c/:collection` (`doc`), PATCH `/v1/c/:collection/:id`\n * (`patch`), and PUT `/v1/c/:collection/:id` (`doc`).\n *\n * @internal\n */\nconst assertJsonBodyField = (body: unknown, field: string): Record<string, unknown> => {\n const value =\n typeof body === \"object\" && body !== null\n ? (body as Record<string, unknown>)[field]\n : undefined;\n if (value === undefined || typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new BaerlyError(\"SchemaError\", `Request body must be { ${field}: object }`);\n }\n return value as Record<string, unknown>;\n};\n\n/**\n * Parse the `?where=<urlencoded JSON>` query-string param. Absent or\n * empty → {@link EMPTY_PREDICATE_WIRE} (match-all). Malformed JSON →\n * `BaerlyError{code:\"SchemaError\"}` with the locked wording\n * `\"Invalid JSON in ?where=\"`. Returns the validated wire form\n * ({@link PredicateWire}).\n *\n * Wire-only validation: any clause with `field === \"_id\"` rejects\n * with `BaerlyError{code:\"InvalidConfig\"}` — agents zero-shot\n * writing `?where={\"clauses\":[{\"op\":\"eq\",\"field\":\"_id\",\"value\":\"x\"}]}`\n * against the list route get pointed at `GET /v1/c/:collection/:id`\n * instead. Kernel-internal `_id` wire construction\n * (`./collection.ts:byId`, `runByIdWithMeta`, `runInsert`) bypasses this\n * layer by design — those paths never come back through `?where=`\n * parsing.\n *\n * @internal\n */\nconst parseWhereParam = (c: Context): PredicateWire => {\n const whereParam = c.req.query(\"where\");\n if (whereParam === undefined || whereParam.length === 0) {\n return EMPTY_PREDICATE_WIRE;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(whereParam);\n } catch {\n throw new BaerlyError(\"SchemaError\", \"Invalid JSON in ?where=\");\n }\n return validateWire(parsed as PredicateWire);\n};\n\n/**\n * Parse `?limit=<n>` as a non-negative safe integer. Returns\n * `undefined` when absent. Rejects floats, NaN, negatives, and\n * non-numeric input with `SchemaError`.\n *\n * @internal\n */\nfunction parseLimit(raw: string | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const n = Number(raw);\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `?limit= must be a non-negative integer; got ${JSON.stringify(raw)}`,\n );\n }\n return n;\n}\n\n/**\n * Parse the `?order=<json>` query param. Mirrors the `?where=` parser\n * shape: undefined → no order, malformed JSON → `SchemaError`. The\n * engine (`runAllWithMeta` → `sortByOrderSpec`) validates the shape\n * itself, so this only handles the wire-level JSON decode.\n *\n * @internal\n */\nfunction parseOrder(raw: string | undefined): OrderSpec<DocumentData> | undefined {\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new BaerlyError(\"SchemaError\", \"Invalid JSON in ?order=\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BaerlyError(\"SchemaError\", \"?order= must encode a JSON object\");\n }\n return parsed as OrderSpec<DocumentData>;\n}\n\nconst ERROR_TO_STATUS: ReadonlyMap<BaerlyErrorCode, HttpStatus> = new Map<\n BaerlyErrorCode,\n HttpStatus\n>([\n [\"Unauthorized\", 401],\n [\"AccessDenied\", 403],\n [\"NotFound\", 404],\n [\"Conflict\", 409],\n [\"PayloadTooLarge\", 413],\n [\"SchemaError\", 400],\n [\"InvalidConfig\", 400],\n // NetworkError, InvalidResponse, Internal → 500\n]);\n\n/**\n * Map an unknown thrown value onto the wire envelope plus an HTTP\n * status code. The mapping is keyed by `BaerlyError.code` so any future\n * code addition forces a re-check here (currently unmapped codes fall\n * through to 500 by design — see the `NetworkError` / `InvalidResponse`\n * / `Internal` comment in `ERROR_TO_STATUS`).\n *\n * Public via `@gusto/baerly-storage/http` for the embed-by-hand recipe\n * (your own Hono / Express / Fastify app calling `Db` directly).\n * The `HttpErrorEnvelope` shape is locked; do not mutate it.\n */\nexport function mapError(err: unknown): { status: HttpStatus; envelope: HttpErrorEnvelope } {\n if (err instanceof BaerlyError) {\n const status = ERROR_TO_STATUS.get(err.code) ?? 500;\n return { status, envelope: errorEnvelope(err.code, err.message, err.issues) };\n }\n // Unknown thrown value: the message may carry internal detail\n // (file paths, bucket names, upstream response bodies). Log on the\n // server side via the observability channel (replaces the legacy\n // bare `console.error`) and return a generic envelope to the\n // client. The mapped-error wire shape itself is locked and does\n // NOT change here.\n getLogger(CATEGORY.http).error(\"unhandled_error\", { error: serializeError(err) });\n return { status: 500, envelope: errorEnvelope(\"Internal\", \"internal error\") };\n}\n\n// Hono-context shortcut used by every handler's catch block.\nfunction mapToResponse(c: Context, err: unknown): Response {\n const { status, envelope } = mapError(err);\n // `mapError` only returns 4xx/5xx — all of which are\n // `ContentfulStatusCode`. The cast bridges the locked `HttpStatus`\n // union (which also includes 204/304 for the wider contract) to\n // Hono's narrower body-bearing subset.\n return c.json(envelope, status as ContentfulStatusCode);\n}\n\n/**\n * Read and parse the JSON request body. Returns the parsed value\n * (an `unknown` — caller narrows). Throws `BaerlyError`:\n *\n * - `\"PayloadTooLarge\"` (→ 413) when the body exceeds `maxBytes`,\n * detected via `Content-Length` pre-check, post-`arrayBuffer`\n * length check, or — if the host adapter pumps the body through\n * a `ReadableStream` (the Node adapter does) — a `BaerlyError`\n * surfaced via `controller.error(...)` on the upstream pump.\n * - `\"SchemaError\"` (→ 400) for empty bodies, JSON parse failures,\n * and any other read failure.\n *\n * Hono's `app.onError` sink routes the throw through `mapToResponse`.\n */\nasync function readJsonBody(c: Context, maxBytes: number): Promise<unknown> {\n const lenHeader = c.req.header(\"content-length\");\n if (lenHeader !== undefined) {\n const parsed = Number.parseInt(lenHeader, 10);\n if (Number.isFinite(parsed) && parsed > maxBytes) {\n throw new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${maxBytes} bytes`);\n }\n }\n // Read with an early-exit guard for chunked transfers. If the\n // upstream adapter (e.g. `@baerly/adapter-node`) caps the body at\n // the stream-pump layer, the rejected `arrayBuffer()` carries a\n // `BaerlyError{code:\"PayloadTooLarge\"}` which we re-throw verbatim;\n // any other read failure becomes a 400 SchemaError.\n let raw: string;\n try {\n const buffer = await c.req.arrayBuffer();\n if (buffer.byteLength > maxBytes) {\n throw new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${maxBytes} bytes`);\n }\n raw = new TextDecoder().decode(buffer);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"SchemaError\",\n `Failed to read request body: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (raw.length === 0) {\n throw new BaerlyError(\"SchemaError\", \"Empty request body\");\n }\n try {\n return JSON.parse(raw);\n } catch {\n throw new BaerlyError(\"SchemaError\", \"Invalid JSON in request body\");\n }\n}\n"],"x_google_ignoreList":[1,2,3,4,5,6,7,8,9,10,11,12],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmIA,MAAa,YAAY,QAAkD;CACzE,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,YAAY,mBAAmB,sBAAsB,KAAK;CAEtE,OAAO;EACL,SAAS,MAAM;EACf,KAAK,aAAa,MAAM,IAAA,EAAoB;CAC9C;AACF;;;AC3IA,IAAI,WAAW,YAAY,SAAS,eAAe;CACjD,QAAQ,SAAS,SAAS;EACxB,IAAI,QAAQ;EACZ,OAAO,SAAS,CAAC;EACjB,eAAe,SAAS,GAAG;GACzB,IAAI,KAAK,OACP,MAAM,IAAI,MAAM,8BAA8B;GAEhD,QAAQ;GACR,IAAI;GACJ,IAAI,UAAU;GACd,IAAI;GACJ,IAAI,WAAW,IAAI;IACjB,UAAU,WAAW,EAAE,CAAC,EAAE,CAAC;IAC3B,QAAQ,IAAI,aAAa;GAC3B,OACE,UAAU,MAAM,WAAW,UAAU,QAAQ,KAAK;GAEpD,IAAI,SACF,IAAI;IACF,MAAM,MAAM,QAAQ,eAAe,SAAS,IAAI,CAAC,CAAC;GACpD,SAAS,KAAK;IACZ,IAAI,eAAe,SAAS,SAAS;KACnC,QAAQ,QAAQ;KAChB,MAAM,MAAM,QAAQ,KAAK,OAAO;KAChC,UAAU;IACZ,OACE,MAAM;GAEV;QAEA,IAAI,QAAQ,cAAc,SAAS,YACjC,MAAM,MAAM,WAAW,OAAO;GAGlC,IAAI,QAAQ,QAAQ,cAAc,SAAS,UACzC,QAAQ,MAAM;GAEhB,OAAO;EACT;CACF;AACF;;;ACzCA,IAAI,mBAAmC,uBAAO;;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