@gusto/baerly-storage 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-DEzInG6M.js","names":["utf8Encoder","compareKeysUtf8","utf8Encoder","encoder","hmac"],"sources":["../packages/protocol/src/auth-resolution.ts","../packages/protocol/src/constants.ts","../packages/protocol/src/env.ts","../packages/protocol/src/sha256.ts","../packages/protocol/src/storage/key.ts","../packages/protocol/src/storage/memory.ts","../packages/protocol/src/types.ts","../packages/protocol/src/time.ts","../packages/protocol/src/storage/ledger.ts","../packages/protocol/src/storage/retry.ts","../packages/dev/src/key-lock.ts","../packages/dev/src/local-fs-key-codec.ts","../packages/dev/src/local-fs.ts","../node_modules/.pnpm/@rgrove+parse-xml@5.2.0/node_modules/@rgrove/parse-xml/dist/browser.js","../packages/adapter-node/src/xml.ts","../packages/adapter-node/src/http-transport.ts","../packages/adapter-node/src/s3-http.ts","../packages/adapter-node/src/gcs-http.ts","../packages/adapter-node/src/credentials/resolve.ts","../packages/adapter-node/src/credentials/goog4-signer.ts","../node_modules/.pnpm/aws4fetch@1.0.20/node_modules/aws4fetch/dist/aws4fetch.esm.mjs","../packages/adapter-node/src/sigv4-sign.ts","../packages/adapter-node/src/credentials/signer.ts","../packages/adapter-node/src/storage-factories.ts","../packages/cli/src/bucket-uri.ts","../packages/cli/src/config.ts"],"sourcesContent":["/** Corrective action for a `sharedSecret(...)` preset misconfig; crosses the wire. */\nexport const SHARED_SECRET_CONFIG_RESOLUTION: string =\n 'Pass a non-empty `secret` and a non-empty `tenantPrefix` with no \"/\" to sharedSecret({ secret, tenantPrefix }).';\n\n/** Corrective action for a `bearerJwt(...)` preset misconfig; crosses the wire. */\nexport const BEARER_JWT_CONFIG_RESOLUTION: string =\n 'Provide non-empty `issuer`, `audience`, and at least one `algorithms` entry; `tenantClaim` and `tenantPrefix` are mutually exclusive and `tenantPrefix` must be non-empty with no \"/\"; `clockSkewMs` and `jwksCacheTtlMs`, when set, must be >= 0.';\n\n/** Corrective action for a `cloudflareAccess(...)` preset misconfig; crosses the wire. */\nexport const CLOUDFLARE_ACCESS_CONFIG_RESOLUTION: string =\n 'Pass a bare team name as `teamDomain` (lowercase letters, digits and \"-\", e.g. `acme`) and a 64-char lowercase-hex `audienceTag` (the Application Audience (AUD) tag from the CF Access app config).';\n\n/**\n * Accepted form of a Cloudflare Access `teamDomain`: the bare team name\n * (`acme`), not the `acme.cloudflareaccess.com` host. The\n * `cloudflareAccess` preset interpolates it into the JWKS host\n * `https://<teamDomain>.cloudflareaccess.com`, so a `/`, `@`, `.` or `:`\n * could point the key fetch at another host. Shared by the preset, the\n * CLI config loader and `baerly doctor` so all three accept the same set.\n *\n * Sited here rather than in `constants.ts`: this module is already in\n * the `auth.js` closure, and importing `constants.ts` from the preset\n * would add about 0.6 KB min-gz to it.\n */\nexport const CF_ACCESS_TEAM_NAME_PATTERN: RegExp = /^[a-z0-9-]+$/;\n","/**\n * Leading and trailing path segments an `assertDocumentValues` error keeps\n * (`a.b.c.d.….w.x.y.z`). The document is caller-controlled and unbounded\n * in depth, so the message's path is capped; 4 + 4 segments name the\n * field's top-level location and its immediate container, which is what a\n * caller needs to find it.\n */\nexport const DOCUMENT_ERROR_PATH_EDGE_SEGMENTS = 4;\n\n/**\n * Characters of one object key an `assertDocumentValues` error path shows\n * before eliding the rest. Keys are caller-controlled and unbounded, so\n * this keeps one long key from making the message unbounded.\n */\nexport const DOCUMENT_ERROR_PATH_KEY_CHARS = 64;\n\n/**\n * Characters of a refused request `Content-Type` an `UnsupportedMediaType`\n * error echoes before eliding the rest. The header is caller-controlled\n * and its message is public, so this keeps one long header from making\n * the error body and the log line unbounded. 100 holds any registered\n * media type with a short parameter.\n */\nexport const UNSUPPORTED_MEDIA_TYPE_ECHO_CHARS = 100;\n\n/**\n * Max encoded size of one committed document (UTF-8 bytes of\n * `encodeJsonBytes(post-image)`, the bytes `LogEntry.after` is stored\n * as): 1 MiB.\n *\n * The writer refuses an insert, update or replace whose post-image is\n * larger, as `InvalidConfig` before any storage call. That bounds every\n * write path the same way: in-process calls, which no HTTP body cap\n * covers, and HTTP merge-patches, each of which fits `MAX_BODY_BYTES`\n * but can grow a stored row past it. Only the post-image is checked, so\n * a row stored larger by an earlier release stays readable, deletable,\n * and shrinkable.\n *\n * 1 MiB matches `MAX_BODY_BYTES` (a document at the cap still fits one\n * request body, with the envelope's few bytes of headroom lost).\n * Firestore's document limit is the same 1 MiB. Any snapshot format must\n * hold one row at this size: a later format sizes its storage unit to\n * fit the row rather than shrinking this cap.\n */\nexport const MAX_DOCUMENT_BYTES = 1_048_576;\n\n/**\n * Max nesting depth of one document or update patch: 100 levels, where\n * each object or array is a level and the document itself is the first.\n * A scalar adds none, so `{ a: [1] }` is 2 levels deep.\n *\n * `assertDocumentValues` refuses a deeper value as `SchemaError` before\n * any write: on `insert` and `replace`, on an update patch and on\n * each merged post-image, in the HTTP client before it sends, and on\n * `baerly admin restore`'s dump lines. Without a cap, a document\n * committed on a host with a deep call stack can overflow a recursive\n * path (`applyMergePatch`, `jsonValueEqual`, `JSON.stringify`) on a host with a\n * shallower one, wedging reads or folds of its collection; on Node 26 a\n * document of about 8,000 levels already overflows. Only writes are\n * checked, so a row stored deeper by an earlier release stays readable\n * and deletable.\n *\n * 100 is MongoDB's limit for BSON documents (\"Nested Depth for BSON\n * Documents\", MongoDB Limits and Thresholds). Any snapshot format must\n * hold a row at this depth.\n */\nexport const MAX_DOCUMENT_DEPTH = 100;\n\n/**\n * Max total object-key length S3 and R2 accept (UTF-8 bytes). A key\n * over this fails the PUT with an opaque provider 400; baerly surfaces\n * it early as InvalidConfig. See docs/spec/storage-compatibility.md.\n */\nexport const MAX_KEY_BYTES = 1024;\n\n/**\n * Largest `limit` an `order(...).limit(k)` read serves from a bounded\n * top-k heap instead of a full sort (`orderRows` in\n * `packages/server/src/query-eval.ts`). Above it the read sorts every\n * row, as it does with no `limit`.\n *\n * Measured with `bench/query-order.ts` (Node 26, random-order keys):\n * n = 2048, k = 20 / 64: 446 -> 57 / 664 -> 150 µs; n = 65,536 about\n * -93%. With the cap lifted the same heap keeps winning on random input\n * (n = 2048: -51% at k = 256, +27% at k = 1000), so 64 is not the\n * crossover. It bounds the heap's worst case, where every row replaces\n * the root, at about `1 + 2·log2(64) = 13` comparisons per row, close\n * to a full sort's `log2(2048) = 11` on random input at the Free row\n * ceiling, and it covers the usual page sizes.\n */\nexport const QUERY_TOP_K_MAX = 64;\n\n/**\n * Adjacent row pairs the top-k pre-scan always compares before it stops\n * comparing once the keys have both risen and fallen (see\n * {@link QUERY_TOP_K_MAX}). The rise/fall counts only choose which end\n * of the input the heap reads from, so that nearly reversed input\n * rarely replaces the root; they never change the result.\n */\nexport const QUERY_TOP_K_SAMPLE = 64;\n\n/**\n * Half-window (in milliseconds) within which a `LogEntry`'s embedded\n * `commit_ts` must agree with wall-clock time for downstream consumers\n * to accept the entry as causally ordered. Bound on tolerated\n * client/server clock skew across the protocol.\n *\n * 5 s is the protocol's tolerance for client/server clock skew.\n * Tightening this can cause spurious rejections on machines that\n * haven't synced NTP; loosening it widens the window during which\n * causal ordering can be disturbed by skew.\n *\n * @see docs/spec/sync-protocol.md\n * @see packages/protocol/src/storage/types.ts (`Storage` JSDoc)\n */\nexport const LAG_WINDOW_MILLIS: number = 5000;\n\n/**\n * Bit width of the descending base-32 seq segment in every LSN\n * (`<base32-time>_<session>_<seq>`, minted in `Writer.commit`).\n * The output character width is `Math.ceil(COUNT_BIT_WIDTH / 5) = 11`.\n *\n * **Domain:** 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1). A collection\n * would need 2^53 writes before the seq counter could overflow — an\n * unreachable ceiling in practice.\n *\n * **Why 53 bits:** JavaScript numbers are IEEE-754 doubles; the safe\n * integer range is exactly [0, 2^53 − 1]. Encoding at this width keeps\n * the arithmetic in the encoder and decoder (`uint2strDesc` /\n * `str2uintDesc` in `packages/protocol/src/types.ts`) exact and\n * leaves no headroom for the negative-overflow path that manifested\n * at the old 10-bit width (domain 0..1023).\n *\n * **Ordering property:** fixed-width base-32 encoding preserves\n * descending lex order across the entire domain\n * (`countKey(a) > countKey(b)` iff `a < b`), which the reverse-walk\n * on `Storage.list` relies on.\n *\n * **Three production consumers** must all agree on this value:\n * 1. Encoder — `countKey` in `packages/protocol/src/types.ts`\n * 2. Decoder — `lsnParts` in `packages/protocol/src/log.ts`\n * 3. Validator regex — `LSN_RE` in `packages/server/src/http/since.ts`\n * (derives its `{N}` from `Math.ceil(COUNT_BIT_WIDTH / 5)`)\n *\n * The independent shape-assertion literal in\n * `tests/fixtures/collection-api-cascade.ts` is kept hand-written and\n * is NOT a consumer of this constant (importing the production\n * validator into the test that checks it would make the assertion\n * a tautology).\n *\n * Changing this constant is a protocol-breaking change — it reshapes\n * every emitted LSN cursor.\n *\n * @see packages/protocol/src/types.ts (`countKey`, `uint2strDesc`)\n * @see packages/protocol/src/log.ts (`lsnParts`, `str2uintDesc` call)\n * @see packages/server/src/http/since.ts (`LSN_RE`)\n * @see docs/spec/log-entry-shape.md\n */\nexport const COUNT_BIT_WIDTH: number = 53;\n\n/**\n * Bit width of the base-32 timestamp prefix encoded into every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`, minted in\n * `Writer.commit`). 42 bits gives ~139 years of millisecond\n * precision, which is enough for the protocol's lifetime.\n *\n * Changing this is a protocol-breaking change — it would re-shape\n * every emitted LSN.\n *\n * @see packages/protocol/src/time.ts (`timestamp`)\n * @see packages/server/src/writer.ts (`Writer.commit`)\n * @see docs/spec/sync-protocol.md\n */\nexport const TIMESTAMP_BIT_WIDTH: number = 42;\n\n/**\n * Length of the random-prefix `session` segment embedded in every\n * {@link LogEntry.lsn} (`<base32-time>_<session>_<seq>`). 6 hex chars\n * from `crypto.randomUUID()` give 16⁶ ≈ 1.7 × 10⁷ distinct sessions;\n * birthday-collision rate at N=100 is ~3 × 10⁻⁴, comfortably below\n * the 1 % bound asserted in `tests/regressions.test.ts`. Collisions\n * within a single commit's writer set are also disambiguated by the\n * trailing `<seq>` counter.\n *\n * @see packages/server/src/writer.ts (`Writer.commit` —\n * `session = uuid().slice(0, SESSION_ID_LENGTH)`)\n */\nexport const SESSION_ID_LENGTH: number = 6;\n\n/**\n * 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/adapter-node/src/http-transport.ts (`parseRetryAfter`)\n */\nexport const RETRY_AFTER_MAX_SECONDS: number = 60;\n\n/**\n * Total attempts (first try included) every storage adapter makes for\n * one `Storage` call before surfacing the last failure: S3, GCS, and\n * the R2 binding, for `get` / `put` / `delete` and for each `list`\n * page. 429 and 5xx share this one counter, so a failing call costs at\n * most 3 requests on every host. Applied by `retryStorageCall`. An\n * `ifMatch` put (a compare-and-swap) is the exception: one attempt,\n * since a resend after a lost ack would meet its own write as a 412.\n *\n * 3 is the common prior-art cap: AWS SDK standard retry mode allows 3\n * attempts (https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html),\n * and the Google SRE book caps per-request retries at 3\n * (https://sre.google/sre-book/handling-overload/). Retrying happens at\n * this one layer only: stacked retry loops multiply (\"3 retries at 5\n * layers = 243x\", AWS Builders' Library, \"Timeouts, retries and backoff\n * with jitter\"). A store failing three times in a row is reported as a\n * retriable `NetworkError` rather than ridden out here.\n *\n * @see packages/protocol/src/storage/retry.ts (`retryStorageCall`)\n */\nexport const STORAGE_RETRY_MAX_ATTEMPTS: number = 3;\n\n/**\n * Full-jitter backoff base, in milliseconds, after a transient failure\n * (5xx, network error): retry `n` (0-based) waits\n * `random() * min(STORAGE_RETRY_MAX_DELAY_MILLIS, base * 2^n)`.\n *\n * 50 ms is the AWS SDKs' transient base\n * (https://aws.amazon.com/blogs/developer/announcing-updated-retry-behavior-for-aws-sdks-and-tools/).\n *\n * @see packages/protocol/src/storage/retry.ts (`storageRetryDelayMillis`)\n */\nexport const STORAGE_RETRY_TRANSIENT_BASE_MILLIS: number = 50;\n\n/**\n * Full-jitter backoff base, in milliseconds, after a throttle (`429`,\n * S3 `503 SlowDown`; any error whose cause carries `throttled: true`).\n * Longer than {@link STORAGE_RETRY_TRANSIENT_BASE_MILLIS} because a\n * throttle says the store is overloaded, and an early resend adds load.\n *\n * 1 s is the AWS SDKs' throttle base\n * (https://aws.amazon.com/blogs/developer/announcing-updated-retry-behavior-for-aws-sdks-and-tools/).\n *\n * @see packages/protocol/src/storage/retry.ts (`storageRetryDelayMillis`)\n */\nexport const STORAGE_RETRY_THROTTLE_BASE_MILLIS: number = 1000;\n\n/**\n * Upper bound, in milliseconds, on one backoff between storage\n * attempts, jittered or server-hinted (`Retry-After` is clamped to\n * it). 20 s is the AWS SDKs' backoff cap\n * (https://aws.amazon.com/blogs/developer/announcing-updated-retry-behavior-for-aws-sdks-and-tools/).\n *\n * @see packages/protocol/src/storage/retry.ts (`storageRetryDelayMillis`)\n */\nexport const STORAGE_RETRY_MAX_DELAY_MILLIS: number = 20_000;\n\n/**\n * Request-ledger limit on the `internal` pool on Workers Free (the\n * `cf-free` maintenance profile): every storage call one invocation may\n * issue, R2 binding calls and `fetch` calls alike. Cloudflare documents\n * 1,000 subrequests to internal services per Free invocation\n * (https://developers.cloudflare.com/workers/platform/limits/); 900 keeps\n * a 10% margin for calls the ledger cannot see but the platform counts:\n * app code in the same Worker, redirects, and any per-call multiplier on\n * the binding. A Free probe confirmed the 1,000 (the 1,001st binding call\n * throws \"Too many API requests by single Worker invocation\"); the R2\n * adapter's refusal on that error is the backstop if the ledger undercounts.\n *\n * @see packages/protocol/src/storage/ledger.ts (`RequestLedger`)\n */\nexport const CF_FREE_INTERNAL_REQUEST_LIMIT: number = 900;\n\n/**\n * Request-ledger limit on the `external` pool under the `cf-free`\n * profile: storage calls that leave through `fetch` (S3 over HTTP, GCS).\n * Only fetch storage charges this pool; R2 binding calls do not. Free\n * allows 50 external subrequests per invocation, and a `fetch` past the\n * 50th throws before it is sent (observed at exactly call 51). 45 keeps 5 for calls outside the ledger: the verifier's JWKS\n * fetch on a cold isolate and app code in the same Worker. The removed\n * response cache's allowance stays headroom; this limit is unchanged.\n * `CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES` and `CF_FREE_FETCH_GC_MAX_SWEEPS`\n * are sized so a whole request fits it.\n */\nexport const CF_FREE_EXTERNAL_REQUEST_LIMIT: number = 45;\n\n/**\n * Request-ledger limit on both pools on Workers Paid (the `cf-paid`\n * maintenance profile): Paid's default 10,000 subrequests per invocation\n * less a 10% margin. An operator who lowers `limits.subrequests` in the\n * Wrangler config is invisible to the Worker, so `cf-paid` assumes the\n * default.\n */\nexport const CF_PAID_REQUEST_LIMIT: number = 9000;\n\n/**\n * Legacy internal Cache API accounting cap. The production Worker never\n * calls the Cache API; point reads always reach storage. Retained with\n * `RequestLedger.chargeCacheCall` for budget-interference tests and\n * internal compatibility, without increasing any supported host limit.\n */\nexport const CF_CACHE_API_MAX_CALLS: number = 3;\n\n/**\n * Storage requests a commit keeps on the request ledger for resolving its\n * committing `log/<seq>` create: `2 * STORAGE_RETRY_MAX_ATTEMPTS` = 6.\n *\n * Once the create is sent, the writer may still need, each retried up to\n * `STORAGE_RETRY_MAX_ATTEMPTS` times by the adapter:\n *\n * - one occupant readback GET of the slot, when the create fails (a 412, a\n * send of unknown outcome, or a throttle that can hide a lost race), and\n * - the `current.json` GET of the delete-floor check, after a win or an\n * adopted lost-ack create.\n *\n * Without room for both, a create that landed but lost its reply cannot be\n * resolved and becomes `AmbiguousCommit`, and a won create skips the\n * delete-floor check. Everything else after the create (the write tick) is\n * best effort and is not reserved.\n *\n * Each slot's attempt runs under a request-ledger hold\n * (`RequestLedger.hold`) of\n * `STORAGE_RETRY_MAX_ATTEMPTS + COMMIT_RESOLUTION_RESERVE` = 9 requests: the\n * create at full retries, plus this reserve. The create is the commit's only\n * write, so the hold is the same for every collection, whatever indexes it\n * declares. Other work in the invocation (a `ctx.waitUntil` write tick)\n * cannot spend held requests. The writer refuses with `CapacityExceeded`,\n * before it writes anything, when the ledger's room cannot cover the hold.\n * After a lost create race it takes a new hold before the next create.\n *\n * The arithmetic assumes the default adapter retry policy; an adapter\n * configured with more retries can need more than it reserves.\n *\n * @see packages/server/src/writer.ts (`#withCommitHold`)\n */\nexport const COMMIT_RESOLUTION_RESERVE: number = 2 * STORAGE_RETRY_MAX_ATTEMPTS;\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 (measured at 150-360 entries at\n * steady state on the free-tier profile).\n *\n * 16 bounds CONCURRENCY, not the per-request total: a walk still issues\n * one GET per live-tail entry, 16 at a time, and every GET is charged to\n * the invocation's request ledger, which refuses a read whose tail does\n * not fit the host's limit. On Workers the platform also caps an\n * invocation at 6 simultaneous outgoing connections, R2 binding calls\n * included, so the walk runs at most 6 at a time there whatever this\n * value is. A reader relies on the compactor keeping the live tail short\n * enough that the walk fits; see `docs/spec/scale-ceilings.md`\n * §Per-tier bounds.\n *\n * @see packages/server/src/log-walk.ts (`walkLogRange`)\n */\nexport const MAX_PARALLEL_LOG_READS: number = 16;\n\n/**\n * Runaway guard on the tolerant forward-probe walk (`probeTailFrom`):\n * max `log/<seq>` GETs past `tail_hint` before it THROWS `Internal`\n * (rather than silently truncating reads). A runaway alarm only — the\n * maintenance tick keeps `tail_hint` near the tail, so a >cap gap means\n * maintenance is off or the collection is far past graduation.\n *\n * @see packages/server/src/log-tail.ts (`probeTailFrom`)\n */\nexport const LOG_FORWARD_PROBE_CAP: number = 100_000;\n\n/**\n * Sequence distance retained below `log_seq_start` before `log/<seq>.json`\n * objects become retirable: a rate limit on how fast retirement approaches the\n * live floor.\n *\n * Folded entries stay readable below the floor for this long, which is what a\n * windowed commit (`Writer#readFoldedWindow`, for an insert guard or an\n * admission re-check whose read predates a fold) needs to finish rather than\n * refuse with `WriteConflict`; it reads at most the entries a fold absorbed\n * between two reads in one request, far fewer than 1024. The value is a\n * literal: it carries no derivation, and shrinking it is a measured change of\n * its own.\n *\n * **This window is NOT a paused-writer fence, and no safety property may be\n * derived from it.** It is a cost margin and a rate limit on how fast\n * retirement approaches the live floor — nothing more. The withdrawn argument\n * was that a certified-deleted slot needs `log_seq_start` to advance by more\n * than this window \"during one in-flight commit\". The arithmetic is correct and\n * the quantifier is vacuous: one in-flight commit bounds no wall-clock and no\n * commit count, so this is a rate x duration assumption expressed in sequences,\n * the same class as `GC_GRACE_PERIOD_MILLIS` in seconds. Lowering the value on\n * cost grounds costs windowed-commit headroom and retirement smoothness; it\n * does not weaken a safety proof, because there was never one here.\n *\n * Withdrawing the claim does not leave the schedule open, because the commit\n * path closes it directly. After the committing `log/<seq>` create resolves,\n * `Writer#assertCommitAboveDeleteFloor` re-reads `current.json` and fails a\n * create that won at a `seq` below `min(log_delete_floor, log_seq_start)` with\n * `BaerlyError{code:\"AmbiguousCommit\"}`, rather than acknowledging a mutation\n * no reader can see. That check keys on the certified delete floor, not on this\n * window, which is exactly why the window may keep being a cost margin without\n * carrying a safety obligation. Do not re-derive a fence from this value.\n *\n * @see packages/server/src/writer.ts (`Writer#assertCommitAboveDeleteFloor`)\n * @see packages/server/src/log-retention.ts\n * @see docs/spec/sync-protocol.md invariant 12\n * @see docs/adr/002-ephemeral-coordination.md § Closed paths\n */\nexport const LOG_RETENTION_SEQ_WINDOW: number = 1024;\n\n/**\n * Maximum log-object DELETEs a retention pass may attempt on one write tick.\n * Twenty keeps a GC tick plus retirement at 48 calls (144 with every call\n * retried), inside Workers Free's 900-call R2 binding limit, and drains faster\n * than the fold floor advances in steady state.\n *\n * `retireLogRange` is the pass that spends this budget. Every maintenance\n * trigger runs it via the shared `retireLogs` helper in `maintenance.ts`:\n * `runScheduledMaintenance` after its GC phase, and `runBoundedMaintenance`\n * both on the hard-GC early-return path and as its final step. The combined\n * per-tick storage-call arithmetic, against the worst cases `maintenance.ts`'s\n * `CLOUDFLARE_FREE_TIER` JSDoc documents (fault-free; times\n * {@link STORAGE_RETRY_MAX_ATTEMPTS} with every call retried):\n *\n * - One retirement pass, worst case, is 23 calls: 1 advisory-gate GET\n * + `casUpdateCurrentJson`'s own GET + 1 CAS PUT + up to 20 DELETEs.\n * - A maximally contended write-tick GC including the retirement gate read\n * is 26 storage operations, pinned exactly by `maintenance-budget.test.ts`.\n * When the gate finds work, the pass adds its CAS read + CAS write + up to\n * 20 DELETEs on top (48, or 144 retried).\n * - A compaction pass is ≤49, so compact + retirement would be 72. **Retirement\n * cannot share a tick with a fold**: in `\"single\"` phase mode a write-tick\n * fold returns before the runner's retirement step, and\n * `maintenance-budget.test.ts` pins that a fold tick issues zero retirement\n * storage ops.\n * - The write-tick host request also spends one `current.json` GET on the\n * commit path's certified-delete-floor check, outside the tick's pinned\n * figures above. Nothing here changes the value 20: retirement never\n * shares a tick with a fold, so the DELETE budget only ever stacks onto a\n * GC tick.\n *\n * A pass whose range is empty returns `{deleted: 0}` and spends 1 GET. Its\n * observability is the `db.log_retention.deleted_total` counter `retireLogs`\n * emits per pass, so a permanently-stalled retirement (a floor wedged at the\n * live floor) is visible as a counter that stays flat while the log object\n * count grows.\n *\n * @see packages/server/src/log-retention.ts\n * @see packages/server/src/maintenance.ts (`retireLogs`)\n */\nexport const LOG_RETENTION_MAX_DELETES_PER_TICK: number = 20;\n\n/**\n * Current major version of the `current.json` control-object schema.\n * Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `CurrentJson` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_SCHEMA_VERSION = 3 as const;\n\n/**\n * MIME type written for `current.json` PUTs. S3 round-trips this on\n * subsequent GETs; useful for diagnostics when staring at a bucket\n * via the AWS console.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n */\nexport const CURRENT_JSON_CONTENT_TYPE: string = \"application/json\";\n\n/**\n * Current major version of the `gc/pending.json` control-object\n * schema. Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `GcPending` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_SCHEMA_VERSION = 1 as const;\n\n/**\n * Current major version of the snapshot control-object schema\n * ({@link SnapshotBody}). Readers MUST reject unknown versions with\n * `BaerlyError{code:\"InvalidResponse\"}` rather than try to coerce.\n *\n * Bump only on a breaking change to `SnapshotBody` field semantics.\n * Adding a new optional field is NOT breaking; renaming or removing\n * a field IS breaking.\n *\n * @see packages/server/src/snapshot.ts\n */\nexport const SNAPSHOT_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 STORAGE_RETRY_THROTTLE_BASE_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 * Fraction of the GC grace one `runGc` pass may spend between the\n * `current.json` read its DELETEs rest on and each DELETE batch. Once\n * the elapsed time exceeds `graceMillis * GC_PASS_GRACE_FRACTION`, the\n * pass issues no further DELETEs and leaves the remaining due\n * candidates in `gc/pending.json` for a later pass, which re-reads the\n * manifest.\n *\n * Why 1/10:\n * - **A live pass never trips it.** Against the 7-day default the\n * budget is ~16.8 hours, and a pass on every first-class host lasts\n * seconds. Only a paused or starved process crosses it.\n * - **It bounds how stale a DELETE's liveness proof can be.** It\n * matters for the legacy `stale-log` arm, whose DELETE can rest on\n * the pass's first `current.json` read: a candidate is due no earlier\n * than its mark plus the grace, so a DELETE issued within `f` of the\n * grace after that read rests on one taken at least `(1 - f)` of the\n * grace after the mark. An `orphan-snapshot` DELETE always rests on\n * the sweep-time re-read, taken after the candidate came due, so a\n * full grace after its mark.\n *\n * In-band, by design: one clock comparison per DELETE batch, no lease\n * and no knob. Elapsed time is the larger of one node's wall-clock and\n * monotonic readings, so neither cross-node skew nor a backward clock\n * correction shortens it, and a suspend the monotonic clock skips still\n * shows on the wall clock. The after-the-mark figures rest on `due_at`\n * and so keep invariant 14's wall-clock limitation. A pass with\n * `graceMillis: 0` (tests only) has no grace to keep a fraction of and\n * is not bounded.\n *\n * @see docs/spec/sync-protocol.md (invariant 14)\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_PASS_GRACE_FRACTION: number = 1 / 10;\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 * Keys per LIST response page on every in-tree object-store adapter:\n * S3 and GCS `max-keys` and R2 binding `limit` all cap at 1000. `runGc`\n * widens its orphan-snapshot mark window past already-pending keys only\n * up to this size, so the widening never adds a full LIST page (a\n * provider may still truncate a page short and cost another request).\n *\n * @see packages/server/src/gc.ts\n * @see docs/spec/storage-compatibility.md\n */\nexport const GC_MARK_LIST_PAGE_KEYS: number = 1000;\n\n/**\n * Bounded retry cap for the `gc/pending.json` CAS read-modify-write\n * loop in {@link casUpdateGcPending}. On `WriteConflict` (a concurrent GC\n * pass landed between this pass's read and its write) the loop\n * re-reads `latest` and re-applies the pure merge mutator, retrying up\n * to this many total attempts before surfacing `WriteConflict`. Safe to\n * retry because the mutator is pure and the sweep DELETEs are\n * idempotent and already performed; a re-merge against fresh state\n * never loses a concurrently-marked candidate. Small fixed cap — under\n * one writer per collection at steady state, contention is rare; this\n * just bounds the worst case so a pathological storm can't spin.\n *\n * @see packages/protocol/src/coordination/gc-pending.ts\n */\nexport const GC_PENDING_CAS_MAX_ATTEMPTS: number = 3;\n\n/**\n * Fold-trigger ratio: fold fires at tail ≥ R×snapshot. Pure READ-AMP / fold-frequency\n * knob — with the ceiling on the snapshot axis (Decision 3a, tail sliced) the\n * auto-maintained snapshot ceiling is S_max = C, NOT C/(1+R). R=1.0 caps steady-state\n * read-amp at ~2× and keeps compaction write-amp (≈1+1/R) moderate. See\n * docs/spec/scale-ceilings.md for the derivation.\n *\n * @see docs/spec/scale-ceilings.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TARGET_RATIO: number = 1;\n\n/**\n * Floor for the ratio denominator — avoid div-by-tiny on a fresh collection. Also\n * sets the first-fold threshold: until a snapshot exists, fold fires at tail ≈ this.\n *\n * @see packages/server/src/maintenance.ts\n */\n// Stryker disable next-line ArithmeticOperator: internal tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_MIN_LIVE_BYTES: number = 64 * 1024;\n\n/**\n * Cold-start per-entry byte estimate for the ratio TRIGGER's derived live-tail\n * size (`estimateTailBytes`), used until the compactor stamps a real\n * `current.json.mean_entry_bytes` on the first fold. Folding too-few entries is\n * barred by Gate-1's entry-count floor (`minEntriesToCompact`), NOT by this\n * value — so over-estimating is equally safe; this is a first-fold-TIMING\n * choice. A small typical log-entry size keeps the first fold's cadence close\n * to a precisely measured path for typical entries; must be non-zero so a\n * bare `Db.create()` still bootstraps its first auto-fold (a 0 fallback leaves\n * the ratio dead pre-stamp). Large-body collections see a bounded first-fold\n * delay; after it stamps a real mean the estimate tracks the exact tail.\n *\n * @see packages/server/src/maintenance.ts (`estimateTailBytes`)\n */\n// Stryker disable next-line ArithmeticOperator: internal cold-start tuning value, not an off-process contract — asserting the literal would be a tautological change-detector. See docs/contributing/mutation-testing.md constants policy.\nexport const MAINTENANCE_COLD_START_ENTRY_BYTES: number = 128;\n\n/**\n * Per-tick GC budget — these are DEFAULTS (= the most-constrained tier, CF free, reusing\n * the TESTED `CLOUDFLARE_FREE_TIER` values in maintenance.ts / maintenance-budget.test.ts).\n * The adapter THREADS per-tier overrides into the context (§8.4); Node/CF-paid raise them.\n * NOT universal constants — a Node-sized value here would exceed the CF-free budget on every fold\n * (round-4 Tier-1). `gcMaxMarks` bounds each LIST classification window and the resulting\n * ledger growth; `gcMaxSweeps` bounds DELETEs. Cadence is BOUNDARY-CROSSING (§3.1), not\n * 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 keys classified per GC category per write-tick pass. Bounds the LIST window and\n * the candidate-ledger growth it can cause.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const WRITE_TICK_GC_MAX_MARKS: number = 20;\n\n/**\n * Maximum candidate DELETEs per write-tick pass.\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 * Cloudflare Free scheduled-compactor tail-discovery budget (`P`). A\n * prior-snapshot fold pass costs 1 GET current + P GETs tail probe +\n * 1 GET prior snapshot + N GETs log + 1 PUT snapshot + 1 PUT current\n * = 4 + N + P storage operations. With P=25 and the Free profile's\n * N=20 slice, the worst pass is 49 operations, 147 with every call\n * retried, inside the 900 a Free invocation may spend through the R2\n * binding ({@link CF_FREE_INTERNAL_REQUEST_LIMIT}). Through `fetch` (45)\n * the pass lowers its probe to what the ledger leaves after the fold\n * ({@link COMPACT_FOLD_WRITE_REQUESTS}), 21 GETs, and fits in 45; see\n * `CLOUDFLARE_FREE_TIER`. Kept at 25\n * because Free CPU, not the request count, binds first on the binding,\n * and the maintenance-backlog baselines were measured at it.\n *\n * @see packages/server/src/maintenance.ts\n * @see packages/server/src/maintenance-budget.test.ts\n */\nexport const CF_FREE_COMPACT_TAIL_PROBE_GETS: number = 25;\n\n/**\n * Cloudflare Paid scheduled-compactor tail-discovery budget (`P`) for\n * `CLOUDFLARE_PAID_TIER`. Without one, the scheduled probe may walk up to\n * {@link LOG_FORWARD_PROBE_CAP} (100,000) GETs past a stale `tail_hint`,\n * which no Paid invocation can issue: the request ledger refuses the pass\n * at {@link CF_PAID_REQUEST_LIMIT} and nothing folds. With a budget, a\n * pass that exhausts it checkpoints the certified lower bound in\n * `current.json` and the next pass resumes there.\n *\n * With the Paid profile's per-pass slice\n * `N` = {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} (200), the worst\n * pass is `4 + N + P` = 1,204 storage calls, 3,612 with every call retried\n * {@link STORAGE_RETRY_MAX_ATTEMPTS} times, well inside 9,000. 1,000 is\n * five slices of discovery per pass: large enough that a pass behind by\n * a normal backlog still folds, small enough that a scheduled compact, GC\n * and retirement pass together stay under the limit at full retries.\n *\n * @see packages/server/src/maintenance.ts (`CLOUDFLARE_PAID_TIER`)\n * @see packages/server/src/maintenance-budget.test.ts\n */\nexport const CF_PAID_COMPACT_TAIL_PROBE_GETS: number = 1000;\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 * Storage requests a write-tick fold issues besides its log GETs, on its\n * common path (every call answered first time, no concurrent writer): the\n * `current.json` GET, one tail-probe GET at the writer's observed tail, the\n * prior-snapshot GET, the snapshot PUT and the `current.json` CAS PUT. A\n * fold of `e` entries costs `5 + e` after the runner's own `current.json`\n * GET (the `6 + e` in {@link CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES}'s\n * derivation counts that GET too).\n *\n * `runBoundedMaintenance` skips the fold when the invocation's request\n * ledger has less than this plus the tail it would fold left. Retries and\n * a tail a concurrent writer lengthened can still overrun; the ledger\n * refuses that call before it is sent and the next tick folds again.\n *\n * @see packages/server/src/maintenance.ts (`runBoundedMaintenance`)\n */\nexport const MAINTENANCE_FOLD_BASE_REQUESTS: number = 5;\n\n/**\n * Storage writes a folding `compact()` pass issues after its log GETs: the\n * snapshot PUT and the `current.json` CAS PUT. A bounded scheduled compact\n * (`maxTailProbeGets` set) reserves these, the prior-snapshot GET and its\n * `maxEntriesPerRun` log GETs out of what the invocation's request ledger\n * has left after its `current.json` GET, and probes the tail with the rest\n * (at most `maxTailProbeGets`). On Workers Free over `fetch`\n * ({@link CF_FREE_EXTERNAL_REQUEST_LIMIT} = 45, N = 20) that leaves a\n * 21-GET probe, so a pass behind a stale `tail_hint` folds in 45 calls\n * instead of being refused at call 46 before it writes anything.\n *\n * @see packages/server/src/compactor.ts\n */\nexport const COMPACT_FOLD_WRITE_REQUESTS: number = 2;\n\n/**\n * Storage requests a write-tick GC slice issues besides its sweep DELETEs,\n * on its common path: the `current.json` GET, the `gc/pending.json` GET,\n * one snapshot LIST page, the fresh `current.json` GET before a due sweep,\n * and the pending CAS (GET + PUT). A slice sweeping `S` costs `6 + S`.\n * Contention adds at most 6 (the pending-bootstrap race, two more CAS\n * attempts), the `12 + S` worst case in `CLOUDFLARE_FREE_TIER`'s JSDoc.\n *\n * `runBoundedMaintenance` lowers the slice's sweep cap to what the\n * invocation's request ledger has left after this, and skips the slice\n * when not even this is left. A deferred sweep stays pending for the next\n * slice.\n *\n * @see packages/server/src/maintenance.ts (`runBoundedMaintenance`)\n */\nexport const MAINTENANCE_GC_BASE_REQUESTS: number = 6;\n\n/**\n * Most storage requests a log-retirement pass can be charged before its\n * floor CAS lands: the advisory `current.json` GET and the CAS's own GET,\n * each up to {@link STORAGE_RETRY_MAX_ATTEMPTS} attempts, plus the CAS PUT,\n * which an If-Match PUT sends once. 7 at 3 attempts.\n *\n * `retireLogRange` moves `log_delete_floor` past the range BEFORE it\n * DELETEs it, and the next pass starts at the floor, so a DELETE refused\n * after the CAS leaks that log object for good. `runBoundedMaintenance`\n * therefore caps the pass at `(remaining - this) / STORAGE_RETRY_MAX_ATTEMPTS`\n * DELETEs, so every DELETE can spend all its attempts, and skips the pass\n * when that leaves none. The range not retired stays retirable.\n *\n * @see packages/server/src/maintenance.ts (`runBoundedMaintenance`)\n * @see packages/server/src/log-retention.ts (`retireLogRange`)\n */\nexport const MAINTENANCE_RETIRE_PRE_FLOOR_REQUESTS: number = 2 * STORAGE_RETRY_MAX_ATTEMPTS + 1;\n\n/**\n * Storage requests the write tick's `tail_hint` refresh issues: one\n * non-retrying `casUpdateCurrentJson` (GET + PUT). `runBoundedMaintenance`\n * skips the refresh when the invocation's request ledger has less left; a\n * later tick refreshes instead.\n *\n * @see packages/server/src/maintenance.ts (`runBoundedMaintenance`)\n */\nexport const MAINTENANCE_TAIL_HINT_REFRESH_REQUESTS: number = 2;\n\n/**\n * Live-tail length at which the write tick folds under the `cf-free`\n * profile when the Worker reaches its bucket through `fetch` (S3 over\n * HTTP) rather than the R2 binding, whatever the tail-to-snapshot ratio.\n * The Cloudflare adapter detects that from the storage it was given and\n * threads this as `foldAtTailEntries`, with\n * {@link CF_FREE_FETCH_GC_MAX_SWEEPS}; Free with the R2 binding, `cf-paid`,\n * and Node keep the ratio trigger alone.\n *\n * Workers Free + S3 is not a supported host. A Worker cannot tell Free\n * from Paid, so `cf-free` caps storage over `fetch` at\n * {@link CF_FREE_EXTERNAL_REQUEST_LIMIT} calls: a request past Free's 50\n * gets a typed `CapacityExceeded` instead of the platform throwing at call\n * 51. This trigger keeps ordinary requests inside that cap, including a\n * Paid Worker on S3 that has not set `cf-paid`.\n *\n * **Why the ratio trigger fails there.** Every storage call there is\n * charged to the `external` pool, {@link CF_FREE_EXTERNAL_REQUEST_LIMIT}\n * (45) of Free's 50 external subrequests per invocation, leaving 5 for the\n * verifier and platform. The Cloudflare limits page counts\n * subrequests per invocation and does not exempt `ctx.waitUntil` work, so\n * the tick a write dispatches is assumed to share the write's cap. A write\n * and a read both replay the live tail, one GET per entry, so a request\n * costs at least its tail. The ratio trigger first folds near 512 entries\n * (`MAINTENANCE_MIN_LIVE_BYTES` / 128-byte entries) and no sooner than\n * {@link WRITE_TICK_MIN_ENTRIES_TO_COMPACT} (50): at that tail an insert\n * alone costs 57 calls, so the fold never fits and every read fails once\n * the tail passes ~41.\n *\n * **Derivation of 7.** From `request-counts.json` (100-doc snapshot, live\n * tail `t`): an insert, an update and a delete each cost `7 + t`, whatever\n * indexes the collection declares; the commit's only write is its log\n * create. A fold of `e` entries costs `6 + e`. A fold and GC never share a\n * tick (`phasesPerTick: \"single\"`), so a request costs its route plus one\n * of:\n *\n * - the fold, triggered at tail `T`, or `T + 1` when the hard-GC guard\n * pre-empts it: at most `14 + 2T`, 28 at `T = 7`;\n * - a GC slice sweeping `D` = {@link CF_FREE_FETCH_GC_MAX_SWEEPS} due\n * snapshots, plus log retirement, including a write whose tail reaches\n * `T + 1` while the hard-GC guard pre-empts the fold.\n *\n * The Worker adds no Cache API calls. The `free-fetch:*` cells measure\n * inserts, cold updates and a mixed rotation through a full cycle of\n * fold and GC phases with\n * every GC slice sweeping its cap; the worst is 30 at `T = 7`,\n * `D = 3`, set by the GC arm. `T = 8`, `D = 2` would only match snapshot\n * creation at the guaranteed GC cadence; `T = 7`, `D = 3` leaves sweep\n * throughput headroom. The 15 calls of room left are deliberately unspent:\n * a later fold trigger moves the snapshot-creation rate and the GC\n * throughput argument on {@link CF_FREE_FETCH_GC_MAX_SWEEPS}, so raising\n * `T` is a measured change of its own.\n * The longest live tail a read then sees is `T + 1` = 8: any read, with or\n * without declared indexes (`$in` included), costs 11. Every point read\n * pays this storage-backed cost, even when repeated.\n * Retried calls (up to `STORAGE_RETRY_MAX_ATTEMPTS` each) are outside this\n * budget.\n *\n * Changing this value, a fold or GC cost, or the GC cadence moves the\n * `free-fetch:*` cells; `tests/unit/request-counts.test.ts` asserts they\n * stay within 45.\n *\n * @see packages/adapter-cloudflare/src/worker.ts (`cfMaintenanceDispatch`)\n * @see tests/fixtures/request-count-free-fetch.ts\n * @see https://developers.cloudflare.com/workers/platform/limits/#subrequests\n */\nexport const CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES: number = 7;\n\n/**\n * Most replaced snapshots one write-tick GC slice deletes under the\n * `cf-free` profile when storage is reached through `fetch`; replaces\n * {@link WRITE_TICK_GC_MAX_SWEEPS} (10) there. Each DELETE is one of the\n * request's external subrequests, and a full 10-delete slice on top of the\n * write that dispatched it exceeds the 45-call budget at the tail lengths a\n * write tick folds from. At 3 every `free-fetch:*` cell fits with room to\n * spare at {@link CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES} (derivation there);\n * the sweep stays at 3 because it is sized by the throughput argument below,\n * which a larger sweep only widens.\n *\n * **Sweep throughput must outrun the fold rate.** Every landed fold\n * replaces one snapshot, so a collection produces at most one sweep\n * candidate per `T` commits (`T` = the fold trigger). On\n * `phasesPerTick: \"single\"` a fold may pre-empt a cadence GC tick but never\n * the hard-GC tick, which runs once per\n * `WRITE_TICK_GC_INTERVAL * GC_STARVATION_GUARD` = 16 commits, so the\n * guaranteed sweep rate alone must cover it:\n *\n * D / 16 > 1 / T, i.e. D > 16 / T = 2.3 at T = 7.\n *\n * `D = 3` clears that with about 31% margin before counting the cadence\n * GC ticks folds do not pre-empt. This sizes the sweep only; it assumes\n * marking keeps pace with the fold rate.\n *\n * @see packages/adapter-cloudflare/src/worker.ts (`cfMaintenanceDispatch`)\n */\nexport const CF_FREE_FETCH_GC_MAX_SWEEPS: number = 3;\n\n/**\n * The scheduled pass's own `minEntriesToCompact` floor (`runMaintenancePass`,\n * which `runScheduledMaintenance` runs), applied when no\n * `options.compact.minEntriesToCompact` is set. Deliberately NOT\n * `DEFAULT_MIN_TO_COMPACT` (compact()'s own 100) or\n * {@link WRITE_TICK_MIN_ENTRIES_TO_COMPACT} (50): both of those floors exist\n * for the IN-BAND write tick, where a write is not a scheduling decision and\n * folding on every one would thrash snapshot rewrites. A scheduler that\n * fires has already decided it is time to do work, so the only live tail\n * worth leaving unfolded is none — a count floor on the scheduled path\n * parks a low-write collection's tail permanently between the floor and\n * the reads' per-entry GET cost (measured: a 36-entry tail costing 36 S3\n * GETs, ~1.2s, on every read because a 100-floor cron tick skipped it for\n * months; a consumer independently converged on 1). Each fold rewrites\n * the whole snapshot, so write-amplification-sensitive callers can still\n * raise it via `options.compact.minEntriesToCompact`; see\n * docs/spec/sync-protocol.md § Maintenance runtime model.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const SCHEDULED_MIN_ENTRIES_TO_COMPACT: number = 1;\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 performs bounded fold work plus bounded GC LIST classification and DELETE sweeps\n * against a co-located S3/R2 — sub-second on the occasional boundary write at a 10×\n * 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\n * here would reintroduce as multi-second commit stalls. Raise the snapshot ceiling separately\n * via `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; these caps slice the per-pass work, not the\n * ceiling.\n *\n * @see packages/adapter-node/src/server.ts\n * @see packages/server/src/maintenance.ts\n * @see docs/spec/scale-ceilings.md\n */\nexport const NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS: number = 200;\n\n/** Node-tier per-category LIST classification/ledger-growth cap. 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_MARKS: number = 200;\n\n/** Node-tier candidate DELETE cap per pass. 10× CF-free. @see {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} */\nexport const NODE_MAINTENANCE_GC_MAX_SWEEPS: number = 100;\n\n/**\n * Keys per parallel DELETE batch in a `runGc` sweep. The pass checks\n * {@link GC_PASS_GRACE_FRACTION} before each batch, so this is how many\n * DELETEs can land after the bound is crossed.\n *\n * Equal to the largest in-band sweep cap\n * ({@link NODE_MAINTENANCE_GC_MAX_SWEEPS}), so every write-tick GC\n * slice issues its DELETEs as one batch and pays no added round trip.\n * Only a pass with a larger or no sweep cap splits its sweep. Batching\n * changes no request count.\n *\n * @see packages/server/src/gc.ts\n */\nexport const GC_SWEEP_DELETE_BATCH_KEYS: number = NODE_MAINTENANCE_GC_MAX_SWEEPS;\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. A\n * conservative configured budget for the CF-free ~10 ms CPU limit; the ~5.5 ms\n * rebuild-time figure behind it is a sizing estimate, not an observed platform\n * limit. 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/spec/scale-ceilings.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 * is past the conservative budget, and a larger snapshot rebuild may\n * exceed an invocation's CPU or memory resources. If an invocation is\n * terminated mid-rebuild the CAS does not land, so that fold does not\n * advance `log_seq_start`. This value is a configured budget; no\n * particular snapshot size is established to cause termination.\n *\n * Sized at 2× {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. The ~5.5 ms\n * rebuild estimate for the default (512 KiB) and the linear\n * extrapolation to ~1 MiB are sizing estimates, not observed platform\n * limits; anything strictly larger is simply outside the budget\n * this constant documents. On CF **paid**\n * (raised CPU limits) or Node, a larger ceiling is fine — hence this is\n * a one-time `console.warn` at 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/spec/scale-ceilings.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).\n *\n * This is the **cf-free** value and the shared default. `pnpm bench:fold-ceiling`\n * measures 2048 rows at ~1.5 ms against the ~10 ms free-tier budget (a ~6.6×\n * margin), and the row axis does not reach 10 ms until ~16,384 rows. The value\n * stays at 2048 as a conservative configured budget: a fold that overruns a free\n * isolate's CPU may be terminated before the `current.json` CAS lands — see\n * {@link CF_FREE_MAX_SAFE_FOLD_BYTES}. The\n * larger hosts no longer inherit it; see {@link CF_PAID_MAINTENANCE_MAX_FOLD_ROWS}\n * and {@link NODE_MAINTENANCE_MAX_FOLD_ROWS}.\n *\n * @see docs/spec/scale-ceilings.md\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_MAX_FOLD_ROWS: number = 2048;\n\n/**\n * Snapshot-rebuild byte ceiling `C` for the **cf-paid** profile.\n *\n * A paid isolate's wall is ~128 MB of Worker memory, not CPU — at a 30 s CPU\n * budget the rebuild is never CPU-bound, but a fold holds the old snapshot, the\n * new snapshot, and the tail at once. `pnpm bench:fold-ceiling` measures peak\n * heap at ~2.4× the snapshot on the byte axis, stable across 704 MB–4.3 GB\n * heaps: 8 MiB peaks at ~19.5 MB, a 4× margin under 128 MB. The next grid cell\n * up (16 MiB ⇒ 37.3 MB peak) exceeds that margin, which is what fixes this\n * value.\n *\n * The margin is deliberately tight because overrun is NOT graceful here: an\n * isolate OOM mid-fold would leave the `current.json` CAS unpublished, so that\n * fold would not advance `log_seq_start`.\n *\n * @see docs/spec/scale-ceilings.md\n * @see bench/measurement/fold-ceiling-probe.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 CF_PAID_MAINTENANCE_MAX_FOLD_BYTES: number = 8 * 1024 * 1024;\n\n/**\n * Snapshot-rebuild row ceiling `E` for the **cf-paid** profile. Same 128 MB\n * memory wall and same 4× margin as {@link CF_PAID_MAINTENANCE_MAX_FOLD_BYTES};\n * the row axis costs ~600 B of peak heap per row (measured), so 32,768 rows\n * peaks at ~19.7 MB. The next grid cell up (65,536 rows ⇒ 39.4 MB) exceeds the\n * margin.\n *\n * @see docs/spec/scale-ceilings.md\n */\nexport const CF_PAID_MAINTENANCE_MAX_FOLD_ROWS: number = 32_768;\n\n/**\n * Snapshot-rebuild byte ceiling `C` for the **node** profile.\n *\n * Serverful Node has no per-request cap, and its fold is not abortable —\n * `nodeMaintenanceDispatch` passes no `signal` — so an over-large fold\n * COMPLETES. The failure mode is one slow write, not a stranded CAS. That\n * asymmetry is why Node's ceiling is set generously where cf-free's and\n * cf-paid's are set tightly: UNDER-setting `C` permanently defers the fold,\n * which is the worse failure on every host. Inline fold latency is budgeted by\n * {@link NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS} (the sliceable tail work), not\n * by this ceiling (the unsliceable snapshot rebuild).\n *\n * 32 MiB is the top of the measured grid, NOT the wall: `pnpm bench:fold-ceiling`\n * reports `grid-exhausted` for this profile at every margin and at every heap\n * from 704 MB up. At a 704 MB heap — the smallest realistic container — a\n * 32 MiB fold peaks at ~37 MB, a ~19× margin. The scaling rule past the grid is\n * `C ≈ heap / 10` (peak ≈ 2.4× snapshot, 4× margin). Finding the real wall\n * needs the byte axis extended past 32 MiB.\n *\n * A separate hard ceiling sits near 512 MB regardless of heap: `encodeJsonBytes`\n * / `decodeJsonBytes` materialize the whole snapshot as a JS string, so a\n * snapshot at V8's `MAX_STRING_LENGTH` throws mid-fold.\n *\n * @see docs/spec/scale-ceilings.md\n * @see bench/measurement/fold-ceiling-probe.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 NODE_MAINTENANCE_MAX_FOLD_BYTES: number = 32 * 1024 * 1024;\n\n/**\n * Snapshot-rebuild row ceiling `E` for the **node** profile. 65,536 rows is the\n * largest row cell with a stable measured peak (~39.4 MB, reproduced within\n * 0.05 MB across four runs); the 131,072-row cell's peak is not yet reliably\n * measurable. Against even a 704 MB heap that is a ~17× margin, consistent with\n * {@link NODE_MAINTENANCE_MAX_FOLD_BYTES} being a measured floor rather than a\n * wall.\n *\n * @see docs/spec/scale-ceilings.md\n */\nexport const NODE_MAINTENANCE_MAX_FOLD_ROWS: number = 65_536;\n\n/**\n * Byte slack the growth refusal keeps under `C` (main-10 G4). A growth write\n * is refused when its projected snapshot bytes would exceed\n * `C - CAPACITY_BYTES_MARGIN`. The projection sizes the snapshot exactly as\n * the compactor encodes it (rows, separators, header) for a known fold end,\n * which is how fold passes are judged against `C` itself. A growth check\n * does not know when its write will fold, so the header's `max_seq` may\n * gain digits by then (at most 16 for a safe integer). 64 bytes covers that\n * with room to spare; `capacity.test.ts` checks the projection against real\n * folds byte for byte.\n *\n * @see docs/spec/scale-ceilings.md\n */\nexport const CAPACITY_BYTES_MARGIN: number = 64;\n\n/**\n * Fraction of a fold ceiling at which an admitted write starts carrying a\n * capacity warning (main-10 G7). The warning fires when the projected\n * snapshot, at its peak over the pending tail and the writes just\n * admitted, holds at least this share of `E` rows or of the `C - margin`\n * bytes the growth refusal compares against. It is a policy choice, not a\n * measurement: 90% leaves roughly 200 rows of runway on Workers Free's\n * 2,048-row `E`, enough for an app to react before the first\n * `CapacityExceeded`, and about 10% of `C` in bytes. The warning is a\n * pure function of `current.json` and the tail, so it clears the moment\n * that state drops back under the threshold.\n *\n * @see packages/server/src/capacity.ts\n */\nexport const CAPACITY_WARN_FRACTION: number = 0.9;\n\n/**\n * `retryAfter` (seconds) on a `MaintenancePending` refusal (main-10 G6).\n * The refused write dispatches one bounded fold before it refuses, and\n * that fold finishes within the same invocation: inline before the\n * response, or in the Cloudflare `ctx.waitUntil` continuation right after\n * it. A retry needs only to land after that, so the value is the smallest\n * non-zero `Retry-After` (RFC 9110 §10.2.3 delay-seconds is a whole\n * number). Each retry runs its own fold pass, so a longer backlog drains\n * across retries rather than within one delay. The HTTP client's caps on\n * those retries are `MAINTENANCE_PENDING_CLIENT_MAX_ATTEMPTS` and\n * `MAINTENANCE_PENDING_CLIENT_MAX_WAIT_MILLIS` in\n * `packages/client/src/request-retry.ts`.\n */\nexport const MAINTENANCE_PENDING_RETRY_AFTER_SECONDS: number = 1;\n\n// Declared here (not the nominal server `MaintenanceProfile`) to avoid a server→protocol cycle; keep field-identical to it.\ntype MaintenanceProfileShape = Readonly<{\n gcInterval: number;\n gcMaxMarks: number;\n gcMaxSweeps: number;\n maxFoldEntriesPerPass: number;\n maxFoldBytes: number;\n maxFoldRows: number;\n}>;\n\n/** CF-free profile; the absent-context default. */\nexport const MAINTENANCE_PROFILE_CF_FREE: MaintenanceProfileShape = {\n gcInterval: WRITE_TICK_GC_INTERVAL,\n gcMaxMarks: WRITE_TICK_GC_MAX_MARKS,\n gcMaxSweeps: WRITE_TICK_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: MAINTENANCE_MAX_FOLD_BYTES_DEFAULT,\n maxFoldRows: MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/** Node profile; 10× CF-free per-pass caps, and its own measured snapshot ceilings. */\nexport const MAINTENANCE_PROFILE_NODE: MaintenanceProfileShape = {\n gcInterval: NODE_MAINTENANCE_GC_INTERVAL,\n gcMaxMarks: NODE_MAINTENANCE_GC_MAX_MARKS,\n gcMaxSweeps: NODE_MAINTENANCE_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: NODE_MAINTENANCE_MAX_FOLD_BYTES,\n maxFoldRows: NODE_MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/**\n * CF-paid profile — opt-in via `BAERLY_MAINTENANCE_PROFILE=cf-paid`. A paid\n * isolate keeps the CF-free single-phase shape (one phase per request) but has a\n * 9,000-call request ledger limit ({@link CF_PAID_REQUEST_LIMIT}), so it reuses the\n * `NODE_MAINTENANCE_*` per-pass caps.\n *\n * A profile moves RATE and the DEFER THRESHOLD, never the stored data or the\n * query semantics — that is the equivalence invariant, and it is what\n * `tests/integration/maintenance-profile-equivalence.test.ts` proves: a read\n * folds snapshot + live tail, so HOW MUCH a profile has folded is invisible to\n * a reader. Snapshot ceilings therefore differ per host, sized to each host's\n * real wall (see {@link CF_PAID_MAINTENANCE_MAX_FOLD_BYTES}). Operators can\n * still raise `C` out-of-band with `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`.\n *\n * @see packages/adapter-cloudflare/src/worker.ts\n * @see docs/about/graduation.md\n */\nexport const MAINTENANCE_PROFILE_CF_PAID: MaintenanceProfileShape = {\n gcInterval: NODE_MAINTENANCE_GC_INTERVAL,\n gcMaxMarks: NODE_MAINTENANCE_GC_MAX_MARKS,\n gcMaxSweeps: NODE_MAINTENANCE_GC_MAX_SWEEPS,\n maxFoldEntriesPerPass: NODE_MAINTENANCE_FOLD_ENTRIES_PER_PASS,\n maxFoldBytes: CF_PAID_MAINTENANCE_MAX_FOLD_BYTES,\n maxFoldRows: CF_PAID_MAINTENANCE_MAX_FOLD_ROWS,\n};\n\n/**\n * Rate-limit the defer-warn off SHARED current.json.last_warned_seq (not per-isolate\n * memory — CF recycles isolates). ~once per this many writes.\n *\n * @see packages/protocol/src/coordination/current-json.ts\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_WARN_INTERVAL_WRITES: number = 1000;\n\n/**\n * Rate-limit for the maintenance tick's `tail_hint` advance on every\n * path where no fold published the hint (originally HR-2, the DEFER\n * path). When the fold defers (snapshot over the configured fold ceiling),\n * when `BAERLY_MAINTENANCE_DISABLE` suppresses both phases, or when a\n * tick runs only GC, the compactor never stamps `tail_hint` via its\n * Step-7 fold CAS — so the gap `(true_tail − tail_hint)` would grow\n * without bound and every read would re-walk the whole live tail via\n * `probeTailFrom`. The runner therefore advances `tail_hint` toward the\n * observed tail with a best-effort `current.json` CAS — but only once\n * per this many writes, so it is NOT a per-commit `current.json` write\n * (which is exactly what single-write commit removed).\n *\n * This interval is a floor on the rate, not a licence to publish more\n * than once per tick. A tick publishes `tail_hint` AT MOST ONCE, by\n * whichever party gets there first, because the interval is measured\n * against the tick's in-memory `current.json` — which no CAS writes back,\n * so a repeat call still reads as due and would rewrite identical bytes.\n * Exactly two parties can publish: the runner's own refresh, and a fold\n * that returned `written` (Step-7 stamped `max(stored, discoveredTail)`\n * with `discoveredTail >= observedTail`). GC is not one of them — a GC\n * tick takes the ordinary rate-limited refresh like any other, which is\n * what makes the bound below unconditional rather than cadence-dependent.\n *\n * Sized at 128: it bounds a deferring collection's worst-case\n * read-walk to ≤128 forward GETs (≈one extra read-page sweep — a\n * negligible per-read latency cost), keeps the gap two-to-three orders\n * of magnitude below {@link LOG_FORWARD_PROBE_CAP} (so the cap-throw is a\n * pure runaway guard, never reached in normal operation), and holds the\n * hint-advance CAS rate under ~1% of the commit rate (negligible\n * Class-A cost, amortized). Smaller would tighten the read-walk at a\n * higher CAS rate; larger would loosen it — 128 is the modest middle.\n *\n * @see packages/server/src/maintenance.ts\n */\nexport const MAINTENANCE_TAIL_HINT_REFRESH_WRITES: number = 128;\n\n/**\n * Stable seed for `CurrentJson.snapshot === null` when building the\n * opaque `_meta.manifest_pointer` cursor emitted on read responses.\n * The literal no longer appears by itself on the wire; it is folded\n * into the server-side digest so the cursor never exposes physical\n * snapshot keys.\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 applyMergePatch} or\n * {@link coalesceMergePatches}: 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 (applyMergePatch, coalesceMergePatches)\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 * Pre-provisioned, first-attempt Class A commit floor, whatever indexes the\n * collection declares.\n *\n * The floor is the sole committing `log/<seq>` create\n * (`If-None-Match: \"*\"`). It is not a ceiling: provisioning,\n * contention/retries, and in-band maintenance can add Class A operations.\n *\n * @see tests/integration/http-cost-shape.test.ts\n * @see packages/server/src/writer.test.ts\n * @see tests/integration/write-amp.test.ts\n */\nexport const COMMIT_CLASS_A_FLOOR: number = 1;\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/**\n * Stands in for \"this manifest has no `generation`\". Both spellings of\n * that state — a `current.json` predating the field, and a bare-LSN\n * cursor minted before this build — decode to this value, so an\n * ordinary string comparison handles them without a fail-open branch.\n * See the truth table in `docs/spec/sync-protocol.md`.\n *\n * `\"-\"` is safe as the sentinel because a real generation is a minted\n * lowercase-hex nonce (`mintGeneration`), and hex contains no `-`. So\n * the sentinel can never collide with a value a manifest actually\n * carries, in either the `/v1/since` cursor codec or the GC candidate\n * fence.\n *\n * Sited HERE rather than next to the cursor codec that first needed\n * it: `constants.ts` is a zero-import leaf, and `runGc` imports this\n * sentinel. Re-exported from `cursor.ts` so existing importers are\n * unaffected. Importing it from `cursor.ts` instead would drag\n * `parseCursor` + `formatCursor` into the `index.js` and\n * `maintenance.js` closures — every consumer paying for a `/v1/since`\n * codec to get one `\"-\"`.\n */\nexport const NO_GENERATION = \"-\";\n\n/**\n * Longest inbound `x-request-id` the adapters carry onto the canonical\n * log line; a longer one is replaced with a generated id. 128 holds\n * every common id format with room to spare (UUID 36, W3C\n * `traceparent` 55, an X-Ray `Root=…;Parent=…;Sampled=…` header ~80)\n * while keeping a caller from inflating every log line it touches.\n */\nexport const MAX_REQUEST_ID_LENGTH = 128;\n","// Deployment detection shared by the in-memory storage guard and the\n// Node resolveStorageFromEnv resolver. Pure (env passed in) so it stays\n// Workerd-loadable. Markers are vars each platform sets unconditionally:\n// Cloud Run, Heroku, Kubernetes, ECS, Railway, Render, Fly.\n//\n// The list is deliberately conservative: every marker here is set ONLY by\n// the platform at runtime, never by that platform's local dev emulator, so\n// detection cannot false-positive a developer's machine. Serverless markers\n// like VERCEL / NETLIFY / AWS_LAMBDA_FUNCTION_NAME are intentionally omitted\n// — their local emulators (`vercel dev`, `netlify dev`, SAM local) set the\n// same vars, so adding them would break local development. Before adding a\n// marker, confirm it is never set by that platform's dev tooling. An\n// unmarked host should set NODE_ENV=production to opt into the guard.\nexport const PAAS_MARKERS = [\n \"RAILWAY_ENVIRONMENT\",\n \"RENDER\",\n \"FLY_APP_NAME\",\n \"K_SERVICE\",\n \"DYNO\",\n \"KUBERNETES_SERVICE_HOST\",\n \"ECS_CONTAINER_METADATA_URI_V4\",\n] as const;\n\n/**\n * True when `env` looks like a deployed environment: `NODE_ENV=production`\n * or any {@link PAAS_MARKERS} set to a non-empty value. Decides whether a\n * non-durable store (in-memory, local-fs) should fail loud instead of\n * silently serving a production workload. A CI runner (`CI` set to a\n * non-empty, non-`false` value) is never treated as deployed, so PaaS\n * markers from an in-cluster CI agent do not trip it.\n */\nexport const isDeployedEnv = (env: Record<string, string | undefined>): boolean => {\n // A CI runner is never a deployment — even in a k8s pod that sets a PaaS\n // marker (e.g. KUBERNETES_SERVICE_HOST) — so it must not trip the markers.\n const inCi = (env[\"CI\"] ?? \"\") !== \"\" && env[\"CI\"] !== \"false\";\n return (\n env[\"NODE_ENV\"] === \"production\" || (!inCi && PAAS_MARKERS.some((m) => (env[m] ?? \"\") !== \"\"))\n );\n};\n","/**\n * SHA-256 of `bytes` as a 64-char lowercase hex string.\n *\n * Zero-import leaf module on purpose: co-locating this with heavier\n * runtime (snapshot-hash.ts / hashing.ts) would drag that module into\n * every consumer's bundle closure. Callers that want a truncated form\n * (e.g. {@link versionFromContent}'s content keys) slice the return.\n */\nexport const sha256Hex = async (bytes: Uint8Array): Promise<string> => {\n // tsc narrows `Uint8Array` to `Uint8Array<ArrayBufferLike>`, which\n // `crypto.subtle.digest` rejects (wants `ArrayBufferView<ArrayBuffer>`;\n // microsoft/TypeScript#61375). A view over an `ArrayBuffer` is passed\n // through and hashes only its own bytes, even at an offset; digest\n // copies its input synchronously. A `SharedArrayBuffer`-backed view is\n // not a valid `BufferSource`, so copy that case.\n let view: Uint8Array<ArrayBuffer>;\n if (bytes.buffer instanceof ArrayBuffer) {\n // Narrowing `bytes.buffer` does not narrow `bytes`; the check above is the proof.\n view = bytes as Uint8Array<ArrayBuffer>;\n } else {\n view = new Uint8Array(bytes.byteLength);\n view.set(bytes);\n }\n const digest = await crypto.subtle.digest(\"SHA-256\", view);\n return new Uint8Array(digest).toHex();\n};\n","import { BaerlyError } from \"../errors.ts\";\n\n/**\n * Validate a raw {@link Storage} object key against the portable baerly key\n * grammar before it is used to address an object. A key MUST be non-empty\n * and `/`-delimited, with **no path segment equal to `.` or `..`**.\n *\n * The dot-segment rule is not a vendor quirk — it is a *client-side*\n * universal: RFC 3986 §5.2.4 \"remove dot segments\" is mandatory for every\n * conformant URL parser, so `<endpoint>/<bucket>/.` normalizes to\n * `<endpoint>/<bucket>/` and `<endpoint>/<bucket>/..` escapes the bucket\n * entirely — *before* the request is signed or sent, in TypeScript, Go,\n * Rust, Python, or any language a `Storage` port is written in. Such a key\n * cannot be addressed over the S3/R2 HTTP API regardless of backend; a bare\n * `.` PUT surfaces as a confusing bucket-root 403 rather than a clear\n * rejection. The kernel never emits such keys (caller-controlled segments\n * are already screened by `assertPathSegment` one layer up), so this is the\n * boundary guard that makes every adapter reject them *identically* and\n * gives ports a single, testable contract.\n *\n * Thrown as `BaerlyError{code:\"InvalidConfig\"}` to match the sibling\n * key/segment guards (`assertKeyWithinLimit`, `assertPathSegment`). The\n * full-key 1024-byte ceiling is enforced separately on the write path\n * (`assertKeyWithinLimit`), where multi-segment keys are assembled.\n *\n * @see docs/spec/storage-compatibility.md — \"Key namespace\"\n */\nexport function assertValidStorageKey(key: string): void {\n if (key.length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"storage key must be a non-empty string\");\n }\n for (const segment of key.split(\"/\")) {\n if (segment === \".\" || segment === \"..\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `storage key may not contain a \".\" or \"..\" path segment — RFC 3986 dot-segment ` +\n `removal makes it unaddressable over the S3/R2 HTTP API: ${JSON.stringify(key)}`,\n );\n }\n }\n}\n","import { isDeployedEnv } from \"../env.ts\";\nimport { BaerlyError } from \"../errors.ts\";\nimport { assertValidStorageKey } from \"./key.ts\";\nimport type {\n Storage,\n StorageGetOptions,\n StorageGetResult,\n StorageListEntry,\n StoragePutOptions,\n StoragePutResult,\n} from \"./types.ts\";\n\ninterface StoredObject {\n body: Uint8Array;\n etag: string;\n contentType?: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\nconst EPHEMERAL_ENV_OPT_IN = \"BAERLY_ALLOW_EPHEMERAL_STORAGE\";\n\n// Read process env without a `node:` import so protocol stays Workerd-\n// loadable. With `nodejs_compat`, Workerd populates `process.env` from text\n// bindings, so the deployed-environment guard also applies on Workers.\nconst readProcessEnv = (): Record<string, string | undefined> =>\n (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ?? {};\n\nlet warnedEphemeralInDeployment = false;\n\n// Fail closed when in-memory storage would silently back a deployed\n// workload (writes \"succeed\" into RAM, vanish on restart). No-op in\n// dev/test; bypass in a deployment only via an explicit acknowledgement.\nconst assertEphemeralAllowed = (explicitOptIn: boolean): void => {\n const env = readProcessEnv();\n if (!isDeployedEnv(env)) {\n return;\n }\n if (!explicitOptIn && env[EPHEMERAL_ENV_OPT_IN] !== \"true\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"Refusing to use in-memory storage in a deployed environment — all data is lost on restart. \" +\n \"MemoryStorage is for tests/local dev only; configure a durable bucket (AWS S3 / Cloudflare R2). \" +\n `To intentionally opt in: new MemoryStorage({ ephemeral: true }) or ${EPHEMERAL_ENV_OPT_IN}=true.`,\n );\n }\n if (!warnedEphemeralInDeployment) {\n warnedEphemeralInDeployment = true;\n console.warn(\n \"[baerly] in-memory storage in a deployed environment — ALL DATA IS LOST ON RESTART.\",\n );\n }\n};\n\n/** Options for {@link MemoryStorage}. */\nexport interface MemoryStorageOptions {\n /**\n * Acknowledge the store is intentionally ephemeral — required to\n * construct in a detected deployment ({@link isDeployedEnv}); ignored in\n * dev/test. Env equivalent: `BAERLY_ALLOW_EPHEMERAL_STORAGE=true`.\n */\n ephemeral?: boolean;\n}\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and\n * R2 use for `list`. JavaScript's default string sort compares UTF-16\n * code units, which diverges from UTF-8 byte order for supplementary-\n * plane characters (e.g. emoji sort before high-BMP characters under\n * UTF-16 but after them in UTF-8). Using this keeps the in-memory\n * reference backend faithful to the real adapters. (All kernel keys\n * are ASCII base-32, where the two orders coincide — this only\n * matters for adversarial / non-ASCII keys.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * In-memory `Storage`. The randomized property test runs against\n * this; it must be deterministic — no clocks beyond the caller's,\n * no randomness, no I/O.\n *\n * ETags are a monotonically increasing hex counter formatted in the\n * `\"<hex>\"` shape S3 returns (the surrounding double-quotes are part\n * of the ETag header value). Keys are stored verbatim.\n *\n * **Test-confidence caveat:** every method resolves on the microtask\n * queue with no real concurrency, so `put` reads `existing` and writes\n * back with no interleaving. MemoryStorage therefore CANNOT exercise the\n * compare-and-swap race the writer-fence model depends on — two writers\n * contending on one `current.json` always serialize here, so a green run\n * is necessary but not sufficient. That race is covered only by the\n * randomized integration tests against real S3 / Minio\n * (`tests/integration/randomized.test.ts`, `node-minio` variant).\n * Relatedly, `serverDate` returns the local clock, not an independent\n * server clock (see the `put` return below).\n */\nexport class MemoryStorage implements Storage {\n readonly #objects = new Map<string, StoredObject>();\n #etagCounter = 0;\n\n constructor(opts?: MemoryStorageOptions) {\n assertEphemeralAllowed(opts?.ephemeral === true);\n }\n\n #nextEtag(): string {\n this.#etagCounter += 1;\n return `\"${this.#etagCounter.toString(16)}\"`;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n if (stored === undefined) {\n return null;\n }\n return { body: stored.body, etag: stored.etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const existing = this.#objects.get(key);\n\n if (opts?.ifNoneMatch === \"*\" && existing !== undefined) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n if (opts?.ifMatch !== undefined) {\n if (existing === undefined) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (existing.etag !== opts.ifMatch) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${existing.etag})`,\n );\n }\n }\n\n const etag = this.#nextEtag();\n this.#objects.set(key, {\n body,\n etag,\n // Stryker disable next-line ObjectLiteral,ConditionalExpression: contentType is stored in the internal StoredObject but never returned by get() — the Storage interface has no contentType on StorageGetResult, so any mutation of this spread is observable-equivalent\n ...(opts?.contentType !== undefined && { contentType: opts.contentType }),\n });\n // `serverDate` is intentionally returned — the kernel's adaptive\n // clock-skew loop consumes the write-time server clock. `list()`\n // needs no such clock: `StorageListEntry` is `key` + `etag` only.\n return { etag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n this.#objects.delete(key);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n const sorted = [...this.#objects.keys()]\n .filter((k) => k.startsWith(prefix) && compareKeysUtf8(k, startAfter) > 0)\n .toSorted(compareKeysUtf8);\n let yielded = 0;\n for (const key of sorted) {\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n const stored = this.#objects.get(key);\n // Stryker disable next-line ConditionalExpression,BlockStatement: unreachable guard — keys come from Map.keys() so the corresponding value is always present; this branch exists only to satisfy noUncheckedIndexedAccess\n if (stored === undefined) {\n continue;\n }\n yield { key, etag: stored.etag };\n yielded += 1;\n }\n }\n\n /**\n * Test-only: drop all objects.\n * @internal\n */\n _clear(): void {\n this.#objects.clear();\n this.#etagCounter = 0;\n }\n}\n\n// Process-singleton MemoryStorage map keyed by bucket. Tests that need\n// multiple `Db` / `Writer` instances to see each other's writes\n// against an in-memory backend reach for this via\n// {@link getOrCreateMemoryStorageForBucket}; {@link resetMemoryStorage}\n// drops every bucket between test cases.\nconst sharedPerBucket = new Map<string, MemoryStorage>();\n\n/**\n * Test isolation: drop every bucket's contents from the shared\n * memory storage used by {@link getOrCreateMemoryStorageForBucket}.\n * Direct `MemoryStorage` instances built via `new MemoryStorage()`\n * are unaffected — those are isolated by construction.\n */\nexport const resetMemoryStorage = (): void => {\n sharedPerBucket.clear();\n};\n\n/**\n * Get the process-singleton {@link MemoryStorage} for the named\n * bucket, creating one on first access. Use this when constructing\n * a `Storage` directly so multiple consumers in the same process\n * see each other's writes for the same bucket name.\n */\nexport const getOrCreateMemoryStorageForBucket = (bucket: string): MemoryStorage => {\n return sharedPerBucket.getOrInsertComputed(bucket, () => new MemoryStorage());\n};\n","import { COUNT_BIT_WIDTH } from \"./constants.ts\";\n\n// Re-exported so existing `./types.ts` importers keep working; the\n// implementations live in `./uuid.ts` so a consumer that needs only\n// `uuidv7` (the client) does not pull in this module's base-32 helpers.\nexport { uuidv7 } from \"./uuid.ts\";\n\ndeclare const brand: unique symbol;\ntype Brand<B> = { [brand]: B };\n\n/**\n * Nominal-typing helper. `Branded<string, \"UUID\">` is a `string` at\n * runtime but the type system rejects mixing it with a plain `string` or\n * a string branded as something else. Used to prevent confusion bugs at\n * protocol boundaries (UUIDs vs. legacy content versions are both\n * strings, but using the wrong one corrupts the per-collection log).\n *\n * Construct branded values via the helpers in this file (e.g. {@link uuid})\n * or with a tagged cast at a single, deliberate boundary — never `as string`\n * to widen one back. See `docs/contributing/conventions/src.md`.\n */\nexport type Branded<T, B> = T & Brand<B>;\n\n/**\n * A UUID minted by this client. {@link uuid} returns v4 values used for\n * writer-session entropy and storage probe keys; {@link uuidv7} returns\n * time-sortable v7 values for caller-facing identifiers. Content side\n * objects use the separate legacy {@link ContentVersionId} hash brand.\n */\nexport type UUID = Branded<string, \"UUID\">;\n\n/**\n * Legacy content-key digest: lowercase SHA-256 hex truncated to 32\n * characters (128 bits), minted by `versionFromContent`. v0.6.0 writers\n * used it to name `content/<hash>.json` side objects; the current kernel\n * retains the brand only for legacy inspection or direct-bucket tooling.\n * Current writers do not mint content side objects, and current GC never\n * touches `content/`.\n */\nexport type ContentVersionId = Branded<string, \"ContentVersionId\">;\n\n/**\n * Mint a fresh {@link UUID}. The cast lives here so callers don't sprinkle\n * `<UUID>crypto.randomUUID()` throughout the codebase.\n */\nexport const uuid = (): UUID => crypto.randomUUID() as UUID;\n\nconst UUID_V7_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;\n\n/**\n * True iff `s` has exactly the shape {@link uuidv7} produces: canonical\n * lowercase 8-4-4-4-12 hex, version nibble `7`, variant nibble in\n * `[89ab]`.\n */\nexport const isUuidV7 = (s: string): s is UUID => UUID_V7_RE.test(s);\n\n/**\n * Mint the trailing seq segment of an LSN (`<base32-time>_<sess>_<seq>`).\n * Uses `COUNT_BIT_WIDTH` (see `packages/protocol/src/constants.ts`) to\n * produce an 11-char descending base-32 string with a domain of\n * 0 .. `Number.MAX_SAFE_INTEGER` (2^53 − 1).\n *\n * Used together with {@link timestamp} (the descending base-32\n * encoding of millis-since-epoch). See {@link uint2strDesc} for the\n * lex-reversal property both rely on.\n */\nexport const countKey = (number: number): string => uint2strDesc(number, COUNT_BIT_WIDTH);\n\nexport const uint2str = (num: number, bits: number) => {\n const maxBase32Length = Math.ceil(bits / 5); // Change from 4 to 5 because log2(32) is roughly 5.\n const base32Representation = num.toString(32);\n return base32Representation.padStart(maxBase32Length, \"0\");\n};\n\nexport const str2uint = (str: string) => {\n return parseInt(str, 32); // Parse the string as base 32.\n};\n\n/**\n * Lex-reversed base-32 encoder for an unsigned integer in `[0, 2^bits)`.\n * Pads to `Math.ceil(bits/5)` chars so all values in the domain compare\n * lex against each other.\n *\n * **Order-reversal property:** for any pair of integers `a < b` (with\n * `a, b ∈ [0, 2^bits)`), `uint2strDesc(a, bits) > uint2strDesc(b, bits)`\n * lexicographically. Composed into an LSN of shape\n * `<base32-time>_<session>_<seq>` (where both `<base32-time>` and\n * `<seq>` use this encoder), a forward `Storage.list(prefix)`\n * returns log entries in reverse-causal order — newer entries first.\n *\n * This is the structural property the read path leans on:\n * `ListObjectsV2` is forward-only on S3, but the descending encoding\n * makes \"fetch the K newest entries\" a single bounded LIST with\n * `maxKeys=K` instead of a full-population LIST + in-memory reverse.\n *\n * Behaviourally verified across randomized populations in\n * `packages/protocol/src/lsn-reverse-list.test.ts`. Quantified\n * bytes-listed reduction is in\n * `docs/spec/attachments/lsn-reverse-walk-baseline.json`\n * (run `pnpm bench:lsn-reverse-walk` to reproduce). Spec rationale:\n * `docs/spec/sync-protocol.md` §\"LSNs, wall clocks, and downstream\n * consumers\".\n */\nexport const uint2strDesc = (num: number, bits: number): string => {\n const maxValue = Math.pow(2, bits) - 1;\n return uint2str(maxValue - num, bits);\n};\n\nexport const str2uintDesc = (str: string, bits: number): number => {\n const maxValue = Math.pow(2, bits) - 1;\n const num = parseInt(str, 32); // Convert base32 string to number\n return maxValue - num;\n};\n","import { TIMESTAMP_BIT_WIDTH } from \"./constants.ts\";\nimport { BaerlyError } from \"./errors.ts\";\nimport { uint2strDesc } from \"./types.ts\";\n\n/**\n * Encode an epoch-millis instant as a lexicographically-DEScending\n * base-32 key (newer sorts first). The load-bearing LSN ordering\n * primitive — see {@link uint2strDesc}.\n *\n * `epoch` is REQUIRED and validated. There is no default: an argless\n * call used to encode `0`, which descending-sorts as the most-ancient\n * instant and would silently invert ordering. A non-finite, negative,\n * or out-of-range `epoch` (e.g. a broken `Date.now()` returning `NaN`)\n * would corrupt the key silently rather than fail loud, so it throws\n * `Internal` instead — this is an invariant violation, not caller config\n * (the only legitimate argument is `Date.now()`).\n */\nexport const timestamp = (epoch: number): string => {\n if (!Number.isInteger(epoch) || epoch < 0 || epoch >= 2 ** TIMESTAMP_BIT_WIDTH) {\n throw new BaerlyError(\n \"Internal\",\n `timestamp(): epoch must be a non-negative integer < 2^${TIMESTAMP_BIT_WIDTH} (got ${epoch})`,\n );\n }\n return uint2strDesc(epoch, TIMESTAMP_BIT_WIDTH);\n};\n\n/**\n * Delay for `ms` milliseconds, with optional cancellation. If\n * `signal` aborts before the delay elapses, the returned promise\n * rejects with `signal.reason`. `retryStorageCall` uses it for its\n * backoff without a signal, so a backoff it has started always runs\n * to completion.\n */\nexport const delay = (ms: number, signal?: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n // Stryker disable next-line BooleanLiteral,ObjectLiteral: `{ once: true }` removes the\n // listener after the first fire. AbortController fires `abort` only once per signal, so\n // `once: false` / `{}` produce identical observable behaviour — the listener stays attached\n // to an already-fired signal, but calling reject on a settled Promise is a no-op. The\n // BooleanLiteral (once:false) and ObjectLiteral ({}) mutations are genuine equivalences.\n { once: true },\n );\n });\n","import { CF_CACHE_API_MAX_CALLS } from \"../constants.ts\";\nimport { BaerlyError } from \"../errors.ts\";\n\n/**\n * A request pool on a {@link RequestLedger}. `internal` is charged for\n * every storage call. `external` is charged as well for a call that\n * leaves through `fetch` (S3 over HTTP, GCS). The legacy cache-accounting\n * seam also charges both pools; the production Worker never calls it.\n * Charging an external call to both pools is safe whether\n * the host keeps one combined counter or two separate ones.\n */\nexport type RequestPool = \"internal\" | \"external\";\n\n/**\n * Capacity a caller holds on a {@link RequestLedger} for calls it is about\n * to issue (from {@link RequestLedger.hold}). Calls made with the hold\n * active (passed to {@link RequestLedger.acquire}; `retryStorageCall` passes\n * {@link currentRequestHold}) draw on it first; every other call in the\n * invocation sees the ledger's room net of it, so concurrent work cannot\n * spend it. Release it once the holder's calls are done; the unspent part\n * returns to the ledger.\n */\nexport class RequestHold {\n readonly #ledger: RequestLedger;\n #left: number;\n\n /** @internal Created by {@link RequestLedger.hold}. */\n constructor(ledger: RequestLedger, amount: number) {\n this.#ledger = ledger;\n this.#left = amount;\n }\n\n /** Held requests not yet spent. */\n get left(): number {\n return this.#left;\n }\n\n /** @internal `true` when this hold is on `ledger` and has room left. */\n covers(ledger: RequestLedger): boolean {\n return this.#ledger === ledger && this.#left > 0;\n }\n\n /** @internal Spend one held request. */\n spend(): void {\n this.#left -= 1;\n }\n\n /** Return the unspent part to the ledger. Idempotent. */\n release(): void {\n const left = this.#left;\n this.#left = 0;\n this.#ledger.unhold(left);\n }\n}\n\n/** Per-pool request limits. `Infinity` counts without ever refusing. */\nexport interface RequestLedgerLimits {\n readonly internal: number;\n readonly external: number;\n}\n\n/** Requests charged so far, per pool, plus Cache API calls (also in `external`). */\nexport interface RequestLedgerCharges {\n readonly internal: number;\n readonly external: number;\n readonly cache: number;\n}\n\n/** Limits that count every request and never refuse one (Node, and any host without a per-invocation cap). */\nexport const UNLIMITED_REQUESTS: RequestLedgerLimits = { internal: Infinity, external: Infinity };\n\n/**\n * Per-invocation storage request budget. The adapter creates one per\n * invocation (an HTTP request, a cron tick) and the server carries it on\n * the observability context, so everything that invocation runs,\n * `ctx.waitUntil` work included, charges the same ledger.\n *\n * `retryStorageCall` charges one request before every attempt, so adapter\n * retries and `list` pages are charged as they are issued. A request that\n * does not fit is refused before it is sent: {@link acquire} throws\n * `CapacityExceeded` whose cause carries `refused: true`, which ends the\n * retry loop at once and keeps `notApplied` on a create. Charging is\n * synchronous, so a `Promise.all` fan-out can never issue past the limit.\n *\n * Calls outside `retryStorageCall` (the verifier's JWKS fetch, GCS\n * signing, app code in the same Worker) are not charged; the limits keep\n * a margin below the platform cap for them.\n */\nexport class RequestLedger {\n readonly limits: RequestLedgerLimits;\n #internal = 0;\n #external = 0;\n #cache = 0;\n // The strictest pool an `acquire` has charged: storage calls run through\n // one adapter per invocation, so this is the pool they draw on.\n #storagePool: RequestPool | undefined;\n // Unspent requests of every active `RequestHold`.\n #held = 0;\n\n constructor(limits: RequestLedgerLimits = UNLIMITED_REQUESTS) {\n this.limits = limits;\n }\n\n /** Requests charged so far. */\n get charged(): RequestLedgerCharges {\n return { internal: this.#internal, external: this.#external, cache: this.#cache };\n }\n\n /**\n * Requests still allowed on `pool` to a caller without a hold: the room\n * left, net of active holds. An external request also needs room in\n * `internal`.\n */\n remaining(pool: RequestPool): number {\n return this.#room(pool) - this.#held;\n }\n\n /** Requests held by active holds, not yet spent. */\n get held(): number {\n return this.#held;\n }\n\n /**\n * Hold `amount` requests for the caller's next calls; see\n * {@link RequestHold}. The caller checks {@link storageRemaining} first:\n * a hold never refuses, and one larger than the room left only blocks\n * other callers sooner.\n */\n hold(amount: number): RequestHold {\n this.#held += amount;\n return new RequestHold(this, amount);\n }\n\n /** @internal Return `amount` unspent held requests (`RequestHold.release`). */\n unhold(amount: number): void {\n this.#held -= amount;\n }\n\n #room(pool: RequestPool): number {\n const internal = this.limits.internal - this.#internal;\n return pool === \"internal\"\n ? internal\n : Math.min(internal, this.limits.external - this.#external);\n }\n\n /**\n * Requests still allowed, net of active holds, on the pool this\n * invocation's storage calls draw on: `external` once any storage call charged it, else `internal`\n * once one charged that, else `Infinity` (no storage call has been\n * charged, so the storage in use does not charge this ledger). A caller\n * that must keep room for its next calls, such as the writer's\n * commit-resolution reserve, checks this after its first storage call.\n * Cache API calls do not count as storage calls here.\n */\n storageRemaining(): number {\n return this.#storagePool === undefined ? Infinity : this.remaining(this.#storagePool);\n }\n\n /**\n * Charge one request to `pool`, or refuse it before it is sent. With an\n * active `hold` on this ledger the request draws on it (it needs only\n * room left in `pool`); otherwise it needs room net of active holds.\n *\n * @throws BaerlyError code=\"CapacityExceeded\", cause `{ refused: true }`,\n * when `pool` has no room. Nothing is charged.\n */\n acquire(pool: RequestPool, hold?: RequestHold): void {\n if (this.#storagePool !== \"external\") {\n this.#storagePool = pool;\n }\n const held = hold?.covers(this) === true;\n if ((held ? this.#room(pool) : this.remaining(pool)) < 1) {\n const limit = pool === \"internal\" ? this.limits.internal : this.limits.external;\n throw new BaerlyError(\n \"CapacityExceeded\",\n `this request has issued its limit of ${String(limit)} ${pool} storage calls, so the next call was not sent; the work this request needs does not fit in one request on this host`,\n // The HTTP envelope fills in the code's canonical resolution.\n { cause: { refused: true, pool, limit } },\n );\n }\n if (held) {\n hold!.spend();\n this.#held -= 1;\n }\n this.#charge(pool);\n }\n\n /**\n * Legacy internal accounting seam; no production Worker caller.\n * Charge one optional Cache API call when it fits: room in `external`\n * and fewer than {@link CF_CACHE_API_MAX_CALLS} cache calls so far.\n * Returns `false`, charging nothing, when it does not; the caller skips\n * the cache call. With `required`, the call is charged whether or not\n * it fits and always returns `true`. Tests use this to model an\n * unrefusable call consuming the platform margin.\n */\n chargeCacheCall(required = false): boolean {\n if (!required && (this.#cache >= CF_CACHE_API_MAX_CALLS || this.remaining(\"external\") < 1)) {\n return false;\n }\n this.#cache += 1;\n this.#charge(\"external\");\n return true;\n }\n\n #charge(pool: RequestPool): void {\n this.#internal += 1;\n if (pool === \"external\") {\n this.#external += 1;\n }\n }\n}\n\nlet resolveLedger: () => RequestLedger | undefined = () => undefined;\n\n/**\n * Register how {@link currentRequestLedger} finds the active ledger. The\n * server registers its observability context here, so adapters, which\n * import only this package, charge the ledger of the invocation they run\n * in. One resolver per process; a later call replaces it.\n */\nexport const setRequestLedgerResolver = (resolver: () => RequestLedger | undefined): void => {\n resolveLedger = resolver;\n};\n\n/** The ledger of the active invocation, or `undefined` outside one (nothing is charged). */\nexport const currentRequestLedger = (): RequestLedger | undefined => resolveLedger();\n\nlet resolveHold: () => RequestHold | undefined = () => undefined;\n\n/**\n * Register how {@link currentRequestHold} finds the active hold, as\n * {@link setRequestLedgerResolver} does for the ledger. The server scopes a\n * hold to the async context of the work it covers, so work started outside\n * that context (a `ctx.waitUntil` tick) never draws on it.\n */\nexport const setRequestHoldResolver = (resolver: () => RequestHold | undefined): void => {\n resolveHold = resolver;\n};\n\n/** The hold active in this async context, if any; `retryStorageCall` charges against it. */\nexport const currentRequestHold = (): RequestHold | undefined => resolveHold();\n","import {\n STORAGE_RETRY_MAX_ATTEMPTS,\n STORAGE_RETRY_MAX_DELAY_MILLIS,\n STORAGE_RETRY_THROTTLE_BASE_MILLIS,\n STORAGE_RETRY_TRANSIENT_BASE_MILLIS,\n} from \"../constants.ts\";\nimport { BaerlyError, isWriteConflict, type BaerlyErrorCode } from \"../errors.ts\";\nimport { delay } from \"../time.ts\";\nimport { currentRequestHold, currentRequestLedger, type RequestPool } from \"./ledger.ts\";\n\n/**\n * Permanent {@link BaerlyError} codes that end `retryStorageCall` at\n * once. These represent caller- or environment-level faults where\n * retrying cannot succeed: `AccessDenied` (403 — credentials/policy),\n * `InvalidConfig` (bad bucket / unsupported credential type),\n * `InvalidResponse` (server returned unparseable data), and\n * `WriteConflict` (a precondition was rejected). `NetworkError` is\n * intentionally absent — it covers transient transport faults and stays\n * retryable.\n *\n * Storage-layer set, distinct from `RETRIABLE_CODES` in `errors.ts`. A\n * blind re-PUT of the same request re-loses a rejected precondition, so\n * this layer never resends it. `WriteConflict` is still retriable for the\n * logical caller: it re-reads and issues a new request, which is what\n * `retriable` means.\n */\nexport const PERMANENT_STORAGE_ERROR_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>(\n [\"AccessDenied\", \"InvalidConfig\", \"InvalidResponse\", \"WriteConflict\"],\n);\n\n/** Options for {@link retryStorageCall}. */\nexport interface StorageRetryOptions {\n /**\n * Retries after the first attempt: a non-negative integer, else the\n * call rejects with `InvalidConfig` before any attempt. Default\n * `STORAGE_RETRY_MAX_ATTEMPTS - 1`; `0` makes exactly one attempt.\n */\n readonly retries?: number;\n /**\n * Backoff base override in ms, applied to every failure class. Omit\n * for the default policy: `STORAGE_RETRY_TRANSIENT_BASE_MILLIS` after\n * a transient failure, `STORAGE_RETRY_THROTTLE_BASE_MILLIS` after a\n * throttle.\n */\n readonly backoffMs?: number;\n /**\n * Set for an `If-None-Match: \"*\"` create. An attempt that failed\n * transiently may still have landed, so a later permanent rejection\n * other than `WriteConflict` (for example a 403) cannot prove the\n * create is not durable; it is reported as `NetworkError` carrying the original\n * error as its cause, per the `Storage.put` contract. When every\n * attempt was throttled (`cause.throttled`) or refused\n * (`cause.refused`, which also ends the loop), the final `NetworkError`'s\n * cause carries `notApplied: true`, unless a throttle's cause carries\n * `mayHaveApplied: true` because the adapter cannot prove its outcome.\n */\n readonly conditionalCreate?: boolean;\n /**\n * Set for an `If-Match` PUT (a compare-and-swap). It gets exactly one\n * attempt, whatever `retries` says: if an attempt lands but its reply is\n * lost or comes back as a 5xx, a resend meets the request's own write as\n * a 412 and reports a false `WriteConflict`. Every in-tree CAS caller\n * treats a failure as \"skip; the next pass re-reads\", so the failure goes\n * straight to it. Adapters set this from `StoragePutOptions.ifMatch`.\n */\n readonly compareAndSwap?: boolean;\n /**\n * The {@link RequestPool} each attempt is charged to on the active\n * invocation's request ledger. `\"internal\"` for a call that stays\n * inside the host (the R2 binding); `\"external\"`, the default, for one\n * that leaves through `fetch`.\n */\n readonly pool?: RequestPool;\n /**\n * The caller's `AbortSignal`. Once it has aborted, whatever the reason,\n * no further attempt is signed, backed off or sent: an attempt that\n * fails after the abort ends the loop, and a backoff the abort lands in\n * ends with `signal.reason`, subject to conditional-create uncertainty\n * handling. A failure that is not a {@link BaerlyError}\n * (the adapter's rethrown abort reason) surfaces as is; a `BaerlyError`\n * goes through the final-attempt path, so a conditional create keeps\n * its unknown outcome.\n */\n readonly signal?: AbortSignal;\n /** Jitter source in `[0, 1)`. Test seam; defaults to `Math.random`. */\n readonly random?: () => number;\n /** Backoff sleep. Test seam; defaults to `delay`. */\n readonly sleep?: (ms: number) => Promise<void>;\n}\n\n/** `true` when an attempt uses the throttle backoff. */\nconst isThrottled = (e: unknown): boolean =>\n e instanceof BaerlyError && (e.cause as { throttled?: boolean } | undefined)?.throttled === true;\n\n/**\n * `true` when an attempt was refused before it was issued and a resend\n * in the same invocation is refused too (the Workers subrequest limit).\n * This proves the attempt was not applied and ends the loop at once.\n */\nconst isRefused = (e: unknown): boolean =>\n e instanceof BaerlyError && (e.cause as { refused?: boolean } | undefined)?.refused === true;\n\n/**\n * `true` for an `AbortError`: a cancellation raised by a call that did\n * not pass its signal in {@link StorageRetryOptions.signal}. A resend\n * would fail the same way, so the loop ends and the error surfaces as is,\n * as the other adapters raise it. Matched on `name` like the writer's\n * predicate: workerd and undici reject with different `DOMException`\n * classes. A passed signal covers every abort reason, not only this name.\n */\nconst isAbortError = (e: unknown): boolean =>\n typeof e === \"object\" && e !== null && \"name\" in e && e.name === \"AbortError\";\n\nconst retryAfterMillis = (e: unknown): number | undefined => {\n if (!(e instanceof BaerlyError)) {\n return undefined;\n }\n const seconds = (e.cause as { retryAfterSeconds?: number } | undefined)?.retryAfterSeconds;\n return seconds === undefined ? undefined : seconds * 1000;\n};\n\n/**\n * The wait before retry `retryIndex` (0-based) after `error`.\n *\n * A server `Retry-After` hint (`cause.retryAfterSeconds`) wins, clamped\n * to `STORAGE_RETRY_MAX_DELAY_MILLIS`. Otherwise full jitter:\n * `random() * min(cap, base * 2^retryIndex)`, with the throttle base for\n * an error whose cause carries `throttled: true` and the transient base\n * for everything else, unless `backoffMs` overrides both.\n */\nexport const storageRetryDelayMillis = (\n error: unknown,\n retryIndex: number,\n opts: Pick<StorageRetryOptions, \"backoffMs\" | \"random\"> = {},\n): number => {\n const hintMs = retryAfterMillis(error);\n if (hintMs !== undefined) {\n return Math.min(hintMs, STORAGE_RETRY_MAX_DELAY_MILLIS);\n }\n const base =\n opts.backoffMs ??\n (isThrottled(error) ? STORAGE_RETRY_THROTTLE_BASE_MILLIS : STORAGE_RETRY_TRANSIENT_BASE_MILLIS);\n const ceiling = Math.min(STORAGE_RETRY_MAX_DELAY_MILLIS, base * 2 ** retryIndex);\n return (opts.random ?? Math.random)() * ceiling;\n};\n\n/**\n * Run one storage request under the single adapter retry policy: at most\n * `retries + 1` attempts (default {@link STORAGE_RETRY_MAX_ATTEMPTS}; one\n * for a `compareAndSwap` call),\n * one counter for throttles and transient failures alike, full-jitter\n * backoff between attempts (see {@link storageRetryDelayMillis}). A\n * {@link PERMANENT_STORAGE_ERROR_CODES} failure, an error whose cause\n * carries `refused: true`, an `AbortError`, or a failure after\n * `opts.signal` aborted ends the loop at once.\n *\n * Every adapter wraps each request — one object call, or one `list`\n * page — in exactly one `retryStorageCall`, so a failing call costs at\n * most `retries + 1` requests. Callers above the `Storage` boundary must\n * not add their own blind resend loop on top.\n *\n * Each attempt is charged to the active invocation's request ledger\n * ({@link currentRequestLedger}) on `opts.pool` before it is sent. An\n * attempt the ledger refuses is never sent: the refusal (`CapacityExceeded`,\n * `cause.refused`) ends the loop like any refusal.\n */\nexport const retryStorageCall = async <T>(\n fn: () => Promise<T>,\n opts: StorageRetryOptions = {},\n): Promise<T> => {\n const retries =\n opts.compareAndSwap === true ? 0 : (opts.retries ?? STORAGE_RETRY_MAX_ATTEMPTS - 1);\n // A non-integer cap would end the loop between attempts and drop the\n // real error; reject it before any request is sent.\n if (!Number.isSafeInteger(retries) || retries < 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `storage retries must be a non-negative integer, got ${String(retries)}`,\n );\n }\n const sleep = opts.sleep ?? delay;\n const ledger = currentRequestLedger();\n const pool = opts.pool ?? \"external\";\n // Set once an attempt of a conditional create ends with an unknown outcome.\n let uncertain = false;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n // A backoff abort must preserve an earlier create's unknown outcome.\n opts.signal?.throwIfAborted();\n ledger?.acquire(pool, currentRequestHold());\n return await fn();\n } catch (error) {\n const aborted = opts.signal?.aborted === true;\n if (isAbortError(error) || (aborted && !(error instanceof BaerlyError))) {\n throw error;\n }\n if (error instanceof BaerlyError && PERMANENT_STORAGE_ERROR_CODES.has(error.code)) {\n if (opts.conditionalCreate === true && uncertain && !isWriteConflict(error)) {\n throw new BaerlyError(\n \"NetworkError\",\n `${error.message} (an earlier attempt of this conditional create may have landed)`,\n { cause: error },\n );\n }\n throw error;\n }\n const refused = isRefused(error);\n const mayHaveApplied =\n error instanceof BaerlyError &&\n (error.cause as { mayHaveApplied?: boolean } | undefined)?.mayHaveApplied === true;\n if ((!isThrottled(error) && !refused) || mayHaveApplied) {\n uncertain = true;\n }\n // The attempt cap and a refusal end here, through the one final-attempt\n // path. Only a create whose every attempt was provably unapplied\n // reports `notApplied`; a throttle may retain an unknown outcome.\n if (attempt >= retries || refused || aborted) {\n if (opts.conditionalCreate === true && error instanceof BaerlyError) {\n if (!uncertain) {\n throw new BaerlyError(error.code, error.message, {\n cause: {\n ...(error.cause as object),\n notApplied: true,\n },\n ...(error.resolution !== undefined && { resolution: error.resolution }),\n });\n }\n if (refused && error.code !== \"NetworkError\") {\n // A ledger refusal proves only that THIS attempt was not sent;\n // an earlier uncertain one may have landed, so the create's\n // fate is unknown, as for a permanent rejection above.\n throw new BaerlyError(\n \"NetworkError\",\n `${error.message} (an earlier attempt of this conditional create may have landed)`,\n { cause: error.cause },\n );\n }\n }\n throw error;\n }\n await sleep(storageRetryDelayMillis(error, attempt, opts));\n }\n }\n throw new BaerlyError(\"Internal\", \"storage retry loop exited without returning or throwing\");\n};\n","/**\n * A keyed async mutex: serializes async critical sections that share a\n * lock key, while letting different keys run concurrently.\n *\n * Deliberately NOT re-exported from `./index.ts` — this is an internal\n * implementation detail of `LocalFsStorage`, not part of the published\n * `@gusto/baerly-storage/dev` surface.\n */\n\ninterface KeyLock {\n /** Resolves when the currently-running holder releases. */\n tail: Promise<void>;\n /** Holders currently running or queued; the entry is evicted at zero. */\n waiters: number;\n}\n\n/**\n * Live locks, keyed by caller-supplied string.\n *\n * Module-level rather than per-owner on purpose. `LocalFsStorage` is\n * constructed freely — `localFsStorage()` mints a fresh instance on every\n * call over the same default root, and the randomized cascade builds N\n * instances over one directory specifically to make them contend — so a\n * lock map hanging off the instance would serialize nothing in exactly the\n * cases that need it. Callers key on the resolved root plus the storage\n * key, which is the real identity of the thing being mutated.\n */\nconst locks = new Map<string, KeyLock>();\n\n/**\n * Run `fn` with exclusive access to `lockKey`, in FIFO order among\n * contenders. Concurrent calls on *different* keys are unaffected.\n *\n * A rejecting `fn` releases the lock like any other completion and the\n * rejection propagates to its own caller only — one failed critical\n * section must not wedge the key or poison the next holder.\n *\n * Scope: one loaded copy of this module, since `locks` is module-level.\n * That is one process in every normal setup. It says nothing about other\n * processes, which need a lock file, a lease, or server-side CAS.\n *\n * `fn` must not itself call `withKeyLock` on the same key — the inner\n * call would wait on the outer call's release and self-deadlock. Nothing\n * in this package does; only one lock is ever held at a time, so there is\n * no lock-ordering cycle either.\n */\nexport const withKeyLock = async <T>(lockKey: string, fn: () => Promise<T>): Promise<T> => {\n const lock = locks.getOrInsertComputed(lockKey, () => ({ tail: Promise.resolve(), waiters: 0 }));\n lock.waiters += 1;\n\n // Take a ticket: wait on the previous holder's release, and publish our\n // own release as what the next arrival waits on. Both happen before any\n // `await`, so tickets are handed out in call order with no interleaving.\n const predecessor = lock.tail;\n let release!: () => void;\n lock.tail = new Promise<void>((resolve) => {\n release = resolve;\n });\n\n await predecessor;\n try {\n return await fn();\n } finally {\n release();\n lock.waiters -= 1;\n // Evict once the last contender drains, so the map is bounded by\n // in-flight writers rather than growing with the keyspace — a\n // long-lived dev server would otherwise retain an entry per key ever\n // written. `waiters` is incremented synchronously at registration and\n // decremented only here, so zero really does mean nobody is left. The\n // identity check is belt-and-braces: there is no `await` between the\n // release above and this line, so it cannot currently be false.\n if (lock.waiters === 0 && locks.get(lockKey) === lock) {\n locks.delete(lockKey);\n }\n }\n};\n\n/** Test-only: number of live lock entries. Pins the eviction path. */\nexport const keyLockCount = (): number => locks.size;\n","import { BaerlyError } from \"@baerly/protocol\";\n\n/**\n * On-disk encoding of `Storage` keys for `LocalFsStorage`.\n *\n * Keys are byte-exact everywhere else (S3, R2, `MemoryStorage`), but a\n * filesystem may fold case and Unicode normalization (default macOS APFS\n * does both), which would merge `A`/`a` or NFC/NFD `é` onto one file. So\n * each `/`-segment is escaped into an alphabet that every case fold and\n * every normalization form leaves unchanged:\n *\n * - `a-z`, `0-9`, `-`, `_` stay literal, and so does `.` except where it\n * would start an on-disk name.\n * - Every other UTF-8 byte becomes `%` plus two lowercase hex digits:\n * `A` → `%41`, `é` (NFC) → `%c3%a9`, `é` (NFD) → `e%cc%81`.\n *\n * Decoding the encoding returns the original key, so distinct keys get\n * distinct names, and folding those names changes nothing. Kernel-written\n * segments (`log/<seq>`, `current.json`, base-32 index values, UUIDv7\n * ids) are already in the literal set, so they look the same on disk.\n * The exception is the snapshot level segment `L9`, stored as `%4c9`.\n *\n * No on-disk name ever starts with `.`, which leaves every dot-prefixed\n * name (staging temps, the format marker, a stray `.DS_Store`) private to\n * the adapter.\n *\n * **`NAME_MAX`.** Escaping can triple a segment, and filenames cap at 255\n * bytes on APFS and ext4. An encoded segment longer than that is split\n * into directory components of at most {@link MAX_PART_BYTES} bytes, each\n * but the last ending in {@link CONTINUATION}. `~` is always escaped by\n * the encoding, so a trailing `~` can only mean \"continued\". Splits fall\n * only between tokens (a literal byte or a `%xx` triplet).\n *\n * **Alternatives that fail.** Refusing a folding filesystem at startup\n * breaks zero-config dev on default macOS. A sidecar key map or hashed\n * filenames breaks the atomic single-file `link(2)` create and readable\n * names. Lowercase-only ids would bend the public `_id` grammar to suit\n * one adapter.\n */\n\n/** Filename limit on APFS and ext4. */\nexport const NAME_MAX_BYTES = 255;\n\n/** Marks a directory component as the head of a split segment. */\nexport const CONTINUATION = \"~\";\n\n/** Longest component that still fits {@link CONTINUATION} under `NAME_MAX`. */\nconst MAX_PART_BYTES = NAME_MAX_BYTES - CONTINUATION.length;\n\nconst utf8Encoder = new TextEncoder();\n// `ignoreBOM: true` keeps a leading U+FEFF: by default `TextDecoder` strips\n// it as a byte-order mark, which would decode `\\uFEFFA` to `A`.\nconst utf8Decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true });\n\n/** Bytes that stay literal: `-` `.` `0-9` `_` `a-z`. `.` is special-cased. */\nconst isLiteralByte = (b: number): boolean =>\n (b >= 0x61 && b <= 0x7a) || // a-z\n (b >= 0x30 && b <= 0x39) || // 0-9\n b === 0x2d || // -\n b === 0x5f || // _\n b === 0x2e; // .\n\nconst DOT = 0x2e;\n\nconst escapeByte = (b: number): string => `%${b.toString(16).padStart(2, \"0\")}`;\n\n/** Tokens of one encoded segment: a literal char or a `%xx` triplet. */\nconst tokenize = (segment: string): string[] => {\n const tokens: string[] = [];\n for (const b of utf8Encoder.encode(segment)) {\n tokens.push(isLiteralByte(b) ? String.fromCharCode(b) : escapeByte(b));\n }\n return tokens;\n};\n\n/**\n * Pack tokens into on-disk components. A component never starts with a\n * literal `.`: such a token is written as `%2e` instead.\n */\nconst pack = (tokens: string[], limit: number): string[] => {\n const parts: string[] = [];\n let current = \"\";\n for (let token of tokens) {\n if (current.length + token.length > limit) {\n parts.push(current);\n current = \"\";\n }\n if (current === \"\" && token === \".\") {\n token = escapeByte(DOT);\n }\n current += token;\n }\n parts.push(current);\n return parts;\n};\n\n/** Encode one non-empty `/`-segment into its on-disk component(s). */\nexport const encodeSegment = (segment: string): string[] => {\n const tokens = tokenize(segment);\n const single = pack(tokens, Number.POSITIVE_INFINITY);\n if (single[0]!.length <= NAME_MAX_BYTES) {\n return single;\n }\n const parts = pack(tokens, MAX_PART_BYTES);\n return parts.map((p, i) => (i < parts.length - 1 ? p + CONTINUATION : p));\n};\n\n/**\n * Encode a key into on-disk path components. The caller has already\n * validated the key's `/`-structure (no empty, `.`, or `..` segment).\n * Rejects a key that is not well-formed UTF-16: `TextEncoder` maps every\n * lone surrogate to U+FFFD, which would make the encoding non-injective.\n */\nexport const encodeKey = (key: string): string[] => {\n if (!key.isWellFormed()) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage: key is not well-formed UTF-16 (lone surrogate): ${JSON.stringify(key)}`,\n );\n }\n return key.split(\"/\").flatMap(encodeSegment);\n};\n\nconst HEX = /^[0-9a-f]{2}$/;\n\n/** Decode one component's bytes (continuation marker already stripped). */\nconst decodeBytes = (component: string, out: number[]): boolean => {\n for (let i = 0; i < component.length; i++) {\n const c = component.charCodeAt(i);\n if (c === 0x25) {\n const hex = component.slice(i + 1, i + 3);\n if (!HEX.test(hex)) {\n return false;\n }\n out.push(Number.parseInt(hex, 16));\n i += 2;\n } else if (isLiteralByte(c)) {\n out.push(c);\n } else {\n return false;\n }\n }\n return true;\n};\n\n/**\n * Decode on-disk path components (relative to the root) back to a key.\n * Returns `null` for anything that is not the canonical encoding of some\n * key — a foreign file, a non-canonical escape, a dangling continuation —\n * so the caller can decide how loudly to fail.\n */\nexport const decodeComponents = (components: readonly string[]): string | null => {\n const segments: string[] = [];\n let bytes: number[] = [];\n for (const component of components) {\n const continued = component.endsWith(CONTINUATION);\n const body = continued ? component.slice(0, -CONTINUATION.length) : component;\n if (body === \"\" || !decodeBytes(body, bytes)) {\n return null;\n }\n if (!continued) {\n let segment: string;\n try {\n segment = utf8Decoder.decode(new Uint8Array(bytes));\n } catch {\n return null;\n }\n if (segment === \".\" || segment === \"..\") {\n return null; // not a valid key segment\n }\n segments.push(segment);\n bytes = [];\n }\n }\n if (bytes.length > 0 || segments.length === 0) {\n return null; // ends mid-segment\n }\n const key = segments.join(\"/\");\n // Canonical-form check: exactly one spelling per key, so `list` can\n // never report a key under two names (`%61` vs `a`, `%2E` vs `%2e`,\n // a split in the wrong place).\n let canonical: string[];\n try {\n canonical = encodeKey(key);\n } catch {\n return null;\n }\n if (canonical.length !== components.length || canonical.some((c, i) => c !== components[i])) {\n return null;\n }\n return key;\n};\n","import { createHash } from \"node:crypto\";\nimport {\n link,\n mkdir,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n stat,\n writeFile,\n} from \"node:fs/promises\";\nimport { dirname, join, resolve, sep } from \"node:path\";\nimport {\n BaerlyError,\n assertValidStorageKey,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\nimport { withKeyLock } from \"./key-lock.ts\";\nimport { decodeComponents, encodeKey } from \"./local-fs-key-codec.ts\";\n\n/**\n * Prefix for the in-directory staging temps (see `put`). Dot-prefixed, so\n * it can never collide with an encoded key (see `local-fs-key-codec.ts`)\n * and `walk` skips it with every other adapter-private name.\n */\nconst TEMP_PREFIX = \".baerly-tmp-\";\n\n/**\n * Root marker recording the on-disk key encoding. Dot-prefixed, so it is\n * never a key. A directory without it is scanned once for names written\n * by the pre-encoding layout (see `#ensureFormat`).\n */\nconst FORMAT_MARKER = \".baerly-localfs.json\";\n\n/** Version of the key encoding in `local-fs-key-codec.ts`. */\nconst KEY_ENCODING = 1;\n\n/** Legacy paths named in the refusal message before it truncates. */\nconst LEGACY_PATHS_SHOWN = 10;\n\n/**\n * Staging path for a two-phase (write → publish) `put`. Always a sibling\n * of the destination: `rename(2)`/`link(2)` refuse to cross filesystems\n * (`EXDEV`), and the bucket root is routinely on a different volume from\n * `os.tmpdir()`. The leading `.` of `TEMP_PREFIX` is what makes staging\n * in-bucket safe — `walk` skips dot-prefixed names at every depth, and no\n * encoded key starts with one, so a crash before the publish leaves a file\n * invisible to `list` rather than a bogus key.\n *\n * The trade-off that invisibility buys: a temp stranded by a hard crash\n * now sits inside the bucket, and because every enumerator goes through\n * `list`, nothing — not `runGc`, not `admin fsck` — will ever reclaim it.\n * Staging in `os.tmpdir()` at least let the OS reap it. Repeated crashes\n * therefore grow the data directory, and clearing that is a manual\n * `find . -name '.baerly-tmp-*' -delete`. Non-crash failures are cleaned\n * up by `put`'s `finally`.\n */\nconst tempPathFor = (finalPath: string): string =>\n join(\n dirname(finalPath),\n `${TEMP_PREFIX}${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`,\n );\n\nexport interface LocalFsStorageOptions {\n /** Root directory; treated as \"the bucket\". */\n root: string;\n}\n\nconst utf8Encoder = new TextEncoder();\n\n/**\n * Compare two keys by their UTF-8 byte sequences — the order S3 and R2\n * use for `list`. JS's default string sort compares UTF-16 code units,\n * which diverges from UTF-8 byte order for supplementary-plane\n * characters; using this keeps `list` ordering faithful to the real\n * adapters. (All kernel keys are ASCII base-32, where both orders\n * coincide.)\n */\nconst compareKeysUtf8 = (a: string, b: string): number => {\n const ba = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ba.length, bb.length);\n for (let i = 0; i < n; i++) {\n if (ba[i] !== bb[i]) {\n return ba[i]! - bb[i]!;\n }\n }\n return ba.length - bb.length;\n};\n\n/**\n * `Storage` backed by a directory tree. Keys may contain `/` and map\n * to nested directories on disk so `ls`/`cat` work as expected.\n *\n * Keys are byte-exact, as on S3 and R2: keys that differ only by case or\n * Unicode normalization are distinct objects even on a filesystem that\n * folds both (default macOS APFS). Each segment is escaped into a\n * fold-invariant alphabet on disk — `A` is stored as `%41`, NFC `é` as\n * `%c3%a9` — while kernel-written segments (lowercase ids, base-32 index\n * values, `current.json`) are stored verbatim. See\n * `local-fs-key-codec.ts`.\n *\n * The root carries a `.baerly-localfs.json` marker naming that encoding.\n * A directory written by an older release, before keys were escaped, is\n * adopted as-is when every name in it already reads the same under the\n * encoding; otherwise every operation refuses with `InvalidConfig`.\n * Such a directory is dev data: move it aside or delete it. Collections\n * worth keeping can be dumped with the older release (`baerly admin\n * dump`, rows only) and restored into a fresh directory (`baerly admin\n * restore`). Data a folding filesystem has already merged is not\n * recoverable.\n *\n * ETags are content-addressed: `\"<sha-256-hex>\"` (the surrounding\n * double-quotes match S3's wire format for non-multipart objects).\n * Identical bodies share an ETag across runs — the property that\n * makes this adapter useful for fixture-based tests.\n *\n * Writes are atomic via `writeFile(temp) + rename(final)`; readers\n * never see a partially-written file. The temp is always a sibling of\n * its destination — `rename(2)`/`link(2)` fail with `EXDEV` across\n * filesystems, and the bucket root is routinely on a different volume\n * from `os.tmpdir()` (see `tempPathFor`).\n *\n * `ifNoneMatch:\"*\"` uses `link(2)` (atomic exclusive create; `EEXIST` ⇒\n * key exists) so concurrent creates have exactly one winner. temp+`link`\n * over `open(…,\"wx\")` keeps a partially-written new key invisible to a\n * concurrent reader.\n *\n * `ifMatch` is a read-compare-write, so it is made atomic by serializing\n * every mutation of a key against every other — see `#lockKey`.\n *\n * Scope of that guarantee, precisely: **one loaded copy of this module**.\n * Within it, concurrent CAS on one key admits exactly one winner and the\n * losers get `WriteConflict`, across any number of `LocalFsStorage` instances\n * whose roots resolve — through symlinks — to the same directory. That is\n * one process in every normal setup, but the lock lives in a module-level\n * map, so a process that somehow loads both this source and the bundled\n * copy has two of them.\n *\n * Across processes it guarantees nothing: two `baerly` CLI runs, or two\n * servers, sharing a directory can both win, because nothing in POSIX\n * makes read-compare-write atomic without a lock file or a lease. That is\n * why this adapter is for single-process dev and self-hosting;\n * horizontally-scaled deploys need S3 / R2, whose server-side conditional\n * write is what the no-lease maintenance fold actually relies on.\n *\n * Node-only — imports `node:fs`, `node:path`, `node:crypto`. Lives in\n * `@baerly/dev` because the protocol kernel is pure-modules / no I/O\n * and must remain Worker-bundleable.\n *\n * ⚠️ **Hard termination and temp files.**\n *\n * Writes stage a sibling `.baerly-tmp-*` file before atomic rename/link.\n * Normal failures clean up the temp in `finally`, but hard termination\n * (`SIGKILL`, OOM, power loss) can strand a temp inside the root directory.\n *\n * These files are hidden from `list`, `gc`, `fsck`, and usage reporting\n * by design—the temp filter applies at every depth.\n *\n * **Manual cleanup procedure:**\n * 1. Stop all writers using the root\n * 2. Run: `find <root> -name '.baerly-tmp-*' -delete`\n *\n * Do not clean while writes are in progress—races with in-flight PUTs\n * can delete a file that a concurrent operation is about to rename.\n */\nexport class LocalFsStorage implements Storage {\n readonly #root: string;\n /** Memoized `realpath` of {@link #root} — see {@link #canonicalRoot}. */\n #realRoot: string | undefined;\n /** Set once the root's key encoding is known to be current. */\n #formatChecked = false;\n\n constructor(opts: LocalFsStorageOptions) {\n this.#root = resolve(opts.root);\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n await this.#ensureFormat(false);\n let body: Buffer;\n try {\n body = await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.get(${key}): ${(error as Error).message}`,\n { cause: error },\n );\n }\n const etag = etagOf(body);\n return { body: toUint8Array(body), etag };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n await this.#ensureFormat(true);\n // Create the parent before taking the lock, so the `realpath` behind\n // `#lockKey` has a directory to canonicalize.\n await mkdir(dirname(path), { recursive: true });\n // Every mutation of a key is serialized against every other. `ifMatch`\n // is the reason: it reads the current body, compares etags, and only\n // then publishes, with awaited fs ops in between — so unguarded, two\n // callers both read the base etag, both pass the compare, and both\n // publish, yielding N winners for one base version. Guarding the\n // unconditional and create-if-absent paths too is not incidental: an\n // unconditional put landing inside another caller's compare→publish\n // window is the same lost update reached from the other side.\n return withKeyLock(await this.#lockKey(path), () => this.#putSerialized(key, path, body, opts));\n }\n\n async #putSerialized(\n key: string,\n path: string,\n body: Uint8Array,\n opts?: StoragePutOptions,\n ): Promise<StoragePutResult> {\n // Re-check inside the critical section. The pre-lock check happens\n // before an unbounded queue wait, so a signal aborted while this call\n // sat behind other writers to the same key would otherwise be ignored\n // and the write would land anyway.\n opts?.signal?.throwIfAborted();\n const newEtag = etagOf(body);\n\n if (opts?.ifNoneMatch === \"*\") {\n // Atomic exclusive create via link(2) — see class JSDoc.\n const tmp = tempPathFor(path);\n try {\n await writeFile(tmp, body);\n await link(tmp, path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"EEXIST\") {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifNoneMatch=\"*\" but key exists)`,\n );\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n { cause: error },\n );\n } finally {\n // Best-effort cleanup — a failed write may leave a partial temp,\n // and a cleanup failure must not mask a WriteConflict thrown above.\n await rm(tmp, { force: true }).catch(() => {});\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n if (opts?.ifMatch !== undefined) {\n // Read-compare-write. Atomic only because `put` holds this key's\n // lock for the whole of it, publish included — see the class JSDoc\n // for what that does and does not guarantee.\n const existing = await readExisting(path);\n if (existing === null) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n const currentEtag = etagOf(existing);\n if (currentEtag !== opts.ifMatch) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but current ETag is ${currentEtag})`,\n );\n }\n }\n\n // Unconditional PUT (or `ifMatch` already verified above). Stage to a\n // sibling temp, then `rename` to publish — the rename is atomic, so a\n // reader sees either the old body or the new one, never a partial\n // write. See `tempPathFor` for why the temp must be a sibling.\n const tmp = tempPathFor(path);\n try {\n await writeFile(tmp, body);\n await rename(tmp, path);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.put(${key}): ${(error as Error).message}`,\n { cause: error },\n );\n } finally {\n // Best-effort cleanup, mirroring the create-if-absent branch. On\n // success the rename already consumed the temp and this is a no-op;\n // on failure it keeps a half-written body from lingering under the\n // bucket root, where only `walk`'s dot-name skip hides it. A\n // cleanup failure must not mask the error thrown above.\n await rm(tmp, { force: true }).catch(() => {});\n }\n return { etag: newEtag, serverDate: new Date() };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const path = this.#pathFor(key);\n await this.#ensureFormat(false);\n // Same lock as `put`: a delete slipping between an `ifMatch` compare\n // and its publish would resurrect the key from a version the caller\n // was told no longer existed.\n return withKeyLock(await this.#lockKey(path), async () => {\n // Re-check after the queue wait — see `#putSerialized`.\n opts?.signal?.throwIfAborted();\n try {\n await rm(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return;\n } // idempotent\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.delete(${key}): ${(error as Error).message}`,\n { cause: error },\n );\n }\n });\n }\n\n /**\n * Identity of the thing being mutated, for {@link withKeyLock}.\n *\n * Keyed on the *canonical filesystem path*, not on the key and not on\n * `this`. Not on `this` because separate instances over one directory\n * are the common case (`localFsStorage()` mints a fresh one per call),\n * so an instance-scoped lock would serialize nothing where it matters.\n * Not on the root spelling the caller passed, because several spellings\n * of a root can name one directory, and handing an alias its own lock\n * lets the race straight back in:\n *\n * - Symlinks. `resolve()` collapses `.`/`..` but not links, so\n * `/tmp/data` and `/private/tmp/data` — the same directory on every\n * Mac — look like two (measured at 2 winners before it was closed).\n * Hence `realpath`, memoized per instance and only cached once it\n * succeeds, so a root that does not exist yet cannot poison the entry.\n * - Case and Unicode in the root path. A caller can spell a root on a\n * folding filesystem as `/Users/me/Data` or `/users/me/data`, or in\n * NFC or NFD, and reach one directory.\n *\n * The key-derived tail of `path` cannot alias: it is the fold-invariant\n * encoding from `local-fs-key-codec.ts`, so distinct keys are distinct\n * files on every filesystem and the case/NFC fold below changes nothing\n * there. The fold is kept for the root-spelling case only. It\n * over-approximates on a case-sensitive filesystem, where two roots\n * differing only in case are really different directories and share a\n * lock; that costs a little concurrency, never correctness. And it is\n * not exact Unicode case folding (JS has no `toCaseFold()`), so a root\n * spelled with `Σ` and one with `σ` get separate locks — acceptable for\n * a root path, which the operator chooses once.\n */\n async #lockKey(path: string): Promise<string> {\n const root = await this.#canonicalRoot();\n return (root + path.slice(this.#root.length)).normalize(\"NFC\").toLowerCase();\n }\n\n /**\n * {@link #root} with symlinks resolved. Cached only on success: `delete`\n * against a bucket that was never created would otherwise memoize the\n * un-canonicalized spelling and defeat the aliasing guard for every\n * later `put`.\n *\n * Only `ENOENT` falls back. Every other `realpath` failure — `EACCES`,\n * `ELOOP`, `ENAMETOOLONG` — throws, because the fallback is a *different\n * lock key*, and absorbing those would let an instance that cannot\n * canonicalize run unserialized against one that can. That is the\n * exactly-one-winner guarantee this lock exists to provide, failing\n * silently, which is indistinguishable from the defect it fixed. A root\n * that is unreadable is a broken deployment either way; the only choice\n * is whether it says so.\n *\n * Not caching failure bounds that to one call but does not erase it.\n * `put` mkdirs before locking so it always canonicalizes; `delete` does\n * not, so against a not-yet-created symlinked root it locks the\n * unresolved spelling while a concurrent `put` locks the resolved one —\n * two locks, no serialization. That needs only ONE spelling in play, not\n * two: the split is resolved-vs-unresolved form of the same path.\n *\n * Known and kept, not overlooked. The hazard `delete` locks\n * against is slipping inside an `ifMatch` compare→publish, which needs\n * the key to exist, hence the root to exist, hence `realpath` to have\n * succeeded — so both conditions hold only if the root appears between\n * this call and the `rm`, and the next call self-heals. Fixes cost more\n * than that: mkdir-to-get-a-lock-key makes deleting from an absent\n * bucket create it, and walking to the deepest existing ancestor adds\n * real complexity for an unreachable window.\n */\n async #canonicalRoot(): Promise<string> {\n if (this.#realRoot !== undefined) {\n return this.#realRoot;\n }\n try {\n this.#realRoot = await realpath(this.#root);\n return this.#realRoot;\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return this.#root;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage: cannot canonicalize root (${this.#root}): ${(error as Error).message}`,\n { cause: error },\n );\n }\n }\n\n async *list(\n prefix: string,\n opts?: {\n startAfter?: string;\n maxKeys?: number;\n signal?: AbortSignal;\n },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n const startAfter = opts?.startAfter ?? \"\";\n const maxKeys = opts?.maxKeys ?? Infinity;\n await this.#ensureFormat(false);\n const keys: string[] = [];\n for (const components of (await walk(this.#root)) ?? []) {\n const key = decodeComponents(components);\n if (key !== null) {\n keys.push(key);\n continue;\n }\n // Not the canonical encoding of any key: a file this adapter did not\n // write (`notes~`, `100%zz`). Usually no `get`/`put`/`delete` can\n // address it either, so it is outside the keyspace and skipped rather\n // than failing every `list` over one stray file.\n //\n // Except on a folding filesystem, where a stray such as `c/%4A` or\n // `README.md` IS the file that `get(\"c/J\")` / `get(\"readme.md\")`\n // reads, and a `put` renames over it keeping the stray spelling.\n // Skipping it would hide a key that the other verbs see, so when the\n // case/NFC fold of the name decodes and resolves to this very file,\n // fail loudly instead. `InvalidConfig`, as the legacy-tree refusal is:\n // both mean the data directory holds files the operator must move.\n const alias = await this.#aliasedKey(components);\n if (alias !== null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage.list: ${join(this.#root, ...components)} was not written by this ` +\n `adapter but the filesystem resolves key ${JSON.stringify(alias)} to it; move the ` +\n `file out of the data directory`,\n );\n }\n }\n keys.sort(compareKeysUtf8);\n let yielded = 0;\n for (const key of keys) {\n if (!key.startsWith(prefix)) {\n continue;\n }\n if (compareKeysUtf8(key, startAfter) <= 0) {\n continue;\n }\n if (yielded >= maxKeys) {\n return;\n }\n opts?.signal?.throwIfAborted();\n let buf: Buffer;\n try {\n buf = await readFile(this.#pathFor(key));\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n // Deleted between `walk` and this read. A key vanishing\n // mid-listing is a legal outcome on a real object store, so skip\n // it rather than failing the whole iteration — and skip it\n // rather than locking, since `list` is a snapshot iterator, not\n // a critical section. Reachable in the maintenance fold, where\n // `runGc` deletes while the compactor walks the same prefixes.\n continue;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage.list(${key}): ${(error as Error).message}`,\n { cause: error },\n );\n }\n yield { key, etag: etagOf(buf) };\n yielded += 1;\n }\n }\n\n /**\n * The key whose on-disk path the filesystem resolves to the stray file at\n * `components`, or `null` if none does. Only a case- or\n * normalization-folding filesystem produces one: the candidate is\n * {@link foldToEncodedAlphabet} of the name, which is a key only if it\n * decodes, and an alias only if both paths name the same inode.\n */\n async #aliasedKey(components: readonly string[]): Promise<string | null> {\n const folded = components.map(foldToEncodedAlphabet);\n const key = decodeComponents(folded);\n if (key === null) {\n return null;\n }\n try {\n const [a, b] = await Promise.all([\n stat(join(this.#root, ...components)),\n stat(join(this.#root, ...folded)),\n ]);\n return a.dev === b.dev && a.ino === b.ino ? key : null;\n } catch (error) {\n // Either side vanished, or the fold names no file: ENOENT, or ENOTDIR\n // when the folded path runs through a key's file (`Notes/todo` beside\n // the key `notes` on a case-sensitive filesystem), or ENAMETOOLONG\n // should a fold ever lengthen a name. None is an alias.\n if (\n isErrnoException(error) &&\n (error.code === \"ENOENT\" || error.code === \"ENOTDIR\" || error.code === \"ENAMETOOLONG\")\n ) {\n return null;\n }\n throw new BaerlyError(\"InvalidResponse\", `LocalFsStorage.list: ${(error as Error).message}`, {\n cause: error,\n });\n }\n }\n\n /**\n * Make sure the root uses the current key encoding before any operation\n * touches it. With the marker present this is one small read per\n * instance. Without it the root is scanned once:\n *\n * - absent root: nothing to read, so reads return without stamping, and\n * the first `put` (`create`) makes the root and stamps it;\n * - every on-disk name already reads the same under the encoding (true\n * of kernel-written trees with lowercase ids that hold no snapshot;\n * the snapshot segment `L9` is escaped): stamp, nothing moves;\n * - otherwise refuse with `InvalidConfig`. There is no in-place\n * migration — renaming cannot undo merges a folding filesystem has\n * already made — so the remedy is dump with the older release and\n * restore into a fresh directory.\n *\n * Only success is cached, so a refusal repeats on every call.\n */\n async #ensureFormat(create: boolean): Promise<void> {\n if (this.#formatChecked) {\n return;\n }\n // Canonicalize first so a broken root (ELOOP, EACCES) reports as such —\n // see `#canonicalRoot` — rather than as a failed marker read.\n await this.#canonicalRoot();\n const marker = join(this.#root, FORMAT_MARKER);\n if (await readFormatMarker(marker)) {\n this.#formatChecked = true;\n return;\n }\n if (create) {\n await mkdir(this.#root, { recursive: true });\n }\n const legacy = await findLegacyPaths(this.#root);\n if (legacy === null) {\n return; // root absent and nothing to create\n }\n // Re-read before refusing: a concurrent opener may have stamped the\n // marker and written encoded names since this scan began.\n if (legacy.length > 0 && !(await readFormatMarker(marker))) {\n const shown = legacy.slice(0, LEGACY_PATHS_SHOWN).map((p) => ` ${p}`);\n if (legacy.length > LEGACY_PATHS_SHOWN) {\n shown.push(` … and ${legacy.length - LEGACY_PATHS_SHOWN} more`);\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage: ${this.#root} holds dev data from an older release, which this ` +\n `release cannot read. Move the directory aside or delete it; the next write ` +\n `starts a fresh one. The usual causes are a folded collection (\\`snapshot/L9/\\`) ` +\n `and an uppercase letter in a collection name or id (a camelCase name such as ` +\n `\\`boardInvitees\\`). To keep a collection's rows, dump it with the older release ` +\n `(\\`baerly admin dump\\`) and restore into the fresh directory ` +\n `(\\`baerly admin restore\\`); a dump holds collection rows only, not other files ` +\n `the app stored here. Paths not valid under the current key encoding (no ` +\n `${FORMAT_MARKER} marker):\\n` +\n `${shown.join(\"\\n\")}\\n` +\n `If a listed path is a stray file that is not data, move it out of the directory ` +\n `instead. Keys that differed only by case or Unicode normalization may already ` +\n `have been merged by the filesystem.`,\n );\n }\n await stampFormatMarker(marker);\n this.#formatChecked = true;\n }\n\n /**\n * Map an S3-style key to a filesystem path under `#root`, rejecting\n * anything that could escape the root (path traversal, absolute\n * paths, empty segments, backslashes) or that the encoding cannot\n * represent injectively (lone surrogates). All rejections throw\n * `BaerlyError(\"InvalidConfig\", …)`.\n */\n #pathFor(key: string): string {\n // Shared Storage key grammar (non-empty, no `.`/`..` segments); the\n // FS-specific guards below add traversal/backslash/empty-segment checks.\n assertValidStorageKey(key);\n if (key.startsWith(\"/\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: leading \"/\" in key: ${key}`);\n }\n if (key.includes(\"\\\\\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: backslash in key: ${key}`);\n }\n const segments = key.split(\"/\");\n if (segments.some((s) => s === \"\" || s === \".\" || s === \"..\")) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: illegal segment in key: ${key}`);\n }\n const path = join(this.#root, ...encodeKey(key));\n if (path !== this.#root && !path.startsWith(this.#root + sep)) {\n throw new BaerlyError(\"InvalidConfig\", `LocalFsStorage: resolved path escapes root: ${key}`);\n }\n return path;\n }\n}\n\nconst etagOf = (body: Uint8Array): string => {\n const h = createHash(\"sha256\").update(body).digest(\"hex\");\n return `\"${h}\"`;\n};\n\nconst toUint8Array = (buf: Buffer): Uint8Array =>\n new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n\nconst isErrnoException = (e: unknown): e is NodeJS.ErrnoException =>\n typeof e === \"object\" && e !== null && \"code\" in e;\n\nconst readExisting = async (path: string): Promise<Buffer | null> => {\n try {\n return await readFile(path);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n return null;\n }\n throw error;\n }\n};\n\n/**\n * `true` when the root's format marker exists and names the current\n * encoding, `false` when it is absent. A marker naming another encoding\n * means a newer release wrote this directory, so it is refused.\n */\nconst readFormatMarker = async (marker: string): Promise<boolean> => {\n const body = await readExisting(marker).catch((error: unknown) => {\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage: cannot read ${marker}: ${(error as Error).message}`,\n { cause: error },\n );\n });\n if (body === null) {\n return false;\n }\n let encoding: unknown;\n try {\n encoding = (JSON.parse(new TextDecoder().decode(body)) as { key_encoding?: unknown })\n .key_encoding;\n } catch (error) {\n throw new BaerlyError(\"InvalidResponse\", `LocalFsStorage: ${marker} is not valid JSON`, {\n cause: error,\n });\n }\n if (encoding !== KEY_ENCODING) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `LocalFsStorage: ${marker} names key_encoding ${JSON.stringify(encoding)}; this release ` +\n `reads only key_encoding ${KEY_ENCODING}`,\n );\n }\n return true;\n};\n\n/**\n * Write the format marker with the same temp + `link(2)` exclusive create\n * as `ifNoneMatch:\"*\"`. Losing that race to a concurrent opener is fine as\n * long as what it wrote is the current encoding.\n */\nconst stampFormatMarker = async (marker: string): Promise<void> => {\n const tmp = tempPathFor(marker);\n try {\n await writeFile(tmp, `${JSON.stringify({ key_encoding: KEY_ENCODING })}\\n`);\n await link(tmp, marker);\n } catch (error) {\n if (isErrnoException(error) && error.code === \"EEXIST\" && (await readFormatMarker(marker))) {\n return;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `LocalFsStorage: cannot write ${marker}: ${(error as Error).message}`,\n { cause: error },\n );\n } finally {\n await rm(tmp, { force: true }).catch(() => {});\n }\n};\n\n/**\n * Non-ASCII characters that APFS's full case folding maps to ASCII but\n * `toLowerCase` leaves alone (Unicode CaseFolding.txt status `F`, plus the\n * `C` mapping of long `ſ`). Each was checked on an APFS volume: a file\n * named with the left side is reached by the right side.\n */\nconst APFS_ASCII_FOLDS: Readonly<Record<string, string>> = {\n ß: \"ss\", // U+00DF\n ẞ: \"ss\", // U+1E9E\n ſ: \"s\", // U+017F\n ff: \"ff\", // U+FB00\n fi: \"fi\", // U+FB01\n fl: \"fl\", // U+FB02\n ffi: \"ffi\", // U+FB03\n ffl: \"ffl\", // U+FB04\n ſt: \"st\", // U+FB05\n st: \"st\", // U+FB06\n};\nconst APFS_ASCII_FOLDABLE = /[ßẞſff-st]/g;\n\n/**\n * Fold an on-disk name the way a folding filesystem matches it, as far as\n * the result can land in the encoded alphabet (`a-z0-9-_.%`). A name\n * containing anything else after the fold cannot decode, so only folds to\n * ASCII matter: lowercase (which also maps Kelvin `K` to `k`) plus\n * {@link APFS_ASCII_FOLDS}. Normalization adds none: the only canonical\n * decompositions to ASCII are Kelvin `K`, U+037E (`;`) and U+1FEF (`` ` ``),\n * and the last two are escaped by the encoding.\n */\nconst foldToEncodedAlphabet = (name: string): string =>\n name.replace(APFS_ASCII_FOLDABLE, (c) => APFS_ASCII_FOLDS[c]!).toLowerCase();\n\n/**\n * Paths under `root` that the pre-encoding layout wrote and the current\n * encoding would read differently (uppercase, non-ASCII, `%`, `~`, a\n * leading `.` …). Empty when the tree can be adopted as-is; `null` when\n * the root does not exist.\n *\n * Walks dot-prefixed names too: the old layout stored a key segment such\n * as an `_id` or collection named `.foo` verbatim, and the encoding treats\n * that name as adapter-private, so skipping it here would adopt the tree\n * and silently drop or orphan that data.\n */\nconst findLegacyPaths = async (root: string): Promise<string[] | null> => {\n const files = await walk(root, isLegacyScanNoise);\n if (files === null) {\n return null;\n }\n return files\n .filter((components) => decodeComponents(components) !== components.join(\"/\"))\n .map((components) => components.join(\"/\"))\n .toSorted();\n};\n\n/**\n * Entries the legacy scan may skip: staging temps (both layouts wrote them,\n * and the old one rejected keys with that prefix), and the files Finder\n * and git leave behind. Junk names are skipped as FILES only — a directory\n * called `.DS_Store` would be a legacy collection or tenant, i.e. data.\n * Nothing else is assumed not to be data.\n *\n * The format marker is deliberately not here. The scan runs only when the\n * marker was absent; if a concurrent opener stamps it mid-scan, the scan\n * flags it like any other name and `#ensureFormat`'s re-read of the marker\n * is what accepts the directory. A nested file with the marker's name is\n * legacy data (a key segment that old layout stored verbatim).\n */\nconst isLegacyScanNoise = (name: string, isDirectory: boolean): boolean =>\n name.startsWith(TEMP_PREFIX) || (!isDirectory && (name === \".DS_Store\" || name === \".gitkeep\"));\n\n/**\n * In the current layout every dot-prefixed name is not a key: no encoded\n * key component starts with `.`, so those are adapter-private (staging\n * temps, the format marker) or foreign (`.DS_Store`). Skipping temps is\n * what keeps a concurrent `list` from surfacing a half-published key.\n */\nconst isDotName = (name: string, _isDirectory: boolean): boolean => name.startsWith(\".\");\n\n/**\n * Recursive directory walk. Returns each file's path components relative\n * to `root`, or `null` when `root` does not exist. Entries for which\n * `skip` holds are ignored at every depth, directories included.\n */\nconst walk = async (\n root: string,\n skip: (name: string, isDirectory: boolean) => boolean = isDotName,\n): Promise<string[][] | null> => {\n const out: string[][] = [];\n const stack: Array<{ dir: string; components: string[] }> = [{ dir: root, components: [] }];\n while (stack.length > 0) {\n const { dir, components } = stack.pop()!;\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch (error) {\n if (isErrnoException(error) && error.code === \"ENOENT\") {\n if (dir === root) {\n return null;\n }\n continue;\n }\n throw error;\n }\n for (const entry of entries) {\n if (skip(entry.name, entry.isDirectory())) {\n continue;\n }\n const next = [...components, entry.name];\n if (entry.isDirectory()) {\n stack.push({ dir: join(dir, entry.name), components: next });\n } else if (entry.isFile()) {\n out.push(next);\n }\n }\n }\n return out;\n};\n","/*! @rgrove/parse-xml v5.2.0 | ISC License | Copyright Ryan Grove */\n\n// src/lib/StringScanner.ts\nvar emptyString = \"\";\nvar surrogatePair = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\nvar StringScanner = class {\n constructor(string) {\n this.o = this.u(string, true);\n this.d = 0;\n this.length = string.length;\n this.p = this.o !== this.length;\n this.h = string;\n if (this.p) {\n let charsToBytes = [];\n for (let byteIndex = 0, charIndex = 0; charIndex <= this.o; ++charIndex) {\n charsToBytes[charIndex] = byteIndex;\n byteIndex += string.codePointAt(byteIndex) > 65535 ? 2 : 1;\n }\n this.C = charsToBytes;\n }\n }\n /**\n * Whether the current character index is at the end of the input string.\n */\n get D() {\n return this.d >= this.o;\n }\n // -- Protected Methods ------------------------------------------------------\n /**\n * Returns the number of characters in the given string, which may differ from\n * the byte length if the string contains multibyte characters.\n */\n u(string, multiByteSafe = this.p) {\n return multiByteSafe ? string.replace(surrogatePair, \"_\").length : string.length;\n }\n // -- Public Methods ---------------------------------------------------------\n /**\n * Advances the scanner by the given number of characters, stopping if the end\n * of the string is reached.\n */\n l(count = 1) {\n this.d = Math.min(this.o, this.d + count);\n }\n /**\n * Returns the byte index of the given character index in the string. The two\n * may differ in strings that contain multibyte characters.\n */\n f(charIndex = this.d) {\n var _a;\n return this.p ? (_a = this.C[charIndex]) != null ? _a : Infinity : charIndex;\n }\n /**\n * Consumes and returns the given number of characters if possible, advancing\n * the scanner and stopping if the end of the string is reached.\n *\n * If no characters could be consumed, an empty string will be returned.\n */\n G(charCount = 1) {\n let chars = this.i(charCount);\n this.l(charCount);\n return chars;\n }\n /**\n * Consumes and returns the given number of bytes if possible, advancing the\n * scanner and stopping if the end of the string is reached.\n *\n * It's up to the caller to ensure that the given byte count doesn't split a\n * multibyte character.\n *\n * If no bytes could be consumed, an empty string will be returned.\n */\n v(byteCount) {\n let byteIndex = this.f();\n let result = this.h.slice(byteIndex, byteIndex + byteCount);\n this.l(this.u(result));\n return result;\n }\n /**\n * Consumes and returns all characters for which the given function returns\n * `true`, stopping when `false` is returned or the end of the input is\n * reached.\n */\n w(fn) {\n let { length, p: multiByteMode, h: string } = this;\n let startByteIndex = this.f();\n let endByteIndex = startByteIndex;\n if (multiByteMode) {\n while (endByteIndex < length) {\n let char = string[endByteIndex];\n let isSurrogatePair = char >= \"\\uD800\" && char <= \"\\uDBFF\";\n if (isSurrogatePair) {\n char += string[endByteIndex + 1];\n }\n if (!fn(char)) {\n break;\n }\n endByteIndex += isSurrogatePair ? 2 : 1;\n }\n } else {\n while (endByteIndex < length && fn(string[endByteIndex])) {\n ++endByteIndex;\n }\n }\n return this.v(endByteIndex - startByteIndex);\n }\n /**\n * Consumes the given string if it exists at the current character index, and\n * advances the scanner.\n *\n * If the given string doesn't exist at the current character index, an empty\n * string will be returned and the scanner will not be advanced.\n */\n b(stringToConsume) {\n let { length } = stringToConsume;\n let byteIndex = this.f();\n if (stringToConsume === this.h.slice(byteIndex, byteIndex + length)) {\n this.l(length === 1 ? 1 : this.u(stringToConsume));\n return stringToConsume;\n }\n return emptyString;\n }\n /**\n * Consumes characters until the given global regex is matched, advancing the\n * scanner up to (but not beyond) the beginning of the match. If the regex\n * doesn't match, nothing will be consumed.\n *\n * Returns the consumed string, or an empty string if nothing was consumed.\n */\n x(regex) {\n let matchByteIndex = this.h.slice(this.f()).search(regex);\n return matchByteIndex > 0 ? this.v(matchByteIndex) : emptyString;\n }\n /**\n * Consumes characters until the given string is found, advancing the scanner\n * up to (but not beyond) that point. If the string is never found, nothing\n * will be consumed.\n *\n * Returns the consumed string, or an empty string if nothing was consumed.\n */\n s(searchString) {\n let byteIndex = this.f();\n let matchByteIndex = this.h.indexOf(searchString, byteIndex);\n return matchByteIndex > 0 ? this.v(matchByteIndex - byteIndex) : emptyString;\n }\n /**\n * Returns the given number of characters starting at the current character\n * index, without advancing the scanner and without exceeding the end of the\n * input string.\n */\n i(count = 1) {\n let { d: charIndex, h: string } = this;\n return this.p ? string.slice(this.f(charIndex), this.f(charIndex + count)) : string.slice(charIndex, charIndex + count);\n }\n /**\n * Resets the scanner position to the given character _index_, or to the start\n * of the input string if no index is given.\n *\n * If _index_ is negative, the scanner position will be moved backward by that\n * many characters, stopping if the beginning of the string is reached.\n */\n j(index = 0) {\n this.d = index >= 0 ? Math.min(this.o, index) : Math.max(0, this.d + index);\n }\n};\n\n// src/lib/syntax.ts\nvar attValueCharDoubleQuote = /[\"&<]/;\nvar attValueCharSingleQuote = /['&<]/;\nvar attValueNormalizedWhitespace = /\\r\\n|[\\n\\r\\t]/g;\nvar endCharData = /<|&|]]>/;\nvar lineBreakToNormalize = /\\r\\n?/g;\nvar markupDeclarationDelimiter = /[\"'<>\\]]|$/;\nvar predefinedEntities = Object.freeze(Object.assign(/* @__PURE__ */ Object.create(null), {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n quot: '\"'\n}));\nfunction isNameChar(char) {\n let cp = char.codePointAt(0);\n return cp >= 97 && cp <= 122 || cp >= 65 && cp <= 90 || cp >= 48 && cp <= 57 || cp === 45 || cp === 46 || cp === 183 || cp >= 768 && cp <= 879 || cp === 8255 || cp === 8256 || isNameStartChar(char, cp);\n}\nfunction isNameStartChar(char, cp = char.codePointAt(0)) {\n return cp >= 97 && cp <= 122 || cp >= 65 && cp <= 90 || cp === 58 || cp === 95 || cp >= 192 && cp <= 214 || cp >= 216 && cp <= 246 || cp >= 248 && cp <= 767 || cp >= 880 && cp <= 893 || cp >= 895 && cp <= 8191 || cp === 8204 || cp === 8205 || cp >= 8304 && cp <= 8591 || cp >= 11264 && cp <= 12271 || cp >= 12289 && cp <= 55295 || cp >= 63744 && cp <= 64975 || cp >= 65008 && cp <= 65533 || cp >= 65536 && cp <= 983039;\n}\nfunction isReferenceChar(char) {\n return char === \"#\" || isNameChar(char);\n}\nfunction isWhitespace(char) {\n let cp = char.codePointAt(0);\n return cp === 32 || cp === 9 || cp === 10 || cp === 13;\n}\nfunction isXmlCodePoint(cp) {\n return cp >= 32 && cp <= 55295 || cp === 10 || cp === 9 || cp === 13 || cp >= 57344 && cp <= 65533 || cp >= 65536 && cp <= 1114111;\n}\n\n// src/lib/XmlNode.ts\nvar _XmlNode = class _XmlNode {\n constructor() {\n /**\n * Parent node of this node, or `null` if this node has no parent.\n */\n this.parent = null;\n /**\n * Starting byte offset of this node in the original XML string, or `-1` if\n * the offset is unknown.\n */\n this.start = -1;\n /**\n * Ending byte offset of this node in the original XML string, or `-1` if the\n * offset is unknown.\n */\n this.end = -1;\n }\n /**\n * Document that contains this node, or `null` if this node is not associated\n * with a document.\n */\n get document() {\n let node = this.parent;\n while (node !== null) {\n if (node.type === _XmlNode.TYPE_DOCUMENT) {\n return node;\n }\n node = node.parent;\n }\n return null;\n }\n /**\n * Whether this node is the root node of the document (also known as the\n * document element).\n */\n get isRootNode() {\n var _a;\n return ((_a = this.parent) == null ? void 0 : _a.type) === _XmlNode.TYPE_DOCUMENT && this.type === _XmlNode.TYPE_ELEMENT;\n }\n /**\n * Whether whitespace should be preserved in the content of this element and\n * its children.\n *\n * This is influenced by the value of the special `xml:space` attribute, and\n * will be `true` for any node whose `xml:space` attribute is set to\n * \"preserve\". If a node has no such attribute, it will inherit the value of\n * the nearest ancestor that does (if any).\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-white-space\n */\n get preserveWhitespace() {\n var _a;\n return !!((_a = this.parent) == null ? void 0 : _a.preserveWhitespace);\n }\n /**\n * Type of this node.\n *\n * The value of this property is a string that matches one of the static\n * `TYPE_*` properties on the `XmlNode` class (e.g. `TYPE_ELEMENT`,\n * `TYPE_TEXT`, etc.).\n *\n * The `XmlNode` class itself is a base class and doesn't have its own type\n * name.\n */\n get type() {\n return \"\";\n }\n /**\n * Returns a JSON-serializable object representing this node, minus properties\n * that could result in circular references.\n */\n toJSON() {\n let json = {\n type: this.type\n };\n if (this.isRootNode) {\n json.isRootNode = true;\n }\n if (this.preserveWhitespace) {\n json.preserveWhitespace = true;\n }\n if (this.start !== -1) {\n json.start = this.start;\n json.end = this.end;\n }\n return json;\n }\n};\n/**\n * Type value for an `XmlCdata` node.\n */\n_XmlNode.TYPE_CDATA = \"cdata\";\n/**\n * Type value for an `XmlComment` node.\n */\n_XmlNode.TYPE_COMMENT = \"comment\";\n/**\n * Type value for an `XmlDocument` node.\n */\n_XmlNode.TYPE_DOCUMENT = \"document\";\n/**\n * Type value for an `XmlDocumentType` node.\n */\n_XmlNode.TYPE_DOCUMENT_TYPE = \"doctype\";\n/**\n * Type value for an `XmlElement` node.\n */\n_XmlNode.TYPE_ELEMENT = \"element\";\n/**\n * Type value for an `XmlProcessingInstruction` node.\n */\n_XmlNode.TYPE_PROCESSING_INSTRUCTION = \"pi\";\n/**\n * Type value for an `XmlText` node.\n */\n_XmlNode.TYPE_TEXT = \"text\";\n/**\n * Type value for an `XmlDeclaration` node.\n */\n_XmlNode.TYPE_XML_DECLARATION = \"xmldecl\";\nvar XmlNode = _XmlNode;\n\n// src/lib/XmlText.ts\nvar XmlText = class extends XmlNode {\n constructor(text = \"\") {\n super();\n this.text = text;\n }\n get type() {\n return XmlNode.TYPE_TEXT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n text: this.text\n });\n }\n};\n\n// src/lib/XmlCdata.ts\nvar XmlCdata = class extends XmlText {\n get type() {\n return XmlNode.TYPE_CDATA;\n }\n};\n\n// src/lib/XmlComment.ts\nvar XmlComment = class extends XmlNode {\n constructor(content = \"\") {\n super();\n this.content = content;\n }\n get type() {\n return XmlNode.TYPE_COMMENT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n content: this.content\n });\n }\n};\n\n// src/lib/XmlDeclaration.ts\nvar XmlDeclaration = class extends XmlNode {\n constructor(version, encoding, standalone) {\n super();\n this.version = version;\n this.encoding = encoding != null ? encoding : null;\n this.standalone = standalone != null ? standalone : null;\n }\n get type() {\n return XmlNode.TYPE_XML_DECLARATION;\n }\n toJSON() {\n let json = XmlNode.prototype.toJSON.call(this);\n json.version = this.version;\n for (let key of [\"encoding\", \"standalone\"]) {\n if (this[key] !== null) {\n json[key] = this[key];\n }\n }\n return json;\n }\n};\n\n// src/lib/XmlElement.ts\nvar XmlElement = class _XmlElement extends XmlNode {\n constructor(name, attributes = /* @__PURE__ */ Object.create(null), children = []) {\n super();\n this.name = name;\n this.attributes = attributes;\n this.children = children;\n }\n /**\n * Whether this element is empty (meaning it has no children).\n */\n get isEmpty() {\n return this.children.length === 0;\n }\n get preserveWhitespace() {\n let node = this;\n while (node instanceof _XmlElement) {\n if (\"xml:space\" in node.attributes) {\n return node.attributes[\"xml:space\"] === \"preserve\";\n }\n node = node.parent;\n }\n return false;\n }\n /**\n * Text content of this element and all its descendants.\n */\n get text() {\n return this.children.map((child) => \"text\" in child ? child.text : \"\").join(\"\");\n }\n get type() {\n return XmlNode.TYPE_ELEMENT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n name: this.name,\n attributes: this.attributes,\n children: this.children.map((child) => child.toJSON())\n });\n }\n};\n\n// src/lib/XmlDocument.ts\nvar XmlDocument = class extends XmlNode {\n constructor(children = []) {\n super();\n this.children = children;\n }\n get document() {\n return this;\n }\n /**\n * Root element of this document, or `null` if this document is empty.\n */\n get root() {\n for (let child of this.children) {\n if (child instanceof XmlElement) {\n return child;\n }\n }\n return null;\n }\n /**\n * Text content of this document and all its descendants.\n */\n get text() {\n return this.children.map((child) => \"text\" in child ? child.text : \"\").join(\"\");\n }\n get type() {\n return XmlNode.TYPE_DOCUMENT;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n children: this.children.map((child) => child.toJSON())\n });\n }\n};\n\n// src/lib/XmlDocumentType.ts\nvar XmlDocumentType = class extends XmlNode {\n constructor(name, publicId, systemId, internalSubset) {\n super();\n this.name = name;\n this.publicId = publicId != null ? publicId : null;\n this.systemId = systemId != null ? systemId : null;\n this.internalSubset = internalSubset != null ? internalSubset : null;\n }\n get type() {\n return XmlNode.TYPE_DOCUMENT_TYPE;\n }\n toJSON() {\n let json = XmlNode.prototype.toJSON.call(this);\n json.name = this.name;\n for (let key of [\"publicId\", \"systemId\", \"internalSubset\"]) {\n if (this[key] !== null) {\n json[key] = this[key];\n }\n }\n return json;\n }\n};\n\n// src/lib/XmlError.ts\nvar XmlError = class extends Error {\n constructor(message, charIndex, xml) {\n let column = 1;\n let excerpt = \"\";\n let line = 1;\n for (let i = 0; i < charIndex; ++i) {\n let char = xml[i];\n if (char === \"\\n\") {\n column = 1;\n excerpt = \"\";\n line += 1;\n } else {\n column += 1;\n excerpt += char;\n }\n }\n let eol = xml.indexOf(\"\\n\", charIndex);\n excerpt += eol === -1 ? xml.slice(charIndex) : xml.slice(charIndex, eol);\n let excerptStart = 0;\n if (excerpt.length > 50) {\n if (column < 40) {\n excerpt = excerpt.slice(0, 50);\n } else {\n excerptStart = column - 20;\n excerpt = excerpt.slice(excerptStart, column + 30);\n }\n }\n super(\n `${message} (line ${line}, column ${column})\n ${excerpt}\n` + \" \".repeat(column - excerptStart + 1) + \"^\\n\"\n );\n this.column = column;\n this.excerpt = excerpt;\n this.line = line;\n this.name = \"XmlError\";\n this.pos = charIndex;\n }\n};\n\n// src/lib/XmlProcessingInstruction.ts\nvar XmlProcessingInstruction = class extends XmlNode {\n constructor(name, content = \"\") {\n super();\n this.name = name;\n this.content = content;\n }\n get type() {\n return XmlNode.TYPE_PROCESSING_INSTRUCTION;\n }\n toJSON() {\n return Object.assign(XmlNode.prototype.toJSON.call(this), {\n name: this.name,\n content: this.content\n });\n }\n};\n\n// src/lib/Parser.ts\nvar defaultMaxElementDepth = 256;\nvar emptyString2 = \"\";\nvar Parser = class {\n /**\n * @param xml XML string to parse.\n * @param options Parser options.\n */\n constructor(xml, options = {}) {\n this.depth = 0;\n var _a;\n let doc = this.document = new XmlDocument();\n this.m = doc;\n this.maxElementDepth = (_a = options.maxElementDepth) != null ? _a : defaultMaxElementDepth;\n this.g = options;\n this.c = new StringScanner(xml);\n if (this.g.includeOffsets) {\n doc.start = 0;\n doc.end = xml.length;\n }\n this.parse();\n }\n /**\n * Adds the given `XmlNode` as a child of `this.currentNode`.\n */\n k(node, charIndex) {\n node.parent = this.m;\n if (this.g.includeOffsets) {\n node.start = this.c.f(charIndex);\n node.end = this.c.f();\n }\n this.m.children.push(node);\n return true;\n }\n /**\n * Adds the given _text_ to the document, either by appending it to a\n * preceding `XmlText` node (if possible) or by creating a new `XmlText` node.\n *\n * When _normalize_ is `true` (the default), line breaks in _text_ are\n * normalized per section 2.11 of the XML spec. This must be `false` for text\n * that comes from a character or entity reference, since references aren't\n * subject to line break normalization.\n */\n y(text, charIndex, normalize = true) {\n let { children } = this.m;\n let { length } = children;\n if (normalize) {\n text = normalizeLineBreaks(text);\n }\n if (length > 0) {\n let prevNode = children[length - 1];\n if ((prevNode == null ? void 0 : prevNode.type) === XmlNode.TYPE_TEXT) {\n let textNode = prevNode;\n textNode.text += text;\n if (this.g.includeOffsets) {\n textNode.end = this.c.f();\n }\n return true;\n }\n }\n return this.k(new XmlText(text), charIndex);\n }\n /**\n * Consumes element attributes.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-starttags\n */\n H() {\n let attributes = /* @__PURE__ */ Object.create(null);\n while (this.e()) {\n let attrName = this.q();\n if (!attrName) {\n break;\n }\n let attrValue = this.t() && this.I();\n if (attrValue === false) {\n throw this.a(\"Attribute value expected\");\n }\n if (attrName in attributes) {\n throw this.a(`Duplicate attribute: ${attrName}`);\n }\n if (attrName === \"xml:space\" && attrValue !== \"default\" && attrValue !== \"preserve\") {\n throw this.a('Value of the `xml:space` attribute must be \"default\" or \"preserve\"');\n }\n attributes[attrName] = attrValue;\n }\n if (this.g.sortAttributes) {\n let attrNames = Object.keys(attributes).sort();\n let sortedAttributes = /* @__PURE__ */ Object.create(null);\n for (let i = 0; i < attrNames.length; ++i) {\n let attrName = attrNames[i];\n sortedAttributes[attrName] = attributes[attrName];\n }\n attributes = sortedAttributes;\n }\n return attributes;\n }\n /**\n * Consumes an `AttValue` (attribute value) if possible.\n *\n * @returns\n * Contents of the `AttValue` minus quotes, or `false` if nothing was\n * consumed. An empty string indicates that an `AttValue` was consumed but\n * was empty.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-AttValue\n */\n I() {\n let { c: scanner } = this;\n let quote = scanner.i();\n if (quote !== '\"' && quote !== \"'\") {\n return false;\n }\n scanner.l();\n let chars;\n let isClosed = false;\n let value = emptyString2;\n let regex = quote === '\"' ? attValueCharDoubleQuote : attValueCharSingleQuote;\n matchLoop: while (!scanner.D) {\n chars = scanner.x(regex);\n if (chars) {\n this.n(chars);\n value += chars.replace(attValueNormalizedWhitespace, \" \");\n }\n switch (scanner.i()) {\n case quote:\n isClosed = true;\n break matchLoop;\n case \"&\":\n value += this.E();\n continue;\n case \"<\":\n throw this.a(\"Unescaped `<` is not allowed in an attribute value\");\n default:\n break matchLoop;\n }\n }\n if (!isClosed) {\n throw this.a(\"Unclosed attribute\");\n }\n scanner.l();\n return value;\n }\n /**\n * Consumes a CDATA section if possible.\n *\n * @returns Whether a CDATA section was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-cdata-sect\n */\n J() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<![CDATA[\")) {\n return false;\n }\n let text = scanner.s(\"]]>\");\n this.n(text);\n if (!scanner.b(\"]]>\")) {\n throw this.a(\"Unclosed CDATA section\");\n }\n return this.g.preserveCdata ? this.k(new XmlCdata(normalizeLineBreaks(text)), startIndex) : this.y(text, startIndex);\n }\n /**\n * Consumes character data if possible.\n *\n * @returns Whether character data was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#dt-chardata\n */\n K() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n let charData = scanner.x(endCharData);\n if (!charData) {\n return false;\n }\n this.n(charData);\n if (scanner.i(3) === \"]]>\") {\n throw this.a(\"Element content may not contain the CDATA section close delimiter `]]>`\");\n }\n return this.y(charData, startIndex);\n }\n /**\n * Consumes a comment if possible.\n *\n * @param addToDocument\n * Whether the comment may be added to the document (subject to the\n * `preserveComments` option). This should be `false` for comments inside a\n * DTD internal subset.\n *\n * @returns Whether a comment was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Comment\n */\n z(addToDocument = true) {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<!--\")) {\n return false;\n }\n let content = scanner.s(\"--\");\n this.n(content);\n if (!scanner.b(\"-->\")) {\n if (scanner.i(2) === \"--\") {\n throw this.a(\"The string `--` isn't allowed inside a comment\");\n }\n throw this.a(\"Unclosed comment\");\n }\n return addToDocument && this.g.preserveComments ? this.k(new XmlComment(normalizeLineBreaks(content)), startIndex) : true;\n }\n /**\n * Consumes a reference in a content context if possible.\n *\n * This differs from `consumeReference()` in that a consumed reference will be\n * added to the document as a text node instead of returned.\n *\n * @returns Whether a reference was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#entproc\n */\n L() {\n let startIndex = this.c.d;\n let ref = this.E();\n return ref ? this.y(ref, startIndex, false) : false;\n }\n /**\n * Consumes a doctype declaration if possible.\n *\n * This is a loose implementation since DTDs are otherwise ignored. The\n * internal subset is only scanned closely enough to find where it ends.\n *\n * @returns Whether a doctype declaration was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#dtd\n */\n M() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<!DOCTYPE\")) {\n return false;\n }\n let name = this.e() && this.q();\n if (!name) {\n throw this.a(\"Expected a name\");\n }\n let publicId;\n let systemId;\n if (this.e()) {\n if (scanner.b(\"PUBLIC\")) {\n publicId = this.e() && this.N();\n if (publicId === false) {\n throw this.a(\"Expected a public identifier\");\n }\n }\n if (publicId !== void 0 || scanner.b(\"SYSTEM\")) {\n systemId = this.e() && this.r();\n if (systemId === false) {\n throw this.a(\"Expected a system identifier\");\n }\n this.e();\n }\n }\n let internalSubset;\n if (scanner.b(\"[\")) {\n internalSubset = this.O();\n if (!scanner.b(\"]\")) {\n throw this.a(\"Unclosed internal subset\");\n }\n this.e();\n }\n if (!scanner.b(\">\")) {\n throw this.a(\"Unclosed doctype declaration\");\n }\n return this.g.preserveDocumentType ? this.k(new XmlDocumentType(name, publicId, systemId, internalSubset), startIndex) : true;\n }\n /**\n * Consumes an element if possible.\n *\n * @returns Whether an element was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-element\n */\n F() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<\")) {\n return false;\n }\n let name = this.q();\n if (!name) {\n scanner.j(startIndex);\n return false;\n }\n if (!(this.depth < this.maxElementDepth)) {\n scanner.j(startIndex);\n throw this.a(`Maximum element depth of ${this.maxElementDepth} exceeded (see the \\`maxElementDepth\\` option)`);\n }\n let attributes = this.H();\n let isEmpty = !!scanner.b(\"/>\");\n let element = new XmlElement(name, attributes);\n element.parent = this.m;\n if (!isEmpty) {\n if (!scanner.b(\">\")) {\n throw this.a(`Unclosed start tag for element \\`${name}\\``);\n }\n this.m = element;\n this.depth += 1;\n do {\n this.K();\n } while (this.F() || this.L() || this.J() || this.A() || this.z());\n let endTagMark = scanner.d;\n let endTagName;\n if (!scanner.b(\"</\") || !(endTagName = this.q()) || endTagName !== name) {\n scanner.j(endTagMark);\n throw this.a(`Missing end tag for element ${name}`);\n }\n this.e();\n if (!scanner.b(\">\")) {\n throw this.a(`Unclosed end tag for element ${name}`);\n }\n this.m = element.parent;\n this.depth -= 1;\n }\n return this.k(element, startIndex);\n }\n /**\n * Consumes an `Eq` production if possible.\n *\n * @returns Whether an `Eq` production was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Eq\n */\n t() {\n this.e();\n if (this.c.b(\"=\")) {\n this.e();\n return true;\n }\n return false;\n }\n /**\n * Consumes the contents of a DTD internal subset, stopping before the closing\n * `]` or at the first content that isn't allowed in an internal subset.\n *\n * The end of the internal subset is the first `]` that isn't inside a\n * comment, processing instruction, or quoted literal, all of which may\n * legally contain `]>`. Since DTDs are otherwise ignored, markup declarations\n * are only scanned closely enough to find where they end.\n *\n * @returns Raw text of the internal subset.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-intSubset\n */\n O() {\n let { c: scanner } = this;\n let startByteIndex = scanner.f();\n while (this.e() || this.z(false) || this.A(false) || this.P() || this.Q()) {\n }\n return scanner.h.slice(startByteIndex, scanner.f());\n }\n /**\n * Consumes an element, attribute-list, entity, or notation declaration in a\n * DTD internal subset if possible.\n *\n * The declaration isn't fully parsed. Quoted literals are skipped as opaque\n * units, and the declaration ends at the first `>` outside a literal.\n *\n * @returns Whether a markup declaration was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-markupdecl\n */\n P() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (scanner.b(\"<!ATTLIST\")) {\n if (this.g.rejectAttributeListDeclarations) {\n scanner.j(startIndex);\n throw this.a(\"Attribute-list declarations aren't allowed when `rejectAttributeListDeclarations` is enabled\");\n }\n } else if (!scanner.b(\"<!ELEMENT\") && !scanner.b(\"<!ENTITY\") && !scanner.b(\"<!NOTATION\")) {\n return false;\n }\n for (; ; ) {\n this.n(scanner.x(markupDeclarationDelimiter));\n let char = scanner.i();\n if (char === \">\") {\n scanner.l();\n return true;\n }\n if (char === '\"' || char === \"'\") {\n this.r();\n continue;\n }\n throw this.a(\"Unclosed markup declaration\");\n }\n }\n /**\n * Consumes `Misc` content if possible.\n *\n * @returns Whether anything was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Misc\n */\n B() {\n return this.z() || this.A() || this.e();\n }\n /**\n * Consumes one or more `Name` characters if possible.\n *\n * @returns `Name` characters, or an empty string if none were consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Name\n */\n q() {\n return isNameStartChar(this.c.i()) ? this.c.w(isNameChar) : emptyString2;\n }\n /**\n * Consumes a parameter entity reference in a DTD internal subset if possible.\n *\n * Since parse-xml doesn't expand parameter entities, a reference is rejected\n * when `rejectAttributeListDeclarations` is enabled, because its replacement\n * text could contain an attribute-list declaration.\n *\n * @returns Whether a parameter entity reference was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-PEReference\n */\n Q() {\n let { c: scanner } = this;\n if (scanner.i() !== \"%\") {\n return false;\n }\n if (this.g.rejectAttributeListDeclarations) {\n throw this.a(\"Parameter entity references aren't allowed when `rejectAttributeListDeclarations` is enabled\");\n }\n scanner.l();\n if (!this.q() || !scanner.b(\";\")) {\n throw this.a(\"Invalid parameter entity reference\");\n }\n return true;\n }\n /**\n * Consumes a processing instruction if possible.\n *\n * @param addToDocument\n * Whether to add the processing instruction to the document. This should be\n * `false` for processing instructions inside a DTD internal subset.\n *\n * @returns Whether a processing instruction was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-pi\n */\n A(addToDocument = true) {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<?\")) {\n return false;\n }\n let name = this.q();\n if (name) {\n if (name.toLowerCase() === \"xml\") {\n scanner.j(startIndex);\n throw this.a(\"XML declaration isn't allowed here\");\n }\n } else {\n throw this.a(\"Invalid processing instruction\");\n }\n if (!this.e()) {\n if (scanner.b(\"?>\")) {\n return addToDocument ? this.k(new XmlProcessingInstruction(name), startIndex) : true;\n }\n throw this.a(\"Whitespace is required after a processing instruction name\");\n }\n let content = scanner.s(\"?>\");\n this.n(content);\n if (!scanner.b(\"?>\")) {\n throw this.a(\"Unterminated processing instruction\");\n }\n return addToDocument ? this.k(new XmlProcessingInstruction(name, normalizeLineBreaks(content)), startIndex) : true;\n }\n /**\n * Consumes a prolog if possible.\n *\n * @returns Whether a prolog was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-prolog-dtd\n */\n R() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n this.S();\n while (this.B()) {\n }\n if (this.M()) {\n while (this.B()) {\n }\n }\n return startIndex < scanner.d;\n }\n /**\n * Consumes a public identifier literal if possible.\n *\n * @returns\n * Value of the public identifier literal minus quotes, or `false` if\n * nothing was consumed. An empty string indicates that a public id literal\n * was consumed but was empty.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-PubidLiteral\n */\n N() {\n let startIndex = this.c.d;\n let value = this.r();\n if (value !== false && !/^[-\\x20\\r\\na-zA-Z0-9'()+,./:=?;!*#@$_%]*$/.test(value)) {\n this.c.j(startIndex);\n throw this.a(\"Invalid character in public identifier\");\n }\n return value;\n }\n /**\n * Consumes a reference if possible.\n *\n * This differs from `consumeContentReference()` in that a consumed reference\n * will be returned rather than added to the document.\n *\n * @returns\n * Parsed reference value, or `false` if nothing was consumed (to\n * distinguish from a reference that resolves to an empty string).\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-Reference\n */\n E() {\n let { c: scanner } = this;\n if (!scanner.b(\"&\")) {\n return false;\n }\n let ref = scanner.w(isReferenceChar);\n if (scanner.G() !== \";\") {\n throw this.a(\"Unterminated reference (a reference must end with `;`)\");\n }\n let parsedValue;\n if (ref[0] === \"#\") {\n let codePoint = ref[1] === \"x\" ? parseInt(ref.slice(2), 16) : parseInt(ref.slice(1), 10);\n if (isNaN(codePoint) || !/^#(?:x[0-9A-Fa-f]+|[0-9]+)$/.test(ref)) {\n throw this.a(\"Invalid character reference\");\n }\n if (!isXmlCodePoint(codePoint)) {\n throw this.a(\"Character reference resolves to an invalid character\");\n }\n parsedValue = String.fromCodePoint(codePoint);\n } else {\n parsedValue = predefinedEntities[ref];\n if (parsedValue === void 0) {\n let {\n ignoreUndefinedEntities,\n resolveUndefinedEntity\n } = this.g;\n let wrappedRef = `&${ref};`;\n if (resolveUndefinedEntity) {\n let resolvedValue = resolveUndefinedEntity(wrappedRef);\n if (resolvedValue !== null && resolvedValue !== void 0) {\n let type = typeof resolvedValue;\n if (type !== \"string\") {\n throw new TypeError(`\\`resolveUndefinedEntity()\\` must return a string, \\`null\\`, or \\`undefined\\`, but returned a value of type ${type}`);\n }\n return resolvedValue;\n }\n }\n if (ignoreUndefinedEntities) {\n return wrappedRef;\n }\n scanner.j(-wrappedRef.length);\n throw this.a(`Named entity isn't defined: ${wrappedRef}`);\n }\n }\n return parsedValue;\n }\n /**\n * Consumes a `SystemLiteral` if possible.\n *\n * A `SystemLiteral` is similar to an attribute value, but allows the\n * characters `<` and `&` and doesn't replace references.\n *\n * @returns\n * Value of the `SystemLiteral` minus quotes, or `false` if nothing was\n * consumed. An empty string indicates that a `SystemLiteral` was consumed\n * but was empty.\n *\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-SystemLiteral\n */\n r() {\n let { c: scanner } = this;\n let quote = scanner.b('\"') || scanner.b(\"'\");\n if (!quote) {\n return false;\n }\n let value = scanner.s(quote);\n this.n(value);\n if (!scanner.b(quote)) {\n throw this.a(\"Missing end quote\");\n }\n return value;\n }\n /**\n * Consumes one or more whitespace characters if possible.\n *\n * @returns Whether any whitespace characters were consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#white\n */\n e() {\n return !!this.c.w(isWhitespace);\n }\n /**\n * Consumes an XML declaration if possible.\n *\n * @returns Whether an XML declaration was consumed.\n * @see https://www.w3.org/TR/2008/REC-xml-20081126/#NT-XMLDecl\n */\n S() {\n let { c: scanner } = this;\n let startIndex = scanner.d;\n if (!scanner.b(\"<?xml\")) {\n return false;\n }\n if (isNameChar(scanner.i())) {\n scanner.j(startIndex);\n return false;\n }\n if (!this.e()) {\n throw this.a(\"Invalid XML declaration\");\n }\n let version = !!scanner.b(\"version\") && this.t() && this.r();\n if (version === false) {\n throw this.a(\"XML version is missing or invalid\");\n } else if (!/^1\\.[0-9]+$/.test(version)) {\n throw this.a(\"Invalid character in version number\");\n }\n let encoding;\n let standalone;\n let hasWhitespace = this.e();\n if (hasWhitespace && scanner.b(\"encoding\")) {\n let value = this.t() && this.r();\n if (value === false) {\n throw this.a(\"Invalid or unclosed XML declaration\");\n } else if (!/^[A-Za-z][\\w.-]*$/.test(value)) {\n throw this.a(\"Invalid character in encoding name\");\n }\n encoding = value;\n hasWhitespace = this.e();\n }\n if (hasWhitespace && scanner.b(\"standalone\")) {\n let value = this.t() && this.r();\n if (value === false) {\n throw this.a(\"Invalid or unclosed XML declaration\");\n } else if (value !== \"yes\" && value !== \"no\") {\n throw this.a('Only \"yes\" and \"no\" are permitted as values of `standalone`');\n }\n standalone = value;\n this.e();\n }\n if (!scanner.b(\"?>\")) {\n throw this.a(\"Invalid or unclosed XML declaration\");\n }\n return this.g.preserveXmlDeclaration ? this.k(new XmlDeclaration(version, encoding, standalone), startIndex) : true;\n }\n /**\n * Returns an `XmlError` for the current scanner position.\n */\n a(message) {\n let { c: scanner } = this;\n return new XmlError(message, scanner.d, scanner.h);\n }\n /**\n * Parses the XML input.\n */\n parse() {\n this.c.b(\"\\uFEFF\");\n this.R();\n if (!this.F()) {\n throw this.a(\"Root element is missing or invalid\");\n }\n while (this.B()) {\n }\n if (!this.c.D) {\n throw this.a(\"Extra content at the end of the document\");\n }\n }\n /**\n * Throws an invalid character error if any character in the given _string_\n * isn't a valid XML character.\n */\n n(string) {\n let { length } = string;\n for (let i = 0; i < length; ++i) {\n let cp = string.codePointAt(i);\n if (!isXmlCodePoint(cp)) {\n this.c.j(-[...string.slice(i)].length);\n throw this.a(\"Invalid character\");\n }\n if (cp > 65535) {\n i += 1;\n }\n }\n }\n};\nfunction normalizeLineBreaks(text) {\n return text.includes(\"\\r\") ? text.replace(lineBreakToNormalize, \"\\n\") : text;\n}\n\n// src/index.ts\nfunction parseXml(xml, options) {\n return new Parser(xml, options).document;\n}\nexport {\n XmlCdata,\n XmlComment,\n XmlDeclaration,\n XmlDocument,\n XmlDocumentType,\n XmlElement,\n XmlError,\n XmlNode,\n XmlProcessingInstruction,\n XmlText,\n parseXml\n};\n","import { BaerlyError } from \"@baerly/protocol\";\nimport { parseXml, type XmlDocument, type XmlElement, type XmlText } from \"@rgrove/parse-xml\";\n\n/**\n * Subset of S3's `ListObjectsV2CommandOutput` produced by\n * {@link parseListObjectsV2CommandOutput}. Field names mirror the\n * S3 REST API exactly (PascalCase) so the parser stays a thin shape\n * over the wire format.\n */\nexport interface ParsedListObjectsV2Output {\n Contents?: Array<{ ETag?: string; Key?: string; LastModified?: Date; Generation?: string }>;\n NextContinuationToken?: string;\n}\n\n/**\n * `<Code>` / `<Message>` extracted from an S3\n * `<Error>…</Error>` response body by {@link parseS3Error}. Field\n * names mirror the S3 REST API (PascalCase), matching the convention\n * of {@link ParsedListObjectsV2Output}.\n */\nexport interface ParsedS3Error {\n Code?: string;\n Message?: string;\n}\n\n// --- parse-xml helpers ---\n\n// Strip any namespace prefix: \"s3:Contents\" -> \"Contents\", \"Contents\" -> \"Contents\".\n// The `includes(\":\")` guard makes the `split(\":\")[1]!` non-null assertion safe.\nconst localName = (name: string): string => (name.includes(\":\") ? name.split(\":\")[1]! : name);\n\n// Type predicates narrowing an XmlNode child to a concrete node class.\n// @rgrove/parse-xml types the `type` discriminant as `string` (not a string\n// literal), so `node.type === \"element\"` does NOT narrow the child union on its\n// own. These localize the one unavoidable assertion behind a checked predicate\n// instead of scattering `as XmlElement` / `as XmlText` casts at each use site.\nconst isElement = (node: XmlElement[\"children\"][number]): node is XmlElement =>\n node.type === \"element\";\nconst isText = (node: XmlElement[\"children\"][number]): node is XmlText => node.type === \"text\";\n\n// Return the first XmlElement child of a document or element whose local name\n// (after any namespace prefix) matches `name`. This makes traversal\n// namespace-agnostic: both `<Error>` and `<ns:Error>` match name \"Error\".\nconst child = (el: XmlElement, name: string): XmlElement | undefined => {\n for (const node of el.children) {\n if (isElement(node) && localName(node.name) === name) {\n return node;\n }\n }\n return undefined;\n};\n\n// Concatenate the direct text child node text values of an element.\n// @rgrove/parse-xml resolves the 5 predefined XML entities (&amp; &lt; &gt;\n// &quot; &apos;) and decimal/hex numeric character references (e.g. Minio's\n// &#34; ETags) by default. Under the default `preserveCdata: false` (which is\n// how we call parseXml), any CDATA section is merged into the element's adjacent\n// text nodes and surfaces as an XmlText (type \"text\"), so the \"text\" branch\n// captures it — there is never a standalone \"cdata\" node. Entities inside a\n// CDATA section are NOT decoded (CDATA is literal), which is the correct S3\n// behavior. We intentionally do NOT decode HTML named entities (&nbsp; etc.) —\n// S3 wire data is XML, not HTML, so this is more spec-correct.\nconst textOf = (el: XmlElement | undefined): string | undefined => {\n if (el === undefined) {\n return undefined;\n }\n let result = \"\";\n for (const node of el.children) {\n if (isText(node)) {\n result += node.text;\n }\n }\n return result === \"\" ? undefined : result;\n};\n\n// Return the first-element-child of an XmlDocument. Unlike `XmlDocument.root`\n// (which is an XmlElement | null getter), this avoids potential null handling\n// confusion by returning undefined on an empty document.\nconst docRoot = (doc: XmlDocument): XmlElement | undefined => doc.root ?? undefined;\n\n// The list request sets `encoding-type=url`, so S3 URL-encodes the **key\n// family only** (Key/Prefix/Delimiter/StartAfter) in the response,\n// including spaces as `+`. Use this to reverse both steps. Do NOT apply it\n// to ETag or NextContinuationToken — S3 leaves those verbatim, and a\n// continuation token routinely contains literal `+` that the `.replace`\n// step would mangle into a space (corrupting pagination on large buckets).\nconst xmlVal = (el: XmlElement | undefined, name: string): string | undefined => {\n const v = el !== undefined ? textOf(child(el, name)) : undefined;\n if (v === undefined || v === \"\") {\n return undefined;\n }\n // A well-formed encoding-type=url response only ever contains valid\n // percent-escapes. A bare `%` or an invalid pair (`%ZZ`) makes\n // decodeURIComponent throw a raw URIError — catch it and re-raise as a\n // typed BaerlyError so the storage layer surfaces a catchable error rather\n // than an unhandled runtime exception. See docs/spec/s3-xml-escaping-cases.md.\n try {\n return decodeURIComponent(v.replace(/\\+/g, \" \"));\n } catch {\n throw new BaerlyError(\"InvalidResponse\", `Malformed percent-escape in S3 <${name}>: ${v}`);\n }\n};\n\n// Read a field verbatim. Used for everything S3 does NOT URL-encode:\n// error-body `Code`/`Message`, list `ETag`/`LastModified`, and\n// `NextContinuationToken` — running any of these through `xmlVal`'s\n// `decodeURIComponent` / `+`→space would corrupt literal `+` and `%`.\nconst rawXmlVal = (el: XmlElement | undefined, name: string): string | undefined => {\n return el !== undefined ? textOf(child(el, name)) : undefined;\n};\n\n/**\n * Build a {@link ParsedS3Error} from the element that directly carries\n * the `<Code>` / `<Message>` children — `<Error>` for S3, the inner\n * `<Error>` for STS. Returns `undefined` when neither child is present\n * so callers can fall back to the raw status. Shared by\n * {@link parseS3Error} and {@link parseStsError}, which differ only in\n * how they locate that element.\n */\nconst codeMessageFrom = (el: XmlElement): ParsedS3Error | undefined => {\n const code = rawXmlVal(el, \"Code\");\n const message = rawXmlVal(el, \"Message\");\n if (code === undefined && message === undefined) {\n return undefined;\n }\n return {\n ...(code !== undefined && { Code: code }),\n ...(message !== undefined && { Message: message }),\n };\n};\n\n/**\n * Parse an S3 `<Error><Code>…</Code><Message>…</Message></Error>`\n * body. Returns `undefined` when the body is not a recognizable S3\n * error document (empty, HTML, a success payload, or a DTD), so\n * callers can fall back to the raw response text. This never throws:\n * it runs on a path that is already reporting an error.\n */\nexport const parseS3Error = (xml: string): ParsedS3Error | undefined => {\n // Skip non-error bodies; refuse DTDs before parsing — see the DTD-guard\n // note above parseListObjectsV2CommandOutput.\n if (!/<Error\\b/i.test(xml) || /<!DOCTYPE\\b/i.test(xml)) {\n return undefined;\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n return undefined;\n }\n // The root element must be <Error> (possibly namespace-prefixed).\n if (root === undefined) {\n return undefined;\n }\n if (localName(root.name) !== \"Error\") {\n return undefined;\n }\n return codeMessageFrom(root);\n};\n\n/**\n * Parse an STS `<ErrorResponse><Error><Code>…</Code><Message>…</Message>\n * </Error></ErrorResponse>` body (the shape STS returns on a failed\n * `AssumeRoleWithWebIdentity` — e.g. `InvalidIdentityToken`,\n * `ExpiredTokenException`, `AccessDenied`). Returns `undefined` when the body\n * is not a recognizable STS error document (empty, HTML, a success payload, or\n * a DTD), so callers can fall back to the bare status. Like {@link parseS3Error}\n * this never throws — it runs on a path that is already reporting an error.\n *\n * Note the nesting differs from S3: STS wraps `<Error>` inside `<ErrorResponse>`.\n */\nexport const parseStsError = (xml: string): ParsedS3Error | undefined => {\n if (!/<Error\\b/i.test(xml) || /<!DOCTYPE\\b/i.test(xml)) {\n return undefined;\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n return undefined;\n }\n if (root === undefined) {\n return undefined;\n }\n // STS wraps <Error> inside <ErrorResponse>; locate the inner <Error> child.\n const errorEl = child(root, \"Error\");\n if (errorEl === undefined) {\n return undefined;\n }\n return codeMessageFrom(errorEl);\n};\n\n/**\n * `<Credentials>` extracted from an STS\n * `<AssumeRoleWithWebIdentityResponse>` body by\n * {@link parseAssumeRoleWithWebIdentity}. Field names mirror the STS REST\n * API (PascalCase), matching the convention of {@link ParsedS3Error}.\n */\nexport interface ParsedWebIdentityCredentials {\n AccessKeyId?: string;\n SecretAccessKey?: string;\n SessionToken?: string;\n Expiration?: string;\n}\n\n/**\n * Parse an STS `AssumeRoleWithWebIdentity` success body, returning the\n * `<Credentials>` block. Reuses the hardened, DTD-guarded parser;\n * throws `InvalidResponse` on a DTD or unparseable XML. Missing fields come\n * back `undefined` so the caller can map them to its own `InvalidResponse`.\n *\n * Unlike {@link parseListObjectsV2CommandOutput}, the error on unparseable\n * XML must NOT echo the body: a success-shaped STS body carries the plaintext\n * `SecretAccessKey`/`SessionToken`, so folding it into a thrown-then-logged\n * error would leak live credentials.\n */\nexport const parseAssumeRoleWithWebIdentity = (xml: string): ParsedWebIdentityCredentials => {\n if (/<!DOCTYPE\\b/i.test(xml)) {\n throw new BaerlyError(\"InvalidResponse\", \"DTD not allowed in STS XML responses\");\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n // No body in the message — see the note above; it may contain live creds.\n throw new BaerlyError(\"InvalidResponse\", \"unparseable STS credentials response\");\n }\n // Traverse: <AssumeRoleWithWebIdentityResponse>\n // <AssumeRoleWithWebIdentityResult>\n // <Credentials>\n const resultEl = root !== undefined ? child(root, \"AssumeRoleWithWebIdentityResult\") : undefined;\n const credsEl = resultEl !== undefined ? child(resultEl, \"Credentials\") : undefined;\n return {\n AccessKeyId: rawXmlVal(credsEl, \"AccessKeyId\"),\n SecretAccessKey: rawXmlVal(credsEl, \"SecretAccessKey\"),\n SessionToken: rawXmlVal(credsEl, \"SessionToken\"),\n Expiration: rawXmlVal(credsEl, \"Expiration\"),\n };\n};\n\n// `new Date(badString)` yields an Invalid Date (a non-null Date whose\n// getTime() is NaN) rather than throwing — surface `undefined` for a\n// malformed `LastModified` rather than propagating a NaN-valued Date.\n//\n// Nothing downstream reads this today: `StorageListEntry` is `key` +\n// `etag` only, so both `S3HttpStorage.list` and `GcsHttpStorage.list`\n// drop the parsed value on the floor. It is retained only as a faithful\n// mirror of the S3 list-response shape. If you are here to add a\n// consumer, read the `StorageListEntry` JSDoc first — GC used to anchor\n// its `due_at` on this and that was a bug.\nconst parseLastModified = (lm: string | undefined): Date | undefined => {\n if (lm === undefined) {\n return undefined;\n }\n const d = new Date(lm);\n return Number.isNaN(d.getTime()) ? undefined : d;\n};\n\n// DTD guard: reject any DOCTYPE before @rgrove/parse-xml sees the bytes. S3/R2/\n// MinIO/GCS never emit a DOCTYPE here, so one is always a bug or an attack —\n// this defangs the DOCTYPE entity vectors (XXE, billion-laughs, the\n// CVE-2026-25896 entity-shadow). @rgrove/parse-xml is safe-by-design (refuses\n// DTD entity definitions), but the regex guard is parser-independent\n// defense-in-depth and independently covers the entity-expansion CVE class.\nexport const parseListObjectsV2CommandOutput = (xml: string): ParsedListObjectsV2Output => {\n if (/<!DOCTYPE\\b/i.test(xml)) {\n throw new BaerlyError(\"InvalidResponse\", \"DTD not allowed in S3 XML responses\");\n }\n let root: XmlElement | undefined;\n try {\n root = docRoot(parseXml(xml));\n } catch {\n throw new BaerlyError(\"InvalidResponse\", `Invalid XML: ${xml}`);\n }\n if (root === undefined) {\n return {};\n }\n // The root element must be <ListBucketResult> (possibly namespace-prefixed).\n // This restores main's `result.ListBucketResult ?? {}` structural guard and\n // matches the sibling error parsers' root checks: a non-list body returns {}.\n if (localName(root.name) !== \"ListBucketResult\") {\n return {};\n }\n // Force-array for Contents: collect all direct <Contents> element children.\n // This replaces the old `isArray: (name) => name === \"Contents\"` config.\n // Namespace-agnostic (matches `child()`), so `<s3:Contents>` also collects.\n const contentEls = root.children\n .filter(isElement)\n .filter((c) => localName(c.name) === \"Contents\");\n\n return {\n Contents: contentEls.map((contentEl) => {\n return {\n ETag: rawXmlVal(contentEl, \"ETag\"),\n Key: xmlVal(contentEl, \"Key\"),\n LastModified: parseLastModified(rawXmlVal(contentEl, \"LastModified\")),\n // GCS's list XML carries a `<Generation>` element per object (its\n // opaque version token) that S3/R2 never emit — undefined there, so\n // this is inert for the S3 path. `GcsHttpStorage.list` prefers it as\n // the entry etag so a list etag equals the generation `get`/`put`\n // return, matching the universal list-etag == version-token contract.\n Generation: rawXmlVal(contentEl, \"Generation\"),\n };\n }),\n NextContinuationToken: rawXmlVal(root, \"NextContinuationToken\"),\n };\n};\n","import { BaerlyError, RETRY_AFTER_MAX_SECONDS } from \"@baerly/protocol\";\nimport { parseS3Error } from \"./xml.ts\";\n\n/**\n * Parse an HTTP `Retry-After` header into a non-negative seconds value,\n * clamped to {@link RETRY_AFTER_MAX_SECONDS}. Returns `undefined` if\n * the header is absent, malformed, or whitespace.\n *\n * RFC 7231 §7.1.3 admits two forms: delta-seconds (non-negative\n * integer) and HTTP-date. Both are accepted; dates in the past return\n * `0`. Fractional seconds, negatives, and arbitrary strings reject.\n *\n * The `now` injection point exists for the unit test; production\n * callers should pass nothing.\n */\nexport function parseRetryAfter(\n header: string | null,\n now: () => number = Date.now,\n): number | undefined {\n if (header === null) {\n return undefined;\n }\n const trimmed = header.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n if (/^\\d+$/.test(trimmed)) {\n const n = Number.parseInt(trimmed, 10);\n return Number.isFinite(n) ? Math.min(n, RETRY_AFTER_MAX_SECONDS) : undefined;\n }\n // RFC 7231 §7.1.1.1 HTTP-date formats (IMF-fixdate, RFC 850, asctime)\n // all contain alphabetic month/day-of-week tokens. Gating on a letter\n // avoids V8's lenient `Date.parse` accepting things like \"5.5\".\n if (!/[a-z]/i.test(trimmed)) {\n return undefined;\n }\n const t = Date.parse(trimmed);\n if (Number.isNaN(t)) {\n return undefined;\n }\n const seconds = Math.max(0, Math.ceil((t - now()) / 1000));\n return Math.min(seconds, RETRY_AFTER_MAX_SECONDS);\n}\n\nexport const retryAfterCause = (res: Response): { retryAfterSeconds?: number } => {\n const hint = parseRetryAfter(res.headers.get(\"Retry-After\"));\n return hint !== undefined ? { retryAfterSeconds: hint } : {};\n};\n\n// Detail suffix for a non-status-mapped XML error response (S3 and GCS's\n// native XML API share the same `<Error><Code>…</Error>` body shape). When\n// the body is a parseable document, surface the store's own error code (and\n// message) instead of concatenating the raw XML blob into the thrown\n// message; otherwise fall back to the raw text.\nexport const xmlErrorDetail = (status: number, body: string): string => {\n const parsed = parseS3Error(body);\n if (parsed !== undefined) {\n const code = parsed.Code ?? \"UnknownError\";\n return parsed.Message !== undefined\n ? `${status} ${code}: ${parsed.Message}`\n : `${status} ${code}`;\n }\n return `${status} ${body}`;\n};\n\n/**\n * Shared status→{@link BaerlyError} mapping for the S3/GCS XML adapters, so\n * the retryable set (`429`/`≥500`) can't drift between them. Store-specific\n * statuses (GCS `412`; S3 `409`/`404`-with-`If-Match`) are handled inline\n * first; the rest route here: `403`→AccessDenied (permanent), `429`/`≥500`→\n * retryable NetworkError carrying `{status, retryAfterSeconds?}`, else\n * InvalidResponse. Callers `throw` the result; consumes `res.text()` on the\n * non-`403` paths. A throttle (`429`, or S3's `503 SlowDown`) also carries\n * `throttled: true`: the store refused the request without applying it.\n */\nexport const mapStorageError = async (\n res: Response,\n verb: string,\n key: string,\n): Promise<BaerlyError> => {\n if (res.status === 403) {\n return new BaerlyError(\"AccessDenied\", `${verb} ${key}: 403`);\n }\n if (res.status === 429 || res.status >= 500) {\n const body = await res.text();\n return new BaerlyError(\"NetworkError\", `${verb} ${key}: ${res.status} ${body}`, {\n cause: {\n status: res.status,\n ...retryAfterCause(res),\n ...(isThrottle(res.status, body) && { throttled: true }),\n },\n });\n }\n return new BaerlyError(\n \"InvalidResponse\",\n `${verb} ${key}: ${xmlErrorDetail(res.status, await res.text())}`,\n );\n};\n\nconst isThrottle = (status: number, body: string): boolean =>\n status === 429 || (status === 503 && parseS3Error(body)?.Code === \"SlowDown\");\n\n/**\n * S3 error codes for an expired STS session token. S3 answers these with\n * HTTP 400, not 403; AWS SDKs treat them as a signal to refresh credentials.\n */\nconst EXPIRED_TOKEN_CODES: ReadonlySet<string> = new Set([\"ExpiredToken\", \"TokenRefreshRequired\"]);\n\n/**\n * Read the S3 expired-token code from a `400` response, or `undefined` for\n * any other response. Reads a clone, so `res` stays readable for\n * {@link mapS3StorageError}.\n */\nexport const s3ExpiredTokenCode = async (res: Response): Promise<string | undefined> => {\n if (res.status !== 400) {\n return undefined;\n }\n const code = parseS3Error(await res.clone().text())?.Code;\n return code !== undefined && EXPIRED_TOKEN_CODES.has(code) ? code : undefined;\n};\n\n/**\n * {@link mapStorageError} for the S3 adapter: a `400` carrying an\n * expired-token code is a credentials failure, so it maps to the permanent\n * `AccessDenied` whose message carries the S3 code, the state and the remedy;\n * every other response maps as {@link mapStorageError} does.\n */\nexport const mapS3StorageError = async (\n res: Response,\n verb: string,\n key: string,\n): Promise<BaerlyError> => {\n if ((await s3ExpiredTokenCode(res)) !== undefined) {\n return new BaerlyError(\n \"AccessDenied\",\n `${verb} ${key}: ${xmlErrorDetail(400, await res.text())} — the credentials provider returned expired credentials even after a refresh; it should return fresh credentials with an accurate \\`expiration\\`.`,\n {\n resolution:\n \"Return fresh credentials with an accurate `expiration` from the credentials provider; static session credentials must be replaced.\",\n },\n );\n }\n return mapStorageError(res, verb, key);\n};\n","import {\n BaerlyError,\n assertValidStorageKey,\n retryStorageCall,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n currentRequestHold,\n currentRequestLedger,\n} from \"@baerly/protocol\";\nimport { mapS3StorageError, retryAfterCause, s3ExpiredTokenCode } from \"./http-transport.ts\";\nimport { parseListObjectsV2CommandOutput } from \"./xml.ts\";\n\n/**\n * Drop a weak-validator prefix from a response ETag. R2's S3 API compresses\n * `application/json` GET responses over ~159 bytes and returns the stored\n * ETag as `W/\"<md5>\"`; `If-Match` with that weak value always fails, while\n * the bare `\"<md5>\"` matches the stored object (and a wrong one is still\n * refused). `current.json` and `gc/pending.json` advance by exactly that\n * get-then-`ifMatch`, so without this no fold lands on R2 over S3.\n */\nconst strongEtag = (etag: string): string => (etag.startsWith(\"W/\") ? etag.slice(2) : etag);\n\n/** State shared by the attempts of one storage call. */\ninterface CallState {\n /** The call already refreshed credentials after an expired-token response. */\n refreshed: boolean;\n}\n\n/**\n * Construction-time options for {@link S3HttpStorage}. Everything is\n * optional except `endpoint` and `bucket`; the consumer chooses how\n * to satisfy `fetch` (browser/Node global vs. injected) and `sign`\n * (anonymous Minio vs. SigV4-signed via aws4fetch).\n */\nexport interface S3HttpStorageOptions {\n /**\n * S3 endpoint URL, e.g. `https://s3.us-east-1.amazonaws.com` or\n * `http://127.0.0.1:9102` (Minio). Trailing slashes are trimmed.\n */\n endpoint: string;\n /** S3 bucket name. */\n bucket: string;\n /**\n * `fetch` implementation. Defaults to `globalThis.fetch.bind(globalThis)`.\n * Tests pass a `vi.fn()` stub.\n */\n fetch?: typeof fetch;\n /**\n * Signs requests before send. Pass `undefined` for anonymous\n * (Minio without creds). The seam is `(req) => Promise<req>` so\n * SigV4 implementations like `aws4fetch.AwsClient.sign` plug in\n * directly.\n */\n sign?: (req: Request) => Promise<Request>;\n /**\n * Retries after the first attempt, for throttled and transient failures\n * alike (and per `list` page). Default `STORAGE_RETRY_MAX_ATTEMPTS - 1`\n * (2, so 3 attempts in total); `0` sends each request once. Must be a\n * non-negative integer; any other value makes each request reject with\n * `InvalidConfig` before it is sent.\n */\n retries?: number;\n /**\n * Backoff base in ms, overriding both default bases (50 ms after a\n * transient failure, 1 s after a throttle). Full jitter applies either\n * way. Omit for the default policy.\n */\n backoffMs?: number;\n}\n\nlet attachInvalidate: (storage: S3HttpStorage, invalidate: (signed: Request) => void) => void;\n\n/**\n * Internal wiring (not re-exported from the package entries): make `storage`\n * drop the credentials that signed a request (`refreshingSigner(...).invalidate`)\n * and resend once per storage call when S3 answers `400 ExpiredToken` /\n * `TokenRefreshRequired`. The resend is charged to the request ledger like any\n * attempt; a second rejection, or storage without this wiring, is\n * `AccessDenied` naming the S3 code.\n */\nexport const withCredentialInvalidation = (\n storage: S3HttpStorage,\n invalidate: (signed: Request) => void,\n): S3HttpStorage => {\n attachInvalidate(storage, invalidate);\n return storage;\n};\n\n/**\n * `Storage` impl that speaks the S3 REST API directly. Works against\n * any S3-compatible endpoint — AWS S3, R2 (S3-compat), Minio. Does not\n * depend on any AWS SDK. GCS is NOT supported over this S3-interop path\n * (its conditional-write semantics can't linearize the commit log); use\n * the native `GcsHttpStorage` adapter instead.\n *\n * Authentication is plugged in via the `sign` callback; this class\n * itself does no SigV4. For Cloudflare Workers, the R2 binding fast\n * path lives in `@baerly/adapter-cloudflare`.\n */\nexport class S3HttpStorage implements Storage {\n readonly #endpoint: string;\n readonly #bucket: string;\n readonly #fetch: typeof fetch;\n readonly #sign?: (req: Request) => Promise<Request>;\n #invalidate?: (signed: Request) => void;\n readonly #retries: number | undefined;\n readonly #backoffMs: number | undefined;\n\n constructor(options: S3HttpStorageOptions) {\n this.#endpoint = options.endpoint.replace(/\\/+$/, \"\");\n this.#bucket = options.bucket;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#sign = options.sign;\n this.#retries = options.retries;\n this.#backoffMs = options.backoffMs;\n }\n\n static {\n attachInvalidate = (storage, invalidate) => {\n storage.#invalidate = invalidate;\n };\n }\n\n #objectUrl(key: string): string {\n // Choke point for every key-addressing verb — reject unaddressable\n // `.`/`..`/empty keys before URL normalization turns them into a\n // bucket-root 403. @see storage-compatibility.md \"Key namespace\".\n assertValidStorageKey(key);\n return `${this.#endpoint}/${this.#bucket}/${encodeURIComponent(key)}`;\n }\n\n async #send(req: Request): Promise<{ res: Response; signed: Request }> {\n const signed = this.#sign ? await this.#sign(req) : req;\n try {\n return { res: await this.#fetch(signed), signed };\n } catch (error) {\n // A cancelled call surfaces as the caller's abort reason, whatever\n // it is, not a retryable NetworkError; the retry loop ends on it.\n if (error instanceof BaerlyError || signed.signal.aborted) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n throw new BaerlyError(\"NetworkError\", msg, { cause: error });\n }\n }\n\n /**\n * Send one request. An expired-session-token `400` drops the credentials\n * that signed it and resends once per storage call (`call` is shared by the\n * attempts of one `#retry`, so the retry policy cannot add a second\n * refresh). The resend is charged to the ledger here because it is a\n * request `retryStorageCall` did not count. A second expired-token\n * response is returned as is and maps to `AccessDenied`.\n */\n async #dispatch(make: () => Request, call: CallState): Promise<Response> {\n const first = await this.#send(make());\n if (\n this.#invalidate === undefined ||\n call.refreshed ||\n (await s3ExpiredTokenCode(first.res)) === undefined\n ) {\n return first.res;\n }\n // Release the socket held by the unread original body (the code was read from a clone).\n await first.res.body?.cancel();\n // A resend after the caller aborted would only re-sign and fail.\n first.signed.signal.throwIfAborted();\n call.refreshed = true;\n this.#invalidate(first.signed);\n currentRequestLedger()?.acquire(\"external\", currentRequestHold());\n const second = await this.#send(make());\n return second.res;\n }\n\n #retry<T>(\n fn: (call: CallState) => Promise<T>,\n opts?: Pick<StoragePutOptions, \"ifMatch\" | \"ifNoneMatch\" | \"signal\">,\n ): Promise<T> {\n const call: CallState = { refreshed: false };\n return retryStorageCall(() => fn(call), {\n ...(this.#retries !== undefined && { retries: this.#retries }),\n ...(this.#backoffMs !== undefined && { backoffMs: this.#backoffMs }),\n conditionalCreate: opts?.ifNoneMatch === \"*\",\n // An If-Match PUT is never resent: a resend after a lost ack would\n // see its own write as a 412.\n compareAndSwap: opts?.ifMatch !== undefined && opts.ifNoneMatch !== \"*\",\n // Every request leaves through `fetch`: the ledger's external pool.\n pool: \"external\",\n // Any caller abort ends the call; the loop never resends past it.\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n });\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n return this.#retry(async (call) => {\n const res = await this.#dispatch(\n () => new Request(url, { method: \"GET\", signal: opts?.signal ?? null }),\n call,\n );\n switch (res.status) {\n case 200: {\n const etag = res.headers.get(\"ETag\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `GET ${key}: missing ETag`);\n }\n const body = new Uint8Array(await res.arrayBuffer());\n return { body, etag: strongEtag(etag) };\n }\n case 404: {\n return null;\n }\n default: {\n throw await mapS3StorageError(res, \"GET\", key);\n }\n }\n }, opts);\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n const headers = new Headers();\n headers.set(\"Content-Type\", opts?.contentType ?? \"application/octet-stream\");\n if (opts?.ifMatch !== undefined) {\n headers.set(\"If-Match\", opts.ifMatch);\n }\n if (opts?.ifNoneMatch === \"*\") {\n headers.set(\"If-None-Match\", \"*\");\n }\n return this.#retry(async (call) => {\n const res = await this.#dispatch(\n () =>\n new Request(url, {\n method: \"PUT\",\n headers,\n // TS lib.dom narrows BodyInit and a generic `Uint8Array<ArrayBufferLike>`\n // is not assignable; the runtime accepts it.\n body: body as BodyInit,\n signal: opts?.signal ?? null,\n }),\n call,\n );\n if (res.status === 412) {\n throw new BaerlyError(\"WriteConflict\", `PUT ${key}: precondition failed`);\n }\n // AWS S3 returns 409 ConditionalRequestConflict when concurrent\n // conditional writes race: a create (If-None-Match:\"*\") or a CAS\n // (If-Match). Minio returns 412. 409 means the write was contended\n // and may NOT have landed, so it maps to a retryable NetworkError.\n // For a create, this adapter's retry re-issues the same PUT, which\n // resolves to 200 (we win) or 412 (key changed/present →\n // WriteConflict → the Writer's readback adopts or re-probes); a\n // direct WriteConflict here would adopt-read a possibly-absent\n // entry. A CAS gets no resend, so its caller sees the NetworkError.\n if (res.status === 409 && (opts?.ifNoneMatch === \"*\" || opts?.ifMatch !== undefined)) {\n throw new BaerlyError(\n \"NetworkError\",\n `PUT ${key}: 409 ConditionalRequestConflict (contended conditional write; retryable)`,\n { cause: { status: res.status, ...retryAfterCause(res) } },\n );\n }\n // S3-compatible servers diverge on `If-Match` against a missing\n // key: AWS S3 returns 412, Minio returns 404 (NoSuchKey). Map\n // 404-with-ifMatch to the same `WriteConflict` semantic so consumers\n // don't have to special-case the wire reply.\n if (res.status === 404 && opts?.ifMatch !== undefined) {\n throw new BaerlyError(\n \"WriteConflict\",\n `PUT ${key}: precondition failed (ifMatch=${opts.ifMatch} but key does not exist)`,\n );\n }\n if (res.status !== 200 && res.status !== 204) {\n throw await mapS3StorageError(res, \"PUT\", key);\n }\n const etag = res.headers.get(\"ETag\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `PUT ${key}: missing ETag`);\n }\n const dateStr = res.headers.get(\"Date\");\n const result: { etag: string; serverDate?: Date } = { etag: strongEtag(etag) };\n if (dateStr !== null) {\n result.serverDate = new Date(dateStr);\n }\n return result;\n }, opts);\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n await this.#retry(async (call) => {\n const res = await this.#dispatch(\n () => new Request(url, { method: \"DELETE\", signal: opts?.signal ?? null }),\n call,\n );\n // 200 / 204 / 404 → success (idempotent); any other status is a real\n // failure (403 → AccessDenied, 429/≥500 → retryable NetworkError, else\n // InvalidResponse) rather than a silently-swallowed non-2xx.\n if (res.status !== 200 && res.status !== 204 && res.status !== 404) {\n throw await mapS3StorageError(res, \"DELETE\", key);\n }\n }, opts);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n let yielded = 0;\n let continuationToken: string | undefined;\n const startAfter = opts?.startAfter ?? \"\";\n while (true) {\n opts?.signal?.throwIfAborted();\n const params = new URLSearchParams();\n params.set(\"list-type\", \"2\");\n params.set(\"prefix\", prefix);\n // Force S3 to URL-encode object keys in the response so keys\n // containing XML-hostile or whitespace bytes survive the round trip.\n // The XML parser (`xmlVal` in ./xml.ts) reverses this on `Key`; only\n // the key family (Key/Prefix/Delimiter/StartAfter) is encoded — ETag\n // and NextContinuationToken come back verbatim.\n params.set(\"encoding-type\", \"url\");\n if (continuationToken !== undefined) {\n params.set(\"continuation-token\", continuationToken);\n } else if (startAfter !== \"\") {\n params.set(\"start-after\", startAfter);\n }\n if (opts?.maxKeys !== undefined) {\n const remaining = opts.maxKeys - yielded;\n params.set(\"max-keys\", String(Math.min(remaining, 1000)));\n }\n const url = `${this.#endpoint}/${this.#bucket}/?${params.toString()}`;\n\n // One retry budget per page: 429 and 5xx share the attempt counter,\n // so a page costs at most `retries + 1` requests whatever fails.\n const parsed = parseListObjectsV2CommandOutput(\n await this.#retry(async (call) => {\n const res = await this.#dispatch(\n () => new Request(url, { method: \"GET\", signal: opts?.signal ?? null }),\n call,\n );\n if (res.status !== 200) {\n throw await mapS3StorageError(res, \"LIST\", prefix);\n }\n return res.text();\n }, opts),\n );\n\n for (const entry of parsed.Contents ?? []) {\n if (entry.Key === undefined) {\n continue;\n }\n yield {\n key: entry.Key,\n etag: entry.ETag ?? \"\",\n };\n yielded += 1;\n if (opts?.maxKeys !== undefined && yielded >= opts.maxKeys) {\n return;\n }\n }\n continuationToken = parsed.NextContinuationToken;\n if (continuationToken === undefined || continuationToken === \"\") {\n return;\n }\n }\n }\n}\n","import {\n BaerlyError,\n assertValidStorageKey,\n retryStorageCall,\n type Storage,\n type StorageGetOptions,\n type StorageGetResult,\n type StorageListEntry,\n type StoragePutOptions,\n type StoragePutResult,\n} from \"@baerly/protocol\";\nimport { mapStorageError } from \"./http-transport.ts\";\nimport { parseListObjectsV2CommandOutput } from \"./xml.ts\";\n\n/** Default GCS native XML API endpoint. */\nexport const DEFAULT_GCS_ENDPOINT = \"https://storage.googleapis.com\";\n\n/**\n * Construction-time options for {@link GcsHttpStorage}. Everything is\n * optional except `bucket`; `endpoint` defaults to the GCS native XML\n * API host. `sign` is injected — `gcsStorage` wires in the\n * GOOG4-HMAC-SHA256 signer ({@link goog4Signer}); unit tests pass a\n * passthrough.\n */\nexport interface GcsHttpStorageOptions {\n /** GCS endpoint. Defaults to `https://storage.googleapis.com`. */\n endpoint?: string;\n /** GCS bucket name. */\n bucket: string;\n /** `fetch` implementation. Defaults to `globalThis.fetch.bind(globalThis)`. */\n fetch?: typeof fetch;\n /** Signs requests before send. GOOG4-HMAC-SHA256 in production. */\n sign?: (req: Request) => Promise<Request>;\n /**\n * Retries after the first attempt, for throttled and transient failures\n * alike (and per `list` page). Default `STORAGE_RETRY_MAX_ATTEMPTS - 1`\n * (2, so 3 attempts in total); `0` sends each request once. Must be a\n * non-negative integer; any other value makes each request reject with\n * `InvalidConfig` before it is sent.\n */\n retries?: number;\n /**\n * Backoff base in ms, overriding both default bases (50 ms after a\n * transient failure, 1 s after a throttle). Full jitter applies either\n * way. Omit for the default policy.\n */\n backoffMs?: number;\n}\n\n/**\n * `Storage` impl that speaks the GCS native XML API and drives GCS's own\n * `x-goog-if-generation-match` conditional writes. Unlike GCS's S3-interop\n * endpoint (which treats `If-Match`/`If-None-Match` as read-scoped and can\n * never linearize the log), the native API returns 412 on any precondition\n * miss and the object `generation` in `x-goog-generation`. That generation\n * is carried verbatim in the opaque `Storage` etag.\n *\n * Authentication is plugged in via `sign` (GOOG4-HMAC-SHA256); this class\n * does no signing itself.\n */\nexport class GcsHttpStorage implements Storage {\n readonly #endpoint: string;\n readonly #bucket: string;\n readonly #fetch: typeof fetch;\n readonly #sign?: (req: Request) => Promise<Request>;\n readonly #retries: number | undefined;\n readonly #backoffMs: number | undefined;\n\n constructor(options: GcsHttpStorageOptions) {\n this.#endpoint = (options.endpoint ?? DEFAULT_GCS_ENDPOINT).replace(/\\/+$/, \"\");\n this.#bucket = options.bucket;\n this.#fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.#sign = options.sign;\n this.#retries = options.retries;\n this.#backoffMs = options.backoffMs;\n }\n\n #objectUrl(key: string): string {\n // Choke point for every key-addressing verb — reject unaddressable\n // `.`/`..`/empty keys before URL normalization turns them into a\n // bucket-root 403. @see storage-compatibility.md \"Key namespace\".\n assertValidStorageKey(key);\n return `${this.#endpoint}/${this.#bucket}/${encodeURIComponent(key)}`;\n }\n\n async #dispatch(req: Request): Promise<Response> {\n const signed = this.#sign ? await this.#sign(req) : req;\n try {\n return await this.#fetch(signed);\n } catch (error) {\n // A cancelled call surfaces as the caller's abort reason, whatever\n // it is, not a retryable NetworkError; the retry loop ends on it.\n if (error instanceof BaerlyError || signed.signal.aborted) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n throw new BaerlyError(\"NetworkError\", msg, { cause: error });\n }\n }\n\n #retry<T>(\n fn: () => Promise<T>,\n opts?: Pick<StoragePutOptions, \"ifMatch\" | \"ifNoneMatch\" | \"signal\">,\n ): Promise<T> {\n return retryStorageCall(fn, {\n ...(this.#retries !== undefined && { retries: this.#retries }),\n ...(this.#backoffMs !== undefined && { backoffMs: this.#backoffMs }),\n conditionalCreate: opts?.ifNoneMatch === \"*\",\n // A generation-match CAS is never resent: a resend after a lost ack\n // would see its own write as a 412.\n compareAndSwap: opts?.ifMatch !== undefined && opts.ifNoneMatch !== \"*\",\n // Every request leaves through `fetch`: the ledger's external pool.\n pool: \"external\",\n // Any caller abort ends the call; the loop never resends past it.\n ...(opts?.signal !== undefined && { signal: opts.signal }),\n });\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n return this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"GET\", signal: opts?.signal ?? null }),\n );\n switch (res.status) {\n case 200: {\n // DELTA 2: version token is x-goog-generation. No ETag fallback —\n // GCS's ETag is a quoted-MD5, not a generation; a fallback value\n // would poison the next x-goog-if-generation-match CAS. Fail loud\n // if absent (it is present on every GCS PUT/GET).\n const etag = res.headers.get(\"x-goog-generation\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `GET ${key}: missing x-goog-generation`);\n }\n const body = new Uint8Array(await res.arrayBuffer());\n return { body, etag };\n }\n case 404: {\n return null;\n }\n default: {\n throw await mapStorageError(res, \"GET\", key);\n }\n }\n }, opts);\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n const headers = new Headers();\n headers.set(\"Content-Type\", opts?.contentType ?? \"application/octet-stream\");\n // DELTA 1: native generation precondition, not S3 If-Match/If-None-Match.\n // ifNoneMatch:\"*\" => create-if-absent (:0); ifMatch => CAS (:<generation>).\n if (opts?.ifNoneMatch === \"*\") {\n headers.set(\"x-goog-if-generation-match\", \"0\");\n } else if (opts?.ifMatch !== undefined) {\n headers.set(\"x-goog-if-generation-match\", opts.ifMatch);\n }\n return this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, {\n method: \"PUT\",\n headers,\n // TS lib.dom narrows BodyInit; the runtime accepts Uint8Array.\n body: body as BodyInit,\n signal: opts?.signal ?? null,\n }),\n );\n // DELTA 3: 412 is the ONLY precondition-failure status on GCS, for\n // BOTH create-collision and stale-CAS. No S3-style 409-contended\n // branch, no 404-with-ifMatch branch.\n if (res.status === 412) {\n throw new BaerlyError(\"WriteConflict\", `PUT ${key}: precondition failed`);\n }\n if (res.status !== 200 && res.status !== 204) {\n throw await mapStorageError(res, \"PUT\", key);\n }\n // DELTA 2: version token is x-goog-generation, returned as etag. No\n // ETag fallback — GCS's ETag is a quoted-MD5, not a generation; a\n // fallback value would poison the next x-goog-if-generation-match CAS.\n // Fail loud if absent (it is present on every GCS PUT/GET).\n const etag = res.headers.get(\"x-goog-generation\");\n if (etag === null) {\n throw new BaerlyError(\"InvalidResponse\", `PUT ${key}: missing x-goog-generation`);\n }\n const dateStr = res.headers.get(\"Date\");\n const result: { etag: string; serverDate?: Date } = { etag };\n if (dateStr !== null) {\n result.serverDate = new Date(dateStr);\n }\n return result;\n }, opts);\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n opts?.signal?.throwIfAborted();\n const url = this.#objectUrl(key);\n await this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"DELETE\", signal: opts?.signal ?? null }),\n );\n // 200 / 204 / 404 → success (idempotent); any other status is a real\n // failure (403 → AccessDenied, 429/≥500 → retryable NetworkError, else\n // InvalidResponse) rather than a silently-swallowed non-2xx.\n if (res.status !== 200 && res.status !== 204 && res.status !== 404) {\n throw await mapStorageError(res, \"DELETE\", key);\n }\n }, opts);\n }\n\n async *list(\n prefix: string,\n opts?: { startAfter?: string; maxKeys?: number; signal?: AbortSignal },\n ): AsyncIterable<StorageListEntry> {\n opts?.signal?.throwIfAborted();\n let yielded = 0;\n let continuationToken: string | undefined;\n const startAfter = opts?.startAfter ?? \"\";\n while (true) {\n opts?.signal?.throwIfAborted();\n const params = new URLSearchParams();\n params.set(\"list-type\", \"2\");\n params.set(\"prefix\", prefix);\n params.set(\"encoding-type\", \"url\");\n if (continuationToken !== undefined) {\n params.set(\"continuation-token\", continuationToken);\n } else if (startAfter !== \"\") {\n params.set(\"start-after\", startAfter);\n }\n if (opts?.maxKeys !== undefined) {\n const remaining = opts.maxKeys - yielded;\n params.set(\"max-keys\", String(Math.min(remaining, 1000)));\n }\n const url = `${this.#endpoint}/${this.#bucket}/?${params.toString()}`;\n\n // One retry budget per page: 429 and 5xx share the attempt counter,\n // so a page costs at most `retries + 1` requests whatever fails.\n const parsed = parseListObjectsV2CommandOutput(\n await this.#retry(async () => {\n const res = await this.#dispatch(\n new Request(url, { method: \"GET\", signal: opts?.signal ?? null }),\n );\n if (res.status !== 200) {\n throw await mapStorageError(res, \"LIST\", prefix);\n }\n return res.text();\n }, opts),\n );\n\n for (const entry of parsed.Contents ?? []) {\n if (entry.Key === undefined) {\n continue;\n }\n yield {\n // The version token is the generation, not the MD5 `<ETag>`, so the\n // list etag matches what get/put return for the same object (the\n // universal list-etag == version-token contract). GCS emits\n // `<Generation>` for every object; the `?? \"\"` is a defensive floor\n // for a malformed row and, like every list etag, is CAS-unused.\n key: entry.Key,\n etag: entry.Generation ?? \"\",\n };\n yielded += 1;\n if (opts?.maxKeys !== undefined && yielded >= opts.maxKeys) {\n return;\n }\n }\n continuationToken = parsed.NextContinuationToken;\n if (continuationToken === undefined || continuationToken === \"\") {\n return;\n }\n }\n }\n}\n","import type { Credentials, CredentialsProvider } from \"./types.ts\";\n\nconst REFRESH_BUFFER_MS = 5 * 60 * 1000;\n\n/** A cached credential-derived value that can be dropped before its expiration. */\nexport type CredentialResolver<T> = (() => Promise<T>) & {\n /**\n * Drop `value` from the cache so the next resolve calls the provider again.\n * A no-op unless `value` is the cached one, so concurrent callers that all\n * saw the same rejected value cause one refresh, not one each.\n */\n invalidate(value: T): void;\n};\n\n/** Cache a credential-derived signing value until five minutes before expiration. */\nexport function credentialResolver<T>(\n credentials: Credentials | CredentialsProvider,\n now: () => number,\n build: (credentials: Credentials) => T,\n): CredentialResolver<T> {\n if (typeof credentials !== \"function\") {\n const value = build(credentials);\n return Object.assign(async () => value, { invalidate() {} });\n }\n\n let cached: { value: T; expiresAt: number } | null = null;\n let inFlight: Promise<T> | null = null;\n const resolve = async () => {\n if (cached !== null && cached.expiresAt - REFRESH_BUFFER_MS > now()) {\n return cached.value;\n }\n if (inFlight === null) {\n // Defer the provider so synchronous throws also clear an assigned flight.\n inFlight = Promise.resolve()\n .then(credentials)\n .then((creds) => {\n const value = build(creds);\n cached = { value, expiresAt: creds.expiration?.getTime() ?? Number.POSITIVE_INFINITY };\n return value;\n })\n .finally(() => {\n inFlight = null;\n });\n }\n return inFlight;\n };\n return Object.assign(resolve, {\n invalidate(value: T) {\n if (cached?.value === value) {\n cached = null;\n }\n },\n });\n}\n","import { sha256Hex } from \"@baerly/protocol\";\nimport type { Credentials, CredentialsProvider } from \"./types.ts\";\nimport { credentialResolver } from \"./resolve.ts\";\n\n/** GOOG4 signing-key prefix (vs AWS SigV4's \"AWS4\"). @see https://docs.cloud.google.com/storage/docs/authentication/signatures */\nconst GOOG4_KEY_PREFIX = \"GOOG4\";\n/** Credential-scope terminator (vs SigV4's \"aws4_request\"). @see https://docs.cloud.google.com/storage/docs/authentication/signatures */\nconst GOOG4_REQUEST = \"goog4_request\";\n/** Signing algorithm string. @see https://docs.cloud.google.com/storage/docs/authentication/signatures */\nconst GOOG4_ALGORITHM = \"GOOG4-HMAC-SHA256\";\n/** GCS storage service name in the credential scope (vs SigV4's \"s3\"). @see https://docs.cloud.google.com/storage/docs/authentication/signatures */\nconst GOOG4_SERVICE = \"storage\";\n/** GCS accepts \"auto\" as the signing region. @see https://docs.cloud.google.com/storage/docs/authentication/signatures */\nconst GOOG4_REGION = \"auto\";\n\nconst encoder = new TextEncoder();\n\n// SHA-256 hex comes from `@baerly/protocol` (shared with snapshotHash /\n// versionFromContent).\n\n/** RFC-3986-strict percent-encoding for canonical query components: encodes\n * everything except the unreserved set A-Za-z0-9-._~. encodeURIComponent\n * already handles that set but leaves !'()* unescaped, so escape those too.\n * @see https://docs.cloud.google.com/storage/docs/authentication/canonical-requests */\nfunction uriEncode(s: string): string {\n return encodeURIComponent(s).replace(\n /[!'()*]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n}\n\n/** Canonical-URI encoding for the request path. `URL.pathname` already\n * percent-encodes spaces / non-ASCII / control chars (and `^` `` ` `` `{` `}`),\n * but leaves GCS's enumerated reserved set raw — the sub-delims, `:@`, and\n * `[]`. GCS canonicalizes the path it receives by percent-encoding exactly\n * that set (`?=!#$&'()*+,:;@[]\"`; `?#\"` can't survive in `pathname`), so we\n * must reproduce the same delta or a `[`/`]`-bearing key signs differently\n * than GCS computes it (403 SignatureDoesNotMatch). Target only the delta so\n * already-encoded `%XX` and the unreserved set stay intact (no double-encode).\n * This is a denylist, not an allow-list, on purpose: over-encoding chars GCS\n * leaves raw (`|` `` ` `` `{}` …) would itself cause a mismatch.\n * @see https://docs.cloud.google.com/storage/docs/authentication/canonical-requests */\nfunction canonicalUri(pathname: string): string {\n return pathname.replace(\n /[!$&'()*+,;=:@[\\]]/g,\n (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n );\n}\n\nasync function hmac(key: Uint8Array, data: string): Promise<Uint8Array<ArrayBuffer>> {\n const view = new Uint8Array(key.byteLength);\n view.set(key);\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n view,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const sig = await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(data));\n return new Uint8Array(sig);\n}\n\n/** SHA-256 hex of the empty payload: the `x-goog-content-sha256` of a bodyless request. @see https://docs.cloud.google.com/storage/docs/authentication/canonical-requests */\nconst EMPTY_PAYLOAD_SHA256 = \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\";\n\n/** The GOOG4 signing key for one secret and UTC day, imported once for reuse.\n * Same key chain as {@link sigV4Signature}, which stays the uncached oracle. */\nasync function importSigningKey(secretAccessKey: string, yyyymmdd: string): Promise<CryptoKey> {\n const dateKey = await hmac(encoder.encode(GOOG4_KEY_PREFIX + secretAccessKey), yyyymmdd);\n const dateRegionKey = await hmac(dateKey, GOOG4_REGION);\n const dateSvcKey = await hmac(dateRegionKey, GOOG4_SERVICE);\n const signingKey = await hmac(dateSvcKey, GOOG4_REQUEST);\n return crypto.subtle.importKey(\"raw\", signingKey, { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n ]);\n}\n\n/** Pure: build the GOOG4 canonical request string. Exported for the intermediates test. */\nexport function goog4CanonicalRequest(input: {\n method: string;\n url: string;\n signedHeaders: Record<string, string>;\n hashedPayload: string;\n}): string {\n const u = new URL(input.url);\n // Normalize to lowercase keys once, so the sort order and the value lookup\n // agree even if a caller passes mixed-case header names (`{ Host: ... }`).\n // The internal caller already lowercases via `Headers` iteration, but this\n // function is also exported for the intermediates test — normalizing here\n // makes the lowercase-key invariant guaranteed rather than assumed.\n const normalized: Record<string, string> = {};\n for (const [name, value] of Object.entries(input.signedHeaders)) {\n normalized[name.toLowerCase()] = value;\n }\n const names = Object.keys(normalized).toSorted();\n const canonicalHeaders = names.map((n) => `${n}:${normalized[n]!.trim()}\\n`).join(\"\");\n const signedHeaderList = names.join(\";\");\n // Sort by encoded key then encoded value; a \"key\\0value\" join makes the pair\n // orderable with a single string comparison (avoids a nested ternary).\n const query = [...u.searchParams]\n .map(([k, v]) => [uriEncode(k), uriEncode(v)] as const)\n .toSorted((a, b) => {\n const ka = `${a[0]}\\0${a[1]}`;\n const kb = `${b[0]}\\0${b[1]}`;\n if (ka < kb) {\n return -1;\n }\n return ka > kb ? 1 : 0;\n })\n .map(([k, v]) => `${k}=${v}`)\n .join(\"&\");\n return [\n input.method,\n canonicalUri(u.pathname), // percent-encoded by URL, plus sub-delims/:@ per GOOG4\n query,\n canonicalHeaders, // trailing \\n included per entry; joined below with \\n\n signedHeaderList,\n input.hashedPayload,\n ].join(\"\\n\");\n}\n\n/** Pure: build the SigV4-family string-to-sign. Async because it hashes the canonical request. */\nexport async function goog4StringToSign(input: {\n algorithm: string;\n amzDate: string;\n scope: string;\n canonicalRequest: string;\n}): Promise<string> {\n const hash = await sha256Hex(encoder.encode(input.canonicalRequest));\n return [input.algorithm, input.amzDate, input.scope, hash].join(\"\\n\");\n}\n\n/**\n * The SigV4-family signing machinery: four-stage HMAC key chain + final HMAC.\n * Identical between GOOG4 and AWS SigV4 modulo the {keyPrefix, terminator,\n * service, region} constants — which is exactly what the AWS-vector oracle\n * exploits to prove this in CI. Exported for oracle 1 and as the uncached\n * reference that `goog4Signer`'s cached signing key is tested against.\n */\nexport async function sigV4Signature(input: {\n keyPrefix: string;\n terminator: string;\n service: string;\n region: string;\n secretAccessKey: string;\n yyyymmdd: string;\n stringToSign: string;\n}): Promise<string> {\n const dateKey = await hmac(\n encoder.encode(input.keyPrefix + input.secretAccessKey),\n input.yyyymmdd,\n );\n const dateRegionKey = await hmac(dateKey, input.region);\n const dateSvcKey = await hmac(dateRegionKey, input.service);\n const signingKey = await hmac(dateSvcKey, input.terminator);\n const signature = await hmac(signingKey, input.stringToSign);\n return signature.toHex();\n}\n\nfunction amzDateFrom(ms: number): { amzDate: string; yyyymmdd: string } {\n const iso = new Date(ms).toISOString(); // 2025-01-01T00:00:00.000Z\n const amzDate = iso.replace(/[:-]/g, \"\").replace(/\\.\\d{3}Z$/, \"Z\"); // 20250101T000000Z\n return { amzDate, yyyymmdd: amzDate.slice(0, 8) };\n}\n\n/**\n * Inputs for {@link goog4Signer}. Named for parity with\n * `SigV4SignerOptions` so both signer families read the same on the\n * curated `/s3` + `/gcs` subpaths.\n */\nexport interface Goog4SignerOptions {\n /** GCS HMAC interoperability credentials (static) or an async resolver. */\n credentials: Credentials | CredentialsProvider;\n /** Clock seam for deterministic tests; defaults to `Date.now`. */\n now?: () => number;\n}\n\nexport function goog4Signer(opts: Goog4SignerOptions): (req: Request) => Promise<Request> {\n const now = opts.now ?? (() => Date.now());\n const resolve = credentialResolver(opts.credentials, now, (creds) => creds);\n\n // The derived signing key depends only on the secret and the UTC day, so\n // each signer keeps the one it last used (a key cache like aws4fetch's per\n // `AwsClient`). Per closure, not module-wide: two signers with different\n // credentials never evict each other, and the secret stays in the closure\n // that already holds it. A rejected derivation is dropped, so the next call\n // derives again rather than failing until the day rolls over.\n let cachedKey: { secret: string; yyyymmdd: string; key: Promise<CryptoKey> } | undefined;\n const signingKeyFor = (secret: string, yyyymmdd: string): Promise<CryptoKey> => {\n if (cachedKey?.secret === secret && cachedKey.yyyymmdd === yyyymmdd) {\n return cachedKey.key;\n }\n const entry = { secret, yyyymmdd, key: importSigningKey(secret, yyyymmdd) };\n cachedKey = entry;\n entry.key.catch(() => {\n if (cachedKey === entry) {\n cachedKey = undefined;\n }\n });\n return entry.key;\n };\n\n return async (req) => {\n const creds = await resolve();\n const { amzDate, yyyymmdd } = amzDateFrom(now());\n const scope = `${yyyymmdd}/${GOOG4_REGION}/${GOOG4_SERVICE}/${GOOG4_REQUEST}`;\n\n // Only a null body is bodyless (GET, DELETE, LIST). An empty-body PUT\n // still has a body stream and takes the read-and-hash path.\n const payloadHash =\n req.body === null\n ? EMPTY_PAYLOAD_SHA256\n : await sha256Hex(new Uint8Array(await req.clone().arrayBuffer()));\n\n const url = new URL(req.url);\n const headers = new Headers(req.headers);\n headers.set(\"host\", url.host);\n headers.set(\"x-goog-date\", amzDate);\n headers.set(\"x-goog-content-sha256\", payloadHash);\n // No session-token header: GCS HMAC interoperability keys are long-lived\n // (access-ID + secret) with no STS-style temporary-credential concept, and\n // GCS documents no header analogous to AWS's x-amz-security-token. A\n // `sessionToken` on the shared Credentials shape (set by the AWS providers)\n // is therefore intentionally ignored here rather than signed into a\n // fabricated x-goog-security-token header.\n // @see https://docs.cloud.google.com/storage/docs/authentication/signatures\n\n // SignedHeaders MUST be computed dynamically from the request — this is the\n // load-bearing correctness point. GCS rejects (403 SignatureDoesNotMatch)\n // any x-goog-* header on the wire that is absent from SignedHeaders, and the\n // transport (Task 1.1) sets x-goog-if-generation-match BEFORE calling sign().\n // A fixed list would leave the precondition header unsigned → every\n // conditional write (the whole commit path) fails, while a bodyless GET\n // still passes — so this bug hides from any smoke test that does not\n // exercise a conditional PUT. Scan the actual request headers instead.\n const signedHeaders: Record<string, string> = {};\n for (const [name, value] of headers) {\n const lower = name.toLowerCase();\n if (lower === \"host\" || lower === \"content-type\" || lower.startsWith(\"x-goog-\")) {\n signedHeaders[lower] = value;\n }\n }\n\n const canonical = goog4CanonicalRequest({\n method: req.method,\n url: req.url,\n signedHeaders,\n hashedPayload: payloadHash,\n });\n const stringToSign = await goog4StringToSign({\n algorithm: GOOG4_ALGORITHM,\n amzDate,\n scope,\n canonicalRequest: canonical,\n });\n const signingKey = await signingKeyFor(creds.secretAccessKey, yyyymmdd);\n const signature = new Uint8Array(\n await crypto.subtle.sign(\"HMAC\", signingKey, encoder.encode(stringToSign)),\n ).toHex();\n\n const signedHeaderList = Object.keys(signedHeaders)\n .map((n) => n.toLowerCase())\n .toSorted()\n .join(\";\");\n headers.set(\n \"Authorization\",\n `${GOOG4_ALGORITHM} Credential=${creds.accessKeyId}/${scope}, ` +\n `SignedHeaders=${signedHeaderList}, Signature=${signature}`,\n );\n return new Request(req, { headers });\n };\n}\n","/**\n * @license MIT <https://opensource.org/licenses/MIT>\n * @copyright Michael Hart 2024\n */\nconst encoder = new TextEncoder();\nconst HOST_SERVICES = {\n appstream2: 'appstream',\n cloudhsmv2: 'cloudhsm',\n email: 'ses',\n marketplace: 'aws-marketplace',\n mobile: 'AWSMobileHubService',\n pinpoint: 'mobiletargeting',\n queue: 'sqs',\n 'git-codecommit': 'codecommit',\n 'mturk-requester-sandbox': 'mturk-requester',\n 'personalize-runtime': 'personalize',\n};\nconst UNSIGNABLE_HEADERS = new Set([\n 'authorization',\n 'content-type',\n 'content-length',\n 'user-agent',\n 'presigned-expires',\n 'expect',\n 'x-amzn-trace-id',\n 'range',\n 'connection',\n]);\nclass AwsClient {\n constructor({ accessKeyId, secretAccessKey, sessionToken, service, region, cache, retries, initRetryMs }) {\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n this.service = service;\n this.region = region;\n this.cache = cache || new Map();\n this.retries = retries != null ? retries : 10;\n this.initRetryMs = initRetryMs || 50;\n }\n async sign(input, init) {\n if (input instanceof Request) {\n const { method, url, headers, body } = input;\n init = Object.assign({ method, url, headers }, init);\n if (init.body == null && headers.has('Content-Type')) {\n init.body = body != null && headers.has('X-Amz-Content-Sha256') ? body : await input.clone().arrayBuffer();\n }\n input = url;\n }\n const signer = new AwsV4Signer(Object.assign({ url: input.toString() }, init, this, init && init.aws));\n const signed = Object.assign({}, init, await signer.sign());\n delete signed.aws;\n try {\n return new Request(signed.url.toString(), signed)\n } catch (e) {\n if (e instanceof TypeError) {\n return new Request(signed.url.toString(), Object.assign({ duplex: 'half' }, signed))\n }\n throw e\n }\n }\n async fetch(input, init) {\n for (let i = 0; i <= this.retries; i++) {\n const fetched = fetch(await this.sign(input, init));\n if (i === this.retries) {\n return fetched\n }\n const res = await fetched;\n if (res.status < 500 && res.status !== 429) {\n return res\n }\n await new Promise(resolve => setTimeout(resolve, Math.random() * this.initRetryMs * Math.pow(2, i)));\n }\n throw new Error('An unknown error occurred, ensure retries is not negative')\n }\n}\nclass AwsV4Signer {\n constructor({ method, url, headers, body, accessKeyId, secretAccessKey, sessionToken, service, region, cache, datetime, signQuery, appendSessionToken, allHeaders, singleEncode }) {\n if (url == null) throw new TypeError('url is a required option')\n if (accessKeyId == null) throw new TypeError('accessKeyId is a required option')\n if (secretAccessKey == null) throw new TypeError('secretAccessKey is a required option')\n this.method = method || (body ? 'POST' : 'GET');\n this.url = new URL(url);\n this.headers = new Headers(headers || {});\n this.body = body;\n this.accessKeyId = accessKeyId;\n this.secretAccessKey = secretAccessKey;\n this.sessionToken = sessionToken;\n let guessedService, guessedRegion;\n if (!service || !region) {\n[guessedService, guessedRegion] = guessServiceRegion(this.url, this.headers);\n }\n this.service = service || guessedService || '';\n this.region = region || guessedRegion || 'us-east-1';\n this.cache = cache || new Map();\n this.datetime = datetime || new Date().toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n this.signQuery = signQuery;\n this.appendSessionToken = appendSessionToken || this.service === 'iotdevicegateway';\n this.headers.delete('Host');\n if (this.service === 's3' && !this.signQuery && !this.headers.has('X-Amz-Content-Sha256')) {\n this.headers.set('X-Amz-Content-Sha256', 'UNSIGNED-PAYLOAD');\n }\n const params = this.signQuery ? this.url.searchParams : this.headers;\n params.set('X-Amz-Date', this.datetime);\n if (this.sessionToken && !this.appendSessionToken) {\n params.set('X-Amz-Security-Token', this.sessionToken);\n }\n this.signableHeaders = ['host', ...this.headers.keys()]\n .filter(header => allHeaders || !UNSIGNABLE_HEADERS.has(header))\n .sort();\n this.signedHeaders = this.signableHeaders.join(';');\n this.canonicalHeaders = this.signableHeaders\n .map(header => header + ':' + (header === 'host' ? this.url.host : (this.headers.get(header) || '').replace(/\\s+/g, ' ')))\n .join('\\n');\n this.credentialString = [this.datetime.slice(0, 8), this.region, this.service, 'aws4_request'].join('/');\n if (this.signQuery) {\n if (this.service === 's3' && !params.has('X-Amz-Expires')) {\n params.set('X-Amz-Expires', '86400');\n }\n params.set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256');\n params.set('X-Amz-Credential', this.accessKeyId + '/' + this.credentialString);\n params.set('X-Amz-SignedHeaders', this.signedHeaders);\n }\n if (this.service === 's3') {\n try {\n this.encodedPath = decodeURIComponent(this.url.pathname.replace(/\\+/g, ' '));\n } catch (e) {\n this.encodedPath = this.url.pathname;\n }\n } else {\n this.encodedPath = this.url.pathname.replace(/\\/+/g, '/');\n }\n if (!singleEncode) {\n this.encodedPath = encodeURIComponent(this.encodedPath).replace(/%2F/g, '/');\n }\n this.encodedPath = encodeRfc3986(this.encodedPath);\n const seenKeys = new Set();\n this.encodedSearch = [...this.url.searchParams]\n .filter(([k]) => {\n if (!k) return false\n if (this.service === 's3') {\n if (seenKeys.has(k)) return false\n seenKeys.add(k);\n }\n return true\n })\n .map(pair => pair.map(p => encodeRfc3986(encodeURIComponent(p))))\n .sort(([k1, v1], [k2, v2]) => k1 < k2 ? -1 : k1 > k2 ? 1 : v1 < v2 ? -1 : v1 > v2 ? 1 : 0)\n .map(pair => pair.join('='))\n .join('&');\n }\n async sign() {\n if (this.signQuery) {\n this.url.searchParams.set('X-Amz-Signature', await this.signature());\n if (this.sessionToken && this.appendSessionToken) {\n this.url.searchParams.set('X-Amz-Security-Token', this.sessionToken);\n }\n } else {\n this.headers.set('Authorization', await this.authHeader());\n }\n return {\n method: this.method,\n url: this.url,\n headers: this.headers,\n body: this.body,\n }\n }\n async authHeader() {\n return [\n 'AWS4-HMAC-SHA256 Credential=' + this.accessKeyId + '/' + this.credentialString,\n 'SignedHeaders=' + this.signedHeaders,\n 'Signature=' + (await this.signature()),\n ].join(', ')\n }\n async signature() {\n const date = this.datetime.slice(0, 8);\n const cacheKey = [this.secretAccessKey, date, this.region, this.service].join();\n let kCredentials = this.cache.get(cacheKey);\n if (!kCredentials) {\n const kDate = await hmac('AWS4' + this.secretAccessKey, date);\n const kRegion = await hmac(kDate, this.region);\n const kService = await hmac(kRegion, this.service);\n kCredentials = await hmac(kService, 'aws4_request');\n this.cache.set(cacheKey, kCredentials);\n }\n return buf2hex(await hmac(kCredentials, await this.stringToSign()))\n }\n async stringToSign() {\n return [\n 'AWS4-HMAC-SHA256',\n this.datetime,\n this.credentialString,\n buf2hex(await hash(await this.canonicalString())),\n ].join('\\n')\n }\n async canonicalString() {\n return [\n this.method.toUpperCase(),\n this.encodedPath,\n this.encodedSearch,\n this.canonicalHeaders + '\\n',\n this.signedHeaders,\n await this.hexBodyHash(),\n ].join('\\n')\n }\n async hexBodyHash() {\n let hashHeader = this.headers.get('X-Amz-Content-Sha256') || (this.service === 's3' && this.signQuery ? 'UNSIGNED-PAYLOAD' : null);\n if (hashHeader == null) {\n if (this.body && typeof this.body !== 'string' && !('byteLength' in this.body)) {\n throw new Error('body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header')\n }\n hashHeader = buf2hex(await hash(this.body || ''));\n }\n return hashHeader\n }\n}\nasync function hmac(key, string) {\n const cryptoKey = await crypto.subtle.importKey(\n 'raw',\n typeof key === 'string' ? encoder.encode(key) : key,\n { name: 'HMAC', hash: { name: 'SHA-256' } },\n false,\n ['sign'],\n );\n return crypto.subtle.sign('HMAC', cryptoKey, encoder.encode(string))\n}\nasync function hash(content) {\n return crypto.subtle.digest('SHA-256', typeof content === 'string' ? encoder.encode(content) : content)\n}\nconst HEX_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];\nfunction buf2hex(arrayBuffer) {\n const buffer = new Uint8Array(arrayBuffer);\n let out = '';\n for (let idx = 0; idx < buffer.length; idx++) {\n const n = buffer[idx];\n out += HEX_CHARS[(n >>> 4) & 0xF];\n out += HEX_CHARS[n & 0xF];\n }\n return out\n}\nfunction encodeRfc3986(urlEncodedStr) {\n return urlEncodedStr.replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n}\nfunction guessServiceRegion(url, headers) {\n const { hostname, pathname } = url;\n if (hostname.endsWith('.on.aws')) {\n const match = hostname.match(/^[^.]{1,63}\\.lambda-url\\.([^.]{1,63})\\.on\\.aws$/);\n return match != null ? ['lambda', match[1] || ''] : ['', '']\n }\n if (hostname.endsWith('.r2.cloudflarestorage.com')) {\n return ['s3', 'auto']\n }\n if (hostname.endsWith('.backblazeb2.com')) {\n const match = hostname.match(/^(?:[^.]{1,63}\\.)?s3\\.([^.]{1,63})\\.backblazeb2\\.com$/);\n return match != null ? ['s3', match[1] || ''] : ['', '']\n }\n const match = hostname.replace('dualstack.', '').match(/([^.]{1,63})\\.(?:([^.]{0,63})\\.)?amazonaws\\.com(?:\\.cn)?$/);\n let service = (match && match[1]) || '';\n let region = match && match[2];\n if (region === 'us-gov') {\n region = 'us-gov-west-1';\n } else if (region === 's3' || region === 's3-accelerate') {\n region = 'us-east-1';\n service = 's3';\n } else if (service === 'iot') {\n if (hostname.startsWith('iot.')) {\n service = 'execute-api';\n } else if (hostname.startsWith('data.jobs.iot.')) {\n service = 'iot-jobs-data';\n } else {\n service = pathname === '/mqtt' ? 'iotdevicegateway' : 'iotdata';\n }\n } else if (service === 'autoscaling') {\n const targetPrefix = (headers.get('X-Amz-Target') || '').split('.')[0];\n if (targetPrefix === 'AnyScaleFrontendService') {\n service = 'application-autoscaling';\n } else if (targetPrefix === 'AnyScaleScalingPlannerFrontendService') {\n service = 'autoscaling-plans';\n }\n } else if (region == null && service.startsWith('s3-')) {\n region = service.slice(3).replace(/^fips-|^external-1/, '');\n service = 's3';\n } else if (service.endsWith('-fips')) {\n service = service.slice(0, -5);\n } else if (region && /-\\d$/.test(service) && !/-\\d$/.test(region)) {\n[service, region] = [region, service];\n }\n return [HOST_SERVICES[service] || service, region || '']\n}\n\nexport { AwsClient, AwsV4Signer };\n","import type { AwsClient } from \"aws4fetch\";\n\n/**\n * Sign an S3 request through `aws4fetch` without touching its body.\n *\n * Given a `Request` with a `Content-Type` and no `X-Amz-Content-Sha256`,\n * `AwsClient.sign` reads the whole body through `req.clone().arrayBuffer()`\n * and rebuilds the request around the copy, although for S3 it signs\n * `UNSIGNED-PAYLOAD` and never hashes the body. Signing only the method,\n * URL and headers yields the same `Authorization` and header set without\n * that copy. The header defaults to `UNSIGNED-PAYLOAD` exactly as\n * `aws4fetch` defaults it for S3, so the signature is unchanged.\n *\n * The signed headers go back onto a `Request` built from the original, so\n * the original body source survives and Node still sends a `Content-Length`.\n * Handing `aws4fetch` the original `Request` with `X-Amz-Content-Sha256`\n * already set would skip the copy too, but it rebuilds the request around\n * `req.body` (a `ReadableStream`), and undici then sends\n * `Transfer-Encoding: chunked` with no length, which AWS S3 `PutObject`\n * rejects.\n */\nexport async function signHeadersOnly(client: AwsClient, req: Request): Promise<Request> {\n const headers = new Headers(req.headers);\n if (!headers.has(\"X-Amz-Content-Sha256\")) {\n headers.set(\"X-Amz-Content-Sha256\", \"UNSIGNED-PAYLOAD\");\n }\n const signed = await client.sign(req.url, { method: req.method, headers });\n return new Request(req, { headers: signed.headers });\n}\n","import { AwsClient } from \"aws4fetch\";\nimport type { Credentials, CredentialsProvider } from \"./types.ts\";\nimport { credentialResolver } from \"./resolve.ts\";\nimport { signHeadersOnly } from \"../sigv4-sign.ts\";\n\nfunction buildAwsClient(creds: Credentials, region: string): AwsClient {\n return new AwsClient({\n accessKeyId: creds.accessKeyId,\n secretAccessKey: creds.secretAccessKey,\n sessionToken: creds.sessionToken,\n region,\n service: \"s3\",\n });\n}\n\n/**\n * A SigV4 signer. `invalidate` is present only for a credentials provider:\n * given a request this signer returned, it drops the credentials that signed\n * it so the next `sign` calls the provider again.\n */\nexport type RefreshingSigner = ((req: Request) => Promise<Request>) & {\n invalidate?: (signed: Request) => void;\n};\n\nexport function refreshingSigner(opts: {\n region: string;\n credentials: Credentials | CredentialsProvider;\n now?: () => number;\n}): RefreshingSigner {\n const region = opts.region;\n const now = opts.now ?? (() => Date.now());\n\n if (typeof opts.credentials !== \"function\") {\n const aws = buildAwsClient(opts.credentials, region);\n return (req) => signHeadersOnly(aws, req);\n }\n\n const resolve = credentialResolver(opts.credentials, now, (creds) =>\n buildAwsClient(creds, region),\n );\n\n const signedBy = new WeakMap<Request, AwsClient>();\n const sign = async (req: Request): Promise<Request> => {\n const aws = await resolve();\n const signed = await signHeadersOnly(aws, req);\n signedBy.set(signed, aws);\n return signed;\n };\n return Object.assign(sign, {\n invalidate(signed: Request) {\n const aws = signedBy.get(signed);\n if (aws !== undefined) {\n resolve.invalidate(aws);\n }\n },\n });\n}\n","import type { Storage } from \"@baerly/protocol\";\nimport { S3HttpStorage, withCredentialInvalidation } from \"./s3-http.ts\";\nimport { GcsHttpStorage } from \"./gcs-http.ts\";\nimport { refreshingSigner } from \"./credentials/signer.ts\";\nimport { goog4Signer } from \"./credentials/goog4-signer.ts\";\nimport type { Credentials, CredentialsProvider } from \"./credentials/types.ts\";\n\nfunction buildS3Storage(opts: {\n endpoint: string;\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n const sign = refreshingSigner({ region: opts.region, credentials: opts.credentials });\n const storage = new S3HttpStorage({ endpoint: opts.endpoint, bucket: opts.bucket, sign });\n return sign.invalidate === undefined\n ? storage\n : withCredentialInvalidation(storage, sign.invalidate);\n}\n\n/**\n * AWS S3 `Storage` factory. Wraps `S3HttpStorage` with the standard\n * `aws4fetch` SigV4 signer. The endpoint is derived from the region as\n * `https://s3.<region>.amazonaws.com`.\n *\n * @example Static credentials\n * ```ts\n * import { s3Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n *\n * @example EKS (refreshing) — auto-detects Pod Identity or IRSA\n * ```ts\n * import { s3Storage, fromEks } from \"@gusto/baerly-storage/node\";\n *\n * const storage = s3Storage({\n * region: process.env[\"AWS_REGION\"] ?? \"us-east-1\",\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: fromEks(),\n * });\n * ```\n */\nexport function s3Storage(opts: {\n region: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://s3.${opts.region}.amazonaws.com`,\n region: opts.region,\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Cloudflare R2 `Storage` factory (S3-compat endpoint). Derives the\n * endpoint from `accountId` as\n * `https://<accountId>.r2.cloudflarestorage.com` and pins region\n * `\"auto\"` — R2 ignores region but `aws4fetch`'s signer requires\n * the field to be set.\n *\n * For Workers that have a native R2 binding (no HTTP hop), see\n * `r2BindingStorage` in `@baerly/adapter-cloudflare`. This factory\n * is for Node hosts that talk to R2 over its public S3-compat URL.\n *\n * @example\n * ```ts\n * import { r2Storage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = r2Storage({\n * accountId: process.env[\"R2_ACCOUNT_ID\"]!,\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"AWS_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"AWS_SECRET_ACCESS_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function r2Storage(opts: {\n accountId: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,\n region: \"auto\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Minio `Storage` factory — for local-dev / self-hosted S3-compat.\n * Endpoint is fully caller-supplied (e.g. `http://localhost:9102`)\n * because Minio deployments don't follow a URL template. Region is\n * pinned to `\"us-east-1\"`; Minio ignores it but `aws4fetch` requires\n * a value.\n *\n * @example\n * ```ts\n * import { minioStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = minioStorage({\n * endpoint: process.env[\"BAERLY_S3_ENDPOINT\"] ?? \"http://localhost:9102\",\n * bucket: \"baerly\",\n * credentials: {\n * accessKeyId: process.env[\"MINIO_ACCESS_KEY\"]!,\n * secretAccessKey: process.env[\"MINIO_SECRET_KEY\"]!,\n * },\n * });\n * ```\n */\nexport function minioStorage(opts: {\n endpoint: string;\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n}): Storage {\n return buildS3Storage({\n endpoint: opts.endpoint,\n region: \"us-east-1\",\n bucket: opts.bucket,\n credentials: opts.credentials,\n });\n}\n\n/**\n * Google Cloud Storage `Storage` factory over the native GCS XML API\n * at `https://storage.googleapis.com`. Wraps {@link GcsHttpStorage} with\n * a GOOG4-HMAC-SHA256 signer, driving GCS's own generation-precondition\n * conditional writes (`x-goog-if-generation-match: 0` for create-if-absent,\n * `x-goog-if-generation-match: <generation>` for compare-and-swap), which\n * return `412` on a lost write. The object `generation` is carried verbatim\n * as the opaque `Storage` etag. This is the sanctioned GCS path — the\n * S3-interop endpoint treats `If-Match`/`If-None-Match` as read-scoped only\n * and cannot linearize the log, so it is not supported.\n *\n * Authentication uses GCS HMAC keys (Console → Settings → Interoperability)\n * — mint an interop key, put the HMAC access key in `credentials.accessKeyId`\n * and the HMAC secret in `credentials.secretAccessKey`.\n *\n * @example\n * ```ts\n * import { gcsStorage } from \"@gusto/baerly-storage/node\";\n *\n * const storage = gcsStorage({\n * bucket: process.env[\"BUCKET\"]!,\n * credentials: {\n * accessKeyId: process.env[\"GCS_HMAC_ACCESS_KEY_ID\"]!,\n * secretAccessKey: process.env[\"GCS_HMAC_SECRET\"]!,\n * },\n * });\n * ```\n */\nexport function gcsStorage(opts: {\n bucket: string;\n credentials: Credentials | CredentialsProvider;\n /** GCS endpoint. Defaults to `https://storage.googleapis.com`. */\n endpoint?: string;\n}): Storage {\n const sign = goog4Signer({ credentials: opts.credentials });\n return new GcsHttpStorage({\n bucket: opts.bucket,\n sign,\n ...(opts.endpoint !== undefined && { endpoint: opts.endpoint }),\n });\n}\n","/**\n * Bucket URI parsing for the CLI surface. Consumed by every\n * `baerly admin <cmd>`, `baerly inspect`, and `baerly export`.\n *\n * Grammar:\n * - `s3://<bucket>[/<prefix>]` — S3-compatible HTTP. Creds via env\n * vars (`BAERLY_S3_ENDPOINT`, `BAERLY_S3_ACCESS_KEY_ID`,\n * `BAERLY_S3_SECRET_ACCESS_KEY`, `BAERLY_S3_REGION` — region\n * defaults to `us-east-1`).\n * - `gcs://<bucket>[/<prefix>]` — native GCS XML API. Creds via\n * env vars `BAERLY_GCS_HMAC_ACCESS_KEY_ID` + `BAERLY_GCS_HMAC_SECRET`\n * (GCS HMAC interop keys: Console → Cloud Storage → Settings →\n * Interoperability). Drives GCS's native generation-precondition\n * path (`x-goog-if-generation-match`); the S3-interop endpoint is\n * NOT supported (it treats If-Match/If-None-Match as read-only).\n * - `file:///<absolute-path>` — `LocalFsStorage` rooted at the path.\n * Relative paths are rejected by the three-slash prefix.\n * - `memory://<bucket>` — `MemoryStorage` keyed via\n * `getOrCreateMemoryStorageForBucket`. Test-only.\n */\n\nimport { LocalFsStorage } from \"@baerly/dev\";\nimport {\n DEFAULT_GCS_ENDPOINT,\n gcsStorage,\n minioStorage,\n r2Storage,\n s3Storage,\n} from \"@baerly/adapter-node\";\nimport { BaerlyError, getOrCreateMemoryStorageForBucket, type Storage } from \"@baerly/protocol\";\n\n/**\n * Result of `parseBucketUri`. `storage` is a constructed `Storage`\n * handle; `keyPrefix` is \"\" for an unprefixed bucket, or a non-empty\n * string ending in `/` for a prefixed one. The target side prepends\n * this to every emitted key.\n */\nexport interface ParsedBucketUri {\n storage: Storage;\n /** Empty for no-prefix; non-empty always ends with \"/\". */\n keyPrefix: string;\n /**\n * Present only for gcs:// URIs. Lets `baerly doctor` run GCS-specific\n * bucket-config checks (Object Versioning) that need a signer + endpoint,\n * beyond the backend-agnostic CAS probe. Other consumers ignore it.\n */\n gcs?: {\n endpoint: string;\n bucket: string;\n credentials: { accessKeyId: string; secretAccessKey: string };\n };\n}\n\n/**\n * Parse a bucket URI into a constructed `Storage` handle + optional\n * key prefix.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — unsupported scheme, or an\n * `s3://` / `gcs://` URI with a missing env var.\n */\nexport const parseBucketUri = async (uri: string): Promise<ParsedBucketUri> => {\n if (uri.startsWith(\"s3://\")) {\n const rest = uri.slice(5);\n const slash = rest.indexOf(\"/\");\n const bucket = slash === -1 ? rest : rest.slice(0, slash);\n const prefix = slash === -1 ? \"\" : rest.slice(slash + 1);\n if (bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `bucket URI: s3:// URI requires a bucket name (got ${JSON.stringify(uri)})`,\n );\n }\n const accessKeyId = requireEnv(\"BAERLY_S3_ACCESS_KEY_ID\");\n const secretAccessKey = requireEnv(\"BAERLY_S3_SECRET_ACCESS_KEY\");\n const region = process.env[\"BAERLY_S3_REGION\"] ?? \"us-east-1\";\n const endpoint = requireEnv(\"BAERLY_S3_ENDPOINT\");\n // Endpoint-pattern dispatch. AWS-shaped → `s3Storage`; R2-shaped →\n // `r2Storage`; anything else (user-supplied / Minio) → `minioStorage`\n // so the full endpoint flows through verbatim.\n const r2Host = endpoint.match(/^https?:\\/\\/([^./]+)\\.r2\\.cloudflarestorage\\.com\\b/i);\n const isAws = /^https?:\\/\\/s3(\\.[^.]+)?\\.amazonaws\\.com\\b/i.test(endpoint);\n const storage: Storage = pickS3Storage({\n r2Host,\n isAws,\n endpoint,\n bucket,\n accessKeyId,\n secretAccessKey,\n region,\n });\n return {\n storage,\n keyPrefix: normalizeKeyPrefix(prefix),\n };\n }\n if (uri.startsWith(\"gcs://\")) {\n const rest = uri.slice(6);\n const slash = rest.indexOf(\"/\");\n const bucket = slash === -1 ? rest : rest.slice(0, slash);\n const prefix = slash === -1 ? \"\" : rest.slice(slash + 1);\n if (bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `bucket URI: gcs:// URI requires a bucket name (got ${JSON.stringify(uri)})`,\n );\n }\n const accessKeyId = requireEnv(\"BAERLY_GCS_HMAC_ACCESS_KEY_ID\");\n const secretAccessKey = requireEnv(\"BAERLY_GCS_HMAC_SECRET\");\n // Single source of truth for the endpoint: the same value drives both\n // the storage handle and the `gcs` probe field, so `doctor`'s\n // versioning probe can never sign against a different host than the\n // handle writes to. If a gcs:// endpoint override lands later, it\n // flows to both from here.\n const endpoint = DEFAULT_GCS_ENDPOINT;\n const credentials = { accessKeyId, secretAccessKey };\n const storage = gcsStorage({ endpoint, bucket, credentials });\n return {\n storage,\n keyPrefix: normalizeKeyPrefix(prefix),\n gcs: { endpoint, bucket, credentials },\n };\n }\n if (uri.startsWith(\"file:///\")) {\n return { storage: new LocalFsStorage({ root: uri.slice(7) }), keyPrefix: \"\" };\n }\n if (uri.startsWith(\"memory://\")) {\n const bucket = uri.slice(9);\n if (bucket.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `bucket URI: memory:// URI requires a bucket name (got ${JSON.stringify(uri)})`,\n );\n }\n return { storage: getOrCreateMemoryStorageForBucket(bucket), keyPrefix: \"\" };\n }\n throw new BaerlyError(\"InvalidConfig\", `bucket URI: unsupported URI ${JSON.stringify(uri)}`);\n};\n\nconst requireEnv = (name: string): string => {\n const v = process.env[name];\n if (v === undefined || v === \"\") {\n throw new BaerlyError(\"InvalidConfig\", `bucket URI: env var ${name} unset`);\n }\n return v;\n};\n\n// Endpoint-shape dispatch for `s3://...` URIs. Extracted so the parser\n// doesn't carry an inline nested ternary.\ninterface S3StoragePick {\n readonly r2Host: RegExpMatchArray | null;\n readonly isAws: boolean;\n readonly endpoint: string;\n readonly bucket: string;\n readonly accessKeyId: string;\n readonly secretAccessKey: string;\n readonly region: string;\n}\nconst pickS3Storage = (opts: S3StoragePick): Storage => {\n const { r2Host, isAws, endpoint, bucket, accessKeyId, secretAccessKey, region } = opts;\n if (r2Host !== null) {\n return r2Storage({\n accountId: r2Host[1]!,\n bucket,\n credentials: { accessKeyId, secretAccessKey },\n });\n }\n if (isAws) {\n return s3Storage({ region, bucket, credentials: { accessKeyId, secretAccessKey } });\n }\n return minioStorage({ endpoint, bucket, credentials: { accessKeyId, secretAccessKey } });\n};\n\n// \"/foo\" → \"foo/\"; \"\" → \"\"; \"foo/\" stays \"foo/\". S3 prefixes are\n// keystroke-significant; canonicalize to ensure the manifest pointer\n// at the target matches its source's encoding.\nconst normalizeKeyPrefix = (prefix: string): string => {\n if (prefix === \"\") {\n return \"\";\n }\n if (prefix.endsWith(\"/\")) {\n return prefix;\n }\n return `${prefix}/`;\n};\n","/**\n * `baerly.config.ts` loader for `baerly deploy` / `baerly doctor`.\n *\n * Mirrors the shape of `BaerlyAppConfig` from `@gusto/baerly-storage/config`\n * but lives in `@baerly/cli` so the validator/loader doesn't depend on\n * the rolldown'd umbrella bundle. The scaffolder emits the config file;\n * the CLI reads it. Both sides agree on the wire shape (informally —\n * the duplication is small and intentional).\n *\n * Resolution order:\n * 1. `<cwd>/baerly.config.ts`\n * 2. `<cwd>/baerly.config.js`\n * 3. `<cwd>/baerly.config.mjs`\n * 4. `<cwd>/baerly.config.json`\n *\n * The `.ts` form relies on Node's built-in type stripping, which handles\n * only erasable syntax (no enums, namespaces or parameter properties);\n * a config using other TypeScript syntax fails with\n * `ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX`. If `import()` throws on the\n * `.ts` file, we re-wrap as `InvalidConfig` with a hint pointing at the\n * `.js` / `.json` fallbacks.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport {\n AUTH_CONFIG_VALUES,\n type AuthConfig,\n BaerlyError,\n CF_ACCESS_TEAM_NAME_PATTERN,\n} from \"@baerly/protocol\";\n\nexport interface AppConfig {\n readonly app: string;\n readonly tenant: string;\n readonly target: \"cloudflare\" | \"node\";\n /**\n * Required. See `AuthConfig` for the per-value semantics. The loader\n * throws `BaerlyError(\"InvalidConfig\", ...)` when `auth` is missing or\n * not a member of `AUTH_CONFIG_VALUES`.\n */\n readonly auth: AuthConfig;\n readonly domain?: string;\n readonly requiredSecrets?: readonly string[];\n readonly cloudflareAccess?: {\n readonly teamDomain: string;\n readonly audienceTag: string;\n };\n /** Absolute path to the repo root that contained the config. */\n readonly repoRoot: string;\n}\n\nconst CONFIG_BASENAMES: readonly string[] = [\n \"baerly.config.ts\",\n \"baerly.config.js\",\n \"baerly.config.mjs\",\n \"baerly.config.json\",\n];\n\n/**\n * Locate the first `baerly.config.*` file under `cwd`. Returns the\n * absolute path or `null` if none exists.\n *\n * Exported so the collection-aware loader (and future consumers) can\n * reuse the same resolution order without re-implementing it.\n */\nconst locateConfig = (cwd: string): string | null => {\n for (const base of CONFIG_BASENAMES) {\n const abs = resolve(cwd, base);\n if (existsSync(abs)) {\n return abs;\n }\n }\n return null;\n};\n\n/**\n * Load `baerly.config.{ts,js,mjs,json}` from `cwd` (defaults to\n * `process.cwd()`). Validates the required fields and the\n * locked-shape optionals; returns an `AppConfig` decorated with the\n * `repoRoot` it was loaded from.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — file missing, default\n * export missing, or any field has the wrong shape / type.\n */\nexport const loadAppConfig = async (cwd: string = process.cwd()): Promise<AppConfig> => {\n const cfgPath = locateConfig(cwd);\n if (cfgPath === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: no baerly.config.{ts,js,mjs,json} at ${cwd}. Are you in a baerly app directory?`,\n );\n }\n\n let raw: unknown;\n if (cfgPath.endsWith(\".json\")) {\n let text: string;\n try {\n text = await readFile(cfgPath, \"utf8\");\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to read ${cfgPath}: ${(error as Error).message}`,\n { cause: error },\n );\n }\n try {\n raw = JSON.parse(text) as unknown;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to parse ${cfgPath}: ${(error as Error).message}`,\n { cause: error },\n );\n }\n } else {\n let mod: { default?: unknown };\n try {\n mod = (await import(pathToFileURL(cfgPath).href)) as { default?: unknown };\n } catch (error) {\n const hint = cfgPath.endsWith(\".ts\")\n ? \" (Node strips types only from erasable TypeScript syntax, so enums, namespaces and parameter properties fail with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX — remove them, or point at a compiled .js or a .json config)\"\n : \"\";\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: failed to load ${cfgPath}: ${(error as Error).message}${hint}`,\n { cause: error },\n );\n }\n raw = mod.default;\n }\n\n if (raw === undefined || typeof raw !== \"object\" || raw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath} must default-export a BaerlyAppConfig object`,\n );\n }\n\n const obj = raw as Record<string, unknown>;\n const app = obj[\"app\"];\n const tenant = obj[\"tenant\"];\n const target = obj[\"target\"];\n if (typeof app !== \"string\" || app.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`app\\` must be a non-empty string`,\n );\n }\n if (typeof tenant !== \"string\" || tenant.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`tenant\\` must be a non-empty string`,\n );\n }\n if (target !== \"cloudflare\" && target !== \"node\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`target\\` must be \"cloudflare\" or \"node\" (got ${JSON.stringify(target)})`,\n );\n }\n\n // `auth` is a required typed posture as of the graduated-auth\n // redesign. The widening cast to `readonly string[]` is needed\n // because `.includes` on a tuple narrows its parameter to the\n // tuple's element type; widening locally is the standard idiom.\n const authRaw = obj[\"auth\"];\n if (typeof authRaw !== \"string\" || !(AUTH_CONFIG_VALUES as readonly string[]).includes(authRaw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`auth\\` is required and must be one of ${JSON.stringify(AUTH_CONFIG_VALUES)} (got ${JSON.stringify(authRaw)})`,\n );\n }\n const auth = authRaw as AuthConfig;\n\n const domainRaw = obj[\"domain\"];\n if (domainRaw !== undefined && typeof domainRaw !== \"string\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`domain\\` must be a string when set`,\n );\n }\n\n const secretsRaw = obj[\"requiredSecrets\"];\n let requiredSecrets: readonly string[] | undefined;\n if (secretsRaw !== undefined) {\n if (!Array.isArray(secretsRaw) || !secretsRaw.every((s) => typeof s === \"string\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`requiredSecrets\\` must be an array of strings`,\n );\n }\n requiredSecrets = secretsRaw as readonly string[];\n }\n\n const cfaRaw = obj[\"cloudflareAccess\"];\n let cloudflareAccess: AppConfig[\"cloudflareAccess\"];\n if (cfaRaw !== undefined) {\n if (typeof cfaRaw !== \"object\" || cfaRaw === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess\\` must be an object when set`,\n );\n }\n const cfa = cfaRaw as Record<string, unknown>;\n const td = cfa[\"teamDomain\"];\n const aud = cfa[\"audienceTag\"];\n if (typeof td !== \"string\" || !CF_ACCESS_TEAM_NAME_PATTERN.test(td)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.teamDomain\\` must be a bare team name of lowercase letters, digits and \"-\", such as \"acme\" (got ${JSON.stringify(td)})`,\n );\n }\n if (typeof aud !== \"string\" || aud.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly: ${cfgPath}: \\`cloudflareAccess.audienceTag\\` must be a non-empty string`,\n );\n }\n cloudflareAccess = { teamDomain: td, audienceTag: aud };\n }\n\n return {\n app,\n tenant,\n target,\n auth,\n ...(domainRaw !== undefined && { domain: domainRaw }),\n ...(requiredSecrets !== undefined && { requiredSecrets }),\n ...(cloudflareAccess !== undefined && { cloudflareAccess }),\n repoRoot: cwd,\n };\n};\n"],"ignoreList":[13,20],"mappings":";;;;;;;;;;;;;;;;;;;AAwBA,MAAa,8BAAsC;;;;;;;;;;;;;;;;;;;;;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