@gusto/baerly-storage 0.4.0 → 0.5.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/dist/CHANGELOG.md +49 -0
- package/dist/baerly.spec.json +1 -1
- package/dist/cloudflare.d.ts +11 -8
- package/dist/cloudflare.js +4 -4
- package/dist/cloudflare.js.map +1 -1
- package/dist/dev-vite.js +1 -1
- package/dist/{http-DxM9MflO.js → http-DGd5tbNs.js} +2 -2
- package/dist/{http-DxM9MflO.js.map → http-DGd5tbNs.js.map} +1 -1
- package/dist/http.js +2 -2
- package/dist/{index-B6oexfOB.d.ts → index-CuA9Mi3K.d.ts} +6 -4
- package/dist/node.d.ts +2 -2
- package/dist/node.js +1 -1
- package/dist/{observability-wzs3-BL_.js → observability-BmflLCdF.js} +48 -12
- package/dist/{observability-wzs3-BL_.js.map → observability-BmflLCdF.js.map} +1 -1
- package/dist/observability.d.ts +1 -1
- package/dist/observability.js +1 -1
- package/dist/{runtime-spec-qL3_lTTU.js → runtime-spec-Dsw2-n8S.js} +2 -2
- package/dist/{runtime-spec-qL3_lTTU.js.map → runtime-spec-Dsw2-n8S.js.map} +1 -1
- package/dist/{src-BG20LZs7.js → src-BL_JoPTn.js} +5 -5
- package/dist/{src-BG20LZs7.js.map → src-BL_JoPTn.js.map} +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http-DxM9MflO.js","names":["#matchResult","#validatedData","#getDecodedParam","#getAllDecodedParams","#getParamValue","#cachedBody","#rawRequest","#executionCtx","#notFoundHandler","#path","#matchResult","#req","#res","#preparedHeaders","#renderer","#layout","#status","#var","#newResponse","Hono","#path","#addRoute","#notFoundHandler","#clone","#dispatch","#handleError","#routes","HonoBase"],"sources":["../packages/protocol/src/log.ts","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/compose.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/request/constants.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/body.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/url.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/request.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/html.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/context.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/router.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/constants.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/hono-base.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/router/pattern-router/router.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/preset/tiny.js","../packages/server/src/http/since.ts","../packages/server/src/http/router.ts"],"sourcesContent":["import { BaerlyError } from \"./errors.ts\";\nimport type { DocumentData, JSONValue } from \"./json.ts\";\nimport { COUNT_BIT_WIDTH } from \"./constants.ts\";\nimport { str2uintDesc } from \"./types.ts\";\n\n/**\n * Debezium-style JSON CDC envelope using pgoutput's message-tag (`I`/`U`/`D`) vocabulary. One per mutation.\n *\n * `LogEntry` is now a public, versionless/additive-only wire contract:\n * 0.3.0 is the public early-access baseline. It is still pre-1.0 and\n * soaking, so breaking changes remain possible, but only through an\n * explicit compatibility decision, changelog/migration notes, and a\n * versioned release. Assume external consumers may exist; do not\n * silently rename, remove, or repurpose fields. Consumers must ignore\n * unknown keys; new optional fields can be added in compatible releases.\n *\n * Field requirement matrix:\n * - Always: `lsn`, `commit_ts`, `op`, `collection`, `session`,\n * `seq`.\n * - For I/U/D: `doc_id`.\n * - For I/U: `after` (full post-image).\n * - Optional: `before` (when `replica_identity === \"FULL\"`), `key_old`\n * (U/D when `replica_identity !== \"PATCH_ONLY\"`), `origin`.\n *\n * @see docs/spec/log-entry-shape.md\n */\nexport interface LogEntry {\n /**\n * Opaque, monotonic, lex-asc cursor. Shape is\n * `<base32-time>_<session>_<seq>` — minted inside\n * `Writer.commit` (see\n * `packages/server/src/writer.ts`) from `timestamp()` +\n * the per-commit `session` + `countKey(seq)`. Consumers ack and\n * resume from this string.\n *\n * When you have a `LogEntry` in hand, prefer the structured\n * `session` / `seq` fields below over parsing this string. The\n * one place that *does* need to crack it open is the\n * `/v1/since` boundary, where a client resumes from an opaque\n * `next_cursor` and no `LogEntry` is in scope — that path uses\n * `lsnParts` (the kernel-blessed parser) rather than ad-hoc\n * `split(\"_\")`.\n */\n lsn: string;\n\n /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */\n commit_ts: string;\n\n /** Insert / Update / Delete. */\n op: \"I\" | \"U\" | \"D\";\n\n /**\n * Collection name — the pgoutput RELATION analogue. Today this is\n * the collection bound to the `current.json` whose `tail_hint` minted\n * the entry. The table API makes collections first-class.\n */\n collection: string;\n\n /**\n * The document key (`ref.key`). Required for every op — `op` is\n * `I | U | D` and all three carry it — so the wire type is required,\n * not optional, matching `log-entry-shape.md`.\n */\n doc_id: string;\n\n /** Required for I, U. The post-image (Debezium's `after`). */\n after?: DocumentData;\n\n /**\n * The pre-image (Debezium's `before`). Present iff the\n * collection's `replica_identity` is `FULL`. ~2× log size on\n * update-heavy collections; off by default.\n */\n before?: DocumentData;\n\n /**\n * Pre-image of the primary key. U/D always carry this when\n * `replica_identity` is not `PATCH_ONLY`. (For baerly-storage today,\n * `_id` is the only PK.)\n */\n key_old?: { readonly [pk: string]: JSONValue };\n\n /** ORIGIN analogue — the writer session id. */\n origin?: string;\n\n /**\n * Causal metadata (baerly-storage-only; no pgoutput analogue). The\n * session id that built the `lsn`. Surfaces here so consumers\n * can dedupe / order without parsing the cursor.\n */\n session: string;\n\n /**\n * The `log/<seq>` slot this entry occupies — the integer in its\n * `log/<seq>.json` key, minted by `Writer.commit` as the forward-probed\n * collection-log tail (the winning `If-None-Match: \"*\"` create). One\n * entry per `session`, so this is a per-collection slot, not a\n * per-session counter. Also encoded (descending base-32) as the LSN's\n * third segment — see `lsnParts`.\n */\n seq: number;\n}\n\n/**\n * Per-collection setting controlling how much pre-image data each\n * `U` / `D` entry carries.\n *\n * - `PATCH_ONLY` (default today, applied unconditionally): `U`\n * carries `{ after }`; no `before`, no `key_old`.\n * Bandwidth-cheap. SQL consumers rebuilding before-images need\n * to maintain a shadow table.\n * - `FULL`: `U` additionally carries `before` and `key_old`. ~2× log\n * size on update-heavy collections; buys true 1:1 logical\n * replication and \"previous value\" answerable from the log\n * alone.\n *\n * Per-collection opt-in is not yet wired; every collection is\n * currently `PATCH_ONLY`.\n */\nexport type ReplicaIdentity = \"PATCH_ONLY\" | \"FULL\";\n\n// `LOG_KEY_PREFIX` + `logObjectKey` live in the zero-import `log-key.ts`\n// leaf so consumers that only need the key shape don't drag this module's\n// `lsn` parsing runtime into their bundle closure (it added +3.8 KB raw to\n// `maintenance.js` when the helper lived here).\n\n/**\n * Extract the `session` and `seq` embedded in an `lsn` of shape\n * `<base32-time>_<session>_<seq>`. The seq portion is decoded as a\n * descending base-32 integer (matches `countKey` in `./types`).\n *\n * Use this at the `/v1/since` cursor-decoding boundary, where a\n * client resumes from an opaque `SinceResponse.next_cursor` and no\n * `LogEntry` is in scope. When iterating `LogEntry` records, read\n * `entry.session` / `entry.seq` directly instead.\n *\n * Throws on malformed input; callers should pass only lsns minted\n * by `Writer.commit` (see\n * `packages/server/src/writer.ts`).\n */\nexport const lsnParts = (lsn: string): { session: string; seq: number } => {\n const parts = lsn.split(\"_\");\n if (parts.length !== 3) {\n throw new BaerlyError(\"InvalidResponse\", `invalid lsn shape: ${lsn}`);\n }\n return {\n session: parts[1]!,\n seq: str2uintDesc(parts[2]!, COUNT_BIT_WIDTH),\n };\n};\n","// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n","// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n","// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n","// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n","// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * `.bytes()` parses the request body as a `Uint8Array`.\n *\n * @see {@link https://hono.dev/docs/api/request#bytes}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.bytes()\n * })\n * ```\n */\n bytes() {\n return this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * <html>\n * <body>\n * <p>{content}</p>\n * </body>\n * </html>\n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n","// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n","// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n","// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler, r.basePath);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = this.getPath(request).slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler, baseRoutePath) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = {\n basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n path,\n method,\n handler\n };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise<Response>} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n","// src/router/pattern-router/router.ts\nimport { METHOD_NAME_ALL, UnsupportedPathError } from \"../../router.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar PatternRouter = class {\n name = \"PatternRouter\";\n #routes = [];\n add(method, path, handler) {\n const endsWithWildcard = path.at(-1) === \"*\";\n if (endsWithWildcard) {\n path = path.slice(0, -2);\n }\n if (path.at(-1) === \"?\") {\n path = path.slice(0, -1);\n this.add(method, path.replace(/\\/[^/]+$/, \"\"), handler);\n }\n const parts = (path.match(/\\/?(:\\w+(?:{(?:(?:{[\\d,]+})|[^}])+})?)|\\/?[^\\/\\?]+/g) || []).map(\n (part) => {\n const match = part.match(/^\\/:([^{]+)(?:{(.*)})?/);\n return match ? `/(?<${match[1]}>${match[2] || \"[^/]+\"})` : part === \"/*\" ? \"/[^/]+\" : part.replace(/[.\\\\+*[^\\]$()]/g, \"\\\\$&\");\n }\n );\n try {\n this.#routes.push([\n new RegExp(`^${parts.join(\"\")}${endsWithWildcard ? \"\" : \"/?$\"}`),\n method,\n handler\n ]);\n } catch {\n throw new UnsupportedPathError();\n }\n }\n match(method, path) {\n const handlers = [];\n for (let i = 0, len = this.#routes.length; i < len; i++) {\n const [pattern, routeMethod, handler] = this.#routes[i];\n if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {\n const match = pattern.exec(path);\n if (match) {\n handlers.push([handler, match.groups || emptyParams]);\n }\n }\n }\n return [handlers];\n }\n};\nexport {\n PatternRouter\n};\n","// src/preset/tiny.ts\nimport { HonoBase } from \"../hono-base.js\";\nimport { PatternRouter } from \"../router/pattern-router/index.js\";\nvar Hono = class extends HonoBase {\n constructor(options = {}) {\n super(options);\n this.router = new PatternRouter();\n }\n};\nexport {\n Hono\n};\n","/**\n * Long-poll `GET /v1/since` handler core. Two exports:\n *\n * - {@link longPollSince} — the long-poll itself. Fast path first;\n * if `listEventsSince` already sees events, return immediately.\n * Otherwise race a poll loop against a 25 s wall-clock timeout and\n * return either the next batch of events or\n * `{ events: [], next_cursor: <same> }` (\"nothing changed within\n * the budget\").\n * - {@link listEventsSince} — one poll cycle. Reads `current.json`,\n * validates the caller's cursor against `log_seq_start`, discovers\n * the true tail by forward-probe, GETs each body by integer `seq`,\n * and returns the parsed `LogEntry`s in causal order.\n *\n * The handler is wired into the Hono router (`router.ts`); the\n * router itself owns request parsing and error → HTTP mapping. This\n * module owns the I/O + cursor semantics.\n *\n * Cost model. While a long-poll connection is active the per-poll\n * cost is one `Storage.get` of `current.json`, the tail\n * forward-probe GETs, plus one `Storage.get` per log entry yielded.\n * These are Class B ops, not Class A. The `< 1 Class A op / writer /\n * hour` cost-model bound (see `docs/spec/sync-protocol.md`) still\n * holds; active long-poll subscribers pay repeated Class B reads for\n * lower-latency delivery.\n */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n COUNT_BIT_WIDTH,\n type LogEntry,\n logSeqStartOf,\n lsnParts,\n} from \"@baerly/protocol\";\nimport type { Db } from \"../db.ts\";\nimport type { SinceResponse } from \"../contract.ts\";\n\n/**\n * Validation regex for an opaque LSN cursor. Matches the shape minted\n * by `Writer.commit` (see `packages/server/src/writer.ts`) and described\n * on {@link LogEntry.lsn} — `<base32-time>_<session>_<seq>` where\n * base-32 is `[0-9a-v]` and the trailing seq is a fixed-width token.\n *\n * The seq width (`{11}`) is `Math.ceil(COUNT_BIT_WIDTH / 5)` chars, derived\n * automatically from the canonical `COUNT_BIT_WIDTH` constant in\n * `packages/protocol/src/constants.ts` via the `SEQ_CHARS` computed\n * constant below — no manual update needed when `COUNT_BIT_WIDTH` changes.\n * Currently: `Math.ceil(53 / 5) = 11`.\n */\n// COUNT_BIT_WIDTH is 53; Math.ceil(53 / 5) = 11.\nconst SEQ_CHARS = Math.ceil(COUNT_BIT_WIDTH / 5); // 11\nconst LSN_RE = new RegExp(`^[0-9a-v]+_[0-9a-v]+_[0-9a-v]{${SEQ_CHARS}}$`);\n\n/**\n * Hard cap on log entries returned in a single poll cycle. 1024 is\n * comfortably above the largest expected per-poll batch under the\n * production 1 s poll interval and bounds the worst-case memory\n * footprint of the parsed-JSON array on a hostile workload.\n */\nconst DEFAULT_MAX_EVENTS = 1024;\n\n/**\n * Default 25 s long-poll budget. CF Workers cap fetch CPU at 30 s on\n * the free plan; 25 s leaves slack for header serialization plus the\n * platform's bookkeeping. Node / Bun / Deno have no comparable cap,\n * but the budget is still useful as a connection-cycling hint for\n * upstream load balancers (most idle-connection timeouts are 30-60 s).\n *\n * Per-request override is via the `timeoutMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sinceTimeoutMs` on\n * `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_TIMEOUT_MS = 25_000;\n\n/**\n * Default 1 s inner-poll interval. See module docstring for the\n * cost-model trade-off.\n *\n * Per-request override is via the `pollIntervalMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sincePollIntervalMs`\n * on `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\n\nexport interface LongPollSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n readonly pollIntervalMs?: number;\n}\n\nexport interface ListEventsSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Long-poll wrapper around {@link listEventsSince}. Returns as soon\n * as the first non-empty poll lands, or when the wall-clock timeout\n * elapses (whichever comes first). On timeout the response is\n * `{ events: [], next_cursor: <same> }` — shipped as `200`, not `304`,\n * because the response body carries the unchanged cursor the client\n * needs for the next poll cycle.\n *\n * @throws BaerlyError{code:\"SchemaError\"} — invalid cursor shape, or\n * the cursor references a log entry that has been folded into a\n * snapshot and GC'd.\n */\nexport async function longPollSince(opts: LongPollSinceOptions): Promise<SinceResponse> {\n const { db, collection, cursor, signal } = opts;\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n\n // Up-front cursor-shape validation. `listEventsSince` also checks,\n // but doing it here short-circuits the fast-path read on bad input.\n if (cursor.length > 0 && !LSN_RE.test(cursor)) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`,\n );\n }\n\n // Fast path: the first poll already sees new events.\n const initial = await listEventsSince({ db, collection, cursor, signal });\n if (initial.length > 0) {\n return { events: initial, next_cursor: initial[initial.length - 1]!.lsn };\n }\n\n // No events yet. Race a timeout against a polling loop.\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n return new Promise<SinceResponse>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let settled = false;\n\n const cleanup = (): void => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n if (signal !== undefined) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n };\n\n const settleResolve = (value: SinceResponse): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n resolve(value);\n };\n const settleReject = (err: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n reject(err);\n };\n\n function onAbort(): void {\n // Treat client disconnect as \"no events, same cursor\" — the\n // socket is gone anyway; the resolve is a no-op for response\n // serialization but keeps the promise from leaking.\n settleResolve({ events: [], next_cursor: cursor });\n }\n\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const tick = async (): Promise<void> => {\n if (settled) {\n return;\n }\n try {\n const events = await listEventsSince({ db, collection, cursor, signal });\n if (settled) {\n return;\n }\n if (events.length > 0) {\n settleResolve({ events, next_cursor: events[events.length - 1]!.lsn });\n return;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n settleResolve({ events: [], next_cursor: cursor });\n return;\n }\n const delay = Math.min(pollIntervalMs, remaining);\n timer = setTimeout(() => {\n void tick();\n }, delay);\n } catch (error) {\n settleReject(error);\n }\n };\n\n // First tick scheduled after `pollIntervalMs` (the initial fast\n // path already covered \"events present at t=0\"). Cap by the\n // remaining deadline so an early-cutoff tester with\n // `timeoutMs < pollIntervalMs` still resolves on time.\n timer = setTimeout(\n () => {\n void tick();\n },\n Math.min(pollIntervalMs, timeoutMs),\n );\n });\n}\n\n/**\n * One poll cycle: read `current.json`, derive the `seq` range to\n * scan from the cursor's embedded seq, GET each log entry by `seq`,\n * return the parsed `LogEntry`s in causal order.\n *\n * On-bucket log keys are `log/<seq>.json` — the same shape\n * `compactor` / `gc` / `rebuild-index` walk. Iterating\n * `[startSeq, endSeq)` and GET-ing each key directly avoids the\n * lex-`startAfter` hazard on integer filenames (`10.json` sorts\n * before `2.json` lex) and gives us the global causal ordering for\n * free — `seq` is monotonic across writer sessions.\n *\n * No `current.json` yet → `[]` (clients can poll a not-yet-existing\n * collection without erroring). Cursor inside `[0, log_seq_start)` →\n * `BaerlyError{code:\"SchemaError\"}`.\n */\nexport async function listEventsSince(opts: ListEventsSinceOptions): Promise<LogEntry[]> {\n const { db, collection, cursor, signal } = opts;\n\n if (cursor.length > 0 && !LSN_RE.test(cursor)) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`,\n );\n }\n\n const read = await db.getCurrentJson(collection, signalOpt(signal));\n if (read === null) {\n // No collection provisioned yet. Clients polling for a collection that\n // doesn't exist see an empty stream, NOT an error.\n return [];\n }\n const logSeqStart = logSeqStartOf(read.json);\n // End bound is the DISCOVERED tail (probe past a stale-low hint).\n // The GET loop below 404-tolerates misses, so over-bounding is safe.\n // Floor at `max(log_seq_start, tail_hint)` — same probe floor every\n // other consumer uses (the invariant `tail_hint >= log_seq_start`\n // holds, so this is consistency, not a behaviour change).\n const tail = await db.probeLogTail(\n collection,\n Math.max(logSeqStart, read.json.tail_hint),\n signalOpt(signal),\n );\n\n // Derive the seq range to scan. Empty cursor → start at\n // `log_seq_start` (the first un-snapshotted entry). Non-empty\n // cursor → start at `cursorSeq + 1`. A cursor whose seq is below\n // `log_seq_start` references an entry the compactor has folded\n // into the snapshot and the GC sweep has deleted; the client must\n // re-bootstrap from a snapshot read before resuming.\n let startSeq: number;\n if (cursor.length === 0) {\n startSeq = logSeqStart;\n } else {\n const cursorSeq = lsnParts(cursor).seq;\n if (cursorSeq < logSeqStart) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor ${JSON.stringify(cursor)} points to a log entry that has been folded into a snapshot (log_seq_start=${logSeqStart}); re-bootstrap from a snapshot read before resuming`,\n );\n }\n startSeq = cursorSeq + 1;\n }\n\n // Cap the range at the discovered `tail` (no entries past the tail\n // exist) and at `DEFAULT_MAX_EVENTS` (hard ceiling per the module\n // docstring).\n const endSeq = Math.min(tail, startSeq + DEFAULT_MAX_EVENTS);\n\n // Sequential GETs (NOT Promise.all). Long-poll is latency-bound,\n // per-poll batch is typically 0-10 entries, sequential keeps\n // memory bounded under pathological workloads.\n const entries: LogEntry[] = [];\n for (let s = startSeq; s < endSeq; s++) {\n const entry = await db.getLogEntry(collection, s, signalOpt(signal));\n if (entry === null) {\n // Race: the GC sweeper deleted this entry between\n // `getCurrentJson` and the GET. Skip; don't error.\n continue;\n }\n entries.push(entry);\n }\n\n return entries;\n}\n\n/** Pack an optional `signal` into the `{ signal? }` shape callers expect. */\nconst signalOpt = (signal: AbortSignal | undefined): { signal?: AbortSignal } | undefined =>\n signal === undefined ? undefined : { signal };\n","/**\n * HTTP dispatcher. A small Hono `app` that implements the\n * five locked CRUD routes from `contract.ts`. Mounted into both\n * adapters (`@baerly/adapter-cloudflare` and `@baerly/adapter-node`);\n * the router itself is platform-agnostic — it accepts a single\n * `Request`, dispatches against a per-request `Db`, and returns a\n * `Response` whose body follows the `HttpOkEnvelope` /\n * `HttpErrorEnvelope` shapes.\n *\n * The anonymous `GET /v1/healthz` liveness probe is served by the\n * adapters directly (see `worker.ts` / `server.ts`) — keeping it\n * upstream of the router avoids spending a `Db.create` on every\n * load-balancer probe.\n *\n * `GET /v1/since` is appended to the same factory (see `./since.ts`\n * for the long-poll core). The Cloudflare adapter wraps Worker-side\n * GETs with `caches.default` *outside* `createRouter` so the router\n * stays platform-agnostic; that wrapper EXCLUDES `/v1/since` —\n * long-poll idleness is not a cache hit.\n */\n\nimport { Hono } from \"hono/tiny\";\nimport type { Context } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport {\n type BaerlyConfig,\n BaerlyError,\n type DocumentData,\n type BaerlyErrorCode,\n EMPTY_PREDICATE_WIRE,\n type OrderSpec,\n type PredicateWire,\n validateWire,\n WHERE_ORDER_JSON_RESOLUTION,\n WRITE_BODY_SHAPE_RESOLUTION,\n} from \"@baerly/protocol\";\nimport type { Db } from \"../db.ts\";\nimport {\n errorEnvelope,\n type HttpErrorEnvelope,\n type HttpOkEnvelope,\n type HttpStatus,\n type SinceResponse,\n} from \"../contract.ts\";\nimport { serializeError } from \"../observability/canonical.ts\";\nimport { CATEGORY, getCurrentContext, getLogger } from \"../observability/index.ts\";\nimport { runAllWithMeta, runByIdWithMeta } from \"../query.ts\";\nimport { longPollSince } from \"./since.ts\";\n\n/**\n * Options for {@link createRouter}.\n *\n * - `db` — single-tenant `Db` instance. The CF/Node adapters build a\n * fresh `Db` per request (after the Verifier resolves the tenant)\n * and hand it to a freshly-constructed router. The router itself\n * is stateless and per-request — `app.fetch(req)` is the only\n * entry point. The Verifier runs in the adapter (see `worker.ts` /\n * `server.ts`) before `createRouter` is called; the router itself\n * has no auth seam.\n */\nexport interface CreateRouterOptions {\n readonly db: Db<BaerlyConfig>;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Hono `app` that serves the CRUD routes:\n *\n * - `GET /v1/c/:collection/:id` → read one document.\n * - `GET /v1/c/:collection?where=<json>&order=<json>&limit=<n>` → list rows\n * matching a predicate, optionally ordered and capped.\n * - `POST /v1/c/:collection` → insert. Body: `{ doc }`. → `201 { _id }`.\n * - `PATCH /v1/c/:collection/:id` → merge-patch. Body: `{ patch }`. → `200 { modified }`.\n * - `PUT /v1/c/:collection/:id` → whole-doc replace. Body: `{ doc }`. → `200 { modified }`.\n * - `DELETE /v1/c/:collection/:id` → delete row by id. → `204`.\n * - `GET /v1/count?collection=<name>&where=<json>` → scalar `{ count: N }`.\n * - `GET /v1/since?collection=<name>&cursor=<opaque>` → long-poll log.\n *\n * @example\n * ```ts\n * import { createRouter, Db } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const db = Db.create({ storage: new MemoryStorage(), app: \"tickets\", tenant: \"acme\" });\n * const app = createRouter({ db });\n * // CF Workers:\n * export default { async fetch(req: Request) { return app.fetch(req); } };\n * ```\n */\nexport function createRouter(options: CreateRouterOptions): Hono {\n const { db, sinceTimeoutMs, sincePollIntervalMs } = options;\n const app = new Hono();\n\n // The router intentionally does NOT mount an observability\n // middleware. Production adapters (`@baerly/adapter-cloudflare`,\n // `@baerly/adapter-node`) open their own `ObservabilityContext`\n // BEFORE calling `createRouter().fetch` so they can stamp adapter-\n // owned fields (e.g. `cache_status`) before the cache wrapper\n // short-circuits. Standalone callers (tests, one-off harnesses) wrap\n // their request via `withHttpObservability` from\n // `@baerly/server`. Either way, one unit-of-work → exactly one\n // canonical line.\n\n // Read one — GET /v1/c/:collection/:id\n app.get(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { rows, manifestPointer, fresh } = await runByIdWithMeta(\n db.collectionReadContext(collection),\n id,\n );\n const row = rows[0];\n if (row === undefined) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return c.json(\n {\n data: row,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<DocumentData>,\n 200,\n );\n });\n\n // List — GET /v1/c/:collection?where=<urlencoded-json>\n app.get(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const wire = parseWhereParam(c);\n const order = parseOrder(c.req.query(\"order\"));\n const limit = parseLimit(c.req.query(\"limit\"));\n const { rows, manifestPointer, fresh } = await runAllWithMeta(\n db.collectionReadContext(collection),\n {\n wire,\n order,\n limit,\n },\n );\n return c.json(\n {\n data: rows,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<ReadonlyArray<DocumentData>>,\n 200,\n );\n });\n\n // Insert — POST /v1/c/:collection Body: { doc } → 201 { _id }\n app.post(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n const { _id } = await db\n .collection(collection)\n .insert(doc as Partial<DocumentData> & DocumentData);\n return c.json({ _id }, 201);\n });\n\n // Patch — PATCH /v1/c/:collection/:id Body: { patch }\n app.patch(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const patch = assertJsonBodyField(body, \"patch\");\n const { modified } = await db.collection(collection).update(id, patch as Partial<DocumentData>);\n if (modified === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return c.json({ modified }, 200);\n });\n\n // Replace — PUT /v1/c/:collection/:id Body: { doc }\n // Whole-document overwrite (NOT merge-patch). Missing row → 404\n // (kernel throws `NotFound` directly via `runReplaceById`); row\n // matches → emits one `op:\"U\"` log entry with the post-image,\n // dropping fields absent from `doc`.\n app.put(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n await db.collection(collection).replace(id, doc as DocumentData);\n return c.json({ modified: 1 }, 200);\n });\n\n // Delete — DELETE /v1/c/:collection/:id → 204\n app.delete(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { deleted } = await db.collection(collection).delete(id);\n if (deleted === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return new Response(null, { status: 204 });\n });\n\n // Count — GET /v1/count?collection=<name>&where=<json>\n //\n // Returns a scalar row count for the matching predicate. Avoids the\n // client downloading every row just to take `.length` (silent egress\n // burn). Engine cost is currently the same as `runAllWithMeta` — the\n // win is wire bytes; an O(snapshot+log) count path can land later\n // without touching this route.\n app.get(\"/v1/count\", async (c) => {\n const collection = c.req.query(\"collection\");\n if (collection === undefined || collection.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n \"GET /v1/count requires ?collection=<name>\",\n undefined,\n undefined,\n undefined,\n \"Add ?collection=<name> to the request URL.\",\n );\n }\n const wire = parseWhereParam(c);\n const { rows, manifestPointer, fresh } = await runAllWithMeta(\n db.collectionReadContext(collection),\n {\n wire,\n order: undefined,\n limit: undefined,\n },\n );\n return c.json(\n {\n data: { count: rows.length },\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<{ count: number }>,\n 200,\n );\n });\n\n // Long-poll — GET /v1/since?collection=<name>&cursor=<opaque>\n //\n // Cache-API note: the Cloudflare adapter's `caches.default` wrapper\n // explicitly EXCLUDES `/v1/since` — long-poll idleness is not a\n // cache hit. The adapter middleware MUST check the path before\n // consulting the cache. Do NOT add cache reads here.\n app.get(\"/v1/since\", async (c) => {\n // The router does NOT set `c.var.db`; the adapter resolves the\n // Verifier BEFORE `createRouter` is called and the resulting `db`\n // is captured in this closure. The handler reads it from the\n // outer scope, not from `c.var`.\n const collection = c.req.query(\"collection\");\n if (typeof collection !== \"string\" || collection.length === 0 || collection.includes(\"/\")) {\n throw new BaerlyError(\n \"SchemaError\",\n \"GET /v1/since requires a non-empty `collection` query parameter without `/`\",\n );\n }\n const cursor = c.req.query(\"cursor\") ?? \"\";\n const result = await longPollSince({\n db,\n collection,\n cursor,\n signal: c.req.raw.signal,\n timeoutMs: sinceTimeoutMs,\n pollIntervalMs: sincePollIntervalMs,\n });\n // 200 covers both \"new events present\" and \"timeout idle\" —\n // see `./since.ts` module JSDoc for why we don't use 304.\n return c.json(result satisfies SinceResponse, 200);\n });\n\n app.onError((err, c) => mapToResponse(c, err));\n\n return app;\n}\n\n/**\n * Hard cap on request-body bytes. 1 MiB — matches `S3HttpStorage`'s\n * conformance-suite default. Over-cap → `413 PayloadTooLarge`.\n *\n * The Node adapter (`@baerly/adapter-node`) imports this constant\n * and passes it to `applyBodyCap`, which wraps the request body\n * with a counting `TransformStream` so chunked uploads trip the cap\n * mid-stream rather than materialising the full buffer. The\n * router's `readJsonBody` keeps the cap as a defence-in-depth check\n * (Content-Length pre-read + post-`arrayBuffer` length) for adapters\n * whose platform doesn't pre-cap.\n *\n * @internal — exported for tests and for the Node adapter's\n * `applyBodyCap` helper. Promote to\n * `packages/protocol/src/constants.ts` only on a third cross-\n * package consumer.\n */\nexport const MAX_BODY_BYTES = 1 << 20; // 1 MiB; matches `S3HttpStorage`'s conformance-suite default.\n\n/**\n * Assert that `body[field]` is a plain object (not undefined / null /\n * array / primitive). Returns the value typed as\n * `Record<string, unknown>` so the caller's next cast doesn't need\n * another guard. Throws `BaerlyError{code:\"SchemaError\"}` with the\n * locked wording `\"Request body must be { <field>: object }\"`.\n *\n * Used by POST `/v1/c/:collection` (`doc`), PATCH `/v1/c/:collection/:id`\n * (`patch`), and PUT `/v1/c/:collection/:id` (`doc`).\n *\n * @internal\n */\nconst assertJsonBodyField = (body: unknown, field: string): Record<string, unknown> => {\n const value =\n typeof body === \"object\" && body !== null\n ? (body as Record<string, unknown>)[field]\n : undefined;\n if (value === undefined || typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new BaerlyError(\n \"SchemaError\",\n `Request body must be { ${field}: object }`,\n undefined,\n undefined,\n undefined,\n WRITE_BODY_SHAPE_RESOLUTION,\n );\n }\n return value as Record<string, unknown>;\n};\n\n/**\n * Parse the `?where=<urlencoded JSON>` query-string param. Absent or\n * empty → {@link EMPTY_PREDICATE_WIRE} (match-all). Malformed JSON →\n * `BaerlyError{code:\"SchemaError\"}` with the locked wording\n * `\"Invalid JSON in ?where=\"`. Returns the validated wire form\n * ({@link PredicateWire}).\n *\n * Wire-only validation: any clause with `field === \"_id\"` rejects\n * with `BaerlyError{code:\"InvalidConfig\"}` — agents zero-shot\n * writing `?where={\"clauses\":[{\"op\":\"eq\",\"field\":\"_id\",\"value\":\"x\"}]}`\n * against the list route get pointed at `GET /v1/c/:collection/:id`\n * instead. Kernel-internal `_id` wire construction\n * (`./collection.ts:byId`, `runByIdWithMeta`, `runInsert`) bypasses this\n * layer by design — those paths never come back through `?where=`\n * parsing.\n *\n * @internal\n */\nconst parseWhereParam = (c: Context): PredicateWire => {\n const whereParam = c.req.query(\"where\");\n if (whereParam === undefined || whereParam.length === 0) {\n return EMPTY_PREDICATE_WIRE;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(whereParam);\n } catch {\n throw new BaerlyError(\n \"SchemaError\",\n \"Invalid JSON in ?where=\",\n undefined,\n undefined,\n undefined,\n WHERE_ORDER_JSON_RESOLUTION,\n );\n }\n try {\n return validateWire(parsed as PredicateWire);\n } catch (error) {\n throw markCallerFacingInvalidConfig(error);\n }\n};\n\n/**\n * Parse `?limit=<n>` as a non-negative safe integer. Returns\n * `undefined` when absent. Rejects floats, NaN, negatives, and\n * non-numeric input with `SchemaError`.\n *\n * @internal\n */\nfunction parseLimit(raw: string | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const n = Number(raw);\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `?limit= must be a non-negative integer; got ${JSON.stringify(raw)}`,\n );\n }\n return n;\n}\n\n/**\n * Parse the `?order=<json>` query param. Mirrors the `?where=` parser\n * shape: undefined → no order, malformed JSON → `SchemaError`. The\n * engine (`runAllWithMeta` → `sortByOrderSpec`) validates the shape\n * itself, so this only handles the wire-level JSON decode.\n *\n * @internal\n */\nfunction parseOrder(raw: string | undefined): OrderSpec<DocumentData> | undefined {\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new BaerlyError(\n \"SchemaError\",\n \"Invalid JSON in ?order=\",\n undefined,\n undefined,\n undefined,\n WHERE_ORDER_JSON_RESOLUTION,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BaerlyError(\n \"SchemaError\",\n \"?order= must encode a JSON object\",\n undefined,\n undefined,\n undefined,\n WHERE_ORDER_JSON_RESOLUTION,\n );\n }\n return parsed as OrderSpec<DocumentData>;\n}\n\n// Exported as the single source of truth for the error-code → HTTP-status\n// mapping: the runtime router (below) and the build-time spec generator\n// (`spec/ir.ts`, reached via the `_internal/spec-gen` subpath) both read it,\n// so the served `/v1/spec` contract cannot drift from real router behaviour —\n// that drift gate is the point. Deliberately NOT re-exported from the\n// `@baerly/server/http` barrel, so the published package surface is unchanged.\nexport const ERROR_TO_STATUS: ReadonlyMap<BaerlyErrorCode, HttpStatus> = new Map<\n BaerlyErrorCode,\n HttpStatus\n>([\n [\"Unauthorized\", 401],\n [\"AccessDenied\", 403],\n [\"NotFound\", 404],\n [\"Conflict\", 409],\n [\"PayloadTooLarge\", 413],\n [\"SchemaError\", 400],\n [\"InvalidConfig\", 400],\n [\"UnsatisfiablePredicate\", 400],\n [\"NetworkError\", 502],\n [\"InvalidResponse\", 502],\n // Internal → 500\n]);\n\n/**\n * Machine-visible policy for whether an error code's thrown message is\n * safe to copy into the HTTP envelope. This is code-level metadata;\n * `Conflict` is instance-contextual because duplicate `_id` conflicts are\n * caller-facing, while retriable CAS/storage conflicts may carry bucket keys.\n * `InvalidConfig` is also contextual: predicate-wire validation errors are\n * caller-facing, but storage/adapter config errors may carry internal layout.\n *\n * Deliberately NOT re-exported from the `@baerly/server/http` barrel.\n */\nexport type ErrorMessagePolicy = \"public\" | \"scrubbed\" | \"contextual\";\n\ntype ErrorCodePolicy =\n | { readonly messagePolicy: \"public\" }\n | {\n readonly messagePolicy: \"scrubbed\";\n readonly scrubbedMessage: string;\n }\n | {\n readonly messagePolicy: \"contextual\";\n readonly scrubbedMessage: string;\n readonly shouldExpose: (err: BaerlyError) => boolean;\n };\n\nconst CALLER_FACING_INVALID_CONFIG_ERRORS = new WeakSet<BaerlyError>();\n\nconst ERROR_CODE_POLICY = {\n AccessDenied: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"access denied\",\n },\n Conflict: {\n messagePolicy: \"contextual\",\n scrubbedMessage: \"write conflict\",\n shouldExpose: (err) => !err.retriable,\n },\n Internal: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n InvalidConfig: {\n messagePolicy: \"contextual\",\n scrubbedMessage: \"invalid server configuration\",\n shouldExpose: (err) => CALLER_FACING_INVALID_CONFIG_ERRORS.has(err),\n },\n InvalidResponse: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"upstream response error\",\n },\n MutationFailed: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n NetworkError: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"upstream network error\",\n },\n NotFound: {\n messagePolicy: \"public\",\n },\n PayloadTooLarge: {\n messagePolicy: \"public\",\n },\n SchemaError: {\n messagePolicy: \"public\",\n },\n Unauthorized: {\n messagePolicy: \"public\",\n },\n UnexpectedWriteInQuery: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n UnsatisfiablePredicate: {\n messagePolicy: \"public\",\n },\n UseQueryAwaitedRecorder: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n} as const satisfies Record<BaerlyErrorCode, ErrorCodePolicy>;\n\nexport const errorMessagePolicyFor = (code: BaerlyErrorCode): ErrorMessagePolicy =>\n ERROR_CODE_POLICY[code].messagePolicy;\n\nconst markCallerFacingInvalidConfig = (err: unknown): unknown => {\n if (err instanceof BaerlyError && err.code === \"InvalidConfig\") {\n CALLER_FACING_INVALID_CONFIG_ERRORS.add(err);\n }\n return err;\n};\n\nconst shouldExposeErrorMessage = (err: BaerlyError): boolean => {\n const policy = ERROR_CODE_POLICY[err.code];\n if (policy.messagePolicy === \"public\") {\n return true;\n }\n if (policy.messagePolicy === \"scrubbed\") {\n return false;\n }\n return policy.shouldExpose(err);\n};\n\nconst scrubbedMessageFor = (code: BaerlyErrorCode): string => {\n const policy = ERROR_CODE_POLICY[code];\n return policy.messagePolicy === \"public\" ? \"internal error\" : policy.scrubbedMessage;\n};\n\nconst logScrubbedError = (err: BaerlyError, status: HttpStatus): void => {\n const ctx = getCurrentContext();\n getLogger(CATEGORY.http).error(\"scrubbed_error\", {\n error: serializeError(err),\n status,\n ...(ctx !== undefined ? { request_id: ctx.request_id } : {}),\n });\n};\n\n/**\n * Map an unknown thrown value onto the wire envelope plus an HTTP\n * status code. The mapping is keyed by `BaerlyError.code` so any future\n * code addition forces a re-check here. Unmapped server-side codes fall\n * through to 500 by design — currently only `Internal`.\n *\n * Public via `@gusto/baerly-storage/http` for the embed-by-hand recipe\n * (your own Hono / Express / Fastify app calling `Db` directly).\n * The `HttpErrorEnvelope` shape is locked; do not mutate it.\n */\nexport function mapError(err: unknown): { status: HttpStatus; envelope: HttpErrorEnvelope } {\n if (err instanceof BaerlyError) {\n const mappedStatus = ERROR_TO_STATUS.get(err.code);\n const status = mappedStatus ?? 500;\n const wireCode: BaerlyErrorCode = mappedStatus === undefined ? \"Internal\" : err.code;\n // Do not use HTTP status as the \"safe to expose\" signal: storage\n // and protocol errors mapped to 4xx/502 often carry physical bucket\n // keys, ETags, upstream response bodies, or provider binding text.\n // Preserve caller-facing messages, scrub server/storage diagnostics,\n // and keep the full detail in the server-side log.\n if (wireCode !== err.code || !shouldExposeErrorMessage(err)) {\n logScrubbedError(err, status);\n return {\n status,\n envelope: errorEnvelope(\n wireCode,\n scrubbedMessageFor(wireCode),\n undefined,\n wireCode === \"Conflict\" ? err.resolution : undefined,\n wireCode === err.code ? err.retriable : undefined,\n ),\n };\n }\n return {\n status,\n envelope: errorEnvelope(err.code, err.message, err.issues, err.resolution, err.retriable),\n };\n }\n // Unknown thrown value: the message may carry internal detail\n // (file paths, bucket names, upstream response bodies). Log on the\n // server side via the observability channel (replaces the legacy\n // bare `console.error`) and return a generic envelope to the\n // client. The mapped-error wire shape itself is locked and does\n // NOT change here.\n getLogger(CATEGORY.http).error(\"unhandled_error\", { error: serializeError(err) });\n return { status: 500, envelope: errorEnvelope(\"Internal\", \"internal error\") };\n}\n\n// Hono-context shortcut used by every handler's catch block.\nfunction mapToResponse(c: Context, err: unknown): Response {\n const { status, envelope } = mapError(err);\n // `mapError` only returns 4xx/5xx — all of which are\n // `ContentfulStatusCode`. The cast bridges the locked `HttpStatus`\n // union (which also includes 204/304 for the wider contract) to\n // Hono's narrower body-bearing subset.\n return c.json(envelope, status as ContentfulStatusCode);\n}\n\n/**\n * Read and parse the JSON request body. Returns the parsed value\n * (an `unknown` — caller narrows). Throws `BaerlyError`:\n *\n * - `\"PayloadTooLarge\"` (→ 413) when the body exceeds `maxBytes`,\n * detected via `Content-Length` pre-check, post-`arrayBuffer`\n * length check, or — if the host adapter pumps the body through\n * a `ReadableStream` (the Node adapter does) — a `BaerlyError`\n * surfaced via `controller.error(...)` on the upstream pump.\n * - `\"SchemaError\"` (→ 400) for empty bodies, JSON parse failures,\n * and any other read failure.\n *\n * Hono's `app.onError` sink routes the throw through `mapToResponse`.\n */\nasync function readJsonBody(c: Context, maxBytes: number): Promise<unknown> {\n const lenHeader = c.req.header(\"content-length\");\n if (lenHeader !== undefined) {\n const parsed = Number.parseInt(lenHeader, 10);\n if (Number.isFinite(parsed) && parsed > maxBytes) {\n throw new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${maxBytes} bytes`);\n }\n }\n // Read with an early-exit guard for chunked transfers. If the\n // upstream adapter (e.g. `@baerly/adapter-node`) caps the body at\n // the stream-pump layer, the rejected `arrayBuffer()` carries a\n // `BaerlyError{code:\"PayloadTooLarge\"}` which we re-throw verbatim;\n // any other read failure becomes a 400 SchemaError.\n let raw: string;\n try {\n const buffer = await c.req.arrayBuffer();\n if (buffer.byteLength > maxBytes) {\n throw new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${maxBytes} bytes`);\n }\n raw = new TextDecoder().decode(buffer);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"SchemaError\",\n `Failed to read request body: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (raw.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n \"Empty request body\",\n undefined,\n undefined,\n undefined,\n WRITE_BODY_SHAPE_RESOLUTION,\n );\n }\n try {\n return JSON.parse(raw);\n } catch {\n throw new BaerlyError(\n \"SchemaError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CACF;CACA,IAAI,IAAI,WAAW,GACjB,MAAM,IAAI,YACR,eACA,sBACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,2BACF;CAEF,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,MAAM,IAAI,YACR,eACA,gCACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,2BACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"http-DGd5tbNs.js","names":["#matchResult","#validatedData","#getDecodedParam","#getAllDecodedParams","#getParamValue","#cachedBody","#rawRequest","#executionCtx","#notFoundHandler","#path","#matchResult","#req","#res","#preparedHeaders","#renderer","#layout","#status","#var","#newResponse","Hono","#path","#addRoute","#notFoundHandler","#clone","#dispatch","#handleError","#routes","HonoBase"],"sources":["../packages/protocol/src/log.ts","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/compose.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/request/constants.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/body.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/url.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/request.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/html.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/context.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/router.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/utils/constants.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/hono-base.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/router/pattern-router/router.js","../node_modules/.pnpm/hono@4.12.27/node_modules/hono/dist/preset/tiny.js","../packages/server/src/http/since.ts","../packages/server/src/http/router.ts"],"sourcesContent":["import { BaerlyError } from \"./errors.ts\";\nimport type { DocumentData, JSONValue } from \"./json.ts\";\nimport { COUNT_BIT_WIDTH } from \"./constants.ts\";\nimport { str2uintDesc } from \"./types.ts\";\n\n/**\n * Debezium-style JSON CDC envelope using pgoutput's message-tag (`I`/`U`/`D`) vocabulary. One per mutation.\n *\n * `LogEntry` is now a public, versionless/additive-only wire contract:\n * 0.3.0 is the public early-access baseline. It is still pre-1.0 and\n * soaking, so breaking changes remain possible, but only through an\n * explicit compatibility decision, changelog/migration notes, and a\n * versioned release. Assume external consumers may exist; do not\n * silently rename, remove, or repurpose fields. Consumers must ignore\n * unknown keys; new optional fields can be added in compatible releases.\n *\n * Field requirement matrix:\n * - Always: `lsn`, `commit_ts`, `op`, `collection`, `session`,\n * `seq`.\n * - For I/U/D: `doc_id`.\n * - For I/U: `after` (full post-image).\n * - Optional: `before` (when `replica_identity === \"FULL\"`), `key_old`\n * (U/D when `replica_identity !== \"PATCH_ONLY\"`), `origin`.\n *\n * @see docs/spec/log-entry-shape.md\n */\nexport interface LogEntry {\n /**\n * Opaque, monotonic, lex-asc cursor. Shape is\n * `<base32-time>_<session>_<seq>` — minted inside\n * `Writer.commit` (see\n * `packages/server/src/writer.ts`) from `timestamp()` +\n * the per-commit `session` + `countKey(seq)`. Consumers ack and\n * resume from this string.\n *\n * When you have a `LogEntry` in hand, prefer the structured\n * `session` / `seq` fields below over parsing this string. The\n * one place that *does* need to crack it open is the\n * `/v1/since` boundary, where a client resumes from an opaque\n * `next_cursor` and no `LogEntry` is in scope — that path uses\n * `lsnParts` (the kernel-blessed parser) rather than ad-hoc\n * `split(\"_\")`.\n */\n lsn: string;\n\n /** ISO-8601 ms timestamp. Redundant with `lsn` but cheap. */\n commit_ts: string;\n\n /** Insert / Update / Delete. */\n op: \"I\" | \"U\" | \"D\";\n\n /**\n * Collection name — the pgoutput RELATION analogue. Today this is\n * the collection bound to the `current.json` whose `tail_hint` minted\n * the entry. The table API makes collections first-class.\n */\n collection: string;\n\n /**\n * The document key (`ref.key`). Required for every op — `op` is\n * `I | U | D` and all three carry it — so the wire type is required,\n * not optional, matching `log-entry-shape.md`.\n */\n doc_id: string;\n\n /** Required for I, U. The post-image (Debezium's `after`). */\n after?: DocumentData;\n\n /**\n * The pre-image (Debezium's `before`). Present iff the\n * collection's `replica_identity` is `FULL`. ~2× log size on\n * update-heavy collections; off by default.\n */\n before?: DocumentData;\n\n /**\n * Pre-image of the primary key. U/D always carry this when\n * `replica_identity` is not `PATCH_ONLY`. (For baerly-storage today,\n * `_id` is the only PK.)\n */\n key_old?: { readonly [pk: string]: JSONValue };\n\n /** ORIGIN analogue — the writer session id. */\n origin?: string;\n\n /**\n * Causal metadata (baerly-storage-only; no pgoutput analogue). The\n * session id that built the `lsn`. Surfaces here so consumers\n * can dedupe / order without parsing the cursor.\n */\n session: string;\n\n /**\n * The `log/<seq>` slot this entry occupies — the integer in its\n * `log/<seq>.json` key, minted by `Writer.commit` as the forward-probed\n * collection-log tail (the winning `If-None-Match: \"*\"` create). One\n * entry per `session`, so this is a per-collection slot, not a\n * per-session counter. Also encoded (descending base-32) as the LSN's\n * third segment — see `lsnParts`.\n */\n seq: number;\n}\n\n/**\n * Per-collection setting controlling how much pre-image data each\n * `U` / `D` entry carries.\n *\n * - `PATCH_ONLY` (default today, applied unconditionally): `U`\n * carries `{ after }`; no `before`, no `key_old`.\n * Bandwidth-cheap. SQL consumers rebuilding before-images need\n * to maintain a shadow table.\n * - `FULL`: `U` additionally carries `before` and `key_old`. ~2× log\n * size on update-heavy collections; buys true 1:1 logical\n * replication and \"previous value\" answerable from the log\n * alone.\n *\n * Per-collection opt-in is not yet wired; every collection is\n * currently `PATCH_ONLY`.\n */\nexport type ReplicaIdentity = \"PATCH_ONLY\" | \"FULL\";\n\n// `LOG_KEY_PREFIX` + `logObjectKey` live in the zero-import `log-key.ts`\n// leaf so consumers that only need the key shape don't drag this module's\n// `lsn` parsing runtime into their bundle closure (it added +3.8 KB raw to\n// `maintenance.js` when the helper lived here).\n\n/**\n * Extract the `session` and `seq` embedded in an `lsn` of shape\n * `<base32-time>_<session>_<seq>`. The seq portion is decoded as a\n * descending base-32 integer (matches `countKey` in `./types`).\n *\n * Use this at the `/v1/since` cursor-decoding boundary, where a\n * client resumes from an opaque `SinceResponse.next_cursor` and no\n * `LogEntry` is in scope. When iterating `LogEntry` records, read\n * `entry.session` / `entry.seq` directly instead.\n *\n * Throws on malformed input; callers should pass only lsns minted\n * by `Writer.commit` (see\n * `packages/server/src/writer.ts`).\n */\nexport const lsnParts = (lsn: string): { session: string; seq: number } => {\n const parts = lsn.split(\"_\");\n if (parts.length !== 3) {\n throw new BaerlyError(\"InvalidResponse\", `invalid lsn shape: ${lsn}`);\n }\n return {\n session: parts[1]!,\n seq: str2uintDesc(parts[2]!, COUNT_BIT_WIDTH),\n };\n};\n","// src/compose.ts\nvar compose = (middleware, onError, onNotFound) => {\n return (context, next) => {\n let index = -1;\n return dispatch(0);\n async function dispatch(i) {\n if (i <= index) {\n throw new Error(\"next() called multiple times\");\n }\n index = i;\n let res;\n let isError = false;\n let handler;\n if (middleware[i]) {\n handler = middleware[i][0][0];\n context.req.routeIndex = i;\n } else {\n handler = i === middleware.length && next || void 0;\n }\n if (handler) {\n try {\n res = await handler(context, () => dispatch(i + 1));\n } catch (err) {\n if (err instanceof Error && onError) {\n context.error = err;\n res = await onError(err, context);\n isError = true;\n } else {\n throw err;\n }\n }\n } else {\n if (context.finalized === false && onNotFound) {\n res = await onNotFound(context);\n }\n }\n if (res && (context.finalized === false || isError)) {\n context.res = res;\n }\n return context;\n }\n };\n};\nexport {\n compose\n};\n","// src/request/constants.ts\nvar GET_MATCH_RESULT = /* @__PURE__ */ Symbol();\nexport {\n GET_MATCH_RESULT\n};\n","// src/utils/body.ts\nimport { HonoRequest } from \"../request.js\";\nvar parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {\n const { all = false, dot = false } = options;\n const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;\n const contentType = headers.get(\"Content-Type\");\n if (contentType?.startsWith(\"multipart/form-data\") || contentType?.startsWith(\"application/x-www-form-urlencoded\")) {\n return parseFormData(request, { all, dot });\n }\n return {};\n};\nasync function parseFormData(request, options) {\n const formData = await request.formData();\n if (formData) {\n return convertFormDataToBodyData(formData, options);\n }\n return {};\n}\nfunction convertFormDataToBodyData(formData, options) {\n const form = /* @__PURE__ */ Object.create(null);\n formData.forEach((value, key) => {\n const shouldParseAllValues = options.all || key.endsWith(\"[]\");\n if (!shouldParseAllValues) {\n form[key] = value;\n } else {\n handleParsingAllValues(form, key, value);\n }\n });\n if (options.dot) {\n Object.entries(form).forEach(([key, value]) => {\n const shouldParseDotValues = key.includes(\".\");\n if (shouldParseDotValues) {\n handleParsingNestedValues(form, key, value);\n delete form[key];\n }\n });\n }\n return form;\n}\nvar handleParsingAllValues = (form, key, value) => {\n if (form[key] !== void 0) {\n if (Array.isArray(form[key])) {\n ;\n form[key].push(value);\n } else {\n form[key] = [form[key], value];\n }\n } else {\n if (!key.endsWith(\"[]\")) {\n form[key] = value;\n } else {\n form[key] = [value];\n }\n }\n};\nvar handleParsingNestedValues = (form, key, value) => {\n if (/(?:^|\\.)__proto__\\./.test(key)) {\n return;\n }\n let nestedForm = form;\n const keys = key.split(\".\");\n keys.forEach((key2, index) => {\n if (index === keys.length - 1) {\n nestedForm[key2] = value;\n } else {\n if (!nestedForm[key2] || typeof nestedForm[key2] !== \"object\" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {\n nestedForm[key2] = /* @__PURE__ */ Object.create(null);\n }\n nestedForm = nestedForm[key2];\n }\n });\n};\nexport {\n parseBody\n};\n","// src/utils/url.ts\nvar splitPath = (path) => {\n const paths = path.split(\"/\");\n if (paths[0] === \"\") {\n paths.shift();\n }\n return paths;\n};\nvar splitRoutingPath = (routePath) => {\n const { groups, path } = extractGroupsFromPath(routePath);\n const paths = splitPath(path);\n return replaceGroupMarks(paths, groups);\n};\nvar extractGroupsFromPath = (path) => {\n const groups = [];\n path = path.replace(/\\{[^}]+\\}/g, (match, index) => {\n const mark = `@${index}`;\n groups.push([mark, match]);\n return mark;\n });\n return { groups, path };\n};\nvar replaceGroupMarks = (paths, groups) => {\n for (let i = groups.length - 1; i >= 0; i--) {\n const [mark] = groups[i];\n for (let j = paths.length - 1; j >= 0; j--) {\n if (paths[j].includes(mark)) {\n paths[j] = paths[j].replace(mark, groups[i][1]);\n break;\n }\n }\n }\n return paths;\n};\nvar patternCache = {};\nvar getPattern = (label, next) => {\n if (label === \"*\") {\n return \"*\";\n }\n const match = label.match(/^\\:([^\\{\\}]+)(?:\\{(.+)\\})?$/);\n if (match) {\n const cacheKey = `${label}#${next}`;\n if (!patternCache[cacheKey]) {\n if (match[2]) {\n patternCache[cacheKey] = next && next[0] !== \":\" && next[0] !== \"*\" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];\n } else {\n patternCache[cacheKey] = [label, match[1], true];\n }\n }\n return patternCache[cacheKey];\n }\n return null;\n};\nvar tryDecode = (str, decoder) => {\n try {\n return decoder(str);\n } catch {\n return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {\n try {\n return decoder(match);\n } catch {\n return match;\n }\n });\n }\n};\nvar tryDecodeURI = (str) => tryDecode(str, decodeURI);\nvar getPath = (request) => {\n const url = request.url;\n const start = url.indexOf(\"/\", url.indexOf(\":\") + 4);\n let i = start;\n for (; i < url.length; i++) {\n const charCode = url.charCodeAt(i);\n if (charCode === 37) {\n const queryIndex = url.indexOf(\"?\", i);\n const hashIndex = url.indexOf(\"#\", i);\n const end = queryIndex === -1 ? hashIndex === -1 ? void 0 : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);\n const path = url.slice(start, end);\n return tryDecodeURI(path.includes(\"%25\") ? path.replace(/%25/g, \"%2525\") : path);\n } else if (charCode === 63 || charCode === 35) {\n break;\n }\n }\n return url.slice(start, i);\n};\nvar getQueryStrings = (url) => {\n const queryIndex = url.indexOf(\"?\", 8);\n return queryIndex === -1 ? \"\" : \"?\" + url.slice(queryIndex + 1);\n};\nvar getPathNoStrict = (request) => {\n const result = getPath(request);\n return result.length > 1 && result.at(-1) === \"/\" ? result.slice(0, -1) : result;\n};\nvar mergePath = (base, sub, ...rest) => {\n if (rest.length) {\n sub = mergePath(sub, ...rest);\n }\n return `${base?.[0] === \"/\" ? \"\" : \"/\"}${base}${sub === \"/\" ? \"\" : `${base?.at(-1) === \"/\" ? \"\" : \"/\"}${sub?.[0] === \"/\" ? sub.slice(1) : sub}`}`;\n};\nvar checkOptionalParameter = (path) => {\n if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(\":\")) {\n return null;\n }\n const segments = path.split(\"/\");\n const results = [];\n let basePath = \"\";\n segments.forEach((segment) => {\n if (segment !== \"\" && !/\\:/.test(segment)) {\n basePath += \"/\" + segment;\n } else if (/\\:/.test(segment)) {\n if (/\\?/.test(segment)) {\n if (results.length === 0 && basePath === \"\") {\n results.push(\"/\");\n } else {\n results.push(basePath);\n }\n const optionalSegment = segment.replace(\"?\", \"\");\n basePath += \"/\" + optionalSegment;\n results.push(basePath);\n } else {\n basePath += \"/\" + segment;\n }\n }\n });\n return results.filter((v, i, a) => a.indexOf(v) === i);\n};\nvar _decodeURI = (value) => {\n if (!/[%+]/.test(value)) {\n return value;\n }\n if (value.indexOf(\"+\") !== -1) {\n value = value.replace(/\\+/g, \" \");\n }\n return value.indexOf(\"%\") !== -1 ? tryDecode(value, decodeURIComponent_) : value;\n};\nvar _getQueryParam = (url, key, multiple) => {\n let encoded;\n if (!multiple && key && !/[%+]/.test(key)) {\n let keyIndex2 = url.indexOf(\"?\", 8);\n if (keyIndex2 === -1) {\n return void 0;\n }\n if (!url.startsWith(key, keyIndex2 + 1)) {\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n while (keyIndex2 !== -1) {\n const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);\n if (trailingKeyCode === 61) {\n const valueIndex = keyIndex2 + key.length + 2;\n const endIndex = url.indexOf(\"&\", valueIndex);\n return _decodeURI(url.slice(valueIndex, endIndex === -1 ? void 0 : endIndex));\n } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {\n return \"\";\n }\n keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);\n }\n encoded = /[%+]/.test(url);\n if (!encoded) {\n return void 0;\n }\n }\n const results = {};\n encoded ??= /[%+]/.test(url);\n let keyIndex = url.indexOf(\"?\", 8);\n while (keyIndex !== -1) {\n const nextKeyIndex = url.indexOf(\"&\", keyIndex + 1);\n let valueIndex = url.indexOf(\"=\", keyIndex);\n if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {\n valueIndex = -1;\n }\n let name = url.slice(\n keyIndex + 1,\n valueIndex === -1 ? nextKeyIndex === -1 ? void 0 : nextKeyIndex : valueIndex\n );\n if (encoded) {\n name = _decodeURI(name);\n }\n keyIndex = nextKeyIndex;\n if (name === \"\") {\n continue;\n }\n let value;\n if (valueIndex === -1) {\n value = \"\";\n } else {\n value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? void 0 : nextKeyIndex);\n if (encoded) {\n value = _decodeURI(value);\n }\n }\n if (multiple) {\n if (!(results[name] && Array.isArray(results[name]))) {\n results[name] = [];\n }\n ;\n results[name].push(value);\n } else {\n results[name] ??= value;\n }\n }\n return key ? results[key] : results;\n};\nvar getQueryParam = _getQueryParam;\nvar getQueryParams = (url, key) => {\n return _getQueryParam(url, key, true);\n};\nvar decodeURIComponent_ = decodeURIComponent;\nexport {\n checkOptionalParameter,\n decodeURIComponent_,\n getPath,\n getPathNoStrict,\n getPattern,\n getQueryParam,\n getQueryParams,\n getQueryStrings,\n mergePath,\n splitPath,\n splitRoutingPath,\n tryDecode,\n tryDecodeURI\n};\n","// src/request.ts\nimport { HTTPException } from \"./http-exception.js\";\nimport { GET_MATCH_RESULT } from \"./request/constants.js\";\nimport { parseBody } from \"./utils/body.js\";\nimport { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from \"./utils/url.js\";\nvar tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);\nvar HonoRequest = class {\n /**\n * `.raw` can get the raw Request object.\n *\n * @see {@link https://hono.dev/docs/api/request#raw}\n *\n * @example\n * ```ts\n * // For Cloudflare Workers\n * app.post('/', async (c) => {\n * const metadata = c.req.raw.cf?.hostMetadata?\n * ...\n * })\n * ```\n */\n raw;\n #validatedData;\n // Short name of validatedData\n #matchResult;\n routeIndex = 0;\n /**\n * `.path` can get the pathname of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#path}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const pathname = c.req.path // `/about/me`\n * })\n * ```\n */\n path;\n bodyCache = {};\n constructor(request, path = \"/\", matchResult = [[]]) {\n this.raw = request;\n this.path = path;\n this.#matchResult = matchResult;\n this.#validatedData = {};\n }\n param(key) {\n return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();\n }\n #getDecodedParam(key) {\n const paramKey = this.#matchResult[0][this.routeIndex][1][key];\n const param = this.#getParamValue(paramKey);\n return param && /\\%/.test(param) ? tryDecodeURIComponent(param) : param;\n }\n #getAllDecodedParams() {\n const decoded = {};\n const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);\n for (const key of keys) {\n const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);\n if (value !== void 0) {\n decoded[key] = /\\%/.test(value) ? tryDecodeURIComponent(value) : value;\n }\n }\n return decoded;\n }\n #getParamValue(paramKey) {\n return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;\n }\n query(key) {\n return getQueryParam(this.url, key);\n }\n queries(key) {\n return getQueryParams(this.url, key);\n }\n header(name) {\n if (name) {\n return this.raw.headers.get(name) ?? void 0;\n }\n const headerData = {};\n this.raw.headers.forEach((value, key) => {\n headerData[key] = value;\n });\n return headerData;\n }\n async parseBody(options) {\n return parseBody(this, options);\n }\n #cachedBody = (key) => {\n const { bodyCache, raw } = this;\n const cachedBody = bodyCache[key];\n if (cachedBody) {\n return cachedBody;\n }\n const anyCachedKey = Object.keys(bodyCache)[0];\n if (anyCachedKey) {\n return bodyCache[anyCachedKey].then((body) => {\n if (anyCachedKey === \"json\") {\n body = JSON.stringify(body);\n }\n return new Response(body)[key]();\n });\n }\n return bodyCache[key] = raw[key]();\n };\n /**\n * `.json()` can parse Request body of type `application/json`\n *\n * @see {@link https://hono.dev/docs/api/request#json}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.json()\n * })\n * ```\n */\n json() {\n return this.#cachedBody(\"text\").then((text) => JSON.parse(text));\n }\n /**\n * `.text()` can parse Request body of type `text/plain`\n *\n * @see {@link https://hono.dev/docs/api/request#text}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.text()\n * })\n * ```\n */\n text() {\n return this.#cachedBody(\"text\");\n }\n /**\n * `.arrayBuffer()` parse Request body as an `ArrayBuffer`\n *\n * @see {@link https://hono.dev/docs/api/request#arraybuffer}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.arrayBuffer()\n * })\n * ```\n */\n arrayBuffer() {\n return this.#cachedBody(\"arrayBuffer\");\n }\n /**\n * `.bytes()` parses the request body as a `Uint8Array`.\n *\n * @see {@link https://hono.dev/docs/api/request#bytes}\n *\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.bytes()\n * })\n * ```\n */\n bytes() {\n return this.#cachedBody(\"arrayBuffer\").then((buffer) => new Uint8Array(buffer));\n }\n /**\n * Parses the request body as a `Blob`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.blob();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#blob\n */\n blob() {\n return this.#cachedBody(\"blob\");\n }\n /**\n * Parses the request body as `FormData`.\n * @example\n * ```ts\n * app.post('/entry', async (c) => {\n * const body = await c.req.formData();\n * });\n * ```\n * @see https://hono.dev/docs/api/request#formdata\n */\n formData() {\n return this.#cachedBody(\"formData\");\n }\n /**\n * Adds validated data to the request.\n *\n * @param target - The target of the validation.\n * @param data - The validated data to add.\n */\n addValidatedData(target, data) {\n this.#validatedData[target] = data;\n }\n valid(target) {\n return this.#validatedData[target];\n }\n /**\n * `.url()` can get the request url strings.\n *\n * @see {@link https://hono.dev/docs/api/request#url}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const url = c.req.url // `http://localhost:8787/about/me`\n * ...\n * })\n * ```\n */\n get url() {\n return this.raw.url;\n }\n /**\n * `.method()` can get the method name of the request.\n *\n * @see {@link https://hono.dev/docs/api/request#method}\n *\n * @example\n * ```ts\n * app.get('/about/me', (c) => {\n * const method = c.req.method // `GET`\n * })\n * ```\n */\n get method() {\n return this.raw.method;\n }\n get [GET_MATCH_RESULT]() {\n return this.#matchResult;\n }\n /**\n * `.matchedRoutes()` can return a matched route in the handler\n *\n * @deprecated\n *\n * Use matchedRoutes helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#matchedroutes}\n *\n * @example\n * ```ts\n * app.use('*', async function logger(c, next) {\n * await next()\n * c.req.matchedRoutes.forEach(({ handler, method, path }, i) => {\n * const name = handler.name || (handler.length < 2 ? '[handler]' : '[middleware]')\n * console.log(\n * method,\n * ' ',\n * path,\n * ' '.repeat(Math.max(10 - path.length, 0)),\n * name,\n * i === c.req.routeIndex ? '<- respond from here' : ''\n * )\n * })\n * })\n * ```\n */\n get matchedRoutes() {\n return this.#matchResult[0].map(([[, route]]) => route);\n }\n /**\n * `routePath()` can retrieve the path registered within the handler\n *\n * @deprecated\n *\n * Use routePath helper defined in \"hono/route\" instead.\n *\n * @see {@link https://hono.dev/docs/api/request#routepath}\n *\n * @example\n * ```ts\n * app.get('/posts/:id', (c) => {\n * return c.json({ path: c.req.routePath })\n * })\n * ```\n */\n get routePath() {\n return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;\n }\n};\nvar cloneRawRequest = async (req) => {\n if (!req.raw.bodyUsed) {\n return req.raw.clone();\n }\n const cacheKey = Object.keys(req.bodyCache)[0];\n if (!cacheKey) {\n throw new HTTPException(500, {\n message: \"Cannot clone request: body was already consumed and not cached. Please use HonoRequest methods (e.g., req.json(), req.text()) instead of consuming req.raw directly.\"\n });\n }\n const requestInit = {\n body: await req[cacheKey](),\n cache: req.raw.cache,\n credentials: req.raw.credentials,\n headers: req.header(),\n integrity: req.raw.integrity,\n keepalive: req.raw.keepalive,\n method: req.method,\n mode: req.raw.mode,\n redirect: req.raw.redirect,\n referrer: req.raw.referrer,\n referrerPolicy: req.raw.referrerPolicy,\n signal: req.raw.signal\n };\n return new Request(req.url, requestInit);\n};\nexport {\n HonoRequest,\n cloneRawRequest\n};\n","// src/utils/html.ts\nvar HtmlEscapedCallbackPhase = {\n Stringify: 1,\n BeforeStream: 2,\n Stream: 3\n};\nvar raw = (value, callbacks) => {\n const escapedString = new String(value);\n escapedString.isEscaped = true;\n escapedString.callbacks = callbacks;\n return escapedString;\n};\nvar escapeRe = /[&<>'\"]/;\nvar stringBufferToString = async (buffer, callbacks) => {\n let str = \"\";\n callbacks ||= [];\n const resolvedBuffer = await Promise.all(buffer);\n for (let i = resolvedBuffer.length - 1; ; i--) {\n str += resolvedBuffer[i];\n i--;\n if (i < 0) {\n break;\n }\n let r = resolvedBuffer[i];\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n const isEscaped = r.isEscaped;\n r = await (typeof r === \"object\" ? r.toString() : r);\n if (typeof r === \"object\") {\n callbacks.push(...r.callbacks || []);\n }\n if (r.isEscaped ?? isEscaped) {\n str += r;\n } else {\n const buf = [str];\n escapeToBuffer(r, buf);\n str = buf[0];\n }\n }\n return raw(str, callbacks);\n};\nvar escapeToBuffer = (str, buffer) => {\n const match = str.search(escapeRe);\n if (match === -1) {\n buffer[0] += str;\n return;\n }\n let escape;\n let index;\n let lastIndex = 0;\n for (index = match; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34:\n escape = \""\";\n break;\n case 39:\n escape = \"'\";\n break;\n case 38:\n escape = \"&\";\n break;\n case 60:\n escape = \"<\";\n break;\n case 62:\n escape = \">\";\n break;\n default:\n continue;\n }\n buffer[0] += str.substring(lastIndex, index) + escape;\n lastIndex = index + 1;\n }\n buffer[0] += str.substring(lastIndex, index);\n};\nvar resolveCallbackSync = (str) => {\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return str;\n }\n const buffer = [str];\n const context = {};\n callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));\n return buffer[0];\n};\nvar resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {\n if (typeof str === \"object\" && !(str instanceof String)) {\n if (!(str instanceof Promise)) {\n str = str.toString();\n }\n if (str instanceof Promise) {\n str = await str;\n }\n }\n const callbacks = str.callbacks;\n if (!callbacks?.length) {\n return Promise.resolve(str);\n }\n if (buffer) {\n buffer[0] += str;\n } else {\n buffer = [str];\n }\n const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then(\n (res) => Promise.all(\n res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))\n ).then(() => buffer[0])\n );\n if (preserveCallbacks) {\n return raw(await resStr, callbacks);\n } else {\n return resStr;\n }\n};\nexport {\n HtmlEscapedCallbackPhase,\n escapeToBuffer,\n raw,\n resolveCallback,\n resolveCallbackSync,\n stringBufferToString\n};\n","// src/context.ts\nimport { HonoRequest } from \"./request.js\";\nimport { HtmlEscapedCallbackPhase, resolveCallback } from \"./utils/html.js\";\nvar TEXT_PLAIN = \"text/plain; charset=UTF-8\";\nvar setDefaultContentType = (contentType, headers) => {\n return {\n \"Content-Type\": contentType,\n ...headers\n };\n};\nvar createResponseInstance = (body, init) => new Response(body, init);\nvar Context = class {\n #rawRequest;\n #req;\n /**\n * `.env` can get bindings (environment variables, secrets, KV namespaces, D1 database, R2 bucket etc.) in Cloudflare Workers.\n *\n * @see {@link https://hono.dev/docs/api/context#env}\n *\n * @example\n * ```ts\n * // Environment object for Cloudflare Workers\n * app.get('*', async c => {\n * const counter = c.env.COUNTER\n * })\n * ```\n */\n env = {};\n #var;\n finalized = false;\n /**\n * `.error` can get the error object from the middleware if the Handler throws an error.\n *\n * @see {@link https://hono.dev/docs/api/context#error}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * await next()\n * if (c.error) {\n * // do something...\n * }\n * })\n * ```\n */\n error;\n #status;\n #executionCtx;\n #res;\n #layout;\n #renderer;\n #notFoundHandler;\n #preparedHeaders;\n #matchResult;\n #path;\n /**\n * Creates an instance of the Context class.\n *\n * @param req - The Request object.\n * @param options - Optional configuration options for the context.\n */\n constructor(req, options) {\n this.#rawRequest = req;\n if (options) {\n this.#executionCtx = options.executionCtx;\n this.env = options.env;\n this.#notFoundHandler = options.notFoundHandler;\n this.#path = options.path;\n this.#matchResult = options.matchResult;\n }\n }\n /**\n * `.req` is the instance of {@link HonoRequest}.\n */\n get req() {\n this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);\n return this.#req;\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#event}\n * The FetchEvent associated with the current request.\n *\n * @throws Will throw an error if the context does not have a FetchEvent.\n */\n get event() {\n if (this.#executionCtx && \"respondWith\" in this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no FetchEvent\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#executionctx}\n * The ExecutionContext associated with the current request.\n *\n * @throws Will throw an error if the context does not have an ExecutionContext.\n */\n get executionCtx() {\n if (this.#executionCtx) {\n return this.#executionCtx;\n } else {\n throw Error(\"This context has no ExecutionContext\");\n }\n }\n /**\n * @see {@link https://hono.dev/docs/api/context#res}\n * The Response object for the current request.\n */\n get res() {\n return this.#res ||= createResponseInstance(null, {\n headers: this.#preparedHeaders ??= new Headers()\n });\n }\n /**\n * Sets the Response object for the current request.\n *\n * @param _res - The Response object to set.\n */\n set res(_res) {\n if (this.#res && _res) {\n _res = createResponseInstance(_res.body, _res);\n for (const [k, v] of this.#res.headers.entries()) {\n if (k === \"content-type\") {\n continue;\n }\n if (k === \"set-cookie\") {\n const cookies = this.#res.headers.getSetCookie();\n _res.headers.delete(\"set-cookie\");\n for (const cookie of cookies) {\n _res.headers.append(\"set-cookie\", cookie);\n }\n } else {\n _res.headers.set(k, v);\n }\n }\n }\n this.#res = _res;\n this.finalized = true;\n }\n /**\n * `.render()` can create a response within a layout.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * return c.render('Hello!')\n * })\n * ```\n */\n render = (...args) => {\n this.#renderer ??= (content) => this.html(content);\n return this.#renderer(...args);\n };\n /**\n * Sets the layout for the response.\n *\n * @param layout - The layout to set.\n * @returns The layout function.\n */\n setLayout = (layout) => this.#layout = layout;\n /**\n * Gets the current layout for the response.\n *\n * @returns The current layout function.\n */\n getLayout = () => this.#layout;\n /**\n * `.setRenderer()` can set the layout in the custom middleware.\n *\n * @see {@link https://hono.dev/docs/api/context#render-setrenderer}\n *\n * @example\n * ```tsx\n * app.use('*', async (c, next) => {\n * c.setRenderer((content) => {\n * return c.html(\n * <html>\n * <body>\n * <p>{content}</p>\n * </body>\n * </html>\n * )\n * })\n * await next()\n * })\n * ```\n */\n setRenderer = (renderer) => {\n this.#renderer = renderer;\n };\n /**\n * `.header()` can set headers.\n *\n * @see {@link https://hono.dev/docs/api/context#header}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n *\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n header = (name, value, options) => {\n if (this.finalized) {\n this.#res = createResponseInstance(this.#res.body, this.#res);\n }\n const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers();\n if (value === void 0) {\n headers.delete(name);\n } else if (options?.append) {\n headers.append(name, value);\n } else {\n headers.set(name, value);\n }\n };\n status = (status) => {\n this.#status = status;\n };\n /**\n * `.set()` can set the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.use('*', async (c, next) => {\n * c.set('message', 'Hono is hot!!')\n * await next()\n * })\n * ```\n */\n set = (key, value) => {\n this.#var ??= /* @__PURE__ */ new Map();\n this.#var.set(key, value);\n };\n /**\n * `.get()` can use the value specified by the key.\n *\n * @see {@link https://hono.dev/docs/api/context#set-get}\n *\n * @example\n * ```ts\n * app.get('/', (c) => {\n * const message = c.get('message')\n * return c.text(`The message is \"${message}\"`)\n * })\n * ```\n */\n get = (key) => {\n return this.#var ? this.#var.get(key) : void 0;\n };\n /**\n * `.var` can access the value of a variable.\n *\n * @see {@link https://hono.dev/docs/api/context#var}\n *\n * @example\n * ```ts\n * const result = c.var.client.oneMethod()\n * ```\n */\n // c.var.propName is a read-only\n get var() {\n if (!this.#var) {\n return {};\n }\n return Object.fromEntries(this.#var);\n }\n #newResponse(data, arg, headers) {\n const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers();\n if (typeof arg === \"object\" && \"headers\" in arg) {\n const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);\n for (const [key, value] of argHeaders) {\n if (key.toLowerCase() === \"set-cookie\") {\n responseHeaders.append(key, value);\n } else {\n responseHeaders.set(key, value);\n }\n }\n }\n if (headers) {\n for (const [k, v] of Object.entries(headers)) {\n if (typeof v === \"string\") {\n responseHeaders.set(k, v);\n } else {\n responseHeaders.delete(k);\n for (const v2 of v) {\n responseHeaders.append(k, v2);\n }\n }\n }\n }\n const status = typeof arg === \"number\" ? arg : arg?.status ?? this.#status;\n return createResponseInstance(data, { status, headers: responseHeaders });\n }\n newResponse = (...args) => this.#newResponse(...args);\n /**\n * `.body()` can return the HTTP response.\n * You can set headers with `.header()` and set HTTP status code with `.status`.\n * This can also be set in `.text()`, `.json()` and so on.\n *\n * @see {@link https://hono.dev/docs/api/context#body}\n *\n * @example\n * ```ts\n * app.get('/welcome', (c) => {\n * // Set headers\n * c.header('X-Message', 'Hello!')\n * c.header('Content-Type', 'text/plain')\n * // Set HTTP status code\n * c.status(201)\n *\n * // Return the response body\n * return c.body('Thank you for coming')\n * })\n * ```\n */\n body = (data, arg, headers) => this.#newResponse(data, arg, headers);\n /**\n * `.text()` can render text as `Content-Type:text/plain`.\n *\n * @see {@link https://hono.dev/docs/api/context#text}\n *\n * @example\n * ```ts\n * app.get('/say', (c) => {\n * return c.text('Hello!')\n * })\n * ```\n */\n text = (text, arg, headers) => {\n return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(\n text,\n arg,\n setDefaultContentType(TEXT_PLAIN, headers)\n );\n };\n /**\n * `.json()` can render JSON as `Content-Type:application/json`.\n *\n * @see {@link https://hono.dev/docs/api/context#json}\n *\n * @example\n * ```ts\n * app.get('/api', (c) => {\n * return c.json({ message: 'Hello!' })\n * })\n * ```\n */\n json = (object, arg, headers) => {\n return this.#newResponse(\n JSON.stringify(object),\n arg,\n setDefaultContentType(\"application/json\", headers)\n );\n };\n html = (html, arg, headers) => {\n const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType(\"text/html; charset=UTF-8\", headers));\n return typeof html === \"object\" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);\n };\n /**\n * `.redirect()` can Redirect, default status code is 302.\n *\n * @see {@link https://hono.dev/docs/api/context#redirect}\n *\n * @example\n * ```ts\n * app.get('/redirect', (c) => {\n * return c.redirect('/')\n * })\n * app.get('/redirect-permanently', (c) => {\n * return c.redirect('/', 301)\n * })\n * ```\n */\n redirect = (location, status) => {\n const locationString = String(location);\n this.header(\n \"Location\",\n // Multibyes should be encoded\n // eslint-disable-next-line no-control-regex\n !/[^\\x00-\\xFF]/.test(locationString) ? locationString : encodeURI(locationString)\n );\n return this.newResponse(null, status ?? 302);\n };\n /**\n * `.notFound()` can return the Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/context#notfound}\n *\n * @example\n * ```ts\n * app.get('/notfound', (c) => {\n * return c.notFound()\n * })\n * ```\n */\n notFound = () => {\n this.#notFoundHandler ??= () => createResponseInstance();\n return this.#notFoundHandler(this);\n };\n};\nexport {\n Context,\n TEXT_PLAIN\n};\n","// src/router.ts\nvar METHOD_NAME_ALL = \"ALL\";\nvar METHOD_NAME_ALL_LOWERCASE = \"all\";\nvar METHODS = [\"get\", \"post\", \"put\", \"delete\", \"options\", \"patch\"];\nvar MESSAGE_MATCHER_IS_ALREADY_BUILT = \"Can not add a route since the matcher is already built.\";\nvar UnsupportedPathError = class extends Error {\n};\nexport {\n MESSAGE_MATCHER_IS_ALREADY_BUILT,\n METHODS,\n METHOD_NAME_ALL,\n METHOD_NAME_ALL_LOWERCASE,\n UnsupportedPathError\n};\n","// src/utils/constants.ts\nvar COMPOSED_HANDLER = \"__COMPOSED_HANDLER\";\nexport {\n COMPOSED_HANDLER\n};\n","// src/hono-base.ts\nimport { compose } from \"./compose.js\";\nimport { Context } from \"./context.js\";\nimport { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from \"./router.js\";\nimport { COMPOSED_HANDLER } from \"./utils/constants.js\";\nimport { getPath, getPathNoStrict, mergePath } from \"./utils/url.js\";\nvar notFoundHandler = (c) => {\n return c.text(\"404 Not Found\", 404);\n};\nvar errorHandler = (err, c) => {\n if (\"getResponse\" in err) {\n const res = err.getResponse();\n return c.newResponse(res.body, res);\n }\n console.error(err);\n return c.text(\"Internal Server Error\", 500);\n};\nvar Hono = class _Hono {\n get;\n post;\n put;\n delete;\n options;\n patch;\n all;\n on;\n use;\n /*\n This class is like an abstract class and does not have a router.\n To use it, inherit the class and implement router in the constructor.\n */\n router;\n getPath;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n _basePath = \"/\";\n #path = \"/\";\n routes = [];\n constructor(options = {}) {\n const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];\n allMethods.forEach((method) => {\n this[method] = (args1, ...args) => {\n if (typeof args1 === \"string\") {\n this.#path = args1;\n } else {\n this.#addRoute(method, this.#path, args1);\n }\n args.forEach((handler) => {\n this.#addRoute(method, this.#path, handler);\n });\n return this;\n };\n });\n this.on = (method, path, ...handlers) => {\n for (const p of [path].flat()) {\n this.#path = p;\n for (const m of [method].flat()) {\n handlers.map((handler) => {\n this.#addRoute(m.toUpperCase(), this.#path, handler);\n });\n }\n }\n return this;\n };\n this.use = (arg1, ...handlers) => {\n if (typeof arg1 === \"string\") {\n this.#path = arg1;\n } else {\n this.#path = \"*\";\n handlers.unshift(arg1);\n }\n handlers.forEach((handler) => {\n this.#addRoute(METHOD_NAME_ALL, this.#path, handler);\n });\n return this;\n };\n const { strict, ...optionsWithoutStrict } = options;\n Object.assign(this, optionsWithoutStrict);\n this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;\n }\n #clone() {\n const clone = new _Hono({\n router: this.router,\n getPath: this.getPath\n });\n clone.errorHandler = this.errorHandler;\n clone.#notFoundHandler = this.#notFoundHandler;\n clone.routes = this.routes;\n return clone;\n }\n #notFoundHandler = notFoundHandler;\n // Cannot use `#` because it requires visibility at JavaScript runtime.\n errorHandler = errorHandler;\n /**\n * `.route()` allows grouping other Hono instance in routes.\n *\n * @see {@link https://hono.dev/docs/api/routing#grouping}\n *\n * @param {string} path - base Path\n * @param {Hono} app - other Hono instance\n * @returns {Hono} routed Hono instance\n *\n * @example\n * ```ts\n * const app = new Hono()\n * const app2 = new Hono()\n *\n * app2.get(\"/user\", (c) => c.text(\"user\"))\n * app.route(\"/api\", app2) // GET /api/user\n * ```\n */\n route(path, app) {\n const subApp = this.basePath(path);\n app.routes.map((r) => {\n let handler;\n if (app.errorHandler === errorHandler) {\n handler = r.handler;\n } else {\n handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;\n handler[COMPOSED_HANDLER] = r.handler;\n }\n subApp.#addRoute(r.method, r.path, handler, r.basePath);\n });\n return this;\n }\n /**\n * `.basePath()` allows base paths to be specified.\n *\n * @see {@link https://hono.dev/docs/api/routing#base-path}\n *\n * @param {string} path - base Path\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * const api = new Hono().basePath('/api')\n * ```\n */\n basePath(path) {\n const subApp = this.#clone();\n subApp._basePath = mergePath(this._basePath, path);\n return subApp;\n }\n /**\n * `.onError()` handles an error and returns a customized Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#error-handling}\n *\n * @param {ErrorHandler} handler - request Handler for error\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.onError((err, c) => {\n * console.error(`${err}`)\n * return c.text('Custom Error Message', 500)\n * })\n * ```\n */\n onError = (handler) => {\n this.errorHandler = handler;\n return this;\n };\n /**\n * `.notFound()` allows you to customize a Not Found Response.\n *\n * @see {@link https://hono.dev/docs/api/hono#not-found}\n *\n * @param {NotFoundHandler} handler - request handler for not-found\n * @returns {Hono} changed Hono instance\n *\n * @example\n * ```ts\n * app.notFound((c) => {\n * return c.text('Custom 404 Message', 404)\n * })\n * ```\n */\n notFound = (handler) => {\n this.#notFoundHandler = handler;\n return this;\n };\n /**\n * `.mount()` allows you to mount applications built with other frameworks into your Hono application.\n *\n * @see {@link https://hono.dev/docs/api/hono#mount}\n *\n * @param {string} path - base Path\n * @param {Function} applicationHandler - other Request Handler\n * @param {MountOptions} [options] - options of `.mount()`\n * @returns {Hono} mounted Hono instance\n *\n * @example\n * ```ts\n * import { Router as IttyRouter } from 'itty-router'\n * import { Hono } from 'hono'\n * // Create itty-router application\n * const ittyRouter = IttyRouter()\n * // GET /itty-router/hello\n * ittyRouter.get('/hello', () => new Response('Hello from itty-router'))\n *\n * const app = new Hono()\n * app.mount('/itty-router', ittyRouter.handle)\n * ```\n *\n * @example\n * ```ts\n * const app = new Hono()\n * // Send the request to another application without modification.\n * app.mount('/app', anotherApp, {\n * replaceRequest: (req) => req,\n * })\n * ```\n */\n mount(path, applicationHandler, options) {\n let replaceRequest;\n let optionHandler;\n if (options) {\n if (typeof options === \"function\") {\n optionHandler = options;\n } else {\n optionHandler = options.optionHandler;\n if (options.replaceRequest === false) {\n replaceRequest = (request) => request;\n } else {\n replaceRequest = options.replaceRequest;\n }\n }\n }\n const getOptions = optionHandler ? (c) => {\n const options2 = optionHandler(c);\n return Array.isArray(options2) ? options2 : [options2];\n } : (c) => {\n let executionContext = void 0;\n try {\n executionContext = c.executionCtx;\n } catch {\n }\n return [c.env, executionContext];\n };\n replaceRequest ||= (() => {\n const mergedPath = mergePath(this._basePath, path);\n const pathPrefixLength = mergedPath === \"/\" ? 0 : mergedPath.length;\n return (request) => {\n const url = new URL(request.url);\n url.pathname = this.getPath(request).slice(pathPrefixLength) || \"/\";\n return new Request(url, request);\n };\n })();\n const handler = async (c, next) => {\n const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));\n if (res) {\n return res;\n }\n await next();\n };\n this.#addRoute(METHOD_NAME_ALL, mergePath(path, \"*\"), handler);\n return this;\n }\n #addRoute(method, path, handler, baseRoutePath) {\n method = method.toUpperCase();\n path = mergePath(this._basePath, path);\n const r = {\n basePath: baseRoutePath !== void 0 ? mergePath(this._basePath, baseRoutePath) : this._basePath,\n path,\n method,\n handler\n };\n this.router.add(method, path, [handler, r]);\n this.routes.push(r);\n }\n #handleError(err, c) {\n if (err instanceof Error) {\n return this.errorHandler(err, c);\n }\n throw err;\n }\n #dispatch(request, executionCtx, env, method) {\n if (method === \"HEAD\") {\n return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, \"GET\")))();\n }\n const path = this.getPath(request, { env });\n const matchResult = this.router.match(method, path);\n const c = new Context(request, {\n path,\n matchResult,\n env,\n executionCtx,\n notFoundHandler: this.#notFoundHandler\n });\n if (matchResult[0].length === 1) {\n let res;\n try {\n res = matchResult[0][0][0][0](c, async () => {\n c.res = await this.#notFoundHandler(c);\n });\n } catch (err) {\n return this.#handleError(err, c);\n }\n return res instanceof Promise ? res.then(\n (resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))\n ).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);\n }\n const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);\n return (async () => {\n try {\n const context = await composed(c);\n if (!context.finalized) {\n throw new Error(\n \"Context is not finalized. Did you forget to return a Response object or `await next()`?\"\n );\n }\n return context.res;\n } catch (err) {\n return this.#handleError(err, c);\n }\n })();\n }\n /**\n * `.fetch()` will be entry point of your app.\n *\n * @see {@link https://hono.dev/docs/api/hono#fetch}\n *\n * @param {Request} request - request Object of request\n * @param {Env} Env - env Object\n * @param {ExecutionContext} - context of execution\n * @returns {Response | Promise<Response>} response of request\n *\n */\n fetch = (request, ...rest) => {\n return this.#dispatch(request, rest[1], rest[0], request.method);\n };\n /**\n * `.request()` is a useful method for testing.\n * You can pass a URL or pathname to send a GET request.\n * app will return a Response object.\n * ```ts\n * test('GET /hello is ok', async () => {\n * const res = await app.request('/hello')\n * expect(res.status).toBe(200)\n * })\n * ```\n * @see https://hono.dev/docs/api/hono#request\n */\n request = (input, requestInit, Env, executionCtx) => {\n if (input instanceof Request) {\n return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);\n }\n input = input.toString();\n return this.fetch(\n new Request(\n /^https?:\\/\\//.test(input) ? input : `http://localhost${mergePath(\"/\", input)}`,\n requestInit\n ),\n Env,\n executionCtx\n );\n };\n /**\n * `.fire()` automatically adds a global fetch event listener.\n * This can be useful for environments that adhere to the Service Worker API, such as non-ES module Cloudflare Workers.\n * @deprecated\n * Use `fire` from `hono/service-worker` instead.\n * ```ts\n * import { Hono } from 'hono'\n * import { fire } from 'hono/service-worker'\n *\n * const app = new Hono()\n * // ...\n * fire(app)\n * ```\n * @see https://hono.dev/docs/api/hono#fire\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API\n * @see https://developers.cloudflare.com/workers/reference/migrate-to-module-workers/\n */\n fire = () => {\n addEventListener(\"fetch\", (event) => {\n event.respondWith(this.#dispatch(event.request, event, void 0, event.request.method));\n });\n };\n};\nexport {\n Hono as HonoBase\n};\n","// src/router/pattern-router/router.ts\nimport { METHOD_NAME_ALL, UnsupportedPathError } from \"../../router.js\";\nvar emptyParams = /* @__PURE__ */ Object.create(null);\nvar PatternRouter = class {\n name = \"PatternRouter\";\n #routes = [];\n add(method, path, handler) {\n const endsWithWildcard = path.at(-1) === \"*\";\n if (endsWithWildcard) {\n path = path.slice(0, -2);\n }\n if (path.at(-1) === \"?\") {\n path = path.slice(0, -1);\n this.add(method, path.replace(/\\/[^/]+$/, \"\"), handler);\n }\n const parts = (path.match(/\\/?(:\\w+(?:{(?:(?:{[\\d,]+})|[^}])+})?)|\\/?[^\\/\\?]+/g) || []).map(\n (part) => {\n const match = part.match(/^\\/:([^{]+)(?:{(.*)})?/);\n return match ? `/(?<${match[1]}>${match[2] || \"[^/]+\"})` : part === \"/*\" ? \"/[^/]+\" : part.replace(/[.\\\\+*[^\\]$()]/g, \"\\\\$&\");\n }\n );\n try {\n this.#routes.push([\n new RegExp(`^${parts.join(\"\")}${endsWithWildcard ? \"\" : \"/?$\"}`),\n method,\n handler\n ]);\n } catch {\n throw new UnsupportedPathError();\n }\n }\n match(method, path) {\n const handlers = [];\n for (let i = 0, len = this.#routes.length; i < len; i++) {\n const [pattern, routeMethod, handler] = this.#routes[i];\n if (routeMethod === method || routeMethod === METHOD_NAME_ALL) {\n const match = pattern.exec(path);\n if (match) {\n handlers.push([handler, match.groups || emptyParams]);\n }\n }\n }\n return [handlers];\n }\n};\nexport {\n PatternRouter\n};\n","// src/preset/tiny.ts\nimport { HonoBase } from \"../hono-base.js\";\nimport { PatternRouter } from \"../router/pattern-router/index.js\";\nvar Hono = class extends HonoBase {\n constructor(options = {}) {\n super(options);\n this.router = new PatternRouter();\n }\n};\nexport {\n Hono\n};\n","/**\n * Long-poll `GET /v1/since` handler core. Two exports:\n *\n * - {@link longPollSince} — the long-poll itself. Fast path first;\n * if `listEventsSince` already sees events, return immediately.\n * Otherwise race a poll loop against a 25 s wall-clock timeout and\n * return either the next batch of events or\n * `{ events: [], next_cursor: <same> }` (\"nothing changed within\n * the budget\").\n * - {@link listEventsSince} — one poll cycle. Reads `current.json`,\n * validates the caller's cursor against `log_seq_start`, discovers\n * the true tail by forward-probe, GETs each body by integer `seq`,\n * and returns the parsed `LogEntry`s in causal order.\n *\n * The handler is wired into the Hono router (`router.ts`); the\n * router itself owns request parsing and error → HTTP mapping. This\n * module owns the I/O + cursor semantics.\n *\n * Cost model. While a long-poll connection is active the per-poll\n * cost is one `Storage.get` of `current.json`, the tail\n * forward-probe GETs, plus one `Storage.get` per log entry yielded.\n * These are Class B ops, not Class A. The `< 1 Class A op / writer /\n * hour` cost-model bound (see `docs/spec/sync-protocol.md`) still\n * holds; active long-poll subscribers pay repeated Class B reads for\n * lower-latency delivery.\n */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\n COUNT_BIT_WIDTH,\n type LogEntry,\n logSeqStartOf,\n lsnParts,\n} from \"@baerly/protocol\";\nimport type { Db } from \"../db.ts\";\nimport type { SinceResponse } from \"../contract.ts\";\n\n/**\n * Validation regex for an opaque LSN cursor. Matches the shape minted\n * by `Writer.commit` (see `packages/server/src/writer.ts`) and described\n * on {@link LogEntry.lsn} — `<base32-time>_<session>_<seq>` where\n * base-32 is `[0-9a-v]` and the trailing seq is a fixed-width token.\n *\n * The seq width (`{11}`) is `Math.ceil(COUNT_BIT_WIDTH / 5)` chars, derived\n * automatically from the canonical `COUNT_BIT_WIDTH` constant in\n * `packages/protocol/src/constants.ts` via the `SEQ_CHARS` computed\n * constant below — no manual update needed when `COUNT_BIT_WIDTH` changes.\n * Currently: `Math.ceil(53 / 5) = 11`.\n */\n// COUNT_BIT_WIDTH is 53; Math.ceil(53 / 5) = 11.\nconst SEQ_CHARS = Math.ceil(COUNT_BIT_WIDTH / 5); // 11\nconst LSN_RE = new RegExp(`^[0-9a-v]+_[0-9a-v]+_[0-9a-v]{${SEQ_CHARS}}$`);\n\n/**\n * Hard cap on log entries returned in a single poll cycle. 1024 is\n * comfortably above the largest expected per-poll batch under the\n * production 1 s poll interval and bounds the worst-case memory\n * footprint of the parsed-JSON array on a hostile workload.\n */\nconst DEFAULT_MAX_EVENTS = 1024;\n\n/**\n * Default 25 s long-poll budget. CF Workers cap fetch CPU at 30 s on\n * the free plan; 25 s leaves slack for header serialization plus the\n * platform's bookkeeping. Node / Bun / Deno have no comparable cap,\n * but the budget is still useful as a connection-cycling hint for\n * upstream load balancers (most idle-connection timeouts are 30-60 s).\n *\n * Per-request override is via the `timeoutMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sinceTimeoutMs` on\n * `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_TIMEOUT_MS = 25_000;\n\n/**\n * Default 1 s inner-poll interval. See module docstring for the\n * cost-model trade-off.\n *\n * Per-request override is via the `pollIntervalMs` field on\n * {@link LongPollSinceOptions} (plumbed from `sincePollIntervalMs`\n * on `CreateRouterOptions` and both Node + Cloudflare adapters).\n */\nconst DEFAULT_POLL_INTERVAL_MS = 1_000;\n\nexport interface LongPollSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n readonly pollIntervalMs?: number;\n}\n\nexport interface ListEventsSinceOptions {\n readonly db: Db<BaerlyConfig>;\n readonly collection: string;\n /** Opaque cursor; empty string = from `log_seq_start`. */\n readonly cursor: string;\n readonly signal?: AbortSignal;\n}\n\n/**\n * Long-poll wrapper around {@link listEventsSince}. Returns as soon\n * as the first non-empty poll lands, or when the wall-clock timeout\n * elapses (whichever comes first). On timeout the response is\n * `{ events: [], next_cursor: <same> }` — shipped as `200`, not `304`,\n * because the response body carries the unchanged cursor the client\n * needs for the next poll cycle.\n *\n * @throws BaerlyError{code:\"SchemaError\"} — invalid cursor shape, or\n * the cursor references a log entry that has been folded into a\n * snapshot and GC'd.\n */\nexport async function longPollSince(opts: LongPollSinceOptions): Promise<SinceResponse> {\n const { db, collection, cursor, signal } = opts;\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n\n // Up-front cursor-shape validation. `listEventsSince` also checks,\n // but doing it here short-circuits the fast-path read on bad input.\n if (cursor.length > 0 && !LSN_RE.test(cursor)) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`,\n );\n }\n\n // Fast path: the first poll already sees new events.\n const initial = await listEventsSince({ db, collection, cursor, signal });\n if (initial.length > 0) {\n return { events: initial, next_cursor: initial[initial.length - 1]!.lsn };\n }\n\n // No events yet. Race a timeout against a polling loop.\n const start = Date.now();\n const deadline = start + timeoutMs;\n\n return new Promise<SinceResponse>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let settled = false;\n\n const cleanup = (): void => {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n if (signal !== undefined) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n };\n\n const settleResolve = (value: SinceResponse): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n resolve(value);\n };\n const settleReject = (err: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n cleanup();\n reject(err);\n };\n\n function onAbort(): void {\n // Treat client disconnect as \"no events, same cursor\" — the\n // socket is gone anyway; the resolve is a no-op for response\n // serialization but keeps the promise from leaking.\n settleResolve({ events: [], next_cursor: cursor });\n }\n\n if (signal !== undefined) {\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n const tick = async (): Promise<void> => {\n if (settled) {\n return;\n }\n try {\n const events = await listEventsSince({ db, collection, cursor, signal });\n if (settled) {\n return;\n }\n if (events.length > 0) {\n settleResolve({ events, next_cursor: events[events.length - 1]!.lsn });\n return;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) {\n settleResolve({ events: [], next_cursor: cursor });\n return;\n }\n const delay = Math.min(pollIntervalMs, remaining);\n timer = setTimeout(() => {\n void tick();\n }, delay);\n } catch (error) {\n settleReject(error);\n }\n };\n\n // First tick scheduled after `pollIntervalMs` (the initial fast\n // path already covered \"events present at t=0\"). Cap by the\n // remaining deadline so an early-cutoff tester with\n // `timeoutMs < pollIntervalMs` still resolves on time.\n timer = setTimeout(\n () => {\n void tick();\n },\n Math.min(pollIntervalMs, timeoutMs),\n );\n });\n}\n\n/**\n * One poll cycle: read `current.json`, derive the `seq` range to\n * scan from the cursor's embedded seq, GET each log entry by `seq`,\n * return the parsed `LogEntry`s in causal order.\n *\n * On-bucket log keys are `log/<seq>.json` — the same shape\n * `compactor` / `gc` / `rebuild-index` walk. Iterating\n * `[startSeq, endSeq)` and GET-ing each key directly avoids the\n * lex-`startAfter` hazard on integer filenames (`10.json` sorts\n * before `2.json` lex) and gives us the global causal ordering for\n * free — `seq` is monotonic across writer sessions.\n *\n * No `current.json` yet → `[]` (clients can poll a not-yet-existing\n * collection without erroring). Cursor inside `[0, log_seq_start)` →\n * `BaerlyError{code:\"SchemaError\"}`.\n */\nexport async function listEventsSince(opts: ListEventsSinceOptions): Promise<LogEntry[]> {\n const { db, collection, cursor, signal } = opts;\n\n if (cursor.length > 0 && !LSN_RE.test(cursor)) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor: invalid shape (expected an lsn returned by a prior SinceResponse); got ${JSON.stringify(cursor)}`,\n );\n }\n\n const read = await db.getCurrentJson(collection, signalOpt(signal));\n if (read === null) {\n // No collection provisioned yet. Clients polling for a collection that\n // doesn't exist see an empty stream, NOT an error.\n return [];\n }\n const logSeqStart = logSeqStartOf(read.json);\n // End bound is the DISCOVERED tail (probe past a stale-low hint).\n // The GET loop below 404-tolerates misses, so over-bounding is safe.\n // Floor at `max(log_seq_start, tail_hint)` — same probe floor every\n // other consumer uses (the invariant `tail_hint >= log_seq_start`\n // holds, so this is consistency, not a behaviour change).\n const tail = await db.probeLogTail(\n collection,\n Math.max(logSeqStart, read.json.tail_hint),\n signalOpt(signal),\n );\n\n // Derive the seq range to scan. Empty cursor → start at\n // `log_seq_start` (the first un-snapshotted entry). Non-empty\n // cursor → start at `cursorSeq + 1`. A cursor whose seq is below\n // `log_seq_start` references an entry the compactor has folded\n // into the snapshot and the GC sweep has deleted; the client must\n // re-bootstrap from a snapshot read before resuming.\n let startSeq: number;\n if (cursor.length === 0) {\n startSeq = logSeqStart;\n } else {\n const cursorSeq = lsnParts(cursor).seq;\n if (cursorSeq < logSeqStart) {\n throw new BaerlyError(\n \"SchemaError\",\n `cursor ${JSON.stringify(cursor)} points to a log entry that has been folded into a snapshot (log_seq_start=${logSeqStart}); re-bootstrap from a snapshot read before resuming`,\n );\n }\n startSeq = cursorSeq + 1;\n }\n\n // Cap the range at the discovered `tail` (no entries past the tail\n // exist) and at `DEFAULT_MAX_EVENTS` (hard ceiling per the module\n // docstring).\n const endSeq = Math.min(tail, startSeq + DEFAULT_MAX_EVENTS);\n\n // Sequential GETs (NOT Promise.all). Long-poll is latency-bound,\n // per-poll batch is typically 0-10 entries, sequential keeps\n // memory bounded under pathological workloads.\n const entries: LogEntry[] = [];\n for (let s = startSeq; s < endSeq; s++) {\n const entry = await db.getLogEntry(collection, s, signalOpt(signal));\n if (entry === null) {\n // Race: the GC sweeper deleted this entry between\n // `getCurrentJson` and the GET. Skip; don't error.\n continue;\n }\n entries.push(entry);\n }\n\n return entries;\n}\n\n/** Pack an optional `signal` into the `{ signal? }` shape callers expect. */\nconst signalOpt = (signal: AbortSignal | undefined): { signal?: AbortSignal } | undefined =>\n signal === undefined ? undefined : { signal };\n","/**\n * HTTP dispatcher. A small Hono `app` that implements the\n * five locked CRUD routes from `contract.ts`. Mounted into both\n * adapters (`@baerly/adapter-cloudflare` and `@baerly/adapter-node`);\n * the router itself is platform-agnostic — it accepts a single\n * `Request`, dispatches against a per-request `Db`, and returns a\n * `Response` whose body follows the `HttpOkEnvelope` /\n * `HttpErrorEnvelope` shapes.\n *\n * The anonymous `GET /v1/healthz` liveness probe is served by the\n * adapters directly (see `worker.ts` / `server.ts`) — keeping it\n * upstream of the router avoids spending a `Db.create` on every\n * load-balancer probe.\n *\n * `GET /v1/since` is appended to the same factory (see `./since.ts`\n * for the long-poll core). The Cloudflare adapter wraps Worker-side\n * GETs with `caches.default` *outside* `createRouter` so the router\n * stays platform-agnostic; that wrapper EXCLUDES `/v1/since` —\n * long-poll idleness is not a cache hit.\n */\n\nimport { Hono } from \"hono/tiny\";\nimport type { Context } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport {\n type BaerlyConfig,\n BaerlyError,\n type DocumentData,\n type BaerlyErrorCode,\n EMPTY_PREDICATE_WIRE,\n type OrderSpec,\n type PredicateWire,\n validateWire,\n WHERE_ORDER_JSON_RESOLUTION,\n WRITE_BODY_SHAPE_RESOLUTION,\n} from \"@baerly/protocol\";\nimport type { Db } from \"../db.ts\";\nimport {\n errorEnvelope,\n type HttpErrorEnvelope,\n type HttpOkEnvelope,\n type HttpStatus,\n type SinceResponse,\n} from \"../contract.ts\";\nimport { serializeError } from \"../observability/canonical.ts\";\nimport { CATEGORY, getCurrentContext, getLogger } from \"../observability/index.ts\";\nimport { runAllWithMeta, runByIdWithMeta } from \"../query.ts\";\nimport { longPollSince } from \"./since.ts\";\n\n/**\n * Options for {@link createRouter}.\n *\n * - `db` — single-tenant `Db` instance. The CF/Node adapters build a\n * fresh `Db` per request (after the Verifier resolves the tenant)\n * and hand it to a freshly-constructed router. The router itself\n * is stateless and per-request — `app.fetch(req)` is the only\n * entry point. The Verifier runs in the adapter (see `worker.ts` /\n * `server.ts`) before `createRouter` is called; the router itself\n * has no auth seam.\n */\nexport interface CreateRouterOptions {\n readonly db: Db<BaerlyConfig>;\n /** Override the long-poll budget. Forwarded to `longPollSince`. */\n readonly sinceTimeoutMs?: number;\n /** Override the long-poll inner-poll cadence. Forwarded to `longPollSince`. */\n readonly sincePollIntervalMs?: number;\n}\n\n/**\n * Build a Hono `app` that serves the CRUD routes:\n *\n * - `GET /v1/c/:collection/:id` → read one document.\n * - `GET /v1/c/:collection?where=<json>&order=<json>&limit=<n>` → list rows\n * matching a predicate, optionally ordered and capped.\n * - `POST /v1/c/:collection` → insert. Body: `{ doc }`. → `201 { _id }`.\n * - `PATCH /v1/c/:collection/:id` → merge-patch. Body: `{ patch }`. → `200 { modified }`.\n * - `PUT /v1/c/:collection/:id` → whole-doc replace. Body: `{ doc }`. → `200 { modified }`.\n * - `DELETE /v1/c/:collection/:id` → delete row by id. → `204`.\n * - `GET /v1/count?collection=<name>&where=<json>` → scalar `{ count: N }`.\n * - `GET /v1/since?collection=<name>&cursor=<opaque>` → long-poll log.\n *\n * @example\n * ```ts\n * import { createRouter, Db } from \"@gusto/baerly-storage\";\n * import { MemoryStorage } from \"@gusto/baerly-storage\";\n *\n * const db = Db.create({ storage: new MemoryStorage(), app: \"tickets\", tenant: \"acme\" });\n * const app = createRouter({ db });\n * // CF Workers:\n * export default { async fetch(req: Request) { return app.fetch(req); } };\n * ```\n */\nexport function createRouter(options: CreateRouterOptions): Hono {\n const { db, sinceTimeoutMs, sincePollIntervalMs } = options;\n const app = new Hono();\n\n // The router intentionally does NOT mount an observability\n // middleware. Production adapters (`@baerly/adapter-cloudflare`,\n // `@baerly/adapter-node`) open their own `ObservabilityContext`\n // BEFORE calling `createRouter().fetch` so they can stamp adapter-\n // owned fields (e.g. `cache_status`) before the cache wrapper\n // short-circuits. Standalone callers (tests, one-off harnesses) wrap\n // their request via `withHttpObservability` from\n // `@baerly/server`. Either way, one unit-of-work → exactly one\n // canonical line.\n\n // Read one — GET /v1/c/:collection/:id\n app.get(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { rows, manifestPointer, fresh } = await runByIdWithMeta(\n db.collectionReadContext(collection),\n id,\n );\n const row = rows[0];\n if (row === undefined) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return c.json(\n {\n data: row,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<DocumentData>,\n 200,\n );\n });\n\n // List — GET /v1/c/:collection?where=<urlencoded-json>\n app.get(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const wire = parseWhereParam(c);\n const order = parseOrder(c.req.query(\"order\"));\n const limit = parseLimit(c.req.query(\"limit\"));\n const { rows, manifestPointer, fresh } = await runAllWithMeta(\n db.collectionReadContext(collection),\n {\n wire,\n order,\n limit,\n },\n );\n return c.json(\n {\n data: rows,\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<ReadonlyArray<DocumentData>>,\n 200,\n );\n });\n\n // Insert — POST /v1/c/:collection Body: { doc } → 201 { _id }\n app.post(\"/v1/c/:collection\", async (c) => {\n const { collection } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n const { _id } = await db\n .collection(collection)\n .insert(doc as Partial<DocumentData> & DocumentData);\n return c.json({ _id }, 201);\n });\n\n // Patch — PATCH /v1/c/:collection/:id Body: { patch }\n app.patch(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const patch = assertJsonBodyField(body, \"patch\");\n const { modified } = await db.collection(collection).update(id, patch as Partial<DocumentData>);\n if (modified === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return c.json({ modified }, 200);\n });\n\n // Replace — PUT /v1/c/:collection/:id Body: { doc }\n // Whole-document overwrite (NOT merge-patch). Missing row → 404\n // (kernel throws `NotFound` directly via `runReplaceById`); row\n // matches → emits one `op:\"U\"` log entry with the post-image,\n // dropping fields absent from `doc`.\n app.put(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const body = await readJsonBody(c, MAX_BODY_BYTES);\n const doc = assertJsonBodyField(body, \"doc\");\n await db.collection(collection).replace(id, doc as DocumentData);\n return c.json({ modified: 1 }, 200);\n });\n\n // Delete — DELETE /v1/c/:collection/:id → 204\n app.delete(\"/v1/c/:collection/:id\", async (c) => {\n const { collection, id } = c.req.param();\n const { deleted } = await db.collection(collection).delete(id);\n if (deleted === 0) {\n throw new BaerlyError(\"NotFound\", `No such row: ${id}`);\n }\n return new Response(null, { status: 204 });\n });\n\n // Count — GET /v1/count?collection=<name>&where=<json>\n //\n // Returns a scalar row count for the matching predicate. Avoids the\n // client downloading every row just to take `.length` (silent egress\n // burn). Engine cost is currently the same as `runAllWithMeta` — the\n // win is wire bytes; an O(snapshot+log) count path can land later\n // without touching this route.\n app.get(\"/v1/count\", async (c) => {\n const collection = c.req.query(\"collection\");\n if (collection === undefined || collection.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n \"GET /v1/count requires ?collection=<name>\",\n undefined,\n undefined,\n undefined,\n \"Add ?collection=<name> to the request URL.\",\n );\n }\n const wire = parseWhereParam(c);\n const { rows, manifestPointer, fresh } = await runAllWithMeta(\n db.collectionReadContext(collection),\n {\n wire,\n order: undefined,\n limit: undefined,\n },\n );\n return c.json(\n {\n data: { count: rows.length },\n _meta: { manifest_pointer: manifestPointer, fresh },\n } satisfies HttpOkEnvelope<{ count: number }>,\n 200,\n );\n });\n\n // Long-poll — GET /v1/since?collection=<name>&cursor=<opaque>\n //\n // Cache-API note: the Cloudflare adapter's `caches.default` wrapper\n // explicitly EXCLUDES `/v1/since` — long-poll idleness is not a\n // cache hit. The adapter middleware MUST check the path before\n // consulting the cache. Do NOT add cache reads here.\n app.get(\"/v1/since\", async (c) => {\n // The router does NOT set `c.var.db`; the adapter resolves the\n // Verifier BEFORE `createRouter` is called and the resulting `db`\n // is captured in this closure. The handler reads it from the\n // outer scope, not from `c.var`.\n const collection = c.req.query(\"collection\");\n if (typeof collection !== \"string\" || collection.length === 0 || collection.includes(\"/\")) {\n throw new BaerlyError(\n \"SchemaError\",\n \"GET /v1/since requires a non-empty `collection` query parameter without `/`\",\n );\n }\n const cursor = c.req.query(\"cursor\") ?? \"\";\n const result = await longPollSince({\n db,\n collection,\n cursor,\n signal: c.req.raw.signal,\n timeoutMs: sinceTimeoutMs,\n pollIntervalMs: sincePollIntervalMs,\n });\n // 200 covers both \"new events present\" and \"timeout idle\" —\n // see `./since.ts` module JSDoc for why we don't use 304.\n return c.json(result satisfies SinceResponse, 200);\n });\n\n app.onError((err, c) => mapToResponse(c, err));\n\n return app;\n}\n\n/**\n * Hard cap on request-body bytes. 1 MiB — matches `S3HttpStorage`'s\n * conformance-suite default. Over-cap → `413 PayloadTooLarge`.\n *\n * The Node adapter (`@baerly/adapter-node`) imports this constant\n * and passes it to `applyBodyCap`, which wraps the request body\n * with a counting `TransformStream` so chunked uploads trip the cap\n * mid-stream rather than materialising the full buffer. The\n * router's `readJsonBody` keeps the cap as a defence-in-depth check\n * (Content-Length pre-read + post-`arrayBuffer` length) for adapters\n * whose platform doesn't pre-cap.\n *\n * @internal — exported for tests and for the Node adapter's\n * `applyBodyCap` helper. Promote to\n * `packages/protocol/src/constants.ts` only on a third cross-\n * package consumer.\n */\nexport const MAX_BODY_BYTES = 1 << 20; // 1 MiB; matches `S3HttpStorage`'s conformance-suite default.\n\n/**\n * Assert that `body[field]` is a plain object (not undefined / null /\n * array / primitive). Returns the value typed as\n * `Record<string, unknown>` so the caller's next cast doesn't need\n * another guard. Throws `BaerlyError{code:\"SchemaError\"}` with the\n * locked wording `\"Request body must be { <field>: object }\"`.\n *\n * Used by POST `/v1/c/:collection` (`doc`), PATCH `/v1/c/:collection/:id`\n * (`patch`), and PUT `/v1/c/:collection/:id` (`doc`).\n *\n * @internal\n */\nconst assertJsonBodyField = (body: unknown, field: string): Record<string, unknown> => {\n const value =\n typeof body === \"object\" && body !== null\n ? (body as Record<string, unknown>)[field]\n : undefined;\n if (value === undefined || typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new BaerlyError(\n \"SchemaError\",\n `Request body must be { ${field}: object }`,\n undefined,\n undefined,\n undefined,\n WRITE_BODY_SHAPE_RESOLUTION,\n );\n }\n return value as Record<string, unknown>;\n};\n\n/**\n * Parse the `?where=<urlencoded JSON>` query-string param. Absent or\n * empty → {@link EMPTY_PREDICATE_WIRE} (match-all). Malformed JSON →\n * `BaerlyError{code:\"SchemaError\"}` with the locked wording\n * `\"Invalid JSON in ?where=\"`. Returns the validated wire form\n * ({@link PredicateWire}).\n *\n * Wire-only validation: any clause with `field === \"_id\"` rejects\n * with `BaerlyError{code:\"InvalidConfig\"}` — agents zero-shot\n * writing `?where={\"clauses\":[{\"op\":\"eq\",\"field\":\"_id\",\"value\":\"x\"}]}`\n * against the list route get pointed at `GET /v1/c/:collection/:id`\n * instead. Kernel-internal `_id` wire construction\n * (`./collection.ts:byId`, `runByIdWithMeta`, `runInsert`) bypasses this\n * layer by design — those paths never come back through `?where=`\n * parsing.\n *\n * @internal\n */\nconst parseWhereParam = (c: Context): PredicateWire => {\n const whereParam = c.req.query(\"where\");\n if (whereParam === undefined || whereParam.length === 0) {\n return EMPTY_PREDICATE_WIRE;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(whereParam);\n } catch {\n throw new BaerlyError(\n \"SchemaError\",\n \"Invalid JSON in ?where=\",\n undefined,\n undefined,\n undefined,\n WHERE_ORDER_JSON_RESOLUTION,\n );\n }\n try {\n return validateWire(parsed as PredicateWire);\n } catch (error) {\n throw markCallerFacingInvalidConfig(error);\n }\n};\n\n/**\n * Parse `?limit=<n>` as a non-negative safe integer. Returns\n * `undefined` when absent. Rejects floats, NaN, negatives, and\n * non-numeric input with `SchemaError`.\n *\n * @internal\n */\nfunction parseLimit(raw: string | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const n = Number(raw);\n if (!Number.isSafeInteger(n) || n < 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `?limit= must be a non-negative integer; got ${JSON.stringify(raw)}`,\n );\n }\n return n;\n}\n\n/**\n * Parse the `?order=<json>` query param. Mirrors the `?where=` parser\n * shape: undefined → no order, malformed JSON → `SchemaError`. The\n * engine (`runAllWithMeta` → `sortByOrderSpec`) validates the shape\n * itself, so this only handles the wire-level JSON decode.\n *\n * @internal\n */\nfunction parseOrder(raw: string | undefined): OrderSpec<DocumentData> | undefined {\n if (raw === undefined || raw.length === 0) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n throw new BaerlyError(\n \"SchemaError\",\n \"Invalid JSON in ?order=\",\n undefined,\n undefined,\n undefined,\n WHERE_ORDER_JSON_RESOLUTION,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BaerlyError(\n \"SchemaError\",\n \"?order= must encode a JSON object\",\n undefined,\n undefined,\n undefined,\n WHERE_ORDER_JSON_RESOLUTION,\n );\n }\n return parsed as OrderSpec<DocumentData>;\n}\n\n// Exported as the single source of truth for the error-code → HTTP-status\n// mapping: the runtime router (below) and the build-time spec generator\n// (`spec/ir.ts`, reached via the `_internal/spec-gen` subpath) both read it,\n// so the served `/v1/spec` contract cannot drift from real router behaviour —\n// that drift gate is the point. Deliberately NOT re-exported from the\n// `@baerly/server/http` barrel, so the published package surface is unchanged.\nexport const ERROR_TO_STATUS: ReadonlyMap<BaerlyErrorCode, HttpStatus> = new Map<\n BaerlyErrorCode,\n HttpStatus\n>([\n [\"Unauthorized\", 401],\n [\"AccessDenied\", 403],\n [\"NotFound\", 404],\n [\"Conflict\", 409],\n [\"PayloadTooLarge\", 413],\n [\"SchemaError\", 400],\n [\"InvalidConfig\", 400],\n [\"UnsatisfiablePredicate\", 400],\n [\"NetworkError\", 502],\n [\"InvalidResponse\", 502],\n // Internal → 500\n]);\n\n/**\n * Machine-visible policy for whether an error code's thrown message is\n * safe to copy into the HTTP envelope. This is code-level metadata;\n * `Conflict` is instance-contextual because duplicate `_id` conflicts are\n * caller-facing, while retriable CAS/storage conflicts may carry bucket keys.\n * `InvalidConfig` is also contextual: predicate-wire validation errors are\n * caller-facing, but storage/adapter config errors may carry internal layout.\n *\n * Deliberately NOT re-exported from the `@baerly/server/http` barrel.\n */\nexport type ErrorMessagePolicy = \"public\" | \"scrubbed\" | \"contextual\";\n\ntype ErrorCodePolicy =\n | { readonly messagePolicy: \"public\" }\n | {\n readonly messagePolicy: \"scrubbed\";\n readonly scrubbedMessage: string;\n }\n | {\n readonly messagePolicy: \"contextual\";\n readonly scrubbedMessage: string;\n readonly shouldExpose: (err: BaerlyError) => boolean;\n };\n\nconst CALLER_FACING_INVALID_CONFIG_ERRORS = new WeakSet<BaerlyError>();\n\nconst ERROR_CODE_POLICY = {\n AccessDenied: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"access denied\",\n },\n Conflict: {\n messagePolicy: \"contextual\",\n scrubbedMessage: \"write conflict\",\n shouldExpose: (err) => !err.retriable,\n },\n Internal: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n InvalidConfig: {\n messagePolicy: \"contextual\",\n scrubbedMessage: \"invalid server configuration\",\n shouldExpose: (err) => CALLER_FACING_INVALID_CONFIG_ERRORS.has(err),\n },\n InvalidResponse: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"upstream response error\",\n },\n MutationFailed: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n NetworkError: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"upstream network error\",\n },\n NotFound: {\n messagePolicy: \"public\",\n },\n PayloadTooLarge: {\n messagePolicy: \"public\",\n },\n SchemaError: {\n messagePolicy: \"public\",\n },\n Unauthorized: {\n messagePolicy: \"public\",\n },\n UnexpectedWriteInQuery: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n UnsatisfiablePredicate: {\n messagePolicy: \"public\",\n },\n UseQueryAwaitedRecorder: {\n messagePolicy: \"scrubbed\",\n scrubbedMessage: \"internal error\",\n },\n} as const satisfies Record<BaerlyErrorCode, ErrorCodePolicy>;\n\nexport const errorMessagePolicyFor = (code: BaerlyErrorCode): ErrorMessagePolicy =>\n ERROR_CODE_POLICY[code].messagePolicy;\n\nconst markCallerFacingInvalidConfig = (err: unknown): unknown => {\n if (err instanceof BaerlyError && err.code === \"InvalidConfig\") {\n CALLER_FACING_INVALID_CONFIG_ERRORS.add(err);\n }\n return err;\n};\n\nconst shouldExposeErrorMessage = (err: BaerlyError): boolean => {\n const policy = ERROR_CODE_POLICY[err.code];\n if (policy.messagePolicy === \"public\") {\n return true;\n }\n if (policy.messagePolicy === \"scrubbed\") {\n return false;\n }\n return policy.shouldExpose(err);\n};\n\nconst scrubbedMessageFor = (code: BaerlyErrorCode): string => {\n const policy = ERROR_CODE_POLICY[code];\n return policy.messagePolicy === \"public\" ? \"internal error\" : policy.scrubbedMessage;\n};\n\nconst logScrubbedError = (err: BaerlyError, status: HttpStatus): void => {\n const ctx = getCurrentContext();\n getLogger(CATEGORY.http).error(\"scrubbed_error\", {\n error: serializeError(err),\n status,\n ...(ctx !== undefined ? { request_id: ctx.request_id } : {}),\n });\n};\n\n/**\n * Map an unknown thrown value onto the wire envelope plus an HTTP\n * status code. The mapping is keyed by `BaerlyError.code` so any future\n * code addition forces a re-check here. Unmapped server-side codes fall\n * through to 500 by design — currently only `Internal`.\n *\n * Public via `@gusto/baerly-storage/http` for the embed-by-hand recipe\n * (your own Hono / Express / Fastify app calling `Db` directly).\n * The `HttpErrorEnvelope` shape is locked; do not mutate it.\n */\nexport function mapError(err: unknown): { status: HttpStatus; envelope: HttpErrorEnvelope } {\n if (err instanceof BaerlyError) {\n const mappedStatus = ERROR_TO_STATUS.get(err.code);\n const status = mappedStatus ?? 500;\n const wireCode: BaerlyErrorCode = mappedStatus === undefined ? \"Internal\" : err.code;\n // Do not use HTTP status as the \"safe to expose\" signal: storage\n // and protocol errors mapped to 4xx/502 often carry physical bucket\n // keys, ETags, upstream response bodies, or provider binding text.\n // Preserve caller-facing messages, scrub server/storage diagnostics,\n // and keep the full detail in the server-side log.\n if (wireCode !== err.code || !shouldExposeErrorMessage(err)) {\n logScrubbedError(err, status);\n return {\n status,\n envelope: errorEnvelope(\n wireCode,\n scrubbedMessageFor(wireCode),\n undefined,\n wireCode === \"Conflict\" ? err.resolution : undefined,\n wireCode === err.code ? err.retriable : undefined,\n ),\n };\n }\n return {\n status,\n envelope: errorEnvelope(err.code, err.message, err.issues, err.resolution, err.retriable),\n };\n }\n // Unknown thrown value: the message may carry internal detail\n // (file paths, bucket names, upstream response bodies). Log on the\n // server side via the observability channel (replaces the legacy\n // bare `console.error`) and return a generic envelope to the\n // client. The mapped-error wire shape itself is locked and does\n // NOT change here.\n getLogger(CATEGORY.http).error(\"unhandled_error\", { error: serializeError(err) });\n return { status: 500, envelope: errorEnvelope(\"Internal\", \"internal error\") };\n}\n\n// Hono-context shortcut used by every handler's catch block.\nfunction mapToResponse(c: Context, err: unknown): Response {\n const { status, envelope } = mapError(err);\n // `mapError` only returns 4xx/5xx — all of which are\n // `ContentfulStatusCode`. The cast bridges the locked `HttpStatus`\n // union (which also includes 204/304 for the wider contract) to\n // Hono's narrower body-bearing subset.\n return c.json(envelope, status as ContentfulStatusCode);\n}\n\n/**\n * Read and parse the JSON request body. Returns the parsed value\n * (an `unknown` — caller narrows). Throws `BaerlyError`:\n *\n * - `\"PayloadTooLarge\"` (→ 413) when the body exceeds `maxBytes`,\n * detected via `Content-Length` pre-check, post-`arrayBuffer`\n * length check, or — if the host adapter pumps the body through\n * a `ReadableStream` (the Node adapter does) — a `BaerlyError`\n * surfaced via `controller.error(...)` on the upstream pump.\n * - `\"SchemaError\"` (→ 400) for empty bodies, JSON parse failures,\n * and any other read failure.\n *\n * Hono's `app.onError` sink routes the throw through `mapToResponse`.\n */\nasync function readJsonBody(c: Context, maxBytes: number): Promise<unknown> {\n const lenHeader = c.req.header(\"content-length\");\n if (lenHeader !== undefined) {\n const parsed = Number.parseInt(lenHeader, 10);\n if (Number.isFinite(parsed) && parsed > maxBytes) {\n throw new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${maxBytes} bytes`);\n }\n }\n // Read with an early-exit guard for chunked transfers. If the\n // upstream adapter (e.g. `@baerly/adapter-node`) caps the body at\n // the stream-pump layer, the rejected `arrayBuffer()` carries a\n // `BaerlyError{code:\"PayloadTooLarge\"}` which we re-throw verbatim;\n // any other read failure becomes a 400 SchemaError.\n let raw: string;\n try {\n const buffer = await c.req.arrayBuffer();\n if (buffer.byteLength > maxBytes) {\n throw new BaerlyError(\"PayloadTooLarge\", `Body exceeds ${maxBytes} bytes`);\n }\n raw = new TextDecoder().decode(buffer);\n } catch (error) {\n if (error instanceof BaerlyError) {\n throw error;\n }\n throw new BaerlyError(\n \"SchemaError\",\n `Failed to read request body: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (raw.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n \"Empty request body\",\n undefined,\n undefined,\n undefined,\n WRITE_BODY_SHAPE_RESOLUTION,\n );\n }\n try {\n return JSON.parse(raw);\n } catch {\n throw new BaerlyError(\n \"SchemaError\",\n \"Invalid JSON in request body\",\n undefined,\n undefined,\n undefined,\n WRITE_BODY_SHAPE_RESOLUTION,\n );\n }\n}\n"],"x_google_ignoreList":[1,2,3,4,5,6,7,8,9,10,11,12],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA4IA,MAAa,YAAY,QAAkD;CACzE,MAAM,QAAQ,IAAI,MAAM,GAAG;CAC3B,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,YAAY,mBAAmB,sBAAsB,KAAK;CAEtE,OAAO;EACL,SAAS,MAAM;EACf,KAAK,aAAa,MAAM,IAAA,EAAoB;CAC9C;AACF;;;ACpJA,IAAI,WAAW,YAAY,SAAS,eAAe;CACjD,QAAQ,SAAS,SAAS;EACxB,IAAI,QAAQ;EACZ,OAAO,SAAS,CAAC;EACjB,eAAe,SAAS,GAAG;GACzB,IAAI,KAAK,OACP,MAAM,IAAI,MAAM,8BAA8B;GAEhD,QAAQ;GACR,IAAI;GACJ,IAAI,UAAU;GACd,IAAI;GACJ,IAAI,W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