viborm 1.16.1 → 1.17.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 (402) hide show
  1. package/dist/adapter-internals-Dz2nNEF5.mjs +2 -0
  2. package/dist/adapter-internals-Dz2nNEF5.mjs.map +1 -0
  3. package/dist/adapter-namespace-C1SUkH2U.mjs +2 -0
  4. package/dist/{adapter-namespace-DwFnfpED.mjs.map → adapter-namespace-C1SUkH2U.mjs.map} +1 -1
  5. package/dist/adapters.d.mts +50 -94
  6. package/dist/adapters.mjs +1 -1
  7. package/dist/{args-7WgBFd_f.mjs → args-DsGRkPRw.mjs} +2 -2
  8. package/dist/{args-7WgBFd_f.mjs.map → args-DsGRkPRw.mjs.map} +1 -1
  9. package/dist/{array-literal-BOzj0E2u.mjs → array-literal-U6SeastY.mjs} +1 -1
  10. package/dist/{array-literal-BOzj0E2u.mjs.map → array-literal-U6SeastY.mjs.map} +1 -1
  11. package/dist/auto-names-GpcDfhaw.mjs +2 -0
  12. package/dist/auto-names-GpcDfhaw.mjs.map +1 -0
  13. package/dist/batch-refs-BuICt2tu.mjs +2 -0
  14. package/dist/{batch-refs-Bd8HvwUc.mjs.map → batch-refs-BuICt2tu.mjs.map} +1 -1
  15. package/dist/better-auth.d.mts +1 -1
  16. package/dist/better-auth.mjs +2 -2
  17. package/dist/bun-sql.d.mts +1 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sqlite.d.mts +1 -1
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/cache/cloudflare-kv.d.mts +1 -1
  22. package/dist/cache/cloudflare-kv.mjs +1 -1
  23. package/dist/cache/memory.d.mts +1 -1
  24. package/dist/cache/memory.mjs +1 -1
  25. package/dist/cache.d.mts +2 -2
  26. package/dist/cache.mjs +1 -1
  27. package/dist/call-D2E7dPCd.mjs +2 -0
  28. package/dist/{call-0bd_B9Vp.mjs.map → call-D2E7dPCd.mjs.map} +1 -1
  29. package/dist/cli.mjs +6 -6
  30. package/dist/cli.mjs.map +1 -1
  31. package/dist/client-Cq_VcF43.d.mts +183 -0
  32. package/dist/client-DkNRAOuH.mjs +2 -0
  33. package/dist/client-DkNRAOuH.mjs.map +1 -0
  34. package/dist/{planner-CYu6_q4w.d.mts → client-driver-DuQy6lsN.d.mts} +3 -3
  35. package/dist/client-rIiFOn1W.mjs +9 -0
  36. package/dist/client-rIiFOn1W.mjs.map +1 -0
  37. package/dist/client.d.mts +2 -2
  38. package/dist/client.mjs +1 -1
  39. package/dist/config.d.mts +2 -2
  40. package/dist/config.mjs +1 -1
  41. package/dist/{confine-CyI9IwjC.mjs → confine-FIfjlAHp.mjs} +2 -2
  42. package/dist/{confine-CyI9IwjC.mjs.map → confine-FIfjlAHp.mjs.map} +1 -1
  43. package/dist/{object-store-BBDTj8x3.d.mts → conformance-C1JveA8y.d.mts} +5 -60
  44. package/dist/conformance-C4JYA0JG.mjs +2 -0
  45. package/dist/conformance-C4JYA0JG.mjs.map +1 -0
  46. package/dist/contract-BBone8RD.mjs +2 -0
  47. package/dist/contract-BBone8RD.mjs.map +1 -0
  48. package/dist/coordination-BxMskOgi.mjs +1 -1
  49. package/dist/d1.d.mts +1 -1
  50. package/dist/d1.mjs +1 -1
  51. package/dist/{database-adapter-01J6mYq5.d.mts → database-adapter-cW0nmWM6.d.mts} +2 -2
  52. package/dist/datetime-physical-codec-Ci0dyOot.mjs +2 -0
  53. package/dist/datetime-physical-codec-Ci0dyOot.mjs.map +1 -0
  54. package/dist/datetime-values-D_G6m5_o.mjs +2 -0
  55. package/dist/datetime-values-D_G6m5_o.mjs.map +1 -0
  56. package/dist/decimal-D4DRlT2y.mjs +2 -0
  57. package/dist/decimal-D4DRlT2y.mjs.map +1 -0
  58. package/dist/{defaults-DAPb-tJ4.mjs → defaults-BrXUK350.mjs} +2 -2
  59. package/dist/{defaults-DAPb-tJ4.mjs.map → defaults-BrXUK350.mjs.map} +1 -1
  60. package/dist/{document-DRPqjDv_.d.mts → document-B8ClXlb7.d.mts} +1 -1
  61. package/dist/{driver-kiIQS_Fd.mjs → driver-BOsmU3kz.mjs} +2 -2
  62. package/dist/{driver-kiIQS_Fd.mjs.map → driver-BOsmU3kz.mjs.map} +1 -1
  63. package/dist/{driver-CTjq1yxj.d.mts → driver-KgGMnfz8.d.mts} +1 -1
  64. package/dist/{driver-lShUkDmf.mjs → driver-PkP_1p80.mjs} +2 -2
  65. package/dist/{driver-lShUkDmf.mjs.map → driver-PkP_1p80.mjs.map} +1 -1
  66. package/dist/{driver-diagnostics-aQ54bArn.mjs → driver-diagnostics-sSpge6kv.mjs} +1 -1
  67. package/dist/{driver-diagnostics-aQ54bArn.mjs.map → driver-diagnostics-sSpge6kv.mjs.map} +1 -1
  68. package/dist/driver.d.mts +1 -1
  69. package/dist/driver.mjs +1 -1
  70. package/dist/durable-object.d.mts +1 -1
  71. package/dist/durable-object.mjs +2 -2
  72. package/dist/error-mapping-B9rSvgG9.mjs +1 -1
  73. package/dist/every-tAZuZ50K.mjs +2 -0
  74. package/dist/{every-CgeIFxWR.mjs.map → every-tAZuZ50K.mjs.map} +1 -1
  75. package/dist/execution-context-couU2tgh.mjs +1 -1
  76. package/dist/{exports-nC8lsVKO.d.mts → exports-reE3GioL.d.mts} +1 -1
  77. package/dist/extension-Bf4vO5mp.mjs +2 -0
  78. package/dist/extension-Bf4vO5mp.mjs.map +1 -0
  79. package/dist/facts-Bjnzv3j-.mjs +2 -0
  80. package/dist/facts-Bjnzv3j-.mjs.map +1 -0
  81. package/dist/{fs-estate-n-QpsFqb.mjs → fs-estate-C3ahNKmi.mjs} +2 -2
  82. package/dist/{fs-estate-n-QpsFqb.mjs.map → fs-estate-C3ahNKmi.mjs.map} +1 -1
  83. package/dist/geo-area-codec-CBdiCOzj.mjs +2 -0
  84. package/dist/{geo-area-codec-Bti2PA2i.mjs.map → geo-area-codec-CBdiCOzj.mjs.map} +1 -1
  85. package/dist/geo-point-DCV0eO1p.mjs +2 -0
  86. package/dist/geo-point-DCV0eO1p.mjs.map +1 -0
  87. package/dist/id-domain-Cj6MnMxg.mjs +2 -0
  88. package/dist/{id-domain-Cg65TLZ-.mjs.map → id-domain-Cj6MnMxg.mjs.map} +1 -1
  89. package/dist/identifier-BdLx66pi.mjs +2 -0
  90. package/dist/identifier-BdLx66pi.mjs.map +1 -0
  91. package/dist/identifier-conversion-CMKVatU4.mjs +3 -0
  92. package/dist/identifier-conversion-CMKVatU4.mjs.map +1 -0
  93. package/dist/{identifiers-BxOf57qy.mjs → identifiers-BAZ_S6Lk.mjs} +1 -1
  94. package/dist/{identifiers-BxOf57qy.mjs.map → identifiers-BAZ_S6Lk.mjs.map} +1 -1
  95. package/dist/{identity-CJlRQA-m.mjs → identity-nPArhpsD.mjs} +2 -2
  96. package/dist/{identity-CJlRQA-m.mjs.map → identity-nPArhpsD.mjs.map} +1 -1
  97. package/dist/index.d.mts +2 -2
  98. package/dist/index.mjs +1 -1
  99. package/dist/index.mjs.map +1 -1
  100. package/dist/instrumentation.d.mts +1 -1
  101. package/dist/instrumentation.mjs +1 -1
  102. package/dist/introspect-dyBpdr2L.mjs +2 -0
  103. package/dist/{introspect-rGqr93B3.mjs.map → introspect-dyBpdr2L.mjs.map} +1 -1
  104. package/dist/json-DvvrTWUw.mjs +2 -0
  105. package/dist/{json-CsAdz9pg.mjs.map → json-DvvrTWUw.mjs.map} +1 -1
  106. package/dist/{json-number-C09rsm1g.mjs → json-number-Guh-5rff.mjs} +1 -1
  107. package/dist/{json-number-C09rsm1g.mjs.map → json-number-Guh-5rff.mjs.map} +1 -1
  108. package/dist/{json-parameter-D7hDrVKw.mjs → json-parameter-DtHhEfyE.mjs} +1 -1
  109. package/dist/{json-parameter-D7hDrVKw.mjs.map → json-parameter-DtHhEfyE.mjs.map} +1 -1
  110. package/dist/judge-words-CqNdnbou.mjs +2 -0
  111. package/dist/judge-words-CqNdnbou.mjs.map +1 -0
  112. package/dist/{key-BDH6oTyC.mjs → key-v4k7Cqb6.mjs} +2 -2
  113. package/dist/{key-BDH6oTyC.mjs.map → key-v4k7Cqb6.mjs.map} +1 -1
  114. package/dist/{keys-CIal55WQ.mjs → keys-BLWaO_YM.mjs} +1 -1
  115. package/dist/{keys-CIal55WQ.mjs.map → keys-BLWaO_YM.mjs.map} +1 -1
  116. package/dist/keys-o4Pl6Vsg.mjs +2 -0
  117. package/dist/{keys-DZdKAd4n.mjs.map → keys-o4Pl6Vsg.mjs.map} +1 -1
  118. package/dist/libsql-C0iMZifz.mjs +3 -0
  119. package/dist/libsql-C0iMZifz.mjs.map +1 -0
  120. package/dist/libsql.d.mts +1 -1
  121. package/dist/libsql.mjs +1 -1
  122. package/dist/light-reLULeHN.mjs +2 -0
  123. package/dist/{light-D2wNSbzY.mjs.map → light-reLULeHN.mjs.map} +1 -1
  124. package/dist/memory-DtTuFo-h.mjs +2 -0
  125. package/dist/memory-DtTuFo-h.mjs.map +1 -0
  126. package/dist/methods-part-Dsi0DBNU.mjs +2 -0
  127. package/dist/{methods-part-BaNx3o7b.mjs.map → methods-part-Dsi0DBNU.mjs.map} +1 -1
  128. package/dist/migrations/mysql/runtime.d.mts +7 -0
  129. package/dist/migrations/mysql/runtime.mjs +2 -0
  130. package/dist/migrations/mysql/runtime.mjs.map +1 -0
  131. package/dist/migrations/mysql.d.mts +7 -5
  132. package/dist/migrations/mysql.mjs +1 -1
  133. package/dist/migrations/mysql.mjs.map +1 -1
  134. package/dist/migrations/postgres/runtime.d.mts +7 -0
  135. package/dist/migrations/postgres/runtime.mjs +2 -0
  136. package/dist/migrations/postgres/runtime.mjs.map +1 -0
  137. package/dist/migrations/postgres.d.mts +7 -5
  138. package/dist/migrations/postgres.mjs +1 -1
  139. package/dist/migrations/postgres.mjs.map +1 -1
  140. package/dist/migrations/snowflake.d.mts +7 -5
  141. package/dist/migrations/snowflake.mjs +1 -1
  142. package/dist/migrations/snowflake.mjs.map +1 -1
  143. package/dist/migrations/sqlite/runtime.d.mts +7 -0
  144. package/dist/migrations/sqlite/runtime.mjs +2 -0
  145. package/dist/migrations/sqlite/runtime.mjs.map +1 -0
  146. package/dist/migrations/sqlite.d.mts +7 -5
  147. package/dist/migrations/sqlite.mjs +1 -1
  148. package/dist/migrations/sqlite.mjs.map +1 -1
  149. package/dist/migrations/storage/durable-object.d.mts +1 -1
  150. package/dist/migrations/storage/durable-object.mjs +1 -1
  151. package/dist/migrations/storage/fs.d.mts +1 -1
  152. package/dist/migrations/storage/fs.mjs +1 -1
  153. package/dist/migrations/storage/r2.d.mts +1 -1
  154. package/dist/migrations/storage/r2.mjs +1 -1
  155. package/dist/migrations/surrealdb.d.mts +7 -5
  156. package/dist/migrations/surrealdb.mjs +1 -1
  157. package/dist/migrations/surrealdb.mjs.map +1 -1
  158. package/dist/migrations/tenant.d.mts +4 -3
  159. package/dist/migrations/tenant.mjs +1 -1
  160. package/dist/migrations/tenant.mjs.map +1 -1
  161. package/dist/migrations.d.mts +7 -5
  162. package/dist/migrations.mjs +1 -1
  163. package/dist/migrations.mjs.map +1 -1
  164. package/dist/model-ByktcCGW.mjs +2 -0
  165. package/dist/model-ByktcCGW.mjs.map +1 -0
  166. package/dist/mysql-DPYi1p_g.mjs +4 -0
  167. package/dist/mysql-DPYi1p_g.mjs.map +1 -0
  168. package/dist/mysql-adapter-6gVm5PHp.mjs +2 -0
  169. package/dist/{mysql-adapter-BFWYPoM0.mjs.map → mysql-adapter-6gVm5PHp.mjs.map} +1 -1
  170. package/dist/mysql2.d.mts +1 -1
  171. package/dist/mysql2.mjs +1 -1
  172. package/dist/{named-statements-CkOOD__I.mjs → named-statements-CswIc5m1.mjs} +2 -2
  173. package/dist/{named-statements-CkOOD__I.mjs.map → named-statements-CswIc5m1.mjs.map} +1 -1
  174. package/dist/native-types-BUkcVedc.mjs +2 -0
  175. package/dist/native-types-BUkcVedc.mjs.map +1 -0
  176. package/dist/neon-http.d.mts +1 -1
  177. package/dist/neon-http.mjs +1 -1
  178. package/dist/normalized-result-D7nVkF36.mjs +1 -1
  179. package/dist/{object-store-Chq1PMYz.mjs → object-store-DnrLNxz_.mjs} +2 -2
  180. package/dist/{object-store-Chq1PMYz.mjs.map → object-store-DnrLNxz_.mjs.map} +1 -1
  181. package/dist/object-store-j4kgh61D.d.mts +59 -0
  182. package/dist/{on-ZkOVmE4-.mjs → on-nOenqmgP.mjs} +2 -2
  183. package/dist/{on-ZkOVmE4-.mjs.map → on-nOenqmgP.mjs.map} +1 -1
  184. package/dist/on.d.mts +1 -1
  185. package/dist/on.mjs +1 -1
  186. package/dist/ordering/keys.mjs +1 -1
  187. package/dist/ordering.d.mts +1 -1
  188. package/dist/ordering.mjs +2 -2
  189. package/dist/pending-operation-B5o-zhES.mjs +2 -0
  190. package/dist/{pending-operation-D4gUKMxD.mjs.map → pending-operation-B5o-zhES.mjs.map} +1 -1
  191. package/dist/permissions.d.mts +1 -1
  192. package/dist/permissions.mjs +1 -1
  193. package/dist/pg.d.mts +2 -2
  194. package/dist/pg.mjs +1 -1
  195. package/dist/pglite.d.mts +1 -1
  196. package/dist/pglite.mjs +1 -1
  197. package/dist/{physical-DO4PEYcc.mjs → physical-BheMRPY0.mjs} +2 -2
  198. package/dist/{physical-DO4PEYcc.mjs.map → physical-BheMRPY0.mjs.map} +1 -1
  199. package/dist/{pinned-session-Y7-2pRBJ.mjs → pinned-session-eNyd0dkT.mjs} +2 -2
  200. package/dist/{pinned-session-Y7-2pRBJ.mjs.map → pinned-session-eNyd0dkT.mjs.map} +1 -1
  201. package/dist/planetscale.d.mts +1 -1
  202. package/dist/planetscale.mjs +1 -1
  203. package/dist/postgres-CEGFOi8D.mjs +27 -0
  204. package/dist/postgres-CEGFOi8D.mjs.map +1 -0
  205. package/dist/postgres-adapter-B-im38AE.mjs +2 -0
  206. package/dist/postgres-adapter-B-im38AE.mjs.map +1 -0
  207. package/dist/{postgres-adapter-BpLizOaK.mjs → postgres-adapter-OoqoBdhb.mjs} +2 -2
  208. package/dist/{postgres-adapter-BpLizOaK.mjs.map → postgres-adapter-OoqoBdhb.mjs.map} +1 -1
  209. package/dist/{postgres-result-133boRW-.mjs → postgres-result-D-bqmofR.mjs} +1 -1
  210. package/dist/{postgres-result-133boRW-.mjs.map → postgres-result-D-bqmofR.mjs.map} +1 -1
  211. package/dist/postgres.d.mts +2 -2
  212. package/dist/postgres.mjs +1 -1
  213. package/dist/provider-limits-DvcCUw7l.mjs +2 -0
  214. package/dist/{provider-limits-SdI1SaJS.mjs.map → provider-limits-DvcCUw7l.mjs.map} +1 -1
  215. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs → provider-parameter-snapshot-DnJ6Av9y.mjs} +2 -2
  216. package/dist/{provider-parameter-snapshot-cyTUDutH.mjs.map → provider-parameter-snapshot-DnJ6Av9y.mjs.map} +1 -1
  217. package/dist/push-fingerprint-CegYVFFp.mjs +18 -0
  218. package/dist/push-fingerprint-CegYVFFp.mjs.map +1 -0
  219. package/dist/{quantized-BKBs0joq.mjs → quantized-DLD2cd6q.mjs} +1 -1
  220. package/dist/{quantized-BKBs0joq.mjs.map → quantized-DLD2cd6q.mjs.map} +1 -1
  221. package/dist/query-DSEMPA7r.mjs +2 -0
  222. package/dist/query-DSEMPA7r.mjs.map +1 -0
  223. package/dist/query-backend-CzwVfrQ6.mjs +2 -0
  224. package/dist/{query-backend-TisPjCPF.mjs.map → query-backend-CzwVfrQ6.mjs.map} +1 -1
  225. package/dist/{query-inspection-DwYBKSDG.mjs → query-inspection-CvtTL5Fs.mjs} +2 -2
  226. package/dist/{query-inspection-DwYBKSDG.mjs.map → query-inspection-CvtTL5Fs.mjs.map} +1 -1
  227. package/dist/raw-B8cNef_V.mjs +2 -0
  228. package/dist/{raw-DqEb71JZ.mjs.map → raw-B8cNef_V.mjs.map} +1 -1
  229. package/dist/{relation-bound-CSNKLyDy.mjs → relation-bound-DHP5cpTE.mjs} +1 -1
  230. package/dist/{relation-bound-CSNKLyDy.mjs.map → relation-bound-DHP5cpTE.mjs.map} +1 -1
  231. package/dist/{result-parsing-BbffueEX.mjs → result-parsing-DfwBAXY2.mjs} +1 -1
  232. package/dist/{result-parsing-BbffueEX.mjs.map → result-parsing-DfwBAXY2.mjs.map} +1 -1
  233. package/dist/{rows-of-Bgl9GVtK.mjs → rows-of-UeSasWGq.mjs} +2 -2
  234. package/dist/{rows-of-Bgl9GVtK.mjs.map → rows-of-UeSasWGq.mjs.map} +1 -1
  235. package/dist/rule-words-ojG0-vSf.mjs +2 -0
  236. package/dist/{rule-words-DMbQuvD2.mjs.map → rule-words-ojG0-vSf.mjs.map} +1 -1
  237. package/dist/runtime-BAqlANG_.mjs +10 -0
  238. package/dist/runtime-BAqlANG_.mjs.map +1 -0
  239. package/dist/runtime-D0oaIS1E.mjs +2 -0
  240. package/dist/runtime-D0oaIS1E.mjs.map +1 -0
  241. package/dist/runtime-Dfkv59_p.mjs +15 -0
  242. package/dist/runtime-Dfkv59_p.mjs.map +1 -0
  243. package/dist/runtime-client-CvGGOOFd.d.mts +38 -0
  244. package/dist/runtime-client-xeiXA_1m.mjs +2 -0
  245. package/dist/runtime-client-xeiXA_1m.mjs.map +1 -0
  246. package/dist/scalar-BTYxpiP_.mjs +4 -0
  247. package/dist/scalar-BTYxpiP_.mjs.map +1 -0
  248. package/dist/schema/introspect.d.mts +2 -2
  249. package/dist/schema/introspect.mjs +1 -1
  250. package/dist/schema/json.d.mts +2 -2
  251. package/dist/schema/json.mjs +1 -1
  252. package/dist/schema-BzkBJTF-.mjs +2 -0
  253. package/dist/{schema-DDkAUfOb.mjs.map → schema-BzkBJTF-.mjs.map} +1 -1
  254. package/dist/schema-D7MyYTjA.mjs +2 -0
  255. package/dist/{schema-DqR_Kcje.mjs.map → schema-D7MyYTjA.mjs.map} +1 -1
  256. package/dist/{schema-introspection-Bbo4DN_d.mjs → schema-introspection-b4xPGPfu.mjs} +4 -4
  257. package/dist/{schema-introspection-Bbo4DN_d.mjs.map → schema-introspection-b4xPGPfu.mjs.map} +1 -1
  258. package/dist/schema.d.mts +1 -1
  259. package/dist/schema.mjs +1 -1
  260. package/dist/{select-assembly-CEpNu-Gw.mjs → select-assembly-B01JtBRm.mjs} +2 -2
  261. package/dist/{select-assembly-CEpNu-Gw.mjs.map → select-assembly-B01JtBRm.mjs.map} +1 -1
  262. package/dist/serializer-CIhcZMxs.mjs +7 -0
  263. package/dist/serializer-CIhcZMxs.mjs.map +1 -0
  264. package/dist/{settle-Pui-1tfJ.mjs → settle-CIbvnLED.mjs} +1 -1
  265. package/dist/{settle-Pui-1tfJ.mjs.map → settle-CIbvnLED.mjs.map} +1 -1
  266. package/dist/{settled-DYYPcaBX.mjs → settled-Clanz_kI.mjs} +2 -2
  267. package/dist/{settled-DYYPcaBX.mjs.map → settled-Clanz_kI.mjs.map} +1 -1
  268. package/dist/snowflake-C1dqbche.mjs +2 -0
  269. package/dist/{snowflake-B8Ei88bg.mjs.map → snowflake-C1dqbche.mjs.map} +1 -1
  270. package/dist/snowflake.d.mts +2 -2
  271. package/dist/snowflake.mjs +2 -2
  272. package/dist/snowflake.mjs.map +1 -1
  273. package/dist/soft-delete.d.mts +1 -1
  274. package/dist/soft-delete.mjs +1 -1
  275. package/dist/{spans-DwDXMvyd.mjs → spans-CVl3RKUR.mjs} +1 -1
  276. package/dist/{spans-DwDXMvyd.mjs.map → spans-CVl3RKUR.mjs.map} +1 -1
  277. package/dist/sql-AHN2niBz.mjs +2 -0
  278. package/dist/{sql-M5WsPhqr.mjs.map → sql-AHN2niBz.mjs.map} +1 -1
  279. package/dist/sql-control-Cdp0_Mwy.mjs +2 -0
  280. package/dist/sql-control-Cdp0_Mwy.mjs.map +1 -0
  281. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs → sql-statement-tokens-BdVJnUQY.mjs} +2 -2
  282. package/dist/{sql-statement-tokens-Z5Ta4iDB.mjs.map → sql-statement-tokens-BdVJnUQY.mjs.map} +1 -1
  283. package/dist/sql-tegqTqGq.mjs +1 -1
  284. package/dist/sql.d.mts +1 -1
  285. package/dist/sqlite-adapter-B7r7w3CS.mjs +2 -0
  286. package/dist/sqlite-adapter-B7r7w3CS.mjs.map +1 -0
  287. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs → sqlite-statement-classifier-CBmKy8Ta.mjs} +2 -2
  288. package/dist/{sqlite-statement-classifier-JBHiQO6Q.mjs.map → sqlite-statement-classifier-CBmKy8Ta.mjs.map} +1 -1
  289. package/dist/sqlite-storage-audit-D8nA9ylL.mjs +2 -0
  290. package/dist/sqlite-storage-audit-D8nA9ylL.mjs.map +1 -0
  291. package/dist/{sqlite-utils-Bfmtkt1b.mjs → sqlite-utils-BAUMCrok.mjs} +2 -2
  292. package/dist/{sqlite-utils-Bfmtkt1b.mjs.map → sqlite-utils-BAUMCrok.mjs.map} +1 -1
  293. package/dist/sqlite3.d.mts +1 -1
  294. package/dist/sqlite3.mjs +1 -1
  295. package/dist/{standard-sql-Bl2OHGfi.mjs → standard-sql-tpcKlArE.mjs} +2 -2
  296. package/dist/{standard-sql-Bl2OHGfi.mjs.map → standard-sql-tpcKlArE.mjs.map} +1 -1
  297. package/dist/surrealdb.d.mts +2 -2
  298. package/dist/surrealdb.mjs +1 -1
  299. package/dist/surrealdb.mjs.map +1 -1
  300. package/dist/surrealql-AyDLKSEQ.mjs +2 -0
  301. package/dist/surrealql-AyDLKSEQ.mjs.map +1 -0
  302. package/dist/time-step-BIdl2Iy7.mjs +2 -0
  303. package/dist/time-step-BIdl2Iy7.mjs.map +1 -0
  304. package/dist/transaction-operation-CaWzo7gE.mjs +1 -1
  305. package/dist/type-mapping-BYre7JQ1.mjs +3 -0
  306. package/dist/type-mapping-BYre7JQ1.mjs.map +1 -0
  307. package/dist/{types-Dy33vBdd.mjs → types-M-IdB4Mo.mjs} +1 -1
  308. package/dist/{types-Dy33vBdd.mjs.map → types-M-IdB4Mo.mjs.map} +1 -1
  309. package/dist/{unit-DUPX5Sdd.mjs → unit-Dnp2HIWg.mjs} +2 -2
  310. package/dist/{unit-DUPX5Sdd.mjs.map → unit-Dnp2HIWg.mjs.map} +1 -1
  311. package/dist/{unit-words-BXpLpyr2.mjs → unit-words-DjVhRXAQ.mjs} +2 -2
  312. package/dist/{unit-words-BXpLpyr2.mjs.map → unit-words-DjVhRXAQ.mjs.map} +1 -1
  313. package/dist/{utils-BHkJsduV.mjs → utils-BB_4NZQC.mjs} +2 -2
  314. package/dist/{utils-BHkJsduV.mjs.map → utils-BB_4NZQC.mjs.map} +1 -1
  315. package/dist/utils-DYrxwV_M.mjs +2 -0
  316. package/dist/utils-DYrxwV_M.mjs.map +1 -0
  317. package/dist/{v1-parse-shared-cJ-uD14P.mjs → v1-parse-shared-CNiFHAJF.mjs} +1 -1
  318. package/dist/{v1-parse-shared-cJ-uD14P.mjs.map → v1-parse-shared-CNiFHAJF.mjs.map} +1 -1
  319. package/dist/validation-CEnhYqhl.mjs +2 -0
  320. package/dist/{validation-BHjx13zG.mjs.map → validation-CEnhYqhl.mjs.map} +1 -1
  321. package/dist/validation.d.mts +1 -1
  322. package/dist/validation.mjs +1 -1
  323. package/dist/validator-CISkL46K.mjs +2 -0
  324. package/dist/validator-CISkL46K.mjs.map +1 -0
  325. package/dist/{values-Ch2cTlss.mjs → values-D0k60ei0.mjs} +2 -2
  326. package/dist/{values-Ch2cTlss.mjs.map → values-D0k60ei0.mjs.map} +1 -1
  327. package/dist/{client-Bb2oZOzg.d.mts → verify-v1-CJFrJ4lx.d.mts} +10 -183
  328. package/dist/version-nEOMCWfV.mjs +2 -0
  329. package/dist/{version-Bu2LCuaj.mjs.map → version-nEOMCWfV.mjs.map} +1 -1
  330. package/dist/view-CmLQ0I6x.mjs +2 -0
  331. package/dist/{view-CHgjF2BO.mjs.map → view-CmLQ0I6x.mjs.map} +1 -1
  332. package/dist/write-sinks-BhwgQn_5.mjs +2 -0
  333. package/dist/{write-sinks-Bei5vFHP.mjs.map → write-sinks-BhwgQn_5.mjs.map} +1 -1
  334. package/package.json +27 -2
  335. package/dist/adapter-namespace-DwFnfpED.mjs +0 -2
  336. package/dist/batch-refs-Bd8HvwUc.mjs +0 -2
  337. package/dist/call-0bd_B9Vp.mjs +0 -2
  338. package/dist/client-BvAmGuYW.mjs +0 -9
  339. package/dist/client-BvAmGuYW.mjs.map +0 -1
  340. package/dist/client-Q4zkYZbn.mjs +0 -2
  341. package/dist/client-Q4zkYZbn.mjs.map +0 -1
  342. package/dist/datetime-physical-codec-DAF7WJpy.mjs +0 -2
  343. package/dist/datetime-physical-codec-DAF7WJpy.mjs.map +0 -1
  344. package/dist/every-CgeIFxWR.mjs +0 -2
  345. package/dist/extension-Dh1ddrlA.mjs +0 -2
  346. package/dist/extension-Dh1ddrlA.mjs.map +0 -1
  347. package/dist/geo-area-codec-Bti2PA2i.mjs +0 -2
  348. package/dist/id-domain-Cg65TLZ-.mjs +0 -2
  349. package/dist/identifier-conversion-BTDxDwDB.mjs +0 -2
  350. package/dist/identifier-conversion-BTDxDwDB.mjs.map +0 -1
  351. package/dist/introspect-rGqr93B3.mjs +0 -2
  352. package/dist/json-CsAdz9pg.mjs +0 -2
  353. package/dist/judge-words-k5GCc4cV.mjs +0 -2
  354. package/dist/judge-words-k5GCc4cV.mjs.map +0 -1
  355. package/dist/keys-DZdKAd4n.mjs +0 -2
  356. package/dist/libsql-BZAXy5PY.mjs +0 -3
  357. package/dist/libsql-BZAXy5PY.mjs.map +0 -1
  358. package/dist/light-D2wNSbzY.mjs +0 -2
  359. package/dist/memory-DgBGBQdJ.mjs +0 -2
  360. package/dist/memory-DgBGBQdJ.mjs.map +0 -1
  361. package/dist/methods-part-BaNx3o7b.mjs +0 -2
  362. package/dist/model-Dtd37Sky.mjs +0 -2
  363. package/dist/model-Dtd37Sky.mjs.map +0 -1
  364. package/dist/mysql-BjIAoFH6.mjs +0 -9
  365. package/dist/mysql-BjIAoFH6.mjs.map +0 -1
  366. package/dist/mysql-adapter-BFWYPoM0.mjs +0 -2
  367. package/dist/native-types-1ewJXVks.mjs +0 -2
  368. package/dist/native-types-1ewJXVks.mjs.map +0 -1
  369. package/dist/pending-operation-D4gUKMxD.mjs +0 -2
  370. package/dist/postgres-CaMB2Y4p.mjs +0 -35
  371. package/dist/postgres-CaMB2Y4p.mjs.map +0 -1
  372. package/dist/postgres-adapter-psTVfuw7.mjs +0 -2
  373. package/dist/postgres-adapter-psTVfuw7.mjs.map +0 -1
  374. package/dist/provider-limits-SdI1SaJS.mjs +0 -2
  375. package/dist/query-BTb6iakn.mjs +0 -2
  376. package/dist/query-BTb6iakn.mjs.map +0 -1
  377. package/dist/query-backend-TisPjCPF.mjs +0 -2
  378. package/dist/raw-DqEb71JZ.mjs +0 -2
  379. package/dist/rule-words-DMbQuvD2.mjs +0 -2
  380. package/dist/scalar-Dm9brvAU.mjs +0 -4
  381. package/dist/scalar-Dm9brvAU.mjs.map +0 -1
  382. package/dist/schema-DDkAUfOb.mjs +0 -2
  383. package/dist/schema-DqR_Kcje.mjs +0 -2
  384. package/dist/serializer-Br9JgpQI.mjs +0 -33
  385. package/dist/serializer-Br9JgpQI.mjs.map +0 -1
  386. package/dist/snowflake-B8Ei88bg.mjs +0 -2
  387. package/dist/sql-M5WsPhqr.mjs +0 -2
  388. package/dist/sqlite-adapter-Cb-SJw2f.mjs +0 -2
  389. package/dist/sqlite-adapter-Cb-SJw2f.mjs.map +0 -1
  390. package/dist/surrealql-f2Rgu47F.mjs +0 -2
  391. package/dist/surrealql-f2Rgu47F.mjs.map +0 -1
  392. package/dist/time-step-DJaIhpAz.mjs +0 -2
  393. package/dist/time-step-DJaIhpAz.mjs.map +0 -1
  394. package/dist/validation-BHjx13zG.mjs +0 -2
  395. package/dist/validator-DMzH5Tz0.mjs +0 -2
  396. package/dist/validator-DMzH5Tz0.mjs.map +0 -1
  397. package/dist/version-Bu2LCuaj.mjs +0 -2
  398. package/dist/view-CHgjF2BO.mjs +0 -2
  399. package/dist/write-sinks-Bei5vFHP.mjs +0 -2
  400. /package/dist/{contract-CxJn0_cV.d.mts → contract-CAoFgKSO.d.mts} +0 -0
  401. /package/dist/{named-statements-NF7Iycjk.d.mts → named-statements-CT4Gbd6t.d.mts} +0 -0
  402. /package/dist/{sql-C4_sFNDm.d.mts → sql-C-SBCGCx.d.mts} +0 -0
package/dist/cache.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { I as Extension, L as Facts, O as AnyTarget, U as PlacedArgument, tt as CachedClientOf, zr as MutationOperations } from "./database-adapter-01J6mYq5.mjs";
2
- import { a as WaitUntilFn, i as Revalidate, n as CacheEntry, o as CacheInvalidationOptions, r as CacheSetOptions, s as WithCacheOptions, t as CacheDriver } from "./driver-CTjq1yxj.mjs";
1
+ import { I as Extension, L as Facts, O as AnyTarget, U as PlacedArgument, tt as CachedClientOf, zr as MutationOperations } from "./database-adapter-cW0nmWM6.mjs";
2
+ import { a as WaitUntilFn, i as Revalidate, n as CacheEntry, o as CacheInvalidationOptions, r as CacheSetOptions, s as WithCacheOptions, t as CacheDriver } from "./driver-KgGMnfz8.mjs";
3
3
 
4
4
  //#region src/cache/extension.d.ts
5
5
  interface CacheExtensionConfig {
package/dist/cache.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{O as e,j as t,k as n}from"./error-mapping-B9rSvgG9.mjs";import{t as r}from"./base-17NSFtrA.mjs";import{t as i}from"./extension-Dh1ddrlA.mjs";import{t as a}from"./methods-part-BaNx3o7b.mjs";import{a as o,c as s,l as c}from"./on-ZkOVmE4-.mjs";import{n as l,r as u,t as d}from"./args-7WgBFd_f.mjs";import{n as f,t as p}from"./call-0bd_B9Vp.mjs";import{t as m}from"./settled-DYYPcaBX.mjs";import{n as h,r as g,t as _}from"./key-BDH6oTyC.mjs";import{h as v,i as y}from"./unit-words-BXpLpyr2.mjs";import{_ as b,a as x,c as S,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as P,t as F,u as I,v as L,y as R}from"./driver-kiIQS_Fd.mjs";function z(t,n,r,i){try{return i()}catch(i){throw new e(r,{cause:i instanceof Error?i:void 0,meta:{method:t,operation:n}})}}function B(e,t){return{run:()=>e.run(),snapshot:()=>z(`snapshot`,t,`The operation result cannot be represented by the cache result codec.`,()=>e.snapshot()),materialize:n=>z(`materialize`,t,`The cached result snapshot is malformed.`,()=>e.materialize(n))}}const V=e=>({"~standard":{version:1,vendor:`viborm.cache`,validate:t=>({value:e(t)})}});function H(t){throw new e(t)}function U(n){let{driver:v,version:y,waitUntil:T,swr:E}=n;v instanceof A||H(`Cache extension configuration requires a CacheDriver instance.`),y!==void 0&&!(typeof y==`string`||Number.isFinite(y))&&H(`Cache extension configuration "version" must be a string or finite number.`),T!==void 0&&typeof T!=`function`&&H(`Cache extension configuration "waitUntil" must be a function.`);let D=({dialect:e,namespace:t})=>b({version:y,dialect:e,namespace:t}),O=async(t,n,i)=>{try{let e=D(h(t));await v[x](``,n,t,t=>S(e,t))}catch(t){throw i===void 0&&t instanceof r?t:new e(i?`Cache invalidation failed after mutation '${i.operation}' on model '${i.model}'.`:`Cache invalidation failed.`,{cause:t instanceof Error?t:void 0,meta:{method:`invalidate`,...i}})}};return i(`viborm.cache`,l({cache:d(V(w)).on(c),xy:u(V(e=>{let t=M(e);return t.swr!==!1&&E===void 0&&H(`A view's "swr" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).`),t}))}),f(e=>{let n=e.values;if(n.xy!==void 0)throw new t(e.operation,[...C]);let r=n.cache;k(r)&&m(e,({certainty:t})=>O(e,r,{model:e.model,operation:e.operation,commitCertainty:t}))},s(c)),p(e=>{let t=e.values.xy;if(t===void 0)return;let n=e.model;return r=>{if(r.mode!==`direct`)return r();let i=_(r);if(i===void 0)return r();let a=h(r);return v[j]({id:i,codec:B(g(r),e.operation),read:t,namespace:D(a),waitUntil:T,model:n,operation:e.operation,origin:r,database:a,revalidate:E})}},s(o),{inner:!0}),a(e=>({$withCache:t=>e.$bind({xy:t}),$invalidate:(...t)=>m(e,()=>O(e,{invalidate:t}))})))}const W=e=>{let{request:t,entry:n,now:r}=e,i=t.read.swr;return i===!1||r-n.createdAt>=i||r>=n.expiresAt?!1:(R(G(e),t.waitUntil),y(t.origin,O(`hit`,`stale`)),!0)};async function G({request:e,key:t,backend:n,store:r}){try{if(!await L(n,t,!0))return}catch{return}let{codec:i}=e;await v(e.origin,{kind:`cache`,operation:`revalidate`,note:I(e,e.database)},async a=>{let o=!1,s,c;try{await i.run(),await r(i.snapshot()),c=O(`revalidate`,`success`,void 0,e)}catch(t){o=!0,s=t,c=O(`revalidate`,`error`,t,e)}try{await L(n,t,!1)}catch(e){s=o?AggregateError([s,e],`Cache revalidation work and cleanup both failed.`,{cause:s}):e,o=!0}if(y(a,c),o)throw s})}function K(e){let t=e.startsWith(`${E}:`)?e:e?`${E}:${e}`:E;if(t===T||t.startsWith(`${T}:`))throw new n(`The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.`);return t}async function q(e,t,n){return e[D](K(t),n)}async function J(e,t,n,r,i){return e[P](K(t),n,r,i)}async function Y(e,t,n){return e[N](`delete`,K(t),n)}async function X(e,t,n){return e[N](`clear`,K(t??``),n)}async function Z(e,t,n,r){return e[x](`${t}:`,n,r,K)}async function Q(e,t){return L(e[F](),K(t),!0)}async function $(e,t){await L(e[F](),K(t),!1)}export{A as CacheDriver,U as cache,X as clearEntries,$ as clearRevalidating,Y as deleteEntry,q as getEntry,Z as invalidateEntries,Q as markRevalidating,J as setEntry,W as staleWhileRevalidate};
1
+ import{O as e,j as t,k as n}from"./error-mapping-B9rSvgG9.mjs";import{t as r}from"./base-17NSFtrA.mjs";import{t as i}from"./extension-Bf4vO5mp.mjs";import{t as a}from"./methods-part-Dsi0DBNU.mjs";import{a as o,c as s,l as c}from"./on-nOenqmgP.mjs";import{n as l,r as u,t as d}from"./args-DsGRkPRw.mjs";import{n as f,t as p}from"./call-D2E7dPCd.mjs";import{t as m}from"./settled-Clanz_kI.mjs";import{n as h,r as g,t as _}from"./key-v4k7Cqb6.mjs";import{h as v,i as y}from"./unit-words-DjVhRXAQ.mjs";import{_ as b,a as x,c as S,d as C,f as w,g as T,h as E,i as D,l as O,m as k,n as A,o as j,p as M,r as N,s as P,t as F,u as I,v as L,y as R}from"./driver-BOsmU3kz.mjs";function z(t,n,r,i){try{return i()}catch(i){throw new e(r,{cause:i instanceof Error?i:void 0,meta:{method:t,operation:n}})}}function B(e,t){return{run:()=>e.run(),snapshot:()=>z(`snapshot`,t,`The operation result cannot be represented by the cache result codec.`,()=>e.snapshot()),materialize:n=>z(`materialize`,t,`The cached result snapshot is malformed.`,()=>e.materialize(n))}}const V=e=>({"~standard":{version:1,vendor:`viborm.cache`,validate:t=>({value:e(t)})}});function H(t){throw new e(t)}function U(n){let{driver:v,version:y,waitUntil:T,swr:E}=n;v instanceof A||H(`Cache extension configuration requires a CacheDriver instance.`),y!==void 0&&!(typeof y==`string`||Number.isFinite(y))&&H(`Cache extension configuration "version" must be a string or finite number.`),T!==void 0&&typeof T!=`function`&&H(`Cache extension configuration "waitUntil" must be a function.`);let D=({dialect:e,namespace:t})=>b({version:y,dialect:e,namespace:t}),O=async(t,n,i)=>{try{let e=D(h(t));await v[x](``,n,t,t=>S(e,t))}catch(t){throw i===void 0&&t instanceof r?t:new e(i?`Cache invalidation failed after mutation '${i.operation}' on model '${i.model}'.`:`Cache invalidation failed.`,{cause:t instanceof Error?t:void 0,meta:{method:`invalidate`,...i}})}};return i(`viborm.cache`,l({cache:d(V(w)).on(c),jp:u(V(e=>{let t=M(e);return t.swr!==!1&&E===void 0&&H(`A view's "swr" option needs the cache configured with it: cache({ driver, swr: staleWhileRevalidate }).`),t}))}),f(e=>{let n=e.values;if(n.jp!==void 0)throw new t(e.operation,[...C]);let r=n.cache;k(r)&&m(e,({certainty:t})=>O(e,r,{model:e.model,operation:e.operation,commitCertainty:t}))},s(c)),p(e=>{let t=e.values.jp;if(t===void 0)return;let n=e.model;return r=>{if(r.mode!==`direct`)return r();let i=_(r);if(i===void 0)return r();let a=h(r);return v[j]({id:i,codec:B(g(r),e.operation),read:t,namespace:D(a),waitUntil:T,model:n,operation:e.operation,origin:r,database:a,revalidate:E})}},s(o),{inner:!0}),a(e=>({$withCache:t=>e.$bind({jp:t}),$invalidate:(...t)=>m(e,()=>O(e,{invalidate:t}))})))}const W=e=>{let{request:t,entry:n,now:r}=e,i=t.read.swr;return i===!1||r-n.createdAt>=i||r>=n.expiresAt?!1:(R(G(e),t.waitUntil),y(t.origin,O(`hit`,`stale`)),!0)};async function G({request:e,key:t,backend:n,store:r}){try{if(!await L(n,t,!0))return}catch{return}let{codec:i}=e;await v(e.origin,{kind:`cache`,operation:`revalidate`,note:I(e,e.database)},async a=>{let o=!1,s,c;try{await i.run(),await r(i.snapshot()),c=O(`revalidate`,`success`,void 0,e)}catch(t){o=!0,s=t,c=O(`revalidate`,`error`,t,e)}try{await L(n,t,!1)}catch(e){s=o?AggregateError([s,e],`Cache revalidation work and cleanup both failed.`,{cause:s}):e,o=!0}if(y(a,c),o)throw s})}function K(e){let t=e.startsWith(`${E}:`)?e:e?`${E}:${e}`:E;if(t===T||t.startsWith(`${T}:`))throw new n(`The official cache namespace is the cache extension's own: the public storage functions cannot address a key under it.`);return t}async function q(e,t,n){return e[D](K(t),n)}async function J(e,t,n,r,i){return e[P](K(t),n,r,i)}async function Y(e,t,n){return e[N](`delete`,K(t),n)}async function X(e,t,n){return e[N](`clear`,K(t??``),n)}async function Z(e,t,n,r){return e[x](`${t}:`,n,r,K)}async function Q(e,t){return L(e[F](),K(t),!0)}async function $(e,t){await L(e[F](),K(t),!1)}export{A as CacheDriver,U as cache,X as clearEntries,$ as clearRevalidating,Y as deleteEntry,q as getEntry,Z as invalidateEntries,Q as markRevalidating,J as setEntry,W as staleWhileRevalidate};
2
2
  //# sourceMappingURL=cache.mjs.map
@@ -0,0 +1,2 @@
1
+ import{b as e,t}from"./base-17NSFtrA.mjs";import{p as n}from"./validation-ATmgN5RE.mjs";import{i as r,l as i,n as a}from"./coordination-BxMskOgi.mjs";import{i as o,o as s}from"./value-guards-CBVIJXlI.mjs";import{r as c}from"./extension-Bf4vO5mp.mjs";import{i as l}from"./schema-BzkBJTF-.mjs";import{s as u,t as d,u as f}from"./on-nOenqmgP.mjs";const p=new Set([`select`,`include`,`omit`,`_count`,`_avg`,`_sum`,`_min`,`_max`,`by`]);function m(e){let t=e.filter(e=>!e.on),n=new Map;return{s0:e,global:t,dv(r,i){if(r===void 0)return t.length>0?t:void 0;let a=l(n,`${r}.${i}`,()=>e.filter(({on:e})=>!e||e.models.has(r)&&e.operations.has(i)));return a.length>0?a:void 0}}}const h=Object.freeze({});function g({handler:r,keep:a,g1:c,watch:l},u){let d=({extension:f,args:m},g,_,v,y,b,x)=>{let S=(t,r)=>new n(`Extension "${f}" first moment for ${g===void 0?_:`${g}.${_}`} ${t}.`,{cause:e(r),meta:{model:g,operation:_}}),C;try{C=r({kind:g===void 0?`raw`:`model`,schema:u,model:g,operation:_,get args(){return v.args},values:(m&&b?.owned(x,m))??h,set(e){if(g===void 0||!s(e))throw S(`set no model call's arguments`);for(let t of Object.keys(e)){let e=p.has(t);if(e||b?.names.has(t))throw S(e?`set "${t}", which decides the result's shape`:`set argument "${t}"`)}v.args=Object.freeze({...v.args,...e})},...g===void 0?c?.(y,f):l?.i5(y,f),[i]:g===void 0?void 0:y})}catch(e){throw e instanceof t?e:S(`threw`,e)}if(s(C)&&o(C.then))throw S(`returned a promise`);if(o(C)){if(a===void 0)throw S(`returned a function: write around()`);a(y,d,C)}};return d}function _(e,t,n,r,i,a,o){let c={args:s(t)?Object.freeze({...t}):t};for(let t of n)t.handler(t,i,e,c,r,a,o);return c.args}function v(e,t,n){(e.seconds??=new Map).set(t,n)}const y=(e,t)=>({[f]({settled:n,collect:r,tell:i}){return n===void 0?!1:((e.g1??=[]).push({extension:t,listener:n,collect:r,tell:i}),!0)}}),b=e=>(t,n)=>{let r=t.call?.seconds?.get(e);return r===void 0?n():r(n)};function x({on:e,inner:t},n,{schema:r,owner:{name:i,args:a}}){let o=(e,t)=>new Set(e.map(e=>t(e)?e:c(`Extension "${i}" target names unknown model or operation "${e}".`,i)));return{extension:i,handler:n,args:a,inner:t,on:e&&{models:o(e.models??Object.keys(r),e=>Object.hasOwn(r,e)),operations:o(e.operations??[...d],e=>d.has(e))}}}function S(e,t,n){let{next:r}=e;r.call={...m([...r.call?.s0??[],x(t,n,e)]),apply:_}}function C(e){return{join(t){e.watch&&t.kl(e.watch),S(t,e,g(e,t.schema))}}}function w(e){return{join(t){let{next:n}=t;e.watch&&t.kl(e.watch);let i=g(e,t.schema);S(t,e,i);let o=x(e,b(i),t);n.around=m([...n.around?.s0??[],o].sort((e,t)=>Number(!!e.inner)-Number(!!t.inner))),r(n,a)}}}function T(e,t){if(!o(e))throw TypeError(`call() takes a function of the call`);let n=u(t);return C({handler:e,on:n,watch:n?.watch})}function E(e,t,n){if(!o(e))throw TypeError(`around() takes a function of the call`);let r=u(t);return w({handler:e,on:r,keep:v,g1:y,watch:r?.watch,inner:n?.inner})}export{T as n,E as t};
2
+ //# sourceMappingURL=call-D2E7dPCd.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"call-0bd_B9Vp.mjs","names":["placed","call"],"sources":["../src/extensions/request.ts","../src/extensions/targeted.ts","../src/extensions/call.ts"],"sourcesContent":["/**\n * The keys of a call's arguments that decide its result's shape, and the\n * types of what a first moment reads and patches.\n */\nimport type { Operations } from \"@client/types\";\n\n/**\n * The keys of a call's arguments that decide its result's shape: the one\n * list of them. A first moment's `c.set` refuses each (`call.ts`), and the\n * types of what it reads and patches leave out those its operation has.\n */\nconst RESULT_SHAPE_KEYS = [\n \"select\",\n \"include\",\n \"omit\",\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n \"by\",\n] as const;\n\n/** What `c.set` tests a patch's keys against. */\nexport const SHAPE_KEYS: ReadonlySet<string> = /* @__PURE__ */ new Set(\n RESULT_SHAPE_KEYS\n);\n\ntype ResultShapeKey = (typeof RESULT_SHAPE_KEYS)[number];\n\n/**\n * Which of those keys each operation has: a future projection spelling\n * extends the list and this table, and the patch types follow.\n */\ninterface ResultShapeKeysByOperation\n extends Record<Operations, ResultShapeKey> {\n findFirst: \"select\" | \"include\" | \"omit\";\n findMany: \"select\" | \"include\" | \"omit\";\n findUnique: \"select\" | \"include\" | \"omit\";\n findUniqueOrThrow: \"select\" | \"include\" | \"omit\";\n findFirstOrThrow: \"select\" | \"include\" | \"omit\";\n create: \"select\" | \"include\" | \"omit\";\n update: \"select\" | \"include\" | \"omit\";\n delete: \"select\" | \"include\" | \"omit\";\n upsert: \"select\" | \"include\" | \"omit\";\n createMany: \"select\" | \"omit\";\n updateMany: \"select\" | \"omit\";\n deleteMany: \"select\" | \"omit\";\n count: \"select\";\n aggregate: \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n groupBy: \"by\" | \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n exist: never;\n}\n\ntype ResultShapeKeyFor<Operation extends Operations> =\n ResultShapeKeysByOperation[Operation];\n\n/** The operation input visible to an ordinary request transform. */\nexport type RequestTransformInput<\n Operation extends Operations,\n Input extends object,\n> = Omit<Input, ResultShapeKeyFor<Operation>>;\n\n/**\n * A shallow patch over the non-projection input. The optional `never`\n * properties make protected keys fail structurally, including held values.\n */\nexport type RequestTransformPatch<\n Operation extends Operations,\n Input extends object,\n> = Partial<RequestTransformInput<Operation, Input>> & {\n readonly [Key in ResultShapeKeyFor<Operation>]?: never;\n};\n","/**\n * The handlers of `call` and `around`, in chain order, each with the calls\n * its target selects, and the handlers one call runs: found the first time\n * a (model, operation) asks, and kept for the chain.\n */\nimport { memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { FirstMoment, runFirstMoments } from \"./call\";\nimport type { CallHandler } from \"./chain-state\";\n\n/** One handler of a chain, and the calls it concerns. */\nexport interface TargetedHandler<\n Handler extends CallableFunction = CallableFunction,\n> extends CallHandler<Handler> {\n /** The models and operations a target selects; every call without one. */\n readonly on?: {\n readonly models: ReadonlySet<string>;\n readonly operations: ReadonlySet<string>;\n };\n /** Placed nearest the core, after every other handler (`around`'s `inner`). */\n readonly inner?: boolean;\n}\n\n/** A chain's handlers of one moment, and the handlers one call runs. */\nexport interface TargetedHandlers<\n Handler extends CallableFunction = CallableFunction,\n> {\n readonly placed: readonly TargetedHandler<Handler>[];\n /** The handlers without a target: the only ones a raw statement runs. */\n readonly global: readonly CallHandler<Handler>[];\n readonly handlers: (\n model: string | undefined,\n operation: string\n ) => readonly CallHandler<Handler>[] | undefined;\n}\n\n/** The first moments of `call` and `around`, and what runs them for one call. */\nexport interface CallHandlers extends TargetedHandlers<FirstMoment> {\n readonly apply: typeof runFirstMoments;\n}\n\n/** The lookup of `placed`, in its order. */\nexport function targetedHandlers<Handler extends CallableFunction>(\n placed: readonly TargetedHandler<Handler>[]\n): TargetedHandlers<Handler> {\n const global = placed.filter((entry) => !entry.on);\n const found = new Map<string, readonly TargetedHandler<Handler>[]>();\n return {\n placed,\n global,\n handlers(model, operation) {\n if (model === undefined) return global.length > 0 ? global : undefined;\n const key = `${model}.${operation}`;\n const list = memo(found, key, () =>\n placed.filter(\n ({ on }) =>\n !on || (on.models.has(model) && on.operations.has(operation))\n )\n );\n return list.length > 0 ? list : undefined;\n },\n };\n}\n","/**\n * `call(fn, target?)` and `around(fn, target?, options?)`: a function on each\n * logical call, in two moments. Every first moment runs in chain order,\n * synchronously, before the call is validated: it reads the arguments and\n * this extension's own (`c.args`, `c.values`), patches the arguments\n * (`c.set`), or refuses the call by throwing. A first moment of\n * `around` may return a second moment, which runs around the prepared\n * call once every first moment ran and the call was validated: the first\n * extension applied outermost. `run()` executes the call once; its failure\n * is the call's, whatever the second moment does after it.\n *\n * Without a target, a part concerns every model call and every raw\n * statement; `target(...)` names model operations only, so a targeted part\n * never sees a raw statement.\n */\n\nimport type { Schema } from \"@client/types\";\nimport { QueryError, VibORMError } from \"@errors\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { Application, ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\nimport type { CallHandler, ResolvedArgs } from \"./chain-state\";\nimport type {\n AnyTarget,\n AroundFacts,\n AroundHandler,\n EmptyFacts,\n MomentOne,\n Part,\n Selection,\n} from \"./contract\";\nimport { coordinate, QUERIES } from \"./coordination\";\nimport { MODEL_OPERATIONS, type SelectionValue, selectionOf } from \"./on\";\nimport { CALL, type CallOrigin } from \"./origin\";\nimport type { AroundRunner } from \"./query\";\nimport { SHAPE_KEYS } from \"./request\";\nimport { type TargetedHandler, targetedHandlers } from \"./targeted\";\nimport { REGISTER, type Registering, type WatchPart } from \"./watch-part\";\n\n/**\n * What a first moment is handed, beside what `contract.ts` types: where the\n * part brings what tells `watch` and `settled`, what they register through.\n */\ninterface FirstContext extends Partial<Registering> {\n readonly kind: \"model\" | \"raw\";\n readonly schema: Schema;\n readonly model: string | undefined;\n readonly operation: string;\n readonly args: Readonly<Record<string, unknown>>;\n readonly values: AdmittedArgs;\n set(patch: unknown): void;\n /** A model call itself, for the words that read it (`database`, `key`). */\n readonly [CALL]: object | undefined;\n}\n\n/**\n * One `call` or `around` part, as its builder wrote it. What only `around`\n * or a watching set needs is handed in by the builder that has it, so a\n * program building `call` alone carries none of it.\n */\ninterface CallSpec {\n readonly handler: (context: FirstContext) => unknown;\n readonly on: SelectionValue | undefined;\n /** `around` only: keeps the second moment a first returned, for the call. */\n readonly keep?: (\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n ) => void;\n /**\n * `around` only: what a raw statement's first moment registers `settled`\n * through, kept on the call, which the host tells of the outcome.\n */\n readonly told?: (call: CallOrigin, extension: string) => Registering;\n /** What registers `watch` and `settled`, where the part brings what tells them. */\n readonly watch?: WatchPart | undefined;\n /** `around` only: placed nearest the core. */\n readonly inner?: boolean;\n}\n\n/**\n * One first moment, as the request lookup holds it: run for one call by\n * `runFirstMoments`, it keeps the second moment its handler returned.\n */\nexport type FirstMoment = (\n owner: Pick<CallHandler, \"extension\" | \"args\">,\n model: string | undefined,\n operation: string,\n state: { args: Readonly<Record<string, unknown>> },\n call: CallOrigin,\n declared: ResolvedArgs | undefined,\n admitted: AdmittedArgs | undefined\n) => void;\n\ntype SecondMoment = (run: unknown) => unknown;\n\nconst NO_VALUES: AdmittedArgs = /* @__PURE__ */ Object.freeze({});\n\n/**\n * One part's first moment against one schema. What the handler throws\n * refuses the call (an error of viborm's own as it is, any other as the\n * cause of a `QueryError`); a promise is refused, and so is a function\n * returned by `call`; a second moment returned by `around` is kept for the\n * call.\n */\nfunction firstOf(\n { handler, keep, told, watch }: CallSpec,\n schema: Schema\n): FirstMoment {\n const first: FirstMoment = (\n { extension, args: own },\n model,\n operation,\n state,\n call,\n declared,\n admitted\n ) => {\n const refusal = (problem: string, cause?: unknown) =>\n new QueryError(\n `Extension \"${extension}\" first moment for ${model === undefined ? operation : `${model}.${operation}`} ${problem}.`,\n { cause: errorCause(cause), meta: { model, operation } }\n );\n let returned: unknown;\n try {\n returned = handler({\n kind: model === undefined ? \"raw\" : \"model\",\n schema,\n model,\n operation,\n get args() {\n return state.args;\n },\n // An extension that declares arguments brings the chain's arguments.\n values: (own && declared?.owned(admitted, own)) ?? NO_VALUES,\n set(patch: unknown) {\n if (model === undefined || !isRecord(patch))\n throw refusal(\"set no model call's arguments\");\n for (const key of Object.keys(patch)) {\n const shape = SHAPE_KEYS.has(key);\n if (shape || declared?.names.has(key))\n throw refusal(\n shape\n ? `set \"${key}\", which decides the result's shape`\n : `set argument \"${key}\"`\n );\n }\n state.args = Object.freeze({ ...state.args, ...patch });\n },\n // Only a part on a set of writes watches a model call, and a raw\n // statement never reaches such a part; an `around` hears a raw\n // statement's outcome.\n ...(model === undefined\n ? told?.(call, extension)\n : watch?.registering(call, extension)),\n [CALL]: model === undefined ? undefined : call,\n });\n } catch (cause) {\n if (cause instanceof VibORMError) throw cause;\n throw refusal(\"threw\", cause);\n }\n // A first moment runs synchronously.\n if (isRecord(returned) && isFunction(returned.then))\n throw refusal(\"returned a promise\");\n if (!isFunction<SecondMoment>(returned)) return;\n if (keep === undefined)\n throw refusal(\"returned a function: write around()\");\n keep(call, first, returned);\n };\n return first;\n}\n\n/**\n * Every first moment of one call, in chain order, over its arguments with\n * the arguments taken out: what `chain.request.apply` runs before a model\n * call is validated, and before a raw statement is sent (`raw.ts`, with no\n * model and its input for arguments). The arguments each sees are those the\n * moments before it left. `call` is the one object both moments of the call\n * are handed: what links an `around` part's second moment to its first.\n */\nexport function runFirstMoments(\n operation: string,\n input: Readonly<Record<string, unknown>>,\n handlers: readonly CallHandler<FirstMoment>[],\n call: CallOrigin,\n model?: string,\n declared?: ResolvedArgs,\n admitted?: AdmittedArgs\n): Record<string, unknown> {\n // An argument that is no object is validation's to refuse, as it is.\n const state = {\n args: isRecord(input) ? Object.freeze({ ...input }) : input,\n };\n for (const handler of handlers)\n handler.handler(handler, model, operation, state, call, declared, admitted);\n return state.args;\n}\n\n/** A call's `seconds`: the second moment each `around` part's first returned. */\nexport type Seconds = Map<FirstMoment, SecondMoment>;\n\n/** What `around` hands its first moments: the call's second moments kept. */\nfunction keepSecond(\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n): void {\n (call.seconds ??= new Map()).set(first, second);\n}\n\n/**\n * What a raw statement's first moment registers through: its `settled`\n * functions, kept on the call, which the host tells of an execute's\n * outcome. A raw statement shows no rows: a `watch` would never be told,\n * and is refused.\n */\nconst rawTold = (call: CallOrigin, extension: string): Registering => ({\n [REGISTER]({ settled, collect, tell }) {\n if (settled === undefined) return false;\n (call.told ??= []).push({ extension, listener: settled, collect, tell });\n return true;\n },\n});\n\n/** The second moment of one `around` part: the second its first returned for this call. */\nconst secondMoment =\n (first: FirstMoment): AroundRunner =>\n (prepared, run) => {\n const second = prepared.call?.seconds?.get(first);\n return second === undefined ? run() : second(run);\n };\n\n/**\n * One part's handler, placed on the calls of its target; on every call\n * without one. A name the schema or the operations do not hold is refused:\n * the types refuse it where `target` is written, and a caller without them\n * would otherwise get a part that never runs.\n */\nfunction placed<H extends CallableFunction>(\n { on, inner }: CallSpec,\n handler: H,\n { schema, owner: { name, args } }: Application\n): TargetedHandler<H> {\n const known = (names: readonly string[], holds: (name: string) => boolean) =>\n new Set(\n names.map((each) =>\n holds(each)\n ? each\n : extensionError(\n `Extension \"${name}\" target names unknown model or operation \"${each}\".`,\n name\n )\n )\n );\n return {\n extension: name,\n handler,\n args,\n inner,\n on: on && {\n models: known(on.models ?? Object.keys(schema), (model) =>\n Object.hasOwn(schema, model)\n ),\n operations: known(on.operations ?? [...MODEL_OPERATIONS], (operation) =>\n MODEL_OPERATIONS.has(operation)\n ),\n },\n };\n}\n\n/** One first moment appended to the chain's, in the order the parts join. */\nfunction appendFirst(\n application: Application,\n spec: CallSpec,\n first: FirstMoment\n): void {\n const { next } = application;\n next.call = {\n ...targetedHandlers([\n ...(next.call?.placed ?? []),\n placed(spec, first, application),\n ]),\n apply: runFirstMoments,\n };\n}\n\n/** What `call` returns: its first moment, made against the schema it joins. */\nfunction callPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n // What watches the call's writes comes with a set that names writes\n // (`target(writes)`): a call that only patches does not carry it.\n if (spec.watch) application.bring(spec.watch);\n appendFirst(application, spec, firstOf(spec, application.schema));\n },\n };\n}\n\n/**\n * What `around` returns: its first moment, and its second around the\n * prepared call, nearest the core with `inner` (after every other part,\n * whatever the chain's order: a later extension's lands before it).\n */\nfunction aroundPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n const { next } = application;\n if (spec.watch) application.bring(spec.watch);\n const first = firstOf(spec, application.schema);\n appendFirst(application, spec, first);\n const handler = placed(spec, secondMoment(first), application);\n const list = next.around?.placed ?? [];\n // A stable sort: the parts without `inner` first, each group in\n // chain order.\n next.around = targetedHandlers(\n [...list, handler].sort((a, b) => Number(!!a.inner) - Number(!!b.inner))\n );\n coordinate(next, QUERIES);\n },\n };\n}\n\n/**\n * A first moment alone: it reads, patches or refuses each call it selects,\n * before validation; without a target, every model call and raw statement.\n */\nexport function call<T extends AnyTarget, M = never, O = never>(\n handler: (c: MomentOne<T, M, O>) => void,\n selected?: Selection<T, M, O>\n): Part<T, EmptyFacts>;\nexport function call(\n handler: (context: never) => unknown,\n selected?: unknown\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"call() takes a function of the call\");\n const on = selectionOf(selected);\n return callPart({ handler, on, watch: on?.watch });\n}\n\n/**\n * Both moments: the first may return a second, `(run) => …`, which runs\n * around the prepared call. With `{ inner: true }` it sits nearest the core,\n * whatever the chain's order (a part that may answer for the core).\n */\nexport function around<T extends AnyTarget, M = never, O = never>(\n handler: AroundHandler<T, M, O>,\n selected?: Selection<T, M, O>,\n options?: { readonly inner?: true }\n): Part<T, AroundFacts<M, O>>;\nexport function around(\n handler: (context: never) => unknown,\n selected?: unknown,\n options?: { readonly inner?: true }\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"around() takes a function of the call\");\n const on = selectionOf(selected);\n return aroundPart({\n handler,\n on,\n keep: keepSecond,\n told: rawTold,\n watch: on?.watch,\n inner: options?.inner,\n });\n}\n"],"mappings":"wVAwBA,MAAa,EAAkD,IAAI,IAbzC,CACxB,SACA,UACA,OACA,SACA,OACA,OACA,OACA,OACA,KACD,CAKA,CCeD,SAAgB,EACd,EAC2B,CAC3B,IAAM,EAASA,EAAO,OAAQ,GAAU,CAAC,EAAM,GAAG,CAC5C,EAAQ,IAAI,IAClB,MAAO,CACL,OAAA,EACA,SACA,SAAS,EAAO,EAAW,CACzB,GAAI,IAAU,IAAA,GAAW,OAAO,EAAO,OAAS,EAAI,EAAS,IAAA,GAE7D,IAAM,EAAO,EAAK,EADN,GAAG,EAAM,GAAG,QAEtBA,EAAO,QACJ,CAAE,QACD,CAAC,GAAO,EAAG,OAAO,IAAI,EAAM,EAAI,EAAG,WAAW,IAAI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dPCd.mjs","names":["placed","call"],"sources":["../src/extensions/request.ts","../src/extensions/targeted.ts","../src/extensions/call.ts"],"sourcesContent":["/**\n * The keys of a call's arguments that decide its result's shape, and the\n * types of what a first moment reads and patches.\n */\nimport type { Operations } from \"@client/types\";\n\n/**\n * The keys of a call's arguments that decide its result's shape: the one\n * list of them. A first moment's `c.set` refuses each (`call.ts`), and the\n * types of what it reads and patches leave out those its operation has.\n */\nconst RESULT_SHAPE_KEYS = [\n \"select\",\n \"include\",\n \"omit\",\n \"_count\",\n \"_avg\",\n \"_sum\",\n \"_min\",\n \"_max\",\n \"by\",\n] as const;\n\n/** What `c.set` tests a patch's keys against. */\nexport const SHAPE_KEYS: ReadonlySet<string> = /* @__PURE__ */ new Set(\n RESULT_SHAPE_KEYS\n);\n\ntype ResultShapeKey = (typeof RESULT_SHAPE_KEYS)[number];\n\n/**\n * Which of those keys each operation has: a future projection spelling\n * extends the list and this table, and the patch types follow.\n */\ninterface ResultShapeKeysByOperation\n extends Record<Operations, ResultShapeKey> {\n findFirst: \"select\" | \"include\" | \"omit\";\n findMany: \"select\" | \"include\" | \"omit\";\n findUnique: \"select\" | \"include\" | \"omit\";\n findUniqueOrThrow: \"select\" | \"include\" | \"omit\";\n findFirstOrThrow: \"select\" | \"include\" | \"omit\";\n create: \"select\" | \"include\" | \"omit\";\n update: \"select\" | \"include\" | \"omit\";\n delete: \"select\" | \"include\" | \"omit\";\n upsert: \"select\" | \"include\" | \"omit\";\n createMany: \"select\" | \"omit\";\n updateMany: \"select\" | \"omit\";\n deleteMany: \"select\" | \"omit\";\n count: \"select\";\n aggregate: \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n groupBy: \"by\" | \"_count\" | \"_avg\" | \"_sum\" | \"_min\" | \"_max\";\n exist: never;\n}\n\ntype ResultShapeKeyFor<Operation extends Operations> =\n ResultShapeKeysByOperation[Operation];\n\n/** The operation input visible to an ordinary request transform. */\nexport type RequestTransformInput<\n Operation extends Operations,\n Input extends object,\n> = Omit<Input, ResultShapeKeyFor<Operation>>;\n\n/**\n * A shallow patch over the non-projection input. The optional `never`\n * properties make protected keys fail structurally, including held values.\n */\nexport type RequestTransformPatch<\n Operation extends Operations,\n Input extends object,\n> = Partial<RequestTransformInput<Operation, Input>> & {\n readonly [Key in ResultShapeKeyFor<Operation>]?: never;\n};\n","/**\n * The handlers of `call` and `around`, in chain order, each with the calls\n * its target selects, and the handlers one call runs: found the first time\n * a (model, operation) asks, and kept for the chain.\n */\nimport { memo } from \"@query-engine/raptor3/shared/schema\";\nimport type { FirstMoment, runFirstMoments } from \"./call\";\nimport type { CallHandler } from \"./chain-state\";\n\n/** One handler of a chain, and the calls it concerns. */\nexport interface TargetedHandler<\n Handler extends CallableFunction = CallableFunction,\n> extends CallHandler<Handler> {\n /** The models and operations a target selects; every call without one. */\n readonly on?: {\n readonly models: ReadonlySet<string>;\n readonly operations: ReadonlySet<string>;\n };\n /** Placed nearest the core, after every other handler (`around`'s `inner`). */\n readonly inner?: boolean;\n}\n\n/** A chain's handlers of one moment, and the handlers one call runs. */\nexport interface TargetedHandlers<\n Handler extends CallableFunction = CallableFunction,\n> {\n readonly placed: readonly TargetedHandler<Handler>[];\n /** The handlers without a target: the only ones a raw statement runs. */\n readonly global: readonly CallHandler<Handler>[];\n readonly handlers: (\n model: string | undefined,\n operation: string\n ) => readonly CallHandler<Handler>[] | undefined;\n}\n\n/** The first moments of `call` and `around`, and what runs them for one call. */\nexport interface CallHandlers extends TargetedHandlers<FirstMoment> {\n readonly apply: typeof runFirstMoments;\n}\n\n/** The lookup of `placed`, in its order. */\nexport function targetedHandlers<Handler extends CallableFunction>(\n placed: readonly TargetedHandler<Handler>[]\n): TargetedHandlers<Handler> {\n const global = placed.filter((entry) => !entry.on);\n const found = new Map<string, readonly TargetedHandler<Handler>[]>();\n return {\n placed,\n global,\n handlers(model, operation) {\n if (model === undefined) return global.length > 0 ? global : undefined;\n const key = `${model}.${operation}`;\n const list = memo(found, key, () =>\n placed.filter(\n ({ on }) =>\n !on || (on.models.has(model) && on.operations.has(operation))\n )\n );\n return list.length > 0 ? list : undefined;\n },\n };\n}\n","/**\n * `call(fn, target?)` and `around(fn, target?, options?)`: a function on each\n * logical call, in two moments. Every first moment runs in chain order,\n * synchronously, before the call is validated: it reads the arguments and\n * this extension's own (`c.args`, `c.values`), patches the arguments\n * (`c.set`), or refuses the call by throwing. A first moment of\n * `around` may return a second moment, which runs around the prepared\n * call once every first moment ran and the call was validated: the first\n * extension applied outermost. `run()` executes the call once; its failure\n * is the call's, whatever the second moment does after it.\n *\n * Without a target, a part concerns every model call and every raw\n * statement; `target(...)` names model operations only, so a targeted part\n * never sees a raw statement.\n */\n\nimport type { Schema } from \"@client/types\";\nimport { QueryError, VibORMError } from \"@errors\";\nimport { isFunction, isRecord } from \"@validation/value-guards\";\nimport { errorCause } from \"../errors/diagnostic-safety\";\nimport type { AdmittedArgs } from \"./arguments\";\nimport type { Application, ExtensionPart } from \"./chain\";\nimport { extensionError } from \"./chain\";\nimport type { CallHandler, ResolvedArgs } from \"./chain-state\";\nimport type {\n AnyTarget,\n AroundFacts,\n AroundHandler,\n EmptyFacts,\n MomentOne,\n Part,\n Selection,\n} from \"./contract\";\nimport { coordinate, QUERIES } from \"./coordination\";\nimport { MODEL_OPERATIONS, type SelectionValue, selectionOf } from \"./on\";\nimport { CALL, type CallOrigin } from \"./origin\";\nimport type { AroundRunner } from \"./query\";\nimport { SHAPE_KEYS } from \"./request\";\nimport { type TargetedHandler, targetedHandlers } from \"./targeted\";\nimport { REGISTER, type Registering, type WatchPart } from \"./watch-part\";\n\n/**\n * What a first moment is handed, beside what `contract.ts` types: where the\n * part brings what tells `watch` and `settled`, what they register through.\n */\ninterface FirstContext extends Partial<Registering> {\n readonly kind: \"model\" | \"raw\";\n readonly schema: Schema;\n readonly model: string | undefined;\n readonly operation: string;\n readonly args: Readonly<Record<string, unknown>>;\n readonly values: AdmittedArgs;\n set(patch: unknown): void;\n /** A model call itself, for the words that read it (`database`, `key`). */\n readonly [CALL]: object | undefined;\n}\n\n/**\n * One `call` or `around` part, as its builder wrote it. What only `around`\n * or a watching set needs is handed in by the builder that has it, so a\n * program building `call` alone carries none of it.\n */\ninterface CallSpec {\n readonly handler: (context: FirstContext) => unknown;\n readonly on: SelectionValue | undefined;\n /** `around` only: keeps the second moment a first returned, for the call. */\n readonly keep?: (\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n ) => void;\n /**\n * `around` only: what a raw statement's first moment registers `settled`\n * through, kept on the call, which the host tells of the outcome.\n */\n readonly told?: (call: CallOrigin, extension: string) => Registering;\n /** What registers `watch` and `settled`, where the part brings what tells them. */\n readonly watch?: WatchPart | undefined;\n /** `around` only: placed nearest the core. */\n readonly inner?: boolean;\n}\n\n/**\n * One first moment, as the request lookup holds it: run for one call by\n * `runFirstMoments`, it keeps the second moment its handler returned.\n */\nexport type FirstMoment = (\n owner: Pick<CallHandler, \"extension\" | \"args\">,\n model: string | undefined,\n operation: string,\n state: { args: Readonly<Record<string, unknown>> },\n call: CallOrigin,\n declared: ResolvedArgs | undefined,\n admitted: AdmittedArgs | undefined\n) => void;\n\ntype SecondMoment = (run: unknown) => unknown;\n\nconst NO_VALUES: AdmittedArgs = /* @__PURE__ */ Object.freeze({});\n\n/**\n * One part's first moment against one schema. What the handler throws\n * refuses the call (an error of viborm's own as it is, any other as the\n * cause of a `QueryError`); a promise is refused, and so is a function\n * returned by `call`; a second moment returned by `around` is kept for the\n * call.\n */\nfunction firstOf(\n { handler, keep, told, watch }: CallSpec,\n schema: Schema\n): FirstMoment {\n const first: FirstMoment = (\n { extension, args: own },\n model,\n operation,\n state,\n call,\n declared,\n admitted\n ) => {\n const refusal = (problem: string, cause?: unknown) =>\n new QueryError(\n `Extension \"${extension}\" first moment for ${model === undefined ? operation : `${model}.${operation}`} ${problem}.`,\n { cause: errorCause(cause), meta: { model, operation } }\n );\n let returned: unknown;\n try {\n returned = handler({\n kind: model === undefined ? \"raw\" : \"model\",\n schema,\n model,\n operation,\n get args() {\n return state.args;\n },\n // An extension that declares arguments brings the chain's arguments.\n values: (own && declared?.owned(admitted, own)) ?? NO_VALUES,\n set(patch: unknown) {\n if (model === undefined || !isRecord(patch))\n throw refusal(\"set no model call's arguments\");\n for (const key of Object.keys(patch)) {\n const shape = SHAPE_KEYS.has(key);\n if (shape || declared?.names.has(key))\n throw refusal(\n shape\n ? `set \"${key}\", which decides the result's shape`\n : `set argument \"${key}\"`\n );\n }\n state.args = Object.freeze({ ...state.args, ...patch });\n },\n // Only a part on a set of writes watches a model call, and a raw\n // statement never reaches such a part; an `around` hears a raw\n // statement's outcome.\n ...(model === undefined\n ? told?.(call, extension)\n : watch?.registering(call, extension)),\n [CALL]: model === undefined ? undefined : call,\n });\n } catch (cause) {\n if (cause instanceof VibORMError) throw cause;\n throw refusal(\"threw\", cause);\n }\n // A first moment runs synchronously.\n if (isRecord(returned) && isFunction(returned.then))\n throw refusal(\"returned a promise\");\n if (!isFunction<SecondMoment>(returned)) return;\n if (keep === undefined)\n throw refusal(\"returned a function: write around()\");\n keep(call, first, returned);\n };\n return first;\n}\n\n/**\n * Every first moment of one call, in chain order, over its arguments with\n * the arguments taken out: what `chain.request.apply` runs before a model\n * call is validated, and before a raw statement is sent (`raw.ts`, with no\n * model and its input for arguments). The arguments each sees are those the\n * moments before it left. `call` is the one object both moments of the call\n * are handed: what links an `around` part's second moment to its first.\n */\nexport function runFirstMoments(\n operation: string,\n input: Readonly<Record<string, unknown>>,\n handlers: readonly CallHandler<FirstMoment>[],\n call: CallOrigin,\n model?: string,\n declared?: ResolvedArgs,\n admitted?: AdmittedArgs\n): Record<string, unknown> {\n // An argument that is no object is validation's to refuse, as it is.\n const state = {\n args: isRecord(input) ? Object.freeze({ ...input }) : input,\n };\n for (const handler of handlers)\n handler.handler(handler, model, operation, state, call, declared, admitted);\n return state.args;\n}\n\n/** A call's `seconds`: the second moment each `around` part's first returned. */\nexport type Seconds = Map<FirstMoment, SecondMoment>;\n\n/** What `around` hands its first moments: the call's second moments kept. */\nfunction keepSecond(\n call: CallOrigin,\n first: FirstMoment,\n second: SecondMoment\n): void {\n (call.seconds ??= new Map()).set(first, second);\n}\n\n/**\n * What a raw statement's first moment registers through: its `settled`\n * functions, kept on the call, which the host tells of an execute's\n * outcome. A raw statement shows no rows: a `watch` would never be told,\n * and is refused.\n */\nconst rawTold = (call: CallOrigin, extension: string): Registering => ({\n [REGISTER]({ settled, collect, tell }) {\n if (settled === undefined) return false;\n (call.told ??= []).push({ extension, listener: settled, collect, tell });\n return true;\n },\n});\n\n/** The second moment of one `around` part: the second its first returned for this call. */\nconst secondMoment =\n (first: FirstMoment): AroundRunner =>\n (prepared, run) => {\n const second = prepared.call?.seconds?.get(first);\n return second === undefined ? run() : second(run);\n };\n\n/**\n * One part's handler, placed on the calls of its target; on every call\n * without one. A name the schema or the operations do not hold is refused:\n * the types refuse it where `target` is written, and a caller without them\n * would otherwise get a part that never runs.\n */\nfunction placed<H extends CallableFunction>(\n { on, inner }: CallSpec,\n handler: H,\n { schema, owner: { name, args } }: Application\n): TargetedHandler<H> {\n const known = (names: readonly string[], holds: (name: string) => boolean) =>\n new Set(\n names.map((each) =>\n holds(each)\n ? each\n : extensionError(\n `Extension \"${name}\" target names unknown model or operation \"${each}\".`,\n name\n )\n )\n );\n return {\n extension: name,\n handler,\n args,\n inner,\n on: on && {\n models: known(on.models ?? Object.keys(schema), (model) =>\n Object.hasOwn(schema, model)\n ),\n operations: known(on.operations ?? [...MODEL_OPERATIONS], (operation) =>\n MODEL_OPERATIONS.has(operation)\n ),\n },\n };\n}\n\n/** One first moment appended to the chain's, in the order the parts join. */\nfunction appendFirst(\n application: Application,\n spec: CallSpec,\n first: FirstMoment\n): void {\n const { next } = application;\n next.call = {\n ...targetedHandlers([\n ...(next.call?.placed ?? []),\n placed(spec, first, application),\n ]),\n apply: runFirstMoments,\n };\n}\n\n/** What `call` returns: its first moment, made against the schema it joins. */\nfunction callPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n // What watches the call's writes comes with a set that names writes\n // (`target(writes)`): a call that only patches does not carry it.\n if (spec.watch) application.bring(spec.watch);\n appendFirst(application, spec, firstOf(spec, application.schema));\n },\n };\n}\n\n/**\n * What `around` returns: its first moment, and its second around the\n * prepared call, nearest the core with `inner` (after every other part,\n * whatever the chain's order: a later extension's lands before it).\n */\nfunction aroundPart(spec: CallSpec): ExtensionPart {\n return {\n join(application) {\n const { next } = application;\n if (spec.watch) application.bring(spec.watch);\n const first = firstOf(spec, application.schema);\n appendFirst(application, spec, first);\n const handler = placed(spec, secondMoment(first), application);\n const list = next.around?.placed ?? [];\n // A stable sort: the parts without `inner` first, each group in\n // chain order.\n next.around = targetedHandlers(\n [...list, handler].sort((a, b) => Number(!!a.inner) - Number(!!b.inner))\n );\n coordinate(next, QUERIES);\n },\n };\n}\n\n/**\n * A first moment alone: it reads, patches or refuses each call it selects,\n * before validation; without a target, every model call and raw statement.\n */\nexport function call<T extends AnyTarget, M = never, O = never>(\n handler: (c: MomentOne<T, M, O>) => void,\n selected?: Selection<T, M, O>\n): Part<T, EmptyFacts>;\nexport function call(\n handler: (context: never) => unknown,\n selected?: unknown\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"call() takes a function of the call\");\n const on = selectionOf(selected);\n return callPart({ handler, on, watch: on?.watch });\n}\n\n/**\n * Both moments: the first may return a second, `(run) => …`, which runs\n * around the prepared call. With `{ inner: true }` it sits nearest the core,\n * whatever the chain's order (a part that may answer for the core).\n */\nexport function around<T extends AnyTarget, M = never, O = never>(\n handler: AroundHandler<T, M, O>,\n selected?: Selection<T, M, O>,\n options?: { readonly inner?: true }\n): Part<T, AroundFacts<M, O>>;\nexport function around(\n handler: (context: never) => unknown,\n selected?: unknown,\n options?: { readonly inner?: true }\n): unknown {\n // Each overload types the handler against its client's context, which is\n // a `FirstContext` at runtime.\n if (!isFunction<CallSpec[\"handler\"]>(handler))\n throw new TypeError(\"around() takes a function of the call\");\n const on = selectionOf(selected);\n return aroundPart({\n handler,\n on,\n keep: keepSecond,\n told: rawTold,\n watch: on?.watch,\n inner: options?.inner,\n });\n}\n"],"mappings":"wVAwBA,MAAa,EAAkD,IAAI,IAbzC,CACxB,SACA,UACA,OACA,SACA,OACA,OACA,OACA,OACA,KACD,CAKA,CCeD,SAAgB,EACd,EAC2B,CAC3B,IAAM,EAASA,EAAO,OAAQ,GAAU,CAAC,EAAM,GAAG,CAC5C,EAAQ,IAAI,IAClB,MAAO,CACL,OAAA,EACA,SACA,SAAS,EAAO,EAAW,CACzB,GAAI,IAAU,IAAA,GAAW,OAAO,EAAO,OAAS,EAAI,EAAS,IAAA,GAE7D,IAAM,EAAO,EAAK,EADN,GAAG,EAAM,GAAG,QAEtBA,EAAO,QACJ,CAAE,QACD,CAAC,GAAO,EAAG,OAAO,IAAI,EAAM,EAAI,EAAG,WAAW,IAAI,EAAU,CAC/D,CACF,CACD,OAAO,EAAK,OAAS,EAAI,EAAO,IAAA,IAEnC,CCsCH,MAAM,EAA0C,OAAO,OAAO,EAAE,CAAC,CASjE,SAAS,EACP,CAAE,UAAS,OAAM,OAAM,SACvB,EACa,CACb,IAAM,GACJ,CAAE,YAAW,KAAM,GACnB,EACA,EACA,EACA,EACA,EACA,IACG,CACH,IAAM,GAAW,EAAiB,IAChC,IAAI,EACF,cAAc,EAAU,qBAAqB,IAAU,IAAA,GAAY,EAAY,GAAG,EAAM,GAAG,IAAY,GAAG,EAAQ,GAClH,CAAE,MAAO,EAAW,EAAM,CAAE,KAAM,CAAE,QAAO,YAAW,CAAE,CACzD,CACC,EACJ,GAAI,CACF,EAAW,EAAQ,CACjB,KAAM,IAAU,IAAA,GAAY,MAAQ,QACpC,SACA,QACA,YACA,IAAI,MAAO,CACT,OAAO,EAAM,MAGf,QAAS,GAAO,GAAU,MAAM,EAAU,EAAI,GAAK,EACnD,IAAI,EAAgB,CAClB,GAAI,I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U,EAAK,QAAQ,QAAU,EAAE,CAI1B,EAAQ,CAAC,MAAM,EAAG,IAAM,OAAO,CAAC,CAAC,EAAE,MAAM,CAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CACzE,CACD,EAAW,EAAM,EAAQ,EAE5B,CAWH,SAAgB,EACd,EACA,EACS,CAGT,GAAI,CAAC,EAAgC,EAAQ,CAC3C,MAAU,UAAU,sCAAsC,CAC5D,IAAM,EAAK,EAAY,EAAS,CAChC,OAAO,EAAS,CAAE,UAAS,KAAI,MAAO,GAAI,MAAO,CAAC,CAapD,SAAgB,EACd,EACA,EACA,EACS,CAGT,GAAI,CAAC,EAAgC,EAAQ,CAC3C,MAAU,UAAU,wCAAwC,CAC9D,IAAM,EAAK,EAAY,EAAS,CAChC,OAAO,EAAW,CAChB,UACA,KACA,KAAM,EACN,KAAM,EACN,MAAO,GAAI,MACX,MAAO,GAAS,MACjB,CAAC"}
package/dist/cli.mjs CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import{N as e}from"./model-Dtd37Sky.mjs";import{c as t}from"./time-step-DJaIhpAz.mjs";import{i as n}from"./validator-DMzH5Tz0.mjs";import{t as r}from"./version-Bu2LCuaj.mjs";import{b as i,i as a,n as o}from"./serializer-Br9JgpQI.mjs";import{a as s}from"./identity-CJlRQA-m.mjs";import{n as c}from"./libsql-BZAXy5PY.mjs";import{t as l}from"./mysql-BjIAoFH6.mjs";import{t as u}from"./postgres-CaMB2Y4p.mjs";import{t as d}from"./every-CgeIFxWR.mjs";import{a as f,n as p,o as m,s as h,t as g}from"./client-BvAmGuYW.mjs";import{a as _,i as v,n as y,r as b}from"./utils-BHkJsduV.mjs";import{t as x}from"./fs-estate-n-QpsFqb.mjs";import{t as S}from"./introspect-rGqr93B3.mjs";import{Command as C,InvalidArgumentError as ee}from"commander";import{existsSync as te,writeFileSync as ne}from"node:fs";import{resolve as w}from"node:path";import{loadEnvFile as T}from"node:process";import{writeFile as E}from"node:fs/promises";import{cancel as D,confirm as O,isCancel as k,note as A,outro as j}from"@clack/prompts";const M=e=>e.type===`decimal`?!e.checked:e.noncanonical!==0,N=e=>{let t=`[storage] "${e.table}"."${e.column}"`;if((e.type===`decimal`?e.declared:e.noncanonical)===null)return`${t}: the column is missing; typed queries that use it fail.\n Create it through viborm push or migrate.`;if(e.type===`decimal`)return`${t}: declared ${e.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;let n=e.type===`time`?`Time`:`DateTime`,r=e.list?"Rewrite each row through the typed client (`update`), which stores canonical members":`Repair with sqliteCanonical${n}Expression from viborm/migrations`;return`${t}: ${e.noncanonical} row(s) of noncanonical ${n} text compare and sort wrongly.\n ${r}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`},P=t=>{let n=Object.values(t).filter(t=>e(t)!==void 0).length,r=`${Object.keys(t).length-n} models`;return n===0?r:`${r}, ${n} ${n===1?`view`:`views`}`},F=e=>[`[${e.code}] ${e.message}`,e.repair].filter(Boolean).join(`
3
- `),I={postgresql:()=>u.lx(),mysql:()=>l.lx(),sqlite:()=>c.lx(),surrealql:e=>i(e).lx()};function L(t,{models:n,driver:r}){let i=t.valid?I[r.dialect]:void 0;if(i===void 0)return t;let s=[...t.errors];for(let[t,o]of Object.entries(n))if(e(o)!==void 0)try{let e=i(r);e&&a(e,{schema:n},o)}catch(e){s.push({code:`W005`,message:e instanceof Error?e.message:String(e),severity:`error`,model:t})}let c=s.length===0&&R[r.dialect];if(c&&Object.values(n).some(t=>e(t)?.refresh===`auto`))try{o(n,{migrationDriver:c()})}catch(e){let t=e.meta;if(t?.model===void 0)throw e;s.push({code:`W005`,message:e.message,severity:`error`,model:Object.keys(n).find(e=>n[e][`~`].names.sql===t.model)??t.model??``})}return{...t,errors:s,valid:s.length===0}}const R={mysql:()=>l};async function z(e){await _({config:e.config,skipValidation:!0},e.json,async r=>{let{models:i}=r;t(i);let a=L(n(i),r),o=e.db?await h({$driver:r.driver,$schema:i}):void 0,s=o?.filter(M)??[];if(e.json)process.stdout.write(`${JSON.stringify(o?{...a,storage:o}:a,null,2)}\n`);else{for(let e of a.errors)process.stderr.write(`error ${F(e)}\n`);for(let e of a.warnings)process.stderr.write(`warning ${F(e)}\n`);for(let e of s)process.stderr.write(`error ${N(e)}\n`);process.stdout.write(a.valid?`Schema valid (${P(i)}).\n`:`Schema invalid: ${a.errors.length} error(s).\n`),o&&process.stdout.write(`Storage audited: ${o.length} column(s), ${s.length} need repair.\n`)}(!a.valid||s.length>0)&&(process.exitCode=1)})}function re(){return new C(`check`).description(`Validate the schema, so clients can be created with skipSchemaValidation`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--json`,`Print machine-readable JSON`).option(`--db`,`Also audit SQLite storage: DateTime/Time text and decimal columns`).action(z)}const B=re(),V=/^[0-9a-f]{8,63}$/;function H(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new ee(`must be a positive safe integer`);return t}function U(e){if(e)return s(e)?{id:e}:V.test(e)?{prefix:e}:{name:e}}const W=e=>e.type===`destructive`?e.proceed():void 0,G=async e=>{if(e.type!==`destructive`)return;let t=await O({message:`${e.description} — approve?`,initialValue:!1});return!k(t)&&t?e.proceed():e.reject()};function K(e,t){if(e.migrations?.resolve)return e.migrations.resolve;if(t.acceptDataLoss)return W;if(!(t.dryRun||t.json||!process.stdin.isTTY))return G}async function q(e,t,n){await _({config:e.opts().config},t.json,async e=>{let r=w(t.dir??e.migrations?.dir??`./migrations`),i=e.migrations?.storage??x(r);await n(g(e.client,{storage:i,...e.migrations?.tables===void 0?{}:{tables:e.migrations.tables}}),e,i)})}function J(){let e=new C(`migrate`).description(`Manage the authenticated migration estate`).option(`--config <path>`,`Path to viborm.config.ts`);return e.command(`generate`).description(`Publish a new estate state from the current schema`).option(`-n, --name <name>`,`Human-readable state label`).option(`-d, --dir <dir>`,`Estate directory`).option(`--from <stateId>`,`Parent state id, or empty for the virtual root`).option(`--custom <path>`,`Compile a TypeScript manual migration author`).option(`--review <path>`,`Write labelled forward/check/rollback review SQL`).option(`--dry-run`,`Preview without publishing`).option(`--low-lock`,`PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps`).option(`--accept-data-loss`,`Approve destructive changes (drops, type changes) for this generate`).option(`--adopt <table...>`,`Adopt existing listed tables without DDL; apply proves each equals its declaration`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async(e,n)=>{let r=t.from===void 0?void 0:t.from===``||t.from===`empty`?null:s(t.from)?t.from:(await e.show(U(t.from))).stateId,i;if(t.custom){let n=await b(w(t.custom)),a=(Object.hasOwn(n,`default`)?n.default:void 0)??n.migration;if(!a)throw Error(`A custom migration module must export a default migration or author function`);let o=await e.graph(),s=Object.freeze(r===void 0?o.leaves.length===0?[null]:[...o.leaves]:[r]);i=typeof a==`function`?await a(s):a}let a=K(n,t),o=await e.generate({name:t.name,from:r,dryRun:t.dryRun,...t.lowLock?{lowLock:!0}:{},...t.adopt?{adopt:t.adopt}:{},...a?{resolve:a}:{},...i?{manualMigration:i}:{}});if(t.json)v(o,!0);else{process.stdout.write(`${o.outcome}: ${o.name??`No schema changes`}${o.stateId?` (${o.stateId})`:``}\n`);for(let e of o.operationsByParent??[])process.stdout.write(`Parent ${e.fromState??`empty`}:\n${e.operations.map(f).join(`
4
- `)}\n`);for(let e of o.warnings??[])process.stderr.write(`warning: ${e}\n`);(o.reviewSql||o.sql)&&process.stdout.write(`${o.reviewSql||o.sql}\n`)}t.jl&&o.reviewSql&&await E(w(t.jl),o.reviewSql,`utf8`)})}),e.command(`check`).description(`Validate estate artifacts without touching the database`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.check();v(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`list`).description(`List estate states`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.list(),!!t.json)})}),e.command(`show`).description(`Show one estate state`).argument(`<state>`,`State id, unambiguous prefix, or name`).option(`-d, --dir <dir>`,`Estate directory`).option(`--sql`,`Print labelled forward/check/rollback review SQL`).option(`--review <path>`,`Write review SQL to this file`).option(`--json`,`Print machine-readable output`).action(async(t,n)=>{await q(e,n,async(e,r,i)=>{let a=await e.show(U(t));if(!(n.sql||n.jl)){v(a,!!n.json);return}let o=await m(i),s=o.states.get(a.stateId),c=s&&o.sql.get(s.sqlHash);if(!(s&&c))throw Error(`The authenticated state SQL is unavailable`);let l=p(s.parents,s.destinationChecks,c);n.json?v({...a,reviewSql:l},!0):(v(a,!1),process.stdout.write(l)),n.jl&&await E(w(n.jl),l,`utf8`)})}),e.command(`graph`).description(`Print estate roots and leaves`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.graph(),!!t.json)})}),e.command(`status`).description(`Show marker, pending path, and unfinished attempts`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.status(),!!t.json)})}),e.command(`verify`).description(`Lock and compare the live schema to the marker`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.verify();v(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`log`).description(`Print the append-only ledger`).option(`-d, --dir <dir>`,`Estate directory`).option(`--limit <n>`,`Maximum events`,H).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.log();v(t.limit?n.slice(-t.limit):n,!!t.json)})}),e.command(`apply`).description(`Apply estate states to the target`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state id, prefix, or name`).option(`--via <stateId...>`,`Force a path through these states`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.apply({to:U(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e.command(`down`).description(`Roll back along the recorded arrival path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Roll back to this state`).option(`--steps <n>`,`Number of states to roll back`,H).option(`--accept-data-loss`,`Approve destructive changes the rollback makes to populated tables`).option(`--expect-revision <n>`,`Refuse unless the marker is at this revision`,H).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async(e,n)=>{if(t.to!==void 0&&t.steps!==void 0)throw Error(`down accepts --to or --steps, not both`);let r=K(n,t),i={dryRun:t.dryRun,...r?{resolve:r}:{},...t.expectRevision===void 0?{}:{expectRevision:t.expectRevision}},a=await e.down(t.to?{to:U(t.to),...i}:{steps:t.steps,...i});if(!a.preview||t.json)v(a,!!t.json);else{for(let e of a.edges)process.stdout.write(e.sql);a.refusal&&process.stderr.write(`down would refuse: ${a.refusal.code}: ${a.refusal.message}\n`)}a.preview&&a.refusal&&(process.exitCode=1)})}),e.command(`baseline`).description(`Adopt an existing database as a known estate state`).requiredOption(`--to <selector>`,`Existing estate state to adopt`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.baseline({to:U(t.to),via:t.via}),!!t.json)})}),e.command(`reanchor`).description(`After a restore left the history older than the database, move the marker to the state the live schema matches`).option(`--to <selector>`,`Adopt this state as the new baseline`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{v(await e.reanchor({to:U(t.to),via:t.via}),!!t.json)})}),e.command(`resolve`).description(`Resolve an unfinished attempt after live proof`).option(`-d, --dir <dir>`,`Estate directory`).option(`--complete`,`Mark complete when destination proof holds`).option(`--rolled-back`,`Mark rolled back when origin proof holds`).option(`--retry`,`Retry from the first proven incomplete step`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{if([t.complete,t.rolledBack,t.retry].filter(Boolean).length!==1)throw Error(`resolve requires exactly one of --complete, --rolled-back, or --retry`);let n=t.complete?`complete`:t.rolledBack?`rolled-back`:`retry`;v(await e.resolve({outcome:n}),!!t.json)})}),e.command(`reset`).description(`Clear managed objects and replay from empty to a selected state`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state after rebuild`).option(`--via <stateId...>`,`Force a rebuild path`).option(`--confirm`,`Confirm destructive reset (not required for dry-run)`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{if(!(t.dryRun||t.confirm))throw Error(`Reset requires --confirm; inspect --dry-run first`);v(await e.reset({to:U(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e}const Y=J();function X(e){return[e.table,e.name].filter(Boolean).join(`.`)}function ie(e,t){let n=[];if(e.length>0){n.push(`Not in the document (${e.length}):`);for(let t of e)n.push(` - ${t.kind} ${X(t)}: ${t.reason}`)}if(t.length>0){n.push(`Warnings (${t.length}):`);for(let e of t)n.push(` - [${e.kind}] ${X(e)}: ${e.message}`)}return n.length===0?`The document states the whole database; a push of it plans nothing.
2
+ import{n as e}from"./facts-Bjnzv3j-.mjs";import{c as t}from"./time-step-BIdl2Iy7.mjs";import{i as n}from"./validator-CISkL46K.mjs";import{t as r}from"./version-nEOMCWfV.mjs";import{i,n as a}from"./serializer-CIhcZMxs.mjs";import{N as o}from"./push-fingerprint-CegYVFFp.mjs";import{a as s}from"./identity-nPArhpsD.mjs";import{t as c}from"./sqlite-storage-audit-D8nA9ylL.mjs";import{t as l}from"./postgres-CEGFOi8D.mjs";import{n as u}from"./libsql-C0iMZifz.mjs";import{t as d}from"./mysql-DPYi1p_g.mjs";import{t as f}from"./every-tAZuZ50K.mjs";import{a as p,i as m,n as ee,r as h}from"./utils-BB_4NZQC.mjs";import{C as g}from"./contract-BBone8RD.mjs";import{n as _,r as v,t as y}from"./client-rIiFOn1W.mjs";import{t as b}from"./fs-estate-C3ahNKmi.mjs";import{t as x}from"./introspect-dyBpdr2L.mjs";import{Command as S,InvalidArgumentError as C}from"commander";import{existsSync as te,writeFileSync as ne}from"node:fs";import{resolve as w}from"node:path";import{loadEnvFile as T}from"node:process";import{writeFile as E}from"node:fs/promises";import{cancel as D,confirm as O,isCancel as k,note as A,outro as j}from"@clack/prompts";const M=e=>e.type===`decimal`?!e.checked:e.noncanonical!==0,N=e=>{let t=`[storage] "${e.table}"."${e.column}"`;if((e.type===`decimal`?e.declared:e.noncanonical)===null)return`${t}: the column is missing; typed queries that use it fail.\n Create it through viborm push or migrate.`;if(e.type===`decimal`)return`${t}: declared ${e.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;let n=e.type===`time`?`Time`:`DateTime`,r=e.list?"Rewrite each row through the typed client (`update`), which stores canonical members":`Repair with sqliteCanonical${n}Expression from viborm/migrations`;return`${t}: ${e.noncanonical} row(s) of noncanonical ${n} text compare and sort wrongly.\n ${r}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`},P=t=>{let n=Object.values(t).filter(t=>e(t)!==void 0).length,r=`${Object.keys(t).length-n} models`;return n===0?r:`${r}, ${n} ${n===1?`view`:`views`}`},F=e=>[`[${e.code}] ${e.message}`,e.repair].filter(Boolean).join(`
3
+ `),I={postgresql:()=>l.cg(),mysql:()=>d.cg(),sqlite:()=>u.cg(),surrealql:e=>o(e).cg()};function L(t,{models:n,driver:r}){let o=t.valid?I[r.dialect]:void 0;if(o===void 0)return t;let s=[...t.errors];for(let[t,a]of Object.entries(n))if(e(a)!==void 0)try{let e=o(r);e&&i(e,{schema:n},a)}catch(e){s.push({code:`W005`,message:e instanceof Error?e.message:String(e),severity:`error`,model:t})}let c=s.length===0&&R[r.dialect];if(c&&Object.values(n).some(t=>e(t)?.refresh===`auto`))try{a(n,{migrationDriver:c()})}catch(e){let t=e.meta;if(t?.model===void 0)throw e;s.push({code:`W005`,message:e.message,severity:`error`,model:Object.keys(n).find(e=>n[e][`~`].names.sql===t.model)??t.model??``})}return{...t,errors:s,valid:s.length===0}}const R={mysql:()=>d};async function z(e){await p({config:e.config,skipValidation:!0},e.json,async r=>{let{models:i}=r;t(i);let a=L(n(i),r),o=e.db?await c({$driver:r.driver,$schema:i}):void 0,s=o?.filter(M)??[];if(e.json)process.stdout.write(`${JSON.stringify(o?{...a,storage:o}:a,null,2)}\n`);else{for(let e of a.errors)process.stderr.write(`error ${F(e)}\n`);for(let e of a.warnings)process.stderr.write(`warning ${F(e)}\n`);for(let e of s)process.stderr.write(`error ${N(e)}\n`);process.stdout.write(a.valid?`Schema valid (${P(i)}).\n`:`Schema invalid: ${a.errors.length} error(s).\n`),o&&process.stdout.write(`Storage audited: ${o.length} column(s), ${s.length} need repair.\n`)}(!a.valid||s.length>0)&&(process.exitCode=1)})}function B(){return new S(`check`).description(`Validate the schema, so clients can be created with skipSchemaValidation`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--json`,`Print machine-readable JSON`).option(`--db`,`Also audit SQLite storage: DateTime/Time text and decimal columns`).action(z)}const re=B(),V=/^[0-9a-f]{8,63}$/;function H(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw new C(`must be a positive safe integer`);return t}function U(e){if(e)return s(e)?{id:e}:V.test(e)?{prefix:e}:{name:e}}const W=e=>e.type===`destructive`?e.proceed():void 0,G=async e=>{if(e.type!==`destructive`)return;let t=await O({message:`${e.description} — approve?`,initialValue:!1});return!k(t)&&t?e.proceed():e.reject()};function K(e,t){if(e.migrations?.resolve)return e.migrations.resolve;if(t.acceptDataLoss)return W;if(!(t.dryRun||t.json||!process.stdin.isTTY))return G}async function q(e,t,n){await p({config:e.opts().config},t.json,async e=>{let r=w(t.dir??e.migrations?.dir??`./migrations`),i=e.migrations?.storage??b(r);await n(y(e.client,{storage:i,...e.migrations?.tables===void 0?{}:{tables:e.migrations.tables}}),e,i)})}function J(){let e=new S(`migrate`).description(`Manage the authenticated migration estate`).option(`--config <path>`,`Path to viborm.config.ts`);return e.command(`generate`).description(`Publish a new estate state from the current schema`).option(`-n, --name <name>`,`Human-readable state label`).option(`-d, --dir <dir>`,`Estate directory`).option(`--from <stateId>`,`Parent state id, or empty for the virtual root`).option(`--custom <path>`,`Compile a TypeScript manual migration author`).option(`--review <path>`,`Write labelled forward/check/rollback review SQL`).option(`--dry-run`,`Preview without publishing`).option(`--low-lock`,`PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps`).option(`--accept-data-loss`,`Approve destructive changes (drops, type changes) for this generate`).option(`--adopt <table...>`,`Adopt existing listed tables without DDL; apply proves each equals its declaration`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async(e,n)=>{let r=t.from===void 0?void 0:t.from===``||t.from===`empty`?null:s(t.from)?t.from:(await e.show(U(t.from))).stateId,i;if(t.custom){let n=await h(w(t.custom)),a=(Object.hasOwn(n,`default`)?n.default:void 0)??n.migration;if(!a)throw Error(`A custom migration module must export a default migration or author function`);let o=await e.graph(),s=Object.freeze(r===void 0?o.leaves.length===0?[null]:[...o.leaves]:[r]);i=typeof a==`function`?await a(s):a}let a=K(n,t),o=await e.generate({name:t.name,from:r,dryRun:t.dryRun,...t.lowLock?{lowLock:!0}:{},...t.adopt?{adopt:t.adopt}:{},...a?{resolve:a}:{},...i?{manualMigration:i}:{}});if(t.json)m(o,!0);else{process.stdout.write(`${o.outcome}: ${o.name??`No schema changes`}${o.stateId?` (${o.stateId})`:``}\n`);for(let e of o.operationsByParent??[])process.stdout.write(`Parent ${e.fromState??`empty`}:\n${e.operations.map(_).join(`
4
+ `)}\n`);for(let e of o.warnings??[])process.stderr.write(`warning: ${e}\n`);(o.reviewSql||o.sql)&&process.stdout.write(`${o.reviewSql||o.sql}\n`)}t.jw&&o.reviewSql&&await E(w(t.jw),o.reviewSql,`utf8`)})}),e.command(`check`).description(`Validate estate artifacts without touching the database`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.check();m(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`list`).description(`List estate states`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{m(await e.list(),!!t.json)})}),e.command(`show`).description(`Show one estate state`).argument(`<state>`,`State id, unambiguous prefix, or name`).option(`-d, --dir <dir>`,`Estate directory`).option(`--sql`,`Print labelled forward/check/rollback review SQL`).option(`--review <path>`,`Write review SQL to this file`).option(`--json`,`Print machine-readable output`).action(async(t,n)=>{await q(e,n,async(e,r,i)=>{let a=await e.show(U(t));if(!(n.sql||n.jw)){m(a,!!n.json);return}let o=await g(i),s=o.states.get(a.stateId),c=s&&o.sql.get(s.sqlHash);if(!(s&&c))throw Error(`The authenticated state SQL is unavailable`);let l=v(s.parents,s.destinationChecks,c);n.json?m({...a,reviewSql:l},!0):(m(a,!1),process.stdout.write(l)),n.jw&&await E(w(n.jw),l,`utf8`)})}),e.command(`graph`).description(`Print estate roots and leaves`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{m(await e.graph(),!!t.json)})}),e.command(`status`).description(`Show marker, pending path, and unfinished attempts`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{m(await e.status(),!!t.json)})}),e.command(`verify`).description(`Lock and compare the live schema to the marker`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.verify();m(n,!!t.json),n.ok||(process.exitCode=1)})}),e.command(`log`).description(`Print the append-only ledger`).option(`-d, --dir <dir>`,`Estate directory`).option(`--limit <n>`,`Maximum events`,H).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{let n=await e.log();m(t.limit?n.slice(-t.limit):n,!!t.json)})}),e.command(`apply`).description(`Apply estate states to the target`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state id, prefix, or name`).option(`--via <stateId...>`,`Force a path through these states`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{m(await e.apply({to:U(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e.command(`down`).description(`Roll back along the recorded arrival path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Roll back to this state`).option(`--steps <n>`,`Number of states to roll back`,H).option(`--accept-data-loss`,`Approve destructive changes the rollback makes to populated tables`).option(`--expect-revision <n>`,`Refuse unless the marker is at this revision`,H).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async(e,n)=>{if(t.to!==void 0&&t.steps!==void 0)throw Error(`down accepts --to or --steps, not both`);let r=K(n,t),i={dryRun:t.dryRun,...r?{resolve:r}:{},...t.expectRevision===void 0?{}:{expectRevision:t.expectRevision}},a=await e.down(t.to?{to:U(t.to),...i}:{steps:t.steps,...i});if(!a.preview||t.json)m(a,!!t.json);else{for(let e of a.edges)process.stdout.write(e.sql);a.refusal&&process.stderr.write(`down would refuse: ${a.refusal.code}: ${a.refusal.message}\n`)}a.preview&&a.refusal&&(process.exitCode=1)})}),e.command(`baseline`).description(`Adopt an existing database as a known estate state`).requiredOption(`--to <selector>`,`Existing estate state to adopt`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{m(await e.baseline({to:U(t.to),via:t.via}),!!t.json)})}),e.command(`reanchor`).description(`After a restore left the history older than the database, move the marker to the state the live schema matches`).option(`--to <selector>`,`Adopt this state as the new baseline`).option(`--via <stateId...>`,`Force the recorded root path`).option(`-d, --dir <dir>`,`Estate directory`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{m(await e.reanchor({to:U(t.to),via:t.via}),!!t.json)})}),e.command(`resolve`).description(`Resolve an unfinished attempt after live proof`).option(`-d, --dir <dir>`,`Estate directory`).option(`--complete`,`Mark complete when destination proof holds`).option(`--rolled-back`,`Mark rolled back when origin proof holds`).option(`--retry`,`Retry from the first proven incomplete step`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{if([t.complete,t.rolledBack,t.retry].filter(Boolean).length!==1)throw Error(`resolve requires exactly one of --complete, --rolled-back, or --retry`);let n=t.complete?`complete`:t.rolledBack?`rolled-back`:`retry`;m(await e.resolve({outcome:n}),!!t.json)})}),e.command(`reset`).description(`Clear managed objects and replay from empty to a selected state`).option(`-d, --dir <dir>`,`Estate directory`).option(`--to <selector>`,`Target state after rebuild`).option(`--via <stateId...>`,`Force a rebuild path`).option(`--confirm`,`Confirm destructive reset (not required for dry-run)`).option(`--dry-run`,`Plan without executing`).option(`--json`,`Print machine-readable output`).action(async t=>{await q(e,t,async e=>{if(!(t.dryRun||t.confirm))throw Error(`Reset requires --confirm; inspect --dry-run first`);m(await e.reset({to:U(t.to),via:t.via,dryRun:t.dryRun}),!!t.json)})}),e}const Y=J();function X(e){return[e.table,e.name].filter(Boolean).join(`.`)}function ie(e,t){let n=[];if(e.length>0){n.push(`Not in the document (${e.length}):`);for(let t of e)n.push(` - ${t.kind} ${X(t)}: ${t.reason}`)}if(t.length>0){n.push(`Warnings (${t.length}):`);for(let e of t)n.push(` - [${e.kind}] ${X(e)}: ${e.message}`)}return n.length===0?`The document states the whole database; a push of it plans nothing.
5
5
  `:`${n.join(`
6
- `)}\n`}async function ae(e){try{if(!e.json)throw Error(`viborm pull writes a JSON schema document: pass --json. A TypeScript schema is not generated yet.`);let t=w(process.cwd(),`.env`);te(t)&&T(t);let n=e.url??process.env.DATABASE_URL;if(!n)throw Error(`viborm pull needs a connection string: pass --url or set DATABASE_URL.`);let r=await S({url:n,...e.tables===void 0?{}:{tables:e.tables},...e.light?{light:!0}:{}}),i=`${JSON.stringify(r.document,null,2)}\n`;e.out===void 0?process.stdout.write(i):ne(w(process.cwd(),e.out),i),process.stderr.write(ie(r.skipped,r.warnings))}catch(t){y(t,e.json===!0)}}function oe(){return new C(`pull`).description(`Read an existing database into a schema document (viborm/schema/json)`).option(`--json`,`Write the JSON schema document`).option(`--url <url>`,`Connection string (postgres://, mysql://, file:, libsql://); defaults to DATABASE_URL`).option(`--out <path>`,`Write the document to this file instead of stdout`).option(`--light`,`Only what a client needs (no indexes); migrations refuse the document`).option(`--tables <names...>`,`Only these tables (exact physical names, space- or comma-separated)`,(e,t)=>[...t??[],...e.split(`,`).map(e=>e.trim()).filter(Boolean)]).action(ae)}const se=oe();function Z(e){let t=e.operations.length===0?[`No schema changes.`]:e.operations.map(e=>`[${e.risk}] ${e.label} (${e.id})`),n=e.statements.map((e,t)=>`${t+1}. ${e.sql}${e.parameters.length===0?``:`\n parameters: ${JSON.stringify(e.parameters)}`}`);A([`Target: ${JSON.stringify(e.target)}`,`Plan: ${e.planHash}`,...t,...n.length===0?[]:[``,`SQL:`,...n]].join(`
7
- `),`Push plan`)}async function Q(e){await _({config:e.config},e.json,async t=>{let n=t.migrations?.tables===void 0?g(t.client):g(t.client,{tables:t.migrations.tables}),r=await n.push({dryRun:!0,...e.forceReset===!0?{forceReset:!0}:{},...t.migrations?.resolve?{resolve:t.migrations.resolve}:{}});if(!e.json&&t.driver?.dialect===`sqlite`&&[`sqlite3`,`bun-sqlite`,`bun-sql`].includes(t.driver.driverName)&&(await t.driver._executeRaw(`PRAGMA database_list`)).rows.some(e=>e.name===`main`&&e.file===``)&&process.stderr.write(`warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.
8
- `),e.dryRun){e.json?v(r,!0):Z(r);return}if(e.json||Z(r),r.destructive&&!e.acceptDataLoss&&(e.p8||e.json||!process.stdin.isTTY))throw Error(`Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.`);if(r.outcome!==`noop`&&!e.p8&&!e.acceptDataLoss&&!e.json&&process.stdin.isTTY){let e=await O({message:r.destructive?`Apply this destructive push plan?`:`Apply this push plan?`,initialValue:!r.destructive});if(k(e)||!e){D(`Push cancelled.`);return}}let i=await n.push({consent:r.consent});e.json?v(i,!0):j(i.outcome===`noop`?`Schema is up to date.`:`Push applied.`)})}function ce(){return new C(`push`).description(`Synchronize the schema directly without migration history`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--dry-run`,`Preview without changing the database`).option(`--force-reset`,`Plan a rebuild from an empty database`).option(`-y, --yes`,`Skip prompts for non-destructive plans`).option(`--accept-data-loss`,`Explicitly accept the previewed destructive plan`).option(`--json`,`Print machine-readable JSON`).action(Q)}const le=ce();d();const $=new C;$.name(`viborm`).description(`VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite`).version(r),$.addCommand(B),$.addCommand(le),$.addCommand(Y),$.addCommand(se);try{await $.parseAsync()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`CLI failed`}\n`),process.exitCode=1}for(let e of[process.stdout,process.stderr])e.writableLength>0&&await new Promise(t=>e.write(``,()=>t()));process.exit();export{};
6
+ `)}\n`}async function ae(e){try{if(!e.json)throw Error(`viborm pull writes a JSON schema document: pass --json. A TypeScript schema is not generated yet.`);let t=w(process.cwd(),`.env`);te(t)&&T(t);let n=e.url??process.env.DATABASE_URL;if(!n)throw Error(`viborm pull needs a connection string: pass --url or set DATABASE_URL.`);let r=await x({url:n,...e.tables===void 0?{}:{tables:e.tables},...e.light?{light:!0}:{}}),i=`${JSON.stringify(r.document,null,2)}\n`;e.out===void 0?process.stdout.write(i):ne(w(process.cwd(),e.out),i),process.stderr.write(ie(r.skipped,r.warnings))}catch(t){ee(t,e.json===!0)}}function oe(){return new S(`pull`).description(`Read an existing database into a schema document (viborm/schema/json)`).option(`--json`,`Write the JSON schema document`).option(`--url <url>`,`Connection string (postgres://, mysql://, file:, libsql://); defaults to DATABASE_URL`).option(`--out <path>`,`Write the document to this file instead of stdout`).option(`--light`,`Only what a client needs (no indexes); migrations refuse the document`).option(`--tables <names...>`,`Only these tables (exact physical names, space- or comma-separated)`,(e,t)=>[...t??[],...e.split(`,`).map(e=>e.trim()).filter(Boolean)]).action(ae)}const se=oe();function Z(e){let t=e.operations.length===0?[`No schema changes.`]:e.operations.map(e=>`[${e.risk}] ${e.label} (${e.id})`),n=e.statements.map((e,t)=>`${t+1}. ${e.sql}${e.parameters.length===0?``:`\n parameters: ${JSON.stringify(e.parameters)}`}`);A([`Target: ${JSON.stringify(e.target)}`,`Plan: ${e.planHash}`,...t,...n.length===0?[]:[``,`SQL:`,...n]].join(`
7
+ `),`Push plan`)}async function Q(e){await p({config:e.config},e.json,async t=>{let n=t.migrations?.tables===void 0?y(t.client):y(t.client,{tables:t.migrations.tables}),r=await n.push({dryRun:!0,...e.forceReset===!0?{forceReset:!0}:{},...t.migrations?.resolve?{resolve:t.migrations.resolve}:{}});if(!e.json&&t.driver?.dialect===`sqlite`&&[`sqlite3`,`bun-sqlite`,`bun-sql`].includes(t.driver.driverName)&&(await t.driver._executeRaw(`PRAGMA database_list`)).rows.some(e=>e.name===`main`&&e.file===``)&&process.stderr.write(`warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.
8
+ `),e.dryRun){e.json?m(r,!0):Z(r);return}if(e.json||Z(r),r.destructive&&!e.acceptDataLoss&&(e.f5||e.json||!process.stdin.isTTY))throw Error(`Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.`);if(r.outcome!==`noop`&&!e.f5&&!e.acceptDataLoss&&!e.json&&process.stdin.isTTY){let e=await O({message:r.destructive?`Apply this destructive push plan?`:`Apply this push plan?`,initialValue:!r.destructive});if(k(e)||!e){D(`Push cancelled.`);return}}let i=await n.push({consent:r.consent});e.json?m(i,!0):j(i.outcome===`noop`?`Schema is up to date.`:`Push applied.`)})}function ce(){return new S(`push`).description(`Synchronize the schema directly without migration history`).option(`--config <path>`,`Path to viborm.config.ts`).option(`--dry-run`,`Preview without changing the database`).option(`--force-reset`,`Plan a rebuild from an empty database`).option(`-y, --yes`,`Skip prompts for non-destructive plans`).option(`--accept-data-loss`,`Explicitly accept the previewed destructive plan`).option(`--json`,`Print machine-readable JSON`).action(Q)}const le=ce();f();const $=new S;$.name(`viborm`).description(`VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite`).version(r),$.addCommand(re),$.addCommand(le),$.addCommand(Y),$.addCommand(se);try{await $.parseAsync()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`CLI failed`}\n`),process.exitCode=1}for(let e of[process.stdout,process.stderr])e.writableLength>0&&await new Promise(t=>e.write(``,()=>t()));process.exit();export{};
9
9
  //# sourceMappingURL=cli.mjs.map
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.mjs","names":["resolve"],"sources":["../src/cli/commands/check.ts","../src/cli/commands/migrate.ts","../src/cli/commands/pull.ts","../src/cli/commands/push.ts","../src/cli/index.ts"],"sourcesContent":["/**\n * Schema check CLI.\n *\n * Runs every check a client runs when it is created (identifiers, model\n * identity, relation resolution, selector names), plus the advisory rules and\n * the query of every view, against the schema of the configured client. Run it in a build or CI step to\n * create clients with `skipSchemaValidation: true` at runtime.\n */\n\nimport { Command } from \"commander\";\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { getMigrationDriver } from \"../../migrations/drivers\";\nimport type {\n MigrationDriver,\n ViewWriter,\n} from \"../../migrations/drivers/base\";\nimport { mysqlMigrationDriver } from \"../../migrations/drivers/mysql\";\nimport { postgresMigrationDriver } from \"../../migrations/drivers/postgres\";\nimport { sqlite3MigrationDriver } from \"../../migrations/drivers/sqlite\";\nimport type { Dialect } from \"../../migrations/drivers/types\";\nimport { serializeModels } from \"../../migrations/serializer\";\nimport {\n auditStorage,\n type StorageColumnAudit,\n} from \"../../migrations/sqlite-storage-audit\";\nimport { writeView } from \"../../migrations/view-definition\";\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport type {\n SchemaValidationIssue,\n ValidationResult,\n} from \"../../schema/validation/types\";\nimport { validateSchema } from \"../../schema/validation/validator\";\nimport { viewFacts } from \"../../schema/view/facts\";\nimport { type LoadedConfig, runCli } from \"../utils\";\n\ntype LoadedModels = LoadedConfig[\"models\"];\n\ninterface CheckCliOptions {\n readonly config?: string;\n readonly json?: boolean;\n readonly db?: boolean;\n}\n\nconst needsRepair = (audit: StorageColumnAudit): boolean =>\n audit.type === \"decimal\" ? !audit.checked : audit.noncanonical !== 0;\n\nconst describeAudit = (audit: StorageColumnAudit): string => {\n const column = `[storage] \"${audit.table}\".\"${audit.column}\"`;\n if ((audit.type === \"decimal\" ? audit.declared : audit.noncanonical) === null)\n return `${column}: the column is missing; typed queries that use it fail.\\n Create it through viborm push or migrate.`;\n if (audit.type === \"decimal\")\n return `${column}: declared ${audit.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;\n const kind = audit.type === \"time\" ? \"Time\" : \"DateTime\";\n const repair = audit.list\n ? \"Rewrite each row through the typed client (`update`), which stores canonical members\"\n : `Repair with sqliteCanonical${kind}Expression from viborm/migrations`;\n return `${column}: ${audit.noncanonical} row(s) of noncanonical ${kind} text compare and sort wrongly.\\n ${repair}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`;\n};\n\n/** How many models and how many database views a valid schema holds. */\nconst summarize = (models: LoadedModels): string => {\n const views = Object.values(models).filter(\n (model) => viewFacts(model) !== undefined\n ).length;\n const tables = `${Object.keys(models).length - views} models`;\n if (views === 0) return tables;\n return `${tables}, ${views} ${views === 1 ? \"view\" : \"views\"}`;\n};\n\n// The repair hint, when the issue has one, goes on its own indented line.\nconst describe = (issue: SchemaValidationIssue): string =>\n [`[${issue.code}] ${issue.message}`, issue.repair]\n .filter(Boolean)\n .join(\"\\n \");\n\n/**\n * Who writes a view's body, per dialect VibORM creates views on: on SurrealDB\n * the read backend of the configured driver, which its migration binds to.\n */\nconst VIEW_WRITERS: Partial<\n Record<Dialect, (driver: AnyDriver) => ViewWriter | undefined>\n> = {\n postgresql: () => postgresMigrationDriver.viewWriter(),\n mysql: () => mysqlMigrationDriver.viewWriter(),\n sqlite: () => sqlite3MigrationDriver.viewWriter(),\n surrealql: (driver) => getMigrationDriver(driver).viewWriter(),\n};\n\n/**\n * What a view's query is refused for (W005), found by compiling its body as\n * a migration would: a clause a view cannot hold, or a query its source does\n * not take. Asked of a schema whose relations resolve, on a dialect VibORM\n * creates views on.\n */\nfunction withViewQueries(\n result: ValidationResult,\n { models, driver }: LoadedConfig\n): ValidationResult {\n const writer = result.valid ? VIEW_WRITERS[driver.dialect] : undefined;\n if (writer === undefined) return result;\n const errors = [...result.errors];\n for (const [model, view] of Object.entries(models)) {\n if (viewFacts(view) === undefined) continue;\n try {\n const written = writer(driver);\n if (written) writeView(written, { schema: models }, view);\n } catch (cause) {\n errors.push({\n code: \"W005\",\n message: cause instanceof Error ? cause.message : String(cause),\n severity: \"error\",\n model,\n });\n }\n }\n // What a view kept by triggers needs of the schema's other tables (MySQL's\n // cascades) is read off the whole schema, as a migration serializes it.\n const cascades = errors.length === 0 && AUTO_CASCADES[driver.dialect];\n if (\n cascades &&\n Object.values(models).some((model) => viewFacts(model)?.refresh === \"auto\")\n )\n try {\n serializeModels(models, { migrationDriver: cascades() });\n } catch (cause) {\n const meta = (cause as { meta?: { feature?: string; model?: string } })\n .meta;\n if (meta?.model === undefined) throw cause;\n errors.push({\n code: \"W005\",\n message: (cause as Error).message,\n severity: \"error\",\n model:\n Object.keys(models).find(\n (key) => models[key]![\"~\"].names.sql === meta.model\n ) ??\n meta.model ??\n \"\",\n });\n }\n return { ...result, errors, valid: errors.length === 0 };\n}\n\n/** The dialects whose cascades a view kept by triggers must follow itself. */\nconst AUTO_CASCADES: Partial<Record<Dialect, () => MigrationDriver>> = {\n mysql: () => mysqlMigrationDriver,\n};\n\nasync function runCheck(options: CheckCliOptions): Promise<void> {\n const load = { config: options.config, skipValidation: true };\n await runCli(load, options.json, async (config) => {\n const { models } = config;\n // The identifier and identity checks hydration runs, whatever the\n // configured client skipped.\n hydrateSchemaNames(models);\n const result = withViewQueries(validateSchema(models), config);\n const storage = options.db\n ? await auditStorage({ $driver: config.driver, $schema: models })\n : undefined;\n const dirty = storage?.filter(needsRepair) ?? [];\n if (options.json) {\n process.stdout.write(\n `${JSON.stringify(storage ? { ...result, storage } : result, null, 2)}\\n`\n );\n } else {\n for (const issue of result.errors)\n process.stderr.write(`error ${describe(issue)}\\n`);\n for (const issue of result.warnings)\n process.stderr.write(`warning ${describe(issue)}\\n`);\n for (const audit of dirty)\n process.stderr.write(`error ${describeAudit(audit)}\\n`);\n process.stdout.write(\n result.valid\n ? `Schema valid (${summarize(models)}).\\n`\n : `Schema invalid: ${result.errors.length} error(s).\\n`\n );\n if (storage)\n process.stdout.write(\n `Storage audited: ${storage.length} column(s), ${dirty.length} need repair.\\n`\n );\n }\n if (!result.valid || dirty.length > 0) process.exitCode = 1;\n });\n}\n\nexport function createCheckCommand(): Command {\n return new Command(\"check\")\n .description(\n \"Validate the schema, so clients can be created with skipSchemaValidation\"\n )\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--json\", \"Print machine-readable JSON\")\n .option(\n \"--db\",\n \"Also audit SQLite storage: DateTime/Time text and decimal columns\"\n )\n .action(runCheck);\n}\n\nexport const checkCommand = createCheckCommand();\n","/**\n * Migration CLI. Composition root is createMigrationClient + loadConfig.\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { confirm, isCancel } from \"@clack/prompts\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport {\n createMigrationClient,\n type WritableMigrations,\n} from \"../../migrations/client\";\nimport { loadMigrationGraph } from \"../../migrations/graph\";\nimport { isSha256 } from \"../../migrations/identity\";\nimport { renderMigrationReview } from \"../../migrations/public-view\";\nimport { formatOperation } from \"../../migrations/push/format\";\nimport type { MigrationStorageWriter } from \"../../migrations/storage/contract\";\nimport { createFsStorageWriter } from \"../../migrations/storage/fs-estate\";\nimport type { ResolveCallback } from \"../../migrations/types\";\nimport type {\n ManualMigrationInput,\n StateSelector,\n} from \"../../migrations/v1-types\";\nimport { type LoadedConfig, loadCliModule, printJson, runCli } from \"../utils\";\n\nconst STATE_ID_PREFIX = /^[0-9a-f]{8,63}$/;\n\nfunction positiveInteger(value: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(\"must be a positive safe integer\");\n }\n return parsed;\n}\n\nfunction selector(value: string | undefined): StateSelector | undefined {\n if (!value) return undefined;\n if (isSha256(value)) return { id: value };\n if (STATE_ID_PREFIX.test(value)) return { prefix: value };\n return { name: value };\n}\n\n/** `--accept-data-loss`: every destructive change approved, nothing else decided. */\nconst approveDestructive: ResolveCallback = (change) =>\n change.type === \"destructive\" ? change.proceed() : undefined;\n\n/** One prompt per destructive change, as `viborm push` asks for its plan. */\nconst confirmDestructive: ResolveCallback = async (change) => {\n if (change.type !== \"destructive\") return;\n const approved = await confirm({\n message: `${change.description} — approve?`,\n initialValue: false,\n });\n return !isCancel(approved) && approved ? change.proceed() : change.reject();\n};\n\n/**\n * The resolver `migrate generate` publishes under, and `migrate down` rolls\n * back under: the config's own, else\n * `--accept-data-loss`, else a prompt on an interactive terminal. With none,\n * generate refuses a destructive change with `V11017`.\n */\nfunction generateResolver(\n config: LoadedConfig,\n opts: { acceptDataLoss?: boolean; dryRun?: boolean; json?: boolean }\n): ResolveCallback | undefined {\n if (config.migrations?.resolve) return config.migrations.resolve;\n if (opts.acceptDataLoss) return approveDestructive;\n if (opts.dryRun || opts.json || !process.stdin.isTTY) return;\n return confirmDestructive;\n}\n\n/** Each subcommand reads the parent's `--config` and its own `--dir`. */\nasync function withMigrations(\n migrate: Command,\n options: { dir?: string; json?: boolean },\n run: (\n migrations: WritableMigrations,\n config: LoadedConfig,\n storage: MigrationStorageWriter\n ) => Promise<void>\n): Promise<void> {\n await runCli(\n { config: migrate.opts<{ config?: string }>().config },\n options.json,\n async (config) => {\n const directory = resolve(\n options.dir ?? config.migrations?.dir ?? \"./migrations\"\n );\n const storage =\n config.migrations?.storage ?? createFsStorageWriter(directory);\n const migrations = createMigrationClient(config.client, {\n storage,\n ...(config.migrations?.tables === undefined\n ? {}\n : { tables: config.migrations.tables }),\n });\n await run(migrations, config, storage);\n }\n );\n}\n\nexport function createMigrateCommand(): Command {\n const migrate = new Command(\"migrate\")\n .description(\"Manage the authenticated migration estate\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\");\n\n migrate\n .command(\"generate\")\n .description(\"Publish a new estate state from the current schema\")\n .option(\"-n, --name <name>\", \"Human-readable state label\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\n \"--from <stateId>\",\n \"Parent state id, or empty for the virtual root\"\n )\n .option(\"--custom <path>\", \"Compile a TypeScript manual migration author\")\n .option(\n \"--review <path>\",\n \"Write labelled forward/check/rollback review SQL\"\n )\n .option(\"--dry-run\", \"Preview without publishing\")\n .option(\n \"--low-lock\",\n \"PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps\"\n )\n .option(\n \"--accept-data-loss\",\n \"Approve destructive changes (drops, type changes) for this generate\"\n )\n .option(\n \"--adopt <table...>\",\n \"Adopt existing listed tables without DDL; apply proves each equals its declaration\"\n )\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n adopt?: string[];\n name?: string;\n dir?: string;\n from?: string;\n dryRun?: boolean;\n lowLock?: boolean;\n acceptDataLoss?: boolean;\n custom?: string;\n review?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations, config) => {\n const from =\n opts.from === undefined\n ? undefined\n : opts.from === \"\" || opts.from === \"empty\"\n ? null\n : isSha256(opts.from)\n ? opts.from\n : (await migrations.show(selector(opts.from)!)).stateId;\n let manualMigration: ManualMigrationInput | undefined;\n if (opts.custom) {\n type Author =\n | ManualMigrationInput\n | ((\n parents: readonly (string | null)[]\n ) => ManualMigrationInput | Promise<ManualMigrationInput>);\n const module = await loadCliModule<{\n default?: Author;\n migration?: Author;\n }>(resolve(opts.custom));\n const author =\n (Object.hasOwn(module, \"default\") ? module.default : undefined) ??\n module.migration;\n if (!author)\n throw new Error(\n \"A custom migration module must export a default migration or author function\"\n );\n const graph = await migrations.graph();\n const parents = Object.freeze(\n from === undefined\n ? graph.leaves.length === 0\n ? [null]\n : [...graph.leaves]\n : [from]\n );\n manualMigration =\n typeof author === \"function\" ? await author(parents) : author;\n }\n const approve = generateResolver(config, opts);\n const result = await migrations.generate({\n name: opts.name,\n from,\n dryRun: opts.dryRun,\n ...(opts.lowLock ? { lowLock: true } : {}),\n ...(opts.adopt ? { adopt: opts.adopt } : {}),\n ...(approve ? { resolve: approve } : {}),\n ...(manualMigration ? { manualMigration } : {}),\n });\n if (opts.json) printJson(result, true);\n else {\n process.stdout.write(\n `${result.outcome}: ${result.name ?? \"No schema changes\"}${result.stateId ? ` (${result.stateId})` : \"\"}\\n`\n );\n for (const parent of result.operationsByParent ?? []) {\n process.stdout.write(\n `Parent ${parent.fromState ?? \"empty\"}:\\n${parent.operations.map(formatOperation).join(\"\\n\")}\\n`\n );\n }\n for (const warning of result.warnings ?? [])\n process.stderr.write(`warning: ${warning}\\n`);\n if (result.reviewSql || result.sql)\n process.stdout.write(`${result.reviewSql || result.sql}\\n`);\n }\n if (opts.review && result.reviewSql)\n await writeFile(resolve(opts.review), result.reviewSql, \"utf8\");\n });\n }\n );\n\n migrate\n .command(\"check\")\n .description(\"Validate estate artifacts without touching the database\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const result = await migrations.check();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n });\n });\n\n migrate\n .command(\"list\")\n .description(\"List estate states\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.list(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"show\")\n .description(\"Show one estate state\")\n .argument(\"<state>\", \"State id, unambiguous prefix, or name\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--sql\", \"Print labelled forward/check/rollback review SQL\")\n .option(\"--review <path>\", \"Write review SQL to this file\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (\n state: string,\n opts: { dir?: string; sql?: boolean; review?: string; json?: boolean }\n ) => {\n await withMigrations(\n migrate,\n opts,\n async (migrations, _config, storage) => {\n const details = await migrations.show(selector(state)!);\n if (!(opts.sql || opts.review)) {\n printJson(details, Boolean(opts.json));\n return;\n }\n const graph = await loadMigrationGraph(storage);\n const manifest = graph.states.get(details.stateId);\n const blob = manifest && graph.sql.get(manifest.sqlHash);\n if (!(manifest && blob))\n throw new Error(\"The authenticated state SQL is unavailable\");\n const reviewSql = renderMigrationReview(\n manifest.parents,\n manifest.destinationChecks,\n blob\n );\n if (opts.json) printJson({ ...details, reviewSql }, true);\n else {\n printJson(details, false);\n process.stdout.write(reviewSql);\n }\n if (opts.review)\n await writeFile(resolve(opts.review), reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"graph\")\n .description(\"Print estate roots and leaves\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.graph(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"status\")\n .description(\"Show marker, pending path, and unfinished attempts\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.status(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"verify\")\n .description(\"Lock and compare the live schema to the marker\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const result = await migrations.verify();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n });\n });\n\n migrate\n .command(\"log\")\n .description(\"Print the append-only ledger\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--limit <n>\", \"Maximum events\", positiveInteger)\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; limit?: number; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const events = await migrations.log();\n printJson(\n opts.limit ? events.slice(-opts.limit) : events,\n Boolean(opts.json)\n );\n });\n });\n\n migrate\n .command(\"apply\")\n .description(\"Apply estate states to the target\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state id, prefix, or name\")\n .option(\"--via <stateId...>\", \"Force a path through these states\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.apply({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"down\")\n .description(\"Roll back along the recorded arrival path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Roll back to this state\")\n .option(\"--steps <n>\", \"Number of states to roll back\", positiveInteger)\n .option(\n \"--accept-data-loss\",\n \"Approve destructive changes the rollback makes to populated tables\"\n )\n .option(\n \"--expect-revision <n>\",\n \"Refuse unless the marker is at this revision\",\n positiveInteger\n )\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n steps?: number;\n acceptDataLoss?: boolean;\n expectRevision?: number;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations, config) => {\n if (opts.to !== undefined && opts.steps !== undefined)\n throw new Error(\"down accepts --to or --steps, not both\");\n const approve = generateResolver(config, opts);\n const common = {\n dryRun: opts.dryRun,\n ...(approve ? { resolve: approve } : {}),\n ...(opts.expectRevision === undefined\n ? {}\n : { expectRevision: opts.expectRevision }),\n };\n const result = await migrations.down(\n opts.to\n ? { to: selector(opts.to)!, ...common }\n : { steps: opts.steps, ...common }\n );\n if (!result.preview || opts.json) {\n printJson(result, Boolean(opts.json));\n } else {\n for (const edge of result.edges) process.stdout.write(edge.sql);\n if (result.refusal) {\n process.stderr.write(\n `down would refuse: ${result.refusal.code}: ${result.refusal.message}\\n`\n );\n }\n }\n // The preview fails where `down` would fail.\n if (result.preview && result.refusal) process.exitCode = 1;\n });\n }\n );\n\n migrate\n .command(\"baseline\")\n .description(\"Adopt an existing database as a known estate state\")\n .requiredOption(\"--to <selector>\", \"Existing estate state to adopt\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.baseline({\n to: selector(opts.to)!,\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"reanchor\")\n .description(\n \"After a restore left the history older than the database, move the marker to the state the live schema matches\"\n )\n .option(\"--to <selector>\", \"Adopt this state as the new baseline\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to?: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.reanchor({\n to: selector(opts.to),\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"resolve\")\n .description(\"Resolve an unfinished attempt after live proof\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--complete\", \"Mark complete when destination proof holds\")\n .option(\"--rolled-back\", \"Mark rolled back when origin proof holds\")\n .option(\"--retry\", \"Retry from the first proven incomplete step\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n complete?: boolean;\n rolledBack?: boolean;\n retry?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n if (\n [opts.complete, opts.rolledBack, opts.retry].filter(Boolean)\n .length !== 1\n )\n throw new Error(\n \"resolve requires exactly one of --complete, --rolled-back, or --retry\"\n );\n const outcome = opts.complete\n ? \"complete\"\n : opts.rolledBack\n ? \"rolled-back\"\n : \"retry\";\n printJson(await migrations.resolve({ outcome }), Boolean(opts.json));\n });\n }\n );\n\n migrate\n .command(\"reset\")\n .description(\n \"Clear managed objects and replay from empty to a selected state\"\n )\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state after rebuild\")\n .option(\"--via <stateId...>\", \"Force a rebuild path\")\n .option(\"--confirm\", \"Confirm destructive reset (not required for dry-run)\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n confirm?: boolean;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n if (!(opts.dryRun || opts.confirm))\n throw new Error(\n \"Reset requires --confirm; inspect --dry-run first\"\n );\n printJson(\n await migrations.reset({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n return migrate;\n}\n\nexport const migrateCommand = createMigrateCommand();\n","/**\n * `viborm pull --json`: an existing database → a schema document.\n *\n * The connection string is `--url`, else `DATABASE_URL` (read from `.env` like\n * every command). The document goes to `--out`, else to stdout, in canonical\n * form; what it does not carry, and where a push of it would change the\n * database, goes to stderr, so stdout stays a document a pipe can parse.\n *\n * `--json` is the only output today. A TypeScript schema will be written from\n * the same document, so the flag names the format rather than defaulting it.\n *\n * `--light` writes a light document (`introspectSchema({ light: true })`): what\n * a client needs, without indexes, which every migration path refuses.\n */\n\nimport { existsSync, writeFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { Command } from \"commander\";\nimport { introspectSchema } from \"../../migrations/introspect\";\nimport type {\n IntrospectionWarning,\n SkippedObject,\n} from \"../../migrations/introspect/types\";\nimport { failCli } from \"../utils\";\n\ninterface PullCliOptions {\n readonly url?: string;\n readonly json?: boolean;\n readonly out?: string;\n readonly tables?: readonly string[];\n readonly light?: boolean;\n}\n\nfunction located(item: {\n table?: string | undefined;\n name?: string | undefined;\n}) {\n return [item.table, item.name].filter(Boolean).join(\".\");\n}\n\n/** The report a human reads beside the document. */\nexport function formatPullReport(\n skipped: readonly SkippedObject[],\n warnings: readonly IntrospectionWarning[]\n): string {\n const lines: string[] = [];\n if (skipped.length > 0) {\n lines.push(`Not in the document (${skipped.length}):`);\n for (const item of skipped)\n lines.push(` - ${item.kind} ${located(item)}: ${item.reason}`);\n }\n if (warnings.length > 0) {\n lines.push(`Warnings (${warnings.length}):`);\n for (const warning of warnings)\n lines.push(\n ` - [${warning.kind}] ${located(warning)}: ${warning.message}`\n );\n }\n return lines.length === 0\n ? \"The document states the whole database; a push of it plans nothing.\\n\"\n : `${lines.join(\"\\n\")}\\n`;\n}\n\nasync function runPull(options: PullCliOptions): Promise<void> {\n try {\n if (!options.json)\n throw new Error(\n \"viborm pull writes a JSON schema document: pass --json. A TypeScript schema is not generated yet.\"\n );\n const envPath = resolve(process.cwd(), \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n const url = options.url ?? process.env.DATABASE_URL;\n if (!url)\n throw new Error(\n \"viborm pull needs a connection string: pass --url or set DATABASE_URL.\"\n );\n const result = await introspectSchema({\n url,\n ...(options.tables === undefined ? {} : { tables: options.tables }),\n ...(options.light ? { light: true } : {}),\n });\n const text = `${JSON.stringify(result.document, null, 2)}\\n`;\n if (options.out === undefined) process.stdout.write(text);\n else writeFileSync(resolve(process.cwd(), options.out), text);\n process.stderr.write(formatPullReport(result.skipped, result.warnings));\n } catch (error) {\n failCli(error, options.json === true);\n }\n}\n\nexport function createPullCommand(): Command {\n return new Command(\"pull\")\n .description(\n \"Read an existing database into a schema document (viborm/schema/json)\"\n )\n .option(\"--json\", \"Write the JSON schema document\")\n .option(\n \"--url <url>\",\n \"Connection string (postgres://, mysql://, file:, libsql://); defaults to DATABASE_URL\"\n )\n .option(\"--out <path>\", \"Write the document to this file instead of stdout\")\n .option(\n \"--light\",\n \"Only what a client needs (no indexes); migrations refuse the document\"\n )\n .option(\n \"--tables <names...>\",\n \"Only these tables (exact physical names, space- or comma-separated)\",\n (value: string, previous: string[] | undefined) => [\n ...(previous ?? []),\n ...value\n .split(\",\")\n .map((name) => name.trim())\n .filter(Boolean),\n ]\n )\n .action(runPull);\n}\n\nexport const pullCommand = createPullCommand();\n","/**\n * History-free, authenticated schema push CLI.\n *\n * The preview is inert. Effectful execution receives only the consent emitted\n * by that preview; no generic force authorization reaches the apply call.\n */\n\nimport { cancel, confirm, isCancel, note, outro } from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport { createMigrationClient } from \"../../migrations/client\";\nimport type { PushPreview } from \"../../migrations/push-v1\";\nimport { printJson, runCli } from \"../utils\";\n\ninterface PushCliOptions {\n readonly config?: string;\n readonly dryRun?: boolean;\n readonly forceReset?: boolean;\n readonly yes?: boolean;\n readonly acceptDataLoss?: boolean;\n readonly json?: boolean;\n}\n\nfunction printPlan(preview: PushPreview): void {\n const operations =\n preview.operations.length === 0\n ? [\"No schema changes.\"]\n : preview.operations.map(\n (operation) =>\n `[${operation.risk}] ${operation.label} (${operation.id})`\n );\n const statements = preview.statements.map(\n (statement, index) =>\n `${index + 1}. ${statement.sql}${\n statement.parameters.length === 0\n ? \"\"\n : `\\n parameters: ${JSON.stringify(statement.parameters)}`\n }`\n );\n const lines = [\n `Target: ${JSON.stringify(preview.target)}`,\n `Plan: ${preview.planHash}`,\n ...operations,\n ...(statements.length === 0 ? [] : [\"\", \"SQL:\", ...statements]),\n ];\n note(lines.join(\"\\n\"), \"Push plan\");\n}\n\nasync function runPush(options: PushCliOptions): Promise<void> {\n await runCli({ config: options.config }, options.json, async (config) => {\n const migrations =\n config.migrations?.tables === undefined\n ? createMigrationClient(config.client)\n : createMigrationClient(config.client, {\n tables: config.migrations.tables,\n });\n // `force` is confined to the inert planning arm. The authenticated apply\n // arm below receives only the consent bound to this exact preview.\n const preview = await migrations.push({\n dryRun: true,\n ...(options.forceReset === true ? { forceReset: true } : {}),\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n });\n\n if (\n !options.json &&\n config.driver?.dialect === \"sqlite\" &&\n [\"sqlite3\", \"bun-sqlite\", \"bun-sql\"].includes(config.driver.driverName)\n ) {\n const databases = await config.driver._executeRaw<{\n name: string;\n file: string;\n }>(\"PRAGMA database_list\");\n if (\n databases.rows.some(\n (database) => database.name === \"main\" && database.file === \"\"\n )\n )\n process.stderr.write(\n \"warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.\\n\"\n );\n }\n\n if (options.dryRun) {\n if (options.json) printJson(preview, true);\n else printPlan(preview);\n return;\n }\n\n if (!options.json) printPlan(preview);\n\n if (\n preview.destructive &&\n !options.acceptDataLoss &&\n (options.yes || options.json || !process.stdin.isTTY)\n ) {\n throw new Error(\n \"Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.\"\n );\n }\n if (\n preview.outcome !== \"noop\" &&\n !options.yes &&\n !options.acceptDataLoss &&\n !options.json &&\n process.stdin.isTTY\n ) {\n const accepted = await confirm({\n message: preview.destructive\n ? \"Apply this destructive push plan?\"\n : \"Apply this push plan?\",\n initialValue: !preview.destructive,\n });\n if (isCancel(accepted) || !accepted) {\n cancel(\"Push cancelled.\");\n return;\n }\n }\n\n const result = await migrations.push({ consent: preview.consent });\n if (options.json) printJson(result, true);\n else\n outro(\n result.outcome === \"noop\" ? \"Schema is up to date.\" : \"Push applied.\"\n );\n });\n}\n\nexport function createPushCommand(): Command {\n return new Command(\"push\")\n .description(\"Synchronize the schema directly without migration history\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--dry-run\", \"Preview without changing the database\")\n .option(\"--force-reset\", \"Plan a rebuild from an empty database\")\n .option(\"-y, --yes\", \"Skip prompts for non-destructive plans\")\n .option(\n \"--accept-data-loss\",\n \"Explicitly accept the previewed destructive plan\"\n )\n .option(\"--json\", \"Print machine-readable JSON\")\n .action(runPush);\n}\n\nexport const pushCommand = createPushCommand();\n","#!/usr/bin/env node\n/**\n * VibORM CLI\n *\n * Command-line interface for VibORM database operations.\n */\n\nimport { Command } from \"commander\";\nimport { registerEveryMigrationDriver } from \"../migrations/dialects/every\";\nimport { VIBORM_VERSION } from \"../version\";\nimport { checkCommand } from \"./commands/check\";\nimport { migrateCommand } from \"./commands/migrate\";\nimport { pullCommand } from \"./commands/pull\";\nimport { pushCommand } from \"./commands/push\";\n\nregisterEveryMigrationDriver();\n\nconst program = new Command();\n\nprogram\n .name(\"viborm\")\n .description(\"VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite\")\n .version(VIBORM_VERSION);\n\n// Register commands\nprogram.addCommand(checkCommand);\nprogram.addCommand(pushCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(pullCommand);\n\n// Parse arguments\ntry {\n await program.parseAsync();\n} catch (error: unknown) {\n process.stderr.write(\n `${error instanceof Error ? error.message : \"CLI failed\"}\\n`\n );\n process.exitCode = 1;\n}\n\n// The command settled and its client was closed (`runCli`): the process ends\n// here, whatever a driver left open. A socket a server never finishes closing\n// (SurrealDB Cloud does not answer a WebSocket's closing handshake) otherwise\n// kept `push` alive for good after it had printed its outcome. What is still\n// buffered (a pipe is written asynchronously outside Linux) goes out first.\nfor (const stream of [process.stdout, process.stderr])\n if (stream.writableLength > 0)\n await new Promise<void>((resolve) => stream.write(\"\", () => resolve()));\nprocess.exit();\n"],"mappings":";0+BA2CA,MAAM,EAAe,GACnB,EAAM,OAAS,UAAY,CAAC,EAAM,QAAU,EAAM,eAAiB,EAE/D,EAAiB,GAAsC,CAC3D,IAAM,EAAS,cAAc,EAAM,MAAM,KAAK,EAAM,OAAO,GAC3D,IAAK,EAAM,OAAS,UAAY,EAAM,SAAW,EAAM,gBAAkB,KACvE,MAAO,GAAG,EAAO,yGACnB,GAAI,EAAM,OAAS,UACjB,MAAO,GAAG,EAAO,aAAa,EAAM,SAAS,wRAC/C,IAAM,EAAO,EAAM,OAAS,OAAS,OAAS,WACxC,EAAS,EAAM,KACjB,uFACA,8BAA8B,EAAK,mCACvC,MAAO,GAAG,EAAO,IAAI,EAAM,aAAa,0BAA0B,EAAK,uCAAuC,EAAO,+FAIjH,EAAa,GAAiC,CAClD,IAAM,EAAQ,OAAO,OAAO,EAAO,CAAC,OACjC,GAAU,EAAU,EAAM,GAAK,IAAA,GACjC,CAAC,OACI,EAAS,GAAG,OAAO,KAAK,EAAO,CAAC,OAAS,EAAM,SAErD,OADI,IAAU,EAAU,EACjB,GAAG,EAAO,IAAI,EAAM,GAAG,IAAU,EAAI,OAAS,WAIjD,EAAY,GAChB,CAAC,IAAI,EAAM,KAAK,IAAI,EAAM,UAAW,EAAM,OAAO,CAC/C,OAAO,QA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iB,wCAAwC,CAChE,OAAO,YAAa,yCAAyC,CAC7D,OACC,qBACA,mDACD,CACA,OAAO,SAAU,8BAA8B,CAC/C,OAAO,EAAQ,CAGpB,MAAa,GAAc,IAAmB,CCjI9C,GAA8B,CAE9B,MAAM,EAAU,IAAI,EAEpB,EACG,KAAK,SAAS,CACd,YAAY,0DAA0D,CACtE,QAAQ,EAAe,CAG1B,EAAQ,WAAW,EAAa,CAChC,EAAQ,WAAW,GAAY,CAC/B,EAAQ,WAAW,EAAe,CAClC,EAAQ,WAAW,GAAY,CAG/B,GAAI,CACF,MAAM,EAAQ,YAAY,OACnB,EAAgB,CACvB,QAAQ,OAAO,MACb,GAAG,aAAiB,MAAQ,EAAM,QAAU,aAAa,IAC1D,CACD,QAAQ,SAAW,EAQrB,IAAK,IAAM,IAAU,CAAC,QAAQ,OAAQ,QAAQ,OAAO,CAC/C,EAAO,eAAiB,GAC1B,MAAM,IAAI,QAAe,GAAY,EAAO,MAAM,OAAUA,GAAS,CAAC,CAAC,CAC3E,QAAQ,MAAM"}
1
+ {"version":3,"file":"cli.mjs","names":["resolve"],"sources":["../src/cli/commands/check.ts","../src/cli/commands/migrate.ts","../src/cli/commands/pull.ts","../src/cli/commands/push.ts","../src/cli/index.ts"],"sourcesContent":["/**\n * Schema check CLI.\n *\n * Runs every check a client runs when it is created (identifiers, model\n * identity, relation resolution, selector names), plus the advisory rules and\n * the query of every view, against the schema of the configured client. Run it in a build or CI step to\n * create clients with `skipSchemaValidation: true` at runtime.\n */\n\nimport { Command } from \"commander\";\nimport type { AnyDriver } from \"../../drivers/driver\";\nimport { getMigrationDriver } from \"../../migrations/drivers\";\nimport type {\n MigrationDriver,\n ViewWriter,\n} from \"../../migrations/drivers/base\";\nimport { mysqlMigrationDriver } from \"../../migrations/drivers/mysql\";\nimport { postgresMigrationDriver } from \"../../migrations/drivers/postgres\";\nimport { sqlite3MigrationDriver } from \"../../migrations/drivers/sqlite\";\nimport type { Dialect } from \"../../migrations/drivers/types\";\nimport { serializeModels } from \"../../migrations/serializer\";\nimport {\n auditStorage,\n type StorageColumnAudit,\n} from \"../../migrations/sqlite-storage-audit\";\nimport { writeView } from \"../../migrations/view-definition\";\nimport { hydrateSchemaNames } from \"../../schema/hydration\";\nimport type {\n SchemaValidationIssue,\n ValidationResult,\n} from \"../../schema/validation/types\";\nimport { validateSchema } from \"../../schema/validation/validator\";\nimport { viewFacts } from \"../../schema/view/facts\";\nimport { type LoadedConfig, runCli } from \"../utils\";\n\ntype LoadedModels = LoadedConfig[\"models\"];\n\ninterface CheckCliOptions {\n readonly config?: string;\n readonly json?: boolean;\n readonly db?: boolean;\n}\n\nconst needsRepair = (audit: StorageColumnAudit): boolean =>\n audit.type === \"decimal\" ? !audit.checked : audit.noncanonical !== 0;\n\nconst describeAudit = (audit: StorageColumnAudit): string => {\n const column = `[storage] \"${audit.table}\".\"${audit.column}\"`;\n if ((audit.type === \"decimal\" ? audit.declared : audit.noncanonical) === null)\n return `${column}: the column is missing; typed queries that use it fail.\\n Create it through viborm push or migrate.`;\n if (audit.type === \"decimal\")\n return `${column}: declared ${audit.declared}, not the checked scaled-integer decimal storage VibORM writes; typed reads, filters and writes are not checked against it.\\n Adopt the table through viborm push, migrate or baseline: https://viborm.dev/docs/migration/drivers/sqlite#adopting-decimal-columns-from-another-tool`;\n const kind = audit.type === \"time\" ? \"Time\" : \"DateTime\";\n const repair = audit.list\n ? \"Rewrite each row through the typed client (`update`), which stores canonical members\"\n : `Repair with sqliteCanonical${kind}Expression from viborm/migrations`;\n return `${column}: ${audit.noncanonical} row(s) of noncanonical ${kind} text compare and sort wrongly.\\n ${repair}: https://viborm.dev/docs/migration/drivers/sqlite#repairing-foreign-timestamp-and-time-text`;\n};\n\n/** How many models and how many database views a valid schema holds. */\nconst summarize = (models: LoadedModels): string => {\n const views = Object.values(models).filter(\n (model) => viewFacts(model) !== undefined\n ).length;\n const tables = `${Object.keys(models).length - views} models`;\n if (views === 0) return tables;\n return `${tables}, ${views} ${views === 1 ? \"view\" : \"views\"}`;\n};\n\n// The repair hint, when the issue has one, goes on its own indented line.\nconst describe = (issue: SchemaValidationIssue): string =>\n [`[${issue.code}] ${issue.message}`, issue.repair]\n .filter(Boolean)\n .join(\"\\n \");\n\n/**\n * Who writes a view's body, per dialect VibORM creates views on: on SurrealDB\n * the read backend of the configured driver, which its migration binds to.\n */\nconst VIEW_WRITERS: Partial<\n Record<Dialect, (driver: AnyDriver) => ViewWriter | undefined>\n> = {\n postgresql: () => postgresMigrationDriver.viewWriter(),\n mysql: () => mysqlMigrationDriver.viewWriter(),\n sqlite: () => sqlite3MigrationDriver.viewWriter(),\n surrealql: (driver) => getMigrationDriver(driver).viewWriter(),\n};\n\n/**\n * What a view's query is refused for (W005), found by compiling its body as\n * a migration would: a clause a view cannot hold, or a query its source does\n * not take. Asked of a schema whose relations resolve, on a dialect VibORM\n * creates views on.\n */\nfunction withViewQueries(\n result: ValidationResult,\n { models, driver }: LoadedConfig\n): ValidationResult {\n const writer = result.valid ? VIEW_WRITERS[driver.dialect] : undefined;\n if (writer === undefined) return result;\n const errors = [...result.errors];\n for (const [model, view] of Object.entries(models)) {\n if (viewFacts(view) === undefined) continue;\n try {\n const written = writer(driver);\n if (written) writeView(written, { schema: models }, view);\n } catch (cause) {\n errors.push({\n code: \"W005\",\n message: cause instanceof Error ? cause.message : String(cause),\n severity: \"error\",\n model,\n });\n }\n }\n // What a view kept by triggers needs of the schema's other tables (MySQL's\n // cascades) is read off the whole schema, as a migration serializes it.\n const cascades = errors.length === 0 && AUTO_CASCADES[driver.dialect];\n if (\n cascades &&\n Object.values(models).some((model) => viewFacts(model)?.refresh === \"auto\")\n )\n try {\n serializeModels(models, { migrationDriver: cascades() });\n } catch (cause) {\n const meta = (cause as { meta?: { feature?: string; model?: string } })\n .meta;\n if (meta?.model === undefined) throw cause;\n errors.push({\n code: \"W005\",\n message: (cause as Error).message,\n severity: \"error\",\n model:\n Object.keys(models).find(\n (key) => models[key]![\"~\"].names.sql === meta.model\n ) ??\n meta.model ??\n \"\",\n });\n }\n return { ...result, errors, valid: errors.length === 0 };\n}\n\n/** The dialects whose cascades a view kept by triggers must follow itself. */\nconst AUTO_CASCADES: Partial<Record<Dialect, () => MigrationDriver>> = {\n mysql: () => mysqlMigrationDriver,\n};\n\nasync function runCheck(options: CheckCliOptions): Promise<void> {\n const load = { config: options.config, skipValidation: true };\n await runCli(load, options.json, async (config) => {\n const { models } = config;\n // The identifier and identity checks hydration runs, whatever the\n // configured client skipped.\n hydrateSchemaNames(models);\n const result = withViewQueries(validateSchema(models), config);\n const storage = options.db\n ? await auditStorage({ $driver: config.driver, $schema: models })\n : undefined;\n const dirty = storage?.filter(needsRepair) ?? [];\n if (options.json) {\n process.stdout.write(\n `${JSON.stringify(storage ? { ...result, storage } : result, null, 2)}\\n`\n );\n } else {\n for (const issue of result.errors)\n process.stderr.write(`error ${describe(issue)}\\n`);\n for (const issue of result.warnings)\n process.stderr.write(`warning ${describe(issue)}\\n`);\n for (const audit of dirty)\n process.stderr.write(`error ${describeAudit(audit)}\\n`);\n process.stdout.write(\n result.valid\n ? `Schema valid (${summarize(models)}).\\n`\n : `Schema invalid: ${result.errors.length} error(s).\\n`\n );\n if (storage)\n process.stdout.write(\n `Storage audited: ${storage.length} column(s), ${dirty.length} need repair.\\n`\n );\n }\n if (!result.valid || dirty.length > 0) process.exitCode = 1;\n });\n}\n\nexport function createCheckCommand(): Command {\n return new Command(\"check\")\n .description(\n \"Validate the schema, so clients can be created with skipSchemaValidation\"\n )\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--json\", \"Print machine-readable JSON\")\n .option(\n \"--db\",\n \"Also audit SQLite storage: DateTime/Time text and decimal columns\"\n )\n .action(runCheck);\n}\n\nexport const checkCommand = createCheckCommand();\n","/**\n * Migration CLI. Composition root is createMigrationClient + loadConfig.\n */\n\nimport { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { confirm, isCancel } from \"@clack/prompts\";\nimport { Command, InvalidArgumentError } from \"commander\";\nimport {\n createMigrationClient,\n type WritableMigrations,\n} from \"../../migrations/client\";\nimport { loadMigrationGraph } from \"../../migrations/graph\";\nimport { isSha256 } from \"../../migrations/identity\";\nimport { renderMigrationReview } from \"../../migrations/public-view\";\nimport { formatOperation } from \"../../migrations/push/format\";\nimport type { MigrationStorageWriter } from \"../../migrations/storage/contract\";\nimport { createFsStorageWriter } from \"../../migrations/storage/fs-estate\";\nimport type { ResolveCallback } from \"../../migrations/types\";\nimport type {\n ManualMigrationInput,\n StateSelector,\n} from \"../../migrations/v1-types\";\nimport { type LoadedConfig, loadCliModule, printJson, runCli } from \"../utils\";\n\nconst STATE_ID_PREFIX = /^[0-9a-f]{8,63}$/;\n\nfunction positiveInteger(value: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(\"must be a positive safe integer\");\n }\n return parsed;\n}\n\nfunction selector(value: string | undefined): StateSelector | undefined {\n if (!value) return undefined;\n if (isSha256(value)) return { id: value };\n if (STATE_ID_PREFIX.test(value)) return { prefix: value };\n return { name: value };\n}\n\n/** `--accept-data-loss`: every destructive change approved, nothing else decided. */\nconst approveDestructive: ResolveCallback = (change) =>\n change.type === \"destructive\" ? change.proceed() : undefined;\n\n/** One prompt per destructive change, as `viborm push` asks for its plan. */\nconst confirmDestructive: ResolveCallback = async (change) => {\n if (change.type !== \"destructive\") return;\n const approved = await confirm({\n message: `${change.description} — approve?`,\n initialValue: false,\n });\n return !isCancel(approved) && approved ? change.proceed() : change.reject();\n};\n\n/**\n * The resolver `migrate generate` publishes under, and `migrate down` rolls\n * back under: the config's own, else\n * `--accept-data-loss`, else a prompt on an interactive terminal. With none,\n * generate refuses a destructive change with `V11017`.\n */\nfunction generateResolver(\n config: LoadedConfig,\n opts: { acceptDataLoss?: boolean; dryRun?: boolean; json?: boolean }\n): ResolveCallback | undefined {\n if (config.migrations?.resolve) return config.migrations.resolve;\n if (opts.acceptDataLoss) return approveDestructive;\n if (opts.dryRun || opts.json || !process.stdin.isTTY) return;\n return confirmDestructive;\n}\n\n/** Each subcommand reads the parent's `--config` and its own `--dir`. */\nasync function withMigrations(\n migrate: Command,\n options: { dir?: string; json?: boolean },\n run: (\n migrations: WritableMigrations,\n config: LoadedConfig,\n storage: MigrationStorageWriter\n ) => Promise<void>\n): Promise<void> {\n await runCli(\n { config: migrate.opts<{ config?: string }>().config },\n options.json,\n async (config) => {\n const directory = resolve(\n options.dir ?? config.migrations?.dir ?? \"./migrations\"\n );\n const storage =\n config.migrations?.storage ?? createFsStorageWriter(directory);\n const migrations = createMigrationClient(config.client, {\n storage,\n ...(config.migrations?.tables === undefined\n ? {}\n : { tables: config.migrations.tables }),\n });\n await run(migrations, config, storage);\n }\n );\n}\n\nexport function createMigrateCommand(): Command {\n const migrate = new Command(\"migrate\")\n .description(\"Manage the authenticated migration estate\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\");\n\n migrate\n .command(\"generate\")\n .description(\"Publish a new estate state from the current schema\")\n .option(\"-n, --name <name>\", \"Human-readable state label\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\n \"--from <stateId>\",\n \"Parent state id, or empty for the virtual root\"\n )\n .option(\"--custom <path>\", \"Compile a TypeScript manual migration author\")\n .option(\n \"--review <path>\",\n \"Write labelled forward/check/rollback review SQL\"\n )\n .option(\"--dry-run\", \"Preview without publishing\")\n .option(\n \"--low-lock\",\n \"PostgreSQL: publish index builds and foreign keys on existing tables as recoverable steps\"\n )\n .option(\n \"--accept-data-loss\",\n \"Approve destructive changes (drops, type changes) for this generate\"\n )\n .option(\n \"--adopt <table...>\",\n \"Adopt existing listed tables without DDL; apply proves each equals its declaration\"\n )\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n adopt?: string[];\n name?: string;\n dir?: string;\n from?: string;\n dryRun?: boolean;\n lowLock?: boolean;\n acceptDataLoss?: boolean;\n custom?: string;\n review?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations, config) => {\n const from =\n opts.from === undefined\n ? undefined\n : opts.from === \"\" || opts.from === \"empty\"\n ? null\n : isSha256(opts.from)\n ? opts.from\n : (await migrations.show(selector(opts.from)!)).stateId;\n let manualMigration: ManualMigrationInput | undefined;\n if (opts.custom) {\n type Author =\n | ManualMigrationInput\n | ((\n parents: readonly (string | null)[]\n ) => ManualMigrationInput | Promise<ManualMigrationInput>);\n const module = await loadCliModule<{\n default?: Author;\n migration?: Author;\n }>(resolve(opts.custom));\n const author =\n (Object.hasOwn(module, \"default\") ? module.default : undefined) ??\n module.migration;\n if (!author)\n throw new Error(\n \"A custom migration module must export a default migration or author function\"\n );\n const graph = await migrations.graph();\n const parents = Object.freeze(\n from === undefined\n ? graph.leaves.length === 0\n ? [null]\n : [...graph.leaves]\n : [from]\n );\n manualMigration =\n typeof author === \"function\" ? await author(parents) : author;\n }\n const approve = generateResolver(config, opts);\n const result = await migrations.generate({\n name: opts.name,\n from,\n dryRun: opts.dryRun,\n ...(opts.lowLock ? { lowLock: true } : {}),\n ...(opts.adopt ? { adopt: opts.adopt } : {}),\n ...(approve ? { resolve: approve } : {}),\n ...(manualMigration ? { manualMigration } : {}),\n });\n if (opts.json) printJson(result, true);\n else {\n process.stdout.write(\n `${result.outcome}: ${result.name ?? \"No schema changes\"}${result.stateId ? ` (${result.stateId})` : \"\"}\\n`\n );\n for (const parent of result.operationsByParent ?? []) {\n process.stdout.write(\n `Parent ${parent.fromState ?? \"empty\"}:\\n${parent.operations.map(formatOperation).join(\"\\n\")}\\n`\n );\n }\n for (const warning of result.warnings ?? [])\n process.stderr.write(`warning: ${warning}\\n`);\n if (result.reviewSql || result.sql)\n process.stdout.write(`${result.reviewSql || result.sql}\\n`);\n }\n if (opts.review && result.reviewSql)\n await writeFile(resolve(opts.review), result.reviewSql, \"utf8\");\n });\n }\n );\n\n migrate\n .command(\"check\")\n .description(\"Validate estate artifacts without touching the database\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const result = await migrations.check();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n });\n });\n\n migrate\n .command(\"list\")\n .description(\"List estate states\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.list(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"show\")\n .description(\"Show one estate state\")\n .argument(\"<state>\", \"State id, unambiguous prefix, or name\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--sql\", \"Print labelled forward/check/rollback review SQL\")\n .option(\"--review <path>\", \"Write review SQL to this file\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (\n state: string,\n opts: { dir?: string; sql?: boolean; review?: string; json?: boolean }\n ) => {\n await withMigrations(\n migrate,\n opts,\n async (migrations, _config, storage) => {\n const details = await migrations.show(selector(state)!);\n if (!(opts.sql || opts.review)) {\n printJson(details, Boolean(opts.json));\n return;\n }\n const graph = await loadMigrationGraph(storage);\n const manifest = graph.states.get(details.stateId);\n const blob = manifest && graph.sql.get(manifest.sqlHash);\n if (!(manifest && blob))\n throw new Error(\"The authenticated state SQL is unavailable\");\n const reviewSql = renderMigrationReview(\n manifest.parents,\n manifest.destinationChecks,\n blob\n );\n if (opts.json) printJson({ ...details, reviewSql }, true);\n else {\n printJson(details, false);\n process.stdout.write(reviewSql);\n }\n if (opts.review)\n await writeFile(resolve(opts.review), reviewSql, \"utf8\");\n }\n );\n }\n );\n\n migrate\n .command(\"graph\")\n .description(\"Print estate roots and leaves\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.graph(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"status\")\n .description(\"Show marker, pending path, and unfinished attempts\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(await migrations.status(), Boolean(opts.json));\n });\n });\n\n migrate\n .command(\"verify\")\n .description(\"Lock and compare the live schema to the marker\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const result = await migrations.verify();\n printJson(result, Boolean(opts.json));\n if (!result.ok) process.exitCode = 1;\n });\n });\n\n migrate\n .command(\"log\")\n .description(\"Print the append-only ledger\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--limit <n>\", \"Maximum events\", positiveInteger)\n .option(\"--json\", \"Print machine-readable output\")\n .action(async (opts: { dir?: string; limit?: number; json?: boolean }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n const events = await migrations.log();\n printJson(\n opts.limit ? events.slice(-opts.limit) : events,\n Boolean(opts.json)\n );\n });\n });\n\n migrate\n .command(\"apply\")\n .description(\"Apply estate states to the target\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state id, prefix, or name\")\n .option(\"--via <stateId...>\", \"Force a path through these states\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.apply({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"down\")\n .description(\"Roll back along the recorded arrival path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Roll back to this state\")\n .option(\"--steps <n>\", \"Number of states to roll back\", positiveInteger)\n .option(\n \"--accept-data-loss\",\n \"Approve destructive changes the rollback makes to populated tables\"\n )\n .option(\n \"--expect-revision <n>\",\n \"Refuse unless the marker is at this revision\",\n positiveInteger\n )\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n steps?: number;\n acceptDataLoss?: boolean;\n expectRevision?: number;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations, config) => {\n if (opts.to !== undefined && opts.steps !== undefined)\n throw new Error(\"down accepts --to or --steps, not both\");\n const approve = generateResolver(config, opts);\n const common = {\n dryRun: opts.dryRun,\n ...(approve ? { resolve: approve } : {}),\n ...(opts.expectRevision === undefined\n ? {}\n : { expectRevision: opts.expectRevision }),\n };\n const result = await migrations.down(\n opts.to\n ? { to: selector(opts.to)!, ...common }\n : { steps: opts.steps, ...common }\n );\n if (!result.preview || opts.json) {\n printJson(result, Boolean(opts.json));\n } else {\n for (const edge of result.edges) process.stdout.write(edge.sql);\n if (result.refusal) {\n process.stderr.write(\n `down would refuse: ${result.refusal.code}: ${result.refusal.message}\\n`\n );\n }\n }\n // The preview fails where `down` would fail.\n if (result.preview && result.refusal) process.exitCode = 1;\n });\n }\n );\n\n migrate\n .command(\"baseline\")\n .description(\"Adopt an existing database as a known estate state\")\n .requiredOption(\"--to <selector>\", \"Existing estate state to adopt\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.baseline({\n to: selector(opts.to)!,\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"reanchor\")\n .description(\n \"After a restore left the history older than the database, move the marker to the state the live schema matches\"\n )\n .option(\"--to <selector>\", \"Adopt this state as the new baseline\")\n .option(\"--via <stateId...>\", \"Force the recorded root path\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n to?: string;\n via?: string[];\n dir?: string;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n printJson(\n await migrations.reanchor({\n to: selector(opts.to),\n via: opts.via,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n migrate\n .command(\"resolve\")\n .description(\"Resolve an unfinished attempt after live proof\")\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--complete\", \"Mark complete when destination proof holds\")\n .option(\"--rolled-back\", \"Mark rolled back when origin proof holds\")\n .option(\"--retry\", \"Retry from the first proven incomplete step\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n complete?: boolean;\n rolledBack?: boolean;\n retry?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n if (\n [opts.complete, opts.rolledBack, opts.retry].filter(Boolean)\n .length !== 1\n )\n throw new Error(\n \"resolve requires exactly one of --complete, --rolled-back, or --retry\"\n );\n const outcome = opts.complete\n ? \"complete\"\n : opts.rolledBack\n ? \"rolled-back\"\n : \"retry\";\n printJson(await migrations.resolve({ outcome }), Boolean(opts.json));\n });\n }\n );\n\n migrate\n .command(\"reset\")\n .description(\n \"Clear managed objects and replay from empty to a selected state\"\n )\n .option(\"-d, --dir <dir>\", \"Estate directory\")\n .option(\"--to <selector>\", \"Target state after rebuild\")\n .option(\"--via <stateId...>\", \"Force a rebuild path\")\n .option(\"--confirm\", \"Confirm destructive reset (not required for dry-run)\")\n .option(\"--dry-run\", \"Plan without executing\")\n .option(\"--json\", \"Print machine-readable output\")\n .action(\n async (opts: {\n dir?: string;\n to?: string;\n via?: string[];\n confirm?: boolean;\n dryRun?: boolean;\n json?: boolean;\n }) => {\n await withMigrations(migrate, opts, async (migrations) => {\n if (!(opts.dryRun || opts.confirm))\n throw new Error(\n \"Reset requires --confirm; inspect --dry-run first\"\n );\n printJson(\n await migrations.reset({\n to: selector(opts.to),\n via: opts.via,\n dryRun: opts.dryRun,\n }),\n Boolean(opts.json)\n );\n });\n }\n );\n\n return migrate;\n}\n\nexport const migrateCommand = createMigrateCommand();\n","/**\n * `viborm pull --json`: an existing database → a schema document.\n *\n * The connection string is `--url`, else `DATABASE_URL` (read from `.env` like\n * every command). The document goes to `--out`, else to stdout, in canonical\n * form; what it does not carry, and where a push of it would change the\n * database, goes to stderr, so stdout stays a document a pipe can parse.\n *\n * `--json` is the only output today. A TypeScript schema will be written from\n * the same document, so the flag names the format rather than defaulting it.\n *\n * `--light` writes a light document (`introspectSchema({ light: true })`): what\n * a client needs, without indexes, which every migration path refuses.\n */\n\nimport { existsSync, writeFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { loadEnvFile } from \"node:process\";\nimport { Command } from \"commander\";\nimport { introspectSchema } from \"../../migrations/introspect\";\nimport type {\n IntrospectionWarning,\n SkippedObject,\n} from \"../../migrations/introspect/types\";\nimport { failCli } from \"../utils\";\n\ninterface PullCliOptions {\n readonly url?: string;\n readonly json?: boolean;\n readonly out?: string;\n readonly tables?: readonly string[];\n readonly light?: boolean;\n}\n\nfunction located(item: {\n table?: string | undefined;\n name?: string | undefined;\n}) {\n return [item.table, item.name].filter(Boolean).join(\".\");\n}\n\n/** The report a human reads beside the document. */\nexport function formatPullReport(\n skipped: readonly SkippedObject[],\n warnings: readonly IntrospectionWarning[]\n): string {\n const lines: string[] = [];\n if (skipped.length > 0) {\n lines.push(`Not in the document (${skipped.length}):`);\n for (const item of skipped)\n lines.push(` - ${item.kind} ${located(item)}: ${item.reason}`);\n }\n if (warnings.length > 0) {\n lines.push(`Warnings (${warnings.length}):`);\n for (const warning of warnings)\n lines.push(\n ` - [${warning.kind}] ${located(warning)}: ${warning.message}`\n );\n }\n return lines.length === 0\n ? \"The document states the whole database; a push of it plans nothing.\\n\"\n : `${lines.join(\"\\n\")}\\n`;\n}\n\nasync function runPull(options: PullCliOptions): Promise<void> {\n try {\n if (!options.json)\n throw new Error(\n \"viborm pull writes a JSON schema document: pass --json. A TypeScript schema is not generated yet.\"\n );\n const envPath = resolve(process.cwd(), \".env\");\n if (existsSync(envPath)) loadEnvFile(envPath);\n const url = options.url ?? process.env.DATABASE_URL;\n if (!url)\n throw new Error(\n \"viborm pull needs a connection string: pass --url or set DATABASE_URL.\"\n );\n const result = await introspectSchema({\n url,\n ...(options.tables === undefined ? {} : { tables: options.tables }),\n ...(options.light ? { light: true } : {}),\n });\n const text = `${JSON.stringify(result.document, null, 2)}\\n`;\n if (options.out === undefined) process.stdout.write(text);\n else writeFileSync(resolve(process.cwd(), options.out), text);\n process.stderr.write(formatPullReport(result.skipped, result.warnings));\n } catch (error) {\n failCli(error, options.json === true);\n }\n}\n\nexport function createPullCommand(): Command {\n return new Command(\"pull\")\n .description(\n \"Read an existing database into a schema document (viborm/schema/json)\"\n )\n .option(\"--json\", \"Write the JSON schema document\")\n .option(\n \"--url <url>\",\n \"Connection string (postgres://, mysql://, file:, libsql://); defaults to DATABASE_URL\"\n )\n .option(\"--out <path>\", \"Write the document to this file instead of stdout\")\n .option(\n \"--light\",\n \"Only what a client needs (no indexes); migrations refuse the document\"\n )\n .option(\n \"--tables <names...>\",\n \"Only these tables (exact physical names, space- or comma-separated)\",\n (value: string, previous: string[] | undefined) => [\n ...(previous ?? []),\n ...value\n .split(\",\")\n .map((name) => name.trim())\n .filter(Boolean),\n ]\n )\n .action(runPull);\n}\n\nexport const pullCommand = createPullCommand();\n","/**\n * History-free, authenticated schema push CLI.\n *\n * The preview is inert. Effectful execution receives only the consent emitted\n * by that preview; no generic force authorization reaches the apply call.\n */\n\nimport { cancel, confirm, isCancel, note, outro } from \"@clack/prompts\";\nimport { Command } from \"commander\";\nimport { createMigrationClient } from \"../../migrations/client\";\nimport type { PushPreview } from \"../../migrations/push-v1\";\nimport { printJson, runCli } from \"../utils\";\n\ninterface PushCliOptions {\n readonly config?: string;\n readonly dryRun?: boolean;\n readonly forceReset?: boolean;\n readonly yes?: boolean;\n readonly acceptDataLoss?: boolean;\n readonly json?: boolean;\n}\n\nfunction printPlan(preview: PushPreview): void {\n const operations =\n preview.operations.length === 0\n ? [\"No schema changes.\"]\n : preview.operations.map(\n (operation) =>\n `[${operation.risk}] ${operation.label} (${operation.id})`\n );\n const statements = preview.statements.map(\n (statement, index) =>\n `${index + 1}. ${statement.sql}${\n statement.parameters.length === 0\n ? \"\"\n : `\\n parameters: ${JSON.stringify(statement.parameters)}`\n }`\n );\n const lines = [\n `Target: ${JSON.stringify(preview.target)}`,\n `Plan: ${preview.planHash}`,\n ...operations,\n ...(statements.length === 0 ? [] : [\"\", \"SQL:\", ...statements]),\n ];\n note(lines.join(\"\\n\"), \"Push plan\");\n}\n\nasync function runPush(options: PushCliOptions): Promise<void> {\n await runCli({ config: options.config }, options.json, async (config) => {\n const migrations =\n config.migrations?.tables === undefined\n ? createMigrationClient(config.client)\n : createMigrationClient(config.client, {\n tables: config.migrations.tables,\n });\n // `force` is confined to the inert planning arm. The authenticated apply\n // arm below receives only the consent bound to this exact preview.\n const preview = await migrations.push({\n dryRun: true,\n ...(options.forceReset === true ? { forceReset: true } : {}),\n ...(config.migrations?.resolve\n ? { resolve: config.migrations.resolve }\n : {}),\n });\n\n if (\n !options.json &&\n config.driver?.dialect === \"sqlite\" &&\n [\"sqlite3\", \"bun-sqlite\", \"bun-sql\"].includes(config.driver.driverName)\n ) {\n const databases = await config.driver._executeRaw<{\n name: string;\n file: string;\n }>(\"PRAGMA database_list\");\n if (\n databases.rows.some(\n (database) => database.name === \"main\" && database.file === \"\"\n )\n )\n process.stderr.write(\n \"warning: SQLite reports an in-memory main database. Use a persistent target for durable schema changes.\\n\"\n );\n }\n\n if (options.dryRun) {\n if (options.json) printJson(preview, true);\n else printPlan(preview);\n return;\n }\n\n if (!options.json) printPlan(preview);\n\n if (\n preview.destructive &&\n !options.acceptDataLoss &&\n (options.yes || options.json || !process.stdin.isTTY)\n ) {\n throw new Error(\n \"Destructive push requires --accept-data-loss; --yes does not authorize data loss. Inspect --dry-run first.\"\n );\n }\n if (\n preview.outcome !== \"noop\" &&\n !options.yes &&\n !options.acceptDataLoss &&\n !options.json &&\n process.stdin.isTTY\n ) {\n const accepted = await confirm({\n message: preview.destructive\n ? \"Apply this destructive push plan?\"\n : \"Apply this push plan?\",\n initialValue: !preview.destructive,\n });\n if (isCancel(accepted) || !accepted) {\n cancel(\"Push cancelled.\");\n return;\n }\n }\n\n const result = await migrations.push({ consent: preview.consent });\n if (options.json) printJson(result, true);\n else\n outro(\n result.outcome === \"noop\" ? \"Schema is up to date.\" : \"Push applied.\"\n );\n });\n}\n\nexport function createPushCommand(): Command {\n return new Command(\"push\")\n .description(\"Synchronize the schema directly without migration history\")\n .option(\"--config <path>\", \"Path to viborm.config.ts\")\n .option(\"--dry-run\", \"Preview without changing the database\")\n .option(\"--force-reset\", \"Plan a rebuild from an empty database\")\n .option(\"-y, --yes\", \"Skip prompts for non-destructive plans\")\n .option(\n \"--accept-data-loss\",\n \"Explicitly accept the previewed destructive plan\"\n )\n .option(\"--json\", \"Print machine-readable JSON\")\n .action(runPush);\n}\n\nexport const pushCommand = createPushCommand();\n","#!/usr/bin/env node\n/**\n * VibORM CLI\n *\n * Command-line interface for VibORM database operations.\n */\n\nimport { Command } from \"commander\";\nimport { registerEveryMigrationDriver } from \"../migrations/dialects/every\";\nimport { VIBORM_VERSION } from \"../version\";\nimport { checkCommand } from \"./commands/check\";\nimport { migrateCommand } from \"./commands/migrate\";\nimport { pullCommand } from \"./commands/pull\";\nimport { pushCommand } from \"./commands/push\";\n\nregisterEveryMigrationDriver();\n\nconst program = new Command();\n\nprogram\n .name(\"viborm\")\n .description(\"VibORM - Type-safe ORM for PostgreSQL, MySQL and SQLite\")\n .version(VIBORM_VERSION);\n\n// Register commands\nprogram.addCommand(checkCommand);\nprogram.addCommand(pushCommand);\nprogram.addCommand(migrateCommand);\nprogram.addCommand(pullCommand);\n\n// Parse arguments\ntry {\n await program.parseAsync();\n} catch (error: unknown) {\n process.stderr.write(\n `${error instanceof Error ? error.message : \"CLI failed\"}\\n`\n );\n process.exitCode = 1;\n}\n\n// The command settled and its client was closed (`runCli`): the process ends\n// here, whatever a driver left open. A socket a server never finishes closing\n// (SurrealDB Cloud does not answer a WebSocket's closing handshake) otherwise\n// kept `push` alive for good after it had printed its outcome. What is still\n// buffered (a pipe is written asynchronously outside Linux) goes out first.\nfor (const stream of [process.stdout, process.stderr])\n if (stream.writableLength > 0)\n await new Promise<void>((resolve) => stream.write(\"\", () => resolve()));\nprocess.exit();\n"],"mappings":";wmCA2CA,MAAM,EAAe,GACnB,EAAM,OAAS,UAAY,CAAC,EAAM,QAAU,EAAM,eAAiB,EAE/D,EAAiB,GAAsC,CAC3D,IAAM,EAAS,cAAc,EAAM,MAAM,KAAK,EAAM,OAAO,GAC3D,IAAK,EAAM,OAAS,UAAY,EAAM,SAAW,EAAM,gBAAkB,KACvE,MAAO,GAAG,EAAO,yGACnB,GAAI,EAAM,OAAS,UACjB,MAAO,GAAG,EAAO,aAAa,EAAM,SAAS,wRAC/C,IAAM,EAAO,EAAM,OAAS,OAAS,OAAS,WACxC,EAAS,EAAM,KACjB,uFACA,8BAA8B,EAAK,mCACvC,MAAO,GAAG,EAAO,IAAI,EAAM,aAAa,0BAA0B,EAAK,uCAAuC,EAAO,+FAIjH,EAAa,GAAiC,CAClD,IAAM,EAAQ,OAAO,OAAO,EAAO,CAAC,OACjC,GAAU,EAAU,EAAM,GAAK,IAAA,GACjC,CAAC,OACI,EAAS,GAAG,OAAO,KAAK,EAAO,CAAC,OAAS,EAAM,SAErD,OADI,IAAU,EAAU,EACjB,GAAG,EAAO,IAAI,EAAM,GAAG,IAAU,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