@gusto/baerly-storage 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +29 -0
- package/README.md +176 -70
- package/dist/API.md +213 -139
- package/dist/CHANGELOG.md +434 -0
- package/dist/RECIPES.md +125 -0
- package/dist/THIRD-PARTY-LICENSES.txt +238 -0
- package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-DyiFK3_k.d.ts} +55 -11
- package/dist/app-config.d.ts +1 -1
- package/dist/auth.d.ts +1 -1
- package/dist/auth.js +301 -301
- package/dist/auth.js.map +1 -1
- package/dist/aws4fetch.esm-p7eEzLCs.js +1702 -0
- package/dist/aws4fetch.esm-p7eEzLCs.js.map +1 -0
- package/dist/baerly.js +35 -15
- package/dist/baerly.js.map +1 -1
- package/dist/baerly.spec.json +342 -0
- package/dist/bytes-BXdamO3L.js.map +1 -1
- package/dist/{client-DYZfoZb9.d.ts → client-Fe8CwB73.d.ts} +10 -10
- package/dist/client-react.d.ts +3 -3
- package/dist/client-react.js +4 -4
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +4 -4
- package/dist/client.js +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{cloudflare-CINJPKCW.js → cloudflare-DzKBrUlg.js} +178 -2
- package/dist/cloudflare-DzKBrUlg.js.map +1 -0
- package/dist/cloudflare.d.ts +49 -6
- package/dist/cloudflare.js +59 -26
- package/dist/cloudflare.js.map +1 -1
- package/dist/config-1tv0-Yzm.js +2693 -0
- package/dist/config-1tv0-Yzm.js.map +1 -0
- package/dist/constants-CfeMWQWk.js +222 -0
- package/dist/constants-CfeMWQWk.js.map +1 -0
- package/dist/context-DRZ3tZ5l.js.map +1 -1
- package/dist/{cost-CQt1YRkA.js → cost-DSMIVqzL.js} +43 -42
- package/dist/cost-DSMIVqzL.js.map +1 -0
- package/dist/current-json-C6nhPOm1.js +190 -0
- package/dist/current-json-C6nhPOm1.js.map +1 -0
- package/dist/{db-BM3y2JQw.d.ts → db-DsPkOVEH.d.ts} +26 -108
- package/dist/{deploy-CrAbfgCq.js → deploy-DonTr-CV.js} +12 -5
- package/dist/deploy-DonTr-CV.js.map +1 -0
- package/dist/dev-vite.d.ts +11 -7
- package/dist/dev-vite.js +7 -6
- package/dist/dev-vite.js.map +1 -1
- package/dist/dev.d.ts +1 -1
- package/dist/dev.js +1 -1
- package/dist/{doctor-Db-hzPmE.js → doctor-DSIyCDg_.js} +14 -136
- package/dist/doctor-DSIyCDg_.js.map +1 -0
- package/dist/{dump-BYA55NLP.js → dump-Bh5k26VQ.js} +10 -31
- package/dist/dump-Bh5k26VQ.js.map +1 -0
- package/dist/{errors-DOdL95kK.js → errors-Dfa3p78c.js} +25 -5
- package/dist/errors-Dfa3p78c.js.map +1 -0
- package/dist/{export-Bhbz90-z.js → export-DtF5tDIM.js} +11 -32
- package/dist/{export-Bhbz90-z.js.map → export-DtF5tDIM.js.map} +1 -1
- package/dist/{fsck-CPPZWt9p.js → fsck-D_djMO5D.js} +28 -39
- package/dist/fsck-D_djMO5D.js.map +1 -0
- package/dist/{http-Cw8p6y5b.js → http-DxM9MflO.js} +151 -79
- package/dist/http-DxM9MflO.js.map +1 -0
- package/dist/http.d.ts +42 -26
- package/dist/http.js +3 -2
- package/dist/{index-DwDTWPSU.d.ts → index-0rZcMBwy.d.ts} +10 -7
- package/dist/{index-C3JAH1Yo.d.ts → index-B6oexfOB.d.ts} +9 -9
- package/dist/{index-cUY-36AN.d.ts → index-BNRh23K9.d.ts} +21 -5
- package/dist/{index-DSvwEUeF.d.ts → index-BYk9oCNf.d.ts} +240 -202
- package/dist/index.d.ts +6 -6
- package/dist/index.js +5 -5
- package/dist/{indexes-DAu2AkTW.d.ts → indexes-Dn9hbGQG.d.ts} +2 -2
- package/dist/{inspect-Bdbzvi-_.js → inspect-6WZ-pC7-.js} +21 -36
- package/dist/inspect-6WZ-pC7-.js.map +1 -0
- package/dist/key-Di6yyxFu.js +35 -0
- package/dist/key-Di6yyxFu.js.map +1 -0
- package/dist/{snapshot-SS8USDUF.js → log-tail-D98U1JBo.js} +179 -84
- package/dist/log-tail-D98U1JBo.js.map +1 -0
- package/dist/{maintenance-ClzBC1Vv.js → maintenance-B4Dki6Ig.js} +438 -176
- package/dist/maintenance-B4Dki6Ig.js.map +1 -0
- package/dist/{maintenance-BRrThz8V.d.ts → maintenance-B_e0T99L.d.ts} +114 -26
- package/dist/{maintenance-BvOv6BMM.js → maintenance-C7coQp4c.js} +217 -94
- package/dist/maintenance-C7coQp4c.js.map +1 -0
- package/dist/maintenance.d.ts +3 -2
- package/dist/maintenance.js +3 -2
- package/dist/node.d.ts +176 -68
- package/dist/node.js +3 -2
- package/dist/{normalize-XWY25_sG.js → normalize-rjnZLwS4.js} +2 -2
- package/dist/normalize-rjnZLwS4.js.map +1 -0
- package/dist/{observability-CpOiEN0k.js → observability-wzs3-BL_.js} +279 -109
- package/dist/observability-wzs3-BL_.js.map +1 -0
- package/dist/observability.d.ts +3 -3
- package/dist/observability.js +1 -1
- package/dist/{plan-DOTl21vq.js → plan-a7PJHBCy.js} +7 -4
- package/dist/plan-a7PJHBCy.js.map +1 -0
- package/dist/{query-BmiQy328.js → query-rAtXNQQB.js} +1063 -1202
- package/dist/query-rAtXNQQB.js.map +1 -0
- package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-BVzQSZlm.js} +10 -32
- package/dist/rebuild-index-BVzQSZlm.js.map +1 -0
- package/dist/{request-BEF_OvMh.js → request-u0M51mhJ.js} +3 -3
- package/dist/{request-BEF_OvMh.js.map → request-u0M51mhJ.js.map} +1 -1
- package/dist/restore-R-4rbciV.js +778 -0
- package/dist/restore-R-4rbciV.js.map +1 -0
- package/dist/runtime-spec-qL3_lTTU.js +391 -0
- package/dist/runtime-spec-qL3_lTTU.js.map +1 -0
- package/dist/s3-http-B-z8th6O.d.ts +60 -0
- package/dist/s3.d.ts +47 -0
- package/dist/s3.js +45 -0
- package/dist/s3.js.map +1 -0
- package/dist/{shared-secret-BJdSwpgw.js → shared-secret-DgEicd3x.js} +13 -5
- package/dist/shared-secret-DgEicd3x.js.map +1 -0
- package/dist/src-BG20LZs7.js +2271 -0
- package/dist/src-BG20LZs7.js.map +1 -0
- package/dist/{src-zhEAmmF7.js → src-CYHFDrKz.js} +82 -99
- package/dist/src-CYHFDrKz.js.map +1 -0
- package/dist/{src-QQ7jDeL2.js → src-DYZ4H1aF.js} +44 -23
- package/dist/src-DYZ4H1aF.js.map +1 -0
- package/dist/subcommand-DoDA-K7d.js +197 -0
- package/dist/subcommand-DoDA-K7d.js.map +1 -0
- package/dist/time-DUqvFMHq.js +119 -0
- package/dist/time-DUqvFMHq.js.map +1 -0
- package/dist/{usage-CLjirdD-.js → usage-DBV1eQHC.js} +7 -22
- package/dist/usage-DBV1eQHC.js.map +1 -0
- package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
- package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
- package/dist/wire-izfGZDvr.js.map +1 -1
- package/package.json +77 -42
- package/dist/cloudflare-CINJPKCW.js.map +0 -1
- package/dist/config-DVfDGyw1.js +0 -278
- package/dist/config-DVfDGyw1.js.map +0 -1
- package/dist/cost-CQt1YRkA.js.map +0 -1
- package/dist/current-json-C-EyJqs0.js +0 -354
- package/dist/current-json-C-EyJqs0.js.map +0 -1
- package/dist/deploy-CrAbfgCq.js.map +0 -1
- package/dist/doctor-Db-hzPmE.js.map +0 -1
- package/dist/dump-BYA55NLP.js.map +0 -1
- package/dist/errors-DOdL95kK.js.map +0 -1
- package/dist/fsck-CPPZWt9p.js.map +0 -1
- package/dist/http-Cw8p6y5b.js.map +0 -1
- package/dist/inspect-Bdbzvi-_.js.map +0 -1
- package/dist/maintenance-BvOv6BMM.js.map +0 -1
- package/dist/maintenance-ClzBC1Vv.js.map +0 -1
- package/dist/normalize-XWY25_sG.js.map +0 -1
- package/dist/observability-CpOiEN0k.js.map +0 -1
- package/dist/plan-DOTl21vq.js.map +0 -1
- package/dist/query-BmiQy328.js.map +0 -1
- package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
- package/dist/restore-C6IcmLeA.js +0 -771
- package/dist/restore-C6IcmLeA.js.map +0 -1
- package/dist/shared-secret-BJdSwpgw.js.map +0 -1
- package/dist/snapshot-SS8USDUF.js.map +0 -1
- package/dist/src-DU1sCMlr.js +0 -6236
- package/dist/src-DU1sCMlr.js.map +0 -1
- package/dist/src-QQ7jDeL2.js.map +0 -1
- package/dist/src-zhEAmmF7.js.map +0 -1
- package/dist/subcommand-DZcHcsYp.js +0 -5122
- package/dist/subcommand-DZcHcsYp.js.map +0 -1
- package/dist/usage-CLjirdD-.js.map +0 -1
- /package/dist/{chunk-EAsCxrDo.js → rolldown-runtime-EAsCxrDo.js} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"doctor-Db-hzPmE.js","names":[],"sources":["../packages/protocol/src/storage/probe-cas.ts","../packages/cli/src/doctor/cas.ts","../packages/cli/src/doctor/cloudflare.ts","../packages/cli/src/doctor.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\nimport { uuid } from \"../types.ts\";\nimport type { Storage } from \"./types.ts\";\n\nconst isConflict = (error: unknown): boolean =>\n error instanceof BaerlyError && error.code === \"Conflict\";\n\n/** One CAS sub-check's outcome. */\nexport interface CasProbeCheck {\n /** Stable identifier (`ifMatch-stale` / `ifNoneMatch-exists`). */\n readonly name: string;\n /** `true` iff the backend rejected the conditional write as required. */\n readonly ok: boolean;\n /** Human-readable detail — what was expected vs. observed. */\n readonly detail: string;\n}\n\n/** Aggregate result of {@link probeCas}. `ok` iff every sub-check passed. */\nexport interface CasProbeResult {\n readonly ok: boolean;\n readonly checks: readonly CasProbeCheck[];\n}\n\n/**\n * Runtime probe that a live `Storage` backend honours the conditional\n * writes the protocol depends on. The storage conformance suite asserts\n * the same semantics in CI for every shipped adapter, but a deployment\n * may point baerly at an arbitrary S3-compatible store; a backend that\n * silently *ignores* `If-Match` (returns 200 instead of rejecting a\n * stale write) causes silent lost-update corruption — every commit\n * CAS-advances `current.json`, and the no-lease maintenance fold relies\n * on the same fence. This is the fail-loud, deploy-time analogue of the\n * conformance CAS block.\n *\n * Writes a single throwaway sentinel under `keyPrefix` and deletes it on\n * the way out (even on failure). Two checks, mirroring the conformance\n * suite:\n * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).\n * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:\"*\"` over an existing\n * key must reject (Conflict).\n *\n * A rejected write surfaces as a `BaerlyError` with `code === \"Conflict\"`\n * (the contract `Storage.put` documents); anything else — a resolved\n * promise, or a non-Conflict error — means the backend does not honour\n * the condition and is reported as a failed check rather than thrown.\n */\nexport const probeCas = async (\n storage: Storage,\n opts?: { keyPrefix?: string; signal?: AbortSignal },\n): Promise<CasProbeResult> => {\n const prefix = opts?.keyPrefix ?? \"\";\n const key = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const enc = new TextEncoder();\n const signal = opts?.signal;\n\n const checks: CasProbeCheck[] = [];\n try {\n const first = await storage.put(key, enc.encode(\"v1\"), { signal });\n\n // ── Check 1: a stale ifMatch must be rejected. ──────────────────\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v2\"), { ifMatch: '\"baerly-cas-probe-stale\"', signal });\n checks.push({\n name: \"ifMatch-stale\",\n ok: false,\n detail:\n \"PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk).\",\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifMatch-stale\",\n ok: true,\n detail: \"stale If-Match rejected (Conflict), as required.\",\n }\n : {\n name: \"ifMatch-stale\",\n ok: false,\n detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // ── Check 2: ifNoneMatch:\"*\" over an existing key must reject. ──\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v3\"), { ifNoneMatch: \"*\", signal });\n checks.push({\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail:\n 'PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe).',\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifNoneMatch-exists\",\n ok: true,\n detail: 'If-None-Match:\"*\" over an existing key rejected (Conflict), as required.',\n }\n : {\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail: `If-None-Match:\"*\" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n void first;\n } finally {\n // Best-effort cleanup — never let a delete failure mask the verdict.\n try {\n await storage.delete(key, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n return { ok: checks.every((c) => c.ok), checks };\n};\n","/**\n * `baerly doctor --bucket <uri>` — live backend CAS probe.\n *\n * Unlike the cloudflare deploy-invariant walk (which only inspects\n * config files), this mode connects to a real bucket and verifies it\n * honours the conditional writes the protocol depends on: every commit\n * CAS-advances `current.json` with `If-Match`, and the no-lease\n * maintenance fold relies on the same fence. A store that silently\n * ignores `If-Match` (returns 200 instead of rejecting a stale write)\n * causes silent lost-update corruption — this is the fail-loud,\n * deploy-time analogue of the conformance CAS block.\n *\n * Writes a single throwaway sentinel and deletes it; see\n * {@link probeCas}.\n */\n\nimport { probeCas, type Storage } from \"@baerly/protocol\";\nimport type { DoctorFinding, DoctorReport } from \"./cloudflare.ts\";\n\nconst CAS_FIX =\n \"Point baerly at an S3-compatible store that honours conditional writes \" +\n \"(If-Match + If-None-Match). Real AWS S3, Cloudflare R2, and GCS do; a \" +\n \"custom gateway / proxy may be stripping conditional headers — check it \" +\n \"returns 412 on a stale If-Match.\";\n\n/**\n * Run the live CAS round-trip against `storage` and shape the result\n * as a {@link DoctorReport}. Status is `error` iff any sub-check failed\n * (a non-conformant backend is a hard blocker, not a warning).\n */\nexport const doctorCas = async (storage: Storage, keyPrefix: string): Promise<DoctorReport> => {\n const result = await probeCas(storage, { keyPrefix });\n const findings: DoctorFinding[] = result.checks.map((c) => ({\n severity: c.ok ? \"ok\" : \"error\",\n check: `cas-${c.name}`,\n message: c.detail,\n ...(c.ok ? {} : { fix: CAS_FIX }),\n }));\n return { findings, status: result.ok ? \"ok\" : \"error\" };\n};\n","/**\n * `baerly doctor --target=cloudflare` — walks the Cloudflare\n * deploy invariants and reports. With `--fix`, remediates what\n * can be safely auto-fixed (R2 bucket creation; secret prompts\n * are still user-driven because `wrangler secret put` reads\n * stdin interactively).\n *\n * Checks (each emitting one {@link DoctorFinding}):\n * 1. `wrangler.jsonc` exists at the package root.\n * 2. Each declared R2 binding exists in CF\n * (`wrangler r2 bucket info`).\n * 3. Each `requiredSecrets` entry is in `wrangler secret list`.\n * 4. If `cloudflareAccess` is set in `baerly.config.ts`,\n * `audienceTag` is 64 lowercase-hex chars and `teamDomain`\n * is non-empty.\n * 5. If `triggers.crons` is empty, warn that the maintenance\n * loop won't run.\n * 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`\n * doesn't declare a matching `routes` entry, warn.\n *\n * Output is a structured {@link DoctorReport} that\n * `packages/cli/src/doctor.ts` renders as either a checklist\n * (text mode) or a JSON envelope (`--json` mode).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parse, type ParseError } from \"jsonc-parser\";\nimport { BaerlyError, SHARED_SECRET_MISSING_MESSAGE } from \"@baerly/protocol\";\nimport type { AppConfig } from \"../config.ts\";\nimport { ensureBindings, parseR2Bindings, type ProcessRunner } from \"../deploy/cloudflare.ts\";\n\n/** One finding from a `baerly doctor` walk. */\nexport interface DoctorFinding {\n /** Severity. `ok` / `info` don't move the overall status. */\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n /** Short check name — stable, machine-readable. */\n readonly check: string;\n /** Human-friendly description. */\n readonly message: string;\n /** Optional remediation hint. */\n readonly fix?: string;\n}\n\n/** Result of a `baerly doctor` walk. */\nexport interface DoctorReport {\n readonly findings: readonly DoctorFinding[];\n /**\n * Overall: `ok` only when every finding has severity `ok` or\n * `info`. `warning` when the worst finding is a warning. `error`\n * when any finding is an error.\n */\n readonly status: \"ok\" | \"warning\" | \"error\";\n}\n\nconst rollupStatus = (findings: readonly DoctorFinding[]): DoctorReport[\"status\"] => {\n let worst: DoctorReport[\"status\"] = \"ok\";\n for (const f of findings) {\n if (f.severity === \"error\") {\n return \"error\";\n }\n if (f.severity === \"warning\") {\n worst = \"warning\";\n }\n }\n return worst;\n};\n\n/**\n * Read the declared cron schedule from `wrangler.jsonc`. Returns\n * `[]` when missing — caller treats empty as a warning.\n */\nconst readDeclaredCrons = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { triggers?: { crons?: unknown } }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const crons = obj.triggers?.crons;\n if (!Array.isArray(crons)) {\n return [];\n }\n return crons.filter((c): c is string => typeof c === \"string\");\n};\n\n/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */\nconst readDeclaredRoutePatterns = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { routes?: unknown }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const routes = obj.routes;\n if (!Array.isArray(routes)) {\n return [];\n }\n return routes\n .map((r) =>\n r !== null && typeof r === \"object\" ? (r as { pattern?: unknown }).pattern : undefined,\n )\n .filter((p): p is string => typeof p === \"string\");\n};\n\n/** Read declared `vars` keys from `wrangler.jsonc`. */\nconst readDeclaredVarKeys = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { vars?: Record<string, unknown> }\n | undefined;\n if (errors.length > 0 || obj === undefined || obj.vars === undefined) {\n return [];\n }\n return Object.keys(obj.vars);\n};\n\n/**\n * Walk the Cloudflare deploy invariants. With `opts.fix === true`,\n * remediate the auto-fixable issues (bucket creation). Secret\n * prompts stay user-driven.\n */\nexport const doctorCloudflare = async (\n config: AppConfig,\n opts: {\n readonly runner?: ProcessRunner;\n readonly fix?: boolean;\n readonly cwd?: string;\n } = {},\n): Promise<DoctorReport> => {\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = resolve(repoRoot, \"wrangler.jsonc\");\n const findings: DoctorFinding[] = [];\n\n // 1. wrangler.jsonc presence.\n if (!existsSync(wranglerPath)) {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc\",\n message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,\n fix: \"Re-scaffold (npm create baerly@latest) or restore the file from git.\",\n });\n return { findings, status: rollupStatus(findings) };\n }\n findings.push({\n severity: \"ok\",\n check: \"wrangler.jsonc\",\n message: `${wranglerPath} found.`,\n });\n\n // 2. R2 bindings — parse first, then probe each.\n let declared: readonly { binding: string; bucket_name: string }[];\n try {\n declared = parseR2Bindings(wranglerPath);\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"InvalidConfig\") {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc.parse\",\n message: error.message,\n });\n return { findings, status: rollupStatus(findings) };\n }\n throw error;\n }\n\n if (opts.fix === true && opts.runner !== undefined) {\n // Run the same provisioning path the deploy fallback uses.\n // Any failure here surfaces as an error finding rather than\n // throwing — doctor's job is to report.\n try {\n await ensureBindings(opts.runner, repoRoot, wranglerPath);\n } catch (error) {\n findings.push({\n severity: \"error\",\n check: \"r2.fix\",\n message: error instanceof Error ? error.message : \"unknown error during ensureBindings\",\n });\n }\n }\n\n if (opts.runner !== undefined) {\n for (const { bucket_name } of declared) {\n const info = await opts.runner.run(\n \"wrangler\",\n [\"r2\", \"bucket\", \"info\", bucket_name],\n repoRoot,\n );\n if (info.code === 0) {\n findings.push({\n severity: \"ok\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" exists.`,\n });\n } else {\n findings.push({\n severity: \"error\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" not found.`,\n fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`,\n });\n }\n }\n } else {\n findings.push({\n severity: \"info\",\n check: \"r2.skip\",\n message: \"no runner supplied; skipped R2 bucket probes.\",\n });\n }\n\n // 3. requiredSecrets — best-effort.\n //\n // `configured` is lifted to the outer scope so the auth-posture\n // block below can read the deployed secret set without re-running\n // `wrangler secret list`. Empty when the runner is absent or the\n // listing call failed.\n const required = config.requiredSecrets ?? [\"SHARED_SECRET\"];\n let configured: readonly string[] = [];\n if (opts.runner !== undefined && required.length > 0) {\n const r = await opts.runner.run(\"wrangler\", [\"secret\", \"list\"], repoRoot);\n if (r.code !== 0) {\n findings.push({\n severity: \"warning\",\n check: \"secrets\",\n message: \"could not list secrets (wrangler exit non-zero); skipping check.\",\n });\n } else {\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (Array.isArray(parsed)) {\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n }\n } catch {\n // fall through with empty configured set\n }\n for (const name of required) {\n if (configured.includes(name)) {\n findings.push({\n severity: \"ok\",\n check: `secret.${name}`,\n message: `secret ${name} is set.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check: `secret.${name}`,\n message: `secret ${name} is required but unset.`,\n fix: `wrangler secret put ${name}`,\n });\n }\n }\n }\n } else if (required.length > 0) {\n findings.push({\n severity: \"info\",\n check: \"secrets.skip\",\n message: \"no runner supplied; skipped secret checks.\",\n });\n }\n\n // 7. config.auth — graduated-auth posture. Walks the typed `auth`\n // field added in `packages/protocol/src/app-config.ts`.\n // FAIL: shared-secret without SHARED_SECRET set on the worker.\n // WARN: auth: \"none\" + deploy target (operator may have a\n // network gate in front; surface it so they confirm).\n // INFO: CF Access vars present + adapter uses config.auth (auth\n // is using config.auth, CF Access env is inert).\n //\n // The presence of the typed field is guaranteed by the loader\n // (config.ts throws on omission), so we walk every loaded config\n // without an existence guard.\n if (config.auth === \"none\") {\n // Deploy-target check: \"cloudflare\" / \"node\" are the only valid\n // values, and both ship to a network-reachable runtime. We warn\n // unconditionally — the doctor's job is to surface the choice,\n // not to second-guess whether the operator's network seam (CF\n // Access, intranet ACL, Tunnel) is upstream.\n findings.push({\n severity: \"warning\",\n check: \"auth.none-on-deploy\",\n message:\n `baerly.config.ts has auth: \"none\" and ships to target=${JSON.stringify(config.target)}. ` +\n \"Every request will resolve to config.tenant with no header check. \" +\n \"Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) \" +\n 'or change `auth` to \"shared-secret\" or pass a custom `verifier:` on the adapter factory.',\n fix:\n 'Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; ' +\n 'or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`.',\n });\n }\n\n if (config.auth === \"shared-secret\" && opts.runner !== undefined) {\n // Mirror the FAIL message wording from the adapter's runtime\n // throw. Locked via `SHARED_SECRET_MISSING_MESSAGE` so doctor +\n // adapter stay in sync.\n //\n // If `configured` is still empty here, the `wrangler secret list`\n // invocation either failed (we already warned with the \"secrets\"\n // finding above) or really lists no secrets. Either way the\n // operator-facing remediation is the same.\n const requiredSecret = \"SHARED_SECRET\";\n if (!configured.includes(requiredSecret)) {\n findings.push({\n severity: \"error\",\n check: \"auth.shared-secret-missing\",\n message: SHARED_SECRET_MISSING_MESSAGE,\n fix:\n \"wrangler secret put SHARED_SECRET (for production) \" +\n \"or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`).\",\n });\n }\n }\n\n // INFO: CF Access env vars in wrangler.jsonc:vars but the adapter\n // is using `config.auth` for the verifier (so the env values are\n // inert). We can't statically parse the user's worker source —\n // surface the heuristic.\n const varKeys = new Set(readDeclaredVarKeys(wranglerPath));\n if (\n varKeys.has(\"CF_ACCESS_TEAM_DOMAIN\") &&\n varKeys.has(\"CF_ACCESS_AUDIENCE_TAG\")\n ) {\n findings.push({\n severity: \"info\",\n check: \"auth.cf-access-inert\",\n message:\n `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} ` +\n `but the adapter uses config.auth=${JSON.stringify(config.auth)}. ` +\n `To wire CF Access, pass \\`verifier: cloudflareAccess({ teamDomain, audienceTag })\\` on the baerlyWorker factory.`,\n });\n }\n\n // 4. cloudflareAccess — when configured, audience tag must be\n // 64 lowercase-hex chars.\n if (config.cloudflareAccess !== undefined) {\n const { teamDomain, audienceTag } = config.cloudflareAccess;\n if (teamDomain.length === 0) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.teamDomain\",\n message: \"cloudflareAccess.teamDomain in baerly.config.ts is empty.\",\n });\n }\n if (!/^[0-9a-f]{64}$/.test(audienceTag)) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.audienceTag\",\n message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,\n fix: \"Copy the AUD tag from the Cloudflare Access app's configuration tab.\",\n });\n } else if (teamDomain.length > 0) {\n findings.push({\n severity: \"ok\",\n check: \"cloudflareAccess\",\n message: `cloudflareAccess audience tag is well-formed; team domain \"${teamDomain}\".`,\n });\n }\n }\n\n // 5. Cron triggers — empty list means the maintenance loop won't\n // run.\n const crons = readDeclaredCrons(wranglerPath);\n if (crons.length === 0) {\n findings.push({\n severity: \"warning\",\n check: \"triggers.crons\",\n message: \"no cron triggers declared; the maintenance loop will not run automatically.\",\n fix: `Add \"triggers\": { \"crons\": [\"* * * * *\"] } to ${wranglerPath}.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"triggers.crons\",\n message: `cron trigger${crons.length === 1 ? \"\" : \"s\"} ${crons.map((c) => JSON.stringify(c)).join(\", \")} declared.`,\n });\n }\n\n // 6. domain ↔ routes coherence.\n if (config.domain !== undefined && config.domain.length > 0) {\n const patterns = readDeclaredRoutePatterns(wranglerPath);\n const expectedPrefix = `${config.domain}/`;\n const hasMatch = patterns.some(\n (p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix),\n );\n if (!hasMatch) {\n findings.push({\n severity: \"warning\",\n check: \"routes.domain\",\n message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,\n fix: `Add { \"pattern\": \"${config.domain}/*\", \"custom_domain\": true } to wrangler.jsonc:routes.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"routes.domain\",\n message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`,\n });\n }\n }\n\n return { findings, status: rollupStatus(findings) };\n};\n","/**\n * `baerly doctor` — citty dispatcher for deploy-invariant checks.\n *\n * Two modes:\n * - `--bucket <uri>` — connect to a live bucket and probe its CAS\n * support (the protocol's load-bearing backend prerequisite). This\n * mode WRITES + deletes one throwaway sentinel; see\n * {@link doctorCas}. Independent of `baerly.config.ts` / `--target`.\n * - otherwise — reads `baerly.config.ts:target` and routes to\n * {@link doctorCloudflare} (read-only deploy-invariant checks). The\n * Node target self-validates at scaffold time — the example IS the\n * contract — so it has no doctor backend.\n *\n * Drift detection, index rebuilds, and writes/min health are separate\n * verbs:\n * - `baerly admin fsck --indexes [--fix]` — index drift.\n * - `baerly admin usage` — writes/min M-size graduation.\n * - `baerly admin rebuild-index` — single-index reconciliation.\n *\n * Renders the returned {@link DoctorReport} into either a\n * stdout checklist (text mode) or a JSON envelope (`--json`\n * mode).\n *\n * Exit-code contract (mirrors `baerly deploy`):\n * - 0 success — report status is `ok` or `warning`.\n * - 1 user error (InvalidConfig, unknown target, missing config).\n * - 2 storage / external error.\n * - 3 protocol invariant.\n *\n * A `warning` status returns exit 0 (the user can deploy; we just\n * flagged a maintenance / coherence issue). An `error` status\n * returns exit 2 unless the underlying cause was an InvalidConfig\n * (which already returned 1 via a thrown BaerlyError).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { doctorCas } from \"./doctor/cas.ts\";\nimport { doctorCloudflare, type DoctorReport } from \"./doctor/cloudflare.ts\";\nimport { defaultRunner } from \"./runner.ts\";\nimport { color, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst DOCTOR_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).',\n valueHint: \"cloudflare\",\n },\n bucket: {\n type: \"string\",\n description:\n \"Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, file:///, or memory:// URI. Independent of --target.\",\n valueHint: \"s3://bucket/prefix\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst colorize = (severity: string, glyph: string): string => {\n if (severity === \"error\") {\n return color.red(glyph);\n }\n if (severity === \"warning\") {\n return color.yellow(glyph);\n }\n if (severity === \"info\") {\n return color.dim(glyph);\n }\n return glyph;\n};\n\nconst renderReport = (\n label: { kind: \"target\" | \"bucket\"; value: string },\n report: DoctorReport,\n): void => {\n if (isJsonMode()) {\n process.stdout.write(\n `${JSON.stringify({ result: { command: \"doctor\", [label.kind]: label.value, ...report } })}\\n`,\n );\n return;\n }\n process.stdout.write(`baerly doctor --${label.kind}=${label.value}\\n\\n`);\n let okCount = 0;\n let warningCount = 0;\n let errorCount = 0;\n for (const f of report.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? \"•\";\n process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\\n`);\n if (f.fix !== undefined) {\n process.stdout.write(` fix: ${f.fix}\\n`);\n }\n if (f.severity === \"ok\") {\n okCount += 1;\n } else if (f.severity === \"warning\") {\n warningCount += 1;\n } else if (f.severity === \"error\") {\n errorCount += 1;\n }\n }\n process.stdout.write(\n `\\nStatus: ${errorCount} error${errorCount === 1 ? \"\" : \"s\"}, ${warningCount} warning${warningCount === 1 ? \"\" : \"s\"}, ${okCount} ok.\\n`,\n );\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"doctor\",\n meta: {\n description:\n \"Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target.\",\n },\n args: DOCTOR_ARGS,\n handler: async (args) => {\n // --bucket is a standalone live-probe mode: it connects to a real\n // bucket and checks CAS, independent of baerly.config.ts / --target.\n if (args.bucket !== undefined) {\n const { storage, keyPrefix } = await parseBucketUri(args.bucket);\n const report = await doctorCas(storage, keyPrefix);\n renderReport({ kind: \"bucket\", value: args.bucket }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const report = await doctorCloudflare(config, {\n runner: defaultRunner(),\n ...(args.fix === true && { fix: true }),\n });\n renderReport({ kind: \"target\", value: target }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. ` +\n `(Node variants self-validate at scaffold time; the example IS the contract.)`,\n );\n },\n});\n\n/** citty `defineCommand` block for `baerly doctor`. */\nexport const doctor = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDoctor = bundle.run;\n"],"mappings":";;;;;;;AAIA,MAAM,cAAc,UAClB,iBAAiB,eAAe,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;AAyCjD,MAAa,WAAW,OACtB,SACA,SAC4B;CAE5B,MAAM,MAAM,GADG,MAAM,aAAa,GACZ,uBAAuB,KAAK;CAClD,MAAM,MAAM,IAAI,YAAY;CAC5B,MAAM,SAAS,MAAM;CAErB,MAAM,SAA0B,CAAC;CACjC,IAAI;EACY,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG,EAAE,OAAO,CAAC;EAGjE,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,SAAS;IAA4B;GAAO,CAAC;GACxF,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAAS,OAAO;GACd,OAAO,KACL,WAAW,KAAK,IACZ;IACE,MAAM;IACN,IAAI;IACJ,QAAQ;GACV,IACA;IACE,MAAM;IACN,IAAI;IACJ,QAAQ,+CAA+C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAC9G,CACN;EACF;EAGA,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,aAAa;IAAK;GAAO,CAAC;GACrE,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAAS,OAAO;GACd,OAAO,KACL,WAAW,KAAK,IACZ;IACE,MAAM;IACN,IAAI;IACJ,QAAQ;GACV,IACA;IACE,MAAM;IACN,IAAI;IACJ,QAAQ,kDAAkD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GACjH,CACN;EACF;CAGF,UAAU;EAER,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E,MAAM;IAAU,OAAO,KAAK;GAAO,GAAG,MAAM;GAC3D,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,SAAS,MAAM,cAAc;EACnC,MAAM,SAAS,KAAK,UAAU,OAAO;EACrC,IAAI,WAAW,cAAc;GAC3B,MAAM,SAAS,MAAM,iBAAiB,QAAQ;IAC5C,QAAQ,cAAc;IACtB,GAAI,KAAK,QAAQ,QAAQ,EAAE,KAAK,KAAK;GACvC,CAAC;GACD,aAAa;IAAE,MAAM;IAAU,OAAO;GAAO,GAAG,MAAM;GACtD,OAAO,OAAO,WAAW,UAAU,IAAI;EACzC;EACA,MAAM,IAAI,YACR,iBACA,yBAAyB,KAAK,UAAU,MAAM,EAAE,qGAElD;CACF;AACF,CAAC;;AAGD,MAAa,SAAS,OAAO;AAOJ,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dump-BYA55NLP.js","names":[],"sources":["../packages/cli/src/admin/dump.ts"],"sourcesContent":["/**\n * `baerly admin dump` — canonical NDJSON of the materialised view.\n *\n * Writes one row per line to stdout, in a strict byte-stable shape so\n * two semantically-equal collections produce byte-equal output. Tests\n * and other programmatic callers can divert the NDJSON output to a\n * file or buffer by passing `{ streams: { stdout } }` to {@link runDump}.\n *\n * Canonical NDJSON dump format:\n *\n * 1. Each row is `{\"_id\":\"<id>\",…}` (no spaces).\n * 2. Row order = ASCII-lex sort on `_id`.\n * 3. Within each row, object keys are sorted ASCII-lex\n * RECURSIVELY — every nested object's keys are sorted too.\n * 4. Numbers as their canonical `JSON.stringify` output.\n * Finite-only (the protocol forbids NaN / Infinity).\n * 5. Strings as `JSON.stringify` output (escape sequences\n * identical to `\\uXXXX` for control codes).\n * 6. One trailing newline at EOF (`\\n`, not `\\r\\n`).\n * 7. No BOM.\n *\n * The round-trip ticket (73) gates byte-equality on this format. A\n * change to any of (1)–(7) is a BREAKING change requiring a\n * round-trip schema-version bump.\n *\n * Empty collection → empty file (no trailing newline) — disambiguates\n * \"zero rows\" from \"one row with empty body\".\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --json JSON envelope (on stdout). Programmatic callers can\n * divert the NDJSON body to a separate writable via the\n * `streams.stdout` option on {@link runDump}.\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Storage / Network / Internal protocol violation.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type Writable } from \"node:stream\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type DocumentValue, type DocumentData } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"../export/index.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst DUMP_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\n/**\n * Recursive byte-stable JSON stringifier. Object keys at every nesting\n * level are sorted ASCII-lex; array element order is preserved as-is.\n * Numbers must be finite (protocol forbids NaN / Infinity in bodies).\n */\nexport const canonicalStringify = (value: DocumentValue): string => {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`,\n );\n }\n return JSON.stringify(value);\n }\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (value === null) {\n // DocumentValue excludes null at the type level, but `unknown` may\n // sneak in via the snapshot fold — be defensive.\n return \"null\";\n }\n if (Array.isArray(value)) {\n const parts = value.map((v) => canonicalStringify(v));\n return `[${parts.join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const keys = Object.keys(value).toSorted();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as Record<string, DocumentValue>)[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: unsupported value type ${typeof value}`,\n );\n};\n\n/**\n * Drain rows to the supplied writable, applying back-pressure on every\n * line. We don't `end()` the stream — the caller owns its lifecycle\n * (`process.stdout` shouldn't be closed; a test-supplied\n * `createWriteStream` flushes on its own `end()`).\n */\nconst writeToSink = async (\n sink: Writable,\n rows: ReadonlyMap<string, DocumentData>,\n): Promise<number> => {\n const ids = [...rows.keys()].toSorted();\n let count = 0;\n for (const id of ids) {\n const body = rows.get(id);\n if (body === undefined) {\n continue;\n }\n // Merge `_id` into the body so the row literal carries it. The\n // map key is authoritative; if a stale `_id` field disagrees, we\n // overwrite it.\n const row: DocumentData = { ...body, _id: id };\n const line = `${canonicalStringify(row)}\\n`;\n if (!sink.write(line)) {\n await new Promise<void>((resolve) => sink.once(\"drain\", resolve));\n }\n count++;\n }\n return count;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.dump\",\n meta: {\n description: \"Canonical NDJSON of the materialised view of one collection.\",\n },\n args: DUMP_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin dump: current.json not found at ${currentJsonKey}`,\n );\n }\n const sink: Writable = ctx.streams?.stdout ?? process.stdout;\n const count = await writeToSink(sink, view);\n emitSuccess({\n command: \"admin.dump\",\n status: \"ok\",\n collection: args.collection,\n dumped: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin dump`. */\nexport const dumpCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDump = bundle.run;\n"],"mappings":";;;;;AAoDA,MAAM,YAAY;CAChB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;AACF;;;;;;AAOA,MAAa,sBAAsB,UAAiC;CAClE,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GACxB,MAAM,IAAI,YACR,mBACA,qDAAqD,OAAO,KAAK,EAAE,sBACrE;EAEF,OAAO,KAAK,UAAU,KAAK;CAC7B;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAChD,OAAO,KAAK,UAAU,KAAK;CAE7B,IAAI,UAAU,MAGZ,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GAErB,OAAO,IADO,MAAM,KAAK,MAAM,mBAAmB,CAAC,CACpC,EAAE,KAAK,GAAG,EAAE;CAE7B,IAAI,OAAO,UAAU,UA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ClD;EAGF,MAAM,QAAQ,MAAM,YADG,IAAI,SAAS,UAAU,QAAQ,QAChB,IAAI;EAC1C,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB,QAAQ;EACV,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOP,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors-DOdL95kK.js","names":[],"sources":["../packages/protocol/src/errors.ts"],"sourcesContent":["/**\n * Discriminator for {@link BaerlyError}. Strings (not subclasses) so they\n * survive cross-realm boundaries (e.g. a Web Worker) and so callers can\n * pattern-match with grep-friendly equality.\n */\nexport type BaerlyErrorCode =\n /** Caller-provided config or input is invalid (bad bucket, unsupported credential type, malformed URL, bucket not version-enabled when versioning was requested). */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 422.\n */\n | \"SchemaError\"\n /**\n * CAS lost on `current.json`. Caller decides whether to retry.\n * Surfaces in the collection API and HTTP layer.\n */\n | \"Conflict\"\n /**\n * `Verifier` returned no identity. HTTP server maps to 401.\n * Code is reserved here so the union locks.\n */\n | \"Unauthorized\"\n /**\n * The addressed resource does not exist. HTTP server maps to 404.\n * Emitted by the row-by-id read / update / delete handlers in\n * `packages/server/src/http/router.ts` when the predicate\n * `{ _id }` matches zero rows. Not a protocol invariant —\n * callers may retry after creating the resource or treat as a\n * miss depending on intent. The CLI maps this to the generic\n * exit-2 \"storage error\" bucket, not the exit-3 \"protocol\n * invariant\" bucket.\n */\n | \"NotFound\"\n /**\n * Request body exceeded the server's size cap. HTTP server maps\n * to 413. Cap is `MAX_BODY_BYTES` (1 MiB today; exported from\n * `packages/server/src/http/router.ts`). The Node adapter\n * enforces during the `node:http` stream pump so the process\n * never materializes a multi-MiB body; Workers also rely on\n * platform-side caps (16 MB free / 100 MB paid).\n */\n | \"PayloadTooLarge\"\n /**\n * A predicate is structurally well-formed but contradicts itself —\n * no document can match. Emitted by `validateWire` and\n * `mergePredicateWires`. Triggers:\n * - `{ clauses: [{op:\"in\", field:\"priority\", value:[]}] }` (empty `in` set)\n * - an `eq` clause with a value outside the residual interval\n * established by range clauses on the same field\n * - merging `{op:\"gt\", value:10}` with `{op:\"lt\", value:5}` on the\n * same field (empty interval)\n * - merging two `in` clauses on the same field with empty intersection\n *\n * Conflicting equality across clauses (`eq:\"open\"` + `eq:\"closed\"` on\n * the same field) surfaces as `InvalidConfig` rather than this code —\n * the merger treats it as a caller-side configuration bug, not an\n * algebraic contradiction.\n *\n * The HTTP layer treats this as a 400 (caller error). The distinct\n * code lets downstream code short-circuit empty-by-construction\n * without re-running the validator or parsing messages.\n */\n | \"UnsatisfiablePredicate\"\n /**\n * A `useQuery` callback awaited a recorder terminal\n * (`.get`/`.first`/`.all`/`.count`). The recorder runs once per\n * render to capture the chain shape; it cannot survive an `await`\n * because the proxy doesn't proxy across microtask boundaries. The\n * recorder's terminal returns a thenable whose `.then` throws this\n * error synchronously, converting what would otherwise be a silent\n * spinner-hang into a render-time error the hook surfaces as\n * `status: \"error\"`. Companion `baerly/no-await-in-use-query` lint\n * flags the pattern at edit time. For compound reads, use\n * `Promise.all` (parallel) or compose two `useQuery` calls with\n * `useQuery.skip` (dependent).\n */\n | \"UseQueryAwaitedRecorder\"\n /**\n * A write method (`.insert`/`.update`/`.replace`/`.delete`) was\n * called on the recorder inside a `useQuery` callback. Writes\n * inside reads are a programming error; the recorder rejects them\n * synchronously from the discovery pass, before any I/O fires. Use\n * `useMutation()` instead.\n */\n | \"UnexpectedWriteInQuery\"\n /**\n * A `useMutation()` callback rejected with a non-`BaerlyError`\n * throwable. The hook wraps the original throw under this code so\n * the `error` slot is always a `BaerlyError`; the original value\n * is preserved on `.cause`.\n */\n | \"MutationFailed\";\n\n/**\n * The single error class thrown by Baerly. Discriminate by `code`, not\n * `instanceof`: the code string survives `JSON.stringify` round-trips\n * across Worker / iframe / postMessage realm boundaries, where each\n * realm has its own `BaerlyError` constructor identity. IDB-restored\n * writes can replay across realms, so `instanceof` would spuriously\n * fail on a structurally-identical error from another realm.\n *\n * @example\n * ```ts\n * try {\n * await db.collection(\"tickets\").insert({ title: \"hi\" });\n * } catch (err) {\n * if (err instanceof BaerlyError && err.code === \"Conflict\") {\n * // ... CAS lost; retry\n * }\n * throw err;\n * }\n * ```\n */\nexport class BaerlyError extends Error {\n readonly code: BaerlyErrorCode;\n override readonly cause?: unknown;\n /**\n * Structured field-path issues, set only when `code === \"SchemaError\"`.\n * Each entry's `path` is a dotted-key list (e.g. `[\"assignee\", \"team\"]`\n * or `[\"items\", 3, \"qty\"]`) that targets the offending field on the\n * input document. `message` is the validator-emitted human string.\n *\n * The HTTP layer's `mapError` renders these into the 400 body via\n * the existing `HttpErrorEnvelope`; older callers that don't know\n * about `issues` see a plain message-only error and stay correct.\n */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /**\n * Raw HTTP status, set only by the client-side wire decoder when\n * inflating an `HttpErrorEnvelope` into this class. Server-side\n * throws never set it (the HTTP layer's `mapError` derives the\n * outbound status from `code`). Useful for diagnostics — e.g. to\n * distinguish 404-as-\"no such row\" from 404-as-\"route not found\".\n * Discriminate by `code` for behavior; reach for `status` only when\n * you genuinely need the wire value.\n */\n readonly status?: number;\n\n constructor(\n code: BaerlyErrorCode,\n message: string,\n cause?: unknown,\n issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>,\n status?: number,\n ) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = cause;\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (issues !== undefined) {\n this.issues = issues;\n }\n // Stryker disable next-line ConditionalExpression: field declaration creates property with undefined value; mutation to true is equivalent\n if (status !== undefined) {\n this.status = status;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgIA,IAAa,cAAb,cAAiC,MAAM;CACrC;CACA;;;;;;;;;;;CAWA;;;;;;;;;;CAaA;CAEA,YACE,MACA,SACA,OACA,QAIA,QACA;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EAEb,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;CAElB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fsck-CPPZWt9p.js","names":[],"sources":["../packages/cli/src/admin/fsck.ts"],"sourcesContent":["/**\n * `baerly admin fsck` — consistency walk for one collection.\n *\n * Default mode (no `--indexes`): read-only checks against the\n * snapshot + log tail.\n * 1. `current.json` exists at the expected key and parses.\n * 2. When `current.snapshot !== null`, the snapshot body's\n * SHA-256 matches the hash embedded in the filename\n * (delegated to `loadSnapshotAsMap`).\n * 3. The log range `[log_seq_start, next_seq)` has no holes —\n * every `log/<seq>.json` is present (HEAD-cheap LIST scan).\n * 4. Every entry inside the live tail is well-formed JSON with\n * the locked `op`, `collection`, and `doc_id` fields.\n *\n * `--indexes` + `--config=<path>` mode: SKIP the snapshot + log\n * walks and ONLY check each declared index for drift via\n * `rebuildIndex(..., { dryRun: true })`. Drift is `(added > 0)`\n * (rows that should be projected but have no key on storage) or\n * `(removed > 0)` (orphan keys for rows that no longer match).\n * Read-only.\n *\n * `--indexes --fix`: same drift walk but with `dryRun: false`, so\n * `rebuildIndex` PUTs missing keys and DELETEs orphans. The findings\n * downgrade from `warning` to `info` (drift was found AND fixed in\n * one pass). `--fix` without `--indexes` is rejected — fsck has no\n * auto-fix outside the index check.\n *\n * Exit codes:\n * 0 — all checks pass.\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag,\n * `--fix` without `--indexes`).\n * 2 — Storage / Network error during the walk.\n * 3 — Protocol invariant violation surfaced by the kernel\n * (Internal / InvalidResponse) — distinguished from exit 4\n * so CI can wire fsck as a regression gate.\n * 4 — One or more findings (orphan / hole / hash-mismatch /\n * index drift). Unique to this command; the other\n * `baerly admin` subcommands reserve 0–3.\n */\n\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { type ArgsDef } from \"citty\";\nimport {\n type BaerlyConfig,\n BaerlyError,\n type IndexDefinition,\n readCurrentJson,\n type Storage,\n} from \"@baerly/protocol\";\nimport { loadSnapshotAsMap } from \"@baerly/server\";\nimport { rebuildIndex } from \"@baerly/server/maintenance\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst FSCK_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n config: {\n type: \"string\",\n required: false,\n description:\n \"Path to baerly.config.{js,mjs,json}. Required with --indexes; resolves index definitions.\",\n valueHint: \"path\",\n },\n indexes: {\n type: \"boolean\",\n description:\n \"Skip snapshot + log walks; check declared indexes for drift via rebuildIndex (read-only by default).\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"With --indexes, rebuild drifted indexes (PUT missing keys, DELETE orphans). Rejected without --indexes.\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\ntype Severity = \"ok\" | \"info\" | \"warning\" | \"finding\";\ninterface Finding {\n readonly severity: Severity;\n readonly check: string;\n readonly message: string;\n readonly key?: string;\n}\n\n/** Severities that count toward the exit-4 \"findings present\" status. */\nconst isFindingSeverity = (s: Severity): boolean => s === \"finding\" || s === \"warning\";\n\nconst loadConfigIndexes = async (\n configPath: string,\n collection: string,\n): Promise<readonly IndexDefinition[]> => {\n if (configPath.endsWith(\".ts\")) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config must point at compiled JS / JSON (got .ts: ${JSON.stringify(configPath)})`,\n );\n }\n let cfg: BaerlyConfig;\n if (configPath.endsWith(\".json\")) {\n const { readFile } = await import(\"node:fs/promises\");\n const text = await readFile(configPath, \"utf8\");\n try {\n cfg = JSON.parse(text) as BaerlyConfig;\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config JSON parse error in ${JSON.stringify(configPath)}: ${(error as Error).message}`,\n );\n }\n } else {\n const pathMod = await import(\"node:path\");\n const abs = configPath.startsWith(\"file://\")\n ? fileURLToPath(configPath)\n : pathMod.resolve(configPath);\n const mod = (await import(pathToFileURL(abs).href)) as { default?: BaerlyConfig };\n if (mod.default === undefined) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: --config ${JSON.stringify(configPath)} has no default export`,\n );\n }\n cfg = mod.default;\n }\n const def = cfg.collections?.[collection];\n return def?.indexes ?? [];\n};\n\nconst listKeys = async (storage: Storage, prefix: string): Promise<string[]> => {\n const out: string[] = [];\n for await (const entry of storage.list(prefix)) {\n out.push(entry.key);\n }\n return out.toSorted();\n};\n\nconst statusLine = (label: string, ok: boolean, detail: string): string =>\n ` ${label.padEnd(22)}${ok ? \"ok\" : \"error\"} ${detail}`.trimEnd();\n\ninterface IndexSummary {\n readonly name: string;\n readonly added: number;\n readonly removed: number;\n readonly kept: number;\n readonly rebuilt: boolean;\n}\n\nconst renderSnapshotLog = (\n collection: string,\n findings: readonly Finding[],\n context: {\n readonly logRange: readonly [number, number];\n readonly logEntriesPresent: number;\n readonly snapshotKey: string | null;\n },\n): string => {\n const lines: string[] = [];\n lines.push(`baerly admin fsck ${collection}`);\n const [from, toExcl] = context.logRange;\n const byCheck = new Map<string, Finding[]>();\n for (const f of findings) {\n const arr = byCheck.get(f.check) ?? [];\n arr.push(f);\n byCheck.set(f.check, arr);\n }\n lines.push(statusLine(\"current.json:\", (byCheck.get(\"current.json\") ?? []).length === 0, \"\"));\n lines.push(\n statusLine(\n \"snapshot hash:\",\n (byCheck.get(\"snapshot\") ?? []).length === 0,\n context.snapshotKey === null ? \"(no snapshot yet)\" : `(sha256 verified)`,\n ),\n );\n lines.push(\n statusLine(\n `log range [${from},${toExcl}):`,\n (byCheck.get(\"log\") ?? []).length === 0,\n `(${context.logEntriesPresent}/${toExcl - from} entries present)`,\n ),\n );\n lines.push(` status: ${findings.some(isFindingFinding) ? \"findings\" : \"ok\"}`);\n for (const f of findings) {\n lines.push(` ${f.check}: ${f.message}${f.key !== undefined ? ` (key=${f.key})` : \"\"}`);\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst renderIndexes = (\n collection: string,\n findings: readonly Finding[],\n summaries: readonly IndexSummary[],\n fix: boolean,\n): string => {\n const lines: string[] = [];\n lines.push(`baerly admin fsck ${collection} --indexes${fix ? \" --fix\" : \"\"}`);\n for (const s of summaries) {\n const verb = s.rebuilt ? \"rebuilt\" : \"would rebuild\";\n if (s.added === 0 && s.removed === 0) {\n lines.push(` ${s.name}: in sync (${s.kept} keys)`);\n } else {\n lines.push(` ${s.name}: ${verb} — added ${s.added}, removed ${s.removed}, kept ${s.kept}`);\n }\n }\n lines.push(` status: ${findings.some(isFindingFinding) ? \"findings\" : \"ok\"}`);\n for (const f of findings) {\n if (f.check === \"log\" || f.check === \"snapshot\" || f.check === \"current.json\") {\n continue;\n }\n lines.push(` ${f.check}: ${f.message}${f.key !== undefined ? ` (key=${f.key})` : \"\"}`);\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst isFindingFinding = (f: Finding): boolean => isFindingSeverity(f.severity);\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.fsck\",\n meta: {\n description: \"Read-only consistency walk for one collection.\",\n },\n args: FSCK_ARGS,\n handler: async (args, ctx) => {\n const indexMode = args.indexes === true;\n const fixMode = args.fix === true;\n if (fixMode && !indexMode) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin fsck: --fix is only valid with --indexes (fsck has no auto-fix outside the index check)\",\n );\n }\n if (indexMode && (args.config === undefined || args.config.length === 0)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"baerly admin fsck: --indexes requires --config=<path> to resolve index definitions\",\n );\n }\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const bucket = await parseBucketUri(args.bucket);\n const collectionPrefix = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}`;\n const currentJsonKey = `${collectionPrefix}/current.json`;\n\n const findings: Finding[] = [];\n\n if (indexMode) {\n // ── Index drift mode. ──────────────────────────────────────────\n // Skip snapshot + log walks. For each declared index, call\n // `rebuildIndex(..., { dryRun: !fix })` — it returns the\n // `(added, removed, kept)` triple we need to call drift.\n const defs = await loadConfigIndexes(args.config!, args.collection);\n const summaries: IndexSummary[] = [];\n for (const def of defs) {\n const check = `index.${def.name}`;\n let result;\n try {\n result = await rebuildIndex(bucket.storage, currentJsonKey, def, {\n dryRun: !fixMode,\n });\n } catch (error) {\n findings.push({\n severity: \"finding\",\n check,\n message: `${def.name}: drift check failed: ${(error as Error).message}`,\n });\n continue;\n }\n const summary: IndexSummary = {\n name: def.name,\n added: result.added,\n removed: result.removed,\n kept: result.kept,\n rebuilt: fixMode,\n };\n summaries.push(summary);\n const drifted = result.added > 0 || result.removed > 0;\n if (!drifted) {\n findings.push({\n severity: \"ok\",\n check,\n message: `${def.name}: in sync (${result.kept} keys).`,\n });\n } else if (fixMode) {\n findings.push({\n severity: \"info\",\n check,\n message: `${def.name}: rebuilt — added ${result.added}, removed ${result.removed}, kept ${result.kept}.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check,\n message: `${def.name}: drift detected — ${result.added} missing, ${result.removed} orphaned (${result.kept} in sync).`,\n });\n }\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.fsck\",\n status: findings.some(isFindingFinding) ? \"findings\" : \"ok\",\n collection: args.collection,\n mode: fixMode ? \"indexes-fix\" : \"indexes\",\n indexes: summaries,\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.key !== undefined && { key: f.key }),\n })),\n });\n } else {\n process.stdout.write(renderIndexes(args.collection, findings, summaries, fixMode));\n }\n return findings.some(isFindingFinding) ? 4 : 0;\n }\n\n // ── Default mode. current.json + snapshot + log walks. ─────────\n const read = await readCurrentJson(bucket.storage, currentJsonKey);\n if (read === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin fsck: current.json not found at ${currentJsonKey}`,\n );\n }\n const cur = read.json;\n const logFrom = cur.log_seq_start ?? 0;\n const logToExcl = cur.next_seq;\n const snapshotKey = cur.snapshot;\n\n // ── Snapshot hash verifies (loadSnapshotAsMap throws on mismatch). ──\n if (snapshotKey !== null) {\n try {\n await loadSnapshotAsMap(bucket.storage, snapshotKey, args.collection);\n } catch (error) {\n if (\n error instanceof BaerlyError &&\n (error.code === \"Internal\" || error.code === \"InvalidResponse\")\n ) {\n findings.push({\n severity: \"finding\",\n check: \"snapshot\",\n message: error.message,\n key: snapshotKey,\n });\n } else {\n throw error;\n }\n }\n }\n\n // ── Log range [from, toExcl) has no holes; entries well-formed. ──\n // LIST the log/ prefix; expect exactly `toExcl - from` keys named\n // `${from}.json` … `${toExcl - 1}.json`. Use a single LIST so the\n // op count is O(pages) not O(range).\n const logPrefix = `${collectionPrefix}/log/`;\n const presentKeys = await listKeys(bucket.storage, logPrefix);\n const presentSeqs = new Set<number>();\n for (const key of presentKeys) {\n const tail = key.slice(logPrefix.length);\n const match = /^(\\d+)\\.json$/.exec(tail);\n if (match === null) {\n continue;\n }\n const seq = Number.parseInt(match[1]!, 10);\n if (Number.isFinite(seq)) {\n presentSeqs.add(seq);\n }\n }\n let logEntriesPresent = 0;\n for (let s = logFrom; s < logToExcl; s++) {\n if (presentSeqs.has(s)) {\n logEntriesPresent++;\n } else {\n findings.push({\n severity: \"finding\",\n check: \"log\",\n message: `missing log entry at seq ${s} inside [log_seq_start, next_seq)`,\n key: `${logPrefix}${s}.json`,\n });\n }\n }\n\n if (isJsonMode()) {\n emitSuccess({\n command: \"admin.fsck\",\n status: findings.some(isFindingFinding) ? \"findings\" : \"ok\",\n collection: args.collection,\n current_json_key: currentJsonKey,\n snapshot: snapshotKey,\n log_range: { from: logFrom, to_excl: logToExcl, present: logEntriesPresent },\n findings: findings.map((f) => ({\n severity: f.severity,\n check: f.check,\n message: f.message,\n ...(f.key !== undefined && { key: f.key }),\n })),\n });\n } else {\n process.stdout.write(\n renderSnapshotLog(args.collection, findings, {\n logRange: [logFrom, logToExcl],\n logEntriesPresent,\n snapshotKey,\n }),\n );\n }\n return findings.some(isFindingFinding) ? 4 : 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin fsck`. */\nexport const fsckCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runFsck = bundle.run;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAu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,KAAK,GAAG,YAAY,EAAE;EACxB,CAAC;EAIL,IAAI,WAAW,GACb,YAAY;GACV,SAAS;GACT,QAAQ,SAAS,KAAK,gBAAgB,IAAI,aAAa;GACvD,YAAY,KAAK;GACjB,kBAAkB;GAClB,UAAU;GACV,WAAW;IAAE,MAAM;IAAS,SAAS;IAAW,SAAS;GAAkB;GAC3E,UAAU,SAAS,KAAK,OAAO;IAC7B,UAAU,EAAE;IACZ,OAAO,EAAE;IACT,SAAS,EAAE;IACX,GAAI,EAAE,QAAQ,KAAA,KAAa,EAAE,KAAK,EAAE,IAAI;GAC1C,EAAE;EACJ,CAAC;OAED,QAAQ,OAAO,MACb,kBAAkB,KAAK,YAAY,UAAU;GAC3C,UAAU,CAAC,SAAS,SAAS;GAC7B;GACA;EACF,CAAC,CACH;EAEF,OAAO,SAAS,KAAK,gBAAgB,IAAI,IAAI;CAC/C;AACF,CAAC;;AAGD,MAAa,UAAU,OAAO;AAOP,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"http-Cw8p6y5b.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":["../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/compose.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request/constants.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/body.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/url.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/request.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/html.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/context.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/utils/constants.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/hono-base.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/router/pattern-router/router.js","../node_modules/.pnpm/hono@4.12.23/node_modules/hono/dist/preset/tiny.js","../packages/server/src/http/since.ts","../packages/server/src/http/router.ts"],"sourcesContent":["// 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`, lists the\n * log keys strictly-greater than the cursor's key, GETs each body,\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` plus one `Storage.get`\n * per log entry yielded. An idle reader (no new entries) pays one\n * Class A op per inner poll; with the production defaults\n * (25 s / 1 s) that is 25 ops per active connection. The\n * `< 1 Class A op / writer / hour` cost-model bound (see\n * `docs/spec/sync-protocol.md`) is for an *idle* reader — i.e. a\n * client that is *not* currently holding a long-poll open.\n * Subscribers paying for real-time-ish delivery are by definition\n * non-idle.\n */\n\nimport {\n type BaerlyConfig,\n BaerlyError,\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\n * `packages/server/src/writer.ts`) and described on\n * {@link LogEntry.lsn} — `<base32-time>_<session>_<seq>` where\n * base-32 is `[0-9a-v]` and the trailing seq is two characters.\n * Mirrored from `tests/integration/log-emit.test.ts:77`.\n */\nconst LSN_RE = /^[0-9a-v]+_[0-9a-v]+_[0-9a-v]{2}$/;\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. 25 polls × 1 list = 25 Class A\n * ops per active long-poll connection. 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 const nextSeq = read.json.next_seq;\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 `next_seq` (no entries past the tail exist) and\n // at `DEFAULT_MAX_EVENTS` (hard ceiling per the module docstring).\n const endSeq = Math.min(nextSeq, 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} 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, 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(\"SchemaError\", \"GET /v1/count requires ?collection=<name>\");\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(\"SchemaError\", `Request body must be { ${field}: object }`);\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(\"SchemaError\", \"Invalid JSON in ?where=\");\n }\n return validateWire(parsed as PredicateWire);\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(\"SchemaError\", \"Invalid JSON in ?order=\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BaerlyError(\"SchemaError\", \"?order= must encode a JSON object\");\n }\n return parsed as OrderSpec<DocumentData>;\n}\n\nconst 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 // NetworkError, InvalidResponse, Internal → 500\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 (currently unmapped codes fall\n * through to 500 by design — see the `NetworkError` / `InvalidResponse`\n * / `Internal` comment in `ERROR_TO_STATUS`).\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 status = ERROR_TO_STATUS.get(err.code) ?? 500;\n return { status, envelope: errorEnvelope(err.code, err.message, err.issues) };\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(\"SchemaError\", \"Empty request body\");\n }\n try {\n return JSON.parse(raw);\n } catch {\n throw new BaerlyError(\"SchemaError\", \"Invalid JSON in request body\");\n }\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11],"mappings":";;;;;;;AACA,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,WAAW,IAAI;IACjB,UAAU,WAAW,GAAG,GAAG;IAC3B,QAAQ,IAAI,aAAa;GAC3B,OACE,UAAU,MAAM,WAAW,UAAU,QAAQ,KAAK;GAEpD,IAAI,SACF,IAAI;IACF,MAAM,MAAM,QAAQ,eAAe,SAAS,IAAI,CAAC,CAAC;GACpD,SAAS,KAAK;IACZ,IAAI,eAAe,SAAS,SAAS;KACnC,QAAQ,QAAQ;KAChB,MAAM,MAAM,QAAQ,KAAK,OAAO;KAChC,UAAU;IACZ,OACE,MAAM;GAEV;QAEA,IAAI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AY,mBAAmB,gBAAgB,SAAS,OAAO;CAE7E;CAMA,IAAI;CACJ,IAAI;EACF,MAAM,SAAS,MAAM,EAAE,IAAI,YAAY;EACvC,IAAI,OAAO,aAAa,UACtB,MAAM,IAAI,YAAY,mBAAmB,gBAAgB,SAAS,OAAO;EAE3E,MAAM,IAAI,YAAY,EAAE,OAAO,MAAM;CACvC,SAAS,OAAO;EACd,IAAI,iBAAiB,aACnB,MAAM;EAER,MAAM,IAAI,YACR,eACA,gCAAgC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACvF;CACF;CACA,IAAI,IAAI,WAAW,GACjB,MAAM,IAAI,YAAY,eAAe,oBAAoB;CAE3D,IAAI;EACF,OAAO,KAAK,MAAM,GAAG;CACvB,QAAQ;EACN,MAAM,IAAI,YAAY,eAAe,8BAA8B;CACrE;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"inspect-Bdbzvi-_.js","names":[],"sources":["../packages/cli/src/inspect.ts"],"sourcesContent":["/**\n * `baerly inspect` — read-only summary for one collection.\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --config Optional path to baerly.config.{js,mjs,json} for index info.\n * --json JSON envelope.\n *\n * Reports, per-collection:\n * - currentJsonKey path.\n * - schema_version, next_seq, log_seq_start (default 0).\n * - live_log_tail (= next_seq - log_seq_start).\n * - snapshot key (or null).\n * - writer_fence (epoch, owner, claimed_at).\n * - materialised row count (via export/loadMaterialisedView).\n * - per-declared-index key count (when --config supplied).\n * - well-formed status: \"ok\" or \"error\" with an `errors` array.\n *\n * For projected monthly Class A / $ trajectories, use\n * `baerly cost --collection=<name>` — the projection used to live as a\n * footer here but moved to its own verb so inspect stays a glance\n * command (no GET-storm over the trailing log sample).\n *\n * Cost shape:\n * 1 GET current.json\n * + 1 GET snapshot (if any)\n * + N GETs log tail (= next_seq - log_seq_start)\n * + K LISTs (one per declared index, when --config supplied)\n * + 1 LIST snapshot/ prefix (orphan detection)\n *\n * Never mutates anything.\n *\n * Exit codes:\n * 0 — inspection ran (status may be \"ok\" or \"error\"; both exit 0).\n * 1 — InvalidConfig (bad bucket URI, missing args, unknown flag).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, readCurrentJson, type CurrentJson, type Storage } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"./export/index.ts\";\nimport { loadCollectionIndexes } from \"./config.ts\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst INSPECT_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n config: {\n type: \"string\",\n required: false,\n description:\n \"Path to baerly.config.{js,mjs,json}; pulls declared indexes for key-count probes.\",\n valueHint: \"path\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst countListEntries = async (\n storage: Storage,\n prefix: string,\n): Promise<{ count: number; keys: string[] }> => {\n let count = 0;\n const keys: string[] = [];\n for await (const entry of storage.list(prefix)) {\n count++;\n keys.push(entry.key);\n }\n return { count, keys };\n};\n\ninterface InspectResult {\n currentJsonKey: string;\n schema_version: number;\n next_seq: number;\n log_seq_start: number;\n live_log_tail: number;\n snapshot: string | null;\n writer_fence: CurrentJson[\"writer_fence\"];\n materialised_rows: number;\n indexes: { name: string; count: number }[];\n status: \"ok\" | \"error\";\n errors: string[];\n}\n\nconst renderText = (r: InspectResult, collection: string): string => {\n const lines: string[] = [];\n lines.push(`baerly inspect ${collection}`);\n lines.push(` current.json: ${r.currentJsonKey}`);\n lines.push(` schema_version: ${r.schema_version}`);\n lines.push(` next_seq: ${r.next_seq}`);\n lines.push(` log_seq_start: ${r.log_seq_start}`);\n lines.push(` live_log_tail: ${r.live_log_tail}`);\n lines.push(` snapshot: ${r.snapshot ?? \"(none)\"}`);\n lines.push(\n ` writer_fence: epoch=${r.writer_fence.epoch} owner=${JSON.stringify(r.writer_fence.owner)} claimed_at=${JSON.stringify(r.writer_fence.claimed_at)}`,\n );\n lines.push(` materialised_rows: ${r.materialised_rows}`);\n if (r.indexes.length > 0) {\n const formatted = r.indexes.map((i) => `${i.name} (count=${i.count})`).join(\", \");\n lines.push(` indexes: ${formatted}`);\n } else {\n lines.push(` indexes: (none declared)`);\n }\n lines.push(` status: ${r.status}`);\n if (r.errors.length > 0) {\n for (const e of r.errors) {\n lines.push(` error: ${e}`);\n }\n }\n return lines.join(\"\\n\") + \"\\n\";\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"inspect\",\n meta: {\n description: \"Read-only summary of one collection's snapshot + log state.\",\n },\n args: INSPECT_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const collectionPrefix = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}`;\n const currentJsonKey = `${collectionPrefix}/current.json`;\n\n const read = await readCurrentJson(bucket.storage, currentJsonKey);\n if (read === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly inspect: current.json not found at ${currentJsonKey}`,\n );\n }\n const cur = read.json;\n const log_seq_start = cur.log_seq_start ?? 0;\n\n const errors: string[] = [];\n let materialisedRows = 0;\n try {\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n materialisedRows = view?.size ?? 0;\n } catch (error) {\n if (error instanceof BaerlyError) {\n errors.push(`${error.code}: ${error.message}`);\n } else {\n errors.push((error as Error).message);\n }\n }\n\n // Orphan-snapshot detection: list every file under <collectionPrefix>/snapshot/\n // and flag anything that isn't the currently-pointed-at snapshot.\n try {\n const snapshotPrefix = `${collectionPrefix}/snapshot/`;\n const { keys } = await countListEntries(bucket.storage, snapshotPrefix);\n for (const k of keys) {\n if (cur.snapshot !== k) {\n errors.push(`orphan snapshot: ${k}`);\n }\n }\n } catch (error) {\n if (error instanceof BaerlyError) {\n errors.push(`${error.code}: ${error.message}`);\n }\n }\n\n const indexes: { name: string; count: number }[] = [];\n if (typeof args.config === \"string\" && args.config.length > 0) {\n const defs = await loadCollectionIndexes(args.config, args.collection, \"baerly inspect\");\n for (const def of defs) {\n const prefix = `${collectionPrefix}/index/${def.name}/`;\n const { count } = await countListEntries(bucket.storage, prefix);\n indexes.push({ name: def.name, count });\n }\n }\n\n const result: InspectResult = {\n currentJsonKey,\n schema_version: cur.schema_version,\n next_seq: cur.next_seq,\n log_seq_start,\n live_log_tail: cur.next_seq - log_seq_start,\n snapshot: cur.snapshot,\n writer_fence: cur.writer_fence,\n materialised_rows: materialisedRows,\n indexes,\n status: errors.length === 0 ? \"ok\" : \"error\",\n errors,\n };\n\n if (isJsonMode()) {\n emitSuccess({ command: \"inspect\", ...result });\n } else {\n process.stdout.write(renderText(result, args.collection));\n }\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly inspect`. */\nexport const inspect = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runInspect = bundle.run;\n"],"mappings":";;;;;;AAkDA,MAAM,eAAe;CACnB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;E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