@gusto/baerly-storage 0.1.2 → 0.3.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.
Files changed (123) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +108 -44
  4. package/dist/API.md +192 -121
  5. package/dist/CHANGELOG.md +144 -0
  6. package/dist/THIRD-PARTY-LICENSES.txt +312 -0
  7. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
  8. package/dist/app-config.d.ts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.js +288 -288
  11. package/dist/auth.js.map +1 -1
  12. package/dist/baerly.js +10 -10
  13. package/dist/baerly.js.map +1 -1
  14. package/dist/bytes-BXdamO3L.js.map +1 -1
  15. package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
  16. package/dist/client-react.d.ts +76 -85
  17. package/dist/client-react.js +95 -53
  18. package/dist/client-react.js.map +1 -1
  19. package/dist/client.d.ts +3 -3
  20. package/dist/client.js.map +1 -1
  21. package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
  22. package/dist/cloudflare-Cn2ibODt.js.map +1 -0
  23. package/dist/cloudflare.d.ts +4 -4
  24. package/dist/cloudflare.js +10 -11
  25. package/dist/cloudflare.js.map +1 -1
  26. package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
  27. package/dist/config-CGyBopy3.js.map +1 -0
  28. package/dist/context-DRZ3tZ5l.js.map +1 -1
  29. package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
  30. package/dist/cost-BZ_MDBmn.js.map +1 -0
  31. package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
  32. package/dist/current-json-DsN7FNY1.js.map +1 -0
  33. package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
  34. package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
  35. package/dist/deploy-BKKyGlSJ.js.map +1 -0
  36. package/dist/dev-vite.d.ts +5 -5
  37. package/dist/dev-vite.js +5 -5
  38. package/dist/dev-vite.js.map +1 -1
  39. package/dist/dev.d.ts +1 -1
  40. package/dist/dev.js +1 -1
  41. package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
  42. package/dist/doctor-BVU4GNXN.js.map +1 -0
  43. package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
  44. package/dist/dump-DPEAKub6.js.map +1 -0
  45. package/dist/errors-DOdL95kK.js.map +1 -1
  46. package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
  47. package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
  48. package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
  49. package/dist/fsck-RXgLOaJG.js.map +1 -0
  50. package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
  51. package/dist/http-Bd4byR4n.js.map +1 -0
  52. package/dist/http.d.ts +15 -15
  53. package/dist/http.js +1 -1
  54. package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
  55. package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
  56. package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
  57. package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
  58. package/dist/index.d.ts +6 -6
  59. package/dist/index.js +4 -4
  60. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
  61. package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
  62. package/dist/inspect-DhI49PSi.js.map +1 -0
  63. package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
  64. package/dist/log-tail-DXeDkWEp.js.map +1 -0
  65. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
  66. package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
  67. package/dist/maintenance-CWBQpZ2y.js.map +1 -0
  68. package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
  69. package/dist/maintenance-C_KSkVjd.js.map +1 -0
  70. package/dist/maintenance.d.ts +3 -2
  71. package/dist/maintenance.js +3 -2
  72. package/dist/node.d.ts +13 -8
  73. package/dist/node.js +1 -1
  74. package/dist/normalize-XWY25_sG.js.map +1 -1
  75. package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
  76. package/dist/observability-BYd-RzEx.js.map +1 -0
  77. package/dist/observability.d.ts +3 -3
  78. package/dist/observability.js +1 -1
  79. package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
  80. package/dist/plan-DIu_B6fy.js.map +1 -0
  81. package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
  82. package/dist/query-sQNO5vU_.js.map +1 -0
  83. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
  84. package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
  85. package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
  86. package/dist/restore-DpQYef6r.js.map +1 -0
  87. package/dist/shared-secret-BJdSwpgw.js.map +1 -1
  88. package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
  89. package/dist/src-CWpkSbvJ.js.map +1 -0
  90. package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
  91. package/dist/src-D24wDpzR.js.map +1 -0
  92. package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
  93. package/dist/src-Db4-qVtM.js.map +1 -0
  94. package/dist/subcommand-CP9NY2J4.js +159 -0
  95. package/dist/subcommand-CP9NY2J4.js.map +1 -0
  96. package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
  97. package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
  98. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  99. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  100. package/package.json +42 -31
  101. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  102. package/dist/config-DVfDGyw1.js +0 -278
  103. package/dist/config-DVfDGyw1.js.map +0 -1
  104. package/dist/cost-CQt1YRkA.js.map +0 -1
  105. package/dist/current-json-C-EyJqs0.js.map +0 -1
  106. package/dist/deploy-CrAbfgCq.js.map +0 -1
  107. package/dist/doctor-Db-hzPmE.js.map +0 -1
  108. package/dist/dump-BYA55NLP.js.map +0 -1
  109. package/dist/fsck-CPPZWt9p.js.map +0 -1
  110. package/dist/http-Cw8p6y5b.js.map +0 -1
  111. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  112. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  113. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  114. package/dist/observability-CpOiEN0k.js.map +0 -1
  115. package/dist/plan-DOTl21vq.js.map +0 -1
  116. package/dist/query-BmiQy328.js.map +0 -1
  117. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  118. package/dist/restore-C6IcmLeA.js.map +0 -1
  119. package/dist/snapshot-SS8USDUF.js.map +0 -1
  120. package/dist/src-DU1sCMlr.js.map +0 -1
  121. package/dist/src-QQ7jDeL2.js.map +0 -1
  122. package/dist/src-zhEAmmF7.js.map +0 -1
  123. package/dist/subcommand-DZcHcsYp.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"cost-CQt1YRkA.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 * 3 Class A ops (PUT content + PUT log entry + CAS-advance\n * current.json). Source: `docs/about/cost-model.md:43-44`.\n */\nconst PROTOCOL_WRITE_AMP = 3;\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 { 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\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;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Q,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-C-EyJqs0.js","names":[],"sources":["../packages/protocol/src/bytes.ts","../packages/protocol/src/constants.ts","../packages/protocol/src/coordination/current-json.ts"],"sourcesContent":["/**\n * UTF-8 JSON byte helpers — names the encode/decode idiom used by\n * every content body, log entry, snapshot, and current.json payload.\n */\n\nexport const encodeJsonBytes = (value: unknown): Uint8Array =>\n new TextEncoder().encode(JSON.stringify(value));\n\nexport const decodeJsonBytes = <T = unknown>(bytes: Uint8Array): T =>\n JSON.parse(new TextDecoder().decode(bytes)) as T;\n","/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * Maximum attempts `S3HttpStorage.list` will make per page when the\n * server replies 429 (rate-limited). After this many in a row, it\n * gives up with `NetworkError`. Separate from the inner transient-\n * failure budget so a single hot page can't burn the whole retry\n * allowance.\n */\nexport const LIST_OBJECT_MAX_RETRIES: number = 10;\n\n/**\n * Backoff (in milliseconds) inserted between LIST attempts when S3\n * returns 429 (rate-limited).\n */\nexport const RATE_LIMIT_BACKOFF_MILLIS: number = 1000;\n\n/**\n * Upper clamp on a server-provided `Retry-After` hint, in seconds.\n * RFC 7231 §7.1.3 allows arbitrary delta-seconds or HTTP-dates, but a\n * client that blindly honours a multi-hour hint hands a misbehaving\n * proxy a denial-of-service primitive. 60s covers any plausible S3-\n * compatible throttle while keeping the worst-case bounded.\n *\n * @see packages/protocol/src/storage/s3-http.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Default retry budget for `S3HttpStorage.retry` (the wrapper around\n * each of the four `Storage` methods). Bounded so that permanent\n * failures (CORS misconfig, NXDOMAIN, persistent 5xx) surface to\n * callers as rejected promises instead of retrying forever and\n * leaving `Writer.commit()` permanently pending.\n *\n * 8 attempts at the existing 100ms→×1.5→10s schedule covers ~30s of\n * transient turbulence, which is enough to ride out a leader election\n * or a brief network blip without papering over a real outage.\n */\nexport const S3_REQUEST_MAX_RETRIES: number = 8;\n\n/**\n * Maximum concurrent log-entry GETs issued by a single `walkLogRange`\n * call. Bounds Class-B fan-out per read and per CAS attempt — without\n * a bound, a reader on a collection whose compactor has fallen behind\n * fans out one GET per live-tail entry (typically 50-100 on the free-\n * tier profile), and a contended writer multiplies that by the CAS\n * retry budget ({@link S3_REQUEST_MAX_RETRIES}).\n *\n * 16 keeps the worst-case under retry to `16 * 8 = 128` concurrent\n * GETs — comfortably under the Workers subrequest cap (50 concurrent\n * / 1000 total) and leaving headroom for the writer's content / index\n * / log / CAS PUTs sharing the same isolate.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 2 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 * 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 * 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 — calibrate via the\n * Task 3 bench, pin in graduation.md.\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/**\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 * Placeholder for `CurrentJson.snapshot === null` in the\n * `_meta.manifest_pointer` cursor emitted on read responses. The\n * wire format is `\"<snapshot>@<next_seq>\"`, and `null` snapshots\n * serialise as this literal so the cursor is never empty and stays\n * byte-stable when destructured by operators.\n *\n * @see packages/server/src/contract.ts (HttpOkMeta)\n */\nexport const MANIFEST_POINTER_EMPTY_SNAPSHOT: string = \"none\";\n\n/**\n * Keys that must never propagate through {@link merge}: assigning to\n * them on a plain object pollutes the prototype chain. The literal\n * `{ __proto__: ... }` syntax is a prototype-setter (not an own key)\n * and bypasses `Object.keys`, but `JSON.parse('{\"__proto__\":...}')`\n * produces a real own property — which is exactly how a malicious\n * HTTP PATCH body would arrive on the wire.\n *\n * Lifted to a constant so every iteration path that touches a\n * caller-supplied object can re-use the same defence without\n * duplicating the keyword list.\n *\n * @see packages/protocol/src/json.ts (merge)\n * @see docs/spec/json-merge-patch.md\n */\nexport const FORBIDDEN_MERGE_KEYS: ReadonlySet<string> = new Set([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Architecturally-enforced ceiling: storage ops per logical write.\n *\n * Three Class A ops: PUT content, PUT log entry, CAS-advance\n * `current.json`. The cost-model page derives the free-tier write\n * budget from this multiplier; the phase-5 end-to-end test asserts it\n * at CI time. Changing this constant is a cost-model-breaking change.\n *\n * @see docs/about/cost-model.md §\"Cost ceiling\"\n * @see tests/integration/phase5-end-to-end.test.ts\n */\nexport const STORAGE_OPS_PER_LOGICAL_WRITE: number = 3;\n\n/**\n * Canonical auth posture identifiers consumed by `BaerlyAppConfig.auth`,\n * the adapter resolution path (`packages/adapter-cloudflare/src/worker.ts`,\n * `packages/adapter-node/src/baerly-node.ts`), and `baerly doctor`.\n *\n * - `\"none\"` — no header check; pin every request to `config.tenant`.\n * For local dev, intranet, CLI tools — contexts where the network\n * seam itself is the trust boundary.\n * - `\"shared-secret\"` — bearer-token check; reads `SHARED_SECRET` from\n * the runtime env and pins every request to `config.tenant`.\n *\n * Custom verifiers (`cloudflareAccess`, `bearerJwt`, SigV4, …) bypass\n * this enum — pass a `Verifier` to the adapter factory's `verifier:`\n * option instead.\n */\nexport const AUTH_CONFIG_VALUES = [\"none\", \"shared-secret\"] as const;\n\n/**\n * Locked error wording for the \"no auth configured\" failure mode. The\n * adapter throws this when neither `config.auth` nor `verifier:`\n * resolves a real `Verifier`. Pinned via a regression test so future\n * refactors do not drift the operator-facing wording.\n *\n * Consumed by:\n * - `packages/adapter-cloudflare/src/worker.ts` (first-fetch throw)\n * - `packages/adapter-node/src/server.ts` (first-fetch throw)\n * - `packages/cli/src/doctor/cloudflare.ts` (FAIL finding mirrors it)\n */\nexport const NO_AUTH_CONFIGURED_MESSAGE: string =\n 'baerly: no auth configured. Set `auth` in baerly.config.ts (\"none\", \"shared-secret\") or pass `verifier` on the adapter factory.';\n\n/**\n * Locked error wording for `auth: \"shared-secret\"` + missing env var.\n * Same pinning rationale as {@link NO_AUTH_CONFIGURED_MESSAGE}.\n */\nexport const SHARED_SECRET_MISSING_MESSAGE: string =\n 'baerly: auth=\"shared-secret\" but SHARED_SECRET env is empty/unset. Cloudflare: `wrangler secret put SHARED_SECRET`, or add to .dev.vars for local dev. Node: set in process env.';\n","/**\n * `current.json` — the per-collection CAS-protected control object — and\n * its embedded {@link WriterFence} epoch token.\n *\n * A dedicated `coordination/` namespace (parallel to `storage/`) holds\n * primitives whose contract is \"atomic agreement over a small JSON\n * object\" rather than \"byte I/O.\" Future siblings (compactor\n * manifest, sweeper checkpoint) join here, not at the top\n * level. The module lives inside `@baerly/protocol` because it is pure\n * (no Node imports, no `node:fs`, no `Buffer`, no `node:crypto`,\n * no implicit globals) and must remain Worker-bundleable — every byte\n * of network traffic threads through the {@link Storage} seam.\n *\n * Contract surface:\n * - {@link readCurrentJson} — fetch + parse + validate\n * - {@link createCurrentJson} — create-only (CAS via `If-None-Match:\"*\"`)\n * - {@link casUpdateCurrentJson} — read-modify-write (CAS via `If-Match`)\n * - {@link claimWriter} — bump epoch + stamp server-clock claim time\n *\n * Why the two-round-trip claim protocol: `claimed_at` MUST come from\n * `StoragePutResult.serverDate` (the single shared clock across\n * instances), not the local clock. `serverDate` is only known *after*\n * the CAS PUT lands, so {@link claimWriter} writes the record with\n * `claimed_at: \"\"` first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. The epoch bump is\n * already durable from the first put either way; a peer landing\n * between the two writes loses cleanly with `Conflict`.\n *\n * Why CAS errors are wrapped: every in-tree {@link Storage} impl\n * surfaces a lost CAS as `BaerlyError{code:\"Conflict\"}`. Downstream\n * callers — the Writer, the compactor, the sweeper —\n * discriminate by `code` to decide whether to retry.\n * We re-wrap here only to add the `current.json at <key>` location\n * context to the message; the `code` is unchanged.\n */\n\nimport { encodeJsonBytes } from \"../bytes.ts\";\nimport { CURRENT_JSON_CONTENT_TYPE, CURRENT_JSON_SCHEMA_VERSION } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport type { Storage, StoragePutOptions, StoragePutResult } from \"../storage/types.ts\";\n\n/**\n * Per-collection control object. CAS-protected. One per\n * `(tenant, collection)` key — for example\n * `<tenant>/<collection>/current.json`. The compactor swaps\n * snapshot generations by CAS-writing this object; the\n * Writer reads it on every commit to find the snapshot\n * pointer; the sweeper reads `writer_fence` to decide which log\n * entries are eligible for GC.\n *\n * The schema is forward-compatible: adding a new optional field is\n * non-breaking. Renaming or removing a field requires bumping\n * {@link CURRENT_JSON_SCHEMA_VERSION}; readers MUST reject\n * unknown major versions with `BaerlyError{code:\"InvalidResponse\"}`.\n */\nexport interface CurrentJson {\n /**\n * Schema version. Today: `2`. Bump on any breaking change to\n * field semantics; readers must reject unknown major versions\n * with `BaerlyError{code:\"InvalidResponse\"}`.\n */\n schema_version: 2;\n\n /**\n * Pointer to the current snapshot generation. `null` before the\n * first compaction has produced a snapshot — readers fall back\n * to log-only replay. Shape is opaque-to-this-module; the\n * compactor owns its interpretation.\n */\n snapshot: string | null;\n\n /**\n * Sequence number of the next log entry. Monotonic per\n * collection. The Writer reads this on commit to mint the\n * next log filename; CAS-write back with `next_seq + 1` ensures\n * no two writers pick the same sequence.\n */\n next_seq: number;\n\n /**\n * Lowest live log sequence number. Entries with `seq < log_seq_start`\n * have been folded into the snapshot at {@link snapshot} (or, if\n * `snapshot === null`, have been dropped because the collection was\n * truncated). Readers walk `[log_seq_start, next_seq)`. Always\n * present on disk — fresh `current.json` writes via\n * {@link createCurrentJson} set this to `0`; the compactor advances\n * it on every fold.\n *\n * Invariants the compactor maintains:\n * - `0 <= log_seq_start <= next_seq`\n * - `log_seq_start` advances monotonically (never decreases)\n * - `log_seq_start > 0` implies `snapshot !== null` (the snapshot\n * covers `[0, log_seq_start)`)\n */\n log_seq_start: number;\n\n /**\n * Embedded write-fence epoch. See {@link WriterFence}.\n */\n writer_fence: WriterFence;\n\n // New in v2:\n\n /** EXACT byte size of the live log tail [log_seq_start, next_seq). Maintained exactly\n * by the full-fence CAS on BOTH paths: each write adds its log bytes; a successful\n * fold (which proves no concurrent write) resets to 0 from a known-empty tail. */\n tail_bytes: number;\n\n /** Byte size of the snapshot pointed to by `snapshot`. */\n snapshot_bytes: number;\n\n /** Row count of the snapshot (= compactor `base.size`, free). With next_seq - log_seq_start\n * (tail entries) this gives the fold's entry count for the ENTRY ceiling `E`. Seeded 0. */\n snapshot_rows: number;\n\n /** Baseline for rate-limiting the graduation defer-warn off SHARED durable state, not\n * per-isolate memory. The warn fires when next_seq - last_warned_seq >=\n * MAINTENANCE_WARN_INTERVAL_WRITES, and that firing CASes last_warned_seq = next_seq.\n * Absent → 0. */\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\n * is not consumed by any ticket in this batch.\n *\n * Borrowed from FoundationDB's `recoveryCount` on cstate, IsleDB's\n * `writer_fence` on `manifest/CURRENT`, and TigerBeetle's VSR view\n * number. The mechanism is the same in all three: every commit\n * checks the epoch on the control object; an entry stamped with\n * a stale epoch is discarded at replay.\n */\nexport interface WriterFence {\n /**\n * Monotonic unsigned integer. Bumped only by an explicit\n * {@link claimWriter} call — do NOT bump on every cold start, do\n * NOT bump on every commit. Triggers per design: (a) detected\n * CAS conflict the writer wants to claim through, (b) admin\n * rotation. The sweeper discards log entries whose stamped epoch\n * is `< current.writer_fence.epoch`.\n */\n epoch: number;\n\n /**\n * Owner identifier — debug only, NOT consulted for safety.\n * Suggested shape: `<worker_id>@<deploy_id>`. May be the empty\n * string when claim provenance is unknown (e.g. initial\n * creation). Safety derives from `epoch`, not from `owner`.\n */\n owner: string;\n\n /**\n * ISO-8601 timestamp from the `StoragePutResult.serverDate` on\n * the successful CAS PUT. **Never use `new Date()` or\n * `Date.now()` to populate this field** — under multi-instance\n * deployment the local clock may disagree with peers; the\n * server's clock is the only one all instances share. Format\n * via `serverDate.toISOString()`. The empty string `\"\"` means\n * \"claim time unknown\" — readers MUST treat it as such rather\n * than parsing it.\n */\n claimed_at: string;\n\n /**\n * Optional explicit lease horizon, also ISO-8601. Reserved for\n * future manual rotation workflows; current code only writes\n * the field through if a caller supplies it and does not read\n * it.\n */\n lease_until?: string;\n}\n\n/**\n * Return shape from {@link readCurrentJson} et al.: the parsed JSON\n * plus the ETag needed for a follow-up CAS write.\n */\nexport interface CurrentJsonRead {\n readonly json: CurrentJson;\n readonly etag: string;\n}\n\n/**\n * Read + parse `current.json` at `key`. Returns `null` on not-found.\n *\n * @throws BaerlyError{code:\"InvalidResponse\"} — body is not valid\n * JSON, or `schema_version` is unknown, or the shape fails\n * the runtime guard.\n */\nexport async function readCurrentJson(\n storage: Storage,\n key: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead | null> {\n const got = await storage.get(key, opts);\n if (got === null) {\n return null;\n }\n const text = new TextDecoder().decode(got.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: body is not valid JSON`,\n error,\n );\n }\n return { json: assertCurrentJson(parsed, key), etag: got.etag };\n}\n\n/**\n * Create `current.json` if-and-only-if it does not exist (S3\n * `If-None-Match: \"*\"`). Use this once per collection at provisioning\n * time; subsequent updates go through {@link casUpdateCurrentJson}.\n *\n * @throws BaerlyError{code:\"Conflict\"} — the key already exists.\n * Caller decides whether to read + reconcile or surface.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `initial` fails the\n * runtime shape guard.\n */\nexport async function createCurrentJson(\n storage: Storage,\n key: string,\n initial: CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n // Catch shape bugs in callers before they hit storage. Cheap.\n assertCurrentJson(initial, key);\n const body = encodeJson(initial);\n const putOpts: StoragePutOptions = {\n ifNoneMatch: \"*\",\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: initial, etag: result.etag };\n}\n\n/**\n * Read-modify-write `current.json` under CAS. The `mutator` receives\n * a deep clone of the current parsed JSON (mutate freely) and returns\n * the new state. The new state is written with `If-Match:\n * <currentEtag>`; on conflict, throws.\n *\n * `mutator` MUST be synchronous and deterministic — it may be called\n * multiple times if the caller wraps this in a retry loop, so it\n * must not have side effects.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer landed a write\n * between this function's read and write. Caller decides\n * whether to retry (read + remutate + rewrite).\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist\n * (use {@link createCurrentJson} instead) or body doesn't\n * parse / fails the shape guard.\n */\nexport async function casUpdateCurrentJson(\n storage: Storage,\n key: string,\n mutator: (current: CurrentJson) => CurrentJson,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n // Defensive deep clone so a mutator that mutates its argument can't\n // corrupt the original record on the caller's retry path.\n // `structuredClone` is a global on Node ≥17 and Workers; the package\n // targets Node ≥24 so it is safe.\n const next = mutator(structuredClone(existing.json));\n assertCurrentJson(next, key);\n const body = encodeJson(next);\n const putOpts: StoragePutOptions = {\n ifMatch: existing.etag,\n contentType: CURRENT_JSON_CONTENT_TYPE,\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n };\n let result: StoragePutResult;\n try {\n result = await storage.put(key, body, putOpts);\n } catch (error) {\n throw translateCasError(error, key);\n }\n return { json: next, etag: result.etag };\n}\n\n/**\n * Claim ownership of the write fence by bumping `epoch` and stamping\n * `claimed_at` from `StoragePutResult.serverDate`. The common call\n * site is \"I detected a CAS conflict during a commit and want to\n * claim the fence before retrying\"; admin rotation is the other call\n * site.\n *\n * `owner` is informational — see {@link WriterFence.owner}. Safety\n * derives from the monotonic `epoch`, not from `owner`.\n *\n * Implementation note (two round-trips): because\n * `StoragePutResult.serverDate` is only known *after* the CAS PUT\n * lands, this function writes the record with `claimed_at: \"\"`\n * first, then overwrites itself with the correct\n * `serverDate.toISOString()` in a second CAS. A peer landing between\n * the two writes loses cleanly with `Conflict` — the epoch bump is\n * already durable from the first put either way. If `serverDate` is\n * `undefined` on the first PUT (impl doesn't surface it), the second\n * write is skipped and `claimed_at` remains the empty string;\n * readers MUST treat the empty string as \"unknown claim time\"\n * rather than parsing it.\n *\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the full failure envelope (absent / lying / non-monotonic Date,\n * peer-between-PUTs, bounded clock skew).\n * @see {@link ../../../../docs/spec/writer-fence-adversarial-model.md} —\n * the \"Differentiation from mps3\" subsection that frames the §103\n * non-obviousness story.\n * @see {@link ../../../../docs/spec/prior-art.md} —\n * IDS-shaped prior-art differentiation against mps3, SlateDB,\n * Iceberg, Delta, and the broader S3-leader-election literature.\n *\n * @throws BaerlyError{code:\"Conflict\"} — another writer claimed the\n * fence between this call's read and write. Caller decides\n * whether to retry.\n * @throws BaerlyError{code:\"InvalidResponse\"} — `key` does not exist.\n */\nexport async function claimWriter(\n storage: Storage,\n key: string,\n owner: string,\n opts?: { signal?: AbortSignal },\n): Promise<CurrentJsonRead> {\n const existing = await readCurrentJson(storage, key, opts);\n if (existing === null) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} does not exist; use createCurrentJson first`,\n );\n }\n const provisional: CurrentJson = {\n ...existing.json,\n writer_fence: {\n epoch: existing.json.writer_fence.epoch + 1,\n owner,\n // Will be overwritten with serverDate.toISOString() once the put\n // returns, when the impl surfaces it. Stays `\"\"` (\"unknown\") if\n // the impl doesn't.\n claimed_at: \"\",\n // 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, next_seq)`. The field is always present\n * on disk (every `createCurrentJson` write seeds it; the compactor\n * advances it on every fold); this helper exists to document intent\n * at call sites that walk the log range or assert the snapshot\n * invariants.\n */\nexport const logSeqStartOf = (c: CurrentJson): number => c.log_seq_start;\n\n// ---------------------------------------------------------------------\n// Internals\n// ---------------------------------------------------------------------\n\nconst encodeJson = (json: CurrentJson): Uint8Array => encodeJsonBytes(json);\n\n/**\n * Runtime guard for `parsed` to be a {@link CurrentJson}. Throws\n * `BaerlyError{code:\"InvalidResponse\"}` rather than coercing. 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) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key} is schema v1 (pre-maintenance); this build requires v2. 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\"])}; expected ${CURRENT_JSON_SCHEMA_VERSION}`,\n );\n }\n if (!(typeof r[\"snapshot\"] === \"string\" || r[\"snapshot\"] === null)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: snapshot must be string|null`,\n );\n }\n // Stryker disable next-line ConditionalExpression,StringLiteral: three equivalent mutants on this line — (1) `typeof r[\"next_seq\"] !== \"number\"` → false is subsumed by !Number.isInteger (which rejects all non-numbers); (2) `r[\"next_seq\"] < 0` → false is subsumed by the downstream `log_seq_start > next_seq` cross-check (log_seq_start ≥ 0, so log_seq_start > negative_next_seq always fires); (3) StringLiteral \"next_seq\" → \"\" turns r[\"\"] → undefined → !Number.isInteger(undefined) still true → still throws.\n if (typeof r[\"next_seq\"] !== \"number\" || !Number.isInteger(r[\"next_seq\"]) || r[\"next_seq\"] < 0) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: next_seq must be a non-negative integer`,\n );\n }\n if (\n // 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[\"next_seq\"]) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: log_seq_start ${String(r[\"log_seq_start\"])} > next_seq ${String(r[\"next_seq\"])}`,\n );\n }\n const fence = r[\"writer_fence\"];\n if (fence === null || typeof fence !== \"object\") {\n throw new BaerlyError(\"InvalidResponse\", `current.json at ${key}: writer_fence missing`);\n }\n const f = fence as Record<string, unknown>;\n // 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[\"tail_bytes\"] !== \"number\"` → false is equivalent — !Number.isInteger rejects all non-numbers, making the typeof check fully subsumed.\n typeof r[\"tail_bytes\"] !== \"number\" ||\n !Number.isInteger(r[\"tail_bytes\"]) ||\n r[\"tail_bytes\"] < 0\n ) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `current.json at ${key}: tail_bytes must be a non-negative integer`,\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 return parsed as CurrentJson;\n};\n\n/**\n * Wrap a storage-level error with `current.json at <key>` location\n * context. `Conflict` (the storage layer's CAS-lost signal) is\n * re-thrown with an annotated message; other `BaerlyError`s pass\n * through; non-`BaerlyError` falls through as `InvalidResponse` (in\n * practice unreachable — every in-tree `Storage` impl wraps).\n */\nconst translateCasError = (e: unknown, key: string): BaerlyError => {\n if (e instanceof BaerlyError && e.code === \"Conflict\") {\n return new BaerlyError(\"Conflict\", `current.json CAS lost at ${key}: ${e.message}`, e);\n }\n if (e instanceof BaerlyError) {\n return e;\n }\n return new BaerlyError(\"InvalidResponse\", `current.json write at ${key} failed: ${String(e)}`, e);\n};\n"],"mappings":";;;;;;AAKA,MAAa,mBAAmB,UAC9B,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,KAAK,CAAC;AAEhD,MAAa,mBAAgC,UAC3C,KAAK,MAAM,IAAI,YAAY,EAAE,OAAO,KAAK,CAAC;;;;;;;ACiD5C,MAAa,4BAAoC;;;;;;;;AA+DjD,MAAa,4BAAoC;;;;;;AAoBjD,MAAa,0BAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC/C,MAAa,yBAAiC,QAAc,KAAK;;;;;;;;;;AAWjE,MAAa,4BAAoC;;;;;;;AAqBjD,MAAa,6BAAqC,KAAK;;;;;;;;;AAoGvD,MAAa,qCAA6C,MAAM;;;;;;;;;;;;;;;;;;;;;;;AAyBhE,MAAa,8BAAsC,OAAO;;;;;;;;;;AAW1D,MAAa,4BAAoC;;;;;;;;AASjD,MAAa,mCAA2C;;;;;;;;;;AAWxD,MAAa,kCAA0C;;;;;;;;;;;;;;;;AAiBvD,MAAa,uBAA4C,IAAI,IAAI;CAC/D;CACA;CACA;AACF,CAAC;;;;;;;;;;;;AA2CD,MAAa,6BACX;;;;;AAMF,MAAa,gCACX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACjPF,eAAsB,gBACpB,SACA,KACA,MACiC;CACjC,MAAM,MAAM,MAAM,QAAQ,IAAI,KAAK,IAAI;CACvC,IAAI,QAAQ,MACV,OAAO;CAET,MAAM,OAAO,IAAI,YAAY,EAAE,OAAO,IAAI,IAAI;CAC9C,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,IAAI;CAC1B,SAAS,OAAO;EACd,MAAM,IAAI,YACR,m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AI,YACR,mBACA,mBAAmB,IAAI,2CACzB;CAEF,IAAI,EAAE,mBAAmB,KAAA,KAAa,OAAO,EAAE,mBAAmB,UAChE,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,qDACzB;CAEF,IAEE,OAAO,EAAE,kBAAkB,YAC3B,CAAC,OAAO,UAAU,EAAE,aAAa,KACjC,EAAE,gBAAgB,GAElB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,4CACzB;CAEF,IAEE,OAAO,EAAE,sBAAsB,YAC/B,CAAC,OAAO,UAAU,EAAE,iBAAiB,KACrC,EAAE,oBAAoB,GAEtB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,gDACzB;CAEF,IAEE,OAAO,EAAE,qBAAqB,YAC9B,CAAC,OAAO,UAAU,EAAE,gBAAgB,KACpC,EAAE,mBAAmB,GAErB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,+CACzB;CAEF,IACE,EAAE,uBAAuB,KAAA,MAExB,OAAO,EAAE,uBAAuB,YAC/B,CAAC,OAAO,UAAU,EAAE,kBAAkB,KACtC,EAAE,qBAAqB,IAEzB,MAAM,IAAI,YACR,mBACA,mBAAmB,IAAI,4DACzB;CAEF,OAAO;AACT;;;;;;;;AASA,MAAM,qBAAqB,GAAY,QAA6B;CAClE,IAAI,aAAa,eAAe,EAAE,SAAS,YACzC,OAAO,IAAI,YAAY,YAAY,4BAA4B,IAAI,IAAI,EAAE,WAAW,CAAC;CAEvF,IAAI,aAAa,aACf,OAAO;CAET,OAAO,IAAI,YAAY,mBAAmB,yBAAyB,IAAI,WAAW,OAAO,CAAC,KAAK,CAAC;AAClG"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"deploy-CrAbfgCq.js","names":[],"sources":["../packages/cli/src/deploy.ts"],"sourcesContent":["/**\n * `baerly deploy` — citty dispatcher.\n *\n * Reads `baerly.config.ts:target` and routes to the matching\n * deploy backend. Today: `cloudflare` only — the `node` example\n * embodies its deployment shape directly (self-host via `node\n * server.js` after your PaaS or container build), so `baerly\n * deploy` rejects `target: \"node\"` with an actionable InvalidConfig.\n *\n * Exit-code contract (standard CLI shape):\n * - 0 success.\n * - 1 user error (InvalidConfig, missing config, unknown target).\n * - 2 storage / external error (NetworkError, Wrangler returned\n * non-zero, anything non-BaerlyError).\n * - 3 protocol invariant (Conflict, Internal, InvalidResponse —\n * should not happen here unless someone hand-edited mid-flight).\n */\n\nimport { defineCommand, type ArgsDef, type ParsedArgs } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { deployCloudflare } from \"./deploy/cloudflare.ts\";\nimport { emitError, emitSuccess, setJsonMode } from \"./output.ts\";\n\nconst DEPLOY_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (\"node\" self-deploys via your PaaS or container build).',\n valueHint: \"cloudflare\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst KNOWN_KEYS: ReadonlySet<string> = new Set([\"target\", \"json\", \"_\"]);\n\nconst errorToExitCode = (code: string): number => {\n if (code === \"InvalidConfig\") {\n return 1;\n }\n if (code === \"Conflict\" || code === \"Internal\" || code === \"InvalidResponse\") {\n return 3;\n }\n return 2;\n};\n\nconst handleDeploy = async (args: ParsedArgs<typeof DEPLOY_ARGS>): Promise<number> => {\n setJsonMode(args.json === true);\n try {\n for (const k of Object.keys(args)) {\n if (!KNOWN_KEYS.has(k)) {\n throw new BaerlyError(\"InvalidConfig\", `baerly deploy: unknown flag --${k}`);\n }\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const exit = await deployCloudflare(config);\n if (exit === 0) {\n emitSuccess({ command: \"deploy\", status: \"ok\", target });\n }\n return exit;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly deploy: target ${JSON.stringify(target)} has no deploy backend. ` +\n `Self-host: \\`node server.js\\` after your PaaS or container build. ` +\n `Cloudflare Workers is the only managed deploy backend today.`,\n );\n } catch (error) {\n if (error instanceof BaerlyError) {\n emitError(\"deploy\", error.code, error.message);\n return errorToExitCode(error.code);\n }\n emitError(\"deploy\", \"Unknown\", (error as Error).message);\n return 2;\n }\n};\n\n/** citty `defineCommand` block for `baerly deploy`. */\nexport const deploy = defineCommand({\n meta: {\n name: \"deploy\",\n description: \"Deploy this baerly app. Dispatches by baerly.config.ts:target.\",\n },\n args: DEPLOY_ARGS,\n run: async ({ args }) => {\n const code = await handleDeploy(args);\n if (code !== 0) {\n process.exit(code);\n }\n },\n});\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDeploy = async (argv: readonly string[]): Promise<number> => {\n const { parseArgs } = await import(\"citty\");\n let parsed: ParsedArgs<typeof DEPLOY_ARGS>;\n try {\n parsed = parseArgs<typeof DEPLOY_ARGS>(argv as string[], DEPLOY_ARGS);\n } catch (error) {\n setJsonMode(argv.includes(\"--json\"));\n emitError(\"deploy\", \"InvalidConfig\", (error as Error).message);\n return 1;\n }\n return handleDeploy(parsed);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAc;CAClB,QAAQ;EACN,MAAM;EACN,aACE;EACF,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;AACF;AAEA,MAAM,aAAkC,IAAI,IAAI;CAAC;CAAU;CAAQ;AAAG,CAAC;AAEvE,MAAM,mBAAmB,SAAyB;CAChD,IAAI,SAAS,iBACX,OAAO;CAET,IAAI,SAAS,cAAc,SAAS,cAAc,SAAS,mBACzD,OAAO;CAET,OAAO;AACT;AAEA,MAAM,eAAe,OAAO,SAA0D;CACpF,YAAY,KAAK,SAAS,IAAI;CAC9B,IAAI;EACF,KAAK,MAAM,KAAK,OAAO,KAAK,IAAI,GAC9B,IAAI,CAAC,WAAW,IAAI,CAAC,GACnB,MAAM,IAAI,YAAY,iBAAiB,iCAAiC,GAAG;EAG/E,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,OAAO,MAAM,iBAAiB,MAAM;GAC1C,IAAI,SAAS,GACX,YAAY;IAAE,SAAS;IAAU,QAAQ;IAAM;GAAO,CAAC;GAEzD,OAAO;EACT;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,uJAGlD;CACF,SAAS,OAAO;EACd,IAAI,iBAAiB,aAAa;GAChC,UAAU,UAAU,MAAM,MAAM,MAAM,OAAO;GAC7C,OAAO,gBAAgB,MAAM,IAAI;EACnC;EACA,UAAU,UAAU,WAAY,MAAgB,OAAO;EACvD,OAAO;CACT;AACF;;AAGA,MAAa,SAAS,cAAc;CAClC,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,OAAO,MAAM,aAAa,IAAI;EACpC,IAAI,SAAS,GACX,QAAQ,KAAK,IAAI;CAErB;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"doctor-Db-hzPmE.js","names":[],"sources":["../packages/protocol/src/storage/probe-cas.ts","../packages/cli/src/doctor/cas.ts","../packages/cli/src/doctor/cloudflare.ts","../packages/cli/src/doctor.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\nimport { uuid } from \"../types.ts\";\nimport type { Storage } from \"./types.ts\";\n\nconst isConflict = (error: unknown): boolean =>\n error instanceof BaerlyError && error.code === \"Conflict\";\n\n/** One CAS sub-check's outcome. */\nexport interface CasProbeCheck {\n /** Stable identifier (`ifMatch-stale` / `ifNoneMatch-exists`). */\n readonly name: string;\n /** `true` iff the backend rejected the conditional write as required. */\n readonly ok: boolean;\n /** Human-readable detail — what was expected vs. observed. */\n readonly detail: string;\n}\n\n/** Aggregate result of {@link probeCas}. `ok` iff every sub-check passed. */\nexport interface CasProbeResult {\n readonly ok: boolean;\n readonly checks: readonly CasProbeCheck[];\n}\n\n/**\n * Runtime probe that a live `Storage` backend honours the conditional\n * writes the protocol depends on. The storage conformance suite asserts\n * the same semantics in CI for every shipped adapter, but a deployment\n * may point baerly at an arbitrary S3-compatible store; a backend that\n * silently *ignores* `If-Match` (returns 200 instead of rejecting a\n * stale write) causes silent lost-update corruption — every commit\n * CAS-advances `current.json`, and the no-lease maintenance fold relies\n * on the same fence. This is the fail-loud, deploy-time analogue of the\n * conformance CAS block.\n *\n * Writes a single throwaway sentinel under `keyPrefix` and deletes it on\n * the way out (even on failure). Two checks, mirroring the conformance\n * suite:\n * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).\n * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:\"*\"` over an existing\n * key must reject (Conflict).\n *\n * A rejected write surfaces as a `BaerlyError` with `code === \"Conflict\"`\n * (the contract `Storage.put` documents); anything else — a resolved\n * promise, or a non-Conflict error — means the backend does not honour\n * the condition and is reported as a failed check rather than thrown.\n */\nexport const probeCas = async (\n storage: Storage,\n opts?: { keyPrefix?: string; signal?: AbortSignal },\n): Promise<CasProbeResult> => {\n const prefix = opts?.keyPrefix ?? \"\";\n const key = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const enc = new TextEncoder();\n const signal = opts?.signal;\n\n const checks: CasProbeCheck[] = [];\n try {\n const first = await storage.put(key, enc.encode(\"v1\"), { signal });\n\n // ── Check 1: a stale ifMatch must be rejected. ──────────────────\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v2\"), { ifMatch: '\"baerly-cas-probe-stale\"', signal });\n checks.push({\n name: \"ifMatch-stale\",\n ok: false,\n detail:\n \"PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk).\",\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifMatch-stale\",\n ok: true,\n detail: \"stale If-Match rejected (Conflict), as required.\",\n }\n : {\n name: \"ifMatch-stale\",\n ok: false,\n detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // ── Check 2: ifNoneMatch:\"*\" over an existing key must reject. ──\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v3\"), { ifNoneMatch: \"*\", signal });\n checks.push({\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail:\n 'PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe).',\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifNoneMatch-exists\",\n ok: true,\n detail: 'If-None-Match:\"*\" over an existing key rejected (Conflict), as required.',\n }\n : {\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail: `If-None-Match:\"*\" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n void first;\n } finally {\n // Best-effort cleanup — never let a delete failure mask the verdict.\n try {\n await storage.delete(key, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n return { ok: checks.every((c) => c.ok), checks };\n};\n","/**\n * `baerly doctor --bucket <uri>` — live backend CAS probe.\n *\n * Unlike the cloudflare deploy-invariant walk (which only inspects\n * config files), this mode connects to a real bucket and verifies it\n * honours the conditional writes the protocol depends on: every commit\n * CAS-advances `current.json` with `If-Match`, and the no-lease\n * maintenance fold relies on the same fence. A store that silently\n * ignores `If-Match` (returns 200 instead of rejecting a stale write)\n * causes silent lost-update corruption — this is the fail-loud,\n * deploy-time analogue of the conformance CAS block.\n *\n * Writes a single throwaway sentinel and deletes it; see\n * {@link probeCas}.\n */\n\nimport { probeCas, type Storage } from \"@baerly/protocol\";\nimport type { DoctorFinding, DoctorReport } from \"./cloudflare.ts\";\n\nconst CAS_FIX =\n \"Point baerly at an S3-compatible store that honours conditional writes \" +\n \"(If-Match + If-None-Match). Real AWS S3, Cloudflare R2, and GCS do; a \" +\n \"custom gateway / proxy may be stripping conditional headers — check it \" +\n \"returns 412 on a stale If-Match.\";\n\n/**\n * Run the live CAS round-trip against `storage` and shape the result\n * as a {@link DoctorReport}. Status is `error` iff any sub-check failed\n * (a non-conformant backend is a hard blocker, not a warning).\n */\nexport const doctorCas = async (storage: Storage, keyPrefix: string): Promise<DoctorReport> => {\n const result = await probeCas(storage, { keyPrefix });\n const findings: DoctorFinding[] = result.checks.map((c) => ({\n severity: c.ok ? \"ok\" : \"error\",\n check: `cas-${c.name}`,\n message: c.detail,\n ...(c.ok ? {} : { fix: CAS_FIX }),\n }));\n return { findings, status: result.ok ? \"ok\" : \"error\" };\n};\n","/**\n * `baerly doctor --target=cloudflare` — walks the Cloudflare\n * deploy invariants and reports. With `--fix`, remediates what\n * can be safely auto-fixed (R2 bucket creation; secret prompts\n * are still user-driven because `wrangler secret put` reads\n * stdin interactively).\n *\n * Checks (each emitting one {@link DoctorFinding}):\n * 1. `wrangler.jsonc` exists at the package root.\n * 2. Each declared R2 binding exists in CF\n * (`wrangler r2 bucket info`).\n * 3. Each `requiredSecrets` entry is in `wrangler secret list`.\n * 4. If `cloudflareAccess` is set in `baerly.config.ts`,\n * `audienceTag` is 64 lowercase-hex chars and `teamDomain`\n * is non-empty.\n * 5. If `triggers.crons` is empty, warn that the maintenance\n * loop won't run.\n * 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`\n * doesn't declare a matching `routes` entry, warn.\n *\n * Output is a structured {@link DoctorReport} that\n * `packages/cli/src/doctor.ts` renders as either a checklist\n * (text mode) or a JSON envelope (`--json` mode).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parse, type ParseError } from \"jsonc-parser\";\nimport { BaerlyError, SHARED_SECRET_MISSING_MESSAGE } from \"@baerly/protocol\";\nimport type { AppConfig } from \"../config.ts\";\nimport { ensureBindings, parseR2Bindings, type ProcessRunner } from \"../deploy/cloudflare.ts\";\n\n/** One finding from a `baerly doctor` walk. */\nexport interface DoctorFinding {\n /** Severity. `ok` / `info` don't move the overall status. */\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n /** Short check name — stable, machine-readable. */\n readonly check: string;\n /** Human-friendly description. */\n readonly message: string;\n /** Optional remediation hint. */\n readonly fix?: string;\n}\n\n/** Result of a `baerly doctor` walk. */\nexport interface DoctorReport {\n readonly findings: readonly DoctorFinding[];\n /**\n * Overall: `ok` only when every finding has severity `ok` or\n * `info`. `warning` when the worst finding is a warning. `error`\n * when any finding is an error.\n */\n readonly status: \"ok\" | \"warning\" | \"error\";\n}\n\nconst rollupStatus = (findings: readonly DoctorFinding[]): DoctorReport[\"status\"] => {\n let worst: DoctorReport[\"status\"] = \"ok\";\n for (const f of findings) {\n if (f.severity === \"error\") {\n return \"error\";\n }\n if (f.severity === \"warning\") {\n worst = \"warning\";\n }\n }\n return worst;\n};\n\n/**\n * Read the declared cron schedule from `wrangler.jsonc`. Returns\n * `[]` when missing — caller treats empty as a warning.\n */\nconst readDeclaredCrons = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { triggers?: { crons?: unknown } }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const crons = obj.triggers?.crons;\n if (!Array.isArray(crons)) {\n return [];\n }\n return crons.filter((c): c is string => typeof c === \"string\");\n};\n\n/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */\nconst readDeclaredRoutePatterns = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { routes?: unknown }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const routes = obj.routes;\n if (!Array.isArray(routes)) {\n return [];\n }\n return routes\n .map((r) =>\n r !== null && typeof r === \"object\" ? (r as { pattern?: unknown }).pattern : undefined,\n )\n .filter((p): p is string => typeof p === \"string\");\n};\n\n/** Read declared `vars` keys from `wrangler.jsonc`. */\nconst readDeclaredVarKeys = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { vars?: Record<string, unknown> }\n | undefined;\n if (errors.length > 0 || obj === undefined || obj.vars === undefined) {\n return [];\n }\n return Object.keys(obj.vars);\n};\n\n/**\n * Walk the Cloudflare deploy invariants. With `opts.fix === true`,\n * remediate the auto-fixable issues (bucket creation). Secret\n * prompts stay user-driven.\n */\nexport const doctorCloudflare = async (\n config: AppConfig,\n opts: {\n readonly runner?: ProcessRunner;\n readonly fix?: boolean;\n readonly cwd?: string;\n } = {},\n): Promise<DoctorReport> => {\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = resolve(repoRoot, \"wrangler.jsonc\");\n const findings: DoctorFinding[] = [];\n\n // 1. wrangler.jsonc presence.\n if (!existsSync(wranglerPath)) {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc\",\n message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,\n fix: \"Re-scaffold (npm create baerly@latest) or restore the file from git.\",\n });\n return { findings, status: rollupStatus(findings) };\n }\n findings.push({\n severity: \"ok\",\n check: \"wrangler.jsonc\",\n message: `${wranglerPath} found.`,\n });\n\n // 2. R2 bindings — parse first, then probe each.\n let declared: readonly { binding: string; bucket_name: string }[];\n try {\n declared = parseR2Bindings(wranglerPath);\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"InvalidConfig\") {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc.parse\",\n message: error.message,\n });\n return { findings, status: rollupStatus(findings) };\n }\n throw error;\n }\n\n if (opts.fix === true && opts.runner !== undefined) {\n // Run the same provisioning path the deploy fallback uses.\n // Any failure here surfaces as an error finding rather than\n // throwing — doctor's job is to report.\n try {\n await ensureBindings(opts.runner, repoRoot, wranglerPath);\n } catch (error) {\n findings.push({\n severity: \"error\",\n check: \"r2.fix\",\n message: error instanceof Error ? error.message : \"unknown error during ensureBindings\",\n });\n }\n }\n\n if (opts.runner !== undefined) {\n for (const { bucket_name } of declared) {\n const info = await opts.runner.run(\n \"wrangler\",\n [\"r2\", \"bucket\", \"info\", bucket_name],\n repoRoot,\n );\n if (info.code === 0) {\n findings.push({\n severity: \"ok\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" exists.`,\n });\n } else {\n findings.push({\n severity: \"error\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" not found.`,\n fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`,\n });\n }\n }\n } else {\n findings.push({\n severity: \"info\",\n check: \"r2.skip\",\n message: \"no runner supplied; skipped R2 bucket probes.\",\n });\n }\n\n // 3. requiredSecrets — best-effort.\n //\n // `configured` is lifted to the outer scope so the auth-posture\n // block below can read the deployed secret set without re-running\n // `wrangler secret list`. Empty when the runner is absent or the\n // listing call failed.\n const required = config.requiredSecrets ?? [\"SHARED_SECRET\"];\n let configured: readonly string[] = [];\n if (opts.runner !== undefined && required.length > 0) {\n const r = await opts.runner.run(\"wrangler\", [\"secret\", \"list\"], repoRoot);\n if (r.code !== 0) {\n findings.push({\n severity: \"warning\",\n check: \"secrets\",\n message: \"could not list secrets (wrangler exit non-zero); skipping check.\",\n });\n } else {\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (Array.isArray(parsed)) {\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n }\n } catch {\n // fall through with empty configured set\n }\n for (const name of required) {\n if (configured.includes(name)) {\n findings.push({\n severity: \"ok\",\n check: `secret.${name}`,\n message: `secret ${name} is set.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check: `secret.${name}`,\n message: `secret ${name} is required but unset.`,\n fix: `wrangler secret put ${name}`,\n });\n }\n }\n }\n } else if (required.length > 0) {\n findings.push({\n severity: \"info\",\n check: \"secrets.skip\",\n message: \"no runner supplied; skipped secret checks.\",\n });\n }\n\n // 7. config.auth — graduated-auth posture. Walks the typed `auth`\n // field added in `packages/protocol/src/app-config.ts`.\n // FAIL: shared-secret without SHARED_SECRET set on the worker.\n // WARN: auth: \"none\" + deploy target (operator may have a\n // network gate in front; surface it so they confirm).\n // INFO: CF Access vars present + adapter uses config.auth (auth\n // is using config.auth, CF Access env is inert).\n //\n // The presence of the typed field is guaranteed by the loader\n // (config.ts throws on omission), so we walk every loaded config\n // without an existence guard.\n if (config.auth === \"none\") {\n // Deploy-target check: \"cloudflare\" / \"node\" are the only valid\n // values, and both ship to a network-reachable runtime. We warn\n // unconditionally — the doctor's job is to surface the choice,\n // not to second-guess whether the operator's network seam (CF\n // Access, intranet ACL, Tunnel) is upstream.\n findings.push({\n severity: \"warning\",\n check: \"auth.none-on-deploy\",\n message:\n `baerly.config.ts has auth: \"none\" and ships to target=${JSON.stringify(config.target)}. ` +\n \"Every request will resolve to config.tenant with no header check. \" +\n \"Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) \" +\n 'or change `auth` to \"shared-secret\" or pass a custom `verifier:` on the adapter factory.',\n fix:\n 'Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; ' +\n 'or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`.',\n });\n }\n\n if (config.auth === \"shared-secret\" && opts.runner !== undefined) {\n // Mirror the FAIL message wording from the adapter's runtime\n // throw. Locked via `SHARED_SECRET_MISSING_MESSAGE` so doctor +\n // adapter stay in sync.\n //\n // If `configured` is still empty here, the `wrangler secret list`\n // invocation either failed (we already warned with the \"secrets\"\n // finding above) or really lists no secrets. Either way the\n // operator-facing remediation is the same.\n const requiredSecret = \"SHARED_SECRET\";\n if (!configured.includes(requiredSecret)) {\n findings.push({\n severity: \"error\",\n check: \"auth.shared-secret-missing\",\n message: SHARED_SECRET_MISSING_MESSAGE,\n fix:\n \"wrangler secret put SHARED_SECRET (for production) \" +\n \"or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`).\",\n });\n }\n }\n\n // INFO: CF Access env vars in wrangler.jsonc:vars but the adapter\n // is using `config.auth` for the verifier (so the env values are\n // inert). We can't statically parse the user's worker source —\n // surface the heuristic.\n const varKeys = new Set(readDeclaredVarKeys(wranglerPath));\n if (\n varKeys.has(\"CF_ACCESS_TEAM_DOMAIN\") &&\n varKeys.has(\"CF_ACCESS_AUDIENCE_TAG\")\n ) {\n findings.push({\n severity: \"info\",\n check: \"auth.cf-access-inert\",\n message:\n `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} ` +\n `but the adapter uses config.auth=${JSON.stringify(config.auth)}. ` +\n `To wire CF Access, pass \\`verifier: cloudflareAccess({ teamDomain, audienceTag })\\` on the baerlyWorker factory.`,\n });\n }\n\n // 4. cloudflareAccess — when configured, audience tag must be\n // 64 lowercase-hex chars.\n if (config.cloudflareAccess !== undefined) {\n const { teamDomain, audienceTag } = config.cloudflareAccess;\n if (teamDomain.length === 0) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.teamDomain\",\n message: \"cloudflareAccess.teamDomain in baerly.config.ts is empty.\",\n });\n }\n if (!/^[0-9a-f]{64}$/.test(audienceTag)) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.audienceTag\",\n message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,\n fix: \"Copy the AUD tag from the Cloudflare Access app's configuration tab.\",\n });\n } else if (teamDomain.length > 0) {\n findings.push({\n severity: \"ok\",\n check: \"cloudflareAccess\",\n message: `cloudflareAccess audience tag is well-formed; team domain \"${teamDomain}\".`,\n });\n }\n }\n\n // 5. Cron triggers — empty list means the maintenance loop won't\n // run.\n const crons = readDeclaredCrons(wranglerPath);\n if (crons.length === 0) {\n findings.push({\n severity: \"warning\",\n check: \"triggers.crons\",\n message: \"no cron triggers declared; the maintenance loop will not run automatically.\",\n fix: `Add \"triggers\": { \"crons\": [\"* * * * *\"] } to ${wranglerPath}.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"triggers.crons\",\n message: `cron trigger${crons.length === 1 ? \"\" : \"s\"} ${crons.map((c) => JSON.stringify(c)).join(\", \")} declared.`,\n });\n }\n\n // 6. domain ↔ routes coherence.\n if (config.domain !== undefined && config.domain.length > 0) {\n const patterns = readDeclaredRoutePatterns(wranglerPath);\n const expectedPrefix = `${config.domain}/`;\n const hasMatch = patterns.some(\n (p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix),\n );\n if (!hasMatch) {\n findings.push({\n severity: \"warning\",\n check: \"routes.domain\",\n message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,\n fix: `Add { \"pattern\": \"${config.domain}/*\", \"custom_domain\": true } to wrangler.jsonc:routes.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"routes.domain\",\n message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`,\n });\n }\n }\n\n return { findings, status: rollupStatus(findings) };\n};\n","/**\n * `baerly doctor` — citty dispatcher for deploy-invariant checks.\n *\n * Two modes:\n * - `--bucket <uri>` — connect to a live bucket and probe its CAS\n * support (the protocol's load-bearing backend prerequisite). This\n * mode WRITES + deletes one throwaway sentinel; see\n * {@link doctorCas}. Independent of `baerly.config.ts` / `--target`.\n * - otherwise — reads `baerly.config.ts:target` and routes to\n * {@link doctorCloudflare} (read-only deploy-invariant checks). The\n * Node target self-validates at scaffold time — the example IS the\n * contract — so it has no doctor backend.\n *\n * Drift detection, index rebuilds, and writes/min health are separate\n * verbs:\n * - `baerly admin fsck --indexes [--fix]` — index drift.\n * - `baerly admin usage` — writes/min M-size graduation.\n * - `baerly admin rebuild-index` — single-index reconciliation.\n *\n * Renders the returned {@link DoctorReport} into either a\n * stdout checklist (text mode) or a JSON envelope (`--json`\n * mode).\n *\n * Exit-code contract (mirrors `baerly deploy`):\n * - 0 success — report status is `ok` or `warning`.\n * - 1 user error (InvalidConfig, unknown target, missing config).\n * - 2 storage / external error.\n * - 3 protocol invariant.\n *\n * A `warning` status returns exit 0 (the user can deploy; we just\n * flagged a maintenance / coherence issue). An `error` status\n * returns exit 2 unless the underlying cause was an InvalidConfig\n * (which already returned 1 via a thrown BaerlyError).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { doctorCas } from \"./doctor/cas.ts\";\nimport { doctorCloudflare, type DoctorReport } from \"./doctor/cloudflare.ts\";\nimport { defaultRunner } from \"./runner.ts\";\nimport { color, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst DOCTOR_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).',\n valueHint: \"cloudflare\",\n },\n bucket: {\n type: \"string\",\n description:\n \"Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, file:///, or memory:// URI. Independent of --target.\",\n valueHint: \"s3://bucket/prefix\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst colorize = (severity: string, glyph: string): string => {\n if (severity === \"error\") {\n return color.red(glyph);\n }\n if (severity === \"warning\") {\n return color.yellow(glyph);\n }\n if (severity === \"info\") {\n return color.dim(glyph);\n }\n return glyph;\n};\n\nconst renderReport = (\n label: { kind: \"target\" | \"bucket\"; value: string },\n report: DoctorReport,\n): void => {\n if (isJsonMode()) {\n process.stdout.write(\n `${JSON.stringify({ result: { command: \"doctor\", [label.kind]: label.value, ...report } })}\\n`,\n );\n return;\n }\n process.stdout.write(`baerly doctor --${label.kind}=${label.value}\\n\\n`);\n let okCount = 0;\n let warningCount = 0;\n let errorCount = 0;\n for (const f of report.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? \"•\";\n process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\\n`);\n if (f.fix !== undefined) {\n process.stdout.write(` fix: ${f.fix}\\n`);\n }\n if (f.severity === \"ok\") {\n okCount += 1;\n } else if (f.severity === \"warning\") {\n warningCount += 1;\n } else if (f.severity === \"error\") {\n errorCount += 1;\n }\n }\n process.stdout.write(\n `\\nStatus: ${errorCount} error${errorCount === 1 ? \"\" : \"s\"}, ${warningCount} warning${warningCount === 1 ? \"\" : \"s\"}, ${okCount} ok.\\n`,\n );\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"doctor\",\n meta: {\n description:\n \"Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target.\",\n },\n args: DOCTOR_ARGS,\n handler: async (args) => {\n // --bucket is a standalone live-probe mode: it connects to a real\n // bucket and checks CAS, independent of baerly.config.ts / --target.\n if (args.bucket !== undefined) {\n const { storage, keyPrefix } = await parseBucketUri(args.bucket);\n const report = await doctorCas(storage, keyPrefix);\n renderReport({ kind: \"bucket\", value: args.bucket }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const report = await doctorCloudflare(config, {\n runner: defaultRunner(),\n ...(args.fix === true && { fix: true }),\n });\n renderReport({ kind: \"target\", value: target }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. ` +\n `(Node variants self-validate at scaffold time; the example IS the contract.)`,\n );\n },\n});\n\n/** citty `defineCommand` block for `baerly doctor`. */\nexport const doctor = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDoctor = bundle.run;\n"],"mappings":";;;;;;;AAIA,MAAM,cAAc,UAClB,iBAAiB,eAAe,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;AAyCjD,MAAa,WAAW,OACtB,SACA,SAC4B;CAE5B,MAAM,MAAM,GADG,MAAM,aAAa,GACZ,uBAAuB,KAAK;CAClD,MAAM,MAAM,IAAI,YAAY;CAC5B,MAAM,SAAS,MAAM;CAErB,MAAM,SAA0B,CAAC;CACjC,IAAI;EACY,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG,EAAE,OAAO,CAAC;EAGjE,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,SAAS;IAA4B;GAAO,CAAC;GACxF,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAAS,OAAO;GACd,OAAO,KACL,WAAW,KAAK,IACZ;IACE,MAAM;IACN,IAAI;IACJ,QAAQ;GACV,IACA;IACE,MAAM;IACN,IAAI;IACJ,QAAQ,+CAA+C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAC9G,CACN;EACF;EAGA,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,aAAa;IAAK;GAAO,CAAC;GACrE,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAA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ACJ,aACE,yFACJ;CACA,MAAM;CACN,SAAS,OAAO,SAAS;EAGvB,IAAI,KAAK,WAAW,KAAA,GAAW;GAC7B,MAAM,EAAE,SAAS,cAAc,MAAM,eAAe,KAAK,MAAM;GAC/D,MAAM,SAAS,MAAM,UAAU,SAAS,SAAS;GACjD,aAAa;IAAE,MAAM;IAAU,OAAO,KAAK;GAAO,GAAG,MAAM;GAC3D,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,SAAS,MAAM,iBAAiB,QAAQ;IAC5C,QAAQ,cAAc;IACtB,GAAI,KAAK,QAAQ,QAAQ,EAAE,KAAK,KAAK;GACvC,CAAC;GACD,aAAa;IAAE,MAAM;IAAU,OAAO;GAAO,GAAG,MAAM;GACtD,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,qGAElD;CACF;AACF,CAAC;;AAGD,MAAa,SAAS,OAAO;AAOJ,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"dump-BYA55NLP.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 { 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 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,K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U,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":"fsck-CPPZWt9p.js","names":[],"sources":["../packages/cli/src/admin/fsck.ts"],"sourcesContent":["/**\n * `baerly admin fsck` — consistency walk for one collection.\n *\n * Default mode (no `--indexes`): read-only checks against the\n * snapshot + log tail.\n * 1. `current.json` exists at the expected key and parses.\n * 2. When `current.snapshot !== null`, the snapshot body's\n * SHA-256 matches the hash embedded in the filename\n * (delegated to `loadSnapshotAsMap`).\n * 3. The log range `[log_seq_start, next_seq)` has no holes —\n * every `log/<seq>.json` is present (HEAD-cheap LIST scan).\n * 4. Every entry inside the live tail is well-formed JSON with\n * the locked `op`, `collection`, and `doc_id` fields.\n *\n * `--indexes` + `--config=<path>` mode: SKIP the snapshot + log\n * walks and ONLY check each declared index for drift via\n * `rebuildIndex(..., { dryRun: true })`. Drift is `(added > 0)`\n * (rows that should be projected but have no key on storage) or\n * `(removed > 0)` (orphan keys for rows that no longer match).\n * Read-only.\n *\n * `--indexes --fix`: same drift walk but with `dryRun: false`, so\n * `rebuildIndex` PUTs missing keys and DELETEs orphans. The findings\n * downgrade from `warning` to `info` (drift was found AND fixed in\n * one pass). `--fix` without `--indexes` is rejected — fsck has no\n * auto-fix outside the index check.\n *\n * Exit codes:\n * 0 — all checks pass.\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag,\n * `--fix` without `--indexes`).\n * 2 — Storage / Network error during the walk.\n * 3 — Protocol invariant violation surfaced by the kernel\n * (Internal / InvalidResponse) — distinguished from exit 4\n * so CI can wire fsck as a regression gate.\n * 4 — One or more findings (orphan / hole / hash-mismatch /\n * index drift). Unique to this command; the other\n * `baerly admin` subcommands reserve 0–3.\n */\n\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { type ArgsDef } from \"citty\";\nimport {\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"@baerly/server\";\nimport { rebuildIndex } from \"@baerly/server/maintenance\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst FSCK_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n config: {\n type: \"string\",\n required: false,\n description:\n \"Path to baerly.config.{js,mjs,json}. Required with --indexes; resolves index definitions.\",\n valueHint: \"path\",\n },\n indexes: {\n type: \"boolean\",\n description:\n \"Skip snapshot + log walks; check declared indexes for drift via rebuildIndex (read-only by default).\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"With --indexes, rebuild drifted indexes (PUT missing keys, DELETE orphans). Rejected without --indexes.\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\ntype Severity = \"ok\" | \"info\" | \"warning\" | \"finding\";\ninterface Finding {\n readonly severity: Severity;\n readonly check: string;\n readonly message: string;\n readonly key?: string;\n}\n\n/** Severities that count toward the exit-4 \"findings present\" status. */\nconst isFindingSeverity = (s: Severity): boolean => s === \"finding\" || s === \"warning\";\n\nconst loadConfigIndexes = async (\n configPath: string,\n collection: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const { readFile } = await import(\"node:fs/promises\");\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const pathMod = await import(\"node:path\");\n const abs = configPath.startsWith(\"file://\")\n ? fileURLToPath(configPath)\n : pathMod.resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n const def = cfg.collections?.[collection];\n return def?.indexes ?? [];\n};\n\nconst listKeys = async (storage: Storage, prefix: string): Promise<string[]> => {\n const out: string[] = [];\n for await (const entry of storage.list(prefix)) {\n out.push(entry.key);\n }\n return out.toSorted();\n};\n\nconst statusLine = (label: string, ok: boolean, detail: string): string =>\n ` ${label.padEnd(22)}${ok ? \"ok\" : \"error\"} ${detail}`.trimEnd();\n\ninterface IndexSummary {\n readonly name: string;\n readonly added: number;\n readonly removed: number;\n readonly kept: number;\n readonly rebuilt: boolean;\n}\n\nconst renderSnapshotLog = (\n collection: string,\n findings: readonly Finding[],\n context: {\n readonly logRange: readonly [number, number];\n readonly logEntriesPresent: number;\n readonly snapshotKey: string | null;\n },\n): string => {\n const lines: string[] = [];\n lines.push(`baerly admin fsck ${collection}`);\n const [from, toExcl] = context.logRange;\n const byCheck = new Map<string, Finding[]>();\n for (const f of findings) {\n const arr = byCheck.get(f.check) ?? [];\n arr.push(f);\n byCheck.set(f.check, arr);\n }\n lines.push(statusLine(\"current.json:\", (byCheck.get(\"current.json\") ?? []).length === 0, \"\"));\n lines.push(\n statusLine(\n \"snapshot hash:\",\n (byCheck.get(\"snapshot\") ?? []).length === 0,\n context.snapshotKey === null ? \"(no snapshot yet)\" : `(sha256 verified)`,\n ),\n );\n lines.push(\n statusLine(\n `log range [${from},${toExcl}):`,\n (byCheck.get(\"log\") ?? []).length === 0,\n `(${context.logEntriesPresent}/${toExcl - from} entries present)`,\n ),\n );\n lines.push(` status: ${findings.some(isFindingFinding) ? \"findings\" : \"ok\"}`);\n for (const f of findings) {\n lines.push(` ${f.check}: ${f.message}${f.key !== undefined ? ` (key=${f.key})` : \"\"}`);\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst renderIndexes = (\n collection: string,\n findings: readonly Finding[],\n summaries: readonly IndexSummary[],\n fix: boolean,\n): string => {\n const lines: string[] = [];\n lines.push(`baerly admin fsck ${collection} --indexes${fix ? \" --fix\" : \"\"}`);\n for (const s of summaries) {\n const verb = s.rebuilt ? \"rebuilt\" : \"would rebuild\";\n if (s.added === 0 && s.removed === 0) {\n lines.push(` ${s.name}: in sync (${s.kept} keys)`);\n } else {\n lines.push(` ${s.name}: ${verb} — added ${s.added}, removed ${s.removed}, kept ${s.kept}`);\n }\n }\n lines.push(` status: ${findings.some(isFindingFinding) ? \"findings\" : \"ok\"}`);\n for (const f of findings) {\n if (f.check === \"log\" || f.check === \"snapshot\" || f.check === \"current.json\") {\n continue;\n }\n lines.push(` ${f.check}: ${f.message}${f.key !== undefined ? ` (key=${f.key})` : \"\"}`);\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst isFindingFinding = (f: Finding): boolean => isFindingSeverity(f.severity);\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.fsck\",\n meta: {\n description: \"Read-only consistency walk for one collection.\",\n },\n args: FSCK_ARGS,\n handler: async (args, ctx) => {\n const indexMode = args.indexes === true;\n const fixMode = args.fix === true;\n if (fixMode && !indexMode) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin fsck: --fix is only valid with --indexes (fsck has no auto-fix outside the index check)\",\n );\n }\n if (indexMode && (args.config === undefined || args.config.length === 0)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin fsck: --indexes requires --config=<path> to resolve index definitions\",\n );\n }\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const bucket = await parseBucketUri(args.bucket);\n const collectionPrefix = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}`;\n const currentJsonKey = `${collectionPrefix}/current.json`;\n\n const findings: Finding[] = [];\n\n if (indexMode) {\n // ── Index drift mode. ──────────────────────────────────────────\n // Skip snapshot + log walks. For each declared index, call\n // `rebuildIndex(..., { dryRun: !fix })` — it returns the\n // `(added, removed, kept)` triple we need to call drift.\n const defs = await loadConfigIndexes(args.config!, args.collection);\n const summaries: IndexSummary[] = [];\n for (const def of defs) {\n const check = `index.${def.name}`;\n let result;\n try {\n result = await rebuildIndex(bucket.storage, currentJsonKey, def, {\n dryRun: !fixMode,\n });\n } catch (error) {\n findings.push({\n severity: \"finding\",\n check,\n message: `${def.name}: drift check failed: ${(error as Error).message}`,\n });\n continue;\n }\n const summary: IndexSummary = {\n name: def.name,\n added: result.added,\n removed: result.removed,\n kept: result.kept,\n rebuilt: fixMode,\n };\n summaries.push(summary);\n const drifted = result.added > 0 || result.removed > 0;\n if (!drifted) {\n findings.push({\n severity: \"ok\",\n check,\n message: `${def.name}: in sync (${result.kept} keys).`,\n });\n } else if (fixMode) {\n findings.push({\n severity: \"info\",\n check,\n message: `${def.name}: rebuilt — added ${result.added}, removed ${result.removed}, kept ${result.kept}.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check,\n message: `${def.name}: drift detected — ${result.added} missing, ${result.removed} orphaned (${result.kept} in sync).`,\n });\n }\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.fsck\",\n status: findings.some(isFindingFinding) ? \"findings\" : \"ok\",\n collection: args.collection,\n mode: fixMode ? \"indexes-fix\" : \"indexes\",\n indexes: summaries,\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.key !== undefined && { key: f.key }),\n })),\n });\n } else {\n process.stdout.write(renderIndexes(args.collection, findings, summaries, fixMode));\n }\n return findings.some(isFindingFinding) ? 4 : 0;\n }\n\n // ── Default mode. current.json + snapshot + log walks. ─────────\n const read = await readCurrentJson(bucket.storage, currentJsonKey);\n if (read === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: current.json not found at ${currentJsonKey}`,\n );\n }\n const cur = read.json;\n const logFrom = cur.log_seq_start ?? 0;\n const logToExcl = cur.next_seq;\n const snapshotKey = cur.snapshot;\n\n // ── Snapshot hash verifies (loadSnapshotAsMap throws on mismatch). ──\n if (snapshotKey !== null) {\n try {\n await loadSnapshotAsMap(bucket.storage, snapshotKey, args.collection);\n } catch (error) {\n if (\n error instanceof BaerlyError &&\n (error.code === \"Internal\" || error.code === \"InvalidResponse\")\n ) {\n findings.push({\n severity: \"finding\",\n check: \"snapshot\",\n message: error.message,\n key: snapshotKey,\n });\n } else {\n throw error;\n }\n }\n }\n\n // ── Log range [from, toExcl) has no holes; entries well-formed. ──\n // LIST the log/ prefix; expect exactly `toExcl - from` keys named\n // `${from}.json` … `${toExcl - 1}.json`. Use a single LIST so the\n // op count is O(pages) not O(range).\n const logPrefix = `${collectionPrefix}/log/`;\n const presentKeys = await listKeys(bucket.storage, logPrefix);\n const presentSeqs = new Set<number>();\n for (const key of presentKeys) {\n const tail = key.slice(logPrefix.length);\n const match = /^(\\d+)\\.json$/.exec(tail);\n if (match === null) {\n continue;\n }\n const seq = Number.parseInt(match[1]!, 10);\n if (Number.isFinite(seq)) {\n presentSeqs.add(seq);\n }\n }\n let logEntriesPresent = 0;\n for (let s = logFrom; s < logToExcl; s++) {\n if (presentSeqs.has(s)) {\n logEntriesPresent++;\n } else {\n findings.push({\n severity: \"finding\",\n check: \"log\",\n message: `missing log entry at seq ${s} inside [log_seq_start, next_seq)`,\n key: `${logPrefix}${s}.json`,\n });\n }\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.fsck\",\n status: findings.some(isFindingFinding) ? \"findings\" : \"ok\",\n collection: args.collection,\n current_json_key: currentJsonKey,\n snapshot: snapshotKey,\n log_range: { from: logFrom, to_excl: logToExcl, present: logEntriesPresent },\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.key !== undefined && { key: f.key }),\n })),\n });\n } else {\n process.stdout.write(\n renderSnapshotLog(args.collection, findings, {\n logRange: [logFrom, logToExcl],\n logEntriesPresent,\n snapshotKey,\n }),\n );\n }\n return findings.some(isFindingFinding) ? 4 : 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin fsck`. */\nexport const fsckCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runFsck = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,YAAY;CAChB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,M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