@gusto/baerly-storage 0.6.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 (218) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -512
  3. package/dist/CHANGELOG.md +1137 -378
  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-ypCm3zjt.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-wrVYf4bb.js → cloudflare-CKHYXccw.js} +61 -82
  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-Di_Q01qx.js → deploy-Obj4nE-Z.js} +10 -14
  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 +9 -14
  53. package/dist/dev-vite.js +11 -10
  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-Bx6xSNJj.d.ts → gcs-admin-Dso1HWQj.d.ts} +18 -14
  68. package/dist/gcs.d.ts +19 -7
  69. package/dist/gcs.js +1 -2
  70. package/dist/{goog4-signer-Z7KnJ1su.js → goog4-signer-CeLIABoE.js} +102 -92
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-7zT29K3P.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-DP3ClvcA.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 +119 -92
  103. package/dist/node.js +3 -3
  104. package/dist/{observability-Ch-VQJyE.js → observability-C-ISCCLE.js} +1247 -326
  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-C4qgiXSg.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--LykAdl1.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-DD5gDc7t.d.ts → s3-http-DBC_wiCL.d.ts} +14 -8
  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-CqcKTjw9.js → sha256-4FfGQNPw.js} +9 -9
  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/{aws4fetch.esm-CXE5ZbAa.js → sigv4-sign-5IUflUD_.js} +143 -96
  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-BMFfDUI2.js → src-Actga-bO.js} +949 -363
  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-BV68pqwJ.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-BMZR8o6U.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 +90 -69
  152. package/dist/aws4fetch.esm-CXE5ZbAa.js.map +0 -1
  153. package/dist/bytes-BXdamO3L.js +0 -11
  154. package/dist/bytes-BXdamO3L.js.map +0 -1
  155. package/dist/cloudflare-wrVYf4bb.js.map +0 -1
  156. package/dist/config-B6nTy8e2.js +0 -3095
  157. package/dist/config-B6nTy8e2.js.map +0 -1
  158. package/dist/constants-CfeMWQWk.js +0 -222
  159. package/dist/constants-CfeMWQWk.js.map +0 -1
  160. package/dist/context-DRZ3tZ5l.js.map +0 -1
  161. package/dist/cost-_SE_SVgZ.js +0 -203
  162. package/dist/cost-_SE_SVgZ.js.map +0 -1
  163. package/dist/current-json-C6nhPOm1.js.map +0 -1
  164. package/dist/db-DjjthkTi.d.ts +0 -254
  165. package/dist/deploy-Di_Q01qx.js.map +0 -1
  166. package/dist/doctor-RWVRpvat.js +0 -102
  167. package/dist/doctor-RWVRpvat.js.map +0 -1
  168. package/dist/dump-m2vEYDNY.js +0 -94
  169. package/dist/dump-m2vEYDNY.js.map +0 -1
  170. package/dist/errors-Dfa3p78c.js +0 -78
  171. package/dist/errors-Dfa3p78c.js.map +0 -1
  172. package/dist/export-DenKwEQu.js +0 -401
  173. package/dist/export-DenKwEQu.js.map +0 -1
  174. package/dist/fsck-2Vq-7-e2.js +0 -279
  175. package/dist/fsck-2Vq-7-e2.js.map +0 -1
  176. package/dist/goog4-signer-Z7KnJ1su.js.map +0 -1
  177. package/dist/http-7zT29K3P.js.map +0 -1
  178. package/dist/http-transport-BTgVCY5r.js +0 -1250
  179. package/dist/http-transport-BTgVCY5r.js.map +0 -1
  180. package/dist/index-BHz92Acj.d.ts +0 -162
  181. package/dist/index-CEZKQsKt.d.ts +0 -1113
  182. package/dist/index-uE-w2dgj.d.ts +0 -115
  183. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  184. package/dist/inspect-BpYbH1DM.js +0 -133
  185. package/dist/inspect-BpYbH1DM.js.map +0 -1
  186. package/dist/log-tail-QWU4wlu-.js +0 -514
  187. package/dist/log-tail-QWU4wlu-.js.map +0 -1
  188. package/dist/maintenance-BGHGt2Yg.d.ts +0 -537
  189. package/dist/maintenance-DULFcpd1.js +0 -2144
  190. package/dist/maintenance-DULFcpd1.js.map +0 -1
  191. package/dist/maintenance-fEi-UZ2o.js +0 -1412
  192. package/dist/maintenance-fEi-UZ2o.js.map +0 -1
  193. package/dist/normalize-rjnZLwS4.js +0 -133
  194. package/dist/normalize-rjnZLwS4.js.map +0 -1
  195. package/dist/observability-Ch-VQJyE.js.map +0 -1
  196. package/dist/plan-C4qgiXSg.js.map +0 -1
  197. package/dist/query-C43r-6ib.js +0 -1773
  198. package/dist/query-C43r-6ib.js.map +0 -1
  199. package/dist/rebuild-index-BH1dc1p6.js +0 -81
  200. package/dist/rebuild-index-BH1dc1p6.js.map +0 -1
  201. package/dist/request-u0M51mhJ.js +0 -72
  202. package/dist/request-u0M51mhJ.js.map +0 -1
  203. package/dist/restore-D0VYWzfP.js +0 -778
  204. package/dist/restore-D0VYWzfP.js.map +0 -1
  205. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  206. package/dist/runtime-spec--LykAdl1.js.map +0 -1
  207. package/dist/sha256-CqcKTjw9.js.map +0 -1
  208. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  209. package/dist/src-BMFfDUI2.js.map +0 -1
  210. package/dist/src-DYZ4H1aF.js +0 -392
  211. package/dist/src-DYZ4H1aF.js.map +0 -1
  212. package/dist/src-DvbTEya2.js +0 -536
  213. package/dist/src-DvbTEya2.js.map +0 -1
  214. package/dist/subcommand-BV68pqwJ.js.map +0 -1
  215. package/dist/time-DUqvFMHq.js.map +0 -1
  216. package/dist/usage-BMZR8o6U.js.map +0 -1
  217. package/dist/validate-DtljsCh1.js.map +0 -1
  218. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare.js","names":["#bucket","#callBinding"],"sources":["../packages/adapter-cloudflare/src/r2-binding-storage.ts","../packages/adapter-cloudflare/src/cache.ts","../packages/adapter-cloudflare/src/resolve-storage.ts","../packages/adapter-cloudflare/src/worker.ts"],"sourcesContent":["import {\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\";\n\n/**\n * Construction options for {@link r2BindingStorage}. The factory takes\n * the `R2Bucket` binding directly, so this interface only exists to\n * document the shape consumers see in their `env`.\n */\nexport interface R2BindingStorageOptions {\n /**\n * The R2 binding from `env`. In `wrangler.toml`:\n *\n * [[r2_buckets]]\n * binding = \"BUCKET\"\n * bucket_name = \"baerly-prod\"\n *\n * Then: `r2BindingStorage(env.BUCKET)`.\n */\n bucket: R2Bucket;\n}\n\n/**\n * R2's binding API returns bare-hex ETags (`R2Object.etag`). The\n * `Storage` contract follows S3's wire format — quoted (`\"<hex>\"`).\n * `stripQuotes` is forgiving of unquoted input so external sources\n * that hand us bare hex don't break.\n */\nconst stripQuotes = (etag: string): string =>\n etag.startsWith('\"') && etag.endsWith('\"') ? etag.slice(1, -1) : etag;\nconst quoteEtag = (hex: string): string => `\"${hex}\"`;\n\nclass R2BindingStorageImpl implements Storage {\n readonly #bucket: R2Bucket;\n\n constructor(bucket: R2Bucket) {\n if (bucket === null || bucket === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"r2BindingStorage: bucket binding is null/undefined — check wrangler.toml [[r2_buckets]] and the env var name\",\n );\n }\n this.#bucket = bucket;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const getOpts: R2GetOptions = {};\n if (opts?.ifNoneMatch !== undefined) {\n getOpts.onlyIf = { etagDoesNotMatch: stripQuotes(opts.ifNoneMatch) };\n }\n const obj = await this.#callBinding(() => this.#bucket.get(key, getOpts), `GET ${key}`);\n if (obj === null) {\n return null;\n }\n // R2 returns a bare `R2Object` (no body) when a conditional GET's\n // precondition succeeds — i.e. the caller's copy is current.\n // Match the `Storage` contract's 304 → null semantics.\n if (!(\"body\" in obj) || obj.body === null) {\n return null;\n }\n const body = new Uint8Array(await obj.arrayBuffer());\n return { body, etag: quoteEtag(obj.etag) };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const putOpts: R2PutOptions = {};\n if (opts?.contentType !== undefined) {\n putOpts.httpMetadata = { contentType: opts.contentType };\n }\n if (opts?.ifMatch !== undefined) {\n putOpts.onlyIf = { etagMatches: stripQuotes(opts.ifMatch) };\n } else if (opts?.ifNoneMatch === \"*\") {\n // R2 spells \"create only\" as `etagDoesNotMatch: \"*\"` (wildcard).\n // Do NOT strip the `*` — it's the literal wildcard, not an\n // etag.\n putOpts.onlyIf = { etagDoesNotMatch: \"*\" };\n }\n const result = await this.#callBinding(\n () => this.#bucket.put(key, body, putOpts),\n `PUT ${key}`,\n );\n if (result === null) {\n // Binding signals precondition failure as `null`.\n throw new BaerlyError(\"Conflict\", `PUT ${key}: precondition failed`);\n }\n // `R2Object.uploaded` is the server-side write clock — surface it\n // verbatim. The kernel's adaptive-clock-skew loop consumes it\n // identically to `S3HttpStorage`'s `Date` header.\n return {\n etag: quoteEtag(result.etag),\n serverDate: result.uploaded,\n };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n // R2.delete is idempotent — matches the `Storage.delete` contract.\n await this.#callBinding(() => this.#bucket.delete(key), `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 let cursor: string | undefined = undefined;\n let yielded = 0;\n const startAfter = opts?.startAfter ?? \"\";\n const cap = opts?.maxKeys ?? Infinity;\n while (true) {\n opts?.signal?.throwIfAborted();\n // Break BEFORE the next list() call when the cap is already hit\n // — R2 rejects `limit: 0` with `MaxKeys params must be positive\n // integer <= 1000. (10022)`, so we can't just clamp.\n if (yielded >= cap) {\n return;\n }\n // R2.list: `limit` capped at 1000 per request. Page via\n // `cursor` until `truncated === false`. `startAfter` honored\n // only on the first page (one-shot cursor).\n const listOpts: R2ListOptions = { prefix };\n if (cursor !== undefined) {\n listOpts.cursor = cursor;\n } else if (startAfter !== \"\") {\n listOpts.startAfter = startAfter;\n }\n if (cap !== Infinity) {\n listOpts.limit = Math.min(cap - yielded, 1000);\n }\n const page = await this.#callBinding(() => this.#bucket.list(listOpts), `LIST ${prefix}`);\n for (const obj of page.objects) {\n if (yielded >= cap) {\n return;\n }\n yield {\n key: obj.key,\n etag: quoteEtag(obj.etag),\n lastModified: obj.uploaded,\n };\n yielded += 1;\n }\n if (!page.truncated) {\n return;\n }\n cursor = page.cursor;\n if (cursor === undefined) {\n return;\n }\n }\n }\n\n /**\n * Map binding-layer errors to `BaerlyError` codes. The R2 binding\n * surfaces failures as plain `Error` with messages; sniff the\n * common ones. If the binding ever adds typed errors, tighten the\n * sniff and keep the message fallback for older runtimes.\n */\n async #callBinding<T>(fn: () => Promise<T>, op: string): Promise<T> {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n if (/auth|permission|forbidden/i.test(msg)) {\n throw new BaerlyError(\"AccessDenied\", `${op}: ${msg}`, error);\n }\n if (/not.*found|no.*such.*bucket/i.test(msg)) {\n throw new BaerlyError(\"InvalidConfig\", `${op}: ${msg}`, error);\n }\n throw new BaerlyError(\"NetworkError\", `${op}: ${msg}`, error);\n }\n }\n}\n\n/**\n * Construct a `Storage` backed by a Cloudflare R2 binding. The R2\n * binding bypasses SigV4 entirely: requests are dispatched in-cell\n * over a Cloudflare-internal channel, so the hot path skips\n * canonical-request building, body hashing, and DNS/TLS to a\n * separate origin.\n *\n * Pick this over `S3HttpStorage` when the Worker and bucket are in\n * the same Cloudflare account. Cross-cloud (AWS, GCS) and\n * cross-account R2 stay on the HTTP path.\n *\n * Wire-format conventions:\n * - ETags returned in `\"<hex>\"` (S3 wire format) even though R2's\n * binding returns bare hex. CAS round-trips strip and re-apply\n * the quotes.\n * - `serverDate` from `R2Object.uploaded` — a real server clock,\n * suitable for the kernel's adaptive-clock-skew loop.\n * - `StorageListEntry.lastModified` from the same clock.\n *\n * Errors map to `BaerlyError` via the same convention as\n * `S3HttpStorage`: `AccessDenied` for binding-level permission\n * failures, `NetworkError` for transient R2 platform failures,\n * `InvalidResponse` for precondition (CAS) failures, `InvalidConfig`\n * if the caller hands in a null/undefined binding.\n *\n * @example\n * ```ts\n * import { r2BindingStorage } from \"@gusto/baerly-storage/cloudflare\";\n *\n * export default {\n * fetch(req, env: { BUCKET: R2Bucket }) {\n * const storage = r2BindingStorage(env.BUCKET);\n * // ...wire to Db\n * },\n * };\n * ```\n */\nexport function r2BindingStorage(bucket: R2Bucket): Storage {\n return new R2BindingStorageImpl(bucket);\n}\n","/**\n * Cloudflare Cache API integration for the Worker read path.\n * Worker-only; Node has no equivalent and runs cache-less.\n *\n * Contract:\n * - Only `GET /v1/c/:collection/:id` is cached. LIST URLs\n * (`GET /v1/c/:collection`, with or without filters) bypass the cache.\n * The Cloudflare Cache API exposes no enumeration primitive, so\n * filtered-LIST variants (`?where=...`) cannot be safely\n * invalidated on writes; rather than ship a per-isolate index\n * that only partially survives across the colo-shared cache, we\n * skip list caching entirely. If LIST caching ever becomes a\n * bottleneck, revisit with a cross-isolate primitive (CF Cache\n * Tags, KV-backed invalidation, etc).\n * - `GET /v1/since` and `GET /v1/healthz` also bypass the cache\n * (the long-poll's mutating cursor is not cacheable; healthz is\n * trivially fast and must never go stale).\n * - Cache key is the request URL + a synthetic `__t=<tenantPrefix>`\n * query param. This is the load-bearing correctness invariant:\n * the HTTP contract derives `tenant` from the `Verifier`, not the\n * URL, so two different Verifier outcomes against the same URL\n * must NOT share a cache entry. See `packages/server/src/contract.ts`.\n * - Only 200 responses with non-empty bodies are stored. 401/403/\n * 404/409/500 always bypass `cache.put`. Negative caching is out\n * of scope.\n * - `PATCH` / `DELETE` that return 2xx call `cache.delete()` on the\n * per-doc URL they hit. `POST` targets a LIST URL (uncached), so\n * nothing to bust. Best-effort — failures are swallowed.\n * - No `Cache-Control` header is added on the wire. We rely on\n * explicit invalidation, not TTLs.\n */\n\n/**\n * Methods we treat as mutating for invalidation purposes. Keep this\n * list narrow — adding a method to `WRITE_METHODS` doubles the\n * invalidation surface and matters for correctness.\n */\nconst WRITE_METHODS = new Set<string>([\"POST\", \"PATCH\", \"DELETE\"]);\n\n/** Pathname prefixes that bypass the cache entirely. */\nconst BYPASS_PREFIXES = [\"/v1/since\", \"/v1/healthz\"];\n\n/**\n * `Cache-Control: max-age=<n>` value we set on the cacheable response\n * handed to `cache.put`. workerd's `caches.default.put` silently\n * no-ops on responses without a cacheable directive, so we synthesize\n * one. The value is large because we rely on explicit per-doc\n * invalidation, not expiry — see `invalidateOnWrite`.\n */\nconst CACHE_TTL_SECONDS = 3600;\n\n/**\n * Build the canonical cache-key `Request` for a given `(req,\n * tenantPrefix)`. The synthetic `__t` query parameter scopes the\n * cache per-tenant; without it, two tenants with overlapping URLs\n * would share entries — a security bug.\n *\n * The returned `Request` is GET-only by construction — even when\n * `req.method` is POST/PATCH/DELETE we use the GET form for\n * `cache.delete()` so the read-side write and the write-side bust\n * land on the same key.\n */\nexport function cacheKeyFor(req: Request, tenantPrefix: string): Request {\n const url = new URL(req.url);\n // `set` not `append` — defends against a malicious caller-supplied\n // `?__t=spoof`. The server-controlled value always wins.\n url.searchParams.set(\"__t\", tenantPrefix);\n return new Request(url.toString(), { method: \"GET\" });\n}\n\n/**\n * Should this request bypass the cache layer entirely (both read and\n * invalidate sides)? Healthz + long-poll + anything that isn't a\n * per-doc URL (`/v1/c/:collection/:id`).\n */\nfunction bypassesCache(url: URL): boolean {\n if (BYPASS_PREFIXES.some((p) => url.pathname.startsWith(p))) {\n return true;\n }\n if (!url.pathname.startsWith(\"/v1/c/\")) {\n return true;\n }\n // LIST URLs (`/v1/c/<table>` with no `/<id>`) bypass — see header\n // docstring for why filtered-LIST caching isn't safe here.\n const parts = url.pathname.split(\"/\").filter(Boolean);\n if (parts.length < 4) {\n return true;\n }\n return false;\n}\n\n/**\n * Discriminator returned alongside the response so the adapter can\n * stamp `cache_status` on the canonical line. The cache itself\n * doesn't emit — the adapter owns the canonical line.\n *\n * - `\"hit\"` — the cache returned an entry (both the 304\n * If-None-Match path and the body-bearing 200 path\n * classify as hits; the cache served the request\n * without invoking the handler).\n * - `\"miss\"` — the request was cacheable but the cache had no\n * entry; the handler ran and (when the response was\n * cacheable) its output was stored.\n * - `\"bypass\"` — the request never consulted the cache (non-GET,\n * LIST URL, a path under {@link BYPASS_PREFIXES}, or\n * a path outside `/v1/c/`).\n */\nexport type CacheStatus = \"hit\" | \"miss\" | \"bypass\";\n\n/**\n * Discriminator-tagged return value of {@link withReadCache}. The\n * adapter stamps `cache_status` onto the canonical-line `extra` bag\n * before flushing — see `worker.ts`'s `fetch` handler.\n */\nexport interface ReadCacheResult {\n readonly response: Response;\n readonly cache_status: CacheStatus;\n}\n\n/**\n * Read-path wrapper. Call this in place of invoking the router\n * directly for `GET` requests. Returns `{ response, cache_status }`\n * so the adapter can stamp `cache_status` on the canonical line:\n *\n * - `cache_status: \"bypass\"` — non-GET method, LIST URL, or a path\n * under {@link BYPASS_PREFIXES} (`/v1/since`, `/v1/healthz`), or\n * a path outside `/v1/c/`. The handler runs verbatim and its\n * response is returned untouched.\n * - `cache_status: \"hit\"` — the cache had an entry. Returns\n * either a synthesized 304 (when `If-None-Match` matches the\n * cached ETag) or the cached body (200). The handler does NOT\n * run.\n * - `cache_status: \"miss\"` — the cache had no entry. The handler\n * runs and, if the response is a cacheable 200 with no\n * `Set-Cookie`, the response is stored before being returned.\n */\nexport async function withReadCache(\n req: Request,\n tenantPrefix: string,\n handler: () => Promise<Response>,\n): Promise<ReadCacheResult> {\n const url = new URL(req.url);\n if (req.method !== \"GET\" || bypassesCache(url)) {\n return { response: await handler(), cache_status: \"bypass\" };\n }\n\n // `caches.default` is Workers-only; DOM's `CacheStorage` lib type\n // doesn't expose it, so we cast through `unknown` to the shape we\n // need. miniflare provides the real binding at runtime.\n const cache = (caches as unknown as { default: Cache }).default;\n const key = cacheKeyFor(req, tenantPrefix);\n const cached = await cache.match(key);\n if (cached !== undefined) {\n const etag = cached.headers.get(\"etag\");\n const ifNoneMatch = req.headers.get(\"if-none-match\");\n if (etag !== null && ifNoneMatch !== null && etag === ifNoneMatch) {\n // 304 has no body, but keeps the ETag so a CDN-aware client\n // can continue revalidating against it.\n return {\n response: new Response(null, {\n status: 304,\n headers: { etag },\n }),\n cache_status: \"hit\",\n };\n }\n // Body-bearing hit. Clone so the cache entry stays intact for\n // the next request in the same Worker isolate. Strip the\n // synthetic `Cache-Control` header we added at `cache.put` time\n // so the client never sees TTLs we don't honor (invalidation-only\n // on the wire).\n const cloned = cached.clone();\n const outHeaders = new Headers(cloned.headers);\n outHeaders.delete(\"cache-control\");\n return {\n response: new Response(cloned.body, {\n status: cloned.status,\n statusText: cloned.statusText,\n headers: outHeaders,\n }),\n cache_status: \"hit\",\n };\n }\n\n const fresh = await handler();\n // Only cache stable 200 responses with a non-empty body. The Cache\n // API silently rejects responses with `Set-Cookie`; baerly never\n // sets cookies, but the guard is cheap insurance.\n if (fresh.status === 200 && !fresh.headers.has(\"set-cookie\")) {\n // workerd's `caches.default.put` silently no-ops on responses\n // without a cacheable `Cache-Control` directive. We synthesize\n // one ONLY on the response we hand the cache — the response we\n // return to the caller is untouched (invalidation-only on the\n // wire).\n const headers = new Headers(fresh.headers);\n headers.set(\"cache-control\", `max-age=${CACHE_TTL_SECONDS}`);\n const cacheable = new Response(fresh.clone().body, {\n status: fresh.status,\n statusText: fresh.statusText,\n headers,\n });\n await cache.put(key, cacheable);\n }\n return { response: fresh, cache_status: \"miss\" };\n}\n\n/**\n * Write-path companion. Call this AFTER the handler returns a 2xx\n * for `PATCH` / `DELETE` on a per-doc URL — busts the cache entry\n * for that URL. `POST` targets a LIST URL (uncached), so nothing to\n * bust; this function returns without touching the cache. Failures\n * are swallowed; a stale entry is recoverable via the 304 path on\n * the next read.\n */\nexport async function invalidateOnWrite(\n req: Request,\n tenantPrefix: string,\n responseStatus: number,\n): Promise<void> {\n if (!WRITE_METHODS.has(req.method)) {\n return;\n }\n if (responseStatus < 200 || responseStatus >= 300) {\n return;\n }\n const url = new URL(req.url);\n if (bypassesCache(url)) {\n return;\n }\n // `caches.default` is Workers-only; DOM's `CacheStorage` lib type\n // doesn't expose it, so we cast through `unknown` to the shape we\n // need. miniflare provides the real binding at runtime.\n const cache = (caches as unknown as { default: Cache }).default;\n await cache.delete(cacheKeyFor(req, tenantPrefix));\n}\n","import { BaerlyError, type Storage } from \"@baerly/protocol\";\nimport { r2BindingStorage } from \"./r2-binding-storage.ts\";\nimport type { BaerlyEnv, BaerlyWorkerOptions } from \"./worker.ts\";\n\n/**\n * Resolve the request-time {@link Storage} for a Worker.\n *\n * Precedence: an explicitly injected `options.storage` (the S3-over-HTTP\n * / cross-account path) wins; otherwise the same-account R2 binding\n * `env.BUCKET`. With neither, fail closed with `InvalidConfig` rather\n * than silently serving nothing.\n */\nexport function resolveWorkerStorage(\n options: Pick<BaerlyWorkerOptions, \"storage\">,\n env: Pick<BaerlyEnv, \"BUCKET\">,\n): Storage {\n if (options.storage) {\n return options.storage;\n }\n if (!env.BUCKET) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerlyWorker: no storage available. Bind an R2 bucket as `BUCKET`, \" +\n \"or pass `storage` in the factory options — e.g. \" +\n 'new S3HttpStorage(...) from \"@gusto/baerly-storage/s3\".',\n );\n }\n return r2BindingStorage(env.BUCKET);\n}\n","import { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport {\n type BaerlyAppConfig,\n CF_FREE_MAX_SAFE_FOLD_BYTES,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_PROFILE_CF_PAID,\n type Storage,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { createRouter } from \"@baerly/server/http\";\nimport { handleSpecRequest } from \"@baerly/server/spec\";\nimport { type MaintenanceDispatch, parseMaintenanceEnv } from \"@baerly/server/maintenance\";\nimport {\n CATEGORY,\n type ObservabilityConfig,\n configureObservability,\n createObservabilityContext,\n deriveOutcome,\n flushCanonicalLine,\n flushUnauthorizedAndRespond,\n getLogger,\n observableStorage,\n runWithContext,\n} from \"@baerly/server/observability\";\nimport { type CacheStatus, invalidateOnWrite, withReadCache } from \"./cache.ts\";\nimport { resolveWorkerStorage } from \"./resolve-storage.ts\";\n\n/**\n * Cloudflare Workers have no TTY, so the default sink is always\n * the JSON console sink — log-aggregator-shaped out of the box.\n * Callers can pass `options.observability.sink` to override.\n */\nconst resolveCfSink = (config: ObservabilityConfig | undefined): ObservabilityConfig => {\n const merged = config ?? {};\n return merged.sink !== undefined ? merged : { ...merged, sink: \"console-json\" };\n};\n\n/**\n * Worker bindings consumed by `baerlyWorker` itself. The caller\n * wires these in `wrangler.jsonc`:\n *\n * \"r2_buckets\": [{ \"binding\": \"BUCKET\", \"bucket_name\": \"<your-bucket>\" }],\n *\n * \"vars\": { \"APP\": \"tickets\" }\n *\n * Tenant resolution is owned by the configured `Verifier`; the\n * adapter never reads a tenant-shaped env var. App-specific vars\n * (`SHARED_SECRET`, `CF_ACCESS_*`, `LOG_*`, a `TENANT` literal for\n * single-tenant `sharedSecret` callers, etc.) belong on the\n * caller's own env type — extend this one:\n *\n * ```ts\n * import type { BaerlyEnv } from \"@gusto/baerly-storage/cloudflare\";\n *\n * interface AppEnv extends BaerlyEnv {\n * readonly TENANT: string;\n * readonly SHARED_SECRET?: string;\n * }\n * ```\n *\n * ## In-band maintenance ops-plane vars\n *\n * Two OPTIONAL `vars` tune the write-tick maintenance the adapter\n * dispatches via `ctx.waitUntil` (CF `vars` are always strings):\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` — raise the snapshot-rebuild\n * ceiling `C`. The default ({@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT},\n * 512 KiB) is sized to rebuild in ~5.5 ms under the CF-free ~10 ms\n * CPU budget. On CF **paid** (raised CPU limits) an operator raises\n * this to fold larger snapshots in one shot. A value above\n * {@link CF_FREE_MAX_SAFE_FOLD_BYTES} warns LOUDLY once at init —\n * on a free isolate that fold risks a mid-rebuild CPU kill.\n * - `BAERLY_MAINTENANCE_DISABLE` — kill switch. Any non-empty value\n * other than `\"0\"` / `\"false\"` disables write-tick maintenance.\n * - `BAERLY_MAINTENANCE_PROFILE` — opt-in profile selector. Set to\n * `\"cf-paid\"` on a paid Worker to raise the per-pass throughput caps\n * (GC marks/sweeps, fold entries per pass) to the Node-tier values,\n * exploiting the paid 10,000-subrequest budget. Default / unknown\n * values resolve to `cf-free` (unchanged zero-config behaviour). Does\n * NOT change the snapshot ceilings `C` / `E` — raise those separately\n * via `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`. Must be set consistently on\n * BOTH the write-tick path and the cron path (use\n * {@link resolveCfMaintenanceProfile} in your\n * {@link WorkerScheduledHandler}).\n */\nexport interface BaerlyEnv {\n BUCKET?: R2Bucket;\n APP: string;\n /**\n * Raise the snapshot-rebuild ceiling `C`. Parsed as a number;\n * ignored when unset / non-numeric. Default\n * {@link MAINTENANCE_MAX_FOLD_BYTES_DEFAULT}. A value above\n * {@link CF_FREE_MAX_SAFE_FOLD_BYTES} warns once at init.\n */\n BAERLY_MAINTENANCE_MAX_FOLD_BYTES?: string;\n /**\n * Write-tick maintenance kill switch. Truthy (non-empty, not\n * `\"0\"` / `\"false\"`) disables the in-band fold + GC dispatch.\n */\n BAERLY_MAINTENANCE_DISABLE?: string;\n /**\n * Opt-in maintenance profile. `\"cf-paid\"` raises per-pass throughput\n * caps to Node-tier values on a paid Worker isolate. Default / unknown\n * values resolve to `cf-free`. Does NOT change snapshot ceilings.\n */\n BAERLY_MAINTENANCE_PROFILE?: string;\n}\n\n/**\n * Resolve the maintenance profile from the opt-in operator env var.\n * Default (unset / unknown) is the CPU-killable CF-free profile, so\n * zero-config behavior is unchanged. `cf-paid` raises the per-pass\n * caps to exploit the paid 10,000-subrequest budget; it does NOT change\n * the snapshot ceilings. Used by BOTH the write-tick dispatch and the\n * cron path so the two maintenance triggers stay coherent when the\n * operator wires the recipe below into their scheduled handler.\n */\nexport const resolveCfMaintenanceProfile = (readEnv: (key: string) => string | undefined) =>\n readEnv(\"BAERLY_MAINTENANCE_PROFILE\") === \"cf-paid\"\n ? MAINTENANCE_PROFILE_CF_PAID\n : MAINTENANCE_PROFILE_CF_FREE;\n\n/**\n * Assemble the per-request {@link MaintenanceDispatch} for a Cloudflare\n * Worker.\n *\n * baerly maintains IN-BAND: the writer reads\n * `getCurrentContext()?.maintenance` at its post-commit dispatch point and\n * runs one bounded compact + GC slice on the (rare) write that crosses a\n * maintenance trigger. Reads stay pure — they never tick. There is no\n * cron, no `triggers`, no operator-installed scheduler.\n *\n * On Cloudflare the fold runs in a `ctx.waitUntil` continuation — FIRE\n * AND FORGET off the response ack, so the commit never blocks on it. The\n * isolate stays alive long enough to drain the continuation; the\n * per-pass caps are the TESTED CF-free `WRITE_TICK_*` defaults\n * (`phasesPerTick: \"single\"` — a CPU-killable free isolate does ONE of\n * fold/GC per request, never both), sized so a single pass stays well\n * under the free-tier 50-subrequest budget. An operator on CF **paid**\n * raises the ceiling via `BAERLY_MAINTENANCE_MAX_FOLD_BYTES`; the\n * per-pass entry/sweep caps stay fixed here (raising them toward the\n * 10,000-subrequest paid budget — the default since 2026-02-11, up from\n * 1,000, and configurable to 10M — is a future graduation knob, not a\n * var). Free stays at 50 external / 1,000 internal-service subrequests.\n *\n * The two ops-plane vars are read off the `env` BINDING (a string map),\n * NOT `process.env` — Workers have no process env:\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (`C`). Parsed\n * as a number; ignored when unset / NaN.\n * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Truthy\n * when set to a non-empty value other than `\"0\"` / `\"false\"`.\n *\n * `readEnv` defaults to reading off the bound `env`; the parameter\n * exists for direct unit coverage.\n */\nexport const cfMaintenanceDispatch = (\n ctx: ExecutionContext,\n readEnv: (key: string) => string | undefined,\n): MaintenanceDispatch => {\n const { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);\n\n return {\n // CF dispatches the fold off the ack via `ctx.waitUntil` — the\n // isolate stays alive to drain it without blocking the response.\n dispatch: (task: () => Promise<void>): void => ctx.waitUntil(task()),\n ...(disabled && { disabled: true }),\n ...(maxFoldBytes !== undefined && { maxFoldBytes }),\n options: {\n // A CPU-killable free isolate does ONE phase per request.\n phasesPerTick: \"single\",\n // Write-tick profile. The cron path (user-supplied `scheduled` callback)\n // resolves the profile via the SAME `resolveCfMaintenanceProfile` export\n // so the two maintenance triggers stay coherent when the operator wires\n // the recipe below into their `scheduled` handler.\n profile: resolveCfMaintenanceProfile(readEnv),\n },\n };\n};\n\n/**\n * Cron Trigger handler. Called once per tick when the user has\n * declared `triggers.crons` in `wrangler.jsonc` AND passed this\n * option. The body owns its own subrequest budget — wrap any\n * outlasting work in `ctx.waitUntil(...)`. Multi-tenant deployments\n * typically iterate a list of `current.json` keys and call\n * {@link runScheduledMaintenance} per tenant.\n */\nexport type WorkerScheduledHandler = (\n event: ScheduledController,\n env: BaerlyEnv,\n ctx: ExecutionContext,\n) => Promise<void> | void;\n\nexport interface BaerlyWorkerOptions {\n /**\n * Your `baerly.config.ts`. **Required.** Carries `auth`,\n * `tenant`, and the declared `collections` (their schemas/indexes\n * flow through to per-request `Db.create` automatically).\n *\n * The adapter resolves the per-request `Verifier` from\n * `config.auth` when no `verifier:` override is supplied — see\n * resolution order on {@link verifier} below.\n *\n * Only `collections` is read for runtime kernel wiring — fields\n * like `target`, `domain`, `cloudflareAccess` are deploy-time\n * concerns that the adapter ignores.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Request-time `Storage`. **Optional.** When unset, the Worker uses\n * the same-account R2 binding `env.BUCKET` (the dominant path). Inject\n * this to talk to S3 / cross-account R2 over the S3 REST API\n * from a Worker — e.g. `new S3HttpStorage(...)` +\n * `sigV4Signer(...)` from `@gusto/baerly-storage/s3`. Resolved once\n * per isolate inside the factory (where `env` is in scope), same as\n * the R2 binding.\n */\n readonly storage?: Storage;\n /**\n * Cron Trigger handler. When unset, `scheduled()` is a no-op even\n * if `triggers.crons` is declared. See {@link WorkerScheduledHandler}.\n */\n readonly scheduled?: WorkerScheduledHandler;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides\n * `config.auth` (the \"dev default in config, prod override via env\"\n * recipe). When unset, the adapter synthesizes one from\n * `config.auth`:\n *\n * - `\"shared-secret\"` → `sharedSecret({ secret: env.SHARED_SECRET,\n * tenantPrefix: config.tenant })`. Throws `InvalidConfig` on\n * first fetch when `SHARED_SECRET` is missing/empty.\n * - `\"none\"` → pins every request to `config.tenant` with no\n * header check.\n *\n * `GET /v1/healthz` always bypasses the verifier.\n *\n * Multi-tenant deployments compose their own verifier on top of a\n * real IdP — JWT, SigV4, Cloudflare Access, etc.\n */\n readonly verifier?: Verifier;\n /**\n * Observability config (LogTape sink + level). When supplied, the\n * Worker calls {@link configureObservability} lazily on first\n * `fetch` / `scheduled` invocation (CF Worker modules can't\n * `await` at the top level). `configureObservability` is\n * idempotent over baerly's own config — it re-runs with\n * `{ reset: true }`, last call wins — and skips over a host config\n * it detects, so re-invocation is harmless.\n *\n * - `level` falls through to `env.LOG_LEVEL` (when typed option\n * is undefined).\n * - `sink` defaults to `\"console-json\"` (Cloudflare's stdout is\n * ingested by Workers Logs as JSON-shaped records).\n *\n * When the field is unset (or `{}`), baerly auto-configures on first\n * `fetch`. Pass `false` to skip configuration entirely — the escape\n * hatch for Workers that embed baerly and own the isolate-wide\n * LogTape configuration themselves. (baerly also never clobbers a\n * host config it detects; `false` additionally suppresses the\n * configure attempt and its meta-logger notice.)\n */\n readonly observability?: ObservabilityConfig | false;\n /**\n * Opt-in dev affordance. When set, `GET /` returns a small\n * human-readable HTML page that links to {@link DevLandingOptions.uiUrl},\n * and `GET /favicon.ico` returns 204 No Content. Leave unset on\n * production Workers — `/` falls through to the existing 404\n * envelope when this option is absent.\n */\n readonly dev?: DevLandingOptions;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Workers module-default export.\n *\n * Order on `fetch`: **healthz → verifier → router**. Health probes\n * don't pay for a Db construction; an auth challenge stops a bad\n * request before any Storage I/O; the router catches everything else.\n *\n * Observability: every HTTP request that flows past the verifier\n * runs inside a single `runWithContext` scope created up front in\n * this adapter — including the read-cache wrapper. The canonical\n * line emitted at end-of-request carries a top-level\n * `cache_status: \"hit\" | \"miss\" | \"bypass\"` field so operators can\n * split hit/miss/bypass directly from the log stream without\n * consulting a CDN dashboard. The router's observability middleware\n * detects the ambient context and passes through — the adapter owns\n * the flush.\n *\n * Cron Triggers are opt-in. Pass `options.scheduled` to wire one;\n * `wrangler.jsonc:triggers.crons` controls the firing cadence.\n * When `options.scheduled` is unset the cron tick is a no-op.\n *\n * The factory receives `env` on the first `fetch` or `scheduled`\n * invocation, resolves `BaerlyWorkerOptions` once, and caches the\n * result for the lifetime of the isolate. Cloudflare Workers cannot\n * `await` at the module top level — the factory pattern is the\n * supported way to read env bindings at startup.\n *\n * @example\n * ```ts\n * import { baerlyWorker } from \"@gusto/baerly-storage/cloudflare\";\n * import config from \"../../baerly.config.ts\";\n *\n * // Dev default: `auth: \"none\"` in baerly.config.ts pins every\n * // request to `config.tenant`. Switch to `auth: \"shared-secret\"`\n * // for staging/prod and `wrangler secret put SHARED_SECRET`.\n * export default baerlyWorker(() => ({ config }));\n * ```\n */\nexport function baerlyWorker<E extends BaerlyEnv = BaerlyEnv>(\n factory: (env: E) => BaerlyWorkerOptions,\n): ExportedHandler<E> {\n // Cached resolution: populated on first fetch/scheduled, reused on\n // every subsequent invocation. Cloudflare Workers can't `await` at\n // the module top level, so we lazy-init on first call to whichever\n // handler fires first.\n interface ResolvedState {\n readonly options: BaerlyWorkerOptions;\n readonly verifier: Verifier;\n // Base Storage resolved once per isolate (injected `options.storage`\n // or the `env.BUCKET` R2 binding), same lifetime as `verifier`. The\n // per-request `observableStorage(...)` wrap still happens on every\n // request — it binds to the request's observability bag — but the\n // underlying handle is no longer reconstructed each time.\n readonly storage: Storage;\n }\n let resolved: ResolvedState | undefined;\n // Cached so every subsequent fetch re-throws the same error rather\n // than re-running `resolveVerifier` on every request after a\n // misconfig. Mirrors the \"first fetch errors, every fetch errors\"\n // contract documented on `auth: \"shared-secret\"` + missing env.\n let resolutionError: unknown;\n let observabilityConfigured = false;\n // Fired at most once per isolate: an operator who raised the snapshot\n // ceiling above what a free CF isolate can rebuild in one shot gets a\n // loud warning. Init-scoped (not per-request) so a busy Worker doesn't\n // spam the log stream.\n let maintenanceCeilingWarned = false;\n\n const ensureResolved = async (env: E): Promise<ResolvedState> => {\n if (resolutionError !== undefined) {\n throw resolutionError;\n }\n if (resolved === undefined) {\n try {\n const options = factory(env);\n const verifier = resolveVerifier({\n factoryVerifier: options.verifier,\n config: options.config,\n readEnv: (k) => {\n const value = (env as unknown as Record<string, unknown>)[k];\n return typeof value === \"string\" ? value : undefined;\n },\n });\n resolved = { options, verifier, storage: resolveWorkerStorage(options, env) };\n } catch (error) {\n resolutionError = error;\n throw error;\n }\n }\n // Lazy-init flag for `configureObservability`. CF Worker modules\n // cannot `await` at the module top level, so the first fetch /\n // scheduled invocation runs the configure. LogTape's `configure`\n // is idempotent (we always pass `reset: true`); a thundering-herd\n // race on the cold-start tick just re-runs the same config.\n if (!observabilityConfigured && resolved.options.observability !== false) {\n await configureObservability(resolveCfSink(resolved.options.observability));\n observabilityConfigured = true;\n // Emit the auth=none startup banner exactly once per isolate.\n // Suppress when an explicit `verifier:` override is in play —\n // the override wins, the log would be misleading. Suppress\n // when `auth === \"shared-secret\"` — the operator already knows.\n if (resolved.options.verifier === undefined && resolved.options.config.auth === \"none\") {\n getLogger(CATEGORY.http).info(\n `[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(resolved.options.config.tenant)}`,\n );\n }\n }\n // Ops-plane guardrail, init-scoped: if the operator raised the\n // snapshot-rebuild ceiling above what a CF FREE isolate can rebuild\n // under its ~10 ms CPU budget, warn LOUDLY exactly once. A fold over\n // this size on a free isolate gets CPU-killed mid-rebuild — the CAS\n // never lands, so the fold silently never advances `log_seq_start`\n // and the tail grows unbounded. `console.warn` (not LogTape) so the\n // signal survives even when observability is unconfigured.\n if (!maintenanceCeilingWarned) {\n maintenanceCeilingWarned = true;\n const rawFoldBytes = (env as unknown as Record<string, unknown>)[\n \"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\"\n ];\n const { maxFoldBytes } = parseMaintenanceEnv((k) =>\n typeof rawFoldBytes === \"string\" && k === \"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\"\n ? rawFoldBytes\n : undefined,\n );\n if (maxFoldBytes !== undefined && maxFoldBytes > CF_FREE_MAX_SAFE_FOLD_BYTES) {\n console.warn(\n `[baerly] BAERLY_MAINTENANCE_MAX_FOLD_BYTES=${rawFoldBytes} exceeds the ` +\n `CF free-tier safe ceiling (${CF_FREE_MAX_SAFE_FOLD_BYTES} bytes). On a free ` +\n `Worker a fold this large risks a mid-rebuild CPU kill (the ~10 ms limit): the ` +\n `current.json CAS never lands, so the fold silently does NOT advance and the tail ` +\n `grows unbounded. Safe remedies: run on CF PAID (raised CPU limits), self-host on ` +\n `NODE, or wait for §11 chunked snapshots. Leave this var unset on free CF.`,\n );\n }\n }\n return resolved;\n };\n\n return {\n async fetch(req, env, ctx): Promise<Response> {\n const url = new URL(req.url);\n\n // /v1/spec — anonymous static contract IR. Keep this before\n // `ensureResolved`: even a verifier/config-resolution failure\n // should not hide the public machine contract. Tenant collections\n // are appended only when resolution succeeds AND the verifier\n // accepts.\n if (req.method === \"GET\" && url.pathname === \"/v1/spec\") {\n return handleSpecRequest(req, async () => {\n const { options, verifier } = await ensureResolved(env);\n return { verifier, config: options.config };\n });\n }\n\n const { options, verifier, storage: baseStorage } = await ensureResolved(env);\n\n // Opt-in dev landing page. Off in production (options.dev\n // unset); when set, GET / serves HTML and GET /favicon.ico\n // returns 204 so browsers don't pin a second JSON 404 next\n // to the landing page.\n if (options.dev !== undefined && req.method === \"GET\") {\n if (url.pathname === \"/\") {\n return new Response(renderDevLanding(options.dev), {\n status: 200,\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n }\n if (url.pathname === \"/favicon.ico\") {\n return new Response(null, { status: 204 });\n }\n }\n\n // Healthz is always anonymous — Cloudflare's load balancer\n // probes it. Keep it ahead of the verifier check; serving it\n // here avoids a `Db.create` (and the canonical-line emission)\n // on every probe. The router no longer mounts healthz — only\n // the adapter does.\n if (req.method === \"GET\" && url.pathname === \"/v1/healthz\") {\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Construct the per-request observability context up front so\n // EVERYTHING downstream — verifier rejection, `Db.create`, and\n // the read-cache wrapper — runs inside the same\n // `runWithContext` scope. Without this lift, a verifier\n // rejection (or a cache-hit short-circuit) would bypass\n // canonical-line emission entirely.\n //\n // The router's observability middleware (see `router.ts`\n // \"Mode A\") detects the ambient context and passes through —\n // it never creates a competing context, and it never flushes\n // its own line. The adapter owns the flush from here on.\n const requestId = req.headers.get(\"x-request-id\") ?? crypto.randomUUID();\n // In-band write-tick maintenance: the writer reads\n // `getCurrentContext()?.maintenance` at its post-commit dispatch\n // point. On CF the fold is dispatched via `ctx.waitUntil` (off the\n // ack) with the CF-free caps + `phasesPerTick: \"single\"`; the\n // ops-plane vars are read off the `env` binding (strings). Built\n // per request so a hot-swapped `env` is observed at call time.\n const obsCtx = createObservabilityContext({\n request_id: requestId,\n maintenance: cfMaintenanceDispatch(ctx, (k) => {\n const value = (env as unknown as Record<string, unknown>)[k];\n return typeof value === \"string\" ? value : undefined;\n }),\n });\n\n // Tenant resolution: the Verifier owns it unconditionally.\n const result = await verifier(req);\n if (result === null) {\n return runWithContext(obsCtx, async () => flushUnauthorizedAndRespond(obsCtx, req));\n }\n const tenantPrefix = result.tenantPrefix;\n\n return runWithContext(obsCtx, async (): Promise<Response> => {\n // Storage is wrapped with `observableStorage(...)` so the\n // per-call class A/B counts and per-op duration histograms\n // land in the active per-request bag. Writer / compactor / GC\n // emissions reach the same bag via `getCurrentContext()?.recorder`\n // — the canonical-line flusher reads it at end-of-request. The\n // base handle is resolved once per isolate (see `ResolvedState`);\n // only the observability wrap is per-request.\n const storage = observableStorage(baseStorage);\n const db = Db.create({\n storage,\n app: env.APP,\n tenant: tenantPrefix,\n config: options.config,\n });\n\n const app = createRouter({\n db,\n sinceTimeoutMs: options.sinceTimeoutMs,\n sincePollIntervalMs: options.sincePollIntervalMs,\n });\n\n let cacheStatus: CacheStatus = \"bypass\";\n let response: Response | undefined;\n let caughtError: unknown;\n try {\n // Hono's `fetch` returns `Response | Promise<Response>`;\n // `withReadCache` wants a `Promise<Response>`. Normalize\n // via `Promise.resolve` so the sync-return branch is wrapped.\n const cacheResult = await withReadCache(req, tenantPrefix, () =>\n Promise.resolve(app.fetch(req, env, ctx)),\n );\n cacheStatus = cacheResult.cache_status;\n response = cacheResult.response;\n } catch (error) {\n caughtError = error;\n throw error;\n } finally {\n const status = caughtError !== undefined ? 500 : (response?.status ?? 500);\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status,\n outcome: deriveOutcome(req.method, status, caughtError),\n ...(caughtError !== undefined && { error: caughtError }),\n extra: {\n method: req.method,\n path: new URL(req.url).pathname,\n cache_status: cacheStatus,\n },\n });\n }\n // `response` is defined here — the `catch` arm above rethrew,\n // so reaching this line implies the try block completed.\n // Best-effort invalidate after writes. `ctx.waitUntil` keeps\n // the Worker alive for the cache.delete without blocking\n // the response.\n ctx.waitUntil(invalidateOnWrite(req, tenantPrefix, response!.status));\n return response!;\n });\n },\n\n async scheduled(event, env, ctx): Promise<void> {\n const { options } = await ensureResolved(env);\n if (options.scheduled !== undefined) {\n // To honour BAERLY_MAINTENANCE_PROFILE on the cron path, call\n // `runScheduledMaintenance(args, CLOUDFLARE_PAID_TIER)` when the\n // profile is \"cf-paid\", or `CLOUDFLARE_FREE_TIER` (the default) —\n // both imported from `@gusto/baerly-storage/maintenance`. Use\n // `resolveCfMaintenanceProfile((k) => env[k])` (exported from this\n // module) to read the env var inside your WorkerScheduledHandler.\n await options.scheduled(event, env, ctx);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAmCA,MAAM,eAAe,SACnB,KAAK,WAAW,IAAG,KAAK,KAAK,SAAS,IAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACnE,MAAM,aAAa,QAAwB,IAAI,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M,UAAU,OAAO,KAAK,KAAoB;GAC9C,MAAM,EAAE,YAAY,MAAM,eAAe,GAAG;GAC5C,IAAI,QAAQ,cAAc,KAAA,GAOxB,MAAM,QAAQ,UAAU,OAAO,KAAK,GAAG;EAE3C;CACF;AACF"}
1
+ {"version":3,"file":"cloudflare.js","names":[],"sources":["../packages/adapter-cloudflare/src/r2-binding-storage.ts","../packages/adapter-cloudflare/src/resolve-storage.ts","../packages/adapter-cloudflare/src/worker.ts"],"sourcesContent":["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\";\n\n/**\n * Construction options for {@link r2BindingStorage}. The factory takes\n * the `R2Bucket` binding directly, so this interface only exists to\n * document the shape consumers see in their `env`.\n */\nexport interface R2BindingStorageOptions {\n /**\n * The R2 binding from `env`. In `wrangler.toml`:\n *\n * [[r2_buckets]]\n * binding = \"BUCKET\"\n * bucket_name = \"baerly-prod\"\n *\n * Then: `r2BindingStorage(env.BUCKET)`.\n */\n bucket: R2Bucket;\n}\n\n/**\n * R2's binding API returns bare-hex ETags (`R2Object.etag`). The\n * `Storage` contract follows S3's wire format — quoted (`\"<hex>\"`).\n * `stripQuotes` is forgiving of unquoted input so external sources\n * that hand us bare hex don't break.\n */\nconst stripQuotes = (etag: string): string =>\n etag.startsWith('\"') && etag.endsWith('\"') ? etag.slice(1, -1) : etag;\nconst quoteEtag = (hex: string): string => `\"${hex}\"`;\n\n/** R2 error `10058` `TooManyRequests` at the end of a binding error message. */\nconst R2_TOO_MANY_REQUESTS = /\\(10058\\)\\s*$/;\n/**\n * workerd's per-invocation subrequest limit. An R2 binding call past the\n * 1,000 internal calls throws \"Too many API requests by single Worker\n * invocation\" (observed on Workers Free, 2026-11-18); \"Too many\n * subrequests …\" is the `fetch` cap's wording, matched in case a runtime\n * reports the binding cap that way.\n */\nconst WORKERS_SUBREQUEST_LIMIT =\n /too many (?:api requests|subrequests) by single worker invocation/i;\n\nclass R2BindingStorageImpl implements Storage {\n readonly #bucket: R2Bucket;\n\n constructor(bucket: R2Bucket) {\n if (bucket === null || bucket === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"r2BindingStorage: bucket binding is null/undefined — check wrangler.toml [[r2_buckets]] and the env var name\",\n );\n }\n this.#bucket = bucket;\n }\n\n async get(key: string, opts?: StorageGetOptions): Promise<StorageGetResult | null> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const obj = await this.#callBinding(() => this.#bucket.get(key), `GET ${key}`, {\n signal: opts?.signal,\n });\n if (obj === null) {\n return null;\n }\n const body = new Uint8Array(await obj.arrayBuffer());\n return { body, etag: quoteEtag(obj.etag) };\n }\n\n async put(key: string, body: Uint8Array, opts?: StoragePutOptions): Promise<StoragePutResult> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n const putOpts: R2PutOptions = {};\n if (opts?.contentType !== undefined) {\n putOpts.httpMetadata = { contentType: opts.contentType };\n }\n if (opts?.ifMatch !== undefined) {\n putOpts.onlyIf = { etagMatches: stripQuotes(opts.ifMatch) };\n } else if (opts?.ifNoneMatch === \"*\") {\n // R2 spells \"create only\" as `etagDoesNotMatch: \"*\"` (wildcard).\n // Do NOT strip the `*` — it's the literal wildcard, not an\n // etag.\n putOpts.onlyIf = { etagDoesNotMatch: \"*\" };\n }\n const result = await this.#callBinding(\n () => this.#bucket.put(key, body, putOpts),\n `PUT ${key}`,\n {\n conditionalCreate: opts?.ifNoneMatch === \"*\",\n // An `etagMatches` CAS is never resent: a resend after a lost ack\n // would see its own write as a precondition failure.\n compareAndSwap: opts?.ifMatch !== undefined,\n signal: opts?.signal,\n },\n );\n if (result === null) {\n // Binding signals precondition failure as `null`. It resolves rather\n // than throws, so it ends the retry loop: a lost-ack resend of a\n // create that already landed surfaces here as a precondition failure,\n // which the Writer resolves by readback.\n throw new BaerlyError(\"WriteConflict\", `PUT ${key}: precondition failed`);\n }\n // `R2Object.uploaded` is the server-side write clock — surface it\n // verbatim. The kernel's adaptive-clock-skew loop consumes it\n // identically to `S3HttpStorage`'s `Date` header.\n return {\n etag: quoteEtag(result.etag),\n serverDate: result.uploaded,\n };\n }\n\n async delete(key: string, opts?: { signal?: AbortSignal }): Promise<void> {\n assertValidStorageKey(key);\n opts?.signal?.throwIfAborted();\n // R2.delete is idempotent — matches the `Storage.delete` contract.\n await this.#callBinding(() => this.#bucket.delete(key), `DELETE ${key}`, {\n signal: opts?.signal,\n });\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 cursor: string | undefined = undefined;\n let yielded = 0;\n const startAfter = opts?.startAfter ?? \"\";\n const cap = opts?.maxKeys ?? Infinity;\n while (true) {\n opts?.signal?.throwIfAborted();\n // Break BEFORE the next list() call when the cap is already hit\n // — R2 rejects `limit: 0` with `MaxKeys params must be positive\n // integer <= 1000. (10022)`, so we can't just clamp.\n if (yielded >= cap) {\n return;\n }\n // R2.list: `limit` capped at 1000 per request. Page via\n // `cursor` until `truncated === false`. `startAfter` honored\n // only on the first page (one-shot cursor).\n const listOpts: R2ListOptions = { prefix };\n if (cursor !== undefined) {\n listOpts.cursor = cursor;\n } else if (startAfter !== \"\") {\n listOpts.startAfter = startAfter;\n }\n if (cap !== Infinity) {\n listOpts.limit = Math.min(cap - yielded, 1000);\n }\n const page = await this.#callBinding(() => this.#bucket.list(listOpts), `LIST ${prefix}`, {\n signal: opts?.signal,\n });\n for (const obj of page.objects) {\n if (yielded >= cap) {\n return;\n }\n yield {\n key: obj.key,\n etag: quoteEtag(obj.etag),\n };\n yielded += 1;\n }\n if (!page.truncated) {\n return;\n }\n cursor = page.cursor;\n if (cursor === undefined) {\n return;\n }\n }\n }\n\n /**\n * Run one binding call under the shared storage retry policy\n * (`retryStorageCall`: 3 attempts, full-jitter backoff), mapping\n * binding-layer errors to `BaerlyError` codes. The R2 binding surfaces\n * failures as plain `Error` with messages; sniff the common ones. If\n * the binding ever adds typed errors, tighten the sniff and keep the\n * message fallback for older runtimes.\n *\n * `AccessDenied` and `InvalidConfig` are permanent and not retried, and\n * no attempt follows the caller's abort, whatever its reason. An\n * `ifMatch` put (`compareAndSwap`) gets one attempt and no retry at all.\n * Two `NetworkError`s have distinct retry behavior:\n *\n * - R2 error `10058` (`TooManyRequests`, 429: \"limit: 1 write/second\n * per key\") is tagged `throttled`, so it is retried from the throttle\n * backoff base. Its `mayHaveApplied` flag preserves create uncertainty:\n * Cloudflare does not document that this error proves an unapplied write.\n * R2 binding errors end `message` with the\n * error code in parentheses\n * (https://developers.cloudflare.com/r2/api/error-codes/).\n * - The Workers per-invocation limit (\"Too many API requests\" on a\n * binding call) is tagged `refused`: not\n * retried, since every later call in the invocation is refused too,\n * and `notApplied` on a create when no earlier attempt is uncertain.\n * The message match is a backstop, not the primary guard.\n *\n * The Writer reads back a failed create: an own entry is adopted, a\n * foreign entry advances to the next slot, and an unknown outcome stays\n * `AmbiguousCommit` even when the slot is currently empty. A negative\n * read cannot prove that an unresolved write will never land.\n *\n * Everything else is a `NetworkError` with an unknown outcome, so an\n * exhausted conditional create does not report `notApplied`.\n */\n #callBinding<T>(\n fn: () => Promise<T>,\n op: string,\n mode: {\n conditionalCreate?: boolean;\n compareAndSwap?: boolean;\n signal?: AbortSignal | undefined;\n } = {},\n ): Promise<T> {\n const { signal, ...retryMode } = mode;\n return retryStorageCall(\n async () => {\n try {\n return await fn();\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n const msg = error instanceof Error ? error.message : String(error);\n if (R2_TOO_MANY_REQUESTS.test(msg)) {\n throw new BaerlyError(\"NetworkError\", `${op}: ${msg}`, {\n cause: { status: 429, throttled: true, mayHaveApplied: true, error },\n });\n }\n if (WORKERS_SUBREQUEST_LIMIT.test(msg)) {\n throw new BaerlyError(\"NetworkError\", `${op}: ${msg}`, {\n cause: { refused: true, error },\n });\n }\n if (/auth|permission|forbidden/i.test(msg)) {\n throw new BaerlyError(\"AccessDenied\", `${op}: ${msg}`, { cause: error });\n }\n if (/not.*found|no.*such.*bucket/i.test(msg)) {\n throw new BaerlyError(\"InvalidConfig\", `${op}: ${msg}`, { cause: error });\n }\n throw new BaerlyError(\"NetworkError\", `${op}: ${msg}`, { cause: error });\n }\n },\n // Binding calls are subrequests to an internal service: charged to\n // the request ledger's `internal` pool only.\n // The binding takes no signal, so a call in flight runs to its end;\n // once the caller has aborted, no further attempt is made.\n { ...retryMode, pool: \"internal\", ...(signal !== undefined && { signal }) },\n );\n }\n}\n\n/**\n * Construct a `Storage` backed by a Cloudflare R2 binding. The R2\n * binding bypasses SigV4 entirely: requests are dispatched in-cell\n * over a Cloudflare-internal channel, so the hot path skips\n * canonical-request building, body hashing, and DNS/TLS to a\n * separate origin.\n *\n * Pick this over `S3HttpStorage` when the Worker and bucket are in\n * the same Cloudflare account. Cross-cloud (AWS, GCS) and\n * cross-account R2 stay on the HTTP path.\n *\n * Wire-format conventions:\n * - ETags returned in `\"<hex>\"` (S3 wire format) even though R2's\n * binding returns bare hex. CAS round-trips strip and re-apply\n * the quotes.\n * - `serverDate` from `R2Object.uploaded` — a real server clock,\n * suitable for the kernel's adaptive-clock-skew loop. `list()`\n * yields `key` + `etag` only; `StorageListEntry` carries no\n * per-entry timestamp.\n *\n * Errors map to `BaerlyError` via the same convention as\n * `S3HttpStorage`: `AccessDenied` for binding-level permission\n * failures, `NetworkError` for transient R2 platform failures,\n * `InvalidResponse` for precondition (CAS) failures, `InvalidConfig`\n * if the caller hands in a null/undefined binding. A failing binding\n * call is retried under the same policy as `S3HttpStorage`: at most 3\n * calls per `get` / `put` / `delete` and per `list` page.\n *\n * @example\n * ```ts\n * import { r2BindingStorage } from \"@gusto/baerly-storage/cloudflare\";\n *\n * export default {\n * fetch(req, env: { BUCKET: R2Bucket }) {\n * const storage = r2BindingStorage(env.BUCKET);\n * // ...wire to Db\n * },\n * };\n * ```\n */\nexport function r2BindingStorage(bucket: R2Bucket): Storage {\n return new R2BindingStorageImpl(bucket);\n}\n\n/**\n * Whether `storage` is the R2 binding itself (from {@link r2BindingStorage}).\n * R2 binding calls do not count toward Workers Free's 50 external\n * subrequests; anything else a Worker is given (`S3HttpStorage`, or a\n * wrapper around either) is assumed to reach the bucket through `fetch`,\n * where every call does.\n */\nexport const isR2BindingStorage = (storage: Storage): boolean =>\n storage instanceof R2BindingStorageImpl;\n","import { BaerlyError, type Storage } from \"@baerly/protocol\";\nimport { r2BindingStorage } from \"./r2-binding-storage.ts\";\nimport type { BaerlyEnv, BaerlyWorkerOptions } from \"./worker.ts\";\n\n/**\n * Resolve the request-time {@link Storage} for a Worker.\n *\n * Precedence: an explicitly injected `options.storage` (the S3-over-HTTP\n * / cross-account path) wins; otherwise the same-account R2 binding\n * `env.BUCKET`. With neither, fail closed with `InvalidConfig` rather\n * than silently serving nothing.\n */\nexport function resolveWorkerStorage(\n options: Pick<BaerlyWorkerOptions, \"storage\">,\n env: Pick<BaerlyEnv, \"BUCKET\">,\n): Storage {\n if (options.storage) {\n return options.storage;\n }\n if (!env.BUCKET) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerlyWorker: no storage available. Bind an R2 bucket as `BUCKET`, \" +\n \"or pass `storage` in the factory options — e.g. \" +\n 'new S3HttpStorage(...) from \"@gusto/baerly-storage/s3\".',\n );\n }\n return r2BindingStorage(env.BUCKET);\n}\n","// Imported from the leaf module, NOT the `@baerly/dev` barrel. The barrel\n// re-exports `LocalFsStorage`, and pulling this through it chunks the whole\n// Node-only local-fs closure — `node:crypto`, `node:fs/promises`, `node:os`,\n// `node:path` — into the Worker bundle for the sake of one HTML string.\n// `dev-landing.ts` has no imports at all.\nimport { type DevLandingOptions, renderDevLanding } from \"@baerly/dev/dev-landing\";\nimport {\n type BaerlyAppConfig,\n BaerlyError,\n CF_FREE_EXTERNAL_REQUEST_LIMIT,\n CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES,\n CF_FREE_FETCH_GC_MAX_SWEEPS,\n CF_FREE_INTERNAL_REQUEST_LIMIT,\n CF_FREE_MAX_SAFE_FOLD_BYTES,\n CF_PAID_REQUEST_LIMIT,\n MAINTENANCE_PROFILE_CF_FREE,\n MAINTENANCE_PROFILE_CF_PAID,\n RequestLedger,\n type Storage,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { Db } from \"@baerly/server\";\nimport { resolveVerifier, withNosniff } from \"@baerly/server/_internal/kernel\";\nimport { createRouter, mapError } from \"@baerly/server/http\";\nimport { handleSpecRequest } from \"@baerly/server/spec\";\nimport {\n type MaintenanceDispatch,\n parseMaintenanceEnv,\n} from \"@baerly/server/_internal/maintenance\";\nimport {\n CATEGORY,\n type ObservabilityConfig,\n configureObservability,\n deriveOutcome,\n flushCanonicalLine,\n getLogger,\n observableStorage,\n runWithContext,\n} from \"@baerly/server/observability\";\nimport {\n createObservabilityContext,\n type ReadEnvelope,\n flushUnauthorizedAndRespond,\n logMaintenanceWarning,\n requestIdFrom,\n} from \"@baerly/server/_internal/observability\";\nimport { isR2BindingStorage } from \"./r2-binding-storage.ts\";\nimport { resolveWorkerStorage } from \"./resolve-storage.ts\";\n\n/**\n * Cloudflare Workers have no TTY, so the default sink is always\n * the JSON console sink — log-aggregator-shaped out of the box.\n * Callers can pass `options.observability.sink` to override.\n */\nconst resolveCfSink = (config: ObservabilityConfig | undefined): ObservabilityConfig => {\n const merged = config ?? {};\n return merged.sink !== undefined ? merged : { ...merged, sink: \"console-json\" };\n};\n\n/**\n * Worker bindings consumed by `baerlyWorker` itself. The caller\n * wires these in `wrangler.jsonc`:\n *\n * \"r2_buckets\": [{ \"binding\": \"BUCKET\", \"bucket_name\": \"<your-bucket>\" }],\n *\n * \"vars\": { \"APP\": \"tickets\" }\n *\n * Tenant resolution is owned by the configured `Verifier`; the\n * adapter never reads a tenant-shaped env var. App-specific vars\n * (`SHARED_SECRET`, `CF_ACCESS_*`, `LOG_*`, a `TENANT` literal for\n * single-tenant `sharedSecret` callers, etc.) belong on the\n * caller's own env type — extend this one:\n *\n * ```ts\n * import type { BaerlyEnv } from \"@gusto/baerly-storage/cloudflare\";\n *\n * interface AppEnv extends BaerlyEnv {\n * readonly TENANT: string;\n * readonly SHARED_SECRET?: string;\n * }\n * ```\n *\n * ## In-band maintenance ops-plane vars\n *\n * Three OPTIONAL `vars` tune the write-tick maintenance the adapter\n * dispatches via `ctx.waitUntil` (CF `vars` are always strings):\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` — override the snapshot-rebuild\n * ceiling `C` that the resolved profile carries. The `cf-free` value\n * (512 KiB) is a conservative budget for the CF-free ~10 ms CPU\n * limit (its ~5.5 ms rebuild figure is a sizing estimate, not an\n * observed limit); `cf-paid` carries 8 MiB. This var wins over either. On\n * the free profile a value above {@link CF_FREE_MAX_SAFE_FOLD_BYTES}\n * warns LOUDLY once at init — a fold that large may exceed a free\n * isolate's CPU or memory resources and not land. Unset / `\"\"` keep\n * the profile default; anything but a plain positive decimal integer\n * (`\"8mb\"`, `\"0\"`, `\" 1024\"`, `\"1e6\"`) throws\n * `BaerlyError{code:\"InvalidConfig\"}` when maintenance dispatch is\n * built. Health, dev, and `/v1/spec` routes stay up.\n * - `BAERLY_MAINTENANCE_DISABLE` — kill switch. Closed, case-insensitive\n * vocabulary: unset / `\"\"` / `\"0\"` / `\"false\"` → not disabled;\n * `\"1\"` / `\"true\"` → disabled; anything else throws\n * `BaerlyError{code:\"InvalidConfig\"}` when maintenance dispatch is built.\n * Stops automatic maintenance only (the in-band tick and its `waitUntil`\n * continuation); `runScheduledMaintenance` is caller-owned and unaffected.\n * - `BAERLY_MAINTENANCE_PROFILE` — opt-in profile selector. Set to\n * `\"cf-paid\"` on a paid Worker to select\n * {@link MAINTENANCE_PROFILE_CF_PAID}, which raises BOTH the per-pass\n * throughput caps (GC marks/sweeps, fold entries per pass) to the\n * Node-tier values, exploiting the paid 10,000-subrequest budget, AND\n * the snapshot ceilings to `C` = 8 MiB / `E` = 32,768. Closed,\n * case-sensitive vocabulary: unset / `\"\"` / `\"cf-free\"` → `cf-free`\n * (zero-config default); `\"cf-paid\"` → `cf-paid`; anything else throws\n * `BaerlyError{code:\"InvalidConfig\"}` when maintenance dispatch is\n * built. `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` still overrides `C`\n * on top of whichever profile resolves; `E` has no var, so the\n * profile switch is the ONLY way to raise the row arm on Cloudflare.\n * Must be set consistently on BOTH the write-tick path and the cron\n * path (pass it as `runScheduledMaintenance`'s `tier` in your\n * {@link WorkerScheduledHandler}).\n */\nexport interface BaerlyEnv {\n BUCKET?: R2Bucket;\n APP: string;\n /**\n * Override the snapshot-rebuild ceiling `C` the resolved profile\n * carries (512 KiB on `cf-free`, 8 MiB on `cf-paid`). A plain positive\n * decimal integer byte count; ignored when unset or empty. Any other\n * value throws `BaerlyError{code:\"InvalidConfig\"}` when maintenance\n * dispatch is built. On the free profile a value above\n * {@link CF_FREE_MAX_SAFE_FOLD_BYTES} warns once at init.\n */\n BAERLY_MAINTENANCE_MAX_FOLD_BYTES?: string;\n /**\n * Write-tick maintenance kill switch. Closed, case-insensitive\n * vocabulary: unset / `\"\"` / `\"0\"` / `\"false\"` → not disabled;\n * `\"1\"` / `\"true\"` → disabled; anything else throws\n * `BaerlyError{code:\"InvalidConfig\"}` when maintenance dispatch is built.\n * As with a missing `SHARED_SECRET`, that throw leaves `fetch` through\n * the ExportedHandler's exception path — the request surfaces as a\n * Worker exception (visible in CF's error telemetry), not as the\n * canonical JSON error envelope the Node adapter returns. Health, dev,\n * and `/v1/spec` routes short-circuit ahead of the parse and stay up.\n */\n BAERLY_MAINTENANCE_DISABLE?: string;\n /**\n * Opt-in maintenance profile. `\"cf-paid\"` raises per-pass throughput\n * caps to Node-tier values on a paid Worker isolate AND takes the paid\n * snapshot ceilings (`C` = 8 MiB, `E` = 32,768). Unset / `\"\"` /\n * `\"cf-free\"` select `cf-free`; anything other than those and\n * `\"cf-paid\"` throws `BaerlyError{code:\"InvalidConfig\"}` when\n * maintenance dispatch is built.\n */\n BAERLY_MAINTENANCE_PROFILE?: string;\n}\n\n/**\n * Non-throwing parse of a `BAERLY_MAINTENANCE_PROFILE` value: the tier it\n * names (`undefined` and `\"\"` mean `cf-free`), or `undefined` when the\n * value is not a recognized selector.\n */\nconst parseCfProfileTier = (raw: string | undefined): \"cf-free\" | \"cf-paid\" | undefined => {\n if (raw === undefined || raw === \"\" || raw === \"cf-free\") {\n return \"cf-free\";\n }\n return raw === \"cf-paid\" ? \"cf-paid\" : undefined;\n};\n\n/**\n * Resolve the maintenance profile from the opt-in operator env var.\n * Unset, `\"\"`, and `\"cf-free\"` select the CPU-limited CF-free profile, so\n * zero-config behavior is unchanged. `cf-paid` raises the per-pass caps\n * to exploit the paid 10,000-subrequest budget AND the snapshot ceilings\n * to `C` = 8 MiB / `E` = 32,768, measured against the paid isolate's own\n * memory wall rather than free's CPU wall. Used by the write-tick\n * dispatch and the request ledger; a cron handler passes the same value\n * as `runScheduledMaintenance`'s `tier`. Unpublished: in-repo callers\n * import it from `@baerly/adapter-cloudflare/worker`.\n *\n * @throws {BaerlyError} `InvalidConfig` for any other value (`\"cf_paid\"`,\n * `\"CF-PAID\"`, `\"cf-paid \"`): a misspelled opt-in would otherwise leave a\n * paid Worker on free caps and ceilings without any signal.\n */\nexport const resolveCfMaintenanceProfile = (readEnv: (key: string) => string | undefined) => {\n const raw = readEnv(\"BAERLY_MAINTENANCE_PROFILE\");\n const tier = parseCfProfileTier(raw);\n if (tier === \"cf-free\") {\n return MAINTENANCE_PROFILE_CF_FREE;\n }\n if (tier === \"cf-paid\") {\n return MAINTENANCE_PROFILE_CF_PAID;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `BAERLY_MAINTENANCE_PROFILE must be one of \"\", \"cf-free\", \"cf-paid\", got ${JSON.stringify(raw)}`,\n );\n};\n\n/** Read a string var off the `env` binding (CF `vars` are always strings). */\nconst envReader =\n (env: BaerlyEnv) =>\n (key: string): string | undefined => {\n const value = (env as unknown as Record<string, unknown>)[key];\n return typeof value === \"string\" ? value : undefined;\n };\n\n/**\n * A fresh request ledger for one Worker invocation (a `fetch` or a\n * `scheduled` call), with the limits of the `BAERLY_MAINTENANCE_PROFILE`\n * tier. The profile, not the account's billing plan, selects them:\n * `cf-free` (the default) allows {@link CF_FREE_INTERNAL_REQUEST_LIMIT}\n * storage calls, of which at most {@link CF_FREE_EXTERNAL_REQUEST_LIMIT}\n * leave through `fetch`; `cf-paid` allows\n * {@link CF_PAID_REQUEST_LIMIT} of either. A storage call past the limit\n * is refused with `CapacityExceeded` before it is sent, where the\n * platform would otherwise throw on it.\n *\n * Never throws. Only the exact value `\"cf-paid\"` raises the limits; any\n * other value, valid or not, gets the free limits, which are safe on\n * every plan. Validation stays with {@link resolveCfMaintenanceProfile}\n * at the maintenance dispatch build, so an invalid value fails API\n * requests there and does not reach a cron callback that never reads it.\n */\nexport const cfRequestLedger = (readEnv: (key: string) => string | undefined): RequestLedger =>\n new RequestLedger(\n parseCfProfileTier(readEnv(\"BAERLY_MAINTENANCE_PROFILE\")) === \"cf-paid\"\n ? { internal: CF_PAID_REQUEST_LIMIT, external: CF_PAID_REQUEST_LIMIT }\n : { internal: CF_FREE_INTERNAL_REQUEST_LIMIT, external: CF_FREE_EXTERNAL_REQUEST_LIMIT },\n );\n\n/**\n * The Worker's read envelope: the request pool its storage charges, so a\n * read the ledger certainly cannot fit is refused from `current.json`\n * alone (the R2 binding charges `internal`; anything else, reached through\n * `fetch`, charges `external`). The data bounds (snapshot, tail, output)\n * are left unbounded on every profile until cold CPU measurements size\n * them; the ledger bounds every read's storage calls today.\n */\nexport const cfReadEnvelope = (storage: Storage): ReadEnvelope => ({\n requestPool: isR2BindingStorage(storage) ? \"internal\" : \"external\",\n});\n\n/**\n * Write-tick options on the free profile for storage reached through\n * `fetch`: the GC sweep capped, and the server's unpublished host trigger\n * `foldAtTailEntries` (`InternalBoundedMaintenanceOptions`), spread into\n * the public options bag. `worker-maintenance.test.ts` pins the result.\n */\nconst CF_FREE_FETCH_TICK = {\n profile: { ...MAINTENANCE_PROFILE_CF_FREE, gcMaxSweeps: CF_FREE_FETCH_GC_MAX_SWEEPS },\n foldAtTailEntries: CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES,\n} as const;\n\n/**\n * Assemble the per-request {@link MaintenanceDispatch} for a Cloudflare\n * Worker.\n *\n * baerly maintains IN-BAND: the writer reads\n * `getCurrentContext()?.maintenance` at its post-commit dispatch point and\n * runs one bounded compact + GC slice on the (rare) write that crosses a\n * maintenance trigger. Reads stay pure — they never tick. There is no\n * cron, no `triggers`, no operator-installed scheduler.\n *\n * On Cloudflare the fold runs in a `ctx.waitUntil` continuation — FIRE\n * AND FORGET off the response ack, so the commit never blocks on it. The\n * isolate stays alive long enough to drain the continuation; the\n * per-pass caps default to the TESTED CF-free `WRITE_TICK_*` values\n * (`phasesPerTick: \"single\"` — a CPU-limited free isolate does ONE of\n * fold/GC per request, never both). Every storage call is charged to the\n * invocation's request ledger (`cfRequestLedger`): on Free, 900 calls\n * through the R2 binding and 45 through `fetch`, below the platform's\n * 1,000 internal-service and 50 external subrequests. An operator on CF **paid** opts\n * into the whole paid tier — per-pass caps AND snapshot ceilings — with\n * `BAERLY_MAINTENANCE_PROFILE=cf-paid`, which is what exploits the\n * 10,000-subrequest paid budget (the default since 2026-02-11, up from\n * 1,000, and configurable to 10M).\n *\n * The three ops-plane vars are read off the `env` BINDING (a string map),\n * NOT `process.env` — Workers have no process env:\n *\n * - `BAERLY_MAINTENANCE_MAX_FOLD_BYTES` → `maxFoldBytes` (`C`), which\n * overrides the resolved profile's ceiling. A plain positive decimal\n * integer; ignored when unset / `\"\"`; any other value throws\n * `BaerlyError{code:\"InvalidConfig\"}`.\n * - `BAERLY_MAINTENANCE_DISABLE` → `disabled` (kill switch). Closed,\n * case-insensitive vocabulary: unset/`\"\"`/`\"0\"`/`\"false\"` → `false`;\n * `\"1\"`/`\"true\"` → `true`; anything else throws\n * `BaerlyError{code:\"InvalidConfig\"}`. Covers automatic maintenance\n * only; it does not stop `runScheduledMaintenance`.\n * - `BAERLY_MAINTENANCE_PROFILE` → `options.profile`, via\n * {@link resolveCfMaintenanceProfile} (closed vocabulary; anything\n * outside it throws `BaerlyError{code:\"InvalidConfig\"}`).\n *\n * `readEnv` defaults to reading off the bound `env`; the parameter\n * exists for direct unit coverage.\n *\n * `storage` is the Worker's base storage. On the free profile, storage\n * other than the R2 binding (`S3HttpStorage`, or any wrapper) is charged\n * to the 45-call `external` pool, so the write tick folds as soon as the\n * live tail reaches {@link CF_FREE_FETCH_FOLD_AT_TAIL_ENTRIES} entries,\n * and a GC slice sweeps at most {@link CF_FREE_FETCH_GC_MAX_SWEEPS}\n * snapshots: a write replays the tail, and on a longer tail or a larger\n * sweep the write plus the tick it dispatches no longer fit in one\n * request. Workers Free + S3 is not a supported host, but the Worker\n * cannot tell Free from Paid: `cf-free` caps fetch storage at 45 calls so\n * a request past Free's 50 gets a typed `CapacityExceeded` instead of the\n * platform throwing at call 51, and this tick keeps ordinary requests\n * inside that cap (a Paid Worker on S3 that has not set `cf-paid` runs\n * here). Detected from the storage itself, so it needs no configuration.\n * Absent ⇒ treated as the R2 binding.\n */\nexport const cfMaintenanceDispatch = (\n ctx: ExecutionContext,\n readEnv: (key: string) => string | undefined,\n storage?: Storage,\n): MaintenanceDispatch => {\n const { maxFoldBytes, disabled } = parseMaintenanceEnv(readEnv);\n const profile = resolveCfMaintenanceProfile(readEnv);\n const fetchBudgeted =\n profile === MAINTENANCE_PROFILE_CF_FREE &&\n storage !== undefined &&\n !isR2BindingStorage(storage);\n\n return {\n // CF dispatches the fold off the ack via `ctx.waitUntil` — the\n // isolate stays alive to drain it without blocking the response.\n dispatch: (task: () => Promise<void>): void => ctx.waitUntil(task()),\n ...(disabled && { disabled: true }),\n ...(maxFoldBytes !== undefined && { maxFoldBytes }),\n // Structured `fold_deferred` warnings. The tick runs in `waitUntil`\n // after the canonical line flushed, so this record (not the deferral\n // counter) is what reaches `wrangler tail` / Workers Logs.\n warn: logMaintenanceWarning,\n options: {\n // A CPU-limited free isolate does ONE phase per request.\n phasesPerTick: \"single\",\n // Write-tick profile. The cron path (user-supplied `scheduled` callback)\n // passes the same `BAERLY_MAINTENANCE_PROFILE` value as\n // `runScheduledMaintenance`'s `tier`, so the two triggers stay coherent.\n ...(fetchBudgeted ? CF_FREE_FETCH_TICK : { profile }),\n },\n };\n};\n\n/**\n * Cron Trigger handler. Called once per tick when the user has\n * declared `triggers.crons` in `wrangler.jsonc` AND passed this\n * option. The body owns its own subrequest budget — wrap any\n * outlasting work in `ctx.waitUntil(...)`; it runs under its own request\n * ledger. Maintain one collection per invocation and shard cron\n * triggers or persist a collection cursor instead of looping tenants /\n * collections. With the R2 binding, Free and Paid may run one whole\n * `runScheduledMaintenance(target, { tier })` pass per invocation, `tier`\n * being the `BAERLY_MAINTENANCE_PROFILE` value. S3 storage needs Paid\n * with `tier: \"cf-paid\"`.\n */\nexport type WorkerScheduledHandler = (\n event: ScheduledController,\n env: BaerlyEnv,\n ctx: ExecutionContext,\n) => Promise<void> | void;\n\nexport interface BaerlyWorkerOptions {\n /**\n * Your `baerly.config.ts`. **Required.** Carries `auth`,\n * `tenant`, and the declared `collections` (their schemas/indexes\n * flow through to per-request `Db.create` automatically).\n *\n * The adapter resolves the per-request `Verifier` from\n * `config.auth` when no `verifier:` override is supplied — see\n * resolution order on {@link verifier} below.\n *\n * Only `collections` is read for runtime kernel wiring — fields\n * like `target`, `domain`, `cloudflareAccess` are deploy-time\n * concerns that the adapter ignores.\n */\n readonly config: BaerlyAppConfig;\n /**\n * Request-time `Storage`. **Optional.** When unset, the Worker uses\n * the same-account R2 binding `env.BUCKET` (the dominant path). Inject\n * this to talk to S3 / cross-account R2 over the S3 REST API\n * from a Worker — e.g. `new S3HttpStorage(...)` +\n * `sigV4Signer(...)` from `@gusto/baerly-storage/s3`. Resolved once\n * per isolate inside the factory (where `env` is in scope), same as\n * the R2 binding. S3 storage needs Workers Paid with\n * `BAERLY_MAINTENANCE_PROFILE=cf-paid`; Workers Free + S3 is not\n * supported. Under the free profile, storage other than the R2 binding\n * is held to 45 calls per request (a typed `CapacityExceeded` past it,\n * not the platform's throw at call 51), so the write tick folds after a\n * few writes instead of on the ratio trigger.\n */\n readonly storage?: Storage;\n /**\n * Cron Trigger handler. When unset, `scheduled()` is a no-op even\n * if `triggers.crons` is declared. See {@link WorkerScheduledHandler}.\n */\n readonly scheduled?: WorkerScheduledHandler;\n /**\n * Per-request `Verifier`. **Optional.** When set, overrides\n * `config.auth` (the \"dev default in config, prod override via env\"\n * recipe). When unset, the adapter synthesizes one from\n * `config.auth`:\n *\n * - `\"shared-secret\"` → `sharedSecret({ secret: env.SHARED_SECRET,\n * tenantPrefix: config.tenant })`. Throws `InvalidConfig` on\n * first fetch when `SHARED_SECRET` is missing/empty.\n * - `\"none\"` → pins every request to `config.tenant` with no\n * header check.\n *\n * `GET /v1/healthz` always bypasses the verifier.\n *\n * Multi-tenant deployments compose their own verifier on top of a\n * real IdP — JWT, SigV4, Cloudflare Access, etc.\n */\n readonly verifier?: Verifier;\n /**\n * Observability config (LogTape sink + level). When supplied, the\n * Worker calls {@link configureObservability} lazily on first\n * `fetch` / `scheduled` invocation (CF Worker modules can't\n * `await` at the top level). `configureObservability` is\n * idempotent over baerly's own config — it re-runs with\n * `{ reset: true }`, last call wins — and skips over a host config\n * it detects, so re-invocation is harmless.\n *\n * - `level` falls through to `env.LOG_LEVEL` (when typed option\n * is undefined).\n * - `sink` defaults to `\"console-json\"` (Cloudflare's stdout is\n * ingested by Workers Logs as JSON-shaped records).\n *\n * When the field is unset (or `{}`), baerly auto-configures on first\n * `fetch`. Pass `false` to skip configuration entirely — the escape\n * hatch for Workers that embed baerly and own the isolate-wide\n * LogTape configuration themselves. (baerly also never clobbers a\n * host config it detects; `false` additionally suppresses the\n * configure attempt and its meta-logger notice.)\n */\n readonly observability?: ObservabilityConfig | false;\n /**\n * Opt-in dev affordance. When set, `GET /` returns a small\n * human-readable HTML page that links to {@link DevLandingOptions.uiUrl},\n * and `GET /favicon.ico` returns 204 No Content. Leave unset on\n * production Workers — `/` falls through to the existing 404\n * envelope when this option is absent.\n */\n readonly dev?: DevLandingOptions;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Workers module-default export.\n *\n * Order on `fetch`: **healthz → verifier → router**. Health probes\n * don't pay for a Db construction; an auth challenge stops a bad\n * request before any Storage I/O; the router catches everything else.\n *\n * Observability: every HTTP request that passes healthz — the\n * verifier included — runs inside a single `runWithContext` scope\n * created up front in this adapter. Every point read reaches storage;\n * response bodies are never cached. The canonical line includes the\n * storage work of each read; the adapter owns the flush.\n *\n * Cron Triggers are opt-in. Pass `options.scheduled` to wire one;\n * `wrangler.jsonc:triggers.crons` controls the firing cadence.\n * When `options.scheduled` is unset the cron tick is a no-op.\n *\n * The factory receives `env` on the first `fetch` or `scheduled`\n * invocation, resolves `BaerlyWorkerOptions` once, and caches the\n * result for the lifetime of the isolate. Cloudflare Workers cannot\n * `await` at the module top level — the factory pattern is the\n * supported way to read env bindings at startup.\n *\n * @example\n * ```ts\n * import { baerlyWorker } from \"@gusto/baerly-storage/cloudflare\";\n * import config from \"../../baerly.config.ts\";\n *\n * // Dev default: `auth: \"none\"` in baerly.config.ts pins every\n * // request to `config.tenant`. Switch to `auth: \"shared-secret\"`\n * // for staging/prod and `wrangler secret put SHARED_SECRET`.\n * export default baerlyWorker(() => ({ config }));\n * ```\n */\nexport function baerlyWorker<E extends BaerlyEnv = BaerlyEnv>(\n factory: (env: E) => BaerlyWorkerOptions,\n): ExportedHandler<E> {\n // Cached resolution: populated on first fetch/scheduled, reused on\n // every subsequent invocation. Cloudflare Workers can't `await` at\n // the module top level, so we lazy-init on first call to whichever\n // handler fires first.\n interface ResolvedState {\n readonly options: BaerlyWorkerOptions;\n readonly verifier: Verifier;\n // Base Storage resolved once per isolate (injected `options.storage`\n // or the `env.BUCKET` R2 binding), same lifetime as `verifier`. The\n // per-request `observableStorage(...)` wrap still happens on every\n // request — it binds to the request's observability bag — but the\n // underlying handle is no longer reconstructed each time.\n readonly storage: Storage;\n }\n let resolved: ResolvedState | undefined;\n // Cached so every subsequent fetch re-throws the same error rather\n // than re-running `resolveVerifier` on every request after a\n // misconfig. Mirrors the \"first fetch errors, every fetch errors\"\n // contract documented on `auth: \"shared-secret\"` + missing env.\n let resolutionError: unknown;\n let observabilityConfigured = false;\n // Completed at most once per handler/isolate: an operator who raised the\n // snapshot ceiling above what a free CF isolate can rebuild in one shot\n // gets a loud warning. A throwing parse leaves this false so the bad\n // binding keeps failing until corrected; a successful check suppresses\n // per-request warning work thereafter.\n let maintenanceCeilingChecked = false;\n\n const ensureResolved = async (env: E): Promise<ResolvedState> => {\n if (resolutionError !== undefined) {\n throw resolutionError;\n }\n if (resolved === undefined) {\n try {\n const options = factory(env);\n const verifier = resolveVerifier({\n factoryVerifier: options.verifier,\n config: options.config,\n readEnv: (k) => {\n const value = (env as unknown as Record<string, unknown>)[k];\n return typeof value === \"string\" ? value : undefined;\n },\n });\n resolved = { options, verifier, storage: resolveWorkerStorage(options, env) };\n } catch (error) {\n resolutionError = error;\n throw error;\n }\n }\n // Lazy-init flag for `configureObservability`. CF Worker modules\n // cannot `await` at the module top level, so the first fetch /\n // scheduled invocation runs the configure. LogTape's `configure`\n // is idempotent (we always pass `reset: true`); a thundering-herd\n // race on the cold-start tick just re-runs the same config.\n if (!observabilityConfigured && resolved.options.observability !== false) {\n await configureObservability(resolveCfSink(resolved.options.observability));\n observabilityConfigured = true;\n // Emit the auth=none startup banner exactly once per isolate.\n // Suppress when an explicit `verifier:` override is in play —\n // the override wins, the log would be misleading. Suppress\n // when `auth === \"shared-secret\"` — the operator already knows.\n if (resolved.options.verifier === undefined && resolved.options.config.auth === \"none\") {\n getLogger(CATEGORY.http).info(\n `[baerly] auth=none — all requests resolve to tenant=${JSON.stringify(resolved.options.config.tenant)}`,\n );\n }\n }\n // Ops-plane guardrail, init-scoped: if the operator raised the\n // snapshot-rebuild ceiling above the conservative budget for a CF FREE\n // isolate's ~10 ms CPU limit, warn LOUDLY exactly once. A fold over this\n // size may exceed the invocation's CPU or memory resources; if it is\n // terminated mid-rebuild the CAS does not land and that fold does not\n // advance `log_seq_start`, so the tail can grow. `console.warn` (not LogTape) so the\n // signal survives even when observability is unconfigured.\n //\n // Scoped to the FREE profile. `CF_FREE_MAX_SAFE_FOLD_BYTES` is free's\n // CPU wall, and the warning's own first remedy is \"run on CF PAID\" —\n // an operator who set `BAERLY_MAINTENANCE_PROFILE=cf-paid` has taken\n // it, and the paid profile's own ceiling (8 MiB) is already 8x this\n // bound. Warning them would contradict the advice. There is no paid\n // equivalent of this guardrail because paid's ceiling is memory-bound,\n // not CPU-bound, and no safe-override threshold has been measured\n // above it.\n //\n // An invalid value is skipped here, not thrown: this runs ahead of the\n // healthz / spec / dev short-circuits and `scheduled()`, which must stay\n // up. The per-request dispatch build re-parses both vars and throws\n // `InvalidConfig` on API requests. The check stays pending so a\n // corrected binding still gets its warning.\n if (!maintenanceCeilingChecked) {\n const readMaintenanceEnv = (k: string): string | undefined => {\n const v = (env as unknown as Record<string, unknown>)[k];\n return typeof v === \"string\" ? v : undefined;\n };\n const rawFoldBytes = readMaintenanceEnv(\"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\");\n let overFreeCeiling: boolean;\n try {\n const { maxFoldBytes } = parseMaintenanceEnv((k) =>\n k === \"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\" ? rawFoldBytes : undefined,\n );\n // The profile is resolved only for an over-raised ceiling.\n overFreeCeiling =\n maxFoldBytes !== undefined &&\n maxFoldBytes > CF_FREE_MAX_SAFE_FOLD_BYTES &&\n resolveCfMaintenanceProfile(readMaintenanceEnv) === MAINTENANCE_PROFILE_CF_FREE;\n } catch {\n return resolved;\n }\n if (overFreeCeiling) {\n console.warn(\n `[baerly] BAERLY_MAINTENANCE_MAX_FOLD_BYTES=${rawFoldBytes} exceeds the ` +\n `CF free-tier safe ceiling (${CF_FREE_MAX_SAFE_FOLD_BYTES} bytes). On a free ` +\n `Worker a fold this large may exceed the invocation's CPU or memory resources (the ~10 ms ` +\n `CPU limit); if it is terminated mid-rebuild the current.json CAS does not land, so ` +\n `that fold does not advance and the tail can grow. Remedies: run on CF PAID (raised CPU limits) ` +\n `or self-host on NODE. Leave this var unset on free CF.`,\n );\n }\n maintenanceCeilingChecked = true;\n }\n return resolved;\n };\n\n const exported: ExportedHandler<E> = {\n async fetch(req, env, ctx): Promise<Response> {\n const url = new URL(req.url);\n\n // /v1/spec — anonymous static contract IR. Keep this before\n // `ensureResolved`: even a verifier/config-resolution failure\n // should not hide the public machine contract. Tenant collections\n // are appended only when resolution succeeds AND the verifier\n // accepts.\n if (req.method === \"GET\" && url.pathname === \"/v1/spec\") {\n return handleSpecRequest(req, async () => {\n const { options, verifier } = await ensureResolved(env);\n return { verifier, config: options.config };\n });\n }\n\n let resolvedState: ResolvedState;\n try {\n resolvedState = await ensureResolved(env);\n } catch (error) {\n // Config resolution failed. The deployment cannot serve, which is\n // a server fault: answer 500 with the scrubbed `Internal` envelope\n // and an `error` canonical line. Observability is configured only\n // after resolution succeeds, so LogTape is silent here; write the\n // full error (with its locked message) to the console so the\n // operator still sees it in `wrangler tail` / Workers Logs.\n console.error(\n `[baerly] config resolution failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,\n );\n const fault = new BaerlyError(\"Internal\", \"internal error\", { cause: error });\n const { status, envelope } = mapError(fault);\n const failedCtx = createObservabilityContext({\n request_id: requestIdFrom(req.headers),\n });\n flushCanonicalLine(failedCtx, failedCtx.recorder, {\n unit: \"http\",\n status,\n outcome: deriveOutcome(req.method, status, fault),\n error: fault,\n extra: { method: req.method, path: url.pathname },\n });\n return new Response(JSON.stringify(envelope), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n const { options, verifier, storage: baseStorage } = resolvedState;\n\n // Opt-in dev landing page. Off in production (options.dev\n // unset); when set, GET / serves HTML and GET /favicon.ico\n // returns 204 so browsers don't pin a second JSON 404 next\n // to the landing page.\n if (options.dev !== undefined && req.method === \"GET\") {\n if (url.pathname === \"/\") {\n return new Response(renderDevLanding(options.dev), {\n status: 200,\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n }\n if (url.pathname === \"/favicon.ico\") {\n return new Response(null, { status: 204 });\n }\n }\n\n // Healthz is always anonymous — Cloudflare's load balancer\n // probes it. Keep it ahead of the verifier check; serving it\n // here avoids a `Db.create` (and the canonical-line emission)\n // on every probe. The router no longer mounts healthz — only\n // the adapter does.\n if (req.method === \"GET\" && url.pathname === \"/v1/healthz\") {\n return new Response(JSON.stringify({ ok: true }), {\n status: 200,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Construct the per-request observability context up front. The\n // verifier, `Db.create`, and the router run inside one\n // `runWithContext` scope below, so work done by any\n // of them (e.g. a verifier's JWKS fetch) sees `getCurrentContext()`.\n // A verifier rejection still emits its canonical line in that scope.\n //\n // The router uses this ambient context and never flushes a\n // competing canonical line. The adapter owns the flush.\n const requestId = requestIdFrom(req.headers);\n // In-band write-tick maintenance: the writer reads\n // `getCurrentContext()?.maintenance` at its post-commit dispatch\n // point. On CF the fold is dispatched via `ctx.waitUntil` (off the\n // ack) with the CF-free caps + `phasesPerTick: \"single\"`; the\n // ops-plane vars are read off the `env` binding (strings). Built\n // per request so a hot-swapped `env` is observed at call time.\n const readEnv = envReader(env);\n const obsCtx = createObservabilityContext({\n request_id: requestId,\n maintenance: cfMaintenanceDispatch(ctx, readEnv, baseStorage),\n // One budget for the whole invocation: the route and the\n // `ctx.waitUntil` tick charge the same ledger.\n ledger: cfRequestLedger(readEnv),\n readEnvelope: cfReadEnvelope(baseStorage),\n });\n\n return runWithContext(obsCtx, async (): Promise<Response> => {\n // Tenant resolution: the Verifier owns it unconditionally.\n // An error thrown before the router runs: an enveloped, mapped\n // error with its own canonical line.\n let result: Awaited<ReturnType<Verifier>>;\n try {\n result = await verifier(req);\n } catch (error) {\n // A throwing verifier is never a 401 (that would tell OAuth\n // clients to discard credentials during an IdP outage).\n const { status, envelope } = mapError(error);\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status,\n outcome: deriveOutcome(req.method, status, error),\n error,\n extra: { method: req.method, path: url.pathname },\n });\n return new Response(JSON.stringify(envelope), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n if (result === null) {\n return flushUnauthorizedAndRespond(obsCtx, req);\n }\n const tenantPrefix = result.tenantPrefix;\n\n // Storage is wrapped with `observableStorage(...)` so the\n // per-call class A/B counts and per-op duration histograms\n // land in the active per-request bag. Writer / compactor / GC\n // emissions reach the same bag via `getCurrentContext()?.recorder`\n // — the canonical-line flusher reads it at end-of-request. The\n // base handle is resolved once per isolate (see `ResolvedState`);\n // only the observability wrap is per-request.\n const storage = observableStorage(baseStorage);\n // One `try` covers `Db.create` (refuses an invalid tenant, for\n // example a non-NFC claim), `createRouter` and `app.fetch`.\n // Any throw maps to the JSON error envelope\n // with the mapped status, and one canonical line records it, as\n // the Node adapter does.\n let outboundStatus = 500;\n let caughtError: unknown;\n let response: Response;\n try {\n const db = Db.create({\n storage,\n app: env.APP,\n tenant: tenantPrefix,\n config: options.config,\n });\n const app = createRouter({\n db,\n sinceTimeoutMs: options.sinceTimeoutMs,\n sincePollIntervalMs: options.sincePollIntervalMs,\n });\n response = await app.fetch(req, env, ctx);\n outboundStatus = response.status;\n } catch (error) {\n caughtError = error;\n const mapped = mapError(error);\n outboundStatus = mapped.status;\n response = new Response(JSON.stringify(mapped.envelope), {\n status: mapped.status,\n headers: { \"content-type\": \"application/json\" },\n });\n } finally {\n flushCanonicalLine(obsCtx, obsCtx.recorder, {\n unit: \"http\",\n status: outboundStatus,\n outcome: deriveOutcome(req.method, outboundStatus, caughtError),\n ...(caughtError !== undefined && { error: caughtError }),\n extra: {\n method: req.method,\n path: url.pathname,\n },\n });\n }\n return response;\n });\n },\n\n async scheduled(event, env, ctx): Promise<void> {\n const { options } = await ensureResolved(env);\n const handler = options.scheduled;\n if (handler !== undefined) {\n // The handler calls `runScheduledMaintenance` (see\n // WorkerScheduledHandler) with `tier` set from\n // BAERLY_MAINTENANCE_PROFILE, one collection per invocation.\n // A cron invocation has its own subrequest limit, so it gets its\n // own context carrying a fresh ledger. It emits no canonical line;\n // metrics recorded inside it are dropped.\n const cronCtx = createObservabilityContext({ ledger: cfRequestLedger(envReader(env)) });\n await runWithContext(cronCtx, () => handler(event, env, ctx));\n }\n },\n };\n // Every response leaves through `withNosniff`, including the healthz /\n // spec / dev-landing short-circuits ahead of the router.\n const route = exported.fetch!;\n exported.fetch = async (req, env, ctx) => withNosniff(await route(req, env, ctx));\n return exported;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,MAAM,eAAe,SACnB,KAAK,WAAW,IAAG,KAAK,KAAK,SAAS,IAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACnE,MAAM,aAAa,QAAwB,IAAI,IAAI;;AAGnD,MAAM,uBAAuB;;;;;;;;AAQ7B,MAAM,2BACJ;AAEF,IAAM,uBAAN,MAA8C;CACnC;CAET,YAAY,QAAkB;EAC5B,IAAI,WAAW,QAAQ,WAAW,KAAA,GAChC,MAAM,IAAI,YACR,iBACA,8GACF;EAEF,KAAK,UAAU;CACjB;CAEA,MAAM,IAAI,KAAa,MAA4D;EACjF,sBAAsB,GAAG;EACzB,MAAM,QAAQ,eAAe;EAC7B,MAAM,MAAM,MAAM,KAAK,mBAAmB,KAAK,QAAQ,IAAI,GAAG,GAAG,OAAO,OAAO,EAC7E,QAAQ,MAAM,OAChB,CAAC;EACD,IAAI,QAAQ,MACV,OAAO;EAGT,OAAO;GAAE,MAAA,IADQ,WAAW,MAAM,IAAI,YAAY,CACt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A,OAAO;GACT,CAAC;EACH;EAEA,MAAM,UAAU,OAAO,KAAK,KAAoB;GAC9C,MAAM,EAAE,YAAY,MAAM,eAAe,GAAG;GAC5C,MAAM,UAAU,QAAQ;GACxB,IAAI,YAAY,KAAA,GAAW;IAOzB,MAAM,UAAU,2BAA2B,EAAE,QAAQ,gBAAgB,UAAU,GAAG,CAAC,EAAE,CAAC;IACtF,MAAM,eAAe,eAAe,QAAQ,OAAO,KAAK,GAAG,CAAC;GAC9D;EACF;CACF;CAGA,MAAM,QAAQ,SAAS;CACvB,SAAS,QAAQ,OAAO,KAAK,KAAK,QAAQ,YAAY,MAAM,MAAM,KAAK,KAAK,GAAG,CAAC;CAChF,OAAO;AACT"}
@@ -0,0 +1,22 @@
1
+ // packages/protocol/src/code-resolution.ts
2
+ /** Canonical per-code corrective action; `errorEnvelope` falls back to this and it crosses the wire as `resolution`. Actionable codes only. One canonical action per actionable code; a throw site may pass a more specific resolution (CLI `restore`), never a different retry meaning. */
3
+ const CODE_RESOLUTIONS = {
4
+ WriteConflict: "Another write changed this data first and this commit did not land. Re-read, then retry.",
5
+ AlreadyExists: "Do not retry. A row with this _id is already committed: insert with a different _id or omit _id to auto-generate one, or use update or replace to change the existing row. If this insert omitted _id or followed an AmbiguousCommit, the row may be this insert's own earlier attempt: re-read it, and do not re-mint by inserting again without an _id.",
6
+ AmbiguousCommit: "Do not retry automatically. Re-read the row named by the error's _id; absence does not prove the write failed. A deliberate retry may repeat logical work; retry an insert with the same _id, and treat AlreadyExists on that retry as a committed row to re-read.",
7
+ CapacityExceeded: "Do not retry unchanged. Delete or shrink rows to make room; if every write is refused, the collection has outgrown this host: export it with baerly admin dump, or move it to a larger host.",
8
+ MaintenancePending: "Retry after the delay in retryAfter (Retry-After header, seconds): maintenance is catching up on this collection and this write was not committed.",
9
+ CursorExpired: "Do not retry this cursor. The changes after it are no longer retained: re-read the rows you need, then resume /v1/since with cursor: \"\".",
10
+ PayloadTooLarge: "Reduce the request body below the server's body-size cap (1 MiB default).",
11
+ UnsupportedMediaType: "Send the request body as JSON with a Content-Type: application/json header.",
12
+ Unauthorized: "Send a valid Authorization header for the server's configured auth method.",
13
+ AccessDenied: "These credentials are denied for this tenant prefix or bucket policy.",
14
+ NotFound: "No row matches this id; create it first or treat this as a miss."
15
+ };
16
+ /** Resolution for a malformed `?where=` / `?order=` query value. */
17
+ const WHERE_ORDER_JSON_RESOLUTION = "Pass a URL-encoded JSON object as the ?where= / ?order= value.";
18
+ /** Resolution for an empty / malformed / unwrapped write body. */
19
+ const WRITE_BODY_SHAPE_RESOLUTION = "Send a JSON body shaped { \"doc\": { ... } } for POST/PUT, or { \"patch\": { ... } } for PATCH.";
20
+ export { WHERE_ORDER_JSON_RESOLUTION as n, WRITE_BODY_SHAPE_RESOLUTION as r, CODE_RESOLUTIONS as t };
21
+
22
+ //# sourceMappingURL=code-resolution-CL_7L0wS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"code-resolution-CL_7L0wS.js","names":[],"sources":["../packages/protocol/src/code-resolution.ts"],"sourcesContent":["import type { BaerlyErrorCode } from \"./errors.ts\";\n\n/** Canonical per-code corrective action; `errorEnvelope` falls back to this and it crosses the wire as `resolution`. Actionable codes only. One canonical action per actionable code; a throw site may pass a more specific resolution (CLI `restore`), never a different retry meaning. */\nexport const CODE_RESOLUTIONS: Partial<Record<BaerlyErrorCode, string>> = {\n WriteConflict:\n \"Another write changed this data first and this commit did not land. Re-read, then retry.\",\n AlreadyExists:\n \"Do not retry. A row with this _id is already committed: insert with a different _id or omit _id to auto-generate one, or use update or replace to change the existing row. If this insert omitted _id or followed an AmbiguousCommit, the row may be this insert's own earlier attempt: re-read it, and do not re-mint by inserting again without an _id.\",\n AmbiguousCommit:\n \"Do not retry automatically. Re-read the row named by the error's _id; absence does not prove the write failed. A deliberate retry may repeat logical work; retry an insert with the same _id, and treat AlreadyExists on that retry as a committed row to re-read.\",\n CapacityExceeded:\n \"Do not retry unchanged. Delete or shrink rows to make room; if every write is refused, the collection has outgrown this host: export it with baerly admin dump, or move it to a larger host.\",\n MaintenancePending:\n \"Retry after the delay in retryAfter (Retry-After header, seconds): maintenance is catching up on this collection and this write was not committed.\",\n CursorExpired:\n 'Do not retry this cursor. The changes after it are no longer retained: re-read the rows you need, then resume /v1/since with cursor: \"\".',\n PayloadTooLarge: \"Reduce the request body below the server's body-size cap (1 MiB default).\",\n UnsupportedMediaType:\n \"Send the request body as JSON with a Content-Type: application/json header.\",\n Unauthorized: \"Send a valid Authorization header for the server's configured auth method.\",\n AccessDenied: \"These credentials are denied for this tenant prefix or bucket policy.\",\n NotFound: \"No row matches this id; create it first or treat this as a miss.\",\n};\n\n/** Resolution for a malformed `?where=` / `?order=` query value. */\nexport const WHERE_ORDER_JSON_RESOLUTION: string =\n \"Pass a URL-encoded JSON object as the ?where= / ?order= value.\";\n\n/** Resolution for an empty / malformed / unwrapped write body. */\nexport const WRITE_BODY_SHAPE_RESOLUTION: string =\n 'Send a JSON body shaped { \"doc\": { ... } } for POST/PUT, or { \"patch\": { ... } } for PATCH.';\n"],"mappings":";;AAGA,MAAa,mBAA6D;CACxE,eACE;CACF,eACE;CACF,iBACE;CACF,kBACE;CACF,oBACE;CACF,eACE;CACF,iBAAiB;CACjB,sBACE;CACF,cAAc;CACd,cAAc;CACd,UAAU;AACZ;;AAGA,MAAa,8BACX;;AAGF,MAAa,8BACX"}