@gusto/baerly-storage 0.1.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +108 -44
- package/dist/API.md +192 -121
- package/dist/CHANGELOG.md +144 -0
- package/dist/THIRD-PARTY-LICENSES.txt +312 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +288 -288
- package/dist/auth.js.map +1 -1
- package/dist/baerly.js +10 -10
- package/dist/baerly.js.map +1 -1
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
- package/dist/client-react.d.ts +76 -85
- package/dist/client-react.js +95 -53
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
- package/dist/cloudflare-Cn2ibODt.js.map +1 -0
- package/dist/cloudflare.d.ts +4 -4
- package/dist/cloudflare.js +10 -11
- package/dist/cloudflare.js.map +1 -1
- package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
- package/dist/config-CGyBopy3.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
- package/dist/cost-BZ_MDBmn.js.map +1 -0
- package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
- package/dist/current-json-DsN7FNY1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
- package/dist/deploy-BKKyGlSJ.js.map +1 -0
- package/dist/dev-vite.d.ts +5 -5
- package/dist/dev-vite.js +5 -5
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
- package/dist/doctor-BVU4GNXN.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
- package/dist/dump-DPEAKub6.js.map +1 -0
- package/dist/errors-DOdL95kK.js.map +1 -1
- package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
- package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
- package/dist/fsck-RXgLOaJG.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
- package/dist/http-Bd4byR4n.js.map +1 -0
- package/dist/http.d.ts +15 -15
- package/dist/http.js +1 -1
- package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
- package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
- package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
- package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
- package/dist/index.d.ts +6 -6
- package/dist/index.js +4 -4
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
- package/dist/inspect-DhI49PSi.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
- package/dist/log-tail-DXeDkWEp.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
- package/dist/maintenance-CWBQpZ2y.js.map +1 -0
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
- package/dist/maintenance-C_KSkVjd.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +13 -8
- package/dist/node.js +1 -1
- package/dist/normalize-XWY25_sG.js.map +1 -1
- package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
- package/dist/observability-BYd-RzEx.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
- package/dist/plan-DIu_B6fy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
- package/dist/query-sQNO5vU_.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
- package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
- package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
- package/dist/restore-DpQYef6r.js.map +1 -0
- package/dist/shared-secret-BJdSwpgw.js.map +1 -1
- package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
- package/dist/src-CWpkSbvJ.js.map +1 -0
- package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
- package/dist/src-D24wDpzR.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
- package/dist/src-Db4-qVtM.js.map +1 -0
- package/dist/subcommand-CP9NY2J4.js +159 -0
- package/dist/subcommand-CP9NY2J4.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
- package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/package.json +42 -31
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
package/dist/cloudflare.js.map
CHANGED
|
@@ -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/worker.ts"],"sourcesContent":["import {\n BaerlyError,\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 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 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 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 { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport {\n type BaerlyAppConfig,\n CF_FREE_MAX_SAFE_FOLD_BYTES,\n type Verifier,\n WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n WRITE_TICK_GC_INTERVAL,\n WRITE_TICK_GC_MAX_MARKS,\n WRITE_TICK_GC_MAX_SWEEPS,\n} from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { createRouter } from \"@baerly/server/http\";\nimport type { MaintenanceDispatch } 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 { r2BindingStorage } from \"./r2-binding-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 */\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\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-CAS 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 * 1000-subrequest paid budget is a future graduation knob, not a var).\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 rawFoldBytes = readEnv(\"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\");\n const parsedFoldBytes =\n rawFoldBytes !== undefined && rawFoldBytes !== \"\" ? Number(rawFoldBytes) : Number.NaN;\n const maxFoldBytes = Number.isFinite(parsedFoldBytes) ? parsedFoldBytes : undefined;\n\n const rawDisable = readEnv(\"BAERLY_MAINTENANCE_DISABLE\");\n const disabled =\n rawDisable !== undefined &&\n rawDisable !== \"\" &&\n rawDisable !== \"0\" &&\n rawDisable.toLowerCase() !== \"false\";\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 maxFoldEntriesPerPass: WRITE_TICK_FOLD_ENTRIES_PER_PASS,\n gcMaxMarks: WRITE_TICK_GC_MAX_MARKS,\n gcMaxSweeps: WRITE_TICK_GC_MAX_SWEEPS,\n gcInterval: WRITE_TICK_GC_INTERVAL,\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 * 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 — passing `{ reset: true }` to LogTape — so\n * 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 * Leave the field unset to skip configuration entirely — the\n * default LogTape configuration is a no-op sink. Adapters that\n * skip configuration still emit through the bag/operator pipe; only\n * the LogTape `console.log` side becomes silent.\n */\n readonly observability?: ObservabilityConfig;\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 }\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 };\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) {\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 if (typeof rawFoldBytes === \"string\" && rawFoldBytes !== \"\") {\n const parsed = Number(rawFoldBytes);\n if (Number.isFinite(parsed) && parsed > 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 }\n return resolved;\n };\n\n return {\n async fetch(req, env, ctx): Promise<Response> {\n const { options, verifier } = 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 const url = new URL(req.url);\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-CAS 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.\n const storage = observableStorage(r2BindingStorage(env.BUCKET));\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 await options.scheduled(event, env, ctx);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,MAAM,eAAe,SACnB,KAAK,WAAW,IAAG,KAAK,KAAK,SAAS,IAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACnE,MAAM,aAAa,QAAwB,IAAI,IAAI;AAEnD,IAAM,uBAAN,MAA8C;CAC5C;CAEA,YAAY,QAAkB;EAC5B,IAAI,WAAW,QAAQ,WAAW,KAAA,GAChC,MAAM,IAAI,YACR,iBACA,8GACF;EAEF,KAAKA,UAAU;CACjB;CAEA,MAAM,IAAI,KAAa,MAA4D;EACjF,MAAM,QAAQ,eAAe;EAC7B,MAAM,UAAwB,CAAC;EAC/B,IAAI,MAAM,gBAAgB,KAAA,GACxB,QAAQ,SAAS,EAAE,kBAAkB,YAAY,KAAK,WAAW,EAAE;EAErE,MAAM,MAAM,MAAM,KAAKC,mBAAmB,KAAKD,QAAQ,IAAI,KAAK,OAAO,GAAG,OAAO,KAAK;EACtF,IAAI,QAAQ,MACV,OAAO;EAKT,IAAI,EAAE,UAAU,QAAQ,IAAI,SAAS,MACnC,OAAO;EAGT,OAAO;GAAE,MAAA,IADQ,WAAW,MAAM,IAAI,YAAY,CACtC;GAAG,MAAM,UAAU,IAAI,IAAI;EAAE;CAC3C;CAEA,MAAM,IAAI,KAAa,MAAkB,MAAqD;EAC5F,MAAM,QAAQ,eAAe;EAC7B,MAAM,UAAwB,CAAC;EAC/B,IAAI,MAAM,gBAAgB,KAAA,GACxB,QAAQ,eAAe,EAAE,aAAa,KAAK,YAAY;EAEzD,IAAI,MAAM,YAAY,KAAA,GACpB,QAAQ,SAAS,EAAE,aAAa,YAAY,KAAK,OAAO,EAAE;OACrD,IAAI,MAAM,gBAAgB,KAI/B,QAAQ,SAAS,EAAE,kBAAkB,IAAI;EAE3C,MAAM,SA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C,IAAI,QAAQ,cAAc,KAAA,GACxB,MAAM,QAAQ,UAAU,OAAO,KAAK,GAAG;EAE3C;CACF;AACF"}
|
|
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/worker.ts"],"sourcesContent":["import {\n BaerlyError,\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 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 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 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 { type DevLandingOptions, renderDevLanding } from \"@baerly/dev\";\nimport {\n type BaerlyAppConfig,\n CF_FREE_MAX_SAFE_FOLD_BYTES,\n MAINTENANCE_PROFILE_CF_FREE,\n type Verifier,\n} from \"@baerly/protocol\";\nimport { Db, resolveVerifier } from \"@baerly/server\";\nimport { createRouter } from \"@baerly/server/http\";\nimport type { MaintenanceDispatch } 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 { r2BindingStorage } from \"./r2-binding-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 */\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\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 rawFoldBytes = readEnv(\"BAERLY_MAINTENANCE_MAX_FOLD_BYTES\");\n const parsedFoldBytes =\n rawFoldBytes !== undefined && rawFoldBytes !== \"\" ? Number(rawFoldBytes) : Number.NaN;\n const maxFoldBytes = Number.isFinite(parsedFoldBytes) ? parsedFoldBytes : undefined;\n\n const rawDisable = readEnv(\"BAERLY_MAINTENANCE_DISABLE\");\n const disabled =\n rawDisable !== undefined &&\n rawDisable !== \"\" &&\n rawDisable !== \"0\" &&\n rawDisable.toLowerCase() !== \"false\";\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 // below) independently picks its own profile; today both resolve to\n // CF-free, so they stay coherent. If a second profile is ever\n // introduced, it MUST be threaded to BOTH paths or the two maintenance\n // triggers diverge.\n profile: MAINTENANCE_PROFILE_CF_FREE,\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 * 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 — passing `{ reset: true }` to LogTape — so\n * 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 * Leave the field unset to skip configuration entirely — the\n * default LogTape configuration is a no-op sink. Adapters that\n * skip configuration still emit through the bag/operator pipe; only\n * the LogTape `console.log` side becomes silent.\n */\n readonly observability?: ObservabilityConfig;\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 }\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 };\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) {\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 if (typeof rawFoldBytes === \"string\" && rawFoldBytes !== \"\") {\n const parsed = Number(rawFoldBytes);\n if (Number.isFinite(parsed) && parsed > 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 }\n return resolved;\n };\n\n return {\n async fetch(req, env, ctx): Promise<Response> {\n const { options, verifier } = 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 const url = new URL(req.url);\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.\n const storage = observableStorage(r2BindingStorage(env.BUCKET));\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 await options.scheduled(event, env, ctx);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,MAAM,eAAe,SACnB,KAAK,WAAW,IAAG,KAAK,KAAK,SAAS,IAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;AACnE,MAAM,aAAa,QAAwB,IAAI,IAAI;AAEnD,IAAM,uBAAN,MAA8C;CAC5C;CAEA,YAAY,QAAkB;EAC5B,IAAI,WAAW,QAAQ,WAAW,KAAA,GAChC,MAAM,IAAI,YACR,iBACA,8GACF;EAEF,KAAKA,UAAU;CACjB;CAEA,MAAM,IAAI,KAAa,MAA4D;EACjF,MAAM,QAAQ,eAAe;EAC7B,MAAM,UAAwB,CAAC;EAC/B,IAAI,MAAM,gBAAgB,KAAA,GACxB,QAAQ,SAAS,EAAE,kBAAkB,YAAY,KAAK,WAAW,EAAE;EAErE,MAAM,MAAM,MAAM,KAAKC,mBAAmB,KAAKD,QAAQ,IAAI,KAAK,OAAO,GAAG,OAAO,KAAK;EACtF,IAAI,QAAQ,MACV,OAAO;E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