@gusto/baerly-storage 0.1.1 → 0.1.2

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 (112) hide show
  1. package/README.md +3 -2
  2. package/dist/API.md +59 -7
  3. package/dist/{app-config-Dj_nGBfj.d.ts → app-config-C0Bbw_Z6.d.ts} +9 -9
  4. package/dist/app-config.d.ts +1 -1
  5. package/dist/auth.d.ts +1 -1
  6. package/dist/baerly.js +10 -10
  7. package/dist/baerly.js.map +1 -1
  8. package/dist/bytes-BXdamO3L.js +11 -0
  9. package/dist/bytes-BXdamO3L.js.map +1 -0
  10. package/dist/{client-CC5yVs1S.d.ts → client-DYZfoZb9.d.ts} +3 -3
  11. package/dist/client-react.d.ts +3 -3
  12. package/dist/client.d.ts +3 -3
  13. package/dist/cloudflare.d.ts +31 -4
  14. package/dist/cloudflare.js +72 -6
  15. package/dist/cloudflare.js.map +1 -1
  16. package/dist/{config-Bsg8wgwo.js → config-DVfDGyw1.js} +82 -2
  17. package/dist/config-DVfDGyw1.js.map +1 -0
  18. package/dist/{context-Oj7ffwD-.js → context-DRZ3tZ5l.js} +3 -2
  19. package/dist/{context-Oj7ffwD-.js.map → context-DRZ3tZ5l.js.map} +1 -1
  20. package/dist/{cost-B1WiZxlf.js → cost-CQt1YRkA.js} +3 -4
  21. package/dist/{cost-B1WiZxlf.js.map → cost-CQt1YRkA.js.map} +1 -1
  22. package/dist/{current-json-BkatBzF7.js → current-json-C-EyJqs0.js} +107 -5
  23. package/dist/current-json-C-EyJqs0.js.map +1 -0
  24. package/dist/{db-aRMK_0R0.d.ts → db-BM3y2JQw.d.ts} +3 -3
  25. package/dist/{deploy-BB-wqbhf.js → deploy-CrAbfgCq.js} +2 -2
  26. package/dist/{deploy-BB-wqbhf.js.map → deploy-CrAbfgCq.js.map} +1 -1
  27. package/dist/dev-vite.d.ts +3 -3
  28. package/dist/dev-vite.js +3 -3
  29. package/dist/dev.d.ts +1 -1
  30. package/dist/dev.js +1 -1
  31. package/dist/{doctor-B8h9GCN9.js → doctor-Db-hzPmE.js} +144 -7
  32. package/dist/doctor-Db-hzPmE.js.map +1 -0
  33. package/dist/{dump-BHo_sIMZ.js → dump-BYA55NLP.js} +3 -4
  34. package/dist/{dump-BHo_sIMZ.js.map → dump-BYA55NLP.js.map} +1 -1
  35. package/dist/errors-DOdL95kK.js.map +1 -1
  36. package/dist/{export-Dz2PZKSR.js → export-Bhbz90-z.js} +4 -5
  37. package/dist/{export-Dz2PZKSR.js.map → export-Bhbz90-z.js.map} +1 -1
  38. package/dist/{fsck-DEz9lyCy.js → fsck-CPPZWt9p.js} +5 -8
  39. package/dist/fsck-CPPZWt9p.js.map +1 -0
  40. package/dist/{http-DeJEeUcO.js → http-Cw8p6y5b.js} +5 -5
  41. package/dist/{http-DeJEeUcO.js.map → http-Cw8p6y5b.js.map} +1 -1
  42. package/dist/http.d.ts +3 -3
  43. package/dist/http.js +1 -1
  44. package/dist/{index-m6pY8iRU.d.ts → index-C3JAH1Yo.d.ts} +14 -2
  45. package/dist/{index-5lX_5NxZ.d.ts → index-DSvwEUeF.d.ts} +63 -54
  46. package/dist/{index-DPaQhAro.d.ts → index-DwDTWPSU.d.ts} +2 -2
  47. package/dist/{index-spCBsIwm.d.ts → index-cUY-36AN.d.ts} +3 -3
  48. package/dist/index.d.ts +5 -5
  49. package/dist/index.js +3 -3
  50. package/dist/{indexes-BIH73Uv4.d.ts → indexes-DAu2AkTW.d.ts} +2 -2
  51. package/dist/{inspect-x02aFWnh.js → inspect-Bdbzvi-_.js} +5 -6
  52. package/dist/{inspect-x02aFWnh.js.map → inspect-Bdbzvi-_.js.map} +1 -1
  53. package/dist/maintenance-BRrThz8V.d.ts +449 -0
  54. package/dist/maintenance-BvOv6BMM.js +1295 -0
  55. package/dist/maintenance-BvOv6BMM.js.map +1 -0
  56. package/dist/maintenance-ClzBC1Vv.js +1895 -0
  57. package/dist/maintenance-ClzBC1Vv.js.map +1 -0
  58. package/dist/maintenance.d.ts +2 -323
  59. package/dist/maintenance.js +2 -2
  60. package/dist/node.d.ts +20 -79
  61. package/dist/node.js +2 -2
  62. package/dist/{observability-2IDYRuZK.js → observability-CpOiEN0k.js} +2 -2
  63. package/dist/{observability-2IDYRuZK.js.map → observability-CpOiEN0k.js.map} +1 -1
  64. package/dist/observability.d.ts +2 -2
  65. package/dist/observability.js +2 -2
  66. package/dist/{plan-Cs17VqjU.js → plan-DOTl21vq.js} +3 -4
  67. package/dist/{plan-Cs17VqjU.js.map → plan-DOTl21vq.js.map} +1 -1
  68. package/dist/{query-DcSbFLJt.js → query-BmiQy328.js} +58 -26
  69. package/dist/query-BmiQy328.js.map +1 -0
  70. package/dist/{rebuild-index-DwXM0WfA.js → rebuild-index-DC_nR6wP.js} +4 -5
  71. package/dist/{rebuild-index-DwXM0WfA.js.map → rebuild-index-DC_nR6wP.js.map} +1 -1
  72. package/dist/{restore-CbKVMMpm.js → restore-C6IcmLeA.js} +44 -120
  73. package/dist/restore-C6IcmLeA.js.map +1 -0
  74. package/dist/{log-walk-DIru96UT.js → snapshot-SS8USDUF.js} +187 -20
  75. package/dist/snapshot-SS8USDUF.js.map +1 -0
  76. package/dist/{src-Cr9C7_tT.js → src-DU1sCMlr.js} +315 -278
  77. package/dist/src-DU1sCMlr.js.map +1 -0
  78. package/dist/{src-n0Te1r98.js → src-QQ7jDeL2.js} +25 -6
  79. package/dist/src-QQ7jDeL2.js.map +1 -0
  80. package/dist/{src-Chafbw8r.js → src-zhEAmmF7.js} +35 -4
  81. package/dist/src-zhEAmmF7.js.map +1 -0
  82. package/dist/{bucket-uri-BrDEYvzy.js → subcommand-DZcHcsYp.js} +222 -22
  83. package/dist/subcommand-DZcHcsYp.js.map +1 -0
  84. package/dist/{usage-RVUQMLop.js → usage-CLjirdD-.js} +4 -4
  85. package/dist/{usage-RVUQMLop.js.map → usage-CLjirdD-.js.map} +1 -1
  86. package/dist/{validate-DhH1lO8I.js → validate-DCq_0DIn.js} +2 -2
  87. package/dist/validate-DCq_0DIn.js.map +1 -0
  88. package/package.json +13 -6
  89. package/dist/bucket-uri-BrDEYvzy.js.map +0 -1
  90. package/dist/config-Bsg8wgwo.js.map +0 -1
  91. package/dist/current-json-BkatBzF7.js.map +0 -1
  92. package/dist/doctor-B8h9GCN9.js.map +0 -1
  93. package/dist/fsck-DEz9lyCy.js.map +0 -1
  94. package/dist/indexes-BXn7a06a.js +0 -297
  95. package/dist/indexes-BXn7a06a.js.map +0 -1
  96. package/dist/log-walk-DIru96UT.js.map +0 -1
  97. package/dist/maintenance-Bn6ul9aV.js +0 -758
  98. package/dist/maintenance-Bn6ul9aV.js.map +0 -1
  99. package/dist/query-DcSbFLJt.js.map +0 -1
  100. package/dist/rebuild-index-C5gTXryd.js +0 -119
  101. package/dist/rebuild-index-C5gTXryd.js.map +0 -1
  102. package/dist/restore-CbKVMMpm.js.map +0 -1
  103. package/dist/snapshot-D7C4_FSl.js +0 -71
  104. package/dist/snapshot-D7C4_FSl.js.map +0 -1
  105. package/dist/snapshot-z_N9hpTe.js +0 -917
  106. package/dist/snapshot-z_N9hpTe.js.map +0 -1
  107. package/dist/src-Chafbw8r.js.map +0 -1
  108. package/dist/src-Cr9C7_tT.js.map +0 -1
  109. package/dist/src-n0Te1r98.js.map +0 -1
  110. package/dist/subcommand-BWs6K7zb.js +0 -110
  111. package/dist/subcommand-BWs6K7zb.js.map +0 -1
  112. package/dist/validate-DhH1lO8I.js.map +0 -1
@@ -1,9 +1,129 @@
1
- import { a as SHARED_SECRET_MISSING_MESSAGE, t as loadAppConfig } from "./config-Bsg8wgwo.js";
1
+ import { f as SHARED_SECRET_MISSING_MESSAGE, t as loadAppConfig } from "./config-DVfDGyw1.js";
2
+ import { a as uuid, n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
2
3
  import { i as isJsonMode, o as BaerlyError, t as color } from "./baerly.js";
3
- import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
4
4
  import { a as defaultRunner, i as parse, n as ensureBindings, r as parseR2Bindings } from "./cloudflare-CINJPKCW.js";
5
5
  import { resolve } from "node:path";
6
6
  import { existsSync, readFileSync } from "node:fs";
7
+ //#region ../protocol/src/storage/probe-cas.ts
8
+ const isConflict = (error) => error instanceof BaerlyError && error.code === "Conflict";
9
+ /**
10
+ * Runtime probe that a live `Storage` backend honours the conditional
11
+ * writes the protocol depends on. The storage conformance suite asserts
12
+ * the same semantics in CI for every shipped adapter, but a deployment
13
+ * may point baerly at an arbitrary S3-compatible store; a backend that
14
+ * silently *ignores* `If-Match` (returns 200 instead of rejecting a
15
+ * stale write) causes silent lost-update corruption — every commit
16
+ * CAS-advances `current.json`, and the no-lease maintenance fold relies
17
+ * on the same fence. This is the fail-loud, deploy-time analogue of the
18
+ * conformance CAS block.
19
+ *
20
+ * Writes a single throwaway sentinel under `keyPrefix` and deletes it on
21
+ * the way out (even on failure). Two checks, mirroring the conformance
22
+ * suite:
23
+ * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).
24
+ * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:"*"` over an existing
25
+ * key must reject (Conflict).
26
+ *
27
+ * A rejected write surfaces as a `BaerlyError` with `code === "Conflict"`
28
+ * (the contract `Storage.put` documents); anything else — a resolved
29
+ * promise, or a non-Conflict error — means the backend does not honour
30
+ * the condition and is reported as a failed check rather than thrown.
31
+ */
32
+ const probeCas = async (storage, opts) => {
33
+ const key = `${opts?.keyPrefix ?? ""}__baerly_cas_probe__/${uuid()}`;
34
+ const enc = new TextEncoder();
35
+ const signal = opts?.signal;
36
+ const checks = [];
37
+ try {
38
+ await storage.put(key, enc.encode("v1"), { signal });
39
+ try {
40
+ await storage.put(key, enc.encode("v2"), {
41
+ ifMatch: "\"baerly-cas-probe-stale\"",
42
+ signal
43
+ });
44
+ checks.push({
45
+ name: "ifMatch-stale",
46
+ ok: false,
47
+ detail: "PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk)."
48
+ });
49
+ } catch (error) {
50
+ checks.push(isConflict(error) ? {
51
+ name: "ifMatch-stale",
52
+ ok: true,
53
+ detail: "stale If-Match rejected (Conflict), as required."
54
+ } : {
55
+ name: "ifMatch-stale",
56
+ ok: false,
57
+ detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
58
+ });
59
+ }
60
+ try {
61
+ await storage.put(key, enc.encode("v3"), {
62
+ ifNoneMatch: "*",
63
+ signal
64
+ });
65
+ checks.push({
66
+ name: "ifNoneMatch-exists",
67
+ ok: false,
68
+ detail: "PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe)."
69
+ });
70
+ } catch (error) {
71
+ checks.push(isConflict(error) ? {
72
+ name: "ifNoneMatch-exists",
73
+ ok: true,
74
+ detail: "If-None-Match:\"*\" over an existing key rejected (Conflict), as required."
75
+ } : {
76
+ name: "ifNoneMatch-exists",
77
+ ok: false,
78
+ detail: `If-None-Match:"*" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`
79
+ });
80
+ }
81
+ } finally {
82
+ try {
83
+ await storage.delete(key, signal === void 0 ? void 0 : { signal });
84
+ } catch {}
85
+ }
86
+ return {
87
+ ok: checks.every((c) => c.ok),
88
+ checks
89
+ };
90
+ };
91
+ //#endregion
92
+ //#region src/doctor/cas.ts
93
+ /**
94
+ * `baerly doctor --bucket <uri>` — live backend CAS probe.
95
+ *
96
+ * Unlike the cloudflare deploy-invariant walk (which only inspects
97
+ * config files), this mode connects to a real bucket and verifies it
98
+ * honours the conditional writes the protocol depends on: every commit
99
+ * CAS-advances `current.json` with `If-Match`, and the no-lease
100
+ * maintenance fold relies on the same fence. A store that silently
101
+ * ignores `If-Match` (returns 200 instead of rejecting a stale write)
102
+ * causes silent lost-update corruption — this is the fail-loud,
103
+ * deploy-time analogue of the conformance CAS block.
104
+ *
105
+ * Writes a single throwaway sentinel and deletes it; see
106
+ * {@link probeCas}.
107
+ */
108
+ const CAS_FIX = "Point baerly at an S3-compatible store that honours conditional writes (If-Match + If-None-Match). Real AWS S3, Cloudflare R2, and GCS do; a custom gateway / proxy may be stripping conditional headers — check it returns 412 on a stale If-Match.";
109
+ /**
110
+ * Run the live CAS round-trip against `storage` and shape the result
111
+ * as a {@link DoctorReport}. Status is `error` iff any sub-check failed
112
+ * (a non-conformant backend is a hard blocker, not a warning).
113
+ */
114
+ const doctorCas = async (storage, keyPrefix) => {
115
+ const result = await probeCas(storage, { keyPrefix });
116
+ return {
117
+ findings: result.checks.map((c) => ({
118
+ severity: c.ok ? "ok" : "error",
119
+ check: `cas-${c.name}`,
120
+ message: c.detail,
121
+ ...c.ok ? {} : { fix: CAS_FIX }
122
+ })),
123
+ status: result.ok ? "ok" : "error"
124
+ };
125
+ };
126
+ //#endregion
7
127
  //#region src/doctor/cloudflare.ts
8
128
  /**
9
129
  * `baerly doctor --target=cloudflare` — walks the Cloudflare
@@ -260,6 +380,11 @@ const DOCTOR_ARGS = {
260
380
  description: "Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).",
261
381
  valueHint: "cloudflare"
262
382
  },
383
+ bucket: {
384
+ type: "string",
385
+ description: "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.",
386
+ valueHint: "s3://bucket/prefix"
387
+ },
263
388
  fix: {
264
389
  type: "boolean",
265
390
  description: "Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual)."
@@ -281,16 +406,16 @@ const colorize = (severity, glyph) => {
281
406
  if (severity === "info") return color.dim(glyph);
282
407
  return glyph;
283
408
  };
284
- const renderReport = (target, report) => {
409
+ const renderReport = (label, report) => {
285
410
  if (isJsonMode()) {
286
411
  process.stdout.write(`${JSON.stringify({ result: {
287
412
  command: "doctor",
288
- target,
413
+ [label.kind]: label.value,
289
414
  ...report
290
415
  } })}\n`);
291
416
  return;
292
417
  }
293
- process.stdout.write(`baerly doctor --target=${target}\n\n`);
418
+ process.stdout.write(`baerly doctor --${label.kind}=${label.value}\n\n`);
294
419
  let okCount = 0;
295
420
  let warningCount = 0;
296
421
  let errorCount = 0;
@@ -309,6 +434,15 @@ const bundle = defineBaerlySubcommand({
309
434
  meta: { description: "Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target." },
310
435
  args: DOCTOR_ARGS,
311
436
  handler: async (args) => {
437
+ if (args.bucket !== void 0) {
438
+ const { storage, keyPrefix } = await parseBucketUri(args.bucket);
439
+ const report = await doctorCas(storage, keyPrefix);
440
+ renderReport({
441
+ kind: "bucket",
442
+ value: args.bucket
443
+ }, report);
444
+ return report.status === "error" ? 2 : 0;
445
+ }
312
446
  const config = await loadAppConfig();
313
447
  const target = args.target ?? config.target;
314
448
  if (target === "cloudflare") {
@@ -316,7 +450,10 @@ const bundle = defineBaerlySubcommand({
316
450
  runner: defaultRunner(),
317
451
  ...args.fix === true && { fix: true }
318
452
  });
319
- renderReport(target, report);
453
+ renderReport({
454
+ kind: "target",
455
+ value: target
456
+ }, report);
320
457
  return report.status === "error" ? 2 : 0;
321
458
  }
322
459
  throw new BaerlyError("InvalidConfig", `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. (Node variants self-validate at scaffold time; the example IS the contract.)`);
@@ -328,4 +465,4 @@ bundle.run;
328
465
  //#endregion
329
466
  export { doctor };
330
467
 
331
- //# sourceMappingURL=doctor-B8h9GCN9.js.map
468
+ //# sourceMappingURL=doctor-Db-hzPmE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doctor-Db-hzPmE.js","names":[],"sources":["../packages/protocol/src/storage/probe-cas.ts","../packages/cli/src/doctor/cas.ts","../packages/cli/src/doctor/cloudflare.ts","../packages/cli/src/doctor.ts"],"sourcesContent":["import { BaerlyError } from \"../errors.ts\";\nimport { uuid } from \"../types.ts\";\nimport type { Storage } from \"./types.ts\";\n\nconst isConflict = (error: unknown): boolean =>\n error instanceof BaerlyError && error.code === \"Conflict\";\n\n/** One CAS sub-check's outcome. */\nexport interface CasProbeCheck {\n /** Stable identifier (`ifMatch-stale` / `ifNoneMatch-exists`). */\n readonly name: string;\n /** `true` iff the backend rejected the conditional write as required. */\n readonly ok: boolean;\n /** Human-readable detail — what was expected vs. observed. */\n readonly detail: string;\n}\n\n/** Aggregate result of {@link probeCas}. `ok` iff every sub-check passed. */\nexport interface CasProbeResult {\n readonly ok: boolean;\n readonly checks: readonly CasProbeCheck[];\n}\n\n/**\n * Runtime probe that a live `Storage` backend honours the conditional\n * writes the protocol depends on. The storage conformance suite asserts\n * the same semantics in CI for every shipped adapter, but a deployment\n * may point baerly at an arbitrary S3-compatible store; a backend that\n * silently *ignores* `If-Match` (returns 200 instead of rejecting a\n * stale write) causes silent lost-update corruption — every commit\n * CAS-advances `current.json`, and the no-lease maintenance fold relies\n * on the same fence. This is the fail-loud, deploy-time analogue of the\n * conformance CAS block.\n *\n * Writes a single throwaway sentinel under `keyPrefix` and deletes it on\n * the way out (even on failure). Two checks, mirroring the conformance\n * suite:\n * - `ifMatch-stale`: a PUT with a stale `ifMatch` must reject (Conflict).\n * - `ifNoneMatch-exists`: a PUT with `ifNoneMatch:\"*\"` over an existing\n * key must reject (Conflict).\n *\n * A rejected write surfaces as a `BaerlyError` with `code === \"Conflict\"`\n * (the contract `Storage.put` documents); anything else — a resolved\n * promise, or a non-Conflict error — means the backend does not honour\n * the condition and is reported as a failed check rather than thrown.\n */\nexport const probeCas = async (\n storage: Storage,\n opts?: { keyPrefix?: string; signal?: AbortSignal },\n): Promise<CasProbeResult> => {\n const prefix = opts?.keyPrefix ?? \"\";\n const key = `${prefix}__baerly_cas_probe__/${uuid()}`;\n const enc = new TextEncoder();\n const signal = opts?.signal;\n\n const checks: CasProbeCheck[] = [];\n try {\n const first = await storage.put(key, enc.encode(\"v1\"), { signal });\n\n // ── Check 1: a stale ifMatch must be rejected. ──────────────────\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v2\"), { ifMatch: '\"baerly-cas-probe-stale\"', signal });\n checks.push({\n name: \"ifMatch-stale\",\n ok: false,\n detail:\n \"PUT with a stale If-Match was ACCEPTED — backend ignores If-Match (silent lost-update risk).\",\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifMatch-stale\",\n ok: true,\n detail: \"stale If-Match rejected (Conflict), as required.\",\n }\n : {\n name: \"ifMatch-stale\",\n ok: false,\n detail: `stale If-Match raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n // ── Check 2: ifNoneMatch:\"*\" over an existing key must reject. ──\n try {\n // Stryker disable next-line StringLiteral: body content is irrelevant to CAS probe; only the conditional header is tested\n await storage.put(key, enc.encode(\"v3\"), { ifNoneMatch: \"*\", signal });\n checks.push({\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail:\n 'PUT with If-None-Match:\"*\" over an existing key was ACCEPTED — backend ignores If-None-Match (create-only writes unsafe).',\n });\n } catch (error) {\n checks.push(\n isConflict(error)\n ? {\n name: \"ifNoneMatch-exists\",\n ok: true,\n detail: 'If-None-Match:\"*\" over an existing key rejected (Conflict), as required.',\n }\n : {\n name: \"ifNoneMatch-exists\",\n ok: false,\n detail: `If-None-Match:\"*\" raised a non-Conflict error: ${error instanceof Error ? error.message : String(error)}`,\n },\n );\n }\n\n void first;\n } finally {\n // Best-effort cleanup — never let a delete failure mask the verdict.\n try {\n await storage.delete(key, signal === undefined ? undefined : { signal });\n } catch {\n /* ignore */\n }\n }\n\n return { ok: checks.every((c) => c.ok), checks };\n};\n","/**\n * `baerly doctor --bucket <uri>` — live backend CAS probe.\n *\n * Unlike the cloudflare deploy-invariant walk (which only inspects\n * config files), this mode connects to a real bucket and verifies it\n * honours the conditional writes the protocol depends on: every commit\n * CAS-advances `current.json` with `If-Match`, and the no-lease\n * maintenance fold relies on the same fence. A store that silently\n * ignores `If-Match` (returns 200 instead of rejecting a stale write)\n * causes silent lost-update corruption — this is the fail-loud,\n * deploy-time analogue of the conformance CAS block.\n *\n * Writes a single throwaway sentinel and deletes it; see\n * {@link probeCas}.\n */\n\nimport { probeCas, type Storage } from \"@baerly/protocol\";\nimport type { DoctorFinding, DoctorReport } from \"./cloudflare.ts\";\n\nconst CAS_FIX =\n \"Point baerly at an S3-compatible store that honours conditional writes \" +\n \"(If-Match + If-None-Match). Real AWS S3, Cloudflare R2, and GCS do; a \" +\n \"custom gateway / proxy may be stripping conditional headers — check it \" +\n \"returns 412 on a stale If-Match.\";\n\n/**\n * Run the live CAS round-trip against `storage` and shape the result\n * as a {@link DoctorReport}. Status is `error` iff any sub-check failed\n * (a non-conformant backend is a hard blocker, not a warning).\n */\nexport const doctorCas = async (storage: Storage, keyPrefix: string): Promise<DoctorReport> => {\n const result = await probeCas(storage, { keyPrefix });\n const findings: DoctorFinding[] = result.checks.map((c) => ({\n severity: c.ok ? \"ok\" : \"error\",\n check: `cas-${c.name}`,\n message: c.detail,\n ...(c.ok ? {} : { fix: CAS_FIX }),\n }));\n return { findings, status: result.ok ? \"ok\" : \"error\" };\n};\n","/**\n * `baerly doctor --target=cloudflare` — walks the Cloudflare\n * deploy invariants and reports. With `--fix`, remediates what\n * can be safely auto-fixed (R2 bucket creation; secret prompts\n * are still user-driven because `wrangler secret put` reads\n * stdin interactively).\n *\n * Checks (each emitting one {@link DoctorFinding}):\n * 1. `wrangler.jsonc` exists at the package root.\n * 2. Each declared R2 binding exists in CF\n * (`wrangler r2 bucket info`).\n * 3. Each `requiredSecrets` entry is in `wrangler secret list`.\n * 4. If `cloudflareAccess` is set in `baerly.config.ts`,\n * `audienceTag` is 64 lowercase-hex chars and `teamDomain`\n * is non-empty.\n * 5. If `triggers.crons` is empty, warn that the maintenance\n * loop won't run.\n * 6. If `baerly.config.ts:domain` is set but `wrangler.jsonc`\n * doesn't declare a matching `routes` entry, warn.\n *\n * Output is a structured {@link DoctorReport} that\n * `packages/cli/src/doctor.ts` renders as either a checklist\n * (text mode) or a JSON envelope (`--json` mode).\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { parse, type ParseError } from \"jsonc-parser\";\nimport { BaerlyError, SHARED_SECRET_MISSING_MESSAGE } from \"@baerly/protocol\";\nimport type { AppConfig } from \"../config.ts\";\nimport { ensureBindings, parseR2Bindings, type ProcessRunner } from \"../deploy/cloudflare.ts\";\n\n/** One finding from a `baerly doctor` walk. */\nexport interface DoctorFinding {\n /** Severity. `ok` / `info` don't move the overall status. */\n readonly severity: \"ok\" | \"info\" | \"warning\" | \"error\";\n /** Short check name — stable, machine-readable. */\n readonly check: string;\n /** Human-friendly description. */\n readonly message: string;\n /** Optional remediation hint. */\n readonly fix?: string;\n}\n\n/** Result of a `baerly doctor` walk. */\nexport interface DoctorReport {\n readonly findings: readonly DoctorFinding[];\n /**\n * Overall: `ok` only when every finding has severity `ok` or\n * `info`. `warning` when the worst finding is a warning. `error`\n * when any finding is an error.\n */\n readonly status: \"ok\" | \"warning\" | \"error\";\n}\n\nconst rollupStatus = (findings: readonly DoctorFinding[]): DoctorReport[\"status\"] => {\n let worst: DoctorReport[\"status\"] = \"ok\";\n for (const f of findings) {\n if (f.severity === \"error\") {\n return \"error\";\n }\n if (f.severity === \"warning\") {\n worst = \"warning\";\n }\n }\n return worst;\n};\n\n/**\n * Read the declared cron schedule from `wrangler.jsonc`. Returns\n * `[]` when missing — caller treats empty as a warning.\n */\nconst readDeclaredCrons = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { triggers?: { crons?: unknown } }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const crons = obj.triggers?.crons;\n if (!Array.isArray(crons)) {\n return [];\n }\n return crons.filter((c): c is string => typeof c === \"string\");\n};\n\n/** Read declared `routes[].pattern` array from `wrangler.jsonc`. */\nconst readDeclaredRoutePatterns = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { routes?: unknown }\n | undefined;\n if (errors.length > 0 || obj === undefined) {\n return [];\n }\n const routes = obj.routes;\n if (!Array.isArray(routes)) {\n return [];\n }\n return routes\n .map((r) =>\n r !== null && typeof r === \"object\" ? (r as { pattern?: unknown }).pattern : undefined,\n )\n .filter((p): p is string => typeof p === \"string\");\n};\n\n/** Read declared `vars` keys from `wrangler.jsonc`. */\nconst readDeclaredVarKeys = (wranglerPath: string): readonly string[] => {\n const text = readFileSync(wranglerPath, \"utf8\");\n const errors: ParseError[] = [];\n const obj = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as\n | { vars?: Record<string, unknown> }\n | undefined;\n if (errors.length > 0 || obj === undefined || obj.vars === undefined) {\n return [];\n }\n return Object.keys(obj.vars);\n};\n\n/**\n * Walk the Cloudflare deploy invariants. With `opts.fix === true`,\n * remediate the auto-fixable issues (bucket creation). Secret\n * prompts stay user-driven.\n */\nexport const doctorCloudflare = async (\n config: AppConfig,\n opts: {\n readonly runner?: ProcessRunner;\n readonly fix?: boolean;\n readonly cwd?: string;\n } = {},\n): Promise<DoctorReport> => {\n const repoRoot = opts.cwd ?? config.repoRoot;\n const wranglerPath = resolve(repoRoot, \"wrangler.jsonc\");\n const findings: DoctorFinding[] = [];\n\n // 1. wrangler.jsonc presence.\n if (!existsSync(wranglerPath)) {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc\",\n message: `Expected wrangler.jsonc at the package root: ${wranglerPath}.`,\n fix: \"Re-scaffold (npm create baerly@latest) or restore the file from git.\",\n });\n return { findings, status: rollupStatus(findings) };\n }\n findings.push({\n severity: \"ok\",\n check: \"wrangler.jsonc\",\n message: `${wranglerPath} found.`,\n });\n\n // 2. R2 bindings — parse first, then probe each.\n let declared: readonly { binding: string; bucket_name: string }[];\n try {\n declared = parseR2Bindings(wranglerPath);\n } catch (error) {\n if (error instanceof BaerlyError && error.code === \"InvalidConfig\") {\n findings.push({\n severity: \"error\",\n check: \"wrangler.jsonc.parse\",\n message: error.message,\n });\n return { findings, status: rollupStatus(findings) };\n }\n throw error;\n }\n\n if (opts.fix === true && opts.runner !== undefined) {\n // Run the same provisioning path the deploy fallback uses.\n // Any failure here surfaces as an error finding rather than\n // throwing — doctor's job is to report.\n try {\n await ensureBindings(opts.runner, repoRoot, wranglerPath);\n } catch (error) {\n findings.push({\n severity: \"error\",\n check: \"r2.fix\",\n message: error instanceof Error ? error.message : \"unknown error during ensureBindings\",\n });\n }\n }\n\n if (opts.runner !== undefined) {\n for (const { bucket_name } of declared) {\n const info = await opts.runner.run(\n \"wrangler\",\n [\"r2\", \"bucket\", \"info\", bucket_name],\n repoRoot,\n );\n if (info.code === 0) {\n findings.push({\n severity: \"ok\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" exists.`,\n });\n } else {\n findings.push({\n severity: \"error\",\n check: `r2.${bucket_name}`,\n message: `R2 bucket \"${bucket_name}\" not found.`,\n fix: `wrangler r2 bucket create ${bucket_name} (or re-run with --fix)`,\n });\n }\n }\n } else {\n findings.push({\n severity: \"info\",\n check: \"r2.skip\",\n message: \"no runner supplied; skipped R2 bucket probes.\",\n });\n }\n\n // 3. requiredSecrets — best-effort.\n //\n // `configured` is lifted to the outer scope so the auth-posture\n // block below can read the deployed secret set without re-running\n // `wrangler secret list`. Empty when the runner is absent or the\n // listing call failed.\n const required = config.requiredSecrets ?? [\"SHARED_SECRET\"];\n let configured: readonly string[] = [];\n if (opts.runner !== undefined && required.length > 0) {\n const r = await opts.runner.run(\"wrangler\", [\"secret\", \"list\"], repoRoot);\n if (r.code !== 0) {\n findings.push({\n severity: \"warning\",\n check: \"secrets\",\n message: \"could not list secrets (wrangler exit non-zero); skipping check.\",\n });\n } else {\n try {\n const parsed = JSON.parse(r.stdout) as unknown;\n if (Array.isArray(parsed)) {\n configured = parsed\n .map((s) =>\n s !== null && typeof s === \"object\" ? (s as { name?: unknown }).name : undefined,\n )\n .filter((n): n is string => typeof n === \"string\");\n }\n } catch {\n // fall through with empty configured set\n }\n for (const name of required) {\n if (configured.includes(name)) {\n findings.push({\n severity: \"ok\",\n check: `secret.${name}`,\n message: `secret ${name} is set.`,\n });\n } else {\n findings.push({\n severity: \"warning\",\n check: `secret.${name}`,\n message: `secret ${name} is required but unset.`,\n fix: `wrangler secret put ${name}`,\n });\n }\n }\n }\n } else if (required.length > 0) {\n findings.push({\n severity: \"info\",\n check: \"secrets.skip\",\n message: \"no runner supplied; skipped secret checks.\",\n });\n }\n\n // 7. config.auth — graduated-auth posture. Walks the typed `auth`\n // field added in `packages/protocol/src/app-config.ts`.\n // FAIL: shared-secret without SHARED_SECRET set on the worker.\n // WARN: auth: \"none\" + deploy target (operator may have a\n // network gate in front; surface it so they confirm).\n // INFO: CF Access vars present + adapter uses config.auth (auth\n // is using config.auth, CF Access env is inert).\n //\n // The presence of the typed field is guaranteed by the loader\n // (config.ts throws on omission), so we walk every loaded config\n // without an existence guard.\n if (config.auth === \"none\") {\n // Deploy-target check: \"cloudflare\" / \"node\" are the only valid\n // values, and both ship to a network-reachable runtime. We warn\n // unconditionally — the doctor's job is to surface the choice,\n // not to second-guess whether the operator's network seam (CF\n // Access, intranet ACL, Tunnel) is upstream.\n findings.push({\n severity: \"warning\",\n check: \"auth.none-on-deploy\",\n message:\n `baerly.config.ts has auth: \"none\" and ships to target=${JSON.stringify(config.target)}. ` +\n \"Every request will resolve to config.tenant with no header check. \" +\n \"Put a network gate in front (CF Access, an upstream JWT, Cloudflare Tunnel, intranet ACL, …) \" +\n 'or change `auth` to \"shared-secret\" or pass a custom `verifier:` on the adapter factory.',\n fix:\n 'Edit baerly.config.ts: set `auth: \"shared-secret\"` and run `wrangler secret put SHARED_SECRET`; ' +\n 'or keep `auth: \"none\"` and wire CF Access in `wrangler.jsonc:vars` + pass a `verifier:` override in `src/server/index.ts`.',\n });\n }\n\n if (config.auth === \"shared-secret\" && opts.runner !== undefined) {\n // Mirror the FAIL message wording from the adapter's runtime\n // throw. Locked via `SHARED_SECRET_MISSING_MESSAGE` so doctor +\n // adapter stay in sync.\n //\n // If `configured` is still empty here, the `wrangler secret list`\n // invocation either failed (we already warned with the \"secrets\"\n // finding above) or really lists no secrets. Either way the\n // operator-facing remediation is the same.\n const requiredSecret = \"SHARED_SECRET\";\n if (!configured.includes(requiredSecret)) {\n findings.push({\n severity: \"error\",\n check: \"auth.shared-secret-missing\",\n message: SHARED_SECRET_MISSING_MESSAGE,\n fix:\n \"wrangler secret put SHARED_SECRET (for production) \" +\n \"or add SHARED_SECRET=<value> to .dev.vars (for `wrangler dev`).\",\n });\n }\n }\n\n // INFO: CF Access env vars in wrangler.jsonc:vars but the adapter\n // is using `config.auth` for the verifier (so the env values are\n // inert). We can't statically parse the user's worker source —\n // surface the heuristic.\n const varKeys = new Set(readDeclaredVarKeys(wranglerPath));\n if (\n varKeys.has(\"CF_ACCESS_TEAM_DOMAIN\") &&\n varKeys.has(\"CF_ACCESS_AUDIENCE_TAG\")\n ) {\n findings.push({\n severity: \"info\",\n check: \"auth.cf-access-inert\",\n message:\n `CF Access env vars (CF_ACCESS_TEAM_DOMAIN, CF_ACCESS_AUDIENCE_TAG) are set in ${wranglerPath} ` +\n `but the adapter uses config.auth=${JSON.stringify(config.auth)}. ` +\n `To wire CF Access, pass \\`verifier: cloudflareAccess({ teamDomain, audienceTag })\\` on the baerlyWorker factory.`,\n });\n }\n\n // 4. cloudflareAccess — when configured, audience tag must be\n // 64 lowercase-hex chars.\n if (config.cloudflareAccess !== undefined) {\n const { teamDomain, audienceTag } = config.cloudflareAccess;\n if (teamDomain.length === 0) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.teamDomain\",\n message: \"cloudflareAccess.teamDomain in baerly.config.ts is empty.\",\n });\n }\n if (!/^[0-9a-f]{64}$/.test(audienceTag)) {\n findings.push({\n severity: \"error\",\n check: \"cloudflareAccess.audienceTag\",\n message: `cloudflareAccess.audienceTag must be 64 lowercase-hex chars (got ${JSON.stringify(audienceTag)}).`,\n fix: \"Copy the AUD tag from the Cloudflare Access app's configuration tab.\",\n });\n } else if (teamDomain.length > 0) {\n findings.push({\n severity: \"ok\",\n check: \"cloudflareAccess\",\n message: `cloudflareAccess audience tag is well-formed; team domain \"${teamDomain}\".`,\n });\n }\n }\n\n // 5. Cron triggers — empty list means the maintenance loop won't\n // run.\n const crons = readDeclaredCrons(wranglerPath);\n if (crons.length === 0) {\n findings.push({\n severity: \"warning\",\n check: \"triggers.crons\",\n message: \"no cron triggers declared; the maintenance loop will not run automatically.\",\n fix: `Add \"triggers\": { \"crons\": [\"* * * * *\"] } to ${wranglerPath}.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"triggers.crons\",\n message: `cron trigger${crons.length === 1 ? \"\" : \"s\"} ${crons.map((c) => JSON.stringify(c)).join(\", \")} declared.`,\n });\n }\n\n // 6. domain ↔ routes coherence.\n if (config.domain !== undefined && config.domain.length > 0) {\n const patterns = readDeclaredRoutePatterns(wranglerPath);\n const expectedPrefix = `${config.domain}/`;\n const hasMatch = patterns.some(\n (p) => p === config.domain || p === expectedPrefix || p.startsWith(expectedPrefix),\n );\n if (!hasMatch) {\n findings.push({\n severity: \"warning\",\n check: \"routes.domain\",\n message: `baerly.config.ts declares domain ${JSON.stringify(config.domain)} but ${wranglerPath} has no matching routes[].pattern.`,\n fix: `Add { \"pattern\": \"${config.domain}/*\", \"custom_domain\": true } to wrangler.jsonc:routes.`,\n });\n } else {\n findings.push({\n severity: \"ok\",\n check: \"routes.domain\",\n message: `routes[].pattern matches domain ${JSON.stringify(config.domain)}.`,\n });\n }\n }\n\n return { findings, status: rollupStatus(findings) };\n};\n","/**\n * `baerly doctor` — citty dispatcher for deploy-invariant checks.\n *\n * Two modes:\n * - `--bucket <uri>` — connect to a live bucket and probe its CAS\n * support (the protocol's load-bearing backend prerequisite). This\n * mode WRITES + deletes one throwaway sentinel; see\n * {@link doctorCas}. Independent of `baerly.config.ts` / `--target`.\n * - otherwise — reads `baerly.config.ts:target` and routes to\n * {@link doctorCloudflare} (read-only deploy-invariant checks). The\n * Node target self-validates at scaffold time — the example IS the\n * contract — so it has no doctor backend.\n *\n * Drift detection, index rebuilds, and writes/min health are separate\n * verbs:\n * - `baerly admin fsck --indexes [--fix]` — index drift.\n * - `baerly admin usage` — writes/min M-size graduation.\n * - `baerly admin rebuild-index` — single-index reconciliation.\n *\n * Renders the returned {@link DoctorReport} into either a\n * stdout checklist (text mode) or a JSON envelope (`--json`\n * mode).\n *\n * Exit-code contract (mirrors `baerly deploy`):\n * - 0 success — report status is `ok` or `warning`.\n * - 1 user error (InvalidConfig, unknown target, missing config).\n * - 2 storage / external error.\n * - 3 protocol invariant.\n *\n * A `warning` status returns exit 0 (the user can deploy; we just\n * flagged a maintenance / coherence issue). An `error` status\n * returns exit 2 unless the underlying cause was an InvalidConfig\n * (which already returned 1 via a thrown BaerlyError).\n */\n\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError } from \"@baerly/protocol\";\nimport { parseBucketUri } from \"./bucket-uri.ts\";\nimport { loadAppConfig } from \"./config.ts\";\nimport { doctorCas } from \"./doctor/cas.ts\";\nimport { doctorCloudflare, type DoctorReport } from \"./doctor/cloudflare.ts\";\nimport { defaultRunner } from \"./runner.ts\";\nimport { color, isJsonMode } from \"./output.ts\";\nimport { defineBaerlySubcommand } from \"./subcommand.ts\";\n\nconst DOCTOR_ARGS = {\n target: {\n type: \"string\",\n description:\n 'Override `baerly.config.ts:target`. Only \"cloudflare\" supported (Node variants self-validate at scaffold time).',\n valueHint: \"cloudflare\",\n },\n bucket: {\n type: \"string\",\n description:\n \"Live-probe a bucket's CAS support (writes + deletes one sentinel; verifies If-Match / If-None-Match are honoured). s3://, file:///, or memory:// URI. Independent of --target.\",\n valueHint: \"s3://bucket/prefix\",\n },\n fix: {\n type: \"boolean\",\n description:\n \"Remediate auto-fixable findings (R2 bucket creation; secret prompts stay manual).\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\nconst SEVERITY_GLYPH: Record<string, string> = {\n ok: \"✓\",\n info: \"•\",\n warning: \"⚠\",\n error: \"✗\",\n};\n\nconst colorize = (severity: string, glyph: string): string => {\n if (severity === \"error\") {\n return color.red(glyph);\n }\n if (severity === \"warning\") {\n return color.yellow(glyph);\n }\n if (severity === \"info\") {\n return color.dim(glyph);\n }\n return glyph;\n};\n\nconst renderReport = (\n label: { kind: \"target\" | \"bucket\"; value: string },\n report: DoctorReport,\n): void => {\n if (isJsonMode()) {\n process.stdout.write(\n `${JSON.stringify({ result: { command: \"doctor\", [label.kind]: label.value, ...report } })}\\n`,\n );\n return;\n }\n process.stdout.write(`baerly doctor --${label.kind}=${label.value}\\n\\n`);\n let okCount = 0;\n let warningCount = 0;\n let errorCount = 0;\n for (const f of report.findings) {\n const glyph = SEVERITY_GLYPH[f.severity] ?? \"•\";\n process.stdout.write(` ${colorize(f.severity, glyph)} ${f.message}\\n`);\n if (f.fix !== undefined) {\n process.stdout.write(` fix: ${f.fix}\\n`);\n }\n if (f.severity === \"ok\") {\n okCount += 1;\n } else if (f.severity === \"warning\") {\n warningCount += 1;\n } else if (f.severity === \"error\") {\n errorCount += 1;\n }\n }\n process.stdout.write(\n `\\nStatus: ${errorCount} error${errorCount === 1 ? \"\" : \"s\"}, ${warningCount} warning${warningCount === 1 ? \"\" : \"s\"}, ${okCount} ok.\\n`,\n );\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"doctor\",\n meta: {\n description:\n \"Walk the deploy invariants and report findings. Dispatches by baerly.config.ts:target.\",\n },\n args: DOCTOR_ARGS,\n handler: async (args) => {\n // --bucket is a standalone live-probe mode: it connects to a real\n // bucket and checks CAS, independent of baerly.config.ts / --target.\n if (args.bucket !== undefined) {\n const { storage, keyPrefix } = await parseBucketUri(args.bucket);\n const report = await doctorCas(storage, keyPrefix);\n renderReport({ kind: \"bucket\", value: args.bucket }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n const config = await loadAppConfig();\n const target = args.target ?? config.target;\n if (target === \"cloudflare\") {\n const report = await doctorCloudflare(config, {\n runner: defaultRunner(),\n ...(args.fix === true && { fix: true }),\n });\n renderReport({ kind: \"target\", value: target }, report);\n return report.status === \"error\" ? 2 : 0;\n }\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly doctor: target ${JSON.stringify(target)} has no doctor backend. ` +\n `(Node variants self-validate at scaffold time; the example IS the contract.)`,\n );\n },\n});\n\n/** citty `defineCommand` block for `baerly doctor`. */\nexport const doctor = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDoctor = bundle.run;\n"],"mappings":";;;;;;;AAIA,MAAM,cAAc,UAClB,iBAAiB,eAAe,MAAM,SAAS;;;;;;;;;;;;;;;;;;;;;;;;AAyCjD,MAAa,WAAW,OACtB,SACA,SAC4B;CAE5B,MAAM,MAAM,GADG,MAAM,aAAa,GACZ,uBAAuB,KAAK;CAClD,MAAM,MAAM,IAAI,YAAY;CAC5B,MAAM,SAAS,MAAM;CAErB,MAAM,SAA0B,CAAC;CACjC,IAAI;EACY,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG,EAAE,OAAO,CAAC;EAGjE,IAAI;GAEF,MAAM,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG;IAAE,SAAS;IAA4B;GAAO,CAAC;GACxF,OAAO,KAAK;IACV,MAAM;IACN,IAAI;IACJ,QACE;GACJ,CAAC;EACH,SAAS,OAAO;GACd,OAAO,KACL,WAAW,KAAK,IACZ;IACE,MAAM;IACN,IAAI;IACJ,QAAQ;GACV,IACA;IACE,MAAM;IACN,IAAI;IACJ,QAAQ,+CAA+C,iBAAiB,QAAQ,MAAM,UAAU,OAAO,K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AElB;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,7 +1,6 @@
1
- import { t as parseBucketUri } from "./bucket-uri-BrDEYvzy.js";
1
+ import { n as parseBucketUri, t as defineBaerlySubcommand } from "./subcommand-DZcHcsYp.js";
2
2
  import { o as BaerlyError, r as emitSuccess } from "./baerly.js";
3
- import { n as loadMaterialisedView } from "./plan-Cs17VqjU.js";
4
- import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
3
+ import { n as loadMaterialisedView } from "./plan-DOTl21vq.js";
5
4
  import "node:stream";
6
5
  //#region src/admin/dump.ts
7
6
  const DUMP_ARGS = {
@@ -113,4 +112,4 @@ bundle.run;
113
112
  //#endregion
114
113
  export { dumpCmd };
115
114
 
116
- //# sourceMappingURL=dump-BHo_sIMZ.js.map
115
+ //# sourceMappingURL=dump-BYA55NLP.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dump-BHo_sIMZ.js","names":[],"sources":["../packages/cli/src/admin/dump.ts"],"sourcesContent":["/**\n * `baerly admin dump` — canonical NDJSON of the materialised view.\n *\n * Writes one row per line to stdout, in a strict byte-stable shape so\n * two semantically-equal collections produce byte-equal output. Tests\n * and other programmatic callers can divert the NDJSON output to a\n * file or buffer by passing `{ streams: { stdout } }` to {@link runDump}.\n *\n * Canonical NDJSON dump format:\n *\n * 1. Each row is `{\"_id\":\"<id>\",…}` (no spaces).\n * 2. Row order = ASCII-lex sort on `_id`.\n * 3. Within each row, object keys are sorted ASCII-lex\n * RECURSIVELY — every nested object's keys are sorted too.\n * 4. Numbers as their canonical `JSON.stringify` output.\n * Finite-only (the protocol forbids NaN / Infinity).\n * 5. Strings as `JSON.stringify` output (escape sequences\n * identical to `\\uXXXX` for control codes).\n * 6. One trailing newline at EOF (`\\n`, not `\\r\\n`).\n * 7. No BOM.\n *\n * The round-trip ticket (73) gates byte-equality on this format. A\n * change to any of (1)–(7) is a BREAKING change requiring a\n * round-trip schema-version bump.\n *\n * Empty collection → empty file (no trailing newline) — disambiguates\n * \"zero rows\" from \"one row with empty body\".\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --json JSON envelope (on stdout). Programmatic callers can\n * divert the NDJSON body to a separate writable via the\n * `streams.stdout` option on {@link runDump}.\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Storage / Network / Internal protocol violation.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type Writable } from \"node:stream\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type DocumentValue, type DocumentData } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"../export/index.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst DUMP_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\n/**\n * Recursive byte-stable JSON stringifier. Object keys at every nesting\n * level are sorted ASCII-lex; array element order is preserved as-is.\n * Numbers must be finite (protocol forbids NaN / Infinity in bodies).\n */\nexport const canonicalStringify = (value: DocumentValue): string => {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`,\n );\n }\n return JSON.stringify(value);\n }\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (value === null) {\n // DocumentValue excludes null at the type level, but `unknown` may\n // sneak in via the snapshot fold — be defensive.\n return \"null\";\n }\n if (Array.isArray(value)) {\n const parts = value.map((v) => canonicalStringify(v));\n return `[${parts.join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const keys = Object.keys(value).toSorted();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as Record<string, DocumentValue>)[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: unsupported value type ${typeof value}`,\n );\n};\n\n/**\n * Drain rows to the supplied writable, applying back-pressure on every\n * line. We don't `end()` the stream — the caller owns its lifecycle\n * (`process.stdout` shouldn't be closed; a test-supplied\n * `createWriteStream` flushes on its own `end()`).\n */\nconst writeToSink = async (\n sink: Writable,\n rows: ReadonlyMap<string, DocumentData>,\n): Promise<number> => {\n const ids = [...rows.keys()].toSorted();\n let count = 0;\n for (const id of ids) {\n const body = rows.get(id);\n if (body === undefined) {\n continue;\n }\n // Merge `_id` into the body so the row literal carries it. The\n // map key is authoritative; if a stale `_id` field disagrees, we\n // overwrite it.\n const row: DocumentData = { ...body, _id: id };\n const line = `${canonicalStringify(row)}\\n`;\n if (!sink.write(line)) {\n await new Promise<void>((resolve) => sink.once(\"drain\", resolve));\n }\n count++;\n }\n return count;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.dump\",\n meta: {\n description: \"Canonical NDJSON of the materialised view of one collection.\",\n },\n args: DUMP_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin dump: current.json not found at ${currentJsonKey}`,\n );\n }\n const sink: Writable = ctx.streams?.stdout ?? process.stdout;\n const count = await writeToSink(sink, view);\n emitSuccess({\n command: \"admin.dump\",\n status: \"ok\",\n collection: args.collection,\n dumped: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin dump`. */\nexport const dumpCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDump = bundle.run;\n"],"mappings":";;;;;;AAoDA,MAAM,YAAY;CAChB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,YAAY;EACV,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,MAAM;EACJ,MAAM;EACN,aAAa;CACf;AACF;;;;;;AAOA,MAAa,sBAAsB,UAAiC;CAClE,IAAI,OAAO,UAAU,UAAU;EAC7B,IAAI,CAAC,OAAO,SAAS,KAAK,GACxB,MAAM,IAAI,YACR,mBACA,qDAAqD,OAAO,KAAK,EAAE,sBACrE;EAEF,OAAO,KAAK,UAAU,KAAK;CAC7B;CACA,IAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAChD,OAAO,KAAK,UAAU,KAAK;CAE7B,IAAI,UAAU,MAGZ,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GAErB,OAAO,IADO,MAAM,KAAK,MAAM,mBAAmB,CAAC,CACpC,EAAE,KAAK,GAAG,EAAE;CAE7B,IAAI,OAAO,UAAU,UAAU;EAC7B,MAAM,OAAO,OAAO,KAAK,KAAK,EAAE,SAAS;EACzC,MAAM,QAAkB,CAAC;EACzB,KAAK,MAAM,KAAK,MAAM;GACpB,MAAM,IAAK,MAAwC;GACnD,IAAI,MAAM,KAAA,GACR;GAEF,MAAM,KAAK,GAAG,KAAK,UAAU,CAAC,EAAE,GAAG,mBAAmB,CAAC,GAAG;EAC5D;EACA,OAAO,IAAI,MAAM,KAAK,GAAG,EAAE;CAC7B;CACA,MAAM,IAAI,YACR,mBACA,6CAA6C,OAAO,OACtD;AACF;;;;;;;AAQA,MAAM,cAAc,OAClB,MACA,SACoB;CACpB,MAAM,MAAM,CAAC,GAAG,KAAK,KAAK,CAAC,EAAE,SAAS;CACtC,IAAI,QAAQ;CACZ,KAAK,MAAM,MAAM,KAAK;EACpB,MAAM,OAAO,KAAK,IAAI,EAAE;EACxB,IAAI,SAAS,KAAA,GACX;EAMF,MAAM,OAAO,GAAG,mBAAmB;GADP,GAAG;GAAM,KAAK;EACL,CAAC,EAAE;EACxC,IAAI,CAAC,KAAK,MAAM,IAAI,GAClB,MAAM,IAAI,SAAe,YAAY,KAAK,KAAK,SAAS,OAAO,CAAC;EAElE;CACF;CACA,OAAO;AACT;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aAAa,+DACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EACzF,MAAM,iBAAiB,GAAG,OAAO,UAAU,MAAM,IAAI,UAAU,OAAO,aAAa,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
+ {"version":3,"file":"dump-BYA55NLP.js","names":[],"sources":["../packages/cli/src/admin/dump.ts"],"sourcesContent":["/**\n * `baerly admin dump` — canonical NDJSON of the materialised view.\n *\n * Writes one row per line to stdout, in a strict byte-stable shape so\n * two semantically-equal collections produce byte-equal output. Tests\n * and other programmatic callers can divert the NDJSON output to a\n * file or buffer by passing `{ streams: { stdout } }` to {@link runDump}.\n *\n * Canonical NDJSON dump format:\n *\n * 1. Each row is `{\"_id\":\"<id>\",…}` (no spaces).\n * 2. Row order = ASCII-lex sort on `_id`.\n * 3. Within each row, object keys are sorted ASCII-lex\n * RECURSIVELY — every nested object's keys are sorted too.\n * 4. Numbers as their canonical `JSON.stringify` output.\n * Finite-only (the protocol forbids NaN / Infinity).\n * 5. Strings as `JSON.stringify` output (escape sequences\n * identical to `\\uXXXX` for control codes).\n * 6. One trailing newline at EOF (`\\n`, not `\\r\\n`).\n * 7. No BOM.\n *\n * The round-trip ticket (73) gates byte-equality on this format. A\n * change to any of (1)–(7) is a BREAKING change requiring a\n * round-trip schema-version bump.\n *\n * Empty collection → empty file (no trailing newline) — disambiguates\n * \"zero rows\" from \"one row with empty body\".\n *\n * Args:\n * --bucket Required. Bucket URI.\n * --app Required (or via baerly.config.ts).\n * --tenant Required (or via baerly.config.ts).\n * --collection Required. Collection name.\n * --json JSON envelope (on stdout). Programmatic callers can\n * divert the NDJSON body to a separate writable via the\n * `streams.stdout` option on {@link runDump}.\n *\n * Exit codes:\n * 0 — dump completed.\n * 1 — InvalidConfig (bad bucket URI, missing args).\n * 2 — Storage / Network / Internal protocol violation.\n * 3 — Protocol invariant (Conflict / Internal / InvalidResponse).\n */\n\nimport { type Writable } from \"node:stream\";\nimport { type ArgsDef } from \"citty\";\nimport { BaerlyError, type DocumentValue, type DocumentData } from \"@baerly/protocol\";\nimport { loadMaterialisedView } from \"../export/index.ts\";\nimport { parseBucketUri } from \"../bucket-uri.ts\";\nimport { emitSuccess } from \"../output.ts\";\nimport { defineBaerlySubcommand } from \"../subcommand.ts\";\n\nconst DUMP_ARGS = {\n bucket: {\n type: \"string\",\n required: true,\n description: \"Bucket URI (s3://<bucket>[/<prefix>], file:///<abs>, memory://<bucket>)\",\n valueHint: \"bucket-uri\",\n },\n app: {\n type: \"string\",\n required: false,\n description: \"Application name segment (defaults to baerly.config.ts).\",\n valueHint: \"app\",\n },\n tenant: {\n type: \"string\",\n required: false,\n description: \"Tenant name segment (defaults to baerly.config.ts).\",\n valueHint: \"tenant\",\n },\n collection: {\n type: \"string\",\n required: true,\n description: \"Collection name.\",\n valueHint: \"name\",\n },\n json: {\n type: \"boolean\",\n description: \"Emit a structured JSON envelope to stdout (success) or stderr (error)\",\n },\n} as const satisfies ArgsDef;\n\n/**\n * Recursive byte-stable JSON stringifier. Object keys at every nesting\n * level are sorted ASCII-lex; array element order is preserved as-is.\n * Numbers must be finite (protocol forbids NaN / Infinity in bodies).\n */\nexport const canonicalStringify = (value: DocumentValue): string => {\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: non-finite number in row body (${String(value)}); protocol violation`,\n );\n }\n return JSON.stringify(value);\n }\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (value === null) {\n // DocumentValue excludes null at the type level, but `unknown` may\n // sneak in via the snapshot fold — be defensive.\n return \"null\";\n }\n if (Array.isArray(value)) {\n const parts = value.map((v) => canonicalStringify(v));\n return `[${parts.join(\",\")}]`;\n }\n if (typeof value === \"object\") {\n const keys = Object.keys(value).toSorted();\n const parts: string[] = [];\n for (const k of keys) {\n const v = (value as Record<string, DocumentValue>)[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${JSON.stringify(k)}:${canonicalStringify(v)}`);\n }\n return `{${parts.join(\",\")}}`;\n }\n throw new BaerlyError(\n \"InvalidResponse\",\n `baerly admin dump: unsupported value type ${typeof value}`,\n );\n};\n\n/**\n * Drain rows to the supplied writable, applying back-pressure on every\n * line. We don't `end()` the stream — the caller owns its lifecycle\n * (`process.stdout` shouldn't be closed; a test-supplied\n * `createWriteStream` flushes on its own `end()`).\n */\nconst writeToSink = async (\n sink: Writable,\n rows: ReadonlyMap<string, DocumentData>,\n): Promise<number> => {\n const ids = [...rows.keys()].toSorted();\n let count = 0;\n for (const id of ids) {\n const body = rows.get(id);\n if (body === undefined) {\n continue;\n }\n // Merge `_id` into the body so the row literal carries it. The\n // map key is authoritative; if a stale `_id` field disagrees, we\n // overwrite it.\n const row: DocumentData = { ...body, _id: id };\n const line = `${canonicalStringify(row)}\\n`;\n if (!sink.write(line)) {\n await new Promise<void>((resolve) => sink.once(\"drain\", resolve));\n }\n count++;\n }\n return count;\n};\n\nconst bundle = defineBaerlySubcommand({\n name: \"admin.dump\",\n meta: {\n description: \"Canonical NDJSON of the materialised view of one collection.\",\n },\n args: DUMP_ARGS,\n handler: async (args, ctx) => {\n const bucket = await parseBucketUri(args.bucket);\n const { app, tenant } = await ctx.resolveAppTenant({ app: args.app, tenant: args.tenant });\n const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;\n const view = await loadMaterialisedView({\n storage: bucket.storage,\n currentJsonKey,\n collection: args.collection,\n });\n if (view === null) {\n throw new BaerlyError(\n \"InvalidConfig\",\n `baerly admin dump: current.json not found at ${currentJsonKey}`,\n );\n }\n const sink: Writable = ctx.streams?.stdout ?? process.stdout;\n const count = await writeToSink(sink, view);\n emitSuccess({\n command: \"admin.dump\",\n status: \"ok\",\n collection: args.collection,\n dumped: count,\n });\n return 0;\n },\n});\n\n/** citty `defineCommand` block for `baerly admin dump`. */\nexport const dumpCmd = bundle.cmd;\n\n/**\n * Programmatic entry used by tests. Bypasses citty's `run` wrapper\n * (which would call `process.exit` and kill vitest) and returns the\n * integer exit code directly.\n */\nexport const runDump = bundle.run;\n"],"mappings":";;;;;AAoDA,MAAM,YAAY;CAChB,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,KAAK;EACH,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,QAAQ;EACN,MAAM;EACN,UAAU;EACV,aAAa;EACb,WAAW;CACb;CACA,Y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YAAY,KAAK,KAAK,SAAS,OAAO,CAAC;EAElE;CACF;CACA,OAAO;AACT;AAEA,MAAM,SAAS,uBAAuB;CACpC,MAAM;CACN,MAAM,EACJ,aAAa,+DACf;CACA,MAAM;CACN,SAAS,OAAO,MAAM,QAAQ;EAC5B,MAAM,SAAS,MAAM,eAAe,KAAK,MAAM;EAC/C,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,iBAAiB;GAAE,KAAK,KAAK;GAAK,QAAQ,KAAK;EAAO,CAAC;EACzF,MAAM,iBAAiB,GAAG,OAAO,UAAU,MAAM,IAAI,UAAU,OAAO,aAAa,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 if (issues !== undefined) {\n this.issues = issues;\n }\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;EACb,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAEhB,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 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,8 +1,7 @@
1
- import { t as parseBucketUri } from "./bucket-uri-BrDEYvzy.js";
2
- import { n as matchesWire, t as validateWire } from "./validate-DhH1lO8I.js";
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";
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-Cs17VqjU.js";
5
- import { t as defineBaerlySubcommand } from "./subcommand-BWs6K7zb.js";
4
+ import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-DOTl21vq.js";
6
5
  import { writeFile } from "node:fs/promises";
7
6
  //#region src/export/ddl.ts
8
7
  /**
@@ -420,4 +419,4 @@ const describeNonObject = (v) => {
420
419
  //#endregion
421
420
  export { exportCmd };
422
421
 
423
- //# sourceMappingURL=export-Dz2PZKSR.js.map
422
+ //# sourceMappingURL=export-Bhbz90-z.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"export-Dz2PZKSR.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,QA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rC,IAAI,OAAO,KAAK,UAAU,YAAY,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-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,S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