@gusto/baerly-storage 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +47 -124
  2. package/dist/API.md +161 -511
  3. package/dist/CHANGELOG.md +1148 -307
  4. package/dist/RECIPES.md +398 -80
  5. package/dist/THIRD-PARTY-LICENSES.txt +5 -26
  6. package/dist/{app-config-DyiFK3_k.d.ts → app-config-C6qW7m8S.d.ts} +119 -111
  7. package/dist/app-config.d.ts +31 -1
  8. package/dist/app-config.js +1 -2
  9. package/dist/app-config.js.map +1 -1
  10. package/dist/auth.d.ts +33 -28
  11. package/dist/auth.js +549 -985
  12. package/dist/auth.js.map +1 -1
  13. package/dist/baerly.js +130 -138
  14. package/dist/baerly.js.map +1 -1
  15. package/dist/baerly.spec.json +97 -22
  16. package/dist/capacity-warning-header-BlVopyiI.js +16 -0
  17. package/dist/capacity-warning-header-BlVopyiI.js.map +1 -0
  18. package/dist/{client-Fe8CwB73.d.ts → client-CHQTXpef.d.ts} +121 -36
  19. package/dist/client-react.d.ts +67 -20
  20. package/dist/client-react.js +240 -54
  21. package/dist/client-react.js.map +1 -1
  22. package/dist/client.d.ts +5 -4
  23. package/dist/client.js +51 -16
  24. package/dist/client.js.map +1 -1
  25. package/dist/{cloudflare-DzKBrUlg.js → cloudflare-CKHYXccw.js} +504 -124
  26. package/dist/cloudflare-CKHYXccw.js.map +1 -0
  27. package/dist/cloudflare.d.ts +106 -71
  28. package/dist/cloudflare.js +334 -271
  29. package/dist/cloudflare.js.map +1 -1
  30. package/dist/code-resolution-CL_7L0wS.js +22 -0
  31. package/dist/code-resolution-CL_7L0wS.js.map +1 -0
  32. package/dist/collection-api-DbyhLAY8.d.ts +1001 -0
  33. package/dist/config-DEzInG6M.js +4035 -0
  34. package/dist/config-DEzInG6M.js.map +1 -0
  35. package/dist/constants-D3GSH3tc.js +469 -0
  36. package/dist/constants-D3GSH3tc.js.map +1 -0
  37. package/dist/{context-DRZ3tZ5l.js → context-rlpSnHFA.js} +17 -17
  38. package/dist/context-rlpSnHFA.js.map +1 -0
  39. package/dist/cost-B52llVDx.js +330 -0
  40. package/dist/cost-B52llVDx.js.map +1 -0
  41. package/dist/{current-json-C6nhPOm1.js → current-json-CC6lE4Aj.js} +115 -32
  42. package/dist/current-json-CC6lE4Aj.js.map +1 -0
  43. package/dist/db-plFUNTSF.d.ts +130 -0
  44. package/dist/db-read-seams-BSs0m1z1.js +3261 -0
  45. package/dist/db-read-seams-BSs0m1z1.js.map +1 -0
  46. package/dist/{deploy-DonTr-CV.js → deploy-Obj4nE-Z.js} +12 -16
  47. package/dist/deploy-Obj4nE-Z.js.map +1 -0
  48. package/dist/{dev-banner-CWHIk8tH.d.ts → dev-banner-B5AUHmu1.d.ts} +1 -4
  49. package/dist/dev-landing-BI5UdmOb.d.ts +32 -0
  50. package/dist/dev-landing-CD-si4dW.js +50 -0
  51. package/dist/dev-landing-CD-si4dW.js.map +1 -0
  52. package/dist/dev-vite.d.ts +38 -39
  53. package/dist/dev-vite.js +67 -36
  54. package/dist/dev-vite.js.map +1 -1
  55. package/dist/dev.d.ts +3 -2
  56. package/dist/dev.js +2 -1
  57. package/dist/doctor-BA0i-YAN.js +270 -0
  58. package/dist/doctor-BA0i-YAN.js.map +1 -0
  59. package/dist/dump-D1vX8ozg.js +133 -0
  60. package/dist/dump-D1vX8ozg.js.map +1 -0
  61. package/dist/errors-7Rk1HGCE.js +160 -0
  62. package/dist/errors-7Rk1HGCE.js.map +1 -0
  63. package/dist/{validate-DtljsCh1.js → export-BVL2EvYE.js} +409 -19
  64. package/dist/export-BVL2EvYE.js.map +1 -0
  65. package/dist/fsck-BWkPgov4.js +145 -0
  66. package/dist/fsck-BWkPgov4.js.map +1 -0
  67. package/dist/gcs-admin-Dso1HWQj.d.ts +127 -0
  68. package/dist/gcs.d.ts +30 -0
  69. package/dist/gcs.js +1 -0
  70. package/dist/goog4-signer-CeLIABoE.js +331 -0
  71. package/dist/goog4-signer-CeLIABoE.js.map +1 -0
  72. package/dist/{http-DGd5tbNs.js → http-Z5rZyYMX.js} +898 -271
  73. package/dist/http-Z5rZyYMX.js.map +1 -0
  74. package/dist/http-transport-DNUM8kU-.js +1299 -0
  75. package/dist/http-transport-DNUM8kU-.js.map +1 -0
  76. package/dist/http.d.ts +366 -294
  77. package/dist/http.js +2 -2
  78. package/dist/index-JJrIu1pO.d.ts +135 -0
  79. package/dist/index-LEgHN0qJ.d.ts +50 -0
  80. package/dist/{index-CuA9Mi3K.d.ts → index-RiEYj8t0.d.ts} +291 -78
  81. package/dist/index.d.ts +27 -6
  82. package/dist/index.js +3 -5
  83. package/dist/inspect-BTsVYZKd.js +196 -0
  84. package/dist/inspect-BTsVYZKd.js.map +1 -0
  85. package/dist/{key-Di6yyxFu.js → key-C4FPZ9Io.js} +3 -4
  86. package/dist/{key-Di6yyxFu.js.map → key-C4FPZ9Io.js.map} +1 -1
  87. package/dist/ledger-Dj_bGgo0.js +192 -0
  88. package/dist/ledger-Dj_bGgo0.js.map +1 -0
  89. package/dist/legacy-names-DgZBtgOh.js +47 -0
  90. package/dist/legacy-names-DgZBtgOh.js.map +1 -0
  91. package/dist/log-C9W15Dfo.d.ts +94 -0
  92. package/dist/log-tail-DWJbneBF.js +142 -0
  93. package/dist/log-tail-DWJbneBF.js.map +1 -0
  94. package/dist/log-walk-C-vA-WGJ.js +111 -0
  95. package/dist/log-walk-C-vA-WGJ.js.map +1 -0
  96. package/dist/maintenance-Dd-Yakqj.js +1709 -0
  97. package/dist/maintenance-Dd-Yakqj.js.map +1 -0
  98. package/dist/maintenance-DevB6z4e.js +2237 -0
  99. package/dist/maintenance-DevB6z4e.js.map +1 -0
  100. package/dist/maintenance.d.ts +100 -3
  101. package/dist/maintenance.js +1 -3
  102. package/dist/node.d.ts +130 -142
  103. package/dist/node.js +4 -3
  104. package/dist/{observability-BmflLCdF.js → observability-C-ISCCLE.js} +1275 -332
  105. package/dist/observability-C-ISCCLE.js.map +1 -0
  106. package/dist/observability.d.ts +27 -3
  107. package/dist/observability.js +3 -3
  108. package/dist/path-segment-DBXG26PW.js +363 -0
  109. package/dist/path-segment-DBXG26PW.js.map +1 -0
  110. package/dist/{plan-a7PJHBCy.js → plan-BvQbaNMe.js} +19 -11
  111. package/dist/plan-BvQbaNMe.js.map +1 -0
  112. package/dist/request-CRWiTrza.js +272 -0
  113. package/dist/request-CRWiTrza.js.map +1 -0
  114. package/dist/restore-U6Im8V1V.js +1467 -0
  115. package/dist/restore-U6Im8V1V.js.map +1 -0
  116. package/dist/retry-OBtLB2GC.js +126 -0
  117. package/dist/retry-OBtLB2GC.js.map +1 -0
  118. package/dist/rolldown-runtime-D3KUYPsf.js +12 -0
  119. package/dist/{runtime-spec-Dsw2-n8S.js → runtime-spec-B5mg3pHF.js} +189 -28
  120. package/dist/runtime-spec-B5mg3pHF.js.map +1 -0
  121. package/dist/{s3-http-B-z8th6O.d.ts → s3-http-DBC_wiCL.d.ts} +18 -10
  122. package/dist/s3.d.ts +20 -7
  123. package/dist/s3.js +4 -5
  124. package/dist/s3.js.map +1 -1
  125. package/dist/sha256-4FfGQNPw.js +22 -0
  126. package/dist/sha256-4FfGQNPw.js.map +1 -0
  127. package/dist/{shared-secret-DgEicd3x.js → shared-secret-Vkur-8r0.js} +27 -15
  128. package/dist/shared-secret-Vkur-8r0.js.map +1 -0
  129. package/dist/sigv4-sign-5IUflUD_.js +507 -0
  130. package/dist/sigv4-sign-5IUflUD_.js.map +1 -0
  131. package/dist/snapshot-CknzkDM0.js +148 -0
  132. package/dist/snapshot-CknzkDM0.js.map +1 -0
  133. package/dist/{src-BL_JoPTn.js → src-Actga-bO.js} +1004 -378
  134. package/dist/src-Actga-bO.js.map +1 -0
  135. package/dist/src-D0MQfvOp.js +812 -0
  136. package/dist/src-D0MQfvOp.js.map +1 -0
  137. package/dist/src-Dr9uo3dc.js +501 -0
  138. package/dist/src-Dr9uo3dc.js.map +1 -0
  139. package/dist/{subcommand-DoDA-K7d.js → subcommand-BLoF66dG.js} +89 -16
  140. package/dist/subcommand-BLoF66dG.js.map +1 -0
  141. package/dist/{time-DUqvFMHq.js → time-DRxTP9iv.js} +15 -34
  142. package/dist/time-DRxTP9iv.js.map +1 -0
  143. package/dist/types-suVbsEWS.d.ts +116 -0
  144. package/dist/{usage-DBV1eQHC.js → usage-CPzVhrQr.js} +40 -45
  145. package/dist/usage-CPzVhrQr.js.map +1 -0
  146. package/dist/uuid-BuT_c404.js +333 -0
  147. package/dist/uuid-BuT_c404.js.map +1 -0
  148. package/dist/verifier-Bmlmndzo.d.ts +95 -0
  149. package/dist/{wire-izfGZDvr.js → wire-DndvKU-K.js} +2 -3
  150. package/dist/wire-DndvKU-K.js.map +1 -0
  151. package/package.json +96 -69
  152. package/dist/aws4fetch.esm-p7eEzLCs.js +0 -1702
  153. package/dist/aws4fetch.esm-p7eEzLCs.js.map +0 -1
  154. package/dist/bytes-BXdamO3L.js +0 -11
  155. package/dist/bytes-BXdamO3L.js.map +0 -1
  156. package/dist/cloudflare-DzKBrUlg.js.map +0 -1
  157. package/dist/config-1tv0-Yzm.js +0 -2693
  158. package/dist/config-1tv0-Yzm.js.map +0 -1
  159. package/dist/constants-CfeMWQWk.js +0 -222
  160. package/dist/constants-CfeMWQWk.js.map +0 -1
  161. package/dist/context-DRZ3tZ5l.js.map +0 -1
  162. package/dist/cost-DSMIVqzL.js +0 -203
  163. package/dist/cost-DSMIVqzL.js.map +0 -1
  164. package/dist/current-json-C6nhPOm1.js.map +0 -1
  165. package/dist/db-DsPkOVEH.d.ts +0 -254
  166. package/dist/deploy-DonTr-CV.js.map +0 -1
  167. package/dist/doctor-DSIyCDg_.js +0 -346
  168. package/dist/doctor-DSIyCDg_.js.map +0 -1
  169. package/dist/dump-Bh5k26VQ.js +0 -94
  170. package/dist/dump-Bh5k26VQ.js.map +0 -1
  171. package/dist/errors-Dfa3p78c.js +0 -78
  172. package/dist/errors-Dfa3p78c.js.map +0 -1
  173. package/dist/export-DtF5tDIM.js +0 -401
  174. package/dist/export-DtF5tDIM.js.map +0 -1
  175. package/dist/fsck-D_djMO5D.js +0 -279
  176. package/dist/fsck-D_djMO5D.js.map +0 -1
  177. package/dist/http-DGd5tbNs.js.map +0 -1
  178. package/dist/index-0rZcMBwy.d.ts +0 -115
  179. package/dist/index-BNRh23K9.d.ts +0 -162
  180. package/dist/index-BYk9oCNf.d.ts +0 -1112
  181. package/dist/indexes-Dn9hbGQG.d.ts +0 -22
  182. package/dist/inspect-6WZ-pC7-.js +0 -133
  183. package/dist/inspect-6WZ-pC7-.js.map +0 -1
  184. package/dist/log-tail-D98U1JBo.js +0 -522
  185. package/dist/log-tail-D98U1JBo.js.map +0 -1
  186. package/dist/maintenance-B4Dki6Ig.js +0 -2157
  187. package/dist/maintenance-B4Dki6Ig.js.map +0 -1
  188. package/dist/maintenance-B_e0T99L.d.ts +0 -537
  189. package/dist/maintenance-C7coQp4c.js +0 -1418
  190. package/dist/maintenance-C7coQp4c.js.map +0 -1
  191. package/dist/normalize-rjnZLwS4.js +0 -133
  192. package/dist/normalize-rjnZLwS4.js.map +0 -1
  193. package/dist/observability-BmflLCdF.js.map +0 -1
  194. package/dist/plan-a7PJHBCy.js.map +0 -1
  195. package/dist/query-rAtXNQQB.js +0 -1773
  196. package/dist/query-rAtXNQQB.js.map +0 -1
  197. package/dist/rebuild-index-BVzQSZlm.js +0 -81
  198. package/dist/rebuild-index-BVzQSZlm.js.map +0 -1
  199. package/dist/request-u0M51mhJ.js +0 -72
  200. package/dist/request-u0M51mhJ.js.map +0 -1
  201. package/dist/restore-R-4rbciV.js +0 -778
  202. package/dist/restore-R-4rbciV.js.map +0 -1
  203. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  204. package/dist/runtime-spec-Dsw2-n8S.js.map +0 -1
  205. package/dist/shared-secret-DgEicd3x.js.map +0 -1
  206. package/dist/src-BL_JoPTn.js.map +0 -1
  207. package/dist/src-CYHFDrKz.js +0 -536
  208. package/dist/src-CYHFDrKz.js.map +0 -1
  209. package/dist/src-DYZ4H1aF.js +0 -392
  210. package/dist/src-DYZ4H1aF.js.map +0 -1
  211. package/dist/subcommand-DoDA-K7d.js.map +0 -1
  212. package/dist/time-DUqvFMHq.js.map +0 -1
  213. package/dist/usage-DBV1eQHC.js.map +0 -1
  214. package/dist/validate-DtljsCh1.js.map +0 -1
  215. package/dist/wire-izfGZDvr.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-7Rk1HGCE.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, a write whose document would encode to more than `MAX_DOCUMENT_BYTES` = 1 MiB). HTTP maps this code to 400. */\n | \"InvalidConfig\"\n /** Generic S3/HTTP transport failure (5xx, unexpected status, retries exhausted). */\n | \"NetworkError\"\n /** S3 returned 403. Either credentials are wrong or the bucket policy denies the operation. */\n | \"AccessDenied\"\n /** Server returned data that didn't parse (malformed XML, non-JSON body where JSON expected). */\n | \"InvalidResponse\"\n /** Internal invariant violation — should not be reachable. File a bug. */\n | \"Internal\"\n /**\n * Document body failed schema validation. Emitted by the table-API\n * write verbs (`Collection.insert`, `Query.update`, `Collection.replace`) when\n * the body is not valid JSON or contains an array where\n * `DocumentValue` is required; also emitted when a collection has a\n * declared `SchemaValidator` (via `Db.create({ collections })`) and\n * the bound schema rejects the doc. In the schema-rejection case the\n * error carries an `issues` array describing each failure. HTTP layer\n * maps this to 400.\n */\n | \"SchemaError\"\n /**\n * Another write won a race this call needed to win, and the losing commit\n * did not land. Re-read, then retry; `retriable` is `true`. Each\n * `Collection` / `Query` verb re-reads on every call, so re-issuing the same\n * call is the retry. The writer makes one commit attempt and resolves a\n * log-create race inside it, so this surfaces from a write only for a\n * rejected precondition the writer does not resolve. Maintenance passes\n * (`compact`, `runGc`, log retirement) raise it when a concurrent pass or\n * writer moved `current.json` first; the next pass retries. HTTP maps this\n * code to 409 with a generic message.\n *\n * `Storage` implementations throw this code for every rejected\n * precondition: a stale `ifMatch`, an `ifMatch` against a missing key, or\n * an `ifNoneMatch: \"*\"` create over an existing key. For a create-only put\n * that followed an attempt of unknown outcome, the occupant may be this\n * call's own earlier write. Callers that care read the key back.\n */\n | \"WriteConflict\"\n /**\n * The thing being created already exists, so the same request can never\n * succeed; `retriable` is `false`. `Collection.insert` raises it when a\n * live row already holds the `_id`, including one a concurrent insert\n * committed first: of concurrent inserts of one `_id`, at most one\n * commits and the others raise this. Insert under a different `_id`,\n * omit `_id` to mint one, or change the stored row with `update` /\n * `replace` — unless this follows a same-`_id` retry after\n * `AmbiguousCommit`, where the stored row may be the first attempt:\n * re-read it instead of inserting under a new `_id`.\n * `baerly admin restore` raises it when the target collection already\n * exists and `--force` was not passed. HTTP maps this code to 409 and\n * keeps the message, which names the id and collection.\n */\n | \"AlreadyExists\"\n /**\n * A write's commit outcome cannot be resolved: one or more committing\n * `log/<seq>` creates may already be durable, but the writer cannot adopt or\n * report a confirmed commit. This includes an unresolved create acknowledgement\n * after the occupant readback, and a create that landed below the\n * certified delete floor (`seq < min(log_delete_floor, log_seq_start)`).\n *\n * `BaerlyError._id` names the affected row, including an auto-ID insert's\n * minted id. Re-read that row and compare it with the intended state before\n * deciding what to do. A matching row helps reconcile the outcome; absence\n * does not prove that a create failed, since a send may still complete or its\n * effect may have been superseded. Retrying is an explicit at-least-once\n * choice and may repeat logical work. Retry an insert with the same `_id`:\n * a second create then targets the same row instead of minting a second\n * document, and commits only if no live row holds that `_id`. An\n * `AlreadyExists` on that retry means a row with that `_id` is committed:\n * re-read it and compare with the intended state rather than inserting\n * under a new `_id`. `retriable` is `false` so generic retry wrappers do\n * not repeat the operation silently. HTTP maps this code to 409.\n */\n | \"AmbiguousCommit\"\n /**\n * The work this request needs is more than the host serving it does in\n * one request, so the request was refused whole; `retriable` is `false`.\n * The refusal is decided per request from the collection's current\n * state and clears by itself once that state changes. Reads and writes\n * both raise it.\n *\n * A refused write commits nothing; a batch refused part-way (a\n * concurrent write filled the room between its check and a row's\n * commit) keeps the rows it already committed. Near the limit only\n * growth is refused (an insert, or an update that makes a row larger):\n * deletes and same-size or shrinking updates still commit, and once\n * maintenance absorbs them, growth is accepted again. When the\n * collection is already more than this host can maintain (for example\n * one grown on a larger host and now served by a smaller one), every\n * write is refused until the collection moves to a larger host or is\n * exported with `baerly admin dump`. Moving hosts is a deployment\n * decision, not an app setting.\n *\n * A refused read returns no rows, never a truncated answer, and writes\n * nothing. Its `resolution` names the remedy for the bound it hit:\n * narrow the predicate or add a limit when the answer is too wide;\n * delete or shrink rows when the collection is too large to read in one\n * request; or retry once maintenance has absorbed pending writes. HTTP\n * maps this code to 409 and keeps the message, which names the\n * collection and the case.\n */\n | \"CapacityExceeded\"\n /**\n * Background maintenance is behind on this collection, so this write was\n * refused and not committed (a batch refused part-way keeps the rows it\n * already committed); `retriable` is `true`. The refusal\n * clears by itself once maintenance catches up. {@link BaerlyError.retryAfter}\n * carries the suggested delay in seconds; wait that long, then repeat the\n * call. HTTP maps this code to 503 with a `Retry-After` header and keeps\n * the message.\n */\n | \"MaintenancePending\"\n /**\n * A `/v1/since` cursor can no longer resume, so the long-poll was\n * refused; `retriable` is `false`, because the same cursor never\n * succeeds again. Either the changes after it are no longer retained\n * (maintenance retired them), or it was minted in a generation that\n * `baerly admin restore --force` has since truncated. Re-read the rows\n * the subscriber shows, then resume with `cursor: \"\"`: the changes\n * between the dead cursor and the restart are not replayed. A\n * malformed cursor is `SchemaError` instead. HTTP maps this code to 410\n * and keeps the message.\n */\n | \"CursorExpired\"\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 router counts bytes\n * while it reads a chunked body and stops at the cap on every\n * host; the Node adapter also enforces it during the `node:http`\n * stream pump and drains the rest of the upload.\n */\n | \"PayloadTooLarge\"\n /**\n * A body-bearing HTTP route (`POST`, `PATCH`, `PUT`) got a request\n * whose `Content-Type` is missing or is not `application/json` or a\n * `+json` type. HTTP server maps to 415 and refuses before reading\n * the body. Parameters such as `charset` are allowed. The JSON-only\n * rule is the CSRF defense for ambient auth: a `text/plain` or\n * form-encoded POST is a CORS-simple request another origin can send.\n */\n | \"UnsupportedMediaType\"\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 * Runtime enumeration of every {@link BaerlyErrorCode}. The spec\n * generator and the drift gate iterate this to assert the IR lists\n * each code; the type guard in `spec/ir-schema.test.ts` fails tsc if\n * this tuple and the union diverge. Keep order stable for deterministic\n * artifact diffs. This is the canonical code list — do not re-list\n * codes elsewhere (see RETRIABLE_CODES, the sibling retriable subset).\n */\nexport const ERROR_CODES = [\n \"InvalidConfig\",\n \"NetworkError\",\n \"AccessDenied\",\n \"InvalidResponse\",\n \"Internal\",\n \"SchemaError\",\n \"WriteConflict\",\n \"AlreadyExists\",\n \"AmbiguousCommit\",\n \"CapacityExceeded\",\n \"MaintenancePending\",\n \"Unauthorized\",\n \"NotFound\",\n \"PayloadTooLarge\",\n \"UnsupportedMediaType\",\n \"UnsatisfiablePredicate\",\n \"CursorExpired\",\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n] as const satisfies readonly BaerlyErrorCode[];\n\n// Exhaustiveness guard: every union member must appear in ERROR_CODES.\n// If a code is added to BaerlyErrorCode without a tuple entry, this\n// errors at tsc time (the union is not assignable to the tuple's union).\ntype _ErrorCodesExhaustive = [BaerlyErrorCode] extends [(typeof ERROR_CODES)[number]]\n ? true\n : [\"missing code in ERROR_CODES\", Exclude<BaerlyErrorCode, (typeof ERROR_CODES)[number]>];\n// eslint-disable-next-line no-underscore-dangle\nconst _errorCodesExhaustive: _ErrorCodesExhaustive = true;\nvoid _errorCodesExhaustive;\n\n/**\n * Codes whose failure can clear on retry. `BaerlyError.retriable` is\n * exactly membership in this set; there are no per-instance overrides.\n */\nexport const RETRIABLE_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"NetworkError\",\n \"WriteConflict\",\n \"MaintenancePending\",\n]);\n\n/**\n * True iff `value` is a code this build knows. Wire decoders use it to\n * catch a code minted by a newer server before it reaches `code`, where\n * an unknown string would defeat both exhaustive switches and\n * {@link isRetriableCode}.\n */\nexport const isBaerlyErrorCode = (value: unknown): value is BaerlyErrorCode =>\n typeof value === \"string\" && (ERROR_CODES as readonly string[]).includes(value);\n\n/**\n * True iff `err` is a `WriteConflict`: a lost conditional write or CAS\n * race. The one predicate every kernel catch site uses, so the code's\n * meaning is tested in one place. Matches on `name` and `code` rather\n * than `instanceof`, so an error from a second loaded copy of this module\n * or another realm still classifies.\n */\nexport const isWriteConflict = (\n err: unknown,\n): err is BaerlyError & { readonly code: \"WriteConflict\" } =>\n typeof err === \"object\" &&\n err !== null &&\n (err as { readonly name?: unknown }).name === \"BaerlyError\" &&\n (err as { readonly code?: unknown }).code === \"WriteConflict\";\n\n/** True iff this error code is retriable (membership in {@link RETRIABLE_CODES}). */\nexport const isRetriableCode = (code: BaerlyErrorCode): boolean => RETRIABLE_CODES.has(code);\n\n/**\n * Codes raised only inside the client-side React runtime\n * (`useQuery` / `useMutation`); they never travel the HTTP wire, so the\n * machine-contract IR reports `httpStatus: null` for them — distinct\n * from a real `500` (a server-side transport/internal failure the HTTP\n * layer maps to a status). Sibling of {@link RETRIABLE_CODES}; add a\n * code here when a new client-only failure mode joins the union.\n */\nexport const CLIENT_RUNTIME_CODES: ReadonlySet<BaerlyErrorCode> = new Set<BaerlyErrorCode>([\n \"UseQueryAwaitedRecorder\",\n \"UnexpectedWriteInQuery\",\n \"MutationFailed\",\n]);\n\n/**\n * Optional fields for {@link BaerlyError}, the third constructor argument.\n * Each field lands on the same-named property of the error; an omitted\n * field leaves that property `undefined`.\n */\nexport interface BaerlyErrorOptions {\n /**\n * The underlying throwable, or a structured detail object. Kept on\n * `error.cause`. A `Storage` adapter reports `cause.notApplied` /\n * `cause.throttled` this way; see the `Storage.put` contract.\n */\n readonly cause?: unknown;\n /** Field-path issues; set only with `code: \"SchemaError\"`. Lands on {@link BaerlyError.issues}. */\n readonly issues?: ReadonlyArray<{\n readonly path: ReadonlyArray<string | number>;\n readonly message: string;\n }>;\n /** Raw HTTP status; set only by the client-side wire decoder. Lands on {@link BaerlyError.status}. */\n readonly status?: number;\n /** Canonical corrective action. Lands on {@link BaerlyError.resolution}. */\n readonly resolution?: string;\n /** The affected row's `_id`; set only with `code: \"AmbiguousCommit\"`. Lands on {@link BaerlyError._id}. */\n readonly _id?: string;\n /** Suggested delay in seconds before retrying; set only with `code: \"MaintenancePending\"`. Lands on {@link BaerlyError.retryAfter}. */\n readonly retryAfter?: number;\n /**\n * Never set. This object is not an `Error`: `Error` requires `message`, so\n * this field makes `new BaerlyError(code, msg, err)` fail to compile. To\n * chain an error, pass `{ cause: err }`.\n */\n readonly message?: never;\n}\n\n/**\n * The single error class thrown by baerly-storage. 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({ _id: \"t-1\", title: \"hi\" });\n * } catch (err) {\n * if (!(err instanceof BaerlyError)) throw err;\n * if (err.code === \"AlreadyExists\") {\n * // t-1 is taken; retrying cannot succeed.\n * } else if (err.code === \"AmbiguousCommit\") {\n * // May have landed: re-read err._id before deciding.\n * } else if (err.retriable) {\n * // WriteConflict or NetworkError: retry with bounded backoff.\n * } else {\n * throw err;\n * }\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 * The `_id` of the row whose commit outcome is unknown, set only when\n * `code === \"AmbiguousCommit\"`. For an auto-ID insert it is the minted\n * id, so the caller can re-read the row and retry with the same `_id`\n * rather than mint a second document. A missing row does not prove the\n * write failed. The HTTP layer carries it in `HttpErrorEnvelope`.\n */\n readonly _id?: string;\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 /** Canonical corrective action; crosses the wire via `HttpErrorEnvelope.error.resolution`. */\n readonly resolution?: string;\n /** Suggested delay in seconds before retrying; set only for `MaintenancePending`. Crosses the wire via `HttpErrorEnvelope.error.retryAfter` and the `Retry-After` header. */\n readonly retryAfter?: number;\n\n /**\n * `true` iff re-running the operation from its read step can succeed:\n * `NetworkError` (retry with backoff) and `WriteConflict` (re-read, then\n * write again). A `Collection` / `Query` verb re-reads on every call, so\n * calling it again is the retry; a blind resend of the same conditional\n * `Storage` put loses again. A pure function of `code`\n * ({@link isRetriableCode}): every instance of a code gives the same\n * answer. `AmbiguousCommit` is `false` because the write may have landed;\n * reconcile by `_id` first.\n */\n get retriable(): boolean {\n return isRetriableCode(this.code);\n }\n\n /**\n * `code` and `message` are positional; everything else goes in `options`,\n * as with `new Error(message, { cause })`. Passing an `Error` (or any\n * non-options value) as the third argument does not compile; the\n * options object is where `cause` goes.\n *\n * @example\n * ```ts\n * throw new BaerlyError(\"NetworkError\", \"PUT failed\", { cause: err });\n * throw new BaerlyError(\"AmbiguousCommit\", \"commit outcome unknown\", { _id: \"t-1\" });\n * ```\n */\n constructor(code: BaerlyErrorCode, message: string, options?: BaerlyErrorOptions) {\n super(message);\n this.name = \"BaerlyError\";\n this.code = code;\n this.cause = options?.cause;\n const { issues, status, resolution, _id, retryAfter } = options ?? {};\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: same rationale as `issues` above\n if (status !== undefined) {\n this.status = status;\n }\n // Stryker disable next-line ConditionalExpression: same rationale as `issues` above\n if (resolution !== undefined) {\n this.resolution = resolution;\n }\n // Stryker disable next-line ConditionalExpression: same rationale as `issues` above\n if (_id !== undefined) {\n this._id = _id;\n }\n // Stryker disable next-line ConditionalExpression: same rationale as `issues` above\n if (retryAfter !== undefined) {\n this.retryAfter = retryAfter;\n }\n }\n}\n"],"mappings":";;;;;;;;;AAgOA,MAAa,cAAc;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;AAgBA,MAAa,kCAAgD,IAAI,IAAqB;CACpF;CACA;CACA;AACF,CAAC;;;;;;;AAQD,MAAa,qBAAqB,UAChC,OAAO,UAAU,YAAa,YAAkC,SAAS,KAAK;;;;;;;;AAShF,MAAa,mBACX,QAEA,OAAO,QAAQ,YACf,QAAQ,QACP,IAAoC,SAAS,iBAC7C,IAAoC,SAAS;;AAGhD,MAAa,mBAAmB,SAAmC,gBAAgB,IAAI,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2E3F,IAAa,cAAb,cAAiC,MAAM;CAC5B;CACS;;;;;;;;;;;CAWT;;;;;;;;CAWA;;;;;;;;;;CAUA;;CAEA;;CAEA;;;;;;;;;;;CAYT,IAAI,YAAqB;EACvB,OAAO,gBAAgB,KAAK,IAAI;CAClC;;;;;;;;;;;;;CAcA,YAAY,MAAuB,SAAiB,SAA8B;EAChF,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ,SAAS;EACtB,MAAM,EAAE,QAAQ,QAAQ,YAAY,KAAK,eAAe,WAAW,CAAC;EAEpE,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,WAAW,KAAA,GACb,KAAK,SAAS;EAGhB,IAAI,eAAe,KAAA,GACjB,KAAK,aAAa;EAGpB,IAAI,QAAQ,KAAA,GACV,KAAK,MAAM;EAGb,IAAI,eAAe,KAAA,GACjB,KAAK,aAAa;CAEtB;AACF"}
@@ -1,5 +1,9 @@
1
- import { o as BaerlyError } from "./baerly.js";
2
- //#region ../protocol/src/query/matches.ts
1
+ import { r as emitSuccess, s as BaerlyError } from "./baerly.js";
2
+ import { n as loadMaterialisedView, r as quoteValue, t as inferPlanForCollection } from "./plan-BvQbaNMe.js";
3
+ import { n as parseBucketUri } from "./config-DEzInG6M.js";
4
+ import { a as TENANT_ARG, c as defineBaerlySubcommand, i as JSON_ARG, n as BUCKET_ARG, o as assertCollectionArg, r as COLLECTION_ARG, t as APP_ARG } from "./subcommand-BLoF66dG.js";
5
+ import { writeFile } from "node:fs/promises";
6
+ // ../protocol/src/query/matches.ts
3
7
  /**
4
8
  * Evaluate a validated wire-form predicate against a `JSONObject`
5
9
  * document. Returns `true` iff every clause holds.
@@ -28,12 +32,15 @@ import { o as BaerlyError } from "./baerly.js";
28
32
  * ```
29
33
  */
30
34
  const matchesWire = (wire, doc) => {
31
- for (const clause of wire.clauses) if (!matchesClause(clause, lookupPath(doc, clause.field))) return false;
35
+ for (const clause of wire.clauses) {
36
+ const actual = lookupPath(doc, clause.field);
37
+ if (!matchesClause(clause, actual)) return false;
38
+ }
32
39
  return true;
33
40
  };
34
- const lookupPath = (doc, field) => {
35
- if (!field.includes(".")) return doc[field];
36
- const segments = field.split(".");
41
+ const lookupPath = (doc, field) => field.includes(".") ? walkPath(doc, field.split(".")) : doc[field];
42
+ /** Follow a split dotted path from `doc`; `undefined` when it cannot be consumed. */
43
+ const walkPath = (doc, segments) => {
37
44
  let cursor = doc;
38
45
  for (const segment of segments) {
39
46
  if (cursor === void 0 || cursor === null || typeof cursor !== "object" || Array.isArray(cursor)) return;
@@ -80,8 +87,7 @@ const compareLT = (actual, bound, inclusive) => {
80
87
  if (typeof bound === "number") return typeof actual === "number" && (inclusive ? actual <= bound : actual < bound);
81
88
  return false;
82
89
  };
83
- //#endregion
84
- //#region ../protocol/src/query/_internals.ts
90
+ // ../protocol/src/query/_internals.ts
85
91
  /** @internal Same primitive type for comparison purposes. */
86
92
  const sameComparableType = (a, b) => typeof a === "string" && typeof b === "string" || typeof a === "number" && typeof b === "number";
87
93
  /**
@@ -99,10 +105,9 @@ const compareScalar = (a, b) => {
99
105
  /** @internal Render a predicate path for use in error messages. */
100
106
  const formatPath = (path) => path.length === 0 ? "<root>" : path.map((p) => JSON.stringify(p)).join(".");
101
107
  /**
102
- * Recursive structural equality for `DocumentValue` values. Lifted to
103
- * `export` so the filtered-index implication checker (in
104
- * `@baerly/server`'s query planner) and other callers can reuse the
105
- * same comparison rule the validator + merger already trust. Two
108
+ * Recursive structural equality for `DocumentValue` values. Exported so
109
+ * `./satisfiable.ts` and other callers reuse the same comparison rule
110
+ * the validator + merger already trust. Two
106
111
  * values `a` and `b` are equal iff:
107
112
  *
108
113
  * - they are reference-equal (covers primitives and object identity);
@@ -130,8 +135,7 @@ const deepEqualDocumentValue = (a, b) => {
130
135
  }
131
136
  return true;
132
137
  };
133
- //#endregion
134
- //#region ../protocol/src/query/satisfiable.ts
138
+ // ../protocol/src/query/satisfiable.ts
135
139
  /**
136
140
  * Per-field satisfiability check for a {@link PredicateWire}. Groups
137
141
  * clauses by field, then runs the same logic the pre-redesign
@@ -275,8 +279,7 @@ const assertWireSatisfiable = (wire) => {
275
279
  }
276
280
  }
277
281
  };
278
- //#endregion
279
- //#region ../protocol/src/query/validate.ts
282
+ // ../protocol/src/query/validate.ts
280
283
  /**
281
284
  * Wire predicate validator. Walks a {@link PredicateWire} and throws
282
285
  * on a structurally bad clause (`BaerlyError{code:"InvalidConfig"}`)
@@ -371,7 +374,394 @@ const validateRangeBound = (value, field, clauseIndex) => {
371
374
  if (t !== "string" && t !== "number") throw new BaerlyError("InvalidConfig", `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) has unsupported type ${JSON.stringify(t)} — must be string or finite number.`);
372
375
  if (t === "number" && !Number.isFinite(value)) throw new BaerlyError("InvalidConfig", `Predicate range bound at clause ${clauseIndex} (field=${JSON.stringify(field)}) is ${String(value)} — finite numbers only (NaN / Infinity do not round-trip through JSON).`);
373
376
  };
374
- //#endregion
375
- export { matchesWire as n, validateWire as t };
377
+ // src/export/ddl.ts
378
+ /**
379
+ * Emit a `CREATE TABLE` statement for the plan, one line per column,
380
+ * terminated with a semicolon + newline so the output is directly
381
+ * pipeable into `psql` / `sqlite3` / `wrangler d1 execute`.
382
+ *
383
+ * `_id` is the primary key (always first in `plan.columns`).
384
+ *
385
+ * D1 today is sqlite-flavoured: same DDL as `target=sqlite` with a
386
+ * single difference — D1 disallows table names starting with
387
+ * `sqlite_`. We refuse them up front.
388
+ */
389
+ const emitCreateTable = (plan) => {
390
+ if (plan.columns.length === 0) throw new BaerlyError("SchemaError", `emitCreateTable: collection ${JSON.stringify(plan.table)} has no observed columns — empty snapshot?`);
391
+ if (plan.target === "d1" && plan.table.toLowerCase().startsWith("sqlite_")) throw new BaerlyError("SchemaError", `emitCreateTable: D1 reserves the sqlite_ table-name prefix (got ${JSON.stringify(plan.table)})`);
392
+ const lines = [];
393
+ lines.push(`CREATE TABLE ${plan.tableIdentifier} (`);
394
+ const colLines = [];
395
+ for (const col of plan.columns) {
396
+ const nullClause = col.nullable ? "" : " NOT NULL";
397
+ const pkClause = col.source === "_id" ? " PRIMARY KEY" : "";
398
+ colLines.push(` ${col.identifier} ${col.sqlType}${nullClause}${pkClause}`);
399
+ }
400
+ lines.push(colLines.join(",\n"));
401
+ lines.push(");");
402
+ return lines.join("\n") + "\n";
403
+ };
404
+ // src/export/rows.ts
405
+ /**
406
+ * Emit one `INSERT INTO …` statement per row. The emitted SQL is
407
+ * directly pipeable into `psql` / `sqlite3` / `wrangler d1
408
+ * execute`. Per-row statements (not one big VALUES tuple) so a
409
+ * mid-stream failure has bounded blast radius.
410
+ *
411
+ * For columns whose plan has `jsonEncoded: true`, the row's value
412
+ * is JSON-stringified first and then string-quoted. Postgres
413
+ * accepts a literal text JSON in a `jsonb` column. SQLite / D1 see
414
+ * the JSON as plain TEXT.
415
+ *
416
+ * Rows are streamed via the async-iterable protocol so the export
417
+ * never materialises the full SQL output in memory. The caller
418
+ * concatenates the yielded chunks (or pipes them straight to disk
419
+ * / stdout).
420
+ */
421
+ async function* emitInsertStatements(plan, rows) {
422
+ const columnList = plan.columns.map((c) => c.identifier).join(", ");
423
+ for (const [id, body] of rows) {
424
+ const values = [];
425
+ for (const col of plan.columns) {
426
+ const raw = col.source === "_id" ? id : body[col.source];
427
+ if (raw === void 0) {
428
+ values.push("NULL");
429
+ continue;
430
+ }
431
+ if (col.jsonEncoded) {
432
+ const json = JSON.stringify(raw);
433
+ values.push(quoteValue(json, plan.target));
434
+ } else values.push(quoteValue(raw, plan.target));
435
+ }
436
+ yield `INSERT INTO ${plan.tableIdentifier} (${columnList}) VALUES (${values.join(", ")});\n`;
437
+ }
438
+ }
439
+ // src/export/where.ts
440
+ /**
441
+ * Wire-predicate → SQL `WHERE` clause translation.
442
+ *
443
+ * Pure function. The translator consumes a validated
444
+ * {@link PredicateWire} — the same shape the read path uses — and
445
+ * an {@link ExportPlan} (from `./plan.ts`), and emits a SQL fragment
446
+ * matched against the plan's columns.
447
+ *
448
+ * Three classes of clause:
449
+ *
450
+ * 1. Flat column, top-level field → direct comparator
451
+ * (`"status" = 'open'`, `"priority" > 5`).
452
+ * 2. JSON-encoded column → JSON-path operators (Postgres `->`/`->>`
453
+ * chains; SQLite/D1 `json_extract(…, '$.…')`).
454
+ * 3. Unmatchable clause (dotted path against a flat column, or a
455
+ * field naming an unknown column) → `1 = 0` plus a hint the CLI
456
+ * surfaces as a `-- TODO(baerly export):` comment above the
457
+ * emitted statement.
458
+ *
459
+ * Dynamic predicates are invisible at runtime — we see the
460
+ * materialised wire, not the source expression. Callers that know
461
+ * they constructed the wire dynamically can pass
462
+ * `options.dynamicHint` to surface an operator-supplied note.
463
+ */
464
+ /**
465
+ * Translate a validated {@link PredicateWire} into a SQL WHERE-clause
466
+ * fragment matched against the plan's columns. The first argument
467
+ * must already have been validated by {@link validateWire} — the
468
+ * function re-validates defensively but the caller's invariant
469
+ * matters for error-message provenance.
470
+ *
471
+ * Pure function. No I/O. Same wire + plan + target → same SQL string.
472
+ *
473
+ * @throws BaerlyError code="InvalidConfig" — wire fails
474
+ * {@link validateWire}; same shape `Query<T>.where` already
475
+ * surfaces.
476
+ */
477
+ const translatePredicateWireToSql = (wire, plan, options) => {
478
+ validateWire(wire);
479
+ const hints = [];
480
+ if (options?.dynamicHint !== void 0 && options.dynamicHint.length > 0) hints.push(`caller-flagged dynamic predicate: ${options.dynamicHint}. Review the emitted SQL for completeness.`);
481
+ const clauses = [];
482
+ for (const clause of wire.clauses) clauses.push(...clauseForWire(clause, plan, hints));
483
+ return {
484
+ sql: clauses.length === 0 ? "" : clauses.join(" AND "),
485
+ hints
486
+ };
487
+ };
488
+ const clauseForWire = (clause, plan, hints) => {
489
+ const segments = clause.field.includes(".") ? clause.field.split(".") : [clause.field];
490
+ const head = segments[0];
491
+ if (head === void 0 || head.length === 0) throw new BaerlyError("InvalidConfig", "translatePredicateWireToSql: empty field path encountered (defensive)");
492
+ const col = plan.columns.find((c) => c.source === head);
493
+ if (col === void 0) {
494
+ hints.push(`predicate field ${JSON.stringify(clause.field)} references a key never observed in the snapshot; this clause cannot match.`);
495
+ return ["1 = 0"];
496
+ }
497
+ if (!col.jsonEncoded && segments.length === 1) return [flatColumnClause(col.identifier, clause, plan.target)];
498
+ if (!col.jsonEncoded && segments.length > 1) {
499
+ hints.push(`predicate path ${JSON.stringify(clause.field)} addresses a flat column; this clause cannot match. Hand-edit if intended.`);
500
+ return ["1 = 0"];
501
+ }
502
+ if (col.jsonEncoded && segments.length === 1) return [jsonColumnRootClause(col, clause, plan.target)];
503
+ return [jsonPathClause(col, segments.slice(1), clause, plan.target)];
504
+ };
505
+ const flatColumnClause = (identifier, clause, target) => {
506
+ switch (clause.op) {
507
+ case "eq": return `${identifier} = ${quoteLeaf(clause.value, target)}`;
508
+ case "gt": return `${identifier} > ${quoteLeaf(clause.value, target)}`;
509
+ case "gte": return `${identifier} >= ${quoteLeaf(clause.value, target)}`;
510
+ case "lt": return `${identifier} < ${quoteLeaf(clause.value, target)}`;
511
+ case "lte": return `${identifier} <= ${quoteLeaf(clause.value, target)}`;
512
+ case "in": return `${identifier} IN (${clause.value.map((v) => quoteLeaf(v, target)).join(", ")})`;
513
+ }
514
+ };
515
+ const jsonColumnRootClause = (col, clause, target) => {
516
+ if (clause.op === "eq") {
517
+ const literal = JSON.stringify(clause.value);
518
+ if (target === "postgres") return `${col.identifier}::text = ${quoteValue(literal, target)}`;
519
+ return `${col.identifier} = ${quoteValue(literal, target)}`;
520
+ }
521
+ if (clause.op === "in") {
522
+ const literals = clause.value.map((v) => quoteValue(JSON.stringify(v), target));
523
+ if (target === "postgres") return `${col.identifier}::text IN (${literals.join(", ")})`;
524
+ return `${col.identifier} IN (${literals.join(", ")})`;
525
+ }
526
+ const comparator = rangeComparator(clause.op);
527
+ const literal = JSON.stringify(clause.value);
528
+ if (target === "postgres") return `${col.identifier}::text ${comparator} ${quoteValue(literal, target)}`;
529
+ return `${col.identifier} ${comparator} ${quoteValue(literal, target)}`;
530
+ };
531
+ const jsonPathClause = (col, tail, clause, target) => {
532
+ const accessor = jsonPathAccessor(col.identifier, tail, target);
533
+ switch (clause.op) {
534
+ case "eq": return `${accessor} = ${quoteLeaf(clause.value, target)}`;
535
+ case "gt": return `${accessor} > ${quoteLeaf(clause.value, target)}`;
536
+ case "gte": return `${accessor} >= ${quoteLeaf(clause.value, target)}`;
537
+ case "lt": return `${accessor} < ${quoteLeaf(clause.value, target)}`;
538
+ case "lte": return `${accessor} <= ${quoteLeaf(clause.value, target)}`;
539
+ case "in": return `${accessor} IN (${clause.value.map((v) => quoteLeaf(v, target)).join(", ")})`;
540
+ }
541
+ };
542
+ const rangeComparator = (op) => {
543
+ if (op === "gt") return ">";
544
+ if (op === "gte") return ">=";
545
+ if (op === "lt") return "<";
546
+ return "<=";
547
+ };
548
+ const jsonPathAccessor = (identifier, tail, target) => {
549
+ if (target === "postgres") {
550
+ let expr = identifier;
551
+ for (let i = 0; i < tail.length; i++) {
552
+ const seg = tail[i];
553
+ const isLast = i === tail.length - 1;
554
+ const key = `'${seg.replace(/'/g, "''")}'`;
555
+ expr = `${expr}${isLast ? "->>" : "->"}${key}`;
556
+ }
557
+ return expr;
558
+ }
559
+ return `json_extract(${identifier}, ${`'$.${tail.map((s) => s.replace(/'/g, "''")).join(".")}'`})`;
560
+ };
561
+ /**
562
+ * Quote a leaf primitive for use as the right-hand side of a
563
+ * comparison. Booleans branch on target. Nested objects must never
564
+ * reach here — wire `eq` clauses on nested objects can only come
565
+ * from the callback form `q.eq("nested", { ... })`, which the
566
+ * export translator does not support today.
567
+ */
568
+ const quoteLeaf = (value, target) => {
569
+ if (typeof value === "object") throw new BaerlyError("InvalidConfig", "translatePredicateWireToSql: nested object reached leaf quoter — callback-form q.eq(field, object) is not supported for SQL export. Hand-edit the emitted SQL.");
570
+ return quoteValue(value, target);
571
+ };
572
+ // src/export/plan-sidecar.ts
573
+ const SIDECAR_SCHEMA_VERSION = 1;
574
+ /**
575
+ * Encode an {@link ExportPlan} as the canonical sidecar JSON string.
576
+ *
577
+ * Wire format is pretty-printed (`indent=2`) with a trailing newline
578
+ * so `cat sidecar.plan.json` is human-readable and `diff` works on
579
+ * two sidecars without spurious line-end noise. The on-wire bytes
580
+ * embed the `schemaVersion` discriminator so future shape changes
581
+ * are detectable; `identifier` and `tableIdentifier` are NOT carried
582
+ * (they're re-derived via {@link quoteIdentifier} on deserialise).
583
+ */
584
+ const serializeExportPlan = (plan) => {
585
+ return JSON.stringify({
586
+ schemaVersion: SIDECAR_SCHEMA_VERSION,
587
+ table: plan.table,
588
+ target: plan.target,
589
+ columns: plan.columns.map((c) => ({
590
+ source: c.source,
591
+ sqlType: c.sqlType,
592
+ nullable: c.nullable,
593
+ jsonEncoded: c.jsonEncoded
594
+ }))
595
+ }, null, 2) + "\n";
596
+ };
597
+ // src/export.ts
598
+ /**
599
+ * `baerly export` — snapshot dump of one collection to SQL.
600
+ *
601
+ * Drives the export modules end-to-end: load the materialised view,
602
+ * infer an `ExportPlan` over the row shape, emit `CREATE TABLE` +
603
+ * `INSERT` statements. When `--where=<json>` is supplied the
604
+ * predicate is translated via `translatePredicateToSql` and applied
605
+ * in-memory through `matches(...)` so the emitted INSERTs already
606
+ * match the filter; the translated WHERE clause is also surfaced as a
607
+ * comment above the inserts so operators can inspect / hand-edit it.
608
+ *
609
+ * The sidecar file (`<output>.plan.json`) carries the `ExportPlan` so
610
+ * a follow-up round-trip ingest can verify the column schema. The
611
+ * sidecar is JSON via `JSON.stringify` — the plan shape is the public
612
+ * contract.
613
+ *
614
+ * Args:
615
+ * --bucket Required. Bucket URI.
616
+ * --app Required (or via baerly.config.ts).
617
+ * --tenant Required (or via baerly.config.ts).
618
+ * --collection Required. Collection name.
619
+ * --target Required. postgres | sqlite | d1.
620
+ * --where Optional. JSON-encoded `Predicate<T>`.
621
+ * --where-comment Optional. Caller hint surfaced as a
622
+ * `-- TODO(baerly export):` comment.
623
+ * --output Optional. Path to write SQL into; default
624
+ * stdout. The sidecar plan is written to
625
+ * `<output>.plan.json` unless `--no-sidecar`.
626
+ * --no-sidecar Skip emitting the sidecar plan file.
627
+ * --json JSON envelope on stdout (or stderr on error).
628
+ *
629
+ * Exit codes:
630
+ * 0 — dump completed.
631
+ * 1 — InvalidConfig (bad args / bucket URI / --where JSON / unknown --target).
632
+ * 2 — Storage / Network error.
633
+ * 3 — Protocol invariant / conflict (Internal / InvalidResponse /
634
+ * WriteConflict / AlreadyExists).
635
+ */
636
+ const EXPORT_ARGS = {
637
+ bucket: BUCKET_ARG,
638
+ app: APP_ARG,
639
+ tenant: TENANT_ARG,
640
+ collection: COLLECTION_ARG,
641
+ target: {
642
+ type: "enum",
643
+ options: [
644
+ "postgres",
645
+ "sqlite",
646
+ "d1"
647
+ ],
648
+ required: true,
649
+ description: "SQL target: postgres | sqlite | d1."
650
+ },
651
+ where: {
652
+ type: "string",
653
+ required: false,
654
+ description: "JSON-encoded PredicateWire ({ clauses: [...] }) filtering the rows to export.",
655
+ valueHint: "json"
656
+ },
657
+ "where-comment": {
658
+ type: "string",
659
+ required: false,
660
+ description: "Caller hint surfaced as a -- TODO(baerly export): comment.",
661
+ valueHint: "text"
662
+ },
663
+ output: {
664
+ type: "string",
665
+ required: false,
666
+ description: "Path to write SQL into; default stdout.",
667
+ valueHint: "path"
668
+ },
669
+ sidecar: {
670
+ type: "boolean",
671
+ default: true,
672
+ description: "Emit a <output>.plan.json sidecar (default true; pass --no-sidecar to skip)."
673
+ },
674
+ json: JSON_ARG
675
+ };
676
+ const parseWherePredicate = (raw) => {
677
+ let parsed;
678
+ try {
679
+ parsed = JSON.parse(raw);
680
+ } catch (error) {
681
+ throw new BaerlyError("InvalidConfig", `baerly export: --where is not valid JSON: ${error.message}`);
682
+ }
683
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new BaerlyError("InvalidConfig", `baerly export: --where must decode to a JSON object (got ${describeNonObject(parsed)})`);
684
+ validateWire(parsed);
685
+ return parsed;
686
+ };
687
+ const filterRows = (rows, wire) => {
688
+ const filtered = /* @__PURE__ */ new Map();
689
+ for (const [id, body] of rows) {
690
+ if (wire === null) {
691
+ filtered.set(id, body);
692
+ continue;
693
+ }
694
+ if (matchesWire(wire, body)) filtered.set(id, body);
695
+ }
696
+ return filtered;
697
+ };
698
+ const buildSql = async (plan, rows, whereClause, whereHints) => {
699
+ let out = emitCreateTable(plan);
700
+ for (const hint of whereHints) out += `-- TODO(baerly export): ${hint}\n`;
701
+ if (whereClause.length > 0) out += `-- WHERE clause for review: ${whereClause}\n`;
702
+ for await (const chunk of emitInsertStatements(plan, rows)) out += chunk;
703
+ return out;
704
+ };
705
+ const bundle = defineBaerlySubcommand({
706
+ name: "export",
707
+ meta: { description: "Snapshot dump of one collection to SQL." },
708
+ args: EXPORT_ARGS,
709
+ handler: async (args, ctx) => {
710
+ const target = args.target;
711
+ const { app, tenant } = await ctx.resolveAppTenant({
712
+ app: args.app,
713
+ tenant: args.tenant
714
+ });
715
+ assertCollectionArg(args.collection, "baerly export");
716
+ const bucket = await parseBucketUri(args.bucket);
717
+ const currentJsonKey = `${bucket.keyPrefix}app/${app}/tenant/${tenant}/manifests/${args.collection}/current.json`;
718
+ const view = await loadMaterialisedView({
719
+ storage: bucket.storage,
720
+ currentJsonKey,
721
+ collection: args.collection
722
+ });
723
+ if (view === null) throw new BaerlyError("InvalidConfig", `baerly export: collection ${JSON.stringify(args.collection)} is not provisioned (no current.json at ${currentJsonKey})`);
724
+ const plan = inferPlanForCollection({
725
+ rows: view,
726
+ target,
727
+ table: args.collection
728
+ });
729
+ let wire = null;
730
+ let whereClause = "";
731
+ let whereHints = [];
732
+ if (typeof args.where === "string" && args.where.length > 0) {
733
+ wire = parseWherePredicate(args.where);
734
+ const translation = translatePredicateWireToSql(wire, plan, typeof args["where-comment"] === "string" && args["where-comment"].length > 0 ? { dynamicHint: args["where-comment"] } : void 0);
735
+ whereClause = translation.sql;
736
+ whereHints = translation.hints;
737
+ } else if (typeof args["where-comment"] === "string" && args["where-comment"].length > 0) whereHints = [`caller-flagged dynamic predicate: ${args["where-comment"]}. No predicate supplied; emitted INSERTs cover the full collection.`];
738
+ const filtered = filterRows(view, wire);
739
+ const sql = await buildSql(plan, filtered, whereClause, whereHints);
740
+ const outputPath = args.output;
741
+ if (typeof outputPath === "string" && outputPath.length > 0) {
742
+ await writeFile(outputPath, sql, "utf8");
743
+ if (args.sidecar !== false) await writeFile(`${outputPath}.plan.json`, serializeExportPlan(plan), "utf8");
744
+ } else process.stdout.write(sql);
745
+ emitSuccess({
746
+ command: "export",
747
+ status: "ok",
748
+ collection: args.collection,
749
+ target,
750
+ rows: filtered.size,
751
+ hints: whereHints,
752
+ ...typeof outputPath === "string" && outputPath.length > 0 && { output: outputPath }
753
+ });
754
+ return 0;
755
+ }
756
+ });
757
+ /** citty `defineCommand` block for `baerly export`. */
758
+ const exportCmd = bundle.cmd;
759
+ bundle.run;
760
+ const describeNonObject = (v) => {
761
+ if (v === null) return "null";
762
+ if (Array.isArray(v)) return "array";
763
+ return typeof v;
764
+ };
765
+ export { exportCmd };
376
766
 
377
- //# sourceMappingURL=validate-DtljsCh1.js.map
767
+ //# sourceMappingURL=export-BVL2EvYE.js.map