@gusto/baerly-storage 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +29 -0
  3. package/README.md +93 -52
  4. package/dist/API.md +151 -109
  5. package/dist/CHANGELOG.md +144 -0
  6. package/dist/THIRD-PARTY-LICENSES.txt +312 -0
  7. package/dist/{app-config-C0Bbw_Z6.d.ts → app-config-BIzyAKzy.d.ts} +14 -2
  8. package/dist/app-config.d.ts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.js +288 -288
  11. package/dist/auth.js.map +1 -1
  12. package/dist/baerly.js +10 -10
  13. package/dist/baerly.js.map +1 -1
  14. package/dist/bytes-BXdamO3L.js.map +1 -1
  15. package/dist/{client-DYZfoZb9.d.ts → client-BJXF3XJA.d.ts} +10 -10
  16. package/dist/client-react.d.ts +3 -3
  17. package/dist/client-react.js.map +1 -1
  18. package/dist/client.d.ts +3 -3
  19. package/dist/client.js.map +1 -1
  20. package/dist/{cloudflare-CINJPKCW.js → cloudflare-Cn2ibODt.js} +178 -2
  21. package/dist/cloudflare-Cn2ibODt.js.map +1 -0
  22. package/dist/cloudflare.d.ts +4 -4
  23. package/dist/cloudflare.js +10 -11
  24. package/dist/cloudflare.js.map +1 -1
  25. package/dist/{subcommand-DZcHcsYp.js → config-CGyBopy3.js} +643 -439
  26. package/dist/config-CGyBopy3.js.map +1 -0
  27. package/dist/context-DRZ3tZ5l.js.map +1 -1
  28. package/dist/{cost-CQt1YRkA.js → cost-BZ_MDBmn.js} +6 -4
  29. package/dist/cost-BZ_MDBmn.js.map +1 -0
  30. package/dist/{current-json-C-EyJqs0.js → current-json-DsN7FNY1.js} +47 -13
  31. package/dist/current-json-DsN7FNY1.js.map +1 -0
  32. package/dist/{db-BM3y2JQw.d.ts → db-CCT6tDfY.d.ts} +26 -108
  33. package/dist/{deploy-CrAbfgCq.js → deploy-BKKyGlSJ.js} +11 -4
  34. package/dist/deploy-BKKyGlSJ.js.map +1 -0
  35. package/dist/dev-vite.d.ts +5 -5
  36. package/dist/dev-vite.js +5 -5
  37. package/dist/dev-vite.js.map +1 -1
  38. package/dist/dev.d.ts +1 -1
  39. package/dist/dev.js +1 -1
  40. package/dist/{doctor-Db-hzPmE.js → doctor-BVU4GNXN.js} +13 -132
  41. package/dist/doctor-BVU4GNXN.js.map +1 -0
  42. package/dist/{dump-BYA55NLP.js → dump-DPEAKub6.js} +5 -3
  43. package/dist/dump-DPEAKub6.js.map +1 -0
  44. package/dist/errors-DOdL95kK.js.map +1 -1
  45. package/dist/{export-Bhbz90-z.js → export-BcuCLFFe.js} +6 -4
  46. package/dist/{export-Bhbz90-z.js.map → export-BcuCLFFe.js.map} +1 -1
  47. package/dist/{fsck-CPPZWt9p.js → fsck-RXgLOaJG.js} +23 -11
  48. package/dist/fsck-RXgLOaJG.js.map +1 -0
  49. package/dist/{http-Cw8p6y5b.js → http-Bd4byR4n.js} +45 -61
  50. package/dist/http-Bd4byR4n.js.map +1 -0
  51. package/dist/http.d.ts +15 -15
  52. package/dist/http.js +1 -1
  53. package/dist/{index-cUY-36AN.d.ts → index-BDceQQi-.d.ts} +20 -4
  54. package/dist/{index-C3JAH1Yo.d.ts → index-Cmsxx-ZN.d.ts} +9 -9
  55. package/dist/{index-DSvwEUeF.d.ts → index-DW7GT6M2.d.ts} +50 -42
  56. package/dist/{index-DwDTWPSU.d.ts → index-DnBGSeuU.d.ts} +10 -7
  57. package/dist/index.d.ts +6 -6
  58. package/dist/index.js +4 -4
  59. package/dist/{indexes-DAu2AkTW.d.ts → indexes-Cx7uMXm0.d.ts} +2 -2
  60. package/dist/{inspect-Bdbzvi-_.js → inspect-DhI49PSi.js} +16 -8
  61. package/dist/inspect-DhI49PSi.js.map +1 -0
  62. package/dist/{snapshot-SS8USDUF.js → log-tail-DXeDkWEp.js} +154 -83
  63. package/dist/log-tail-DXeDkWEp.js.map +1 -0
  64. package/dist/{maintenance-BRrThz8V.d.ts → maintenance-BkhUr72A.d.ts} +91 -26
  65. package/dist/{maintenance-ClzBC1Vv.js → maintenance-CWBQpZ2y.js} +368 -161
  66. package/dist/maintenance-CWBQpZ2y.js.map +1 -0
  67. package/dist/{maintenance-BvOv6BMM.js → maintenance-C_KSkVjd.js} +204 -82
  68. package/dist/maintenance-C_KSkVjd.js.map +1 -0
  69. package/dist/maintenance.d.ts +3 -2
  70. package/dist/maintenance.js +3 -2
  71. package/dist/node.d.ts +13 -8
  72. package/dist/node.js +1 -1
  73. package/dist/normalize-XWY25_sG.js.map +1 -1
  74. package/dist/{observability-CpOiEN0k.js → observability-BYd-RzEx.js} +63 -55
  75. package/dist/observability-BYd-RzEx.js.map +1 -0
  76. package/dist/observability.d.ts +3 -3
  77. package/dist/observability.js +1 -1
  78. package/dist/{plan-DOTl21vq.js → plan-DIu_B6fy.js} +7 -4
  79. package/dist/plan-DIu_B6fy.js.map +1 -0
  80. package/dist/{query-BmiQy328.js → query-sQNO5vU_.js} +1071 -1099
  81. package/dist/query-sQNO5vU_.js.map +1 -0
  82. package/dist/{rebuild-index-DC_nR6wP.js → rebuild-index-DP4CqSSs.js} +5 -4
  83. package/dist/rebuild-index-DP4CqSSs.js.map +1 -0
  84. package/dist/{restore-C6IcmLeA.js → restore-DpQYef6r.js} +362 -328
  85. package/dist/restore-DpQYef6r.js.map +1 -0
  86. package/dist/shared-secret-BJdSwpgw.js.map +1 -1
  87. package/dist/{src-QQ7jDeL2.js → src-CWpkSbvJ.js} +40 -20
  88. package/dist/src-CWpkSbvJ.js.map +1 -0
  89. package/dist/{src-DU1sCMlr.js → src-D24wDpzR.js} +269 -258
  90. package/dist/src-D24wDpzR.js.map +1 -0
  91. package/dist/{src-zhEAmmF7.js → src-Db4-qVtM.js} +36 -96
  92. package/dist/src-Db4-qVtM.js.map +1 -0
  93. package/dist/subcommand-CP9NY2J4.js +159 -0
  94. package/dist/subcommand-CP9NY2J4.js.map +1 -0
  95. package/dist/{usage-CLjirdD-.js → usage-CTfDq9HR.js} +3 -3
  96. package/dist/{usage-CLjirdD-.js.map → usage-CTfDq9HR.js.map} +1 -1
  97. package/dist/{validate-DCq_0DIn.js → validate-DtljsCh1.js} +51 -51
  98. package/dist/{validate-DCq_0DIn.js.map → validate-DtljsCh1.js.map} +1 -1
  99. package/package.json +40 -29
  100. package/dist/cloudflare-CINJPKCW.js.map +0 -1
  101. package/dist/config-DVfDGyw1.js +0 -278
  102. package/dist/config-DVfDGyw1.js.map +0 -1
  103. package/dist/cost-CQt1YRkA.js.map +0 -1
  104. package/dist/current-json-C-EyJqs0.js.map +0 -1
  105. package/dist/deploy-CrAbfgCq.js.map +0 -1
  106. package/dist/doctor-Db-hzPmE.js.map +0 -1
  107. package/dist/dump-BYA55NLP.js.map +0 -1
  108. package/dist/fsck-CPPZWt9p.js.map +0 -1
  109. package/dist/http-Cw8p6y5b.js.map +0 -1
  110. package/dist/inspect-Bdbzvi-_.js.map +0 -1
  111. package/dist/maintenance-BvOv6BMM.js.map +0 -1
  112. package/dist/maintenance-ClzBC1Vv.js.map +0 -1
  113. package/dist/observability-CpOiEN0k.js.map +0 -1
  114. package/dist/plan-DOTl21vq.js.map +0 -1
  115. package/dist/query-BmiQy328.js.map +0 -1
  116. package/dist/rebuild-index-DC_nR6wP.js.map +0 -1
  117. package/dist/restore-C6IcmLeA.js.map +0 -1
  118. package/dist/snapshot-SS8USDUF.js.map +0 -1
  119. package/dist/src-DU1sCMlr.js.map +0 -1
  120. package/dist/src-QQ7jDeL2.js.map +0 -1
  121. package/dist/src-zhEAmmF7.js.map +0 -1
  122. package/dist/subcommand-DZcHcsYp.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doctor-BVU4GNXN.js","names":[],"sources":["../packages/cli/src/doctor/cloudflare.ts","../packages/cli/src/doctor.ts"],"sourcesContent":["/**\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. Report `triggers.crons` as optional. In-band write-triggered\n * maintenance is the default; cron only drives an explicit\n * `runScheduledMaintenance` sweep when the operator opts in.\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 ok; in-band\n * write-triggered maintenance is the default and needs no cron.\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 (varKeys.has(\"CF_ACCESS_TEAM_DOMAIN\") && varKeys.has(\"CF_ACCESS_AUDIENCE_TAG\")) {\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 — optional. In-band write-tick maintenance is\n // the default; cron only exists for an explicit out-of-band sweep.\n const crons = readDeclaredCrons(wranglerPath);\n if (crons.length === 0) {\n findings.push({\n severity: \"ok\",\n check: \"triggers.crons\",\n message: \"no cron triggers declared; in-band write-triggered maintenance is the default.\",\n });\n } else {\n findings.push({\n severity: \"info\",\n check: \"triggers.crons\",\n message:\n `cron trigger${crons.length === 1 ? \"\" : \"s\"} ${crons.map((c) => JSON.stringify(c)).join(\", \")} declared ` +\n \"for opt-in scheduled maintenance; write-triggered maintenance still runs by default.\",\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,MAAM,gBAAgB,aAA+D;CACnF,IAAI,QAAgC;CACpC,KAAK,MAAM,KAAK,UAA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EAAE,QAAQ,KAAA,GACZ,QAAQ,OAAO,MAAM,aAAa,EAAE,IAAI,GAAG;EAE7C,IAAI,EAAE,aAAa,MACjB,WAAW;OACN,IAAI,EAAE,aAAa,WACxB,gBAAgB;OACX,IAAI,EAAE,aAAa,SACxB,cAAc;CAElB;CACA,QAAQ,OAAO,MACb,aAAa,WAAW,QAAQ,eAAe,IAAI,KAAK,IAAI,IAAI,aAAa,UAAU,iBAAiB,IAAI,KAAK,IAAI,IAAI,QAAQ,OACnI;AACF;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aACE,yFACJ;CACA,MAAM;CACN,SAAS,OAAO,SAAS;EAGvB,IAAI,KAAK,WAAW,KAAA,GAAW;GAC7B,MAAM,EAAE,SAAS,cAAc,MAAM,eAAe,KAAK,MAAM;GAC/D,MAAM,SAAS,MAAM,UAAU,SAAS,SAAS;GACjD,aAAa;IAAE,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,6 +1,7 @@
1
- import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
1
+ import { r as parseBucketUri } from "./config-CGyBopy3.js";
2
2
  import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
3
- import { n as loadMaterialisedView } from "./plan-DOTl21vq.js";
3
+ import { n as loadMaterialisedView } from "./plan-DIu_B6fy.js";
4
+ import { n as defineBaerlySubcommand, t as assertCollectionArg } from "./subcommand-CP9NY2J4.js";
4
5
  import "node:stream";
5
6
  //#region src/admin/dump.ts
6
7
  const DUMP_ARGS = {
@@ -89,6 +90,7 @@ const bundle = defineBaerlySubcommand({
89
90
  app: args.app,
90
91
  tenant: args.tenant
91
92
  });
93
+ assertCollectionArg(args.collection, "baerly admin dump");
92
94
  const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
93
95
  const view = await loadMaterialisedView({
94
96
  storage: bucket.storage,
@@ -112,4 +114,4 @@ bundle.run;
112
114
  //#endregion
113
115
  export { dumpCmd };
114
116
 
115
- //# sourceMappingURL=dump-BYA55NLP.js.map
117
+ //# sourceMappingURL=dump-DPEAKub6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dump-DPEAKub6.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 { assertCollectionArg, 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 assertCollectionArg(args.collection, \"baerly admin dump\");\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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,KAAK,WAAW;EACnG,MAAM,OAAO,MAAM,qBAAqB;GACtC,SAAS,OAAO;GAChB;GACA,YAAY,KAAK;EACnB,CAAC;EACD,IAAI,SAAS,MACX,MAAM,IAAI,YACR,iBACA,gDAAgD,gBAClD;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 +1 @@
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
+ {"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 400.\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,7 +1,8 @@
1
- import { n as matchesWire, t as validateWire } from "./validate-DCq_0DIn.js";
2
- import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
1
+ import { r as parseBucketUri } from "./config-CGyBopy3.js";
2
+ import { n as matchesWire, t as validateWire } from "./validate-DtljsCh1.js";
3
3
  import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
4
- import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-DOTl21vq.js";
4
+ import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-DIu_B6fy.js";
5
+ import { n as defineBaerlySubcommand, t as assertCollectionArg } from "./subcommand-CP9NY2J4.js";
5
6
  import { writeFile } from "node:fs/promises";
6
7
  //#region src/export/ddl.ts
7
8
  /**
@@ -367,6 +368,7 @@ const bundle = defineBaerlySubcommand({
367
368
  app: args.app,
368
369
  tenant: args.tenant
369
370
  });
371
+ assertCollectionArg(args.collection, "baerly export");
370
372
  const bucket = await parseBucketUri(args.bucket);
371
373
  const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
372
374
  const view = await loadMaterialisedView({
@@ -419,4 +421,4 @@ const describeNonObject = (v) => {
419
421
  //#endregion
420
422
  export { exportCmd };
421
423
 
422
- //# sourceMappingURL=export-Bhbz90-z.js.map
424
+ //# sourceMappingURL=export-BcuCLFFe.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"export-Bhbz90-z.js","names":[],"sources":["../packages/cli/src/export/ddl.ts","../packages/cli/src/export/rows.ts","../packages/cli/src/export/where.ts","../packages/cli/src/export/plan-sidecar.ts","../packages/cli/src/export.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\nimport type { ExportPlan } from \"./types.ts\";\n\n/**\n * Emit a `CREATE TABLE` statement for the plan, one line per column,\n * terminated with a semicolon + newline so the output is directly\n * pipeable into `psql` / `sqlite3` / `wrangler d1 execute`.\n *\n * `_id` is the primary key (always first in `plan.columns`).\n *\n * D1 today is sqlite-flavoured: same DDL as `target=sqlite` with a\n * single difference — D1 disallows table names starting with\n * `sqlite_`. We refuse them up front.\n */\nexport const emitCreateTable = (plan: ExportPlan): string => {\n if (plan.columns.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: collection ${JSON.stringify(plan.table)} has no observed columns — empty snapshot?`,\n );\n }\n if (plan.target === \"d1\" && plan.table.toLowerCase().startsWith(\"sqlite_\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: D1 reserves the sqlite_ table-name prefix (got ${JSON.stringify(plan.table)})`,\n );\n }\n const lines: string[] = [];\n lines.push(`CREATE TABLE ${plan.tableIdentifier} (`);\n const colLines: string[] = [];\n for (const col of plan.columns) {\n const nullClause = col.nullable ? \"\" : \" NOT NULL\";\n const pkClause = col.source === \"_id\" ? \" PRIMARY KEY\" : \"\";\n colLines.push(` ${col.identifier} ${col.sqlType}${nullClause}${pkClause}`);\n }\n lines.push(colLines.join(\",\\n\"));\n lines.push(\");\");\n return lines.join(\"\\n\") + \"\\n\";\n};\n","import type { DocumentValue } from \"@baerly/protocol\";\nimport type { ExportPlan, ExportRow } from \"./types.ts\";\nimport { quoteValue } from \"./sql-escape.ts\";\n\n/**\n * Emit one `INSERT INTO …` statement per row. The emitted SQL is\n * directly pipeable into `psql` / `sqlite3` / `wrangler d1\n * execute`. Per-row statements (not one big VALUES tuple) so a\n * mid-stream failure has bounded blast radius.\n *\n * For columns whose plan has `jsonEncoded: true`, the row's value\n * is JSON-stringified first and then string-quoted. Postgres\n * accepts a literal text JSON in a `jsonb` column. SQLite / D1 see\n * the JSON as plain TEXT.\n *\n * Rows are streamed via the async-iterable protocol so the export\n * never materialises the full SQL output in memory. The caller\n * concatenates the yielded chunks (or pipes them straight to disk\n * / stdout).\n */\nexport async function* emitInsertStatements(\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n): AsyncIterable<string> {\n const columnList = plan.columns.map((c) => c.identifier).join(\", \");\n // Iterate in `Map` insertion order — stable, and the snapshot\n // body itself sorts by `_id` (compactor.ts: `docs is sorted by\n // _id for deterministic byte output`).\n for (const [id, body] of rows) {\n const values: string[] = [];\n for (const col of plan.columns) {\n const raw: DocumentValue | undefined =\n col.source === \"_id\"\n ? (id as DocumentValue)\n : (body as Record<string, DocumentValue>)[col.source];\n if (raw === undefined) {\n values.push(\"NULL\");\n continue;\n }\n if (col.jsonEncoded) {\n const json = JSON.stringify(raw);\n values.push(quoteValue(json, plan.target));\n } else {\n values.push(quoteValue(raw, plan.target));\n }\n }\n yield `INSERT INTO ${plan.tableIdentifier} (${columnList}) VALUES (${values.join(\", \")});\\n`;\n }\n}\n","/**\n * Wire-predicate → SQL `WHERE` clause translation.\n *\n * Pure function. The translator consumes a validated\n * {@link PredicateWire} — the same shape the read path uses — and\n * an {@link ExportPlan} (from `./plan.ts`), and emits a SQL fragment\n * matched against the plan's columns.\n *\n * Three classes of clause:\n *\n * 1. Flat column, top-level field → direct comparator\n * (`\"status\" = 'open'`, `\"priority\" > 5`).\n * 2. JSON-encoded column → JSON-path operators (Postgres `->`/`->>`\n * chains; SQLite/D1 `json_extract(…, '$.…')`).\n * 3. Unmatchable clause (dotted path against a flat column, or a\n * field naming an unknown column) → `1 = 0` plus a hint the CLI\n * surfaces as a `-- TODO(baerly export):` comment above the\n * emitted statement.\n *\n * Dynamic predicates are invisible at runtime — we see the\n * materialised wire, not the source expression. Callers that know\n * they constructed the wire dynamically can pass\n * `options.dynamicHint` to surface an operator-supplied note.\n */\n\nimport {\n BaerlyError,\n type DocumentValue,\n type PredicateClause,\n type PredicateWire,\n validateWire,\n} from \"@baerly/protocol\";\nimport { quoteValue } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget } from \"./types.ts\";\n\nexport interface WhereTranslation {\n /** SQL fragment without the leading `WHERE`. Empty when no predicate. */\n readonly sql: string;\n /**\n * Hand-edit hints for the operator. One entry per non-matchable\n * clause (§3.6) or per dynamically-constructed sub-clause flagged\n * by the caller. The CLI surfaces these as `-- TODO(baerly export): …`\n * comments above the emitted statement.\n */\n readonly hints: readonly string[];\n}\n\n/**\n * Translate a validated {@link PredicateWire} into a SQL WHERE-clause\n * fragment matched against the plan's columns. The first argument\n * must already have been validated by {@link validateWire} — the\n * function re-validates defensively but the caller's invariant\n * matters for error-message provenance.\n *\n * Pure function. No I/O. Same wire + plan + target → same SQL string.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — wire fails\n * {@link validateWire}; same shape `Query<T>.where` already\n * surfaces.\n */\nexport const translatePredicateWireToSql = (\n wire: PredicateWire,\n plan: ExportPlan,\n options?: { readonly dynamicHint?: string },\n): WhereTranslation => {\n validateWire(wire);\n const hints: string[] = [];\n if (options?.dynamicHint !== undefined && options.dynamicHint.length > 0) {\n hints.push(\n `caller-flagged dynamic predicate: ${options.dynamicHint}. Review the emitted SQL for completeness.`,\n );\n }\n const clauses: string[] = [];\n for (const clause of wire.clauses) {\n clauses.push(...clauseForWire(clause, plan, hints));\n }\n return {\n sql: clauses.length === 0 ? \"\" : clauses.join(\" AND \"),\n hints,\n };\n};\n\nconst clauseForWire = (clause: PredicateClause, plan: ExportPlan, hints: string[]): string[] => {\n const segments = clause.field.includes(\".\") ? clause.field.split(\".\") : [clause.field];\n const head = segments[0];\n if (head === undefined || head.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: empty field path encountered (defensive)\",\n );\n }\n const col = plan.columns.find((c) => c.source === head);\n if (col === undefined) {\n hints.push(\n `predicate field ${JSON.stringify(clause.field)} references a key never observed in the snapshot; this clause cannot match.`,\n );\n return [\"1 = 0\"];\n }\n // §3.2 — flat column, top-level field → direct comparator.\n if (!col.jsonEncoded && segments.length === 1) {\n return [flatColumnClause(col.identifier, clause, plan.target)];\n }\n // §3.6 — flat column, dotted path → unmatchable.\n if (!col.jsonEncoded && segments.length > 1) {\n hints.push(\n `predicate path ${JSON.stringify(clause.field)} addresses a flat column; this clause cannot match. Hand-edit if intended.`,\n );\n return [\"1 = 0\"];\n }\n // §3.3 — JSON column, top-level field.\n if (col.jsonEncoded && segments.length === 1) {\n return [jsonColumnRootClause(col, clause, plan.target)];\n }\n // §3.4 / §3.5 — JSON column, dotted path.\n return [jsonPathClause(col, segments.slice(1), clause, plan.target)];\n};\n\nconst flatColumnClause = (\n identifier: string,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n switch (clause.op) {\n case \"eq\": {\n return `${identifier} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${identifier} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${identifier} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${identifier} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${identifier} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${identifier} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst jsonColumnRootClause = (\n col: ColumnPlan,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n // The root JSON column stores the value as JSON-encoded text;\n // we compare against the JSON encoding of the predicate value.\n // Range and `in` ops on a JSON-encoded root column compare the\n // JSON text lexicographically, which is rarely what the caller\n // wanted — for those, the operator is expected to promote the\n // field into a flat column or hand-edit the emitted SQL.\n if (clause.op === \"eq\") {\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text = ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} = ${quoteValue(literal, target)}`;\n }\n if (clause.op === \"in\") {\n const literals = (clause.value as ReadonlyArray<DocumentValue>).map((v) =>\n quoteValue(JSON.stringify(v), target),\n );\n if (target === \"postgres\") {\n return `${col.identifier}::text IN (${literals.join(\", \")})`;\n }\n return `${col.identifier} IN (${literals.join(\", \")})`;\n }\n // Range against JSON-encoded root: fall back to a lex compare on\n // the JSON serialisation. Surface a comment via the SQL itself;\n // the operator can hand-edit.\n const comparator = rangeComparator(clause.op);\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text ${comparator} ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} ${comparator} ${quoteValue(literal, target)}`;\n};\n\nconst jsonPathClause = (\n col: ColumnPlan,\n tail: readonly string[],\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n const accessor = jsonPathAccessor(col.identifier, tail, target);\n switch (clause.op) {\n case \"eq\": {\n return `${accessor} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${accessor} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${accessor} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${accessor} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${accessor} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${accessor} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst rangeComparator = (op: PredicateClause[\"op\"]): string => {\n if (op === \"gt\") {\n return \">\";\n }\n if (op === \"gte\") {\n return \">=\";\n }\n if (op === \"lt\") {\n return \"<\";\n }\n return \"<=\";\n};\n\nconst jsonPathAccessor = (\n identifier: string,\n tail: readonly string[],\n target: SqlTarget,\n): string => {\n if (target === \"postgres\") {\n let expr = identifier;\n for (let i = 0; i < tail.length; i++) {\n const seg = tail[i]!;\n const isLast = i === tail.length - 1;\n const key = `'${seg.replace(/'/g, \"''\")}'`;\n expr = `${expr}${isLast ? \"->>\" : \"->\"}${key}`;\n }\n return expr;\n }\n const jsonPath = `'$.${tail.map((s) => s.replace(/'/g, \"''\")).join(\".\")}'`;\n return `json_extract(${identifier}, ${jsonPath})`;\n};\n\n/**\n * Quote a leaf primitive for use as the right-hand side of a\n * comparison. Booleans branch on target. Nested objects must never\n * reach here — wire `eq` clauses on nested objects can only come\n * from the callback form `q.eq(\"nested\", { ... })`, which the\n * export translator does not support today.\n */\nconst quoteLeaf = (value: DocumentValue, target: SqlTarget): string => {\n if (typeof value === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: nested object reached leaf quoter — callback-form q.eq(field, object) is not supported for SQL export. Hand-edit the emitted SQL.\",\n );\n }\n return quoteValue(value, target);\n};\n","/**\n * Sidecar plan serialisation for `baerly export`.\n *\n * `baerly export --output=foo.sql` writes the inferred {@link ExportPlan}\n * alongside the SQL dump as `foo.sql.plan.json`. The round-trip test\n * (`tests/integration/export-round-trip.test.ts`) consumes the sidecar\n * to coerce SQLite-returned values back to their original JS type\n * (e.g. SQLite stores booleans as 0/1; we restore `true`/`false`).\n *\n * Wire shape (`schemaVersion = 1`):\n *\n * ```json\n * {\n * \"schemaVersion\": 1,\n * \"table\": \"tickets\",\n * \"target\": \"sqlite\",\n * \"columns\": [\n * { \"source\": \"_id\", \"sqlType\": \"TEXT\", \"nullable\": false, \"jsonEncoded\": false },\n * ...\n * ]\n * }\n * ```\n *\n * `identifier` is NOT carried on the wire — we re-derive it via\n * {@link quoteIdentifier} on deserialise. An attacker writing the\n * sidecar should not get SQL-emit control over identifiers.\n *\n * `rowCount` is also not preserved across the sidecar boundary; the\n * deserialised plan reports `0`. This is intentional — consumers that\n * care about row count read the SQL stream itself.\n */\n\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { quoteIdentifier } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget, SqlType } from \"./types.ts\";\n\nconst SIDECAR_SCHEMA_VERSION = 1 as const;\n\nconst VALID_TARGETS: ReadonlySet<string> = new Set([\"postgres\", \"sqlite\", \"d1\"]);\n\nconst VALID_SQL_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"boolean\",\n \"integer\",\n \"double precision\",\n \"jsonb\",\n \"TEXT\",\n \"INTEGER\",\n \"REAL\",\n]);\n\n/**\n * Encode an {@link ExportPlan} as the canonical sidecar JSON string.\n *\n * Wire format is pretty-printed (`indent=2`) with a trailing newline\n * so `cat sidecar.plan.json` is human-readable and `diff` works on\n * two sidecars without spurious line-end noise. The on-wire bytes\n * embed the `schemaVersion` discriminator so future shape changes\n * are detectable; `identifier` and `tableIdentifier` are NOT carried\n * (they're re-derived via {@link quoteIdentifier} on deserialise).\n */\nexport const serializeExportPlan = (plan: ExportPlan): string => {\n return (\n JSON.stringify(\n {\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n table: plan.table,\n target: plan.target,\n columns: plan.columns.map((c) => ({\n source: c.source,\n sqlType: c.sqlType,\n nullable: c.nullable,\n jsonEncoded: c.jsonEncoded,\n })),\n },\n null,\n 2,\n ) + \"\\n\"\n );\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Parse the sidecar JSON string back into an {@link ExportPlan}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when the sidecar JSON is\n * malformed, the schema version is unsupported, or any required\n * field is missing / has an unexpected type. Identifiers are\n * re-quoted via {@link quoteIdentifier} rather than copied off the\n * wire — the sidecar cannot smuggle SQL-injection via a\n * pre-quoted identifier.\n */\nexport const deserializeExportPlan = (text: string): ExportPlan => {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: parse failed: ${(error as Error).message}`,\n );\n }\n if (!isObject(raw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"deserializeExportPlan: top-level value is not an object\",\n );\n }\n if (raw[\"schemaVersion\"] !== SIDECAR_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unsupported schemaVersion ${String(raw[\"schemaVersion\"])} (expected ${String(SIDECAR_SCHEMA_VERSION)})`,\n );\n }\n if (typeof raw[\"table\"] !== \"string\" || raw[\"table\"].length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: missing or empty table\");\n }\n if (typeof raw[\"target\"] !== \"string\" || !VALID_TARGETS.has(raw[\"target\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unknown target ${JSON.stringify(raw[\"target\"])}`,\n );\n }\n if (!Array.isArray(raw[\"columns\"])) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: columns is not an array\");\n }\n const table = raw[\"table\"];\n const target = raw[\"target\"] as SqlTarget;\n const columns: ColumnPlan[] = [];\n for (const [i, col] of raw[\"columns\"].entries()) {\n if (!isObject(col)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}] is not an object`,\n );\n }\n if (typeof col[\"source\"] !== \"string\" || col[\"source\"].length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].source is missing or empty`,\n );\n }\n if (typeof col[\"sqlType\"] !== \"string\" || !VALID_SQL_TYPES.has(col[\"sqlType\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].sqlType ${JSON.stringify(col[\"sqlType\"])} is not a recognised SqlType`,\n );\n }\n if (typeof col[\"nullable\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].nullable is not a boolean`,\n );\n }\n if (typeof col[\"jsonEncoded\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].jsonEncoded is not a boolean`,\n );\n }\n columns.push({\n source: col[\"source\"],\n identifier: quoteIdentifier(col[\"source\"], target),\n sqlType: col[\"sqlType\"] as SqlType,\n nullable: col[\"nullable\"],\n jsonEncoded: col[\"jsonEncoded\"],\n });\n }\n return {\n table,\n target,\n tableIdentifier: quoteIdentifier(table, target),\n columns,\n // Not preserved across the sidecar boundary — see file JSDoc.\n rowCount: 0,\n };\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked\n primary-key field on document shapes; the exporter threads it\n through the materialised view and the emitted INSERT rows. */\n\n/**\n * `baerly export` — snapshot dump of one collection to SQL.\n *\n * Drives the export modules end-to-end: load the materialised view,\n * infer an `ExportPlan` over the row shape, emit `CREATE TABLE` +\n * `INSERT` statements. When `--where=<json>` is supplied the\n * predicate is translated via `translatePredicateToSql` and applied\n * in-memory through `matches(...)` so the emitted INSERTs already\n * match the filter; the translated WHERE clause is also surfaced as a\n * comment above the inserts so operators can inspect / hand-edit it.\n *\n * The sidecar file (`<output>.plan.json`) carries the `ExportPlan` so\n * a follow-up round-trip ingest can verify the column schema. The\n * sidecar is JSON via `JSON.stringify` — the plan shape is the public\n * contract.\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 * --target Required. postgres | sqlite | d1.\n * --where Optional. JSON-encoded `Predicate<T>`.\n * --where-comment Optional. Caller hint surfaced as a\n * `-- TODO(baerly export):` comment.\n * --output Optional. Path to write SQL into; default\n * stdout. The sidecar plan is written to\n * `<output>.plan.json` unless `--no-sidecar`.\n * --no-sidecar Skip emitting the sidecar plan file.\n * --json JSON envelope on stdout (or stderr on error).\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad args / bucket URI / --where JSON / unknown --target).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Internal / InvalidResponse / Conflict).\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, matchesWire, type PredicateWire, validateWire } from \"@baerly/protocol\";\nimport {\n type ExportPlan,\n type ExportRow,\n type SqlTarget,\n emitCreateTable,\n emitInsertStatements,\n inferPlanForCollection,\n loadMaterialisedView,\n serializeExportPlan,\n translatePredicateWireToSql,\n} from \"./export/index.ts\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess } from \"./output.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst EXPORT_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 target: {\n type: \"enum\",\n options: [\"postgres\", \"sqlite\", \"d1\"],\n required: true,\n description: \"SQL target: postgres | sqlite | d1.\",\n },\n where: {\n type: \"string\",\n required: false,\n description: \"JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.\",\n valueHint: \"json\",\n },\n \"where-comment\": {\n type: \"string\",\n required: false,\n description: \"Caller hint surfaced as a -- TODO(baerly export): comment.\",\n valueHint: \"text\",\n },\n output: {\n type: \"string\",\n required: false,\n description: \"Path to write SQL into; default stdout.\",\n valueHint: \"path\",\n },\n sidecar: {\n type: \"boolean\",\n default: true,\n description: \"Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip).\",\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 parseWherePredicate = (raw: string): PredicateWire => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where is not valid JSON: ${(error as Error).message}`,\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where must decode to a JSON object (got ${describeNonObject(parsed)})`,\n );\n }\n // Re-validate defensively; the translator will reject too, but\n // surfacing the error here gives a single uniform error path.\n validateWire(parsed as PredicateWire);\n return parsed as PredicateWire;\n};\n\nconst filterRows = (\n rows: ReadonlyMap<string, ExportRow>,\n wire: PredicateWire | null,\n): Map<string, ExportRow> => {\n const filtered = new Map<string, ExportRow>();\n for (const [id, body] of rows) {\n if (wire === null) {\n filtered.set(id, body);\n continue;\n }\n if (matchesWire(wire, body)) {\n filtered.set(id, body);\n }\n }\n return filtered;\n};\n\nconst buildSql = async (\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n whereClause: string,\n whereHints: readonly string[],\n): Promise<string> => {\n let out = emitCreateTable(plan);\n for (const hint of whereHints) {\n out += `-- TODO(baerly export): ${hint}\\n`;\n }\n if (whereClause.length > 0) {\n out += `-- WHERE clause for review: ${whereClause}\\n`;\n }\n for await (const chunk of emitInsertStatements(plan, rows)) {\n out += chunk;\n }\n return out;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"export\",\n meta: {\n description: \"Snapshot dump of one collection to SQL.\",\n },\n args: EXPORT_ARGS,\n handler: async (args, ctx) => {\n const target: SqlTarget = args.target;\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const bucket = await parseBucketUri(args.bucket);\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 export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`,\n );\n }\n const plan = inferPlanForCollection({\n rows: view,\n target,\n table: args.collection,\n });\n\n let wire: PredicateWire | null = null;\n let whereClause = \"\";\n let whereHints: readonly string[] = [];\n if (typeof args.where === \"string\" && args.where.length > 0) {\n wire = parseWherePredicate(args.where);\n const translation = translatePredicateWireToSql(\n wire,\n plan,\n typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0\n ? { dynamicHint: args[\"where-comment\"] }\n : undefined,\n );\n whereClause = translation.sql;\n whereHints = translation.hints;\n } else if (typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0) {\n // Bare --where-comment with no predicate still surfaces the operator's\n // note so reviewers see the intent.\n whereHints = [\n `caller-flagged dynamic predicate: ${args[\"where-comment\"]}. No predicate supplied; emitted INSERTs cover the full collection.`,\n ];\n }\n\n const filtered = filterRows(view, wire);\n const sql = await buildSql(plan, filtered, whereClause, whereHints);\n\n const outputPath = args.output;\n if (typeof outputPath === \"string\" && outputPath.length > 0) {\n await writeFile(outputPath, sql, \"utf8\");\n if (args.sidecar !== false) {\n await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), \"utf8\");\n }\n } else {\n process.stdout.write(sql);\n }\n\n emitSuccess({\n command: \"export\",\n status: \"ok\",\n collection: args.collection,\n target,\n rows: filtered.size,\n hints: whereHints,\n ...(typeof outputPath === \"string\" && outputPath.length > 0 && { output: outputPath }),\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly export`. */\nexport const exportCmd = 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 runExport = bundle.run;\n\n// Build a human-readable label for the \"expected JSON object\" error.\n// `null`, arrays, and the bare `undefined` need to be disambiguated\n// from `typeof`'s default \"object\".\nconst describeNonObject = (v: unknown): string => {\n if (v === null) {\n return \"null\";\n }\n if (Array.isArray(v)) {\n return \"array\";\n }\n return typeof v;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AAcA,MAAa,mBAAmB,SAA6B;CAC3D,IAAI,KAAK,QAAQ,WAAW,GAC1B,MAAM,IAAI,YACR,eACA,+BAA+B,KAAK,UAAU,KAAK,KAAK,EAAE,2CAC5D;CAEF,IAAI,KAAK,WAAW,QAAQ,KAAK,MAAM,YAAY,EAAE,WAAW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KAAK,MAAM,SAAS,GAAG;GAC3D,OAAO,oBAAoB,KAAK,KAAK;GACrC,MAAM,cAAc,4BAClB,MACA,MACA,OAAO,KAAK,qBAAqB,YAAY,KAAK,iBAAiB,SAAS,IACxE,EAAE,aAAa,KAAK,iBAAiB,IACrC,KAAA,CACN;GACA,cAAc,YAAY;GAC1B,aAAa,YAAY;EAC3B,OAAO,IAAI,OAAO,KAAK,qBAAqB,YAAY,KAAK,iBAAiB,SAAS,GAGrF,aAAa,CACX,qCAAqC,KAAK,iBAAiB,oEAC7D;EAGF,MAAM,WAAW,WAAW,MAAM,IAAI;EACtC,MAAM,MAAM,MAAM,SAAS,MAAM,UAAU,aAAa,UAAU;EAElE,MAAM,aAAa,KAAK;EACxB,IAAI,OAAO,eAAe,YAAY,WAAW,SAAS,GAAG;GAC3D,MAAM,UAAU,YAAY,KAAK,MAAM;GACvC,IAAI,KAAK,YAAY,OACnB,MAAM,UAAU,GAAG,WAAW,aAAa,oBAAoB,IAAI,GAAG,MAAM;EAEhF,OACE,QAAQ,OAAO,MAAM,GAAG;EAG1B,YAAY;GACV,SAAS;GACT,QAAQ;GACR,YAAY,KAAK;GACjB;GACA,MAAM,SAAS;GACf,OAAO;GACP,GAAI,OAAO,eAAe,YAAY,WAAW,SAAS,KAAK,EAAE,QAAQ,WAAW;EACtF,CAAC;EACD,OAAO;CACT;AACF,CAAC;;AAGD,MAAa,YAAY,OAAO;AAOP,OAAO;AAKhC,MAAM,qBAAqB,MAAuB;CAChD,IAAI,MAAM,MACR,OAAO;CAET,IAAI,MAAM,QAAQ,CAAC,GACjB,OAAO;CAET,OAAO,OAAO;AAChB"}
1
+ {"version":3,"file":"export-BcuCLFFe.js","names":[],"sources":["../packages/cli/src/export/ddl.ts","../packages/cli/src/export/rows.ts","../packages/cli/src/export/where.ts","../packages/cli/src/export/plan-sidecar.ts","../packages/cli/src/export.ts"],"sourcesContent":["import { BaerlyError } from \"@baerly/protocol\";\nimport type { ExportPlan } from \"./types.ts\";\n\n/**\n * Emit a `CREATE TABLE` statement for the plan, one line per column,\n * terminated with a semicolon + newline so the output is directly\n * pipeable into `psql` / `sqlite3` / `wrangler d1 execute`.\n *\n * `_id` is the primary key (always first in `plan.columns`).\n *\n * D1 today is sqlite-flavoured: same DDL as `target=sqlite` with a\n * single difference — D1 disallows table names starting with\n * `sqlite_`. We refuse them up front.\n */\nexport const emitCreateTable = (plan: ExportPlan): string => {\n if (plan.columns.length === 0) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: collection ${JSON.stringify(plan.table)} has no observed columns — empty snapshot?`,\n );\n }\n if (plan.target === \"d1\" && plan.table.toLowerCase().startsWith(\"sqlite_\")) {\n throw new BaerlyError(\n \"SchemaError\",\n `emitCreateTable: D1 reserves the sqlite_ table-name prefix (got ${JSON.stringify(plan.table)})`,\n );\n }\n const lines: string[] = [];\n lines.push(`CREATE TABLE ${plan.tableIdentifier} (`);\n const colLines: string[] = [];\n for (const col of plan.columns) {\n const nullClause = col.nullable ? \"\" : \" NOT NULL\";\n const pkClause = col.source === \"_id\" ? \" PRIMARY KEY\" : \"\";\n colLines.push(` ${col.identifier} ${col.sqlType}${nullClause}${pkClause}`);\n }\n lines.push(colLines.join(\",\\n\"));\n lines.push(\");\");\n return lines.join(\"\\n\") + \"\\n\";\n};\n","import type { DocumentValue } from \"@baerly/protocol\";\nimport type { ExportPlan, ExportRow } from \"./types.ts\";\nimport { quoteValue } from \"./sql-escape.ts\";\n\n/**\n * Emit one `INSERT INTO …` statement per row. The emitted SQL is\n * directly pipeable into `psql` / `sqlite3` / `wrangler d1\n * execute`. Per-row statements (not one big VALUES tuple) so a\n * mid-stream failure has bounded blast radius.\n *\n * For columns whose plan has `jsonEncoded: true`, the row's value\n * is JSON-stringified first and then string-quoted. Postgres\n * accepts a literal text JSON in a `jsonb` column. SQLite / D1 see\n * the JSON as plain TEXT.\n *\n * Rows are streamed via the async-iterable protocol so the export\n * never materialises the full SQL output in memory. The caller\n * concatenates the yielded chunks (or pipes them straight to disk\n * / stdout).\n */\nexport async function* emitInsertStatements(\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n): AsyncIterable<string> {\n const columnList = plan.columns.map((c) => c.identifier).join(\", \");\n // Iterate in `Map` insertion order — stable, and the snapshot\n // body itself sorts by `_id` (compactor.ts: `docs is sorted by\n // _id for deterministic byte output`).\n for (const [id, body] of rows) {\n const values: string[] = [];\n for (const col of plan.columns) {\n const raw: DocumentValue | undefined =\n col.source === \"_id\"\n ? (id as DocumentValue)\n : (body as Record<string, DocumentValue>)[col.source];\n if (raw === undefined) {\n values.push(\"NULL\");\n continue;\n }\n if (col.jsonEncoded) {\n const json = JSON.stringify(raw);\n values.push(quoteValue(json, plan.target));\n } else {\n values.push(quoteValue(raw, plan.target));\n }\n }\n yield `INSERT INTO ${plan.tableIdentifier} (${columnList}) VALUES (${values.join(\", \")});\\n`;\n }\n}\n","/**\n * Wire-predicate → SQL `WHERE` clause translation.\n *\n * Pure function. The translator consumes a validated\n * {@link PredicateWire} — the same shape the read path uses — and\n * an {@link ExportPlan} (from `./plan.ts`), and emits a SQL fragment\n * matched against the plan's columns.\n *\n * Three classes of clause:\n *\n * 1. Flat column, top-level field → direct comparator\n * (`\"status\" = 'open'`, `\"priority\" > 5`).\n * 2. JSON-encoded column → JSON-path operators (Postgres `->`/`->>`\n * chains; SQLite/D1 `json_extract(…, '$.…')`).\n * 3. Unmatchable clause (dotted path against a flat column, or a\n * field naming an unknown column) → `1 = 0` plus a hint the CLI\n * surfaces as a `-- TODO(baerly export):` comment above the\n * emitted statement.\n *\n * Dynamic predicates are invisible at runtime — we see the\n * materialised wire, not the source expression. Callers that know\n * they constructed the wire dynamically can pass\n * `options.dynamicHint` to surface an operator-supplied note.\n */\n\nimport {\n BaerlyError,\n type DocumentValue,\n type PredicateClause,\n type PredicateWire,\n validateWire,\n} from \"@baerly/protocol\";\nimport { quoteValue } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget } from \"./types.ts\";\n\nexport interface WhereTranslation {\n /** SQL fragment without the leading `WHERE`. Empty when no predicate. */\n readonly sql: string;\n /**\n * Hand-edit hints for the operator. One entry per non-matchable\n * clause (§3.6) or per dynamically-constructed sub-clause flagged\n * by the caller. The CLI surfaces these as `-- TODO(baerly export): …`\n * comments above the emitted statement.\n */\n readonly hints: readonly string[];\n}\n\n/**\n * Translate a validated {@link PredicateWire} into a SQL WHERE-clause\n * fragment matched against the plan's columns. The first argument\n * must already have been validated by {@link validateWire} — the\n * function re-validates defensively but the caller's invariant\n * matters for error-message provenance.\n *\n * Pure function. No I/O. Same wire + plan + target → same SQL string.\n *\n * @throws BaerlyError code=\"InvalidConfig\" — wire fails\n * {@link validateWire}; same shape `Query<T>.where` already\n * surfaces.\n */\nexport const translatePredicateWireToSql = (\n wire: PredicateWire,\n plan: ExportPlan,\n options?: { readonly dynamicHint?: string },\n): WhereTranslation => {\n validateWire(wire);\n const hints: string[] = [];\n if (options?.dynamicHint !== undefined && options.dynamicHint.length > 0) {\n hints.push(\n `caller-flagged dynamic predicate: ${options.dynamicHint}. Review the emitted SQL for completeness.`,\n );\n }\n const clauses: string[] = [];\n for (const clause of wire.clauses) {\n clauses.push(...clauseForWire(clause, plan, hints));\n }\n return {\n sql: clauses.length === 0 ? \"\" : clauses.join(\" AND \"),\n hints,\n };\n};\n\nconst clauseForWire = (clause: PredicateClause, plan: ExportPlan, hints: string[]): string[] => {\n const segments = clause.field.includes(\".\") ? clause.field.split(\".\") : [clause.field];\n const head = segments[0];\n if (head === undefined || head.length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: empty field path encountered (defensive)\",\n );\n }\n const col = plan.columns.find((c) => c.source === head);\n if (col === undefined) {\n hints.push(\n `predicate field ${JSON.stringify(clause.field)} references a key never observed in the snapshot; this clause cannot match.`,\n );\n return [\"1 = 0\"];\n }\n // §3.2 — flat column, top-level field → direct comparator.\n if (!col.jsonEncoded && segments.length === 1) {\n return [flatColumnClause(col.identifier, clause, plan.target)];\n }\n // §3.6 — flat column, dotted path → unmatchable.\n if (!col.jsonEncoded && segments.length > 1) {\n hints.push(\n `predicate path ${JSON.stringify(clause.field)} addresses a flat column; this clause cannot match. Hand-edit if intended.`,\n );\n return [\"1 = 0\"];\n }\n // §3.3 — JSON column, top-level field.\n if (col.jsonEncoded && segments.length === 1) {\n return [jsonColumnRootClause(col, clause, plan.target)];\n }\n // §3.4 / §3.5 — JSON column, dotted path.\n return [jsonPathClause(col, segments.slice(1), clause, plan.target)];\n};\n\nconst flatColumnClause = (\n identifier: string,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n switch (clause.op) {\n case \"eq\": {\n return `${identifier} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${identifier} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${identifier} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${identifier} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${identifier} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${identifier} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst jsonColumnRootClause = (\n col: ColumnPlan,\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n // The root JSON column stores the value as JSON-encoded text;\n // we compare against the JSON encoding of the predicate value.\n // Range and `in` ops on a JSON-encoded root column compare the\n // JSON text lexicographically, which is rarely what the caller\n // wanted — for those, the operator is expected to promote the\n // field into a flat column or hand-edit the emitted SQL.\n if (clause.op === \"eq\") {\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text = ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} = ${quoteValue(literal, target)}`;\n }\n if (clause.op === \"in\") {\n const literals = (clause.value as ReadonlyArray<DocumentValue>).map((v) =>\n quoteValue(JSON.stringify(v), target),\n );\n if (target === \"postgres\") {\n return `${col.identifier}::text IN (${literals.join(\", \")})`;\n }\n return `${col.identifier} IN (${literals.join(\", \")})`;\n }\n // Range against JSON-encoded root: fall back to a lex compare on\n // the JSON serialisation. Surface a comment via the SQL itself;\n // the operator can hand-edit.\n const comparator = rangeComparator(clause.op);\n const literal = JSON.stringify(clause.value);\n if (target === \"postgres\") {\n return `${col.identifier}::text ${comparator} ${quoteValue(literal, target)}`;\n }\n return `${col.identifier} ${comparator} ${quoteValue(literal, target)}`;\n};\n\nconst jsonPathClause = (\n col: ColumnPlan,\n tail: readonly string[],\n clause: PredicateClause,\n target: SqlTarget,\n): string => {\n const accessor = jsonPathAccessor(col.identifier, tail, target);\n switch (clause.op) {\n case \"eq\": {\n return `${accessor} = ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gt\": {\n return `${accessor} > ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"gte\": {\n return `${accessor} >= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lt\": {\n return `${accessor} < ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"lte\": {\n return `${accessor} <= ${quoteLeaf(clause.value as DocumentValue, target)}`;\n }\n case \"in\": {\n return `${accessor} IN (${(clause.value as ReadonlyArray<DocumentValue>)\n .map((v) => quoteLeaf(v, target))\n .join(\", \")})`;\n }\n }\n};\n\nconst rangeComparator = (op: PredicateClause[\"op\"]): string => {\n if (op === \"gt\") {\n return \">\";\n }\n if (op === \"gte\") {\n return \">=\";\n }\n if (op === \"lt\") {\n return \"<\";\n }\n return \"<=\";\n};\n\nconst jsonPathAccessor = (\n identifier: string,\n tail: readonly string[],\n target: SqlTarget,\n): string => {\n if (target === \"postgres\") {\n let expr = identifier;\n for (let i = 0; i < tail.length; i++) {\n const seg = tail[i]!;\n const isLast = i === tail.length - 1;\n const key = `'${seg.replace(/'/g, \"''\")}'`;\n expr = `${expr}${isLast ? \"->>\" : \"->\"}${key}`;\n }\n return expr;\n }\n const jsonPath = `'$.${tail.map((s) => s.replace(/'/g, \"''\")).join(\".\")}'`;\n return `json_extract(${identifier}, ${jsonPath})`;\n};\n\n/**\n * Quote a leaf primitive for use as the right-hand side of a\n * comparison. Booleans branch on target. Nested objects must never\n * reach here — wire `eq` clauses on nested objects can only come\n * from the callback form `q.eq(\"nested\", { ... })`, which the\n * export translator does not support today.\n */\nconst quoteLeaf = (value: DocumentValue, target: SqlTarget): string => {\n if (typeof value === \"object\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"translatePredicateWireToSql: nested object reached leaf quoter — callback-form q.eq(field, object) is not supported for SQL export. Hand-edit the emitted SQL.\",\n );\n }\n return quoteValue(value, target);\n};\n","/**\n * Sidecar plan serialisation for `baerly export`.\n *\n * `baerly export --output=foo.sql` writes the inferred {@link ExportPlan}\n * alongside the SQL dump as `foo.sql.plan.json`. The round-trip test\n * (`tests/integration/export-round-trip.test.ts`) consumes the sidecar\n * to coerce SQLite-returned values back to their original JS type\n * (e.g. SQLite stores booleans as 0/1; we restore `true`/`false`).\n *\n * Wire shape (`schemaVersion = 1`):\n *\n * ```json\n * {\n * \"schemaVersion\": 1,\n * \"table\": \"tickets\",\n * \"target\": \"sqlite\",\n * \"columns\": [\n * { \"source\": \"_id\", \"sqlType\": \"TEXT\", \"nullable\": false, \"jsonEncoded\": false },\n * ...\n * ]\n * }\n * ```\n *\n * `identifier` is NOT carried on the wire — we re-derive it via\n * {@link quoteIdentifier} on deserialise. An attacker writing the\n * sidecar should not get SQL-emit control over identifiers.\n *\n * `rowCount` is also not preserved across the sidecar boundary; the\n * deserialised plan reports `0`. This is intentional — consumers that\n * care about row count read the SQL stream itself.\n */\n\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { quoteIdentifier } from \"./sql-escape.ts\";\nimport type { ColumnPlan, ExportPlan, SqlTarget, SqlType } from \"./types.ts\";\n\nconst SIDECAR_SCHEMA_VERSION = 1 as const;\n\nconst VALID_TARGETS: ReadonlySet<string> = new Set([\"postgres\", \"sqlite\", \"d1\"]);\n\nconst VALID_SQL_TYPES: ReadonlySet<string> = new Set([\n \"text\",\n \"boolean\",\n \"integer\",\n \"double precision\",\n \"jsonb\",\n \"TEXT\",\n \"INTEGER\",\n \"REAL\",\n]);\n\n/**\n * Encode an {@link ExportPlan} as the canonical sidecar JSON string.\n *\n * Wire format is pretty-printed (`indent=2`) with a trailing newline\n * so `cat sidecar.plan.json` is human-readable and `diff` works on\n * two sidecars without spurious line-end noise. The on-wire bytes\n * embed the `schemaVersion` discriminator so future shape changes\n * are detectable; `identifier` and `tableIdentifier` are NOT carried\n * (they're re-derived via {@link quoteIdentifier} on deserialise).\n */\nexport const serializeExportPlan = (plan: ExportPlan): string => {\n return (\n JSON.stringify(\n {\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n table: plan.table,\n target: plan.target,\n columns: plan.columns.map((c) => ({\n source: c.source,\n sqlType: c.sqlType,\n nullable: c.nullable,\n jsonEncoded: c.jsonEncoded,\n })),\n },\n null,\n 2,\n ) + \"\\n\"\n );\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\n/**\n * Parse the sidecar JSON string back into an {@link ExportPlan}.\n *\n * @throws BaerlyError code=\"InvalidConfig\" when the sidecar JSON is\n * malformed, the schema version is unsupported, or any required\n * field is missing / has an unexpected type. Identifiers are\n * re-quoted via {@link quoteIdentifier} rather than copied off the\n * wire — the sidecar cannot smuggle SQL-injection via a\n * pre-quoted identifier.\n */\nexport const deserializeExportPlan = (text: string): ExportPlan => {\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: parse failed: ${(error as Error).message}`,\n );\n }\n if (!isObject(raw)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n \"deserializeExportPlan: top-level value is not an object\",\n );\n }\n if (raw[\"schemaVersion\"] !== SIDECAR_SCHEMA_VERSION) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unsupported schemaVersion ${String(raw[\"schemaVersion\"])} (expected ${String(SIDECAR_SCHEMA_VERSION)})`,\n );\n }\n if (typeof raw[\"table\"] !== \"string\" || raw[\"table\"].length === 0) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: missing or empty table\");\n }\n if (typeof raw[\"target\"] !== \"string\" || !VALID_TARGETS.has(raw[\"target\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: unknown target ${JSON.stringify(raw[\"target\"])}`,\n );\n }\n if (!Array.isArray(raw[\"columns\"])) {\n throw new BaerlyError(\"InvalidConfig\", \"deserializeExportPlan: columns is not an array\");\n }\n const table = raw[\"table\"];\n const target = raw[\"target\"] as SqlTarget;\n const columns: ColumnPlan[] = [];\n for (const [i, col] of raw[\"columns\"].entries()) {\n if (!isObject(col)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}] is not an object`,\n );\n }\n if (typeof col[\"source\"] !== \"string\" || col[\"source\"].length === 0) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].source is missing or empty`,\n );\n }\n if (typeof col[\"sqlType\"] !== \"string\" || !VALID_SQL_TYPES.has(col[\"sqlType\"])) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].sqlType ${JSON.stringify(col[\"sqlType\"])} is not a recognised SqlType`,\n );\n }\n if (typeof col[\"nullable\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].nullable is not a boolean`,\n );\n }\n if (typeof col[\"jsonEncoded\"] !== \"boolean\") {\n throw new BaerlyError(\n \"InvalidConfig\",\n `deserializeExportPlan: columns[${i}].jsonEncoded is not a boolean`,\n );\n }\n columns.push({\n source: col[\"source\"],\n identifier: quoteIdentifier(col[\"source\"], target),\n sqlType: col[\"sqlType\"] as SqlType,\n nullable: col[\"nullable\"],\n jsonEncoded: col[\"jsonEncoded\"],\n });\n }\n return {\n table,\n target,\n tableIdentifier: quoteIdentifier(table, target),\n columns,\n // Not preserved across the sidecar boundary — see file JSDoc.\n rowCount: 0,\n };\n};\n","/* eslint-disable no-underscore-dangle -- `_id` is the locked\n primary-key field on document shapes; the exporter threads it\n through the materialised view and the emitted INSERT rows. */\n\n/**\n * `baerly export` — snapshot dump of one collection to SQL.\n *\n * Drives the export modules end-to-end: load the materialised view,\n * infer an `ExportPlan` over the row shape, emit `CREATE TABLE` +\n * `INSERT` statements. When `--where=<json>` is supplied the\n * predicate is translated via `translatePredicateToSql` and applied\n * in-memory through `matches(...)` so the emitted INSERTs already\n * match the filter; the translated WHERE clause is also surfaced as a\n * comment above the inserts so operators can inspect / hand-edit it.\n *\n * The sidecar file (`<output>.plan.json`) carries the `ExportPlan` so\n * a follow-up round-trip ingest can verify the column schema. The\n * sidecar is JSON via `JSON.stringify` — the plan shape is the public\n * contract.\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 * --target Required. postgres | sqlite | d1.\n * --where Optional. JSON-encoded `Predicate<T>`.\n * --where-comment Optional. Caller hint surfaced as a\n * `-- TODO(baerly export):` comment.\n * --output Optional. Path to write SQL into; default\n * stdout. The sidecar plan is written to\n * `<output>.plan.json` unless `--no-sidecar`.\n * --no-sidecar Skip emitting the sidecar plan file.\n * --json JSON envelope on stdout (or stderr on error).\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad args / bucket URI / --where JSON / unknown --target).\n * 2 — Storage / Network error.\n * 3 — Protocol invariant (Internal / InvalidResponse / Conflict).\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, matchesWire, type PredicateWire, validateWire } from \"@baerly/protocol\";\nimport {\n type ExportPlan,\n type ExportRow,\n type SqlTarget,\n emitCreateTable,\n emitInsertStatements,\n inferPlanForCollection,\n loadMaterialisedView,\n serializeExportPlan,\n translatePredicateWireToSql,\n} from \"./export/index.ts\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { emitSuccess } from \"./output.ts\";\nimport { assertCollectionArg, defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst EXPORT_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 target: {\n type: \"enum\",\n options: [\"postgres\", \"sqlite\", \"d1\"],\n required: true,\n description: \"SQL target: postgres | sqlite | d1.\",\n },\n where: {\n type: \"string\",\n required: false,\n description: \"JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.\",\n valueHint: \"json\",\n },\n \"where-comment\": {\n type: \"string\",\n required: false,\n description: \"Caller hint surfaced as a -- TODO(baerly export): comment.\",\n valueHint: \"text\",\n },\n output: {\n type: \"string\",\n required: false,\n description: \"Path to write SQL into; default stdout.\",\n valueHint: \"path\",\n },\n sidecar: {\n type: \"boolean\",\n default: true,\n description: \"Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip).\",\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 parseWherePredicate = (raw: string): PredicateWire => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where is not valid JSON: ${(error as Error).message}`,\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly export: --where must decode to a JSON object (got ${describeNonObject(parsed)})`,\n );\n }\n // Re-validate defensively; the translator will reject too, but\n // surfacing the error here gives a single uniform error path.\n validateWire(parsed as PredicateWire);\n return parsed as PredicateWire;\n};\n\nconst filterRows = (\n rows: ReadonlyMap<string, ExportRow>,\n wire: PredicateWire | null,\n): Map<string, ExportRow> => {\n const filtered = new Map<string, ExportRow>();\n for (const [id, body] of rows) {\n if (wire === null) {\n filtered.set(id, body);\n continue;\n }\n if (matchesWire(wire, body)) {\n filtered.set(id, body);\n }\n }\n return filtered;\n};\n\nconst buildSql = async (\n plan: ExportPlan,\n rows: ReadonlyMap<string, ExportRow>,\n whereClause: string,\n whereHints: readonly string[],\n): Promise<string> => {\n let out = emitCreateTable(plan);\n for (const hint of whereHints) {\n out += `-- TODO(baerly export): ${hint}\\n`;\n }\n if (whereClause.length > 0) {\n out += `-- WHERE clause for review: ${whereClause}\\n`;\n }\n for await (const chunk of emitInsertStatements(plan, rows)) {\n out += chunk;\n }\n return out;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"export\",\n meta: {\n description: \"Snapshot dump of one collection to SQL.\",\n },\n args: EXPORT_ARGS,\n handler: async (args, ctx) => {\n const target: SqlTarget = args.target;\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n assertCollectionArg(args.collection, \"baerly export\");\n const bucket = await parseBucketUri(args.bucket);\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 export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`,\n );\n }\n const plan = inferPlanForCollection({\n rows: view,\n target,\n table: args.collection,\n });\n\n let wire: PredicateWire | null = null;\n let whereClause = \"\";\n let whereHints: readonly string[] = [];\n if (typeof args.where === \"string\" && args.where.length > 0) {\n wire = parseWherePredicate(args.where);\n const translation = translatePredicateWireToSql(\n wire,\n plan,\n typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0\n ? { dynamicHint: args[\"where-comment\"] }\n : undefined,\n );\n whereClause = translation.sql;\n whereHints = translation.hints;\n } else if (typeof args[\"where-comment\"] === \"string\" && args[\"where-comment\"].length > 0) {\n // Bare --where-comment with no predicate still surfaces the operator's\n // note so reviewers see the intent.\n whereHints = [\n `caller-flagged dynamic predicate: ${args[\"where-comment\"]}. No predicate supplied; emitted INSERTs cover the full collection.`,\n ];\n }\n\n const filtered = filterRows(view, wire);\n const sql = await buildSql(plan, filtered, whereClause, whereHints);\n\n const outputPath = args.output;\n if (typeof outputPath === \"string\" && outputPath.length > 0) {\n await writeFile(outputPath, sql, \"utf8\");\n if (args.sidecar !== false) {\n await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), \"utf8\");\n }\n } else {\n process.stdout.write(sql);\n }\n\n emitSuccess({\n command: \"export\",\n status: \"ok\",\n collection: args.collection,\n target,\n rows: filtered.size,\n hints: whereHints,\n ...(typeof outputPath === \"string\" && outputPath.length > 0 && { output: outputPath }),\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly export`. */\nexport const exportCmd = 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 runExport = bundle.run;\n\n// Build a human-readable label for the \"expected JSON object\" error.\n// `null`, arrays, and the bare `undefined` need to be disambiguated\n// from `typeof`'s default \"object\".\nconst describeNonObject = (v: unknown): string => {\n if (v === null) {\n return \"null\";\n }\n if (Array.isArray(v)) {\n return \"array\";\n }\n return typeof v;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAcA,MAAa,mB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C,GACjB,OAAO;CAET,OAAO,OAAO;AAChB"}
@@ -1,7 +1,8 @@
1
- import { f as readCurrentJson, n as loadSnapshotAsMap } from "./snapshot-SS8USDUF.js";
2
- import { i as rebuildIndex } from "./maintenance-BvOv6BMM.js";
3
- import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
1
+ import { r as parseBucketUri } from "./config-CGyBopy3.js";
2
+ import { c as loadSnapshotAsMap, h as readCurrentJson } from "./log-tail-DXeDkWEp.js";
3
+ import { i as rebuildIndex } from "./maintenance-C_KSkVjd.js";
4
4
  import { i as isJsonMode, o as BaerlyError, r as emitSuccess } from "./baerly.js";
5
+ import { n as defineBaerlySubcommand, t as assertCollectionArg } from "./subcommand-CP9NY2J4.js";
5
6
  import { fileURLToPath, pathToFileURL } from "node:url";
6
7
  //#region src/admin/fsck.ts
7
8
  /**
@@ -13,10 +14,16 @@ import { fileURLToPath, pathToFileURL } from "node:url";
13
14
  * 2. When `current.snapshot !== null`, the snapshot body's
14
15
  * SHA-256 matches the hash embedded in the filename
15
16
  * (delegated to `loadSnapshotAsMap`).
16
- * 3. The log range `[log_seq_start, next_seq)` has no holes —
17
- * every `log/<seq>.json` is present (HEAD-cheap LIST scan).
18
- * 4. Every entry inside the live tail is well-formed JSON with
19
- * the locked `op`, `collection`, and `doc_id` fields.
17
+ * 3. The live log range has no holes. The upper bound is derived
18
+ * from a single LIST of `log/` plus `current.json.tail_hint`
19
+ * (max(highest present seq + 1, tail_hint)), and every seq from
20
+ * `log_seq_start` up to that tail must be present.
21
+ * This is a presence/hole check by key, NOT a per-entry decode:
22
+ * fsck does not GET and parse each `log/<seq>.json`, so it does
23
+ * not assert every entry is well-formed JSON or carries the locked
24
+ * `op`/`collection`/`doc_id` fields. A full decode walk is
25
+ * intentionally omitted to keep the op count O(LIST pages); the
26
+ * read path validates entry shape at fold time.
20
27
  *
21
28
  * `--indexes` + `--config=<path>` mode: SKIP the snapshot + log
22
29
  * walks and ONLY check each declared index for drift via
@@ -160,6 +167,7 @@ const bundle = defineBaerlySubcommand({
160
167
  app: args.app,
161
168
  tenant: args.tenant
162
169
  });
170
+ assertCollectionArg(args.collection, "baerly admin fsck");
163
171
  const bucket = await parseBucketUri(args.bucket);
164
172
  const collectionPrefix = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}`;
165
173
  const currentJsonKey = `${collectionPrefix}/current.json`;
@@ -224,7 +232,6 @@ const bundle = defineBaerlySubcommand({
224
232
  if (read === null) throw new BaerlyError("InvalidConfig", `baerly admin fsck: current.json not found at ${currentJsonKey}`);
225
233
  const cur = read.json;
226
234
  const logFrom = cur.log_seq_start ?? 0;
227
- const logToExcl = cur.next_seq;
228
235
  const snapshotKey = cur.snapshot;
229
236
  if (snapshotKey !== null) try {
230
237
  await loadSnapshotAsMap(bucket.storage, snapshotKey, args.collection);
@@ -240,19 +247,24 @@ const bundle = defineBaerlySubcommand({
240
247
  const logPrefix = `${collectionPrefix}/log/`;
241
248
  const presentKeys = await listKeys(bucket.storage, logPrefix);
242
249
  const presentSeqs = /* @__PURE__ */ new Set();
250
+ let maxSeq = logFrom - 1;
243
251
  for (const key of presentKeys) {
244
252
  const tail = key.slice(logPrefix.length);
245
253
  const match = /^(\d+)\.json$/.exec(tail);
246
254
  if (match === null) continue;
247
255
  const seq = Number.parseInt(match[1], 10);
248
- if (Number.isFinite(seq)) presentSeqs.add(seq);
256
+ if (Number.isFinite(seq)) {
257
+ presentSeqs.add(seq);
258
+ if (seq > maxSeq) maxSeq = seq;
259
+ }
249
260
  }
261
+ const logToExcl = Math.max(cur.tail_hint, maxSeq + 1);
250
262
  let logEntriesPresent = 0;
251
263
  for (let s = logFrom; s < logToExcl; s++) if (presentSeqs.has(s)) logEntriesPresent++;
252
264
  else findings.push({
253
265
  severity: "finding",
254
266
  check: "log",
255
- message: `missing log entry at seq ${s} inside [log_seq_start, next_seq)`,
267
+ message: `missing log entry at seq ${s} inside [log_seq_start, tail)`,
256
268
  key: `${logPrefix}${s}.json`
257
269
  });
258
270
  if (isJsonMode()) emitSuccess({
@@ -287,4 +299,4 @@ bundle.run;
287
299
  //#endregion
288
300
  export { fsckCmd };
289
301
 
290
- //# sourceMappingURL=fsck-CPPZWt9p.js.map
302
+ //# sourceMappingURL=fsck-RXgLOaJG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fsck-RXgLOaJG.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 live log range has no holes. The upper bound is derived\n * from a single LIST of `log/` plus `current.json.tail_hint`\n * (max(highest present seq + 1, tail_hint)), and every seq from\n * `log_seq_start` up to that tail must be present.\n * This is a presence/hole check by key, NOT a per-entry decode:\n * fsck does not GET and parse each `log/<seq>.json`, so it does\n * not assert every entry is well-formed JSON or carries the locked\n * `op`/`collection`/`doc_id` fields. A full decode walk is\n * intentionally omitted to keep the op count O(LIST pages); the\n * read path validates entry shape at fold time.\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 { assertCollectionArg, 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 assertCollectionArg(args.collection, \"baerly admin fsck\");\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 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, tail) has no holes (presence check only). ──\n // LIST the log/ prefix and derive the upper bound from both listed\n // keys and `tail_hint`: under single-write commit `tail_hint` is\n // normally a lower bound, but fsck must also catch an over-claimed\n // hint whose `[log_seq_start, tail_hint)` range is not actually\n // present. Use a single LIST so the op count is O(pages).\n const logPrefix = `${collectionPrefix}/log/`;\n const presentKeys = await listKeys(bucket.storage, logPrefix);\n const presentSeqs = new Set<number>();\n let maxSeq = logFrom - 1;\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 if (seq > maxSeq) {\n maxSeq = seq;\n }\n }\n }\n const logToExcl = Math.max(cur.tail_hint, maxSeq + 1);\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, tail)`,\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,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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