viborm 1.3.3 → 1.4.1

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 (234) hide show
  1. package/dist/{adapter-internals-AGgQRu5t.mjs → adapter-internals-Cy2QEBnH.mjs} +1 -1
  2. package/dist/{adapter-internals-AGgQRu5t.mjs.map → adapter-internals-Cy2QEBnH.mjs.map} +1 -1
  3. package/dist/{adapter-namespace-CWLEmon2.mjs → adapter-namespace-NnXlXR8c.mjs} +2 -2
  4. package/dist/{adapter-namespace-CWLEmon2.mjs.map → adapter-namespace-NnXlXR8c.mjs.map} +1 -1
  5. package/dist/adapter-result-parser-D6lluSMi.mjs +2 -0
  6. package/dist/adapter-result-parser-D6lluSMi.mjs.map +1 -0
  7. package/dist/adapters.d.mts +1 -1
  8. package/dist/adapters.mjs +1 -1
  9. package/dist/{array-literal-BKdLfNzM.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  10. package/dist/{array-literal-BKdLfNzM.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  11. package/dist/{batch-refs-DGJPz8-G.mjs → batch-refs-BYCu1JnQ.mjs} +1 -1
  12. package/dist/{batch-refs-DGJPz8-G.mjs.map → batch-refs-BYCu1JnQ.mjs.map} +1 -1
  13. package/dist/bind-parameter-capacity-D6p9HrbB.mjs +2 -0
  14. package/dist/bind-parameter-capacity-D6p9HrbB.mjs.map +1 -0
  15. package/dist/builder-BxCr9ANq.mjs +2 -0
  16. package/dist/builder-BxCr9ANq.mjs.map +1 -0
  17. package/dist/bun-sql.d.mts +3 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sql.mjs.map +1 -1
  20. package/dist/bun-sqlite.d.mts +1 -1
  21. package/dist/bun-sqlite.mjs +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache.d.mts +1 -1
  27. package/dist/cache.mjs +1 -1
  28. package/dist/{canonical-json-BReb5nFO.mjs → canonical-json-acY4dQNQ.mjs} +2 -2
  29. package/dist/canonical-json-acY4dQNQ.mjs.map +1 -0
  30. package/dist/chain-C4EUyLzF.mjs +2 -0
  31. package/dist/chain-C4EUyLzF.mjs.map +1 -0
  32. package/dist/cli.mjs +1 -1
  33. package/dist/{client-DR0vYetv.d.mts → client-3FqgR4eS.d.mts} +3 -1
  34. package/dist/client-DUulrWw5.mjs +2 -0
  35. package/dist/client-DUulrWw5.mjs.map +1 -0
  36. package/dist/{client-DjtWangN.mjs → client-sAey5P-I.mjs} +16 -16
  37. package/dist/client-sAey5P-I.mjs.map +1 -0
  38. package/dist/client.d.mts +1 -1
  39. package/dist/client.mjs +1 -1
  40. package/dist/{clock-YTLtjLFS.mjs → clock-CJotKAxc.mjs} +1 -1
  41. package/dist/{clock-YTLtjLFS.mjs.map → clock-CJotKAxc.mjs.map} +1 -1
  42. package/dist/config.d.mts +1 -1
  43. package/dist/config.mjs +1 -1
  44. package/dist/current-C2fZL9Ln.mjs +2 -0
  45. package/dist/current-C2fZL9Ln.mjs.map +1 -0
  46. package/dist/d1.d.mts +1 -1
  47. package/dist/d1.mjs +1 -1
  48. package/dist/d1.mjs.map +1 -1
  49. package/dist/{datetime-physical-codec-qKxFtI3B.mjs → datetime-physical-codec-CFoeuitT.mjs} +2 -2
  50. package/dist/{datetime-physical-codec-qKxFtI3B.mjs.map → datetime-physical-codec-CFoeuitT.mjs.map} +1 -1
  51. package/dist/{driver-BvP7eW0A.mjs → driver-BqD-3_jO.mjs} +2 -2
  52. package/dist/{driver-BvP7eW0A.mjs.map → driver-BqD-3_jO.mjs.map} +1 -1
  53. package/dist/driver-DseQwbsu.mjs +2 -0
  54. package/dist/driver-DseQwbsu.mjs.map +1 -0
  55. package/dist/driver.d.mts +1 -1
  56. package/dist/driver.mjs +1 -1
  57. package/dist/error-mapping-6op318w6.mjs.map +1 -1
  58. package/dist/every-CEQMQEdt.mjs +2 -0
  59. package/dist/{every-WUr3mlvg.mjs.map → every-CEQMQEdt.mjs.map} +1 -1
  60. package/dist/execution-context-asSCmyas.mjs +2 -0
  61. package/dist/execution-context-asSCmyas.mjs.map +1 -0
  62. package/dist/{fs-estate-azK36i9V.mjs → fs-estate-N_F2YqYa.mjs} +2 -2
  63. package/dist/{fs-estate-azK36i9V.mjs.map → fs-estate-N_F2YqYa.mjs.map} +1 -1
  64. package/dist/{geo-area-codec-BmMmWgU_.mjs → geo-area-codec-4W5b7whM.mjs} +2 -2
  65. package/dist/{geo-area-codec-BmMmWgU_.mjs.map → geo-area-codec-4W5b7whM.mjs.map} +1 -1
  66. package/dist/geo-point-codec-pAWYj5ZZ.mjs +2 -0
  67. package/dist/geo-point-codec-pAWYj5ZZ.mjs.map +1 -0
  68. package/dist/{hydration-BflrXEIQ.mjs → hydration-Az2rjp5a.mjs} +2 -2
  69. package/dist/{hydration-BflrXEIQ.mjs.map → hydration-Az2rjp5a.mjs.map} +1 -1
  70. package/dist/{identifier-conversion-Bs7A2GGU.mjs → identifier-conversion-ufaCNi9E.mjs} +2 -2
  71. package/dist/{identifier-conversion-Bs7A2GGU.mjs.map → identifier-conversion-ufaCNi9E.mjs.map} +1 -1
  72. package/dist/identity-CmRos0Yf.mjs +2 -0
  73. package/dist/identity-CmRos0Yf.mjs.map +1 -0
  74. package/dist/{index-B_jh2oaQ.d.mts → index-oVv9RLt5.d.mts} +1315 -1057
  75. package/dist/index.d.mts +1 -1
  76. package/dist/index.mjs +1 -1
  77. package/dist/instrumentation.d.mts +1 -1
  78. package/dist/instrumentation.mjs +1 -1
  79. package/dist/instrumentation.mjs.map +1 -1
  80. package/dist/{invariant-D57gi_yW.mjs → invariant-D_fIjY_z.mjs} +1 -1
  81. package/dist/{invariant-D57gi_yW.mjs.map → invariant-D_fIjY_z.mjs.map} +1 -1
  82. package/dist/{json-number-DvmiNx0n.mjs → json-number-CGXpPu4D.mjs} +1 -1
  83. package/dist/{json-number-DvmiNx0n.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  84. package/dist/{key-B89Z4vxn.mjs → key-CyLRw0ne.mjs} +2 -2
  85. package/dist/{key-B89Z4vxn.mjs.map → key-CyLRw0ne.mjs.map} +1 -1
  86. package/dist/{libsql-C8dn4id0.mjs → libsql-DPrXWc_J.mjs} +2 -2
  87. package/dist/{libsql-C8dn4id0.mjs.map → libsql-DPrXWc_J.mjs.map} +1 -1
  88. package/dist/libsql.d.mts +1 -1
  89. package/dist/libsql.mjs +1 -1
  90. package/dist/libsql.mjs.map +1 -1
  91. package/dist/{memory-B7CcHS6I.mjs → memory-DiTWROVS.mjs} +2 -2
  92. package/dist/{memory-B7CcHS6I.mjs.map → memory-DiTWROVS.mjs.map} +1 -1
  93. package/dist/migrations/mysql.d.mts +4 -4
  94. package/dist/migrations/mysql.mjs +1 -1
  95. package/dist/migrations/postgres.d.mts +4 -4
  96. package/dist/migrations/postgres.mjs +1 -1
  97. package/dist/migrations/sqlite.d.mts +4 -4
  98. package/dist/migrations/sqlite.mjs +1 -1
  99. package/dist/migrations/storage/durable-object.mjs +1 -1
  100. package/dist/migrations/storage/fs.mjs +1 -1
  101. package/dist/migrations/storage/r2.mjs +1 -1
  102. package/dist/migrations/tenant.d.mts +2 -2
  103. package/dist/migrations/tenant.mjs +1 -1
  104. package/dist/migrations.d.mts +4 -4
  105. package/dist/migrations.mjs +1 -1
  106. package/dist/mysql-adapter-B1U35CJn.mjs +2 -0
  107. package/dist/{mysql-adapter-ABpgFB2N.mjs.map → mysql-adapter-B1U35CJn.mjs.map} +1 -1
  108. package/dist/{mysql-mUmhH9Cf.mjs → mysql-fJlFIW7m.mjs} +2 -2
  109. package/dist/{mysql-mUmhH9Cf.mjs.map → mysql-fJlFIW7m.mjs.map} +1 -1
  110. package/dist/mysql2.d.mts +1 -1
  111. package/dist/mysql2.mjs +1 -1
  112. package/dist/mysql2.mjs.map +1 -1
  113. package/dist/neon-http.d.mts +3 -1
  114. package/dist/neon-http.mjs +1 -1
  115. package/dist/neon-http.mjs.map +1 -1
  116. package/dist/normalized-result-BF7gr4_b.mjs +2 -0
  117. package/dist/normalized-result-BF7gr4_b.mjs.map +1 -0
  118. package/dist/{object-store-Ds9NKRU6.d.mts → object-store-C56-FLkl.d.mts} +3 -3
  119. package/dist/{object-store-CZADAv4c.mjs → object-store-WjVilDvN.mjs} +2 -2
  120. package/dist/{object-store-CZADAv4c.mjs.map → object-store-WjVilDvN.mjs.map} +1 -1
  121. package/dist/permissions.d.mts +1 -1
  122. package/dist/permissions.mjs +1 -1
  123. package/dist/pg.d.mts +26 -1
  124. package/dist/pg.mjs +1 -1
  125. package/dist/pg.mjs.map +1 -1
  126. package/dist/pglite.d.mts +3 -1
  127. package/dist/pglite.mjs +1 -1
  128. package/dist/pglite.mjs.map +1 -1
  129. package/dist/{physical-uJfmo4-Z.mjs → physical-C4D-979R.mjs} +2 -2
  130. package/dist/{physical-uJfmo4-Z.mjs.map → physical-C4D-979R.mjs.map} +1 -1
  131. package/dist/{pinned-session-C79aDzOg.mjs → pinned-session-FYOFV_gB.mjs} +2 -2
  132. package/dist/{pinned-session-C79aDzOg.mjs.map → pinned-session-FYOFV_gB.mjs.map} +1 -1
  133. package/dist/planetscale.d.mts +1 -1
  134. package/dist/planetscale.mjs +1 -1
  135. package/dist/planetscale.mjs.map +1 -1
  136. package/dist/{planner-DHZG9Vy7.d.mts → planner-C3KX6S85.d.mts} +1 -1
  137. package/dist/{postgres-BACQ_wqF.mjs → postgres-DD92WdFu.mjs} +2 -2
  138. package/dist/{postgres-BACQ_wqF.mjs.map → postgres-DD92WdFu.mjs.map} +1 -1
  139. package/dist/postgres-adapter-B7hzWhky.mjs +2 -0
  140. package/dist/postgres-adapter-B7hzWhky.mjs.map +1 -0
  141. package/dist/postgres-adapter-CJmoxTW7.mjs +2 -0
  142. package/dist/{postgres-adapter-DaMvNOkx.mjs.map → postgres-adapter-CJmoxTW7.mjs.map} +1 -1
  143. package/dist/postgres-result-BCUQf8b_.mjs +2 -0
  144. package/dist/{postgres-result-D403cLyA.mjs.map → postgres-result-BCUQf8b_.mjs.map} +1 -1
  145. package/dist/postgres.d.mts +3 -1
  146. package/dist/postgres.mjs +1 -1
  147. package/dist/postgres.mjs.map +1 -1
  148. package/dist/{provider-limits-DSv2tYFr.mjs → provider-limits-D0ECF7_Q.mjs} +2 -2
  149. package/dist/{provider-limits-DSv2tYFr.mjs.map → provider-limits-D0ECF7_Q.mjs.map} +1 -1
  150. package/dist/relation-bound-BrZLsSke.mjs +2 -0
  151. package/dist/relation-bound-BrZLsSke.mjs.map +1 -0
  152. package/dist/{result-parsing-8wEK3GY1.mjs → result-parsing-CQf_eCl8.mjs} +1 -1
  153. package/dist/{result-parsing-8wEK3GY1.mjs.map → result-parsing-CQf_eCl8.mjs.map} +1 -1
  154. package/dist/result-shape-ic2j3Tze.mjs +2 -0
  155. package/dist/result-shape-ic2j3Tze.mjs.map +1 -0
  156. package/dist/{rows-v1VuwOTa.mjs → rows-YyvK9MDz.mjs} +2 -2
  157. package/dist/{rows-v1VuwOTa.mjs.map → rows-YyvK9MDz.mjs.map} +1 -1
  158. package/dist/{scalar-Cm7nMFmO.mjs → scalar-Dyns7kc7.mjs} +2 -2
  159. package/dist/{scalar-Cm7nMFmO.mjs.map → scalar-Dyns7kc7.mjs.map} +1 -1
  160. package/dist/schema/json.d.mts +1 -1
  161. package/dist/schema/json.mjs +1 -1
  162. package/dist/{schema-D3-ScVH6.mjs → schema-CUm_yh6L.mjs} +2 -2
  163. package/dist/{schema-D3-ScVH6.mjs.map → schema-CUm_yh6L.mjs.map} +1 -1
  164. package/dist/{schema-introspection-TdJrSaKd.mjs → schema-introspection-LpRNeSG2.mjs} +2 -2
  165. package/dist/{schema-introspection-TdJrSaKd.mjs.map → schema-introspection-LpRNeSG2.mjs.map} +1 -1
  166. package/dist/schema.d.mts +1 -1
  167. package/dist/schema.mjs +1 -1
  168. package/dist/select-assembly-BjT_fDbu.mjs +2 -0
  169. package/dist/select-assembly-BjT_fDbu.mjs.map +1 -0
  170. package/dist/{settle-etgtP1WM.mjs → settle-C4w1GfTU.mjs} +2 -2
  171. package/dist/{settle-etgtP1WM.mjs.map → settle-C4w1GfTU.mjs.map} +1 -1
  172. package/dist/{sha256-CEYo7k7R.mjs → sha256-_Nu4s32f.mjs} +1 -1
  173. package/dist/{sha256-CEYo7k7R.mjs.map → sha256-_Nu4s32f.mjs.map} +1 -1
  174. package/dist/soft-delete.d.mts +3 -3
  175. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs → sql-statement-tokens-4J5l5Lyt.mjs} +1 -1
  176. package/dist/{sql-statement-tokens-BW7Q-rF-.mjs.map → sql-statement-tokens-4J5l5Lyt.mjs.map} +1 -1
  177. package/dist/sqlite-adapter-B3dRr5fl.mjs +2 -0
  178. package/dist/sqlite-adapter-B3dRr5fl.mjs.map +1 -0
  179. package/dist/{sqlite-utils-BvSlEs5W.mjs → sqlite-utils-C5_KQPZn.mjs} +2 -2
  180. package/dist/{sqlite-utils-BvSlEs5W.mjs.map → sqlite-utils-C5_KQPZn.mjs.map} +1 -1
  181. package/dist/sqlite3.d.mts +1 -1
  182. package/dist/sqlite3.mjs +1 -1
  183. package/dist/sqlite3.mjs.map +1 -1
  184. package/dist/{standard-sql-CYdZ_KXH.mjs → standard-sql-DmKF8msN.mjs} +2 -2
  185. package/dist/{standard-sql-CYdZ_KXH.mjs.map → standard-sql-DmKF8msN.mjs.map} +1 -1
  186. package/dist/{to-many-Btc9X5Ga.mjs → to-many-DxQuOBuq.mjs} +2 -2
  187. package/dist/{to-many-Btc9X5Ga.mjs.map → to-many-DxQuOBuq.mjs.map} +1 -1
  188. package/dist/transaction-operation-CU1zlxiG.mjs.map +1 -1
  189. package/dist/{utils-Qr8ug94X.mjs → utils-CQ2nQwwO.mjs} +2 -2
  190. package/dist/{utils-Qr8ug94X.mjs.map → utils-CQ2nQwwO.mjs.map} +1 -1
  191. package/dist/{v-514RME2X.mjs → v-BcroBusN.mjs} +2 -2
  192. package/dist/{v-514RME2X.mjs.map → v-BcroBusN.mjs.map} +1 -1
  193. package/dist/{validation-CPnrLcjW.mjs → validation-CjWRiLWU.mjs} +2 -2
  194. package/dist/{validation-CPnrLcjW.mjs.map → validation-CjWRiLWU.mjs.map} +1 -1
  195. package/dist/validation.d.mts +1 -1
  196. package/dist/validation.mjs +1 -1
  197. package/dist/{validator-CQOw7G3q.mjs → validator-yrGnrsAo.mjs} +2 -2
  198. package/dist/{validator-CQOw7G3q.mjs.map → validator-yrGnrsAo.mjs.map} +1 -1
  199. package/dist/version-B9azgPiR.mjs +2 -0
  200. package/dist/{version-0RVYpih5.mjs.map → version-B9azgPiR.mjs.map} +1 -1
  201. package/package.json +16 -16
  202. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs +0 -2
  203. package/dist/bind-parameter-capacity-DiwRmZ1h.mjs.map +0 -1
  204. package/dist/builder-D6Ug-zjM.mjs +0 -2
  205. package/dist/builder-D6Ug-zjM.mjs.map +0 -1
  206. package/dist/canonical-json-BReb5nFO.mjs.map +0 -1
  207. package/dist/chain-B5IbqLGi.mjs +0 -2
  208. package/dist/chain-B5IbqLGi.mjs.map +0 -1
  209. package/dist/client-BmcHzDBa.mjs +0 -2
  210. package/dist/client-BmcHzDBa.mjs.map +0 -1
  211. package/dist/client-DjtWangN.mjs.map +0 -1
  212. package/dist/current-oXcxSCBQ.mjs +0 -2
  213. package/dist/current-oXcxSCBQ.mjs.map +0 -1
  214. package/dist/driver-Bzc0GCQ4.mjs +0 -2
  215. package/dist/driver-Bzc0GCQ4.mjs.map +0 -1
  216. package/dist/every-WUr3mlvg.mjs +0 -2
  217. package/dist/execution-context-rJXTRVrJ.mjs +0 -2
  218. package/dist/execution-context-rJXTRVrJ.mjs.map +0 -1
  219. package/dist/geo-point-codec-D95uXgDF.mjs +0 -2
  220. package/dist/geo-point-codec-D95uXgDF.mjs.map +0 -1
  221. package/dist/identity-Bj2EN6Ss.mjs +0 -2
  222. package/dist/identity-Bj2EN6Ss.mjs.map +0 -1
  223. package/dist/mysql-adapter-ABpgFB2N.mjs +0 -2
  224. package/dist/postgres-adapter-Ci07rgh_.mjs +0 -2
  225. package/dist/postgres-adapter-Ci07rgh_.mjs.map +0 -1
  226. package/dist/postgres-adapter-DaMvNOkx.mjs +0 -2
  227. package/dist/postgres-result-D403cLyA.mjs +0 -2
  228. package/dist/result-shape-BKydBCsR.mjs +0 -2
  229. package/dist/result-shape-BKydBCsR.mjs.map +0 -1
  230. package/dist/select-assembly-uZfvbYjz.mjs +0 -2
  231. package/dist/select-assembly-uZfvbYjz.mjs.map +0 -1
  232. package/dist/sqlite-adapter-DPc9T6Lh.mjs +0 -2
  233. package/dist/sqlite-adapter-DPc9T6Lh.mjs.map +0 -1
  234. package/dist/version-0RVYpih5.mjs +0 -2
@@ -625,6 +625,18 @@ interface DatabaseAdapterCapabilities {
625
625
  * clause, so a read taken only to lock rows is skipped there.
626
626
  */
627
627
  supportsRowLocks: boolean;
628
+ /**
629
+ * Whether a locking read whose exact match finds NOTHING still takes a lock.
630
+ * MySQL (InnoDB) does: a gap or next-key lock that two concurrent misses
631
+ * both hold and that each one's INSERT then waits on, a deadlock. So a read
632
+ * whose other arm inserts the key it looked for reads unlocked there and is
633
+ * confirmed under lock once it finds a row. PostgreSQL locks only the rows a
634
+ * read returns, so there that read locks what it finds and needs no
635
+ * confirmation. SQLite takes no row lock at all (`supportsRowLocks`), so
636
+ * its confirmation stays: it is the read that sees what changed. Absent:
637
+ * false.
638
+ */
639
+ locksMissingKeys?: boolean;
628
640
  /**
629
641
  * Whether a statement states each relation filter body it repeats ONCE, in
630
642
  * a `WITH`, as the key set every arm repeating it tests (a semijoin on the
@@ -634,6 +646,51 @@ interface DatabaseAdapterCapabilities {
634
646
  * a recursive walk stays where it is. Absent: false.
635
647
  */
636
648
  sharesRelationBodies?: boolean;
649
+ /**
650
+ * Whether a many-to-many relation filter reads its junction joined to the
651
+ * target, correlated in the filter's own `WHERE` (`EXISTS (SELECT 1 FROM
652
+ * junction j JOIN target t ON t.key = j.target WHERE j.source = parent.key
653
+ * AND …)`), rather than as the target's membership in a correlated junction
654
+ * subquery. `true` where the dialect plans the joined form at least as well
655
+ * everywhere measured (SQLite); `"unbounded"` where it does only in a
656
+ * statement whose root read is unbounded, a count, an aggregate, a
657
+ * `findMany` without `take` or a write: PostgreSQL turns the join into a
658
+ * hashed semijoin there (10–300× faster scans) but plans it about 0.2 ms
659
+ * more slowly, which a bounded read (a unique, first or existence read, a
660
+ * `take`) pays without the scan to win it back. Absent: false.
661
+ */
662
+ joinsJunctionFilters?: boolean | "unbounded";
663
+ /**
664
+ * Whether a recursive CTE fails once it runs a fixed number of iterations
665
+ * (MySQL's `cte_max_recursion_depth`, 1000 by default): a recursive filter
666
+ * then keeps its walk in place, whose anchor holds the first hop, rather
667
+ * than a reaching set, which spends one iteration per depth from its
668
+ * anchor. Absent: false.
669
+ */
670
+ boundsRecursionIterations?: boolean;
671
+ /**
672
+ * The most terms one compound `SELECT` may chain, where the transport
673
+ * bounds it below anything the engine writes: Cloudflare D1, 5. The engine
674
+ * nests a longer union in derived tables of at most that many. Absent:
675
+ * unbounded.
676
+ */
677
+ compoundSelectTerms?: number;
678
+ /**
679
+ * Whether the transport bounds expression depth below what nested relation
680
+ * filters reach unless each level reads from a derived table SQLite
681
+ * flattens (D1, depth 100; `SQLiteAdapter({ deepExpressions: false })`):
682
+ * a relation filter's own `EXISTS` then joins no flag member. Absent: false.
683
+ */
684
+ boundsExpressionDepth?: boolean;
685
+ /**
686
+ * Where relation bodies are shared, the relations (`FROM` items) a
687
+ * statement may reference before the engine trades plans for fewer:
688
+ * PlanetScale Neki refuses a statement over 256. Over it, a recursive
689
+ * filter's walk the statement repeats becomes one reaching set, then rows
690
+ * join the key sets they test, each as far as the statement needs. Absent:
691
+ * unbounded, so neither.
692
+ */
693
+ relationsPerStatement?: number;
637
694
  }
638
695
  //#endregion
639
696
  //#region src/adapters/adapter-core-types.d.ts
@@ -4765,1193 +4822,1266 @@ interface RawOperation<T$1> extends Promise<T$1> {
4765
4822
  readonly [RAW_OPERATION]: true;
4766
4823
  }
4767
4824
  //#endregion
4768
- //#region src/extensions/methods.d.ts
4769
- type NoMethods = Record<never, never>;
4770
- type ExtensionMethod = (this: void, ...args: never[]) => unknown;
4771
- type ExtensionMethodRecord = Readonly<Record<string, ExtensionMethod>>;
4772
- declare const extensionCacheState: unique symbol;
4773
- interface ExtensionCacheState {
4774
- readonly [extensionCacheState]: true;
4775
- }
4776
- declare const extensionResultConsumerState: unique symbol;
4777
- interface ExtensionResultConsumerState {
4778
- readonly [extensionResultConsumerState]: true;
4779
- }
4780
- /** The only static facts accumulated while extensions are chained. */
4781
- interface ClientExtensionState<ClientMethods extends object = NoMethods, ModelMethods extends object = NoMethods, CacheState extends ExtensionCacheState | undefined = undefined, ResultConsumerState extends ExtensionResultConsumerState | undefined = undefined, Controls$1 extends object = NoControls, RowModels extends string = never, Data$1 = never> {
4782
- readonly client: ClientMethods;
4783
- readonly models: ModelMethods;
4784
- readonly cache: CacheState;
4785
- readonly resultConsumer: ResultConsumerState;
4786
- /** The controls the chain declares: each one's values and placement. */
4787
- readonly controls: Controls$1;
4788
- /** The models the chain's `rows` can hide from a relation read. */
4789
- readonly rows: RowModels;
4790
- /** The fields the chain's `data` writes, which a caller no longer writes. */
4791
- readonly data: Data$1;
4792
- }
4793
- type EmptyClientExtensionState = ClientExtensionState;
4794
- /** Internal constraint for either the absent or enabled nominal cache bit. */
4795
- type ExtensionStateConstraint = ClientExtensionState<object, object, ExtensionCacheState | undefined, ExtensionResultConsumerState | undefined, object, string, unknown>;
4796
- /** Whether the current type-state includes the official cache capability. */
4797
- type HasExtensionCache<X$1 extends ExtensionStateConstraint> = [X$1["cache"]] extends [ExtensionCacheState] ? true : false;
4825
+ //#region src/client/result-types.d.ts
4798
4826
  /**
4799
- * Add the official cache capability without carrying its runtime config. Its
4800
- * one control, `cache` on every write, joins the chain's controls as its
4801
- * definition declares it.
4827
+ * Maps VibORM scalar types to their DATABASE RESULT types.
4828
+ * This is what the ORM returns after querying the database.
4829
+ *
4830
+ * Key difference from validation schema output:
4831
+ * - datetime/date/time: returns Date (not ISO string)
4832
+ * - json: inferred from custom schema if present, otherwise unknown
4833
+ * - enum: inferred from schema values
4802
4834
  */
4803
- type EnableExtensionCache<X$1 extends ExtensionStateConstraint> = ClientExtensionState<X$1["client"], X$1["models"], ExtensionCacheState, X$1["resultConsumer"], X$1["controls"] & DefinitionControls<{
4804
- readonly controls: OfficialCacheControls;
4805
- }>, X$1["rows"], X$1["data"]>;
4806
- /** Whether an earlier extension was typed against result-bearing delegates. */
4807
- type HasResultConsumingExtension<X$1 extends ExtensionStateConstraint> = [X$1["resultConsumer"]] extends [undefined] ? false : [X$1["resultConsumer"]] extends [ExtensionResultConsumerState] ? true : false;
4808
- type MethodsForModel<X$1 extends ExtensionStateConstraint, ModelName$1 extends PropertyKey> = ModelName$1 extends keyof X$1["models"] ? X$1["models"][ModelName$1] : NoMethods;
4835
+ type ScalarResultTypeMap = {
4836
+ string: string;
4837
+ int: number;
4838
+ number: number;
4839
+ decimal: Decimal;
4840
+ boolean: boolean;
4841
+ datetime: Date;
4842
+ date: Date;
4843
+ time: string;
4844
+ bigint: bigint;
4845
+ json: unknown;
4846
+ blob: Uint8Array;
4847
+ vector: number[];
4848
+ point: GeoPoint;
4849
+ enum: string;
4850
+ };
4809
4851
  /**
4810
- * One model's delegate after the chain's methods and controls. On a chain
4811
- * that declares create `data`, its writes may leave out the fields the chain
4812
- * writes on a create.
4852
+ * Extract the ScalarState from a Scalar using infer to preserve literal types.
4813
4853
  */
4814
- type ExtensionModelDelegate<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, ModelName$1 extends keyof ClientSchema<C$1>> = ([X$1["data"]] extends [never] ? Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1] : Omit<Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1], StampedOperation> & StampedOperations<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"], X$1["data"], ModelName$1>) & MethodsForModel<X$1, ModelName$1>;
4854
+ type ExtractScalarState<F$1> = F$1 extends {
4855
+ "~": {
4856
+ state: infer S;
4857
+ };
4858
+ } ? S extends ScalarState ? S : never : never;
4815
4859
  /**
4816
- * Model delegates after the methods contributed by the current chain. The
4817
- * always-true test is deliberate: for a client generic over its config it
4818
- * stays deferred, so the model map adds no index signature to that client and
4819
- * its `$` members stay reachable inside a body generic over `C`.
4860
+ * Get the base scalar type for a field, handling custom schemas.
4861
+ * For json/enum scalars with custom schemas, infer from the schema.
4862
+ * For datetime fields, always return Date (regardless of validation schema output).
4863
+ *
4864
+ * The enum arm reads the scalar's own `base` schema, so an enum's literal union
4865
+ * survives a relation read exactly as it does a direct one: this helper is
4866
+ * reached through the same `InferScalarOutput` on both paths.
4820
4867
  */
4821
- type ExtensionModelClient<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = [keyof C$1["schema"]] extends [PropertyKey] ? { [ModelName in keyof ClientSchema<C$1>]: ExtensionModelDelegate<C$1, X$1, ModelName> } : unknown;
4822
- /** The surface given to one client-method factory. */
4823
- type ExtensionClientScope<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = ExtensionModelClient<C$1, X$1> & RawSurface & X$1["client"] & {
4824
- readonly $schema: ClientSchema<C$1>;
4825
- readonly $transaction: TransactionClient<C$1, X$1>["$transaction"];
4826
- /**
4827
- * The client this scope's methods are called on, its calls admitting
4828
- * these values of this extension's own controls as if passed (a
4829
- * `bound: true` control only from here). Its type is that client's,
4830
- * which only the method knows: declare it with a `this` parameter,
4831
- * `$with<Self>(this: Self, value: Value): Self`, outside the returned
4832
- * literal (inside it, the factory's contextual type makes `Self` void).
4833
- */
4834
- readonly $bind: (values: Readonly<Record<string, unknown>>) => unknown;
4835
- };
4836
- type NonFunctionKeys<Methods$1 extends object> = { [Key in keyof Methods$1]: Methods$1[Key] extends CallableFunction ? never : Key }[keyof Methods$1];
4837
- type InvalidClientMethodKeys<Methods$1 extends object, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = Exclude<keyof Methods$1, `$${string}`> | Extract<keyof Methods$1, keyof RawSurface | "$driver" | "$schema" | "$transaction" | "$connect" | "$disconnect" | "$withCache" | "$invalidate" | "$extends" | keyof X$1["client"]> | (string extends keyof C$1["schema"] ? never : Extract<keyof Methods$1, keyof C$1["schema"]>) | NonFunctionKeys<Methods$1>;
4838
- type GuardMethodFactory<Factory$1, Forbidden extends PropertyKey> = Factory$1 extends ((...args: infer Params) => infer Methods) ? Methods extends object ? (...args: Params) => Methods & Record<Forbidden, never> : (...args: Params) => never : never;
4839
- type ClientFactoryGuard<Definition$1, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = Definition$1 extends {
4840
- readonly client: infer Factory;
4841
- } ? Factory extends ((...args: never[]) => infer Methods) ? Methods extends object ? {
4842
- readonly client: GuardMethodFactory<Factory, InvalidClientMethodKeys<Methods, C$1, X$1>>;
4843
- } : {
4844
- readonly client: never;
4845
- } : {
4846
- readonly client: never;
4847
- } : unknown;
4868
+ type GetScalarResultType<F$1 extends Scalar> = ExtractScalarState<F$1> extends infer S ? S extends ScalarState ? S["type"] extends "json" ? S["schema"] extends StandardSchemaV1<any, infer O> ? O : unknown : S["type"] extends "enum" ? EnumValues<S["base"]>[number] : ScalarResultTypeMap[S["type"]] : unknown : unknown;
4848
4869
  /**
4849
- * What every model factory may not return: a core operation or `then`. That
4850
- * each returned member is a function is the definition's own factory type
4851
- * (`ModelMethodFactory` returns an `ExtensionMethodRecord`), not this guard;
4852
- * `object` only keeps the all-optional key list from being a weak type, which
4853
- * would refuse every return that names none of those keys. Stated as a target
4854
- * shape, not a conditional over the factory, so a factory map generic over the
4855
- * client is checked rather than deferred. A method a prior extension put on
4856
- * the model cannot be named here for a client generic over its extension
4857
- * state: the runtime refuses that replacement when the extension is applied.
4870
+ * Apply nullable wrapper based on scalar state.
4871
+ * Uses non-distributive check to handle boolean literals correctly.
4858
4872
  */
4859
- type ModelFactoryGuard = (...args: never[]) => object & { readonly [Name in Operations | "then"]?: never };
4873
+ type ApplyNullable<T$1, Nullable> = [Nullable] extends [true] ? T$1 | null : T$1;
4860
4874
  /**
4861
- * Model keys outside the schema are refused by the definition's own `model`
4862
- * type (its per-schema factory table); this guard checks each factory's
4863
- * methods.
4875
+ * Apply array wrapper based on scalar state.
4876
+ * Uses non-distributive check to handle boolean literals correctly.
4864
4877
  */
4865
- type ModelFactoriesGuard<Definition$1> = Definition$1 extends {
4866
- readonly model: infer Factories;
4867
- } ? {
4868
- readonly model: { readonly [ModelName in keyof Factories]: ModelFactoryGuard };
4869
- } : unknown;
4870
- type ExtensionMethodDefinitionGuard<Definition$1, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = ClientFactoryGuard<Definition$1, C$1, X$1> & ModelFactoriesGuard<Definition$1>;
4871
- type ClientMethodsOf<Definition$1> = Definition$1 extends {
4872
- readonly client: (...args: never[]) => infer Methods;
4873
- } ? Methods extends object ? Methods : NoMethods : NoMethods;
4874
- type ModelMethodsOf<Definition$1> = Definition$1 extends {
4875
- readonly model: infer Factories;
4876
- } ? Factories extends object ? { readonly [ModelName in keyof Factories]: Factories[ModelName] extends ((...args: never[]) => infer Methods) ? Methods extends object ? Methods : NoMethods : NoMethods } : NoMethods : NoMethods;
4877
- type MergeModelMethods<Left extends object, Right extends object> = { readonly [ModelName in keyof Left | keyof Right]: (ModelName extends keyof Left ? Left[ModelName] : NoMethods) & (ModelName extends keyof Right ? Right[ModelName] : NoMethods) };
4878
- type ResultConsumerContextOf<Definition$1> = Definition$1 extends {
4879
- readonly client: unknown;
4880
- } | {
4881
- readonly model: unknown;
4882
- } ? "result-consuming" : Definition$1 extends {
4883
- readonly query: infer Query;
4884
- } ? Query extends CallableFunction ? "result-independent" : "result-consuming" : "result-independent";
4885
- /** Incoming facts keep their nominal bit derivation inside this named state. */
4886
- interface ExtensionContributionState<ClientMethods extends object, ModelMethods extends object, Controls$1 extends object, RowModels extends string, Data$1, ConsumerContext extends string> extends ExtensionStateConstraint {
4887
- readonly client: ClientMethods;
4888
- readonly models: ModelMethods;
4889
- readonly cache: undefined;
4890
- readonly resultConsumer: ConsumerContext extends "result-consuming" ? ExtensionResultConsumerState : undefined;
4891
- readonly controls: Controls$1;
4892
- readonly rows: RowModels;
4893
- readonly data: Data$1;
4894
- }
4895
- /** Retain contribution facts, never the factory's contextual argument surface. */
4896
- type ExtensionStateContributionOf<Definition$1> = [Definition$1] extends [unknown] ? ExtensionContributionState<ClientMethodsOf<Definition$1>, ModelMethodsOf<Definition$1>, DefinitionControls<Definition$1>, RowsModels<Definition$1>, DefinitionData<Definition$1>, ResultConsumerContextOf<Definition$1>> : never;
4897
- /** Accumulate the same seven facts lazily, without retaining callback definitions. */
4898
- interface AccumulatedExtensionState<X$1 extends ExtensionStateConstraint, Contribution extends ExtensionStateConstraint> extends ExtensionStateConstraint {
4899
- readonly client: X$1["client"] & Contribution["client"];
4900
- readonly models: MergeModelMethods<X$1["models"], Contribution["models"]>;
4901
- readonly cache: X$1["cache"];
4902
- readonly resultConsumer: HasResultConsumingExtension<Contribution> extends true ? ExtensionResultConsumerState : X$1["resultConsumer"];
4903
- readonly controls: X$1["controls"] & Contribution["controls"];
4904
- readonly rows: X$1["rows"] | Contribution["rows"];
4905
- readonly data: X$1["data"] | Contribution["data"];
4906
- }
4907
- /** Public compatibility surface: the incoming argument remains a definition. */
4908
- type MergeExtensionState<X$1 extends ExtensionStateConstraint, Definition$1> = AccumulatedExtensionState<X$1, ExtensionStateContributionOf<Definition$1>>;
4909
- //#endregion
4910
- //#region src/extensions/request.d.ts
4878
+ type ApplyArray<T$1, IsArray> = [IsArray] extends [true] ? T$1[] : T$1;
4911
4879
  /**
4912
- * The single operation-specific owner of request properties that determine the
4913
- * public result type. A future projection spelling extends this table; runtime
4914
- * detachment and the handler input/patch types then change together.
4880
+ * Infer the DATABASE RESULT type for a scalar.
4881
+ *
4882
+ * This is the canonical helper for inferring output types from scalars.
4883
+ * It correctly handles:
4884
+ * - All scalar types with proper DB result mapping (datetime → Date)
4885
+ * - Custom schemas for json/enum scalars
4886
+ * - Nullable scalars
4887
+ * - Array scalars
4888
+ *
4889
+ * @example
4890
+ * // For s.dateTime().nullable() → Date | null
4891
+ * // For s.string().array() → string[]
4892
+ * // For s.json().schema(z.object({...})) → { ... }
4915
4893
  */
4916
- declare const RESULT_SHAPE_KEYS_BY_OPERATION: Readonly<{
4917
- findFirst: readonly ["select", "include", "omit"];
4918
- findMany: readonly ["select", "include", "omit"];
4919
- findUnique: readonly ["select", "include", "omit"];
4920
- findUniqueOrThrow: readonly ["select", "include", "omit"];
4921
- findFirstOrThrow: readonly ["select", "include", "omit"];
4922
- create: readonly ["select", "include", "omit"];
4923
- update: readonly ["select", "include", "omit"];
4924
- delete: readonly ["select", "include", "omit"];
4925
- upsert: readonly ["select", "include", "omit"];
4926
- createMany: readonly ["select", "omit"];
4927
- updateMany: readonly ["select", "omit"];
4928
- deleteMany: readonly ["select", "omit"];
4929
- count: readonly ["select"];
4930
- aggregate: readonly ["_count", "_avg", "_sum", "_min", "_max"];
4931
- groupBy: readonly ["by", "_count", "_avg", "_sum", "_min", "_max"];
4932
- exist: readonly [];
4933
- }>;
4934
- type ResultShapeKeyFor<Operation$2 extends Operations> = (typeof RESULT_SHAPE_KEYS_BY_OPERATION)[Operation$2][number];
4935
- /** The operation input visible to an ordinary request transform. */
4936
- type RequestTransformInput<Operation$2 extends Operations, Input$1 extends object> = Omit<Input$1, ResultShapeKeyFor<Operation$2>>;
4894
+ type InferScalarOutput<F$1 extends Scalar> = ExtractScalarState<F$1> extends infer S ? S extends ScalarState ? ApplyNullable<ApplyArray<GetScalarResultType<F$1>, S["array"]>, S["nullable"]> : never : never;
4937
4895
  /**
4938
- * A shallow patch over the non-projection input. The optional `never`
4939
- * properties make protected keys fail structurally, including held values.
4896
+ * Result for batch operations (createMany, updateMany, deleteMany)
4940
4897
  */
4941
- type RequestTransformPatch<Operation$2 extends Operations, Input$1 extends object> = Partial<RequestTransformInput<Operation$2, Input$1>> & { readonly [Key in ResultShapeKeyFor<Operation$2>]?: never };
4942
- interface GenericRequestContext {
4943
- readonly model: string;
4944
- readonly operation: Operations;
4945
- readonly input: Readonly<RequestTransformPatch<Operations, Record<string, unknown>>>;
4946
- /** The call's controls this handler's extension declares, and only those. */
4947
- readonly controls?: AdmittedControls;
4898
+ interface BatchPayload {
4899
+ count: number;
4948
4900
  }
4949
- type GenericRequestHandlerCall = (context: GenericRequestContext) => Readonly<RequestTransformPatch<Operations, Record<string, unknown>>>;
4950
- declare const officialRequestHandlerIdentity: unique symbol;
4951
- /** Public ordinary request handler; official identities cannot be erased into it. */
4952
- type GenericRequestHandler = GenericRequestHandlerCall & {
4953
- readonly [officialRequestHandlerIdentity]?: never;
4954
- };
4955
- /** Internal nominal call shape used by official request-based capabilities. */
4956
- type OfficialGenericRequestHandler = GenericRequestHandlerCall & {
4957
- readonly [officialRequestHandlerIdentity]: true;
4958
- };
4959
- type RequestOperationInput<S$1 extends Schema$1, ModelName$1 extends keyof S$1, OperationName$1 extends Operations> = Extract<Exclude<OperationPayload<OperationName$1, S$1[ModelName$1]>, undefined>, object>;
4960
- type RequestHandlerMap<S$1 extends Schema$1> = { readonly [ModelName in keyof S$1]?: { readonly [OperationName in Operations]?: (context: {
4961
- readonly model: ModelName;
4962
- readonly operation: OperationName;
4963
- readonly input: Readonly<RequestTransformInput<OperationName, RequestOperationInput<S$1, ModelName, OperationName>>>;
4964
- /** The call's controls this handler's extension declares, and only those. */
4965
- readonly controls?: AdmittedControls;
4966
- }) => RequestTransformPatch<OperationName, RequestOperationInput<S$1, ModelName, OperationName>> } };
4967
- //#endregion
4968
- //#region src/extensions/statement.d.ts
4969
- /** The trusted identity exposed to one low-level statement transform. */
4970
- interface StatementContext {
4971
- readonly statement: Sql;
4972
- readonly model: string | undefined;
4973
- readonly operation: Operations | keyof RawSurface;
4974
- }
4975
- type StatementHandler = (context: StatementContext) => Sql;
4976
- //#endregion
4977
- //#region src/extensions/definition.d.ts
4978
- type ExtensionConfig<S$1 extends Schema$1> = {
4979
- readonly schema: S$1;
4980
- readonly driver: AnyDriver;
4981
- };
4982
4901
  /**
4983
- * A model factory, declared as a method so a factory typed against the client
4984
- * it extends (`(delegate: M[K & keyof M]) => …`, generic over that client) is
4985
- * compared in either direction rather than only contravariantly.
4902
+ * Result type for count operations
4903
+ * Supports select for per-field counts like Prisma: count({ select: { _all: true, name: true } })
4986
4904
  */
4987
- type ModelMethodFactory<Delegate> = {
4988
- factory(delegate: Delegate): ExtensionMethodRecord;
4989
- }["factory"];
4905
+ /** Literal selections are required; runtime choices expose optional fields. */
4906
+ type SelectedFields<Selection$1, Fields$1> = { [K in keyof Selection$1 & keyof Fields$1 as Selection$1[K] extends true | object ? K : never]: Fields$1[K] } & { [K in keyof Selection$1 & keyof Fields$1 as Selection$1[K] extends true | object ? never : Extract<Selection$1[K], true | object> extends never ? never : K]?: Fields$1[K] };
4907
+ type SelectedCountResult<Selection$1> = Prettify<SelectedFields<Selection$1, { [K in keyof Selection$1]: number }>>;
4908
+ type CountResultType<Args, Selected = (Args extends {
4909
+ select: infer Selection;
4910
+ } ? SelectedCountResult<Selection> : never)> = Args extends {
4911
+ select: unknown;
4912
+ } ? keyof Selected extends never ? number : Selected : number;
4990
4913
  /**
4991
- * One factory per schema model. A definition's model key is looked up here by
4992
- * index, never by a conditional: a key outside the schema reads `never` (the
4993
- * factory is refused where it is written), and a key set generic over the
4994
- * client is substituted rather than deferred, so a plugin generic over `C`
4995
- * type-checks and meets the schema check when it is applied.
4914
+ * The non-recursive part of a model that result inference can compare safely.
4915
+ *
4916
+ * Full `Model` equality walks relation getters and collapses mutually-recursive
4917
+ * model consts. These two key sets identify the usual case without touching any
4918
+ * scalar implementation, external schema, or relation target. There are two,
4919
+ * not three, because a model now holds ONE relation map across both target
4920
+ * domains (§5.2).
4996
4921
  */
4997
- type ModelFactoryTable<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = { readonly [ModelName in keyof ClientSchema<C$1>]: ModelMethodFactory<ExtensionModelDelegate<C$1, X$1, ModelName>> };
4998
- /** The model keys a definition's own `model` map names. */
4999
- type DefinitionModelKeys<Self> = Self extends {
5000
- readonly model?: infer Factories;
5001
- } ? keyof Factories : never;
4922
+ type ModelResultSurface<M$1 extends Model$1<any>> = M$1 extends Model$1<infer S> ? readonly [Extract<keyof S["scalars"], string>, Extract<keyof S["relations"], string>] : never;
4923
+ type SameKeySet<Left, Right> = [Exclude<Left, Right>] extends [never] ? [Exclude<Right, Left>] extends [never] ? true : false : false;
4924
+ type IsUsableModelResultSurface<Surface> = [Surface] extends [never] ? false : Surface extends readonly [infer Scalars, infer Relations] ? string extends Scalars ? false : string extends Relations ? false : true : false;
4925
+ /** Exact equality for the two shallow key sets above. */
4926
+ type SameModelResultSurface<Left, Right> = IsUsableModelResultSurface<Left> extends true ? IsUsableModelResultSurface<Right> extends true ? Left extends readonly [infer LS, infer LR] ? Right extends readonly [infer RS, infer RR] ? SameKeySet<LS, RS> extends true ? SameKeySet<LR, RR> : false : false : false : false : false;
5002
4927
  /**
5003
- * `Self` is the definition itself when `$extends` checks it (F-bounded), so
5004
- * its model keys come from the definition; otherwise every schema model.
4928
+ * The shallow surfaces of the models whose rows a client's `rows` can hide
4929
+ * from a relation read (`ClientRowsContext`, ./types.ts). It rides the same
4930
+ * result context as the omission defaults, as one more member of the union.
5005
4931
  */
5006
- type ContextualExtensionDefinition<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, Self = unknown> = ExtensionMembers<C$1, X$1> & {
5007
- readonly model?: unknown extends Self ? { readonly [ModelName in keyof ClientSchema<C$1>]?: ModelMethodFactory<ExtensionModelDelegate<C$1, X$1, ModelName>> } : { readonly [ModelName in DefinitionModelKeys<Self>]?: ModelFactoryTable<C$1, X$1>[ModelName & keyof ClientSchema<C$1>] };
5008
- };
5009
- type ExtensionMembers<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = {
5010
- readonly name: string;
5011
- readonly request?: GenericRequestHandler | RequestHandlerMap<ClientSchema<C$1>>;
5012
- readonly query?: GenericQueryHandler | QueryHandlerMap<C$1, X$1["rows"]>;
5013
- readonly statement?: StatementHandler;
5014
- readonly observe?: ObserveHandler;
5015
- readonly controls?: ControlsContribution;
5016
- readonly rows?: RowsContribution;
5017
- readonly deletion?: DeletionContribution;
5018
- readonly data?: DataContribution;
5019
- readonly client?: (scope: ExtensionClientScope<C$1, X$1>) => ExtensionMethodRecord;
5020
- };
5021
- type SchemaGenericExtensionDefinition = Omit<ContextualExtensionDefinition<ExtensionConfig<Schema$1>, EmptyClientExtensionState>, "request" | "query"> & {
5022
- readonly request?: GenericRequestHandler;
5023
- readonly query?: GenericQueryHandler;
5024
- };
4932
+ interface ClientHiddenContext<Surfaces> {
4933
+ readonly hidden: Surfaces;
4934
+ }
5025
4935
  /**
5026
- * Public reusable extension definition.
4936
+ * `null` where a relation read can find this target hidden, and nothing
4937
+ * otherwise. Models are compared by their shallow surface, as the omission
4938
+ * defaults are: a target that shares its surface with a hidden model widens
4939
+ * with it, and a surface too wide to compare widens too, both on the `| null`
4940
+ * side. It distributes over the context, so a client without `rows` never
4941
+ * resolves a target, and TypeScript measures the context parameter of every
4942
+ * result type through it cheaply: the `[Hidden] extends [never]` form it
4943
+ * replaces cost the schema-only floor 33,535 types (measured, U7 repair).
4944
+ */
4945
+ type HiddenTargetNull<R$1 extends AnyRelation, Context> = Context extends ClientHiddenContext<infer Hidden> ? true extends HidesTarget<R$1, Hidden> ? null : never : never;
4946
+ type HidesTarget<R$1 extends AnyRelation, Hidden$1> = Hidden$1 extends unknown ? IsUsableModelResultSurface<Hidden$1> extends false ? true : MatchesSurface<TargetSurfaces<R$1>, Hidden$1> : never;
4947
+ type MatchesSurface<Surface, Hidden$1> = Surface extends unknown ? IsUsableModelResultSurface<Surface> extends false ? true : SameModelResultSurface<Surface, Hidden$1> : never;
4948
+ /** The shallow surface of each model a relation can target. */
4949
+ type TargetSurfaces<R$1 extends AnyRelation> = IsVariantTarget<R$1> extends true ? ModelResultSurface<GetPolymorphicTarget<R$1, PolymorphicPublicTypes<R$1>>> : ModelResultSurface<GetTargetModel<R$1>>;
4950
+ /** One configured model's compact, client-owned result default. */
4951
+ interface ClientResultOmitEntry<Surface, Omission, Unique> {
4952
+ readonly surface: Surface;
4953
+ readonly omission: Omission;
4954
+ readonly unique: Unique;
4955
+ }
4956
+ /** Named boundary so TypeScript can cache the carrier during result recursion. */
4957
+ interface ClientResultOmitContext<Entries$1> {
4958
+ readonly entries: Entries$1;
4959
+ }
4960
+ type EntrySurface<Entry> = Entry extends ClientResultOmitEntry<infer Surface, unknown, unknown> ? Surface : never;
4961
+ type MatchingClientOmitEntries<M$1 extends Model$1<any>, Context, Entries$1 = (Context extends ClientResultOmitContext<infer E> ? E : never)> = M$1 extends unknown ? Entries$1 extends unknown ? true extends SameModelResultSurface<ModelResultSurface<M$1>, EntrySurface<Entries$1>> ? Entries$1 : never : never : never;
4962
+ type IsUnion<T$1, Whole = T$1> = T$1 extends Whole ? [Whole] extends [T$1] ? false : true : never;
4963
+ type HasMultipleModelResultSurfaces<M$1 extends Model$1<any>, WholeSurface = ModelResultSurface<M$1>> = M$1 extends unknown ? SameModelResultSurface<ModelResultSurface<M$1>, WholeSurface> extends true ? false : true : never;
4964
+ type EntryOmission<Entry> = Entry extends ClientResultOmitEntry<unknown, infer Omission, unknown> ? Omission : never;
4965
+ type EntryUnique<Entry> = Entry extends ClientResultOmitEntry<unknown, unknown, infer Unique> ? Unique : never;
4966
+ type PossibleOmitKeys<Entry> = Entry extends unknown ? keyof Exclude<EntryOmission<Entry>, undefined> : never;
4967
+ type SoftenedResolvedOmit<Keys$1 extends PropertyKey> = [Keys$1] extends [never] ? undefined : { [K in Keys$1]: boolean };
4968
+ /**
4969
+ * Resolve a nested target's client default without comparing model graphs.
5027
4970
  *
5028
- * A schema with a string index has no exact model vocabulary, so its reusable
5029
- * request/query contributions must use the polymorphic all-operation form.
5030
- * Supplying a concrete schema retains its exact model and operation maps.
4971
+ * A unique shallow surface identifies the configured model exactly. When two
4972
+ * schema models have the same surface, the current public types contain no
4973
+ * nominal identity that can distinguish their runtime objects. In that case,
4974
+ * every possibly omitted field becomes a widened boolean; `ApplyOmit` renders
4975
+ * it optional, which is honest in both runtime worlds.
5031
4976
  */
5032
- type ClientExtension<S$1 extends Schema$1 = Schema$1> = string extends keyof S$1 ? SchemaGenericExtensionDefinition : ContextualExtensionDefinition<ExtensionConfig<S$1>, EmptyClientExtensionState>;
5033
- type DefinitionKeys = keyof ContextualExtensionDefinition<VibORMConfig, EmptyClientExtensionState>;
5034
- declare const schemaBoundExtensionContext: unique symbol;
5035
- type SchemaBoundExtension<Definition$1> = Definition$1 & {
5036
- readonly [schemaBoundExtensionContext]: ResultConsumerContextOf<Definition$1>;
5037
- };
5038
- type UnknownDefinitionKeys<Definition$1> = Record<Exclude<keyof Definition$1, DefinitionKeys | typeof schemaBoundExtensionContext>, never>;
5039
- type ConfigOmit$2<C$1 extends VibORMConfig> = "omit" extends keyof C$1 ? C$1[Extract<"omit", keyof C$1>] : undefined;
5040
- type HasNamedClientOmit<C$1 extends VibORMConfig> = string extends keyof NonNullable<ConfigOmit$2<C$1>> ? false : [Exclude<ConfigOmit$2<C$1>, undefined>] extends [never] ? false : true;
5041
- /** Refuse replaying a schema-bound result consumer into an omitted client. */
5042
- type SchemaBoundExtensionAdmission<Definition$1, C$1 extends VibORMConfig> = Definition$1 extends {
5043
- readonly [schemaBoundExtensionContext]: infer Context;
5044
- } ? Context extends "result-consuming" ? HasNamedClientOmit<C$1> extends true ? {
5045
- readonly [schemaBoundExtensionContext]: never;
5046
- } : unknown : unknown : unknown;
5047
- type OperationMapGuard<Map$1, S$1 extends Schema$1> = Map$1 extends CallableFunction ? unknown : Map$1 extends object ? Record<Exclude<keyof Map$1, keyof S$1>, never> & { readonly [ModelName in keyof Map$1]: ModelName extends keyof S$1 ? Map$1[ModelName] extends object ? Record<Exclude<keyof Map$1[ModelName], Operations>, never> : never : never } : never;
5048
- type ComponentMapGuard<Definition$1, Key$1 extends "request" | "query", S$1 extends Schema$1> = Definition$1 extends { readonly [K in Key$1]: infer Component } ? { readonly [K in Key$1]: OperationMapGuard<Component, S$1> } : unknown;
5049
- /** Policy model keys must be a subset of a concrete bound schema. */
5050
- type PolicyModelsGuard<Definition$1, S$1 extends Schema$1, Key$1 extends "data" | "rows" | "deletion"> = Definition$1 extends { readonly [K in Key$1]: {
5051
- readonly models: infer Models;
5052
- } } ? string extends keyof S$1 ? unknown : [keyof Models] extends [keyof S$1] ? unknown : { readonly [K in Key$1]: {
5053
- readonly models: Record<keyof Models, never>;
5054
- } } : unknown;
5055
- /** Structural refusal for non-fresh extension definitions and contributions. */
5056
- type ExactExtensionDefinition<Definition$1, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = UnknownDefinitionKeys<Definition$1> & ComponentMapGuard<Definition$1, "request", C$1["schema"]> & ComponentMapGuard<Definition$1, "query", C$1["schema"]> & PolicyModelsGuard<Definition$1, C$1["schema"], "data"> & PolicyModelsGuard<Definition$1, C$1["schema"], "rows"> & PolicyModelsGuard<Definition$1, C$1["schema"], "deletion"> & ExtensionMethodDefinitionGuard<Definition$1, C$1, X$1>;
5057
- type DefineExtensionBinder<S$1 extends Schema$1> = <const Definition$1>(definition: Definition$1 & ContextualExtensionDefinition<ExtensionConfig<S$1>, EmptyClientExtensionState> & ExactExtensionDefinition<Definition$1, ExtensionConfig<S$1>, EmptyClientExtensionState>) => SchemaBoundExtension<NoInfer<Definition$1>>;
5058
- declare function defineExtension<const Definition$1 extends SchemaGenericExtensionDefinition>(definition: Definition$1 & ExactExtensionDefinition<Definition$1, ExtensionConfig<Schema$1>, EmptyClientExtensionState>): NoInfer<Definition$1>;
5059
- declare function defineExtension<S$1 extends Schema$1>(): DefineExtensionBinder<S$1>;
5060
- //#endregion
5061
- //#region src/extensions/controls.d.ts
5062
- /** The operations a declared control is accepted on. */
5063
- type ControlPlacement = "reads" | "writes" | "all" | readonly Operations[];
4977
+ type ResolveClientOmit<M$1 extends Model$1<any>, Context, Matches = MatchingClientOmitEntries<M$1, Context>, AmbiguousKeys extends PropertyKey = PossibleOmitKeys<Matches>> = [Context] extends [never] ? undefined : [Matches] extends [never] ? undefined : true extends HasMultipleModelResultSurfaces<M$1> ? SoftenedResolvedOmit<AmbiguousKeys> : true extends IsUnion<EntryOmission<Matches>> ? SoftenedResolvedOmit<AmbiguousKeys> : false extends EntryUnique<Matches> ? SoftenedResolvedOmit<AmbiguousKeys> : EntryOmission<Matches>;
4978
+ /** Get the target model itself without resolving its recursive state. */
4979
+ type GetTargetModel<R$1 extends AnyRelation> = TargetGetter<R$1> extends (() => infer Target) ? Target extends Model$1<any> ? Target : never : never;
5064
4980
  /**
5065
- * One argument an extension declares. Its values are a closed list or a
5066
- * Standard Schema; `on` names the operations that accept it (every operation
5067
- * when absent). With `required`, a call on one of those operations that does
5068
- * not pass it is refused, on the models the extension names in `rows`,
5069
- * `data` or `deletion` only; an extension that names no model asks for it on
5070
- * every model. With `bound`, it is accepted only from a binding (the client
5071
- * scope's `$bind`), never from a call's arguments: its placement reads no
5072
- * argument, so a call that passes it is refused as passing an unknown key.
5073
- * With `uncacheable`, a read that holds a value of it is never served from
5074
- * the cache: `$withCache` on that read is refused before any statement. A
5075
- * value held in a variable keeps its literal type only with `as const`, as a
5076
- * held enum clause does.
4981
+ * Get the target model's state from a relation
5077
4982
  */
5078
- type ControlDeclaration = ({
5079
- readonly oneOf: readonly (string | number | boolean)[];
5080
- } | {
5081
- readonly schema: StandardSchemaV1;
5082
- }) & {
5083
- readonly on?: ControlPlacement;
5084
- readonly required?: boolean;
5085
- readonly bound?: boolean;
5086
- readonly uncacheable?: boolean;
5087
- };
5088
- type ControlsContribution = {
5089
- readonly [name: string]: ControlDeclaration;
5090
- };
5091
- /** Constant scalar `where` or `data` fields of one model. */
5092
- type ScalarFields = {
5093
- readonly [field: string]: unknown;
5094
- };
4983
+ type GetTargetModelState<R$1 extends AnyRelation> = GetTargetModel<R$1> extends infer T ? T extends Model$1<infer S> ? S extends ModelState ? S : never : never : never;
5095
4984
  /**
5096
- * Which rows an operation sees. `control` names the call argument that picks
5097
- * a mode; every model entry declares the same mode names, `default` among
5098
- * them. `root` filters the call's own candidates, `related` rows reached
5099
- * through a relation; each is a model's `where`, admitted once when the
5100
- * extension is applied, or the name of one of its `verbs` predicates. Where a
5101
- * filter takes a value, `{ control: "<name>", path?: "a.b" }` takes the value
5102
- * the call passed for that control (or a field of it), `{ now: true }` the
5103
- * call's instant, and `{ $if: … }` tests a call value. An absent value
5104
- * (`null` included) matches nothing where its control is required, and drops
5105
- * its filter where it is not.
5106
- *
5107
- * `verbs` judges, per model, what a call may do to the rows it sees: a mode
5108
- * only narrows them (R8). A model's entry may be a function returning it:
5109
- * it is called when a call of the chain first needs that model, and its
5110
- * entry admitted then, so a refusal of it fails that call instead of
5111
- * `$extends`. A function returning deeply frozen plain data is called once
5112
- * per schema; one returning anything else, once per client.
4985
+ * Infer the output type for a model, respecting omit settings.
4986
+ * Uses InferScalarOutput for correct DB result types (e.g., Date for datetime).
5113
4987
  */
5114
- type RowsContribution = {
5115
- readonly control: string;
5116
- readonly default: string;
5117
- readonly models: {
5118
- readonly [model: string]: {
5119
- readonly [mode: string]: {
5120
- readonly root?: ScalarFields | string;
5121
- readonly related?: ScalarFields | string;
5122
- };
5123
- };
5124
- };
5125
- readonly verbs?: {
5126
- readonly [model: string]: RowsVerbs | (() => RowsVerbs);
5127
- };
5128
- };
4988
+ type InferModelOutput<S$1 extends ModelState> = S$1["omit"] extends Record<string, true> ? Omit<{ [K in keyof S$1["scalars"]]: S$1["scalars"][K] extends Scalar ? InferScalarOutput<S$1["scalars"][K]> : never }, keyof S$1["omit"]> : { [K in keyof S$1["scalars"]]: S$1["scalars"][K] extends Scalar ? InferScalarOutput<S$1["scalars"][K]> : never };
5129
4989
  /**
5130
- * One model's named predicates, each a `where` admitted once, and the verbs
5131
- * that take them. `read` ANDs with every mode's `root` and `related`; a write
5132
- * takes its verb's beside them: a delete `delete`'s, an update, for each
5133
- * field its data writes, that field's `writes` entry, else `update`'s, and
5134
- * `update`'s when its data writes only stamps. A join row's change is a write
5135
- * of the relation on both rows it links; a row only addressed to reach its
5136
- * children is read. A verb left out matches nothing.
4990
+ * `omit` at the TYPE level.
5137
4991
  *
5138
- * The row a write produces is judged too, as a value, against the rows as
5139
- * they stand before the write, inside the statement that writes it (R4): a
5140
- * created row at `place` (a model naming none is not judged on create); an
5141
- * updated row at the predicates that judged its old row, and, for each field
5142
- * its data writes, at that field's `moves` entry, and where it writes the
5143
- * key of an `acyclic` relation (a to-one relation of the model to itself),
5144
- * outside its own subtree. `acyclic` may be a function returning that list:
5145
- * it is called the first time an update writes the key of one of the
5146
- * model's self relations. A refused row is written by no statement.
4992
+ * Three cases, mirroring what the runtime can and cannot know:
4993
+ * - `true` — the key is gone;
4994
+ * - `false` (or absent) — the key stays;
4995
+ * - a widened `boolean` (a variable, a spread, `cond ? true : false`) — only
4996
+ * the runtime decides, so the key becomes OPTIONAL rather than being guessed
4997
+ * into one arm. Claiming it is present would be a lie exactly when the flag
4998
+ * is `true`, which is the case a caller writes this for.
5147
4999
  *
5148
- * `evidence` declares a projection key (`evidence.as`) a `select` or
5149
- * `include` may name at every depth, on reads and on the rows a write
5150
- * returns: per row, whether each of `names` holds there beside `read`, or,
5151
- * `ordered`, the last of them that holds (`null` on a row `read` does not
5152
- * hold). `reads` gates a field on a predicate: the row carries it only where
5153
- * `read` and that predicate hold, a `select` naming it fails on a row
5154
- * without them, and every operand a call writes over it (`where`, `orderBy`,
5155
- * aggregates, `distinct`, unique lookups, relation filters) reads it as
5156
- * absent there. A key or foreign-key field is never gated.
5000
+ * Model-level `.omit()` never appears here: those fields are absent from
5001
+ * `InferModelOutput` already, and the `omit` schema has no key to name them
5002
+ * with (see `src/validation/model/core/projection.ts`).
5157
5003
  */
5158
- type RowsVerbs = {
5159
- readonly predicates: {
5160
- readonly [name: string]: ScalarFields;
5161
- };
5162
- readonly read?: string;
5163
- readonly update?: string;
5164
- readonly delete?: string;
5165
- readonly writes?: {
5166
- readonly [field: string]: string;
5167
- };
5168
- readonly place?: string;
5169
- readonly moves?: {
5170
- readonly [field: string]: string;
5171
- };
5172
- readonly acyclic?: readonly string[] | (() => readonly string[]);
5173
- readonly evidence?: {
5174
- readonly as: string;
5175
- readonly names: readonly string[];
5176
- readonly ordered?: boolean;
5177
- };
5178
- readonly reads?: {
5179
- readonly [field: string]: string;
5180
- };
5181
- };
5004
+ type DefinitelyOmittedKeys<O$1> = { [K in keyof O$1]: [O$1[K]] extends [true] ? K : never }[keyof O$1];
5005
+ type MaybeOmittedKeys<O$1> = { [K in keyof O$1]: [O$1[K]] extends [true] ? never : [O$1[K]] extends [false] ? never : boolean extends O$1[K] ? K : never }[keyof O$1];
5006
+ type ReduceOmit<T$1, O$1> = Omit<T$1, Extract<DefinitelyOmittedKeys<O$1> | MaybeOmittedKeys<O$1>, keyof T$1>> & Partial<Pick<T$1, Extract<MaybeOmittedKeys<O$1>, keyof T$1>>>;
5182
5007
  /**
5183
- * What a delete does on the models named here: an update that stamps `at`
5184
- * with the call's time and writes `assign`, unless the call's controls match
5185
- * `removeWhen`.
5008
+ * An `omit` that MAY be absent decides nothing on its own, so every key it
5009
+ * names softens to a widened `boolean` — which {@link ReduceOmit} renders as an
5010
+ * OPTIONAL key, the same convention a widened flag already follows. It is the
5011
+ * spread idiom's other half: `{ ...(cond && { omit: { title: true } }) }` types
5012
+ * `omit` as optional, and promising `title` outright would be a lie exactly
5013
+ * when `cond` holds.
5186
5014
  */
5187
- type DeletionContribution = {
5188
- readonly removeWhen?: {
5189
- readonly [control: string]: string | number | boolean;
5190
- };
5191
- readonly models: {
5192
- readonly [model: string]: {
5193
- readonly at?: string;
5194
- readonly assign?: ScalarFields;
5195
- };
5196
- };
5197
- };
5015
+ type SoftenNodeOmit<O$1> = { [F in keyof O$1]: boolean };
5016
+ type ApplyOmit<T$1, O$1> = [O$1] extends [undefined] ? T$1 : undefined extends O$1 ? ReduceOmit<T$1, SoftenNodeOmit<Exclude<O$1, undefined>>> : ReduceOmit<T$1, O$1>;
5198
5017
  /**
5199
- * Fields an extension writes on the models named here: `create` on every
5200
- * create of the model, `update` on every update of it, a soft delete's
5201
- * included. A value is a constant, `{ control: "<name>", path?: "a.b" }` for
5202
- * the value the call passed for that control or a field of it (a call that
5203
- * passed none writes nothing there), `{ now: true }` for the call's instant,
5204
- * or, on `update`, one of the field's update operators (`{ increment: 1 }`). A field is written only where the caller left it
5205
- * out: a call that writes it itself, or writes the relation whose foreign key
5206
- * holds it, keeps its own value there. A create may leave out such a field
5207
- * even where the schema requires it: the call's data is checked with it
5208
- * counted as given. When the model names here are known to the types
5209
- * (written out, or kept by a `const` type parameter, not a plain
5210
- * `string[]`), the extended client's types agree, nested creates included:
5211
- * the field is optional on a create. When two extensions name a field, the
5212
- * later one writes it, and a value the caller writes wins over both.
5018
+ * Layer a query-local omission over a configured client default, per field.
5019
+ * A local `false` restores one configured field; an optional local omission
5020
+ * softens only the fields whose runtime value remains undecided.
5213
5021
  */
5214
- type DataContribution = {
5215
- readonly models: {
5216
- readonly [model: string]: {
5217
- readonly create?: ScalarFields;
5218
- readonly update?: ScalarFields;
5219
- };
5220
- };
5221
- };
5222
- /** Operations that select candidates: where a rows control is accepted. */
5223
- type CandidateOperations = Exclude<Operations, "create" | "createMany">;
5224
- /** One declared control as the delegates see it. */
5225
- interface PlacedControl<Value = unknown, Models$1 = PropertyKey, Placed = Operations> {
5226
- readonly value: Value;
5227
- readonly models: Models$1;
5228
- readonly operations: Placed;
5229
- }
5230
- type NoControls = Record<never, never>;
5231
- type ControlValue<Declaration> = Declaration extends {
5232
- readonly oneOf: readonly (infer Value)[];
5233
- } ? Value : Declaration extends {
5234
- readonly schema: StandardSchemaV1<infer Input>;
5235
- } ? Input : never;
5236
- type PlacementOperations<On> = On extends "reads" ? CacheableOperations : On extends "writes" ? MutationOperations : On extends readonly (infer Operation)[] ? Operation : Operations;
5022
+ type MergeClientOmit<Default, Local> = [Default] extends [undefined] ? Local : [Local] extends [undefined] ? Default : undefined extends Local ? Prettify<Omit<Default, keyof Exclude<Local, undefined>> & { [F in keyof Exclude<Local, undefined>]: boolean }> : Prettify<Omit<Default, keyof Local> & Local>;
5237
5023
  /**
5238
- * `deletion` places the control `removeWhen` names: on the deletes of the
5239
- * models it manages, whatever the declaration's `on` says.
5024
+ * The value a node STATES under one projection key, or `undefined` when it
5025
+ * states none.
5026
+ *
5027
+ * INDEXED ACCESS, not `Node extends { omit: infer O }`: a conditional matches a
5028
+ * REQUIRED property, so it reads an OPTIONAL one — the exact shape TypeScript
5029
+ * gives the spread idiom, `{ ...(cond && { select: sel }) }` -> `{ select?: Sel }`
5030
+ * — as "no such key", and the key would silently decide nothing. Indexed access
5031
+ * reports it as `Sel | undefined`, which is the truth: only the runtime knows.
5032
+ *
5033
+ * An object with a string INDEX SIGNATURE states nothing, for the same reason
5034
+ * `NoExtraClauseKeys` (./types.ts) refuses to police one: it declares no spelled
5035
+ * key, and reading `Record<string, unknown>["select"]` as a projection would
5036
+ * turn every dynamically-built payload into the ambiguous arm.
5240
5037
  */
5241
- type PlaceControl<Name$1, Declaration, Deletion> = Deletion extends {
5242
- readonly removeWhen: infer RemoveWhen;
5243
- readonly models: infer Managed;
5244
- } ? Name$1 extends keyof RemoveWhen ? PlacedControl<ControlValue<Declaration>, keyof Managed, "delete" | "deleteMany"> : PlaceFreeControl<Declaration> : PlaceFreeControl<Declaration>;
5245
- type PlaceFreeControl<Declaration> = PlacedControl<ControlValue<Declaration>, PropertyKey, PlacementOperations<Declaration extends {
5246
- readonly on: infer On;
5247
- } ? On : "all">>;
5248
- type DeclaredControls<Definition$1> = Definition$1 extends {
5249
- readonly controls: infer Controls extends ControlsContribution;
5250
- } ? { readonly [Name in keyof Controls as Controls[Name] extends {
5251
- readonly bound: true;
5252
- } ? never : Name]: PlaceControl<Name, Controls[Name], Definition$1 extends {
5253
- readonly deletion: infer Deletion;
5254
- } ? Deletion : unknown> } : NoControls;
5255
- /** Every model entry declares the same mode names: those are the values. */
5256
- type RowsModes<Rows$1 extends RowsContribution> = Rows$1["default"] | { [Model in keyof Rows$1["models"]]: keyof Rows$1["models"][Model] }[keyof Rows$1["models"]];
5257
- /** The rows control: every candidate-selecting operation of every model. */
5258
- type RowsControl<Definition$1> = Definition$1 extends {
5259
- readonly rows: infer Rows extends RowsContribution;
5260
- } ? { readonly [Name in Rows["control"]]: PlacedControl<RowsModes<Rows>, PropertyKey, CandidateOperations> } : NoControls;
5038
+ type NodeKey<Node, Key$1 extends string> = string extends keyof Node ? undefined : Key$1 extends keyof Node ? Node[Extract<Key$1, keyof Node>] : undefined;
5261
5039
  /**
5262
- * The models one definition's `rows` can hide from a relation read: its
5263
- * `models` and `verbs` keys. A to-one relation that targets one of them reads `null` when
5264
- * its target is hidden, so the result types widen it (`result-types.ts`).
5040
+ * Exported so the client layer can keep this query-local value distinct from
5041
+ * its configured default: selected worlds apply only this value, while
5042
+ * unselected worlds merge both before reducing the result.
5265
5043
  */
5266
- type RowsModels<Definition$1> = Definition$1 extends {
5267
- readonly rows: infer Rows extends RowsContribution;
5268
- } ? Extract<keyof Rows["models"] | (Rows extends {
5269
- readonly verbs: infer Verbs;
5270
- } ? keyof Verbs : never), string> : never;
5271
- /** The controls one definition places, keyed by control name. */
5272
- type DefinitionControls<Definition$1> = DeclaredControls<Definition$1> & RowsControl<Definition$1>;
5273
- /** The optional control arguments one (model, operation) accepts. */
5274
- type OperationControls<Controls$1, ModelName$1, Operation$2> = { readonly [Name in keyof Controls$1 as Controls$1[Name] extends PlacedControl<unknown, infer Models, infer Placed> ? ModelName$1 extends Models ? Operation$2 extends Placed ? Name : never : never : never]?: Controls$1[Name] extends PlacedControl<infer Value> ? Value : never };
5044
+ type NodeOmit<Node> = NodeKey<Node, "omit">;
5275
5045
  /**
5276
- * The fields one `data` entry writes on its models' creates: there they may
5277
- * be left out even where the schema requires them. An update's fields need
5278
- * nothing, as every field of an update is optional already.
5046
+ * The parse boundary treats an explicitly-`undefined` key as an ABSENT key
5047
+ * (`src/validation/primitives/object.ts`), which is what makes the
5048
+ * spread-an-optional idiom work; so `{ select: undefined }` and `{}` are the
5049
+ * same payload, and this helper reports them the same way.
5279
5050
  */
5280
- interface StampedFields<Models$1 = PropertyKey, Fields$1 = PropertyKey> {
5281
- readonly models: Models$1;
5282
- readonly fields: Fields$1;
5283
- }
5284
- type CreateStamps<Model$2, Entry> = "create" extends keyof Entry ? Entry extends {
5285
- readonly create?: infer Fields;
5286
- } ? StampedFields<Model$2, keyof NonNullable<Fields>> : never : never;
5051
+ type NodeSelect<Node> = NodeKey<Node, "select">;
5052
+ type NodeInclude<Node> = NodeKey<Node, "include">;
5053
+ /** The public recurrence request stated by one admitted relation node. */
5054
+ type NodeRecurse<Node> = NodeKey<Node, "recurse">;
5055
+ /** The two keys of a polymorphic COLLECTION projection envelope. */
5056
+ type NodeOnly<Projection> = NodeKey<Projection, "only">;
5057
+ type NodeVariants<Projection> = NodeKey<Projection, "variants">;
5287
5058
  /**
5288
- * What one definition's `data` writes on creates: one member per model. A
5289
- * definition whose model names are lost (`{ [model: string]: ... }`, as a
5290
- * recipe called with a plain `string[]` builds) writes nothing the types can
5291
- * name: its required fields stay required in the payloads.
5059
+ * The model that OWNS one asking slot, reconstructed from the state result
5060
+ * inference already carries.
5061
+ *
5062
+ * `Model<State>` is the identity `s.model(...)` returns for that exact state,
5063
+ * which is what the static membership projection compares getters against. It
5064
+ * is not a second model concept: it is the same type, spelled from the half of
5065
+ * it these mapped types thread.
5292
5066
  */
5293
- type DefinitionData<Definition$1> = Definition$1 extends {
5294
- readonly data: {
5295
- readonly models: infer Models;
5296
- };
5297
- } ? string extends keyof Models ? never : { [Model in keyof Models]: CreateStamps<Model, Models[Model]> }[keyof Models] : never;
5298
- /** The fields a chain writes on every create of one model. */
5299
- type StampedFieldNames<Data$1, ModelName$1> = Data$1 extends StampedFields<infer Models, infer Fields extends PropertyKey> ? ModelName$1 extends Models ? Fields : never : never;
5067
+ type SourceModelOf<S$1 extends ModelState> = Model$1<S$1>;
5068
+ /** Does this relation name variants rather than one model? */
5069
+ type IsVariantTarget<R$1 extends AnyRelation> = TargetKind<R$1> extends "variants" ? true : false;
5070
+ /** The configured target model at one public discriminator. */
5071
+ type GetPolymorphicTarget<R$1 extends AnyRelation, PublicType$1 extends PropertyKey> = PublicType$1 extends keyof VariantEntries<R$1> ? VariantEntries<R$1>[PublicType$1] extends {
5072
+ readonly getter: infer Getter;
5073
+ } ? Getter extends (() => infer Target) ? Target extends Model$1<any> ? Target : never : never : never : never;
5074
+ type PolymorphicPublicTypes<R$1 extends AnyRelation> = Extract<keyof VariantEntries<R$1>, string>;
5300
5075
  /**
5301
- * The controls one call admitted, by name. A `rows` control is resolved to its
5302
- * mode, so an absent one reads as its default; an absent plain control is not
5303
- * here.
5076
+ * Result for a relation when included
5077
+ * - To-many relations return arrays
5078
+ * - To-one relations return single objects (nullable if optional)
5304
5079
  */
5305
- type AdmittedControls = Readonly<Record<string, unknown>>;
5306
- //#endregion
5307
- //#region src/extensions/query.d.ts
5308
- type QueryInterceptionMode = "direct" | "transaction" | "array";
5309
- type RawQueryKind = "queryRaw" | "executeRaw" | "queryRawUnsafe" | "executeRawUnsafe";
5310
- type WriteOutcome = Readonly<{
5311
- certainty: "committed" | "may-have-committed";
5312
- }>;
5313
- type WriteOutcomeListener = (outcome: WriteOutcome) => unknown | Promise<unknown>;
5314
- type GenericQueryContextBase<Result> = {
5315
- readonly mode: QueryInterceptionMode;
5316
- readonly input: Readonly<Record<string, unknown>>;
5317
- readonly proceed: () => Promise<Result>;
5318
- readonly onWriteOutcome: (listener: WriteOutcomeListener) => void;
5319
- };
5320
- type GenericModelQueryContext<Result> = GenericQueryContextBase<Result> & {
5321
- readonly kind: "model";
5322
- readonly model: string;
5323
- readonly operation: Operations;
5324
- /** The call's controls this handler's extension declares, and only those. */
5325
- readonly controls?: AdmittedControls;
5326
- };
5327
- type GenericRawQueryContext<Result> = GenericQueryContextBase<Result> & { [Kind in RawQueryKind]: {
5328
- readonly kind: Kind;
5329
- readonly model: undefined;
5330
- readonly operation: `$${Kind}`;
5331
- } }[RawQueryKind];
5332
- type GenericQueryContext<Result> = GenericModelQueryContext<Result> | GenericRawQueryContext<Result>;
5333
- type GenericQueryHandlerCall = <Result>(context: GenericQueryContext<Result>) => Promise<Result>;
5334
- declare const officialQueryHandlerIdentity: unique symbol;
5335
- /** Public ordinary query handler; official identities cannot be erased into it. */
5336
- type GenericQueryHandler = GenericQueryHandlerCall & {
5337
- readonly [officialQueryHandlerIdentity]?: never;
5338
- };
5339
- /** Internal nominal call shape used by official query-based capabilities. */
5340
- type OfficialGenericQueryHandler = GenericQueryHandlerCall & {
5341
- readonly [officialQueryHandlerIdentity]: true;
5342
- };
5343
5080
  /**
5344
- * Per-model query handlers. Their results read the result context of the
5345
- * chain they are applied to: `Hidden` names the models its `rows` can hide
5346
- * (`rows` cannot follow a model-mapped handler, so a later extension adds
5347
- * none). A `rows` entry in the handler's OWN definition is not seen, as no
5348
- * definition types against its own contributions: declare it one step
5349
- * earlier.
5081
+ * The relation's cardinality wrapper, applied to an already-built element type
5082
+ * (plan §8.1's `RelationResult`): a to-many slot is an array, and a singular
5083
+ * slot is nullable unless the static membership projection PROVES it cannot be
5084
+ * empty. `SlotMayBeEmpty` answering a widened `boolean` therefore reads as
5085
+ * nullable, which is the safe direction — the promise "this is always present"
5086
+ * is the one that breaks callers.
5087
+ *
5088
+ * The asking key travels with the relation. Dropping it would let a self
5089
+ * relation select its own declaration as its inverse (§8.1 step 2).
5350
5090
  */
5351
- type QueryHandlerMap<C$1 extends VibORMConfig, Hidden$1 extends string = never> = { readonly [ModelName in keyof ClientSchema<C$1>]?: { readonly [OperationName in Operations]?: <Arg extends Exclude<OperationPayload<OperationName, ClientSchema<C$1>[ModelName]>, undefined>>(context: {
5352
- readonly mode: QueryInterceptionMode;
5353
- readonly kind: "model";
5354
- readonly model: ModelName;
5355
- readonly operation: OperationName;
5356
- readonly input: Readonly<Arg>;
5357
- /** The call's controls this handler's extension declares, and only those. */
5358
- readonly controls?: AdmittedControls;
5359
- readonly proceed: () => Promise<ContextualOperationResult<C$1, ModelName, OperationName, Arg, ClientRowsContext<C$1, Hidden$1>>>;
5360
- readonly onWriteOutcome: (listener: WriteOutcomeListener) => void;
5361
- }) => Promise<ContextualOperationResult<C$1, ModelName, OperationName, Arg, ClientRowsContext<C$1, Hidden$1>>> } };
5362
- //#endregion
5363
- //#region src/cache/capability.d.ts
5364
- declare const OFFICIAL_CACHE_NAME = "viborm.cache";
5365
- /** The exact official query contribution. It is recognized by identity. */
5366
- type OfficialCacheQueryContribution = OfficialGenericQueryHandler & {
5367
- bind(thisArg: unknown): GenericQueryHandler;
5368
- };
5091
+ type WrapRelation<S$1 extends ModelState, K$1, R$1 extends AnyRelation, T$1> = Cardinality<R$1> extends "many" ? T$1[] : SlotMayBeEmpty<SourceModelOf<S$1>, K$1, R$1> extends false ? T$1 : T$1 | null;
5092
+ type WrapRelationNode<S$1 extends ModelState, K$1, R$1 extends AnyRelation, T$1> = [T$1] extends [never] ? never : WrapRelation<S$1, K$1, R$1, T$1>;
5369
5093
  /**
5370
- * A mutation's `cache` argument is the cache's declared control (ruling 7):
5371
- * core removes and admits it before request handlers run, through the cache's
5372
- * own parser, so a malformed value is still a `CacheConfigurationError`.
5094
+ * A singular slot whose target the client's `rows` can hide reads `null` when
5095
+ * it is hidden, whatever the membership proves about the stored reference.
5096
+ * Applied beside {@link WrapRelation}, never inside it: a recursive slot is
5097
+ * always a self relation, which may be empty already (CM002), so only the
5098
+ * outer slot of a node ever needs it.
5373
5099
  */
5374
- type OfficialCacheControls = {
5375
- readonly cache: {
5376
- readonly schema: StandardSchemaV1<CacheInvalidationOptions>;
5377
- readonly on: "writes";
5378
- };
5379
- };
5380
- /** The official value accepted by the dedicated `$extends` overload. */
5381
- type OfficialCacheExtension = {
5382
- readonly name: typeof OFFICIAL_CACHE_NAME;
5383
- readonly query: OfficialCacheQueryContribution;
5384
- readonly controls: OfficialCacheControls;
5385
- };
5386
- //#endregion
5387
- //#region src/client/omit.d.ts
5388
- /** Fields a client hides by default, per model key of the schema. */
5389
- type ClientOmitConfig<S$1 extends Record<string, AnyModel>> = { [K in keyof S$1]?: ClientModelOmit<S$1[K]> };
5100
+ type OrHidden<T$1, R$1 extends AnyRelation, ClientDefaults> = [T$1] extends [never] ? never : Cardinality<R$1> extends "many" ? T$1 : T$1 | HiddenTargetNull<R$1, ClientDefaults>;
5390
5101
  /**
5391
- * The scalars of `M` a client may hide — every scalar except the ones the
5392
- * MODEL already hides for good (naming one of those has no `omit` key to name;
5393
- * see `@validation/model/core/projection`).
5394
- *
5395
- * The `any` arm is not decoration. A schema-generic extension sees
5396
- * `Model<any>`, whose `scalars` is `any` — and the subtraction above would then
5397
- * cancel to `never`, leaving `Partial<Record<never, true>>`, a config object
5398
- * with no known properties. Answering `string` preserves the contextual
5399
- * literal `true` until a concrete schema binds the official extension.
5102
+ * One finite named wrapper for an ordinary inferred node. The wrapper recurs
5103
+ * only through its relation property, so the ordinary projection is inferred
5104
+ * once rather than expanded once per requested depth. The repeated key is
5105
+ * wrapped by {@link WrapRelation}, the same cardinality and emptiness rule as
5106
+ * the outer slot, and its arguments are the same at every level.
5400
5107
  */
5401
- type ProjectableKeysOf<M$1 extends AnyModel> = 0 extends 1 & M$1["~"]["state"]["scalars"] ? string : Extract<Exclude<keyof M$1["~"]["state"]["scalars"], M$1["~"]["state"]["omit"] extends Record<string, true> ? keyof M$1["~"]["state"]["omit"] : never>, string>;
5108
+ type RecursiveRelationNode<Node, S$1 extends ModelState, K$1, R$1 extends AnyRelation, Exhaustive extends boolean> = Node & (Exhaustive extends true ? { [Field in Extract<K$1, PropertyKey>]: WrapRelation<S$1, K$1, R$1, RecursiveRelationNode<Node, S$1, K$1, R$1, Exhaustive>> } : { [Field in Extract<K$1, PropertyKey>]?: WrapRelation<S$1, K$1, R$1, RecursiveRelationNode<Node, S$1, K$1, R$1, Exhaustive>> });
5109
+ type IsExhaustiveRecurrence<Node> = [NodeRecurse<Node>] extends [{
5110
+ readonly depth: false;
5111
+ }] ? true : false;
5112
+ type ApplyRecurrence<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Node, Inferred> = [NodeRecurse<Node>] extends [undefined] ? Inferred : RecursiveRelationNode<Inferred, S$1, K$1, R$1, IsExhaustiveRecurrence<Node>>;
5113
+ type InferRelationResult<S$1 extends ModelState, K$1, R$1 extends AnyRelation, ClientDefaults = never> = OrHidden<WrapRelation<S$1, K$1, R$1, ApplyOmit<InferModelOutput<GetTargetModelState<R$1>>, ResolveClientOmit<GetTargetModel<R$1>, ClientDefaults>>>, R$1, ClientDefaults>;
5114
+ type InferPolymorphicTargetVariant<Target$1 extends Model$1<any>, Override$1, ClientDefaults> = Target$1 extends Model$1<infer TargetState> ? TargetState extends ModelState ? Override$1 extends true ? ApplyOmit<InferModelOutput<TargetState>, ResolveClientOmit<Target$1, ClientDefaults>> : Override$1 extends object ? InferSelectInclude<TargetState, Override$1, NodeSelect<Override$1>, MergeClientOmit<ResolveClientOmit<Target$1, ClientDefaults>, NodeOmit<Override$1>>, ClientDefaults> : ApplyOmit<InferModelOutput<TargetState>, ResolveClientOmit<Target$1, ClientDefaults>> : never : never;
5402
5115
  /**
5403
- * The fields one model hides by default, each flagged `true`.
5404
- *
5405
- * `true` only — not `boolean`. Two reasons, and they are the same reason:
5406
- * - a `false` here would be a key that does nothing (the resolver only ever
5407
- * acts on `=== true`), and a config key that silently does nothing is the
5408
- * shape this codebase refuses; per-field re-inclusion belongs on the QUERY
5409
- * (`omit: { passwordHash: false }`), which is where it can be undone;
5410
- * - `boolean` as the contextual type widens the `true` a caller writes, and a
5411
- * widened flag is a flag the RESULT TYPE cannot resolve — it would render
5412
- * `passwordHash?: string` on a client that hides the column outright.
5116
+ * One configured polymorphic target. A missing projection key does not filter
5117
+ * that discriminator; it keeps the target model's default scalar output.
5413
5118
  */
5414
- type ClientModelOmit<M$1 extends AnyModel> = Partial<Record<ProjectableKeysOf<M$1>, true>>;
5415
- type ClientOmitKeys<Value> = Value extends unknown ? keyof Value : never;
5416
- type ClientOmitEntry<Given, ModelName$1 extends PropertyKey> = Given extends unknown ? ModelName$1 extends keyof Given ? Given[ModelName$1] : never : never;
5417
- /** Structural exactness for a direct client-default omit configuration. */
5418
- type ExactClientOmitConfig<Given, S$1 extends Record<string, AnyModel>> = Record<Exclude<ClientOmitKeys<Given>, keyof S$1>, never> & { [ModelName in Extract<ClientOmitKeys<Given>, keyof S$1>]?: Record<Exclude<ClientOmitKeys<ClientOmitEntry<Given, ModelName>>, keyof ClientModelOmit<S$1[ModelName]>>, never> };
5419
- //#endregion
5420
- //#region src/client/default-omit-extension.d.ts
5421
- declare const OFFICIAL_DEFAULT_OMIT_NAME = "viborm.defaultOmit";
5422
- declare const officialDefaultOmitConfig: unique symbol;
5423
- /** The authenticated request identity carrying one exact static omit witness. */
5424
- type OfficialDefaultOmitRequestContribution<Config> = OfficialGenericRequestHandler & {
5425
- readonly [officialDefaultOmitConfig]: Config;
5426
- bind(thisArg: unknown): GenericRequestHandler;
5427
- };
5428
- /** The official value accepted by the dedicated `$extends` admission branch. */
5429
- type OfficialDefaultOmitExtension<Config extends object = object> = {
5430
- readonly name: typeof OFFICIAL_DEFAULT_OMIT_NAME;
5431
- readonly request: OfficialDefaultOmitRequestContribution<Config>;
5432
- };
5433
- type DefaultOmitBinder<S$1 extends Schema$1> = <const Config extends ClientOmitConfig<S$1>>(config: Config & NoInfer<ExactClientOmitConfig<Config, S$1>>) => OfficialDefaultOmitExtension<Config & object>;
5434
- /** Create VibORM's fixed-name schema-bound default-omit extension. */
5435
- declare function defaultOmit<S$1 extends Schema$1>(): DefaultOmitBinder<S$1>;
5436
- //#endregion
5437
- //#region src/client/result-types.d.ts
5119
+ type InferPolymorphicVariant<R$1 extends AnyRelation, PublicType$1 extends PolymorphicPublicTypes<R$1>, Override$1, ClientDefaults> = GetPolymorphicTarget<R$1, PublicType$1> extends infer Target ? Target extends Model$1<any> ? InferPolymorphicTargetVariant<Target, Override$1, ClientDefaults> : never : never;
5120
+ type PolymorphicProjectionAt<Projection, PublicType$1 extends PropertyKey> = PublicType$1 extends keyof Projection ? Projection[PublicType$1] : undefined;
5438
5121
  /**
5439
- * Maps VibORM scalar types to their DATABASE RESULT types.
5440
- * This is what the ORM returns after querying the database.
5122
+ * One arm out of a collection's `variants` container.
5441
5123
  *
5442
- * Key difference from validation schema output:
5443
- * - datetime/date/time: returns Date (not ISO string)
5444
- * - json: inferred from custom schema if present, otherwise unknown
5445
- * - enum: inferred from schema values
5124
+ * The `Exclude` + re-added `undefined` is not decoration: `PolymorphicProjectionAt`
5125
+ * distributes over the KEY, not over the container, and `keyof (X | undefined)`
5126
+ * is `never` — so a container that MAY be undefined would answer `undefined`
5127
+ * for every arm, i.e. "no projection stated", i.e. the full default row. That
5128
+ * is the unsafe direction: the runtime may well apply the projection and return
5129
+ * fewer columns than the type promised.
5130
+ *
5131
+ * Splitting the container instead hands `InferPolymorphicTargetVariant` a
5132
+ * `Configured | undefined` override, which it already distributes into
5133
+ * `Selected | Default` — the honest union a caller in this position narrows.
5446
5134
  */
5447
- type ScalarResultTypeMap = {
5448
- string: string;
5449
- int: number;
5450
- number: number;
5451
- decimal: Decimal;
5452
- boolean: boolean;
5453
- datetime: Date;
5454
- date: Date;
5455
- time: string;
5456
- bigint: bigint;
5457
- json: unknown;
5458
- blob: Uint8Array;
5459
- vector: number[];
5460
- point: GeoPoint;
5461
- enum: string;
5462
- };
5135
+ type PolymorphicArmAt<Variants$1, PublicType$1 extends PropertyKey> = PolymorphicProjectionAt<Exclude<Variants$1, undefined>, PublicType$1> | (undefined extends Variants$1 ? undefined : never);
5463
5136
  /**
5464
- * Extract the ScalarState from a Scalar using infer to preserve literal types.
5137
+ * Exhaustive direct polymorphic result. Projection objects override individual
5138
+ * targets; omitted targets remain in the union with their default projection.
5465
5139
  */
5466
- type ExtractScalarState<F$1> = F$1 extends {
5467
- "~": {
5468
- state: infer S;
5469
- };
5470
- } ? S extends ScalarState ? S : never : never;
5140
+ type PolymorphicVariants<R$1 extends AnyRelation, Projection = undefined, ClientDefaults = never> = { [PublicType in PolymorphicPublicTypes<R$1>]: {
5141
+ readonly type: PublicType;
5142
+ readonly data: InferPolymorphicVariant<R$1, PublicType, PolymorphicProjectionAt<Projection, PublicType>, ClientDefaults>;
5143
+ } }[PolymorphicPublicTypes<R$1>];
5471
5144
  /**
5472
- * Get the base scalar type for a field, handling custom schemas.
5473
- * For json/enum scalars with custom schemas, infer from the schema.
5474
- * For datetime fields, always return Date (regardless of validation schema output).
5145
+ * The variants a COLLECTION projection can still produce, after `only`.
5475
5146
  *
5476
- * The enum arm reads the scalar's own `base` schema, so an enum's literal union
5477
- * survives a relation read exactly as it does a direct one: this helper is
5478
- * reached through the same `InferScalarOutput` on both paths.
5479
- */
5480
- type GetScalarResultType<F$1 extends Scalar> = ExtractScalarState<F$1> extends infer S ? S extends ScalarState ? S["type"] extends "json" ? S["schema"] extends StandardSchemaV1<any, infer O> ? O : unknown : S["type"] extends "enum" ? EnumValues<S["base"]>[number] : ScalarResultTypeMap[S["type"]] : unknown : unknown;
5481
- /**
5482
- * Apply nullable wrapper based on scalar state.
5483
- * Uses non-distributive check to handle boolean literals correctly.
5147
+ * The two `undefined` tests are ordered, and the order is the whole point:
5148
+ *
5149
+ * - `[Only] extends [undefined]` — the key is ABSENT (or the payload has an
5150
+ * index signature, which states nothing). Every variant survives.
5151
+ * - `undefined extends Only` — the key MAY be undefined, the shape real code
5152
+ * produces (`only: cond ? ["post"] : undefined`, or a forwarded optional
5153
+ * property). Only the runtime knows, so nothing is narrowed. This MUST be
5154
+ * tested BEFORE the element extraction: `readonly ["post"] | undefined`
5155
+ * matches `readonly (infer T)[]` on its defined member and would otherwise
5156
+ * narrow to `"post"` on a call that may not narrow at all.
5157
+ * - the tuple/array case narrows to the named members.
5158
+ * - anything else (a `string[]` built at runtime, an unresolvable generic)
5159
+ * narrows nothing, which is the honest answer.
5484
5160
  */
5485
- type ApplyNullable<T$1, Nullable> = [Nullable] extends [true] ? T$1 | null : T$1;
5161
+ type AllowedPublicTypes<R$1 extends AnyRelation, Only> = [Only] extends [undefined] ? PolymorphicPublicTypes<R$1> : undefined extends Only ? PolymorphicPublicTypes<R$1> : Only extends readonly (infer T)[] ? Extract<T, PolymorphicPublicTypes<R$1>> : PolymorphicPublicTypes<R$1>;
5486
5162
  /**
5487
- * Apply array wrapper based on scalar state.
5488
- * Uses non-distributive check to handle boolean literals correctly.
5163
+ * One element of a collection result: the same `{ type, data }` envelope the
5164
+ * to-one slot produces, but reached through `variants` rather than through the
5165
+ * projection's top level — which is what lets a public variant literally named
5166
+ * `only` or `variants` keep working.
5489
5167
  */
5490
- type ApplyArray<T$1, IsArray> = [IsArray] extends [true] ? T$1[] : T$1;
5168
+ type PolymorphicCollectionVariants<R$1 extends AnyRelation, Projection, ClientDefaults> = { [PublicType in AllowedPublicTypes<R$1, NodeOnly<Projection>>]: {
5169
+ readonly type: PublicType;
5170
+ readonly data: InferPolymorphicVariant<R$1, PublicType, PolymorphicArmAt<NodeVariants<Projection>, PublicType>, ClientDefaults>;
5171
+ } }[AllowedPublicTypes<R$1, NodeOnly<Projection>>];
5491
5172
  /**
5492
- * Infer the DATABASE RESULT type for a scalar.
5173
+ * CARDINALITY FIRST, through the same reader both target domains use — never by
5174
+ * testing `state.cardinality` inline, so one rule governs both levels.
5493
5175
  *
5494
- * This is the canonical helper for inferring output types from scalars.
5495
- * It correctly handles:
5496
- * - All scalar types with proper DB result mapping (datetime → Date)
5497
- * - Custom schemas for json/enum scalars
5498
- * - Nullable scalars
5499
- * - Array scalars
5176
+ * A collection is NEVER `| null`: an empty collection is `[]`, and `.optional()`
5177
+ * is unspellable on a collection state precisely so emptiness has one reading.
5178
+ * The singular arm asks the SAME `SlotMayBeEmpty` an ordinary slot asks; for a
5179
+ * variant target that projection is exactly the declared `.optional()` (§8.1).
5500
5180
  *
5501
- * @example
5502
- * // For s.dateTime().nullable() → Date | null
5503
- * // For s.string().array() → string[]
5504
- * // For s.json().schema(z.object({...})) → { ... }
5181
+ * The array wrapper is applied UNCONDITIONALLY, outside `WrapRelationNode`'s
5182
+ * never-collapse. `only: []` legitimately produces a `never` element union, and
5183
+ * collapsing that to `never` would type a call that returns a fresh empty array
5184
+ * as returning nothing at all; `readonly never[]` is the shape that matches.
5505
5185
  */
5506
- type InferScalarOutput<F$1 extends Scalar> = ExtractScalarState<F$1> extends infer S ? S extends ScalarState ? ApplyNullable<ApplyArray<GetScalarResultType<F$1>, S["array"]>, S["nullable"]> : never : never;
5186
+ type InferPolymorphicResult<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Projection = undefined, ClientDefaults = never> = Cardinality<R$1> extends "many" ? readonly PolymorphicCollectionVariants<R$1, Projection, ClientDefaults>[] : SlotMayBeEmpty<SourceModelOf<S$1>, K$1, R$1> extends false ? PolymorphicVariants<R$1, Projection, ClientDefaults> | HiddenTargetNull<R$1, ClientDefaults> : PolymorphicVariants<R$1, Projection, ClientDefaults> | null;
5507
5187
  /**
5508
- * Result for batch operations (createMany, updateMany, deleteMany)
5188
+ * Infer result from select/include args
5189
+ * - select: ONLY returns selected fields
5190
+ * - include: returns base model + included relations
5191
+ * - neither: returns base model output
5192
+ *
5193
+ * The dispatch is on the select VALUE, not on key presence. `{ select: undefined }`
5194
+ * is the spread-an-optional idiom collapsed to a literal `undefined`, and the
5195
+ * parse boundary hands the engine a payload with no projection at all — so it
5196
+ * returns the full default row, exactly like `{}`. Reading it as "a selection of
5197
+ * nothing" typed that call `{}`, and `rows[0].id` stopped compiling on a call
5198
+ * that returns `id` at runtime.
5199
+ *
5200
+ * `select` + `include` is refused only when both keys carry values. `omit`
5201
+ * composes with either projection mode: in the selected world it subtracts
5202
+ * from the selected shape; in the unselected world it subtracts from the
5203
+ * default scalar shape.
5509
5204
  */
5510
- interface BatchPayload {
5511
- count: number;
5512
- }
5205
+ type InferSelectInclude<S$1 extends ModelState, Args, Selection$1 = NodeSelect<Args>, UnselectedOmit = NodeOmit<Args>, ClientDefaults = never> = [Selection$1] extends [undefined] ? InferUnselectedRow<S$1, Args, UnselectedOmit, ClientDefaults> : undefined extends Selection$1 ? InferUnselectedRow<S$1, Args, UnselectedOmit, ClientDefaults> | InferSelectedRow<S$1, Args, Exclude<Selection$1, undefined>, ClientDefaults> : InferSelectedRow<S$1, Args, Selection$1, ClientDefaults>;
5513
5206
  /**
5514
- * Result type for count operations
5515
- * Supports select for per-field counts like Prisma: count({ select: { _all: true, name: true } })
5207
+ * The row a node returns in the world where its `select` carries a value.
5208
+ *
5209
+ * `select` is exclusive with `include`, so a definite include makes this world
5210
+ * impossible. A local `omit` is different: it subtracts from the selected
5211
+ * result. Keys outside the selected shape have no effect.
5516
5212
  */
5517
- /** Literal selections are required; runtime choices expose optional fields. */
5518
- type SelectedFields<Selection$1, Fields$1> = { [K in keyof Selection$1 & keyof Fields$1 as Selection$1[K] extends true | object ? K : never]: Fields$1[K] } & { [K in keyof Selection$1 & keyof Fields$1 as Selection$1[K] extends true | object ? never : Extract<Selection$1[K], true | object> extends never ? never : K]?: Fields$1[K] };
5519
- type SelectedCountResult<Selection$1> = Prettify<SelectedFields<Selection$1, { [K in keyof Selection$1]: number }>>;
5520
- type CountResultType<Args, Selected = (Args extends {
5521
- select: infer Selection;
5522
- } ? SelectedCountResult<Selection> : never)> = Args extends {
5523
- select: unknown;
5524
- } ? keyof Selected extends never ? number : Selected : number;
5213
+ type InferSelectedRow<S$1 extends ModelState, Args, Selection$1, ClientDefaults> = undefined extends NodeInclude<Args> ? InferSelectResult<S$1, Selection$1, NodeOmit<Args>, ClientDefaults> : never;
5525
5214
  /**
5526
- * The non-recursive part of a model that result inference can compare safely.
5215
+ * The row a node returns when it states no `select`: the model's own output,
5216
+ * plus whatever `include` adds, reduced by the node's `omit`.
5527
5217
  *
5528
- * Full `Model` equality walks relation getters and collapses mutually-recursive
5529
- * model consts. These two key sets identify the usual case without touching any
5530
- * scalar implementation, external schema, or relation target. There are two,
5531
- * not three, because a model now holds ONE relation map across both target
5532
- * domains (§5.2).
5218
+ * An `include` that MAY be absent is read as ABSENT — the common ground of both
5219
+ * worlds — while a MAYBE `omit` softens instead (`ApplyOmit`). The asymmetry is
5220
+ * the direction of the lie: `include` only ADDS keys, so promising the smaller
5221
+ * row promises nothing that is missing at runtime, and the caller who wants the
5222
+ * relation spells the `include` definitely; `omit` REMOVES them, so reading a
5223
+ * maybe-omit as absent would promise a column the runtime may have dropped.
5533
5224
  */
5534
- type ModelResultSurface<M$1 extends Model$1<any>> = M$1 extends Model$1<infer S> ? readonly [Extract<keyof S["scalars"], string>, Extract<keyof S["relations"], string>] : never;
5535
- type SameKeySet<Left, Right> = [Exclude<Left, Right>] extends [never] ? [Exclude<Right, Left>] extends [never] ? true : false : false;
5536
- type IsUsableModelResultSurface<Surface> = [Surface] extends [never] ? false : Surface extends readonly [infer Scalars, infer Relations] ? string extends Scalars ? false : string extends Relations ? false : true : false;
5537
- /** Exact equality for the two shallow key sets above. */
5538
- type SameModelResultSurface<Left, Right> = IsUsableModelResultSurface<Left> extends true ? IsUsableModelResultSurface<Right> extends true ? Left extends readonly [infer LS, infer LR] ? Right extends readonly [infer RS, infer RR] ? SameKeySet<LS, RS> extends true ? SameKeySet<LR, RR> : false : false : false : false : false;
5225
+ type InferUnselectedRow<S$1 extends ModelState, Args, Omission = NodeOmit<Args>, ClientDefaults = never> = undefined extends NodeInclude<Args> ? ApplyOmit<InferModelOutput<S$1>, Omission> : ApplyOmit<InferIncludeResult<S$1, NodeInclude<Args>, ClientDefaults>, Omission>;
5539
5226
  /**
5540
- * The shallow surfaces of the models whose rows a client's `rows` can hide
5541
- * from a relation read (`ClientRowsContext`, ./types.ts). It rides the same
5542
- * result context as the omission defaults, as one more member of the union.
5227
+ * Result when select is provided - ONLY selected fields are returned
5543
5228
  */
5544
- interface ClientHiddenContext<Surfaces> {
5545
- readonly hidden: Surfaces;
5546
- }
5229
+ type InferSelectResult<S$1 extends ModelState, Selection$1, Omission = undefined, ClientDefaults = never> = Prettify<ApplyOmit<InferSelectedFields<S$1, Selection$1, ClientDefaults> & InferRelationCountSelection<S$1, Selection$1>, Omission> & InferDistanceSelection<S$1, Selection$1, Omission>>;
5547
5230
  /**
5548
- * `null` where a relation read can find this target hidden, and nothing
5549
- * otherwise. Models are compared by their shallow surface, as the omission
5550
- * defaults are: a target that shares its surface with a hidden model widens
5551
- * with it, and a surface too wide to compare widens too, both on the `| null`
5552
- * side. It distributes over the context, so a client without `rows` never
5553
- * resolves a target, and TypeScript measures the context parameter of every
5554
- * result type through it cheaply: the `[Hidden] extends [never]` form it
5555
- * replaces cost the schema-only floor 33,535 types (measured, U7 repair).
5231
+ * ONE mapped type over the model's shape, dispatching per member on TARGET KIND.
5232
+ *
5233
+ * There is no second polymorphic pass any more: both target domains live in the
5234
+ * one relation map (§5.2), and what still differs is only the ELEMENT shape a
5235
+ * variant slot produces — a discriminated `{ type, data }` union reached through
5236
+ * its own projection envelope. Splitting the map again here would put the same
5237
+ * key through two mapped types and let their guards drift apart.
5556
5238
  */
5557
- type HiddenTargetNull<R$1 extends AnyRelation, Context> = Context extends ClientHiddenContext<infer Hidden> ? true extends HidesTarget<R$1, Hidden> ? null : never : never;
5558
- type HidesTarget<R$1 extends AnyRelation, Hidden$1> = Hidden$1 extends unknown ? IsUsableModelResultSurface<Hidden$1> extends false ? true : MatchesSurface<TargetSurfaces<R$1>, Hidden$1> : never;
5559
- type MatchesSurface<Surface, Hidden$1> = Surface extends unknown ? IsUsableModelResultSurface<Surface> extends false ? true : SameModelResultSurface<Surface, Hidden$1> : never;
5560
- /** The shallow surface of each model a relation can target. */
5561
- type TargetSurfaces<R$1 extends AnyRelation> = IsVariantTarget<R$1> extends true ? ModelResultSurface<GetPolymorphicTarget<R$1, PolymorphicPublicTypes<R$1>>> : ModelResultSurface<GetTargetModel<R$1>>;
5562
- /** One configured model's compact, client-owned result default. */
5563
- interface ClientResultOmitEntry<Surface, Omission, Unique> {
5564
- readonly surface: Surface;
5565
- readonly omission: Omission;
5566
- readonly unique: Unique;
5567
- }
5568
- /** Named boundary so TypeScript can cache the carrier during result recursion. */
5569
- interface ClientResultOmitContext<Entries$1> {
5570
- readonly entries: Entries$1;
5571
- }
5572
- type EntrySurface<Entry> = Entry extends ClientResultOmitEntry<infer Surface, unknown, unknown> ? Surface : never;
5573
- type MatchingClientOmitEntries<M$1 extends Model$1<any>, Context, Entries$1 = (Context extends ClientResultOmitContext<infer E> ? E : never)> = M$1 extends unknown ? Entries$1 extends unknown ? true extends SameModelResultSurface<ModelResultSurface<M$1>, EntrySurface<Entries$1>> ? Entries$1 : never : never : never;
5574
- type IsUnion<T$1, Whole = T$1> = T$1 extends Whole ? [Whole] extends [T$1] ? false : true : never;
5575
- type HasMultipleModelResultSurfaces<M$1 extends Model$1<any>, WholeSurface = ModelResultSurface<M$1>> = M$1 extends unknown ? SameModelResultSurface<ModelResultSurface<M$1>, WholeSurface> extends true ? false : true : never;
5576
- type EntryOmission<Entry> = Entry extends ClientResultOmitEntry<unknown, infer Omission, unknown> ? Omission : never;
5577
- type EntryUnique<Entry> = Entry extends ClientResultOmitEntry<unknown, unknown, infer Unique> ? Unique : never;
5578
- type PossibleOmitKeys<Entry> = Entry extends unknown ? keyof Exclude<EntryOmission<Entry>, undefined> : never;
5579
- type SoftenedResolvedOmit<Keys$1 extends PropertyKey> = [Keys$1] extends [never] ? undefined : { [K in Keys$1]: boolean };
5239
+ type InferSelectedFields<S$1 extends ModelState, Selection$1, ClientDefaults> = SelectedFields<Selection$1, { [K in keyof Selection$1 & keyof S$1["shape"] as S$1["shape"][K] extends Scalar ? true extends Selection$1[K] ? K : never : K]: S$1["shape"][K] extends Scalar ? InferScalarOutput<S$1["shape"][K]> : S$1["shape"][K] extends AnyRelation ? InferSelectedRelation<S$1, K, S$1["shape"][K], Selection$1[K], ClientDefaults> : never }>;
5240
+ /** One selected relation member, per target kind then per projection value. */
5241
+ type InferSelectedRelation<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Projection, ClientDefaults> = IsVariantTarget<R$1> extends true ? Projection extends true ? InferPolymorphicResult<S$1, K$1, R$1, undefined, ClientDefaults> : Projection extends object ? InferPolymorphicResult<S$1, K$1, R$1, Projection, ClientDefaults> : never : Projection extends true ? InferRelationResult<S$1, K$1, R$1, ClientDefaults> : Projection extends object ? InferRelationNodeResult<S$1, K$1, R$1, Projection, ClientDefaults> : never;
5242
+ type VectorScalarFieldKeys<S$1 extends ModelState> = { [K in keyof S$1["shape"]]: S$1["shape"][K] extends Scalar ? [ExtractScalarState<S$1["shape"][K]>] extends [ScalarState<"vector">] ? K : never : never }[keyof S$1["shape"]];
5243
+ type PointScalarFieldKeys<S$1 extends ModelState> = { [K in keyof S$1["shape"]]: S$1["shape"][K] extends Scalar ? [ExtractScalarState<S$1["shape"][K]>] extends [ScalarState<"point">] ? K : never : never }[keyof S$1["shape"]];
5244
+ type NullableDistanceScalarFieldKeys<S$1 extends ModelState> = { [K in DistanceScalarFieldKeys<S$1>]: S$1["shape"][K] extends Scalar ? ExtractScalarState<S$1["shape"][K]>["nullable"] extends true ? K : never : never }[DistanceScalarFieldKeys<S$1>];
5245
+ type DistanceScalarFieldKeys<S$1 extends ModelState> = VectorScalarFieldKeys<S$1> | PointScalarFieldKeys<S$1>;
5246
+ type SelectedDistanceKeys<S$1 extends ModelState, Selection$1> = { [K in keyof Selection$1 & DistanceScalarFieldKeys<S$1>]: Selection$1[K] extends {
5247
+ _distance: unknown;
5248
+ } ? K : never }[keyof Selection$1 & DistanceScalarFieldKeys<S$1>];
5249
+ type SelectedDistanceSources<S$1 extends ModelState, Selection$1> = { [K in SelectedDistanceKeys<S$1, Selection$1>]: true };
5250
+ type RemainingDistanceSources<S$1 extends ModelState, Selection$1, Omission> = ApplyOmit<SelectedDistanceSources<S$1, Selection$1>, Omission>;
5251
+ type RequiredKeys<T$1> = { [K in keyof T$1]-?: Record<never, never> extends Pick<T$1, K> ? never : K }[keyof T$1];
5252
+ type CosineDistanceKeys<S$1 extends ModelState, Selection$1> = { [K in keyof Selection$1 & VectorScalarFieldKeys<S$1>]: Selection$1[K] extends {
5253
+ _distance: {
5254
+ metric: infer Metric;
5255
+ };
5256
+ } ? "cosine" extends Metric ? K : never : never }[keyof Selection$1 & VectorScalarFieldKeys<S$1>];
5257
+ type DistanceValueForSources<S$1 extends ModelState, Sources, Selection$1> = Extract<keyof Sources, NullableDistanceScalarFieldKeys<S$1> | CosineDistanceKeys<S$1, Selection$1>> extends never ? number : number | null;
5258
+ type InferDistanceSelection<S$1 extends ModelState, Selection$1, Omission = undefined, Remaining = RemainingDistanceSources<S$1, Selection$1, Omission>> = [keyof Remaining] extends [never] ? Record<never, never> : [RequiredKeys<Remaining>] extends [never] ? {
5259
+ _distance?: DistanceValueForSources<S$1, Remaining, Selection$1>;
5260
+ } : {
5261
+ _distance: DistanceValueForSources<S$1, Remaining, Selection$1>;
5262
+ };
5580
5263
  /**
5581
- * Resolve a nested target's client default without comparing model graphs.
5264
+ * To-many (list) relation keys — the exact set Prisma's `_count: true`
5265
+ * shorthand expands to (`<Model>CountOutputType` holds only list relations).
5582
5266
  *
5583
- * A unique shallow surface identifies the configured model exactly. When two
5584
- * schema models have the same surface, the current public types contain no
5585
- * nominal identity that can distinguish their runtime objects. In that case,
5586
- * every possibly omitted field becomes a widened boolean; `ApplyOmit` renders
5587
- * it optional, which is honest in both runtime worlds.
5267
+ * ONE rule for both target domains: a variant collection is a list relation by
5268
+ * every reading that matters here — it holds many rows and it has a count.
5588
5269
  */
5589
- type ResolveClientOmit<M$1 extends Model$1<any>, Context, Matches = MatchingClientOmitEntries<M$1, Context>, AmbiguousKeys extends PropertyKey = PossibleOmitKeys<Matches>> = [Context] extends [never] ? undefined : [Matches] extends [never] ? undefined : true extends HasMultipleModelResultSurfaces<M$1> ? SoftenedResolvedOmit<AmbiguousKeys> : true extends IsUnion<EntryOmission<Matches>> ? SoftenedResolvedOmit<AmbiguousKeys> : false extends EntryUnique<Matches> ? SoftenedResolvedOmit<AmbiguousKeys> : EntryOmission<Matches>;
5590
- /** Get the target model itself without resolving its recursive state. */
5591
- type GetTargetModel<R$1 extends AnyRelation> = TargetGetter<R$1> extends (() => infer Target) ? Target extends Model$1<any> ? Target : never : never;
5270
+ type ToManyRelationKeys<S$1 extends ModelState> = { [K in keyof S$1["relations"]]: S$1["relations"][K] extends AnyRelation ? Cardinality<S$1["relations"][K]> extends "many" ? K : never : never }[keyof S$1["relations"]];
5592
5271
  /**
5593
- * Get the target model's state from a relation
5272
+ * The relation keys the EXPLICIT `_count: { select: … }` form may name.
5273
+ *
5274
+ * A deliberate superset of Prisma's, minus one cell: a variant SINGULAR slot's
5275
+ * `countFilter` family is a named refusal, so naming it must not compile either.
5276
+ * An ordinary singular relation stays nameable, as it is today.
5594
5277
  */
5595
- type GetTargetModelState<R$1 extends AnyRelation> = GetTargetModel<R$1> extends infer T ? T extends Model$1<infer S> ? S extends ModelState ? S : never : never : never;
5278
+ type CountableRelationKeys<S$1 extends ModelState> = { [K in keyof S$1["relations"]]: S$1["relations"][K] extends AnyRelation ? IsVariantTarget<S$1["relations"][K]> extends true ? Cardinality<S$1["relations"][K]> extends "many" ? K : never : K : never }[keyof S$1["relations"]];
5279
+ type InferRelationCountSelection<S$1 extends ModelState, Selection$1> = Selection$1 extends {
5280
+ _count: {
5281
+ select: infer CountSelection;
5282
+ };
5283
+ } ? {
5284
+ _count: { [K in keyof CountSelection & CountableRelationKeys<S$1> as CountSelection[K] extends true | object ? K : never]: number };
5285
+ } : Selection$1 extends {
5286
+ _count: true;
5287
+ } ? {
5288
+ _count: { [K in ToManyRelationKeys<S$1>]: number };
5289
+ } : Record<never, never>;
5596
5290
  /**
5597
- * Infer the output type for a model, respecting omit settings.
5598
- * Uses InferScalarOutput for correct DB result types (e.g., Date for datetime).
5291
+ * Result when include is provided - base result + included relations
5599
5292
  */
5600
- type InferModelOutput<S$1 extends ModelState> = S$1["omit"] extends Record<string, true> ? Omit<{ [K in keyof S$1["scalars"]]: S$1["scalars"][K] extends Scalar ? InferScalarOutput<S$1["scalars"][K]> : never }, keyof S$1["omit"]> : { [K in keyof S$1["scalars"]]: S$1["scalars"][K] extends Scalar ? InferScalarOutput<S$1["scalars"][K]> : never };
5293
+ type InferIncludeResult<S$1 extends ModelState, Include$1, ClientDefaults = never> = Prettify<InferModelOutput<S$1> & { [K in keyof Include$1 & keyof S$1["relations"] as Include$1[K] extends true | object ? K : never]: S$1["relations"][K] extends AnyRelation ? InferSelectedRelation<S$1, K, S$1["relations"][K], Include$1[K], ClientDefaults> : never } & InferRelationCountSelection<S$1, Include$1>>;
5601
5294
  /**
5602
- * `omit` at the TYPE level.
5603
- *
5604
- * Three cases, mirroring what the runtime can and cannot know:
5605
- * - `true` — the key is gone;
5606
- * - `false` (or absent) — the key stays;
5607
- * - a widened `boolean` (a variable, a spread, `cond ? true : false`) — only
5608
- * the runtime decides, so the key becomes OPTIONAL rather than being guessed
5609
- * into one arm. Claiming it is present would be a lie exactly when the flag
5610
- * is `true`, which is the case a caller writes this for.
5611
- *
5612
- * Model-level `.omit()` never appears here: those fields are absent from
5613
- * `InferModelOutput` already, and the `omit` schema has no key to name them
5614
- * with (see `src/validation/model/core/projection.ts`).
5295
+ * A relation node in `select`/`include` position: `{ select }`, `{ include }`,
5296
+ * `{ omit }`, pagination-only (`{ where, take, … }`), or any combination the
5297
+ * parse boundary accepts. A selected node applies its local omit after the
5298
+ * selection. An unselected node applies it to the default/include shape.
5299
+ * Pagination-only nodes fall through to the full relation payload.
5615
5300
  */
5616
- type DefinitelyOmittedKeys<O$1> = { [K in keyof O$1]: [O$1[K]] extends [true] ? K : never }[keyof O$1];
5617
- type MaybeOmittedKeys<O$1> = { [K in keyof O$1]: [O$1[K]] extends [true] ? never : [O$1[K]] extends [false] ? never : boolean extends O$1[K] ? K : never }[keyof O$1];
5618
- type ReduceOmit<T$1, O$1> = Omit<T$1, Extract<DefinitelyOmittedKeys<O$1> | MaybeOmittedKeys<O$1>, keyof T$1>> & Partial<Pick<T$1, Extract<MaybeOmittedKeys<O$1>, keyof T$1>>>;
5301
+ type InferRelationNodeResult<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Node, ClientDefaults = never> = OrHidden<WrapRelationNode<S$1, K$1, R$1, ApplyRecurrence<S$1, K$1, R$1, Node, InferSelectInclude<GetTargetModelState<R$1>, Node, NodeSelect<Node>, MergeClientOmit<ResolveClientOmit<GetTargetModel<R$1>, ClientDefaults>, NodeOmit<Node>>, ClientDefaults>>>, R$1, ClientDefaults>;
5619
5302
  /**
5620
- * An `omit` that MAY be absent decides nothing on its own, so every key it
5621
- * names softens to a widened `boolean` — which {@link ReduceOmit} renders as an
5622
- * OPTIONAL key, the same convention a widened flag already follows. It is the
5623
- * spread idiom's other half: `{ ...(cond && { omit: { title: true } }) }` types
5624
- * `omit` as optional, and promising `title` outright would be a lie exactly
5625
- * when `cond` holds.
5303
+ * Extract scalar keys from a ModelShape
5626
5304
  */
5627
- type SoftenNodeOmit<O$1> = { [F in keyof O$1]: boolean };
5628
- type ApplyOmit<T$1, O$1> = [O$1] extends [undefined] ? T$1 : undefined extends O$1 ? ReduceOmit<T$1, SoftenNodeOmit<Exclude<O$1, undefined>>> : ReduceOmit<T$1, O$1>;
5305
+ type ScalarKeys$1<T$1 extends ModelShape> = { [K in keyof T$1]: T$1[K] extends Scalar ? K : never }[keyof T$1];
5629
5306
  /**
5630
- * Layer a query-local omission over a configured client default, per field.
5631
- * A local `false` restores one configured field; an optional local omission
5632
- * softens only the fields whose runtime value remains undecided.
5307
+ * Infer base type from a scalar for aggregates.
5308
+ * Uses InferScalarOutput for correct DB result types.
5633
5309
  */
5634
- type MergeClientOmit<Default, Local> = [Default] extends [undefined] ? Local : [Local] extends [undefined] ? Default : undefined extends Local ? Prettify<Omit<Default, keyof Exclude<Local, undefined>> & { [F in keyof Exclude<Local, undefined>]: boolean }> : Prettify<Omit<Default, keyof Local> & Local>;
5310
+ type InferScalarBase<F$1> = F$1 extends Scalar ? InferScalarOutput<F$1> : never;
5311
+ /** True when the scalar is a decimal, whose aggregates stay exact Decimals. */
5312
+ type IsDecimalScalar<F$1> = ExtractScalarState<F$1> extends {
5313
+ type: "decimal";
5314
+ } ? true : false;
5635
5315
  /**
5636
- * The value a node STATES under one projection key, or `undefined` when it
5637
- * states none.
5316
+ * Result type for aggregate operations
5317
+ * Dynamically typed based on which aggregates are requested
5638
5318
  *
5639
- * INDEXED ACCESS, not `Node extends { omit: infer O }`: a conditional matches a
5640
- * REQUIRED property, so it reads an OPTIONAL one — the exact shape TypeScript
5641
- * gives the spread idiom, `{ ...(cond && { select: sel }) }` -> `{ select?: Sel }`
5642
- * — as "no such key", and the key would silently decide nothing. Indexed access
5643
- * reports it as `Sel | undefined`, which is the truth: only the runtime knows.
5319
+ * THE RULE, and it is the RESULT PARSER's rule, not a guess:
5320
+ * `result-aggregate-parser.ts` marks `_sum` / `_min` / `_max` as `typed` and
5321
+ * decodes them through the FIELD'S OWN scalar decoder, so those three come back
5322
+ * spelled exactly like the column — `_sum` of an `s.bigInt()` is a `bigint`,
5323
+ * `_sum` of an `s.decimal({ precision, scale })` is an exact `Decimal`
5324
+ * (widened in precision, but still the field's scale). Only `_avg` takes the
5325
+ * widen-to-number path, and even it stays a `Decimal` for a decimal, because an
5326
+ * average of decimals is still a decimal — quantized to the field scale with
5327
+ * round-half-to-even.
5644
5328
  *
5645
- * An object with a string INDEX SIGNATURE states nothing, for the same reason
5646
- * `NoExtraClauseKeys` (./types.ts) refuses to police one: it declares no spelled
5647
- * key, and reading `Record<string, unknown>["select"]` as a projection would
5648
- * turn every dynamically-built payload into the ambiguous arm.
5329
+ * `_sum` used to be typed `number` for everything but a decimal, which made
5330
+ * `agg._sum.big * 2` type-check and then throw "Cannot mix BigInt and other
5331
+ * types" — and, worse, `agg._sum.big === 150` silently false. The decoder is the
5332
+ * half that is pinned behaviorally (tests/drivers/scalar-roundtrip-behavior.ts),
5333
+ * so the type follows it.
5649
5334
  */
5650
- type NodeKey<Node, Key$1 extends string> = string extends keyof Node ? undefined : Key$1 extends keyof Node ? Node[Extract<Key$1, keyof Node>] : undefined;
5335
+ type AggregateResultType<T$1 extends ModelShape, Args> = Prettify<SelectedFields<Args, { [K in keyof Args as K extends `_${string}` ? K : never]: K extends "_count" ? Args[K] extends boolean ? number : Args[K] extends object ? SelectedCountResult<Args[K]> : never : K extends "_sum" ? Args[K] extends object ? SelectedFields<Args[K], { [F in keyof Args[K]]: (F extends ScalarKeys$1<T$1> ? InferScalarBase<T$1[F]> : number) | null }> : never : K extends "_avg" ? Args[K] extends object ? SelectedFields<Args[K], { [F in keyof Args[K]]: (F extends ScalarKeys$1<T$1> ? IsDecimalScalar<T$1[F]> extends true ? Decimal : number : number) | null }> : never : K extends "_min" | "_max" ? Args[K] extends object ? SelectedFields<Args[K], { [F in keyof Args[K]]: F extends ScalarKeys$1<T$1> ? InferScalarBase<T$1[F]> | null : never }> : never : never }>>;
5651
5336
  /**
5652
- * Exported so the client layer can keep this query-local value distinct from
5653
- * its configured default: selected worlds apply only this value, while
5654
- * unselected worlds merge both before reducing the result.
5337
+ * Result type for groupBy operations
5338
+ * Includes the grouped-by fields plus any requested aggregates
5655
5339
  */
5656
- type NodeOmit<Node> = NodeKey<Node, "omit">;
5340
+ type GroupByResultType<T$1 extends ModelShape, Args> = Args extends {
5341
+ by: infer B;
5342
+ } ? Prettify<(B extends readonly (infer K)[] ? { [F in Extract<K, ScalarKeys$1<T$1> & keyof T$1>]: InferScalarBase<T$1[F]> } : B extends ScalarKeys$1<T$1> & keyof T$1 ? { [F in B]: InferScalarBase<T$1[F]> } : never) & AggregateResultType<T$1, Args>> : never;
5343
+ //#endregion
5344
+ //#region src/extensions/result-types.d.ts
5345
+ type AllModels = "$allModels";
5346
+ /** `Base` with `Over`'s members replacing its own. */
5347
+ type Override<Base$1, Over> = [keyof Over] extends [never] ? Base$1 : [keyof Base$1] extends [never] ? Over : Omit<Base$1, keyof Over> & Over;
5348
+ type FieldsAt<Result$1, Key$1> = Key$1 extends keyof Result$1 ? Result$1[Key$1] : unknown;
5349
+ /**
5350
+ * The fields one model gains, with their types: `$allModels` first, the
5351
+ * model's own after it, as the runtime orders them.
5352
+ */
5353
+ type ModelResultFields<Result$1, ModelName$1> = Override<FieldsAt<Result$1, AllModels> & {}, FieldsAt<Result$1, ModelName$1> & {}>;
5354
+ /**
5355
+ * Each declared field's type: what its `compute` returns. A definition
5356
+ * without `result` contributes `Record<never, never>`, spelled out rather
5357
+ * than through a local alias: a consumer's declaration emit prints this type
5358
+ * inside every extended client's state, and a name no public entry exports
5359
+ * would make that client unnameable there (TS2742).
5360
+ */
5361
+ type DefinitionResultFields<Definition$1> = Definition$1 extends {
5362
+ readonly result: infer Declared;
5363
+ } ? Declared extends object ? { readonly [ModelName in keyof Declared]: { -readonly [Field in keyof Declared[ModelName]]: Declared[ModelName][Field] extends {
5364
+ compute(...args: never[]): infer Value;
5365
+ } ? Value : never } } : Record<never, never> : Record<never, never>;
5366
+ /** The chain's fields with a later extension's: it wins a name. */
5367
+ type MergeResultFields<Previous extends object, Next$1 extends object> = [keyof Next$1] extends [never] ? Previous : [keyof Previous] extends [never] ? Next$1 : { readonly [ModelName in keyof Previous | keyof Next$1]: Override<FieldsAt<Previous, ModelName> & {}, FieldsAt<Next$1, ModelName> & {}> };
5368
+ /** The row a model's `compute` reads from: its scalars and earlier fields. */
5369
+ type ComputeRow<M$1, Earlier> = M$1 extends Model$1<infer State> ? Override<InferModelOutput<State>, Earlier> : never;
5370
+ /** The keys a `needs` map asks for. */
5371
+ type NeededKeys<Needs> = Needs extends object ? { [Key in keyof Needs]: Needs[Key] extends false ? never : Key }[keyof Needs] : never;
5372
+ /** The row one model's `compute` reads, before `needs` narrows it. */
5373
+ type ComputeRowOf<C$1 extends VibORMConfig, Earlier extends object, ModelName$1> = ModelName$1 extends keyof ClientSchema<C$1> ? ComputeRow<ClientSchema<C$1>[ModelName$1], ModelResultFields<Earlier, ModelName$1>> : never;
5374
+ /**
5375
+ * The `result` member as `$extends` and `defineExtension` type it. `Fields`
5376
+ * is its own type parameter, inferred from each field's `needs`, so that
5377
+ * each `compute` is given exactly the fields its `needs` names, typed from
5378
+ * the model: reading one it does not name is a compile error, as it would be
5379
+ * `undefined` at runtime, and a need the model lacks is refused. The
5380
+ * definition's own type parameter cannot carry this: a definition holding a
5381
+ * `compute` not yet typed is not inferred from at all. The shapes are
5382
+ * written inline, not through an interface, which TypeScript does not infer
5383
+ * through.
5384
+ */
5385
+ type ResultInference<C$1 extends VibORMConfig, Earlier extends object, Fields$1> = {
5386
+ readonly result?: { readonly [ModelName in keyof Fields$1]: ModelName extends "$allModels" ? { readonly [Field in keyof Fields$1[ModelName]]: {
5387
+ readonly needs?: Fields$1[ModelName][Field] & Readonly<Record<string, boolean>>;
5388
+ compute(row: { readonly [Key in NeededKeys<Fields$1[ModelName][Field]>]: unknown }): unknown;
5389
+ } } : { readonly [Field in keyof Fields$1[ModelName]]: {
5390
+ readonly needs?: Fields$1[ModelName][Field] & Readonly<Record<Exclude<keyof Fields$1[ModelName][Field], keyof ComputeRowOf<C$1, Earlier, ModelName>>, never>> & { readonly [Key in keyof ComputeRowOf<C$1, Earlier, ModelName>]?: boolean };
5391
+ compute(row: Pick<ComputeRowOf<C$1, Earlier, ModelName>, Extract<NeededKeys<Fields$1[ModelName][Field]>, keyof ComputeRowOf<C$1, Earlier, ModelName>>>): unknown;
5392
+ } } } & Readonly<Record<Exclude<keyof Fields$1, keyof ClientSchema<C$1> | "$allModels">, never>>;
5393
+ };
5657
5394
  /**
5658
- * The parse boundary treats an explicitly-`undefined` key as an ABSENT key
5659
- * (`src/validation/primitives/object.ts`), which is what makes the
5660
- * spread-an-optional idiom work; so `{ select: undefined }` and `{}` are the
5661
- * same payload, and this helper reports them the same way.
5395
+ * The `result` member of the definition envelope: which keys it holds. The
5396
+ * types of `needs` and `compute` are {@link ResultInference}'s.
5662
5397
  */
5663
- type NodeSelect<Node> = NodeKey<Node, "select">;
5664
- type NodeInclude<Node> = NodeKey<Node, "include">;
5665
- /** The public recurrence request stated by one admitted relation node. */
5666
- type NodeRecurse<Node> = NodeKey<Node, "recurse">;
5667
- /** The two keys of a polymorphic COLLECTION projection envelope. */
5668
- type NodeOnly<Projection> = NodeKey<Projection, "only">;
5669
- type NodeVariants<Projection> = NodeKey<Projection, "variants">;
5398
+ type ResultDefinition<C$1 extends VibORMConfig> = { readonly [ModelName in keyof ClientSchema<C$1> | "$allModels"]?: {
5399
+ readonly [field: string]: {
5400
+ readonly needs?: object;
5401
+ readonly compute: unknown;
5402
+ };
5403
+ } };
5404
+ //#endregion
5405
+ //#region src/extensions/methods.d.ts
5406
+ type NoMethods = Record<never, never>;
5407
+ type ExtensionMethod = (this: void, ...args: never[]) => unknown;
5408
+ type ExtensionMethodRecord = Readonly<Record<string, ExtensionMethod>>;
5409
+ declare const extensionCacheState: unique symbol;
5410
+ interface ExtensionCacheState {
5411
+ readonly [extensionCacheState]: true;
5412
+ }
5413
+ declare const extensionResultConsumerState: unique symbol;
5414
+ interface ExtensionResultConsumerState {
5415
+ readonly [extensionResultConsumerState]: true;
5416
+ }
5417
+ /** The only static facts accumulated while extensions are chained. */
5418
+ interface ClientExtensionState<ClientMethods extends object = NoMethods, ModelMethods extends object = NoMethods, CacheState extends ExtensionCacheState | undefined = undefined, ResultConsumerState extends ExtensionResultConsumerState | undefined = undefined, Controls$1 extends object = NoControls, RowModels extends string = never, Data$1 = never, Result$1 extends object = Record<never, never>> {
5419
+ readonly client: ClientMethods;
5420
+ readonly models: ModelMethods;
5421
+ readonly cache: CacheState;
5422
+ readonly resultConsumer: ResultConsumerState;
5423
+ /** The controls the chain declares: each one's values and placement. */
5424
+ readonly controls: Controls$1;
5425
+ /** The models the chain's `rows` can hide from a relation read. */
5426
+ readonly rows: RowModels;
5427
+ /** The fields the chain's `data` writes, which a caller no longer writes. */
5428
+ readonly data: Data$1;
5429
+ /** The fields the chain's `result` computes, per model key, and their types. */
5430
+ readonly result: Result$1;
5431
+ }
5432
+ type EmptyClientExtensionState = ClientExtensionState;
5433
+ /** Internal constraint for either the absent or enabled nominal cache bit. */
5434
+ type ExtensionStateConstraint = ClientExtensionState<object, object, ExtensionCacheState | undefined, ExtensionResultConsumerState | undefined, object, string, unknown, object>;
5435
+ /** Whether the current type-state includes the official cache capability. */
5436
+ type HasExtensionCache<X$1 extends ExtensionStateConstraint> = [X$1["cache"]] extends [ExtensionCacheState] ? true : false;
5670
5437
  /**
5671
- * The model that OWNS one asking slot, reconstructed from the state result
5672
- * inference already carries.
5673
- *
5674
- * `Model<State>` is the identity `s.model(...)` returns for that exact state,
5675
- * which is what the static membership projection compares getters against. It
5676
- * is not a second model concept: it is the same type, spelled from the half of
5677
- * it these mapped types thread.
5438
+ * Add the official cache capability without carrying its runtime config. Its
5439
+ * one control, `cache` on every write, joins the chain's controls as its
5440
+ * definition declares it.
5678
5441
  */
5679
- type SourceModelOf<S$1 extends ModelState> = Model$1<S$1>;
5680
- /** Does this relation name variants rather than one model? */
5681
- type IsVariantTarget<R$1 extends AnyRelation> = TargetKind<R$1> extends "variants" ? true : false;
5682
- /** The configured target model at one public discriminator. */
5683
- type GetPolymorphicTarget<R$1 extends AnyRelation, PublicType$1 extends PropertyKey> = PublicType$1 extends keyof VariantEntries<R$1> ? VariantEntries<R$1>[PublicType$1] extends {
5684
- readonly getter: infer Getter;
5685
- } ? Getter extends (() => infer Target) ? Target extends Model$1<any> ? Target : never : never : never : never;
5686
- type PolymorphicPublicTypes<R$1 extends AnyRelation> = Extract<keyof VariantEntries<R$1>, string>;
5442
+ type EnableExtensionCache<X$1 extends ExtensionStateConstraint> = ClientExtensionState<X$1["client"], X$1["models"], ExtensionCacheState, X$1["resultConsumer"], X$1["controls"] & DefinitionControls<{
5443
+ readonly controls: OfficialCacheControls;
5444
+ }>, X$1["rows"], X$1["data"], X$1["result"]>;
5445
+ /** Whether an earlier extension was typed against result-bearing delegates. */
5446
+ type HasResultConsumingExtension<X$1 extends ExtensionStateConstraint> = [X$1["resultConsumer"]] extends [undefined] ? false : [X$1["resultConsumer"]] extends [ExtensionResultConsumerState] ? true : false;
5447
+ type MethodsForModel<X$1 extends ExtensionStateConstraint, ModelName$1 extends PropertyKey> = ModelName$1 extends keyof X$1["models"] ? X$1["models"][ModelName$1] : NoMethods;
5687
5448
  /**
5688
- * Result for a relation when included
5689
- * - To-many relations return arrays
5690
- * - To-one relations return single objects (nullable if optional)
5449
+ * One model's delegate after the chain's methods and controls. On a chain
5450
+ * that declares create `data`, its writes may leave out the fields the chain
5451
+ * writes on a create.
5691
5452
  */
5453
+ type ExtensionModelDelegate<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, ModelName$1 extends keyof ClientSchema<C$1>> = ([X$1["data"]] extends [never] ? Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1] : Omit<Client<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"]>[ModelName$1], StampedOperation> & StampedOperations<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"], X$1["data"], ModelName$1>) & MethodsForModel<X$1, ModelName$1>;
5692
5454
  /**
5693
- * The relation's cardinality wrapper, applied to an already-built element type
5694
- * (plan §8.1's `RelationResult`): a to-many slot is an array, and a singular
5695
- * slot is nullable unless the static membership projection PROVES it cannot be
5696
- * empty. `SlotMayBeEmpty` answering a widened `boolean` therefore reads as
5697
- * nullable, which is the safe direction — the promise "this is always present"
5698
- * is the one that breaks callers.
5699
- *
5700
- * The asking key travels with the relation. Dropping it would let a self
5701
- * relation select its own declaration as its inverse (§8.1 step 2).
5455
+ * One model's delegate on a chain that declares `result`: its projecting
5456
+ * operations rebuilt so `select` and `omit` name the computed fields and the
5457
+ * rows carry them. A chain without `result` never reaches this type.
5702
5458
  */
5703
- type WrapRelation<S$1 extends ModelState, K$1, R$1 extends AnyRelation, T$1> = Cardinality<R$1> extends "many" ? T$1[] : SlotMayBeEmpty<SourceModelOf<S$1>, K$1, R$1> extends false ? T$1 : T$1 | null;
5704
- type WrapRelationNode<S$1 extends ModelState, K$1, R$1 extends AnyRelation, T$1> = [T$1] extends [never] ? never : WrapRelation<S$1, K$1, R$1, T$1>;
5459
+ type ComputedModelDelegate<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, ModelName$1 extends keyof ClientSchema<C$1>> = Omit<ExtensionModelDelegate<C$1, X$1, ModelName$1>, ComputedOperation> & ComputedOperations<C$1, ClientRowsContext<C$1, X$1["rows"]>, X$1["controls"], X$1["data"], ModelName$1, X$1["result"]>;
5705
5460
  /**
5706
- * A singular slot whose target the client's `rows` can hide reads `null` when
5707
- * it is hidden, whatever the membership proves about the stored reference.
5708
- * Applied beside {@link WrapRelation}, never inside it: a recursive slot is
5709
- * always a self relation, which may be empty already (CM002), so only the
5710
- * outer slot of a node ever needs it.
5461
+ * Model delegates after the methods contributed by the current chain. The
5462
+ * always-true test is deliberate: for a client generic over its config it
5463
+ * stays deferred, so the model map adds no index signature to that client and
5464
+ * its `$` members stay reachable inside a body generic over `C`. A chain
5465
+ * that declares `result` is told apart here, once per client.
5711
5466
  */
5712
- type OrHidden<T$1, R$1 extends AnyRelation, ClientDefaults> = [T$1] extends [never] ? never : Cardinality<R$1> extends "many" ? T$1 : T$1 | HiddenTargetNull<R$1, ClientDefaults>;
5467
+ type ExtensionModelClient<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = [keyof C$1["schema"]] extends [PropertyKey] ? [keyof X$1["result"]] extends [never] ? { [ModelName in keyof ClientSchema<C$1>]: ExtensionModelDelegate<C$1, X$1, ModelName> } : { [ModelName in keyof ClientSchema<C$1>]: ComputedModelDelegate<C$1, X$1, ModelName> } : unknown;
5468
+ /** The surface given to one client-method factory. */
5469
+ type ExtensionClientScope<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = ExtensionModelClient<C$1, X$1> & RawSurface & X$1["client"] & {
5470
+ readonly $schema: ClientSchema<C$1>;
5471
+ readonly $transaction: TransactionClient<C$1, X$1>["$transaction"];
5472
+ /**
5473
+ * The client this scope's methods are called on, its calls admitting
5474
+ * these values of this extension's own controls as if passed (a
5475
+ * `bound: true` control only from here). Its type is that client's,
5476
+ * which only the method knows: declare it with a `this` parameter,
5477
+ * `$with<Self>(this: Self, value: Value): Self`, outside the returned
5478
+ * literal (inside it, the factory's contextual type makes `Self` void).
5479
+ */
5480
+ readonly $bind: (values: Readonly<Record<string, unknown>>) => unknown;
5481
+ };
5482
+ type NonFunctionKeys<Methods$1 extends object> = { [Key in keyof Methods$1]: Methods$1[Key] extends CallableFunction ? never : Key }[keyof Methods$1];
5483
+ type InvalidClientMethodKeys<Methods$1 extends object, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = Exclude<keyof Methods$1, `$${string}`> | Extract<keyof Methods$1, keyof RawSurface | "$driver" | "$schema" | "$transaction" | "$connect" | "$disconnect" | "$withCache" | "$invalidate" | "$extends" | keyof X$1["client"]> | (string extends keyof C$1["schema"] ? never : Extract<keyof Methods$1, keyof C$1["schema"]>) | NonFunctionKeys<Methods$1>;
5484
+ type GuardMethodFactory<Factory$1, Forbidden extends PropertyKey> = Factory$1 extends ((...args: infer Params) => infer Methods) ? Methods extends object ? (...args: Params) => Methods & Record<Forbidden, never> : (...args: Params) => never : never;
5485
+ type ClientFactoryGuard<Definition$1, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = Definition$1 extends {
5486
+ readonly client: infer Factory;
5487
+ } ? Factory extends ((...args: never[]) => infer Methods) ? Methods extends object ? {
5488
+ readonly client: GuardMethodFactory<Factory, InvalidClientMethodKeys<Methods, C$1, X$1>>;
5489
+ } : {
5490
+ readonly client: never;
5491
+ } : {
5492
+ readonly client: never;
5493
+ } : unknown;
5713
5494
  /**
5714
- * One finite named wrapper for an ordinary inferred node. The wrapper recurs
5715
- * only through its relation property, so the ordinary projection is inferred
5716
- * once rather than expanded once per requested depth. The repeated key is
5717
- * wrapped by {@link WrapRelation}, the same cardinality and emptiness rule as
5718
- * the outer slot, and its arguments are the same at every level.
5495
+ * What every model factory may not return: a core operation or `then`. That
5496
+ * each returned member is a function is the definition's own factory type
5497
+ * (`ModelMethodFactory` returns an `ExtensionMethodRecord`), not this guard;
5498
+ * `object` only keeps the all-optional key list from being a weak type, which
5499
+ * would refuse every return that names none of those keys. Stated as a target
5500
+ * shape, not a conditional over the factory, so a factory map generic over the
5501
+ * client is checked rather than deferred. A method a prior extension put on
5502
+ * the model cannot be named here for a client generic over its extension
5503
+ * state: the runtime refuses that replacement when the extension is applied.
5719
5504
  */
5720
- type RecursiveRelationNode<Node, S$1 extends ModelState, K$1, R$1 extends AnyRelation, Exhaustive extends boolean> = Node & (Exhaustive extends true ? { [Field in Extract<K$1, PropertyKey>]: WrapRelation<S$1, K$1, R$1, RecursiveRelationNode<Node, S$1, K$1, R$1, Exhaustive>> } : { [Field in Extract<K$1, PropertyKey>]?: WrapRelation<S$1, K$1, R$1, RecursiveRelationNode<Node, S$1, K$1, R$1, Exhaustive>> });
5721
- type IsExhaustiveRecurrence<Node> = [NodeRecurse<Node>] extends [{
5722
- readonly depth: false;
5723
- }] ? true : false;
5724
- type ApplyRecurrence<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Node, Inferred> = [NodeRecurse<Node>] extends [undefined] ? Inferred : RecursiveRelationNode<Inferred, S$1, K$1, R$1, IsExhaustiveRecurrence<Node>>;
5725
- type InferRelationResult<S$1 extends ModelState, K$1, R$1 extends AnyRelation, ClientDefaults = never> = OrHidden<WrapRelation<S$1, K$1, R$1, ApplyOmit<InferModelOutput<GetTargetModelState<R$1>>, ResolveClientOmit<GetTargetModel<R$1>, ClientDefaults>>>, R$1, ClientDefaults>;
5726
- type InferPolymorphicTargetVariant<Target$1 extends Model$1<any>, Override, ClientDefaults> = Target$1 extends Model$1<infer TargetState> ? TargetState extends ModelState ? Override extends true ? ApplyOmit<InferModelOutput<TargetState>, ResolveClientOmit<Target$1, ClientDefaults>> : Override extends object ? InferSelectInclude<TargetState, Override, NodeSelect<Override>, MergeClientOmit<ResolveClientOmit<Target$1, ClientDefaults>, NodeOmit<Override>>, ClientDefaults> : ApplyOmit<InferModelOutput<TargetState>, ResolveClientOmit<Target$1, ClientDefaults>> : never : never;
5505
+ type ModelFactoryGuard = (...args: never[]) => object & { readonly [Name in Operations | "then"]?: never };
5727
5506
  /**
5728
- * One configured polymorphic target. A missing projection key does not filter
5729
- * that discriminator; it keeps the target model's default scalar output.
5507
+ * Model keys outside the schema are refused by the definition's own `model`
5508
+ * type (its per-schema factory table); this guard checks each factory's
5509
+ * methods.
5730
5510
  */
5731
- type InferPolymorphicVariant<R$1 extends AnyRelation, PublicType$1 extends PolymorphicPublicTypes<R$1>, Override, ClientDefaults> = GetPolymorphicTarget<R$1, PublicType$1> extends infer Target ? Target extends Model$1<any> ? InferPolymorphicTargetVariant<Target, Override, ClientDefaults> : never : never;
5732
- type PolymorphicProjectionAt<Projection, PublicType$1 extends PropertyKey> = PublicType$1 extends keyof Projection ? Projection[PublicType$1] : undefined;
5511
+ type ModelFactoriesGuard<Definition$1> = Definition$1 extends {
5512
+ readonly model: infer Factories;
5513
+ } ? {
5514
+ readonly model: { readonly [ModelName in keyof Factories]: ModelFactoryGuard };
5515
+ } : unknown;
5516
+ type ExtensionMethodDefinitionGuard<Definition$1, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = ClientFactoryGuard<Definition$1, C$1, X$1> & ModelFactoriesGuard<Definition$1>;
5517
+ type ClientMethodsOf<Definition$1> = Definition$1 extends {
5518
+ readonly client: (...args: never[]) => infer Methods;
5519
+ } ? Methods extends object ? Methods : NoMethods : NoMethods;
5520
+ type ModelMethodsOf<Definition$1> = Definition$1 extends {
5521
+ readonly model: infer Factories;
5522
+ } ? Factories extends object ? { readonly [ModelName in keyof Factories]: Factories[ModelName] extends ((...args: never[]) => infer Methods) ? Methods extends object ? Methods : NoMethods : NoMethods } : NoMethods : NoMethods;
5523
+ type MergeModelMethods<Left extends object, Right extends object> = { readonly [ModelName in keyof Left | keyof Right]: (ModelName extends keyof Left ? Left[ModelName] : NoMethods) & (ModelName extends keyof Right ? Right[ModelName] : NoMethods) };
5524
+ type ResultConsumerContextOf<Definition$1> = Definition$1 extends {
5525
+ readonly client: unknown;
5526
+ } | {
5527
+ readonly model: unknown;
5528
+ } ? "result-consuming" : Definition$1 extends {
5529
+ readonly query: infer Query;
5530
+ } ? Query extends CallableFunction ? "result-independent" : "result-consuming" : "result-independent";
5531
+ /** Incoming facts keep their nominal bit derivation inside this named state. */
5532
+ interface ExtensionContributionState<ClientMethods extends object, ModelMethods extends object, Controls$1 extends object, RowModels extends string, Data$1, ConsumerContext extends string, Result$1 extends object = Record<never, never>> extends ExtensionStateConstraint {
5533
+ readonly client: ClientMethods;
5534
+ readonly models: ModelMethods;
5535
+ readonly cache: undefined;
5536
+ readonly resultConsumer: ConsumerContext extends "result-consuming" ? ExtensionResultConsumerState : undefined;
5537
+ readonly controls: Controls$1;
5538
+ readonly rows: RowModels;
5539
+ readonly data: Data$1;
5540
+ readonly result: Result$1;
5541
+ }
5542
+ /** Retain contribution facts, never the factory's contextual argument surface. */
5543
+ type ExtensionStateContributionOf<Definition$1> = [Definition$1] extends [unknown] ? ExtensionContributionState<ClientMethodsOf<Definition$1>, ModelMethodsOf<Definition$1>, DefinitionControls<Definition$1>, RowsModels<Definition$1>, DefinitionData<Definition$1>, ResultConsumerContextOf<Definition$1>, DefinitionResultFields<Definition$1>> : never;
5544
+ /** Accumulate the same seven facts lazily, without retaining callback definitions. */
5545
+ interface AccumulatedExtensionState<X$1 extends ExtensionStateConstraint, Contribution extends ExtensionStateConstraint> extends ExtensionStateConstraint {
5546
+ readonly client: X$1["client"] & Contribution["client"];
5547
+ readonly models: MergeModelMethods<X$1["models"], Contribution["models"]>;
5548
+ readonly cache: X$1["cache"];
5549
+ readonly resultConsumer: HasResultConsumingExtension<Contribution> extends true ? ExtensionResultConsumerState : X$1["resultConsumer"];
5550
+ readonly controls: X$1["controls"] & Contribution["controls"];
5551
+ readonly rows: X$1["rows"] | Contribution["rows"];
5552
+ readonly data: X$1["data"] | Contribution["data"];
5553
+ readonly result: MergeResultFields<X$1["result"], Contribution["result"]>;
5554
+ }
5555
+ /** Public compatibility surface: the incoming argument remains a definition. */
5556
+ type MergeExtensionState<X$1 extends ExtensionStateConstraint, Definition$1> = AccumulatedExtensionState<X$1, ExtensionStateContributionOf<Definition$1>>;
5557
+ //#endregion
5558
+ //#region src/extensions/request.d.ts
5733
5559
  /**
5734
- * One arm out of a collection's `variants` container.
5735
- *
5736
- * The `Exclude` + re-added `undefined` is not decoration: `PolymorphicProjectionAt`
5737
- * distributes over the KEY, not over the container, and `keyof (X | undefined)`
5738
- * is `never` — so a container that MAY be undefined would answer `undefined`
5739
- * for every arm, i.e. "no projection stated", i.e. the full default row. That
5740
- * is the unsafe direction: the runtime may well apply the projection and return
5741
- * fewer columns than the type promised.
5742
- *
5743
- * Splitting the container instead hands `InferPolymorphicTargetVariant` a
5744
- * `Configured | undefined` override, which it already distributes into
5745
- * `Selected | Default` — the honest union a caller in this position narrows.
5560
+ * The single operation-specific owner of request properties that determine the
5561
+ * public result type. A future projection spelling extends this table; runtime
5562
+ * detachment and the handler input/patch types then change together.
5746
5563
  */
5747
- type PolymorphicArmAt<Variants$1, PublicType$1 extends PropertyKey> = PolymorphicProjectionAt<Exclude<Variants$1, undefined>, PublicType$1> | (undefined extends Variants$1 ? undefined : never);
5564
+ declare const RESULT_SHAPE_KEYS_BY_OPERATION: Readonly<{
5565
+ findFirst: readonly ["select", "include", "omit"];
5566
+ findMany: readonly ["select", "include", "omit"];
5567
+ findUnique: readonly ["select", "include", "omit"];
5568
+ findUniqueOrThrow: readonly ["select", "include", "omit"];
5569
+ findFirstOrThrow: readonly ["select", "include", "omit"];
5570
+ create: readonly ["select", "include", "omit"];
5571
+ update: readonly ["select", "include", "omit"];
5572
+ delete: readonly ["select", "include", "omit"];
5573
+ upsert: readonly ["select", "include", "omit"];
5574
+ createMany: readonly ["select", "omit"];
5575
+ updateMany: readonly ["select", "omit"];
5576
+ deleteMany: readonly ["select", "omit"];
5577
+ count: readonly ["select"];
5578
+ aggregate: readonly ["_count", "_avg", "_sum", "_min", "_max"];
5579
+ groupBy: readonly ["by", "_count", "_avg", "_sum", "_min", "_max"];
5580
+ exist: readonly [];
5581
+ }>;
5582
+ type ResultShapeKeyFor<Operation$2 extends Operations> = (typeof RESULT_SHAPE_KEYS_BY_OPERATION)[Operation$2][number];
5583
+ /** The operation input visible to an ordinary request transform. */
5584
+ type RequestTransformInput<Operation$2 extends Operations, Input$1 extends object> = Omit<Input$1, ResultShapeKeyFor<Operation$2>>;
5748
5585
  /**
5749
- * Exhaustive direct polymorphic result. Projection objects override individual
5750
- * targets; omitted targets remain in the union with their default projection.
5586
+ * A shallow patch over the non-projection input. The optional `never`
5587
+ * properties make protected keys fail structurally, including held values.
5751
5588
  */
5752
- type PolymorphicVariants<R$1 extends AnyRelation, Projection = undefined, ClientDefaults = never> = { [PublicType in PolymorphicPublicTypes<R$1>]: {
5753
- readonly type: PublicType;
5754
- readonly data: InferPolymorphicVariant<R$1, PublicType, PolymorphicProjectionAt<Projection, PublicType>, ClientDefaults>;
5755
- } }[PolymorphicPublicTypes<R$1>];
5589
+ type RequestTransformPatch<Operation$2 extends Operations, Input$1 extends object> = Partial<RequestTransformInput<Operation$2, Input$1>> & { readonly [Key in ResultShapeKeyFor<Operation$2>]?: never };
5590
+ interface GenericRequestContext {
5591
+ readonly model: string;
5592
+ readonly operation: Operations;
5593
+ readonly input: Readonly<RequestTransformPatch<Operations, Record<string, unknown>>>;
5594
+ /** The call's controls this handler's extension declares, and only those. */
5595
+ readonly controls?: AdmittedControls;
5596
+ }
5597
+ type GenericRequestHandlerCall = (context: GenericRequestContext) => Readonly<RequestTransformPatch<Operations, Record<string, unknown>>>;
5598
+ declare const officialRequestHandlerIdentity: unique symbol;
5599
+ /** Public ordinary request handler; official identities cannot be erased into it. */
5600
+ type GenericRequestHandler = GenericRequestHandlerCall & {
5601
+ readonly [officialRequestHandlerIdentity]?: never;
5602
+ };
5603
+ /** Internal nominal call shape used by official request-based capabilities. */
5604
+ type OfficialGenericRequestHandler = GenericRequestHandlerCall & {
5605
+ readonly [officialRequestHandlerIdentity]: true;
5606
+ };
5607
+ type RequestOperationInput<S$1 extends Schema$1, ModelName$1 extends keyof S$1, OperationName$1 extends Operations> = Extract<Exclude<OperationPayload<OperationName$1, S$1[ModelName$1]>, undefined>, object>;
5608
+ type RequestHandlerMap<S$1 extends Schema$1> = { readonly [ModelName in keyof S$1]?: { readonly [OperationName in Operations]?: (context: {
5609
+ readonly model: ModelName;
5610
+ readonly operation: OperationName;
5611
+ readonly input: Readonly<RequestTransformInput<OperationName, RequestOperationInput<S$1, ModelName, OperationName>>>;
5612
+ /** The call's controls this handler's extension declares, and only those. */
5613
+ readonly controls?: AdmittedControls;
5614
+ }) => RequestTransformPatch<OperationName, RequestOperationInput<S$1, ModelName, OperationName>> } };
5615
+ //#endregion
5616
+ //#region src/extensions/statement.d.ts
5617
+ /** The trusted identity exposed to one low-level statement transform. */
5618
+ interface StatementContext {
5619
+ readonly statement: Sql;
5620
+ readonly model: string | undefined;
5621
+ readonly operation: Operations | keyof RawSurface;
5622
+ }
5623
+ type StatementHandler = (context: StatementContext) => Sql;
5624
+ //#endregion
5625
+ //#region src/extensions/definition.d.ts
5626
+ type ExtensionConfig<S$1 extends Schema$1> = {
5627
+ readonly schema: S$1;
5628
+ readonly driver: AnyDriver;
5629
+ };
5756
5630
  /**
5757
- * The variants a COLLECTION projection can still produce, after `only`.
5758
- *
5759
- * The two `undefined` tests are ordered, and the order is the whole point:
5760
- *
5761
- * - `[Only] extends [undefined]` — the key is ABSENT (or the payload has an
5762
- * index signature, which states nothing). Every variant survives.
5763
- * - `undefined extends Only` — the key MAY be undefined, the shape real code
5764
- * produces (`only: cond ? ["post"] : undefined`, or a forwarded optional
5765
- * property). Only the runtime knows, so nothing is narrowed. This MUST be
5766
- * tested BEFORE the element extraction: `readonly ["post"] | undefined`
5767
- * matches `readonly (infer T)[]` on its defined member and would otherwise
5768
- * narrow to `"post"` on a call that may not narrow at all.
5769
- * - the tuple/array case narrows to the named members.
5770
- * - anything else (a `string[]` built at runtime, an unresolvable generic)
5771
- * narrows nothing, which is the honest answer.
5631
+ * A model factory, declared as a method so a factory typed against the client
5632
+ * it extends (`(delegate: M[K & keyof M]) => …`, generic over that client) is
5633
+ * compared in either direction rather than only contravariantly.
5772
5634
  */
5773
- type AllowedPublicTypes<R$1 extends AnyRelation, Only> = [Only] extends [undefined] ? PolymorphicPublicTypes<R$1> : undefined extends Only ? PolymorphicPublicTypes<R$1> : Only extends readonly (infer T)[] ? Extract<T, PolymorphicPublicTypes<R$1>> : PolymorphicPublicTypes<R$1>;
5635
+ type ModelMethodFactory<Delegate> = {
5636
+ factory(delegate: Delegate): ExtensionMethodRecord;
5637
+ }["factory"];
5774
5638
  /**
5775
- * One element of a collection result: the same `{ type, data }` envelope the
5776
- * to-one slot produces, but reached through `variants` rather than through the
5777
- * projection's top level — which is what lets a public variant literally named
5778
- * `only` or `variants` keep working.
5639
+ * One factory per schema model. A definition's model key is looked up here by
5640
+ * index, never by a conditional: a key outside the schema reads `never` (the
5641
+ * factory is refused where it is written), and a key set generic over the
5642
+ * client is substituted rather than deferred, so a plugin generic over `C`
5643
+ * type-checks and meets the schema check when it is applied.
5779
5644
  */
5780
- type PolymorphicCollectionVariants<R$1 extends AnyRelation, Projection, ClientDefaults> = { [PublicType in AllowedPublicTypes<R$1, NodeOnly<Projection>>]: {
5781
- readonly type: PublicType;
5782
- readonly data: InferPolymorphicVariant<R$1, PublicType, PolymorphicArmAt<NodeVariants<Projection>, PublicType>, ClientDefaults>;
5783
- } }[AllowedPublicTypes<R$1, NodeOnly<Projection>>];
5645
+ type ModelFactoryTable<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = { readonly [ModelName in keyof ClientSchema<C$1>]: ModelMethodFactory<ExtensionModelDelegate<C$1, X$1, ModelName>> };
5646
+ /** The model keys a definition's own `model` map names. */
5647
+ type DefinitionModelKeys<Self> = Self extends {
5648
+ readonly model?: infer Factories;
5649
+ } ? keyof Factories : never;
5784
5650
  /**
5785
- * CARDINALITY FIRST, through the same reader both target domains use — never by
5786
- * testing `state.cardinality` inline, so one rule governs both levels.
5787
- *
5788
- * A collection is NEVER `| null`: an empty collection is `[]`, and `.optional()`
5789
- * is unspellable on a collection state precisely so emptiness has one reading.
5790
- * The singular arm asks the SAME `SlotMayBeEmpty` an ordinary slot asks; for a
5791
- * variant target that projection is exactly the declared `.optional()` (§8.1).
5792
- *
5793
- * The array wrapper is applied UNCONDITIONALLY, outside `WrapRelationNode`'s
5794
- * never-collapse. `only: []` legitimately produces a `never` element union, and
5795
- * collapsing that to `never` would type a call that returns a fresh empty array
5796
- * as returning nothing at all; `readonly never[]` is the shape that matches.
5797
- */
5798
- type InferPolymorphicResult<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Projection = undefined, ClientDefaults = never> = Cardinality<R$1> extends "many" ? readonly PolymorphicCollectionVariants<R$1, Projection, ClientDefaults>[] : SlotMayBeEmpty<SourceModelOf<S$1>, K$1, R$1> extends false ? PolymorphicVariants<R$1, Projection, ClientDefaults> | HiddenTargetNull<R$1, ClientDefaults> : PolymorphicVariants<R$1, Projection, ClientDefaults> | null;
5651
+ * `Self` is the definition itself when `$extends` checks it (F-bounded), so
5652
+ * its model keys come from the definition; otherwise every schema model.
5653
+ */
5654
+ type ContextualExtensionDefinition<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, Self = unknown> = ExtensionMembers<C$1, X$1> & {
5655
+ readonly result?: ResultDefinition<C$1>;
5656
+ readonly model?: unknown extends Self ? { readonly [ModelName in keyof ClientSchema<C$1>]?: ModelMethodFactory<ExtensionModelDelegate<C$1, X$1, ModelName>> } : { readonly [ModelName in DefinitionModelKeys<Self>]?: ModelFactoryTable<C$1, X$1>[ModelName & keyof ClientSchema<C$1>] };
5657
+ };
5658
+ type ExtensionMembers<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = {
5659
+ readonly name: string;
5660
+ readonly request?: GenericRequestHandler | RequestHandlerMap<ClientSchema<C$1>>;
5661
+ readonly query?: GenericQueryHandler | QueryHandlerMap<C$1, X$1["rows"]>;
5662
+ readonly statement?: StatementHandler;
5663
+ readonly observe?: ObserveHandler;
5664
+ readonly controls?: ControlsContribution;
5665
+ readonly rows?: RowsContribution;
5666
+ readonly deletion?: DeletionContribution;
5667
+ readonly data?: DataContribution;
5668
+ readonly client?: (scope: ExtensionClientScope<C$1, X$1>) => ExtensionMethodRecord;
5669
+ };
5670
+ type SchemaGenericExtensionDefinition = Omit<ContextualExtensionDefinition<ExtensionConfig<Schema$1>, EmptyClientExtensionState>, "request" | "query"> & {
5671
+ readonly request?: GenericRequestHandler;
5672
+ readonly query?: GenericQueryHandler;
5673
+ };
5799
5674
  /**
5800
- * Infer result from select/include args
5801
- * - select: ONLY returns selected fields
5802
- * - include: returns base model + included relations
5803
- * - neither: returns base model output
5804
- *
5805
- * The dispatch is on the select VALUE, not on key presence. `{ select: undefined }`
5806
- * is the spread-an-optional idiom collapsed to a literal `undefined`, and the
5807
- * parse boundary hands the engine a payload with no projection at all — so it
5808
- * returns the full default row, exactly like `{}`. Reading it as "a selection of
5809
- * nothing" typed that call `{}`, and `rows[0].id` stopped compiling on a call
5810
- * that returns `id` at runtime.
5675
+ * Public reusable extension definition.
5811
5676
  *
5812
- * `select` + `include` is refused only when both keys carry values. `omit`
5813
- * composes with either projection mode: in the selected world it subtracts
5814
- * from the selected shape; in the unselected world it subtracts from the
5815
- * default scalar shape.
5677
+ * A schema with a string index has no exact model vocabulary, so its reusable
5678
+ * request/query contributions must use the polymorphic all-operation form.
5679
+ * Supplying a concrete schema retains its exact model and operation maps.
5816
5680
  */
5817
- type InferSelectInclude<S$1 extends ModelState, Args, Selection$1 = NodeSelect<Args>, UnselectedOmit = NodeOmit<Args>, ClientDefaults = never> = [Selection$1] extends [undefined] ? InferUnselectedRow<S$1, Args, UnselectedOmit, ClientDefaults> : undefined extends Selection$1 ? InferUnselectedRow<S$1, Args, UnselectedOmit, ClientDefaults> | InferSelectedRow<S$1, Args, Exclude<Selection$1, undefined>, ClientDefaults> : InferSelectedRow<S$1, Args, Selection$1, ClientDefaults>;
5681
+ type ClientExtension<S$1 extends Schema$1 = Schema$1> = string extends keyof S$1 ? SchemaGenericExtensionDefinition : ContextualExtensionDefinition<ExtensionConfig<S$1>, EmptyClientExtensionState>;
5682
+ type DefinitionKeys = keyof ContextualExtensionDefinition<VibORMConfig, EmptyClientExtensionState>;
5683
+ declare const schemaBoundExtensionContext: unique symbol;
5684
+ type SchemaBoundExtension<Definition$1> = Definition$1 & {
5685
+ readonly [schemaBoundExtensionContext]: ResultConsumerContextOf<Definition$1>;
5686
+ };
5687
+ type UnknownDefinitionKeys<Definition$1> = Record<Exclude<keyof Definition$1, DefinitionKeys | typeof schemaBoundExtensionContext>, never>;
5688
+ type ConfigOmit$2<C$1 extends VibORMConfig> = "omit" extends keyof C$1 ? C$1[Extract<"omit", keyof C$1>] : undefined;
5689
+ type HasNamedClientOmit<C$1 extends VibORMConfig> = string extends keyof NonNullable<ConfigOmit$2<C$1>> ? false : [Exclude<ConfigOmit$2<C$1>, undefined>] extends [never] ? false : true;
5690
+ /** Refuse replaying a schema-bound result consumer into an omitted client. */
5691
+ type SchemaBoundExtensionAdmission<Definition$1, C$1 extends VibORMConfig> = Definition$1 extends {
5692
+ readonly [schemaBoundExtensionContext]: infer Context;
5693
+ } ? Context extends "result-consuming" ? HasNamedClientOmit<C$1> extends true ? {
5694
+ readonly [schemaBoundExtensionContext]: never;
5695
+ } : unknown : unknown : unknown;
5696
+ type OperationMapGuard<Map$1, S$1 extends Schema$1> = Map$1 extends CallableFunction ? unknown : Map$1 extends object ? Record<Exclude<keyof Map$1, keyof S$1>, never> & { readonly [ModelName in keyof Map$1]: ModelName extends keyof S$1 ? Map$1[ModelName] extends object ? Record<Exclude<keyof Map$1[ModelName], Operations>, never> : never : never } : never;
5697
+ type ComponentMapGuard<Definition$1, Key$1 extends "request" | "query", S$1 extends Schema$1> = Definition$1 extends { readonly [K in Key$1]: infer Component } ? { readonly [K in Key$1]: OperationMapGuard<Component, S$1> } : unknown;
5698
+ /** Policy model keys must be a subset of a concrete bound schema. */
5699
+ type PolicyModelsGuard<Definition$1, S$1 extends Schema$1, Key$1 extends "data" | "rows" | "deletion"> = Definition$1 extends { readonly [K in Key$1]: {
5700
+ readonly models: infer Models;
5701
+ } } ? string extends keyof S$1 ? unknown : [keyof Models] extends [keyof S$1] ? unknown : { readonly [K in Key$1]: {
5702
+ readonly models: Record<keyof Models, never>;
5703
+ } } : unknown;
5704
+ /** Structural refusal for non-fresh extension definitions and contributions. */
5705
+ type ExactExtensionDefinition<Definition$1, C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint> = UnknownDefinitionKeys<Definition$1> & ComponentMapGuard<Definition$1, "request", C$1["schema"]> & ComponentMapGuard<Definition$1, "query", C$1["schema"]> & PolicyModelsGuard<Definition$1, C$1["schema"], "data"> & PolicyModelsGuard<Definition$1, C$1["schema"], "rows"> & PolicyModelsGuard<Definition$1, C$1["schema"], "deletion"> & ExtensionMethodDefinitionGuard<Definition$1, C$1, X$1>;
5706
+ type DefineExtensionBinder<S$1 extends Schema$1> = <const Definition$1, Fields$1 = unknown>(definition: Definition$1 & ContextualExtensionDefinition<ExtensionConfig<S$1>, EmptyClientExtensionState> & ExactExtensionDefinition<Definition$1, ExtensionConfig<S$1>, EmptyClientExtensionState> & ResultInference<ExtensionConfig<S$1>, Record<never, never>, Fields$1>) => SchemaBoundExtension<NoInfer<Definition$1>>;
5707
+ declare function defineExtension<const Definition$1 extends SchemaGenericExtensionDefinition>(definition: Definition$1 & ExactExtensionDefinition<Definition$1, ExtensionConfig<Schema$1>, EmptyClientExtensionState>): NoInfer<Definition$1>;
5708
+ declare function defineExtension<S$1 extends Schema$1>(): DefineExtensionBinder<S$1>;
5709
+ //#endregion
5710
+ //#region src/extensions/controls.d.ts
5711
+ /** The operations a declared control is accepted on. */
5712
+ type ControlPlacement = "reads" | "writes" | "all" | readonly Operations[];
5818
5713
  /**
5819
- * The row a node returns in the world where its `select` carries a value.
5714
+ * One argument an extension declares. Its values are a closed list or a
5715
+ * Standard Schema; `on` names the operations that accept it (every operation
5716
+ * when absent). With `required`, a call on one of those operations that does
5717
+ * not pass it is refused, on the models the extension names in `rows`,
5718
+ * `data` or `deletion` only; an extension that names no model asks for it on
5719
+ * every model. With `bound`, it is accepted only from a binding (the client
5720
+ * scope's `$bind`), never from a call's arguments: its placement reads no
5721
+ * argument, so a call that passes it is refused as passing an unknown key.
5722
+ * With `uncacheable`, a read that holds a value of it is never served from
5723
+ * the cache: `$withCache` on that read is refused before any statement. A
5724
+ * value held in a variable keeps its literal type only with `as const`, as a
5725
+ * held enum clause does.
5726
+ */
5727
+ type ControlDeclaration = ({
5728
+ readonly oneOf: readonly (string | number | boolean)[];
5729
+ } | {
5730
+ readonly schema: StandardSchemaV1;
5731
+ }) & {
5732
+ readonly on?: ControlPlacement;
5733
+ readonly required?: boolean;
5734
+ readonly bound?: boolean;
5735
+ readonly uncacheable?: boolean;
5736
+ };
5737
+ type ControlsContribution = {
5738
+ readonly [name: string]: ControlDeclaration;
5739
+ };
5740
+ /** Constant scalar `where` or `data` fields of one model. */
5741
+ type ScalarFields = {
5742
+ readonly [field: string]: unknown;
5743
+ };
5744
+ /**
5745
+ * Which rows an operation sees. `control` names the call argument that picks
5746
+ * a mode; every model entry declares the same mode names, `default` among
5747
+ * them. `root` filters the call's own candidates, `related` rows reached
5748
+ * through a relation; each is a model's `where`, admitted once when the
5749
+ * extension is applied, or the name of one of its `verbs` predicates. Where a
5750
+ * filter takes a value, `{ control: "<name>", path?: "a.b" }` takes the value
5751
+ * the call passed for that control (or a field of it), `{ now: true }` the
5752
+ * call's instant, and `{ $if: … }` tests a call value. An absent value
5753
+ * (`null` included) matches nothing where its control is required, and drops
5754
+ * its filter where it is not.
5820
5755
  *
5821
- * `select` is exclusive with `include`, so a definite include makes this world
5822
- * impossible. A local `omit` is different: it subtracts from the selected
5823
- * result. Keys outside the selected shape have no effect.
5756
+ * `verbs` judges, per model, what a call may do to the rows it sees: a mode
5757
+ * only narrows them (R8). A model's entry may be a function returning it:
5758
+ * it is called when a call of the chain first needs that model, and its
5759
+ * entry admitted then, so a refusal of it fails that call instead of
5760
+ * `$extends`. A function returning deeply frozen plain data is called once
5761
+ * per schema; one returning anything else, once per client.
5824
5762
  */
5825
- type InferSelectedRow<S$1 extends ModelState, Args, Selection$1, ClientDefaults> = undefined extends NodeInclude<Args> ? InferSelectResult<S$1, Selection$1, NodeOmit<Args>, ClientDefaults> : never;
5763
+ type RowsContribution = {
5764
+ readonly control: string;
5765
+ readonly default: string;
5766
+ readonly models: {
5767
+ readonly [model: string]: {
5768
+ readonly [mode: string]: {
5769
+ readonly root?: ScalarFields | string;
5770
+ readonly related?: ScalarFields | string;
5771
+ };
5772
+ };
5773
+ };
5774
+ readonly verbs?: {
5775
+ readonly [model: string]: RowsVerbs | (() => RowsVerbs);
5776
+ };
5777
+ };
5826
5778
  /**
5827
- * The row a node returns when it states no `select`: the model's own output,
5828
- * plus whatever `include` adds, reduced by the node's `omit`.
5779
+ * One model's named predicates, each a `where` admitted once, and the verbs
5780
+ * that take them. `read` ANDs with every mode's `root` and `related`; a write
5781
+ * takes its verb's beside them: a delete `delete`'s, an update, for each
5782
+ * field its data writes, that field's `writes` entry, else `update`'s, and
5783
+ * `update`'s when its data writes only stamps. A join row's change is a write
5784
+ * of the relation on both rows it links; a row only addressed to reach its
5785
+ * children is read. A verb left out matches nothing.
5829
5786
  *
5830
- * An `include` that MAY be absent is read as ABSENT — the common ground of both
5831
- * worlds — while a MAYBE `omit` softens instead (`ApplyOmit`). The asymmetry is
5832
- * the direction of the lie: `include` only ADDS keys, so promising the smaller
5833
- * row promises nothing that is missing at runtime, and the caller who wants the
5834
- * relation spells the `include` definitely; `omit` REMOVES them, so reading a
5835
- * maybe-omit as absent would promise a column the runtime may have dropped.
5787
+ * The row a write produces is judged too, as a value, against the rows as
5788
+ * they stand before the write, inside the statement that writes it (R4): a
5789
+ * created row at `place` (a model naming none is not judged on create); an
5790
+ * updated row at the predicates that judged its old row, and, for each field
5791
+ * its data writes, at that field's `moves` entry, and where it writes the
5792
+ * key of an `acyclic` relation (a to-one relation of the model to itself),
5793
+ * outside its own subtree. `acyclic` may be a function returning that list:
5794
+ * it is called the first time an update writes the key of one of the
5795
+ * model's self relations. A refused row is written by no statement.
5796
+ *
5797
+ * `evidence` declares a projection key (`evidence.as`) a `select` or
5798
+ * `include` may name at every depth, on reads and on the rows a write
5799
+ * returns: per row, whether each of `names` holds there beside `read`, or,
5800
+ * `ordered`, the last of them that holds (`null` on a row `read` does not
5801
+ * hold). `reads` gates a field on a predicate: the row carries it only where
5802
+ * `read` and that predicate hold, a `select` naming it fails on a row
5803
+ * without them, and every operand a call writes over it (`where`, `orderBy`,
5804
+ * aggregates, `distinct`, unique lookups, relation filters) reads it as
5805
+ * absent there. A key or foreign-key field is never gated.
5836
5806
  */
5837
- type InferUnselectedRow<S$1 extends ModelState, Args, Omission = NodeOmit<Args>, ClientDefaults = never> = undefined extends NodeInclude<Args> ? ApplyOmit<InferModelOutput<S$1>, Omission> : ApplyOmit<InferIncludeResult<S$1, NodeInclude<Args>, ClientDefaults>, Omission>;
5807
+ type RowsVerbs = {
5808
+ readonly predicates: {
5809
+ readonly [name: string]: ScalarFields;
5810
+ };
5811
+ readonly read?: string;
5812
+ readonly update?: string;
5813
+ readonly delete?: string;
5814
+ readonly writes?: {
5815
+ readonly [field: string]: string;
5816
+ };
5817
+ readonly place?: string;
5818
+ readonly moves?: {
5819
+ readonly [field: string]: string;
5820
+ };
5821
+ readonly acyclic?: readonly string[] | (() => readonly string[]);
5822
+ readonly evidence?: {
5823
+ readonly as: string;
5824
+ readonly names: readonly string[];
5825
+ readonly ordered?: boolean;
5826
+ };
5827
+ readonly reads?: {
5828
+ readonly [field: string]: string;
5829
+ };
5830
+ };
5838
5831
  /**
5839
- * Result when select is provided - ONLY selected fields are returned
5832
+ * What a delete does on the models named here: an update that stamps `at`
5833
+ * with the call's time and writes `assign`, unless the call's controls match
5834
+ * `removeWhen`.
5840
5835
  */
5841
- type InferSelectResult<S$1 extends ModelState, Selection$1, Omission = undefined, ClientDefaults = never> = Prettify<ApplyOmit<InferSelectedFields<S$1, Selection$1, ClientDefaults> & InferRelationCountSelection<S$1, Selection$1>, Omission> & InferDistanceSelection<S$1, Selection$1, Omission>>;
5836
+ type DeletionContribution = {
5837
+ readonly removeWhen?: {
5838
+ readonly [control: string]: string | number | boolean;
5839
+ };
5840
+ readonly models: {
5841
+ readonly [model: string]: {
5842
+ readonly at?: string;
5843
+ readonly assign?: ScalarFields;
5844
+ };
5845
+ };
5846
+ };
5842
5847
  /**
5843
- * ONE mapped type over the model's shape, dispatching per member on TARGET KIND.
5844
- *
5845
- * There is no second polymorphic pass any more: both target domains live in the
5846
- * one relation map (§5.2), and what still differs is only the ELEMENT shape a
5847
- * variant slot produces — a discriminated `{ type, data }` union reached through
5848
- * its own projection envelope. Splitting the map again here would put the same
5849
- * key through two mapped types and let their guards drift apart.
5848
+ * Fields an extension writes on the models named here: `create` on every
5849
+ * create of the model, `update` on every update of it, a soft delete's
5850
+ * included. A value is a constant, `{ control: "<name>", path?: "a.b" }` for
5851
+ * the value the call passed for that control or a field of it (a call that
5852
+ * passed none writes nothing there), `{ now: true }` for the call's instant,
5853
+ * or, on `update`, one of the field's update operators (`{ increment: 1 }`). A field is written only where the caller left it
5854
+ * out: a call that writes it itself, or writes the relation whose foreign key
5855
+ * holds it, keeps its own value there. A create may leave out such a field
5856
+ * even where the schema requires it: the call's data is checked with it
5857
+ * counted as given. When the model names here are known to the types
5858
+ * (written out, or kept by a `const` type parameter, not a plain
5859
+ * `string[]`), the extended client's types agree, nested creates included:
5860
+ * the field is optional on a create. When two extensions name a field, the
5861
+ * later one writes it, and a value the caller writes wins over both.
5850
5862
  */
5851
- type InferSelectedFields<S$1 extends ModelState, Selection$1, ClientDefaults> = SelectedFields<Selection$1, { [K in keyof Selection$1 & keyof S$1["shape"] as S$1["shape"][K] extends Scalar ? true extends Selection$1[K] ? K : never : K]: S$1["shape"][K] extends Scalar ? InferScalarOutput<S$1["shape"][K]> : S$1["shape"][K] extends AnyRelation ? InferSelectedRelation<S$1, K, S$1["shape"][K], Selection$1[K], ClientDefaults> : never }>;
5852
- /** One selected relation member, per target kind then per projection value. */
5853
- type InferSelectedRelation<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Projection, ClientDefaults> = IsVariantTarget<R$1> extends true ? Projection extends true ? InferPolymorphicResult<S$1, K$1, R$1, undefined, ClientDefaults> : Projection extends object ? InferPolymorphicResult<S$1, K$1, R$1, Projection, ClientDefaults> : never : Projection extends true ? InferRelationResult<S$1, K$1, R$1, ClientDefaults> : Projection extends object ? InferRelationNodeResult<S$1, K$1, R$1, Projection, ClientDefaults> : never;
5854
- type VectorScalarFieldKeys<S$1 extends ModelState> = { [K in keyof S$1["shape"]]: S$1["shape"][K] extends Scalar ? [ExtractScalarState<S$1["shape"][K]>] extends [ScalarState<"vector">] ? K : never : never }[keyof S$1["shape"]];
5855
- type PointScalarFieldKeys<S$1 extends ModelState> = { [K in keyof S$1["shape"]]: S$1["shape"][K] extends Scalar ? [ExtractScalarState<S$1["shape"][K]>] extends [ScalarState<"point">] ? K : never : never }[keyof S$1["shape"]];
5856
- type NullableDistanceScalarFieldKeys<S$1 extends ModelState> = { [K in DistanceScalarFieldKeys<S$1>]: S$1["shape"][K] extends Scalar ? ExtractScalarState<S$1["shape"][K]>["nullable"] extends true ? K : never : never }[DistanceScalarFieldKeys<S$1>];
5857
- type DistanceScalarFieldKeys<S$1 extends ModelState> = VectorScalarFieldKeys<S$1> | PointScalarFieldKeys<S$1>;
5858
- type SelectedDistanceKeys<S$1 extends ModelState, Selection$1> = { [K in keyof Selection$1 & DistanceScalarFieldKeys<S$1>]: Selection$1[K] extends {
5859
- _distance: unknown;
5860
- } ? K : never }[keyof Selection$1 & DistanceScalarFieldKeys<S$1>];
5861
- type SelectedDistanceSources<S$1 extends ModelState, Selection$1> = { [K in SelectedDistanceKeys<S$1, Selection$1>]: true };
5862
- type RemainingDistanceSources<S$1 extends ModelState, Selection$1, Omission> = ApplyOmit<SelectedDistanceSources<S$1, Selection$1>, Omission>;
5863
- type RequiredKeys<T$1> = { [K in keyof T$1]-?: Record<never, never> extends Pick<T$1, K> ? never : K }[keyof T$1];
5864
- type CosineDistanceKeys<S$1 extends ModelState, Selection$1> = { [K in keyof Selection$1 & VectorScalarFieldKeys<S$1>]: Selection$1[K] extends {
5865
- _distance: {
5866
- metric: infer Metric;
5863
+ type DataContribution = {
5864
+ readonly models: {
5865
+ readonly [model: string]: {
5866
+ readonly create?: ScalarFields;
5867
+ readonly update?: ScalarFields;
5868
+ };
5867
5869
  };
5868
- } ? "cosine" extends Metric ? K : never : never }[keyof Selection$1 & VectorScalarFieldKeys<S$1>];
5869
- type DistanceValueForSources<S$1 extends ModelState, Sources, Selection$1> = Extract<keyof Sources, NullableDistanceScalarFieldKeys<S$1> | CosineDistanceKeys<S$1, Selection$1>> extends never ? number : number | null;
5870
- type InferDistanceSelection<S$1 extends ModelState, Selection$1, Omission = undefined, Remaining = RemainingDistanceSources<S$1, Selection$1, Omission>> = [keyof Remaining] extends [never] ? Record<never, never> : [RequiredKeys<Remaining>] extends [never] ? {
5871
- _distance?: DistanceValueForSources<S$1, Remaining, Selection$1>;
5872
- } : {
5873
- _distance: DistanceValueForSources<S$1, Remaining, Selection$1>;
5874
5870
  };
5871
+ /** Operations that select candidates: where a rows control is accepted. */
5872
+ type CandidateOperations = Exclude<Operations, "create" | "createMany">;
5873
+ /** One declared control as the delegates see it. */
5874
+ interface PlacedControl<Value = unknown, Models$1 = PropertyKey, Placed = Operations> {
5875
+ readonly value: Value;
5876
+ readonly models: Models$1;
5877
+ readonly operations: Placed;
5878
+ }
5879
+ type NoControls = Record<never, never>;
5880
+ type ControlValue<Declaration> = Declaration extends {
5881
+ readonly oneOf: readonly (infer Value)[];
5882
+ } ? Value : Declaration extends {
5883
+ readonly schema: StandardSchemaV1<infer Input>;
5884
+ } ? Input : never;
5885
+ type PlacementOperations<On> = On extends "reads" ? CacheableOperations : On extends "writes" ? MutationOperations : On extends readonly (infer Operation)[] ? Operation : Operations;
5886
+ /**
5887
+ * `deletion` places the control `removeWhen` names: on the deletes of the
5888
+ * models it manages, whatever the declaration's `on` says.
5889
+ */
5890
+ type PlaceControl<Name$1, Declaration, Deletion> = Deletion extends {
5891
+ readonly removeWhen: infer RemoveWhen;
5892
+ readonly models: infer Managed;
5893
+ } ? Name$1 extends keyof RemoveWhen ? PlacedControl<ControlValue<Declaration>, keyof Managed, "delete" | "deleteMany"> : PlaceFreeControl<Declaration> : PlaceFreeControl<Declaration>;
5894
+ type PlaceFreeControl<Declaration> = PlacedControl<ControlValue<Declaration>, PropertyKey, PlacementOperations<Declaration extends {
5895
+ readonly on: infer On;
5896
+ } ? On : "all">>;
5897
+ type DeclaredControls<Definition$1> = Definition$1 extends {
5898
+ readonly controls: infer Controls extends ControlsContribution;
5899
+ } ? { readonly [Name in keyof Controls as Controls[Name] extends {
5900
+ readonly bound: true;
5901
+ } ? never : Name]: PlaceControl<Name, Controls[Name], Definition$1 extends {
5902
+ readonly deletion: infer Deletion;
5903
+ } ? Deletion : unknown> } : NoControls;
5904
+ /** Every model entry declares the same mode names: those are the values. */
5905
+ type RowsModes<Rows$1 extends RowsContribution> = Rows$1["default"] | { [Model in keyof Rows$1["models"]]: keyof Rows$1["models"][Model] }[keyof Rows$1["models"]];
5906
+ /** The rows control: every candidate-selecting operation of every model. */
5907
+ type RowsControl<Definition$1> = Definition$1 extends {
5908
+ readonly rows: infer Rows extends RowsContribution;
5909
+ } ? { readonly [Name in Rows["control"]]: PlacedControl<RowsModes<Rows>, PropertyKey, CandidateOperations> } : NoControls;
5875
5910
  /**
5876
- * To-many (list) relation keys — the exact set Prisma's `_count: true`
5877
- * shorthand expands to (`<Model>CountOutputType` holds only list relations).
5878
- *
5879
- * ONE rule for both target domains: a variant collection is a list relation by
5880
- * every reading that matters here — it holds many rows and it has a count.
5911
+ * The models one definition's `rows` can hide from a relation read: its
5912
+ * `models` and `verbs` keys. A to-one relation that targets one of them reads `null` when
5913
+ * its target is hidden, so the result types widen it (`result-types.ts`).
5881
5914
  */
5882
- type ToManyRelationKeys<S$1 extends ModelState> = { [K in keyof S$1["relations"]]: S$1["relations"][K] extends AnyRelation ? Cardinality<S$1["relations"][K]> extends "many" ? K : never : never }[keyof S$1["relations"]];
5915
+ type RowsModels<Definition$1> = Definition$1 extends {
5916
+ readonly rows: infer Rows extends RowsContribution;
5917
+ } ? Extract<keyof Rows["models"] | (Rows extends {
5918
+ readonly verbs: infer Verbs;
5919
+ } ? keyof Verbs : never), string> : never;
5920
+ /** The controls one definition places, keyed by control name. */
5921
+ type DefinitionControls<Definition$1> = DeclaredControls<Definition$1> & RowsControl<Definition$1>;
5922
+ /** The optional control arguments one (model, operation) accepts. */
5923
+ type OperationControls<Controls$1, ModelName$1, Operation$2> = { readonly [Name in keyof Controls$1 as Controls$1[Name] extends PlacedControl<unknown, infer Models, infer Placed> ? ModelName$1 extends Models ? Operation$2 extends Placed ? Name : never : never : never]?: Controls$1[Name] extends PlacedControl<infer Value> ? Value : never };
5883
5924
  /**
5884
- * The relation keys the EXPLICIT `_count: { select: … }` form may name.
5885
- *
5886
- * A deliberate superset of Prisma's, minus one cell: a variant SINGULAR slot's
5887
- * `countFilter` family is a named refusal, so naming it must not compile either.
5888
- * An ordinary singular relation stays nameable, as it is today.
5925
+ * The fields one `data` entry writes on its models' creates: there they may
5926
+ * be left out even where the schema requires them. An update's fields need
5927
+ * nothing, as every field of an update is optional already.
5889
5928
  */
5890
- type CountableRelationKeys<S$1 extends ModelState> = { [K in keyof S$1["relations"]]: S$1["relations"][K] extends AnyRelation ? IsVariantTarget<S$1["relations"][K]> extends true ? Cardinality<S$1["relations"][K]> extends "many" ? K : never : K : never }[keyof S$1["relations"]];
5891
- type InferRelationCountSelection<S$1 extends ModelState, Selection$1> = Selection$1 extends {
5892
- _count: {
5893
- select: infer CountSelection;
5894
- };
5895
- } ? {
5896
- _count: { [K in keyof CountSelection & CountableRelationKeys<S$1> as CountSelection[K] extends true | object ? K : never]: number };
5897
- } : Selection$1 extends {
5898
- _count: true;
5899
- } ? {
5900
- _count: { [K in ToManyRelationKeys<S$1>]: number };
5901
- } : Record<never, never>;
5929
+ interface StampedFields<Models$1 = PropertyKey, Fields$1 = PropertyKey> {
5930
+ readonly models: Models$1;
5931
+ readonly fields: Fields$1;
5932
+ }
5933
+ type CreateStamps<Model$2, Entry> = "create" extends keyof Entry ? Entry extends {
5934
+ readonly create?: infer Fields;
5935
+ } ? StampedFields<Model$2, keyof NonNullable<Fields>> : never : never;
5902
5936
  /**
5903
- * Result when include is provided - base result + included relations
5937
+ * What one definition's `data` writes on creates: one member per model. A
5938
+ * definition whose model names are lost (`{ [model: string]: ... }`, as a
5939
+ * recipe called with a plain `string[]` builds) writes nothing the types can
5940
+ * name: its required fields stay required in the payloads.
5904
5941
  */
5905
- type InferIncludeResult<S$1 extends ModelState, Include$1, ClientDefaults = never> = Prettify<InferModelOutput<S$1> & { [K in keyof Include$1 & keyof S$1["relations"] as Include$1[K] extends true | object ? K : never]: S$1["relations"][K] extends AnyRelation ? InferSelectedRelation<S$1, K, S$1["relations"][K], Include$1[K], ClientDefaults> : never } & InferRelationCountSelection<S$1, Include$1>>;
5942
+ type DefinitionData<Definition$1> = Definition$1 extends {
5943
+ readonly data: {
5944
+ readonly models: infer Models;
5945
+ };
5946
+ } ? string extends keyof Models ? never : { [Model in keyof Models]: CreateStamps<Model, Models[Model]> }[keyof Models] : never;
5947
+ /** The fields a chain writes on every create of one model. */
5948
+ type StampedFieldNames<Data$1, ModelName$1> = Data$1 extends StampedFields<infer Models, infer Fields extends PropertyKey> ? ModelName$1 extends Models ? Fields : never : never;
5906
5949
  /**
5907
- * A relation node in `select`/`include` position: `{ select }`, `{ include }`,
5908
- * `{ omit }`, pagination-only (`{ where, take, … }`), or any combination the
5909
- * parse boundary accepts. A selected node applies its local omit after the
5910
- * selection. An unselected node applies it to the default/include shape.
5911
- * Pagination-only nodes fall through to the full relation payload.
5950
+ * The controls one call admitted, by name. A `rows` control is resolved to its
5951
+ * mode, so an absent one reads as its default; an absent plain control is not
5952
+ * here.
5912
5953
  */
5913
- type InferRelationNodeResult<S$1 extends ModelState, K$1, R$1 extends AnyRelation, Node, ClientDefaults = never> = OrHidden<WrapRelationNode<S$1, K$1, R$1, ApplyRecurrence<S$1, K$1, R$1, Node, InferSelectInclude<GetTargetModelState<R$1>, Node, NodeSelect<Node>, MergeClientOmit<ResolveClientOmit<GetTargetModel<R$1>, ClientDefaults>, NodeOmit<Node>>, ClientDefaults>>>, R$1, ClientDefaults>;
5954
+ type AdmittedControls = Readonly<Record<string, unknown>>;
5955
+ //#endregion
5956
+ //#region src/extensions/query.d.ts
5957
+ type QueryInterceptionMode = "direct" | "transaction" | "array";
5958
+ type RawQueryKind = "queryRaw" | "executeRaw" | "queryRawUnsafe" | "executeRawUnsafe";
5959
+ type WriteOutcome = Readonly<{
5960
+ certainty: "committed" | "may-have-committed";
5961
+ }>;
5962
+ type WriteOutcomeListener = (outcome: WriteOutcome) => unknown | Promise<unknown>;
5963
+ type GenericQueryContextBase<Result$1> = {
5964
+ readonly mode: QueryInterceptionMode;
5965
+ readonly input: Readonly<Record<string, unknown>>;
5966
+ readonly proceed: () => Promise<Result$1>;
5967
+ readonly onWriteOutcome: (listener: WriteOutcomeListener) => void;
5968
+ };
5969
+ type GenericModelQueryContext<Result$1> = GenericQueryContextBase<Result$1> & {
5970
+ readonly kind: "model";
5971
+ readonly model: string;
5972
+ readonly operation: Operations;
5973
+ /** The call's controls this handler's extension declares, and only those. */
5974
+ readonly controls?: AdmittedControls;
5975
+ };
5976
+ type GenericRawQueryContext<Result$1> = GenericQueryContextBase<Result$1> & { [Kind in RawQueryKind]: {
5977
+ readonly kind: Kind;
5978
+ readonly model: undefined;
5979
+ readonly operation: `$${Kind}`;
5980
+ } }[RawQueryKind];
5981
+ type GenericQueryContext<Result$1> = GenericModelQueryContext<Result$1> | GenericRawQueryContext<Result$1>;
5982
+ type GenericQueryHandlerCall = <Result$1>(context: GenericQueryContext<Result$1>) => Promise<Result$1>;
5983
+ declare const officialQueryHandlerIdentity: unique symbol;
5984
+ /** Public ordinary query handler; official identities cannot be erased into it. */
5985
+ type GenericQueryHandler = GenericQueryHandlerCall & {
5986
+ readonly [officialQueryHandlerIdentity]?: never;
5987
+ };
5988
+ /** Internal nominal call shape used by official query-based capabilities. */
5989
+ type OfficialGenericQueryHandler = GenericQueryHandlerCall & {
5990
+ readonly [officialQueryHandlerIdentity]: true;
5991
+ };
5914
5992
  /**
5915
- * Extract scalar keys from a ModelShape
5993
+ * Per-model query handlers. Their results read the result context of the
5994
+ * chain they are applied to: `Hidden` names the models its `rows` can hide
5995
+ * (`rows` cannot follow a model-mapped handler, so a later extension adds
5996
+ * none). A `rows` entry in the handler's OWN definition is not seen, as no
5997
+ * definition types against its own contributions: declare it one step
5998
+ * earlier.
5916
5999
  */
5917
- type ScalarKeys$1<T$1 extends ModelShape> = { [K in keyof T$1]: T$1[K] extends Scalar ? K : never }[keyof T$1];
6000
+ type QueryHandlerMap<C$1 extends VibORMConfig, Hidden$1 extends string = never> = { readonly [ModelName in keyof ClientSchema<C$1>]?: { readonly [OperationName in Operations]?: <Arg extends Exclude<OperationPayload<OperationName, ClientSchema<C$1>[ModelName]>, undefined>>(context: {
6001
+ readonly mode: QueryInterceptionMode;
6002
+ readonly kind: "model";
6003
+ readonly model: ModelName;
6004
+ readonly operation: OperationName;
6005
+ readonly input: Readonly<Arg>;
6006
+ /** The call's controls this handler's extension declares, and only those. */
6007
+ readonly controls?: AdmittedControls;
6008
+ readonly proceed: () => Promise<ContextualOperationResult<C$1, ModelName, OperationName, Arg, ClientRowsContext<C$1, Hidden$1>>>;
6009
+ readonly onWriteOutcome: (listener: WriteOutcomeListener) => void;
6010
+ }) => Promise<ContextualOperationResult<C$1, ModelName, OperationName, Arg, ClientRowsContext<C$1, Hidden$1>>> } };
6011
+ //#endregion
6012
+ //#region src/cache/capability.d.ts
6013
+ declare const OFFICIAL_CACHE_NAME = "viborm.cache";
6014
+ /** The exact official query contribution. It is recognized by identity. */
6015
+ type OfficialCacheQueryContribution = OfficialGenericQueryHandler & {
6016
+ bind(thisArg: unknown): GenericQueryHandler;
6017
+ };
5918
6018
  /**
5919
- * Infer base type from a scalar for aggregates.
5920
- * Uses InferScalarOutput for correct DB result types.
6019
+ * A mutation's `cache` argument is the cache's declared control (ruling 7):
6020
+ * core removes and admits it before request handlers run, through the cache's
6021
+ * own parser, so a malformed value is still a `CacheConfigurationError`.
5921
6022
  */
5922
- type InferScalarBase<F$1> = F$1 extends Scalar ? InferScalarOutput<F$1> : never;
5923
- /** True when the scalar is a decimal, whose aggregates stay exact Decimals. */
5924
- type IsDecimalScalar<F$1> = ExtractScalarState<F$1> extends {
5925
- type: "decimal";
5926
- } ? true : false;
6023
+ type OfficialCacheControls = {
6024
+ readonly cache: {
6025
+ readonly schema: StandardSchemaV1<CacheInvalidationOptions>;
6026
+ readonly on: "writes";
6027
+ };
6028
+ };
6029
+ /** The official value accepted by the dedicated `$extends` overload. */
6030
+ type OfficialCacheExtension = {
6031
+ readonly name: typeof OFFICIAL_CACHE_NAME;
6032
+ readonly query: OfficialCacheQueryContribution;
6033
+ readonly controls: OfficialCacheControls;
6034
+ };
6035
+ //#endregion
6036
+ //#region src/client/omit.d.ts
6037
+ /** Fields a client hides by default, per model key of the schema. */
6038
+ type ClientOmitConfig<S$1 extends Record<string, AnyModel>> = { [K in keyof S$1]?: ClientModelOmit<S$1[K]> };
5927
6039
  /**
5928
- * Result type for aggregate operations
5929
- * Dynamically typed based on which aggregates are requested
5930
- *
5931
- * THE RULE, and it is the RESULT PARSER's rule, not a guess:
5932
- * `result-aggregate-parser.ts` marks `_sum` / `_min` / `_max` as `typed` and
5933
- * decodes them through the FIELD'S OWN scalar decoder, so those three come back
5934
- * spelled exactly like the column — `_sum` of an `s.bigInt()` is a `bigint`,
5935
- * `_sum` of an `s.decimal({ precision, scale })` is an exact `Decimal`
5936
- * (widened in precision, but still the field's scale). Only `_avg` takes the
5937
- * widen-to-number path, and even it stays a `Decimal` for a decimal, because an
5938
- * average of decimals is still a decimal — quantized to the field scale with
5939
- * round-half-to-even.
6040
+ * The scalars of `M` a client may hide — every scalar except the ones the
6041
+ * MODEL already hides for good (naming one of those has no `omit` key to name;
6042
+ * see `@validation/model/core/projection`).
5940
6043
  *
5941
- * `_sum` used to be typed `number` for everything but a decimal, which made
5942
- * `agg._sum.big * 2` type-check and then throw "Cannot mix BigInt and other
5943
- * types" — and, worse, `agg._sum.big === 150` silently false. The decoder is the
5944
- * half that is pinned behaviorally (tests/drivers/scalar-roundtrip-behavior.ts),
5945
- * so the type follows it.
6044
+ * The `any` arm is not decoration. A schema-generic extension sees
6045
+ * `Model<any>`, whose `scalars` is `any` — and the subtraction above would then
6046
+ * cancel to `never`, leaving `Partial<Record<never, true>>`, a config object
6047
+ * with no known properties. Answering `string` preserves the contextual
6048
+ * literal `true` until a concrete schema binds the official extension.
5946
6049
  */
5947
- type AggregateResultType<T$1 extends ModelShape, Args> = Prettify<SelectedFields<Args, { [K in keyof Args as K extends `_${string}` ? K : never]: K extends "_count" ? Args[K] extends boolean ? number : Args[K] extends object ? SelectedCountResult<Args[K]> : never : K extends "_sum" ? Args[K] extends object ? SelectedFields<Args[K], { [F in keyof Args[K]]: (F extends ScalarKeys$1<T$1> ? InferScalarBase<T$1[F]> : number) | null }> : never : K extends "_avg" ? Args[K] extends object ? SelectedFields<Args[K], { [F in keyof Args[K]]: (F extends ScalarKeys$1<T$1> ? IsDecimalScalar<T$1[F]> extends true ? Decimal : number : number) | null }> : never : K extends "_min" | "_max" ? Args[K] extends object ? SelectedFields<Args[K], { [F in keyof Args[K]]: F extends ScalarKeys$1<T$1> ? InferScalarBase<T$1[F]> | null : never }> : never : never }>>;
6050
+ type ProjectableKeysOf<M$1 extends AnyModel> = 0 extends 1 & M$1["~"]["state"]["scalars"] ? string : Extract<Exclude<keyof M$1["~"]["state"]["scalars"], M$1["~"]["state"]["omit"] extends Record<string, true> ? keyof M$1["~"]["state"]["omit"] : never>, string>;
5948
6051
  /**
5949
- * Result type for groupBy operations
5950
- * Includes the grouped-by fields plus any requested aggregates
6052
+ * The fields one model hides by default, each flagged `true`.
6053
+ *
6054
+ * `true` only — not `boolean`. Two reasons, and they are the same reason:
6055
+ * - a `false` here would be a key that does nothing (the resolver only ever
6056
+ * acts on `=== true`), and a config key that silently does nothing is the
6057
+ * shape this codebase refuses; per-field re-inclusion belongs on the QUERY
6058
+ * (`omit: { passwordHash: false }`), which is where it can be undone;
6059
+ * - `boolean` as the contextual type widens the `true` a caller writes, and a
6060
+ * widened flag is a flag the RESULT TYPE cannot resolve — it would render
6061
+ * `passwordHash?: string` on a client that hides the column outright.
5951
6062
  */
5952
- type GroupByResultType<T$1 extends ModelShape, Args> = Args extends {
5953
- by: infer B;
5954
- } ? Prettify<(B extends readonly (infer K)[] ? { [F in Extract<K, ScalarKeys$1<T$1> & keyof T$1>]: InferScalarBase<T$1[F]> } : B extends ScalarKeys$1<T$1> & keyof T$1 ? { [F in B]: InferScalarBase<T$1[F]> } : never) & AggregateResultType<T$1, Args>> : never;
6063
+ type ClientModelOmit<M$1 extends AnyModel> = Partial<Record<ProjectableKeysOf<M$1>, true>>;
6064
+ type ClientOmitKeys<Value> = Value extends unknown ? keyof Value : never;
6065
+ type ClientOmitEntry<Given, ModelName$1 extends PropertyKey> = Given extends unknown ? ModelName$1 extends keyof Given ? Given[ModelName$1] : never : never;
6066
+ /** Structural exactness for a direct client-default omit configuration. */
6067
+ type ExactClientOmitConfig<Given, S$1 extends Record<string, AnyModel>> = Record<Exclude<ClientOmitKeys<Given>, keyof S$1>, never> & { [ModelName in Extract<ClientOmitKeys<Given>, keyof S$1>]?: Record<Exclude<ClientOmitKeys<ClientOmitEntry<Given, ModelName>>, keyof ClientModelOmit<S$1[ModelName]>>, never> };
6068
+ //#endregion
6069
+ //#region src/client/default-omit-extension.d.ts
6070
+ declare const OFFICIAL_DEFAULT_OMIT_NAME = "viborm.defaultOmit";
6071
+ declare const officialDefaultOmitConfig: unique symbol;
6072
+ /** The authenticated request identity carrying one exact static omit witness. */
6073
+ type OfficialDefaultOmitRequestContribution<Config> = OfficialGenericRequestHandler & {
6074
+ readonly [officialDefaultOmitConfig]: Config;
6075
+ bind(thisArg: unknown): GenericRequestHandler;
6076
+ };
6077
+ /** The official value accepted by the dedicated `$extends` admission branch. */
6078
+ type OfficialDefaultOmitExtension<Config extends object = object> = {
6079
+ readonly name: typeof OFFICIAL_DEFAULT_OMIT_NAME;
6080
+ readonly request: OfficialDefaultOmitRequestContribution<Config>;
6081
+ };
6082
+ type DefaultOmitBinder<S$1 extends Schema$1> = <const Config extends ClientOmitConfig<S$1>>(config: Config & NoInfer<ExactClientOmitConfig<Config, S$1>>) => OfficialDefaultOmitExtension<Config & object>;
6083
+ /** Create VibORM's fixed-name schema-bound default-omit extension. */
6084
+ declare function defaultOmit<S$1 extends Schema$1>(): DefaultOmitBinder<S$1>;
5955
6085
  //#endregion
5956
6086
  //#region src/client/projected-types.d.ts
5957
6087
  /** The row operations a projection key reaches. */
@@ -6018,18 +6148,18 @@ type KeyResult<Entry, Asked> = Entry extends {
6018
6148
  type KeyMember<Node, Models$1 extends ProjectionModelsConstraint, Name$1 extends keyof Models$1, Key$1 extends string> = Key$1 extends keyof Spelled<Node> ? Spelled<Node>[Key$1] extends false | undefined ? unknown : { readonly [K in Key$1]: KeyResult<Models$1[Name$1]["evidence"], Spelled<Node>[Key$1]> } : unknown;
6019
6149
  type SpelledRelations<Node, Models$1 extends ProjectionModelsConstraint, Name$1 extends keyof Models$1> = Extract<keyof Spelled<Node>, keyof RelationsOf<Models$1, Name$1>>;
6020
6150
  /** Preserve a variant carrier and overlay its selected target document. */
6021
- type OverlayVariant<Result, Node, Models$1 extends ProjectionModelsConstraint, Links$2, Key$1 extends string> = Result extends readonly unknown[] ? { [Index in keyof Result]: OverlayVariant<Result[Index], Node extends {
6151
+ type OverlayVariant<Result$1, Node, Models$1 extends ProjectionModelsConstraint, Links$2, Key$1 extends string> = Result$1 extends readonly unknown[] ? { [Index in keyof Result$1]: OverlayVariant<Result$1[Index], Node extends {
6022
6152
  readonly variants?: infer Arms;
6023
- } ? Arms : undefined, Models$1, Links$2, Key$1> } : Result extends {
6153
+ } ? Arms : undefined, Models$1, Links$2, Key$1> } : Result$1 extends {
6024
6154
  readonly type: infer Variant;
6025
6155
  readonly data: unknown;
6026
- } ? { [P in keyof Result]: P extends "data" ? Variant extends keyof Node ? Overlay<Result[P], Node[Variant], Models$1, VariantName<Models$1, Links$2, Variant>, Key$1> : Result[P] : Result[P] } : Result;
6027
- type OverlayRelation<Result, Node, Models$1 extends ProjectionModelsConstraint, Name$1 extends keyof Models$1, Field$1, Key$1 extends string> = Field$1 extends keyof Models$1[Name$1]["relations"] ? Models$1[Name$1]["relations"][Field$1] extends infer Links ? [Links] extends [PropertyKey] ? Overlay<Result, Node, Models$1, Extract<Links, keyof Models$1>, Key$1> : OverlayVariant<Result, Node, Models$1, Links, Key$1> : never : Result;
6156
+ } ? { [P in keyof Result$1]: P extends "data" ? Variant extends keyof Node ? Overlay<Result$1[P], Node[Variant], Models$1, VariantName<Models$1, Links$2, Variant>, Key$1> : Result$1[P] : Result$1[P] } : Result$1;
6157
+ type OverlayRelation<Result$1, Node, Models$1 extends ProjectionModelsConstraint, Name$1 extends keyof Models$1, Field$1, Key$1 extends string> = Field$1 extends keyof Models$1[Name$1]["relations"] ? Models$1[Name$1]["relations"][Field$1] extends infer Links ? [Links] extends [PropertyKey] ? Overlay<Result$1, Node, Models$1, Extract<Links, keyof Models$1>, Key$1> : OverlayVariant<Result$1, Node, Models$1, Links, Key$1> : never : Result$1;
6028
6158
  type OverlayRow<Row$1, Node, Models$1 extends ProjectionModelsConstraint, Name$1 extends keyof Models$1, Key$1 extends string> = Prettify<{ [Field in keyof Row$1]: Field extends SpelledRelations<Node, Models$1, Name$1> ? Spelled<Node>[Field] extends object ? OverlayRelation<Row$1[Field], Spelled<Node>[Field], Models$1, Name$1, Field, Key$1> : Row$1[Field] : Row$1[Field] } & KeyMember<Node, Models$1, Name$1, Key$1>>;
6029
6159
  /** A result with the key's member added wherever the call spelled it. */
6030
- type Overlay<Result, Node, Models$1 extends ProjectionModelsConstraint, Name$1 extends keyof Models$1, Key$1 extends string> = Result extends readonly (infer Row)[] ? OverlayRow<Row, Node, Models$1, Name$1, Key$1>[] : Result extends object ? OverlayRow<Result, Node, Models$1, Name$1, Key$1> : Result;
6160
+ type Overlay<Result$1, Node, Models$1 extends ProjectionModelsConstraint, Name$1 extends keyof Models$1, Key$1 extends string> = Result$1 extends readonly (infer Row)[] ? OverlayRow<Row, Node, Models$1, Name$1, Key$1>[] : Result$1 extends object ? OverlayRow<Result$1, Node, Models$1, Name$1, Key$1> : Result$1;
6031
6161
  type ProjectedMethod<O$1 extends ProjectedOperation, C$1 extends VibORMConfig, ModelName$1 extends keyof ClientSchema<C$1>, ClientDefaults, Controls$1, Models$1 extends ProjectionModelsConstraint, Key$1 extends string, Pending extends boolean = true, M$1 extends Model$1<any> = ClientSchema<C$1>[ModelName$1], Payload = OperationPayload<O$1, M$1>, Placed = PlacedOperationControls<Controls$1, ModelName$1, O$1>> = <Arg extends ProjectedArgs<Exclude<Payload, undefined>, Models$1, ModelName$1, Key$1>>(args: Arg & WithControlArgs<NoExtraOperationKeys<O$1, WithoutKey<Arg, Key$1>, Exclude<Payload, undefined>, M$1, Placed>, Placed>) => ProjectedCarrier<Overlay<ContextualOperationResult<C$1, ModelName$1, O$1, WithoutKey<Arg, Key$1>, ClientDefaults>, Arg, Models$1, ModelName$1, Key$1>, Pending>;
6032
- type ProjectedCarrier<Result, Pending extends boolean> = Pending extends true ? PendingOperation<Result> : Promise<Result>;
6162
+ type ProjectedCarrier<Result$1, Pending extends boolean> = Pending extends true ? PendingOperation<Result$1> : Promise<Result$1>;
6033
6163
  /** Type-only projection facts retained when a cached view changes the carrier. */
6034
6164
  declare const projectedModelState: unique symbol;
6035
6165
  /**
@@ -6090,6 +6220,14 @@ interface VibORMConfig<S$1 extends Schema$1 = Schema$1> {
6090
6220
  * table and selector names, and the absence of required-relation cycles.
6091
6221
  */
6092
6222
  skipSchemaValidation?: boolean;
6223
+ /**
6224
+ * Answer the `findUnique` calls issued in the same tick with one read over
6225
+ * their keys (Prisma's dataloader), instead of one read each. Off by
6226
+ * default: the shared read runs in the first call's async context, so a
6227
+ * driver that picks its database by `AsyncLocalStorage`, or a trace per
6228
+ * request, sees that call's context for every call of the batch.
6229
+ */
6230
+ findUniqueBatching?: boolean;
6093
6231
  }
6094
6232
  interface DriverConfig<S$1 extends Schema$1 = Schema$1> extends Omit<VibORMConfig<S$1>, "driver"> {}
6095
6233
  type OrdinaryOfficialExtensionGuard<Definition$1> = Definition$1 extends {
@@ -6137,6 +6275,7 @@ interface ProjectedContribution<Contribution extends ExtensionStateConstraint, P
6137
6275
  readonly controls: Contribution["controls"];
6138
6276
  readonly rows: Contribution["rows"];
6139
6277
  readonly data: Contribution["data"];
6278
+ readonly result: Contribution["result"];
6140
6279
  }
6141
6280
  type ContributionOf<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, Definition$1, Contribution extends ExtensionStateConstraint = ExtensionStateContributionOf<Definition$1>> = DeclaresEvidence<C$1, Definition$1> extends false ? Contribution : ProjectedContribution<Contribution, ProjectedModelOperations<GatedConfig<C$1, Definition$1>, ClientRowsContext<GatedConfig<C$1, Definition$1>, X$1["rows"] | Contribution["rows"]>, X$1["controls"] & Contribution["controls"], Definition$1>>;
6142
6281
  type AppliedExtensionState<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, Definition$1> = Definition$1 extends OfficialCacheExtension ? EnableExtensionCache<X$1> : Definition$1 extends OfficialDefaultOmitExtension ? X$1 : AccumulatedExtensionState<X$1, ContributionOf<C$1, X$1, Definition$1>>;
@@ -6249,10 +6388,10 @@ interface VibORMClientMembers<C$1 extends VibORMConfig, X$1 extends ExtensionSta
6249
6388
  * Definitions append to the immutable chain; factories compose through the
6250
6389
  * same `$extends` method. Definition model keys are checked against this schema.
6251
6390
  */
6252
- $extends<Result = VibORMClient<C$1, X$1>>(factory: (client: NoInfer<VibORMClient<C$1, X$1>>) => Result & {
6391
+ $extends<Result$1 = VibORMClient<C$1, X$1>>(factory: (client: NoInfer<VibORMClient<C$1, X$1>>) => Result$1 & {
6253
6392
  readonly $schema: Schema$1;
6254
- }): Result;
6255
- $extends<const Definition$1 extends OfficialAwareDefinition<C$1, X$1, Definition$1>>(extension: Definition$1 & ExtensionAdmission<Definition$1, C$1, X$1> & (Definition$1 extends ((...args: never[]) => unknown) ? never : unknown)): VibORMClient<AppliedClientConfig<C$1, Definition$1>, AppliedExtensionState<C$1, X$1, Definition$1>>;
6393
+ }): Result$1;
6394
+ $extends<const Definition$1 extends OfficialAwareDefinition<C$1, X$1, Definition$1>, Fields$1 = unknown>(extension: Definition$1 & ExtensionAdmission<Definition$1, C$1, X$1> & (Definition$1 extends ((...args: never[]) => unknown) ? never : unknown) & ResultInference<C$1, X$1["result"], Fields$1>): VibORMClient<AppliedClientConfig<C$1, Definition$1>, AppliedExtensionState<C$1, X$1, Definition$1>>;
6256
6395
  }
6257
6396
  type ApplyClientExtensions<C$1 extends VibORMConfig, X$1 extends ExtensionStateConstraint, Definitions extends readonly unknown[]> = Definitions extends readonly [] ? VibORMClient<C$1, X$1> : Definitions extends readonly [infer Definition, ...infer RemainingDefinitions] ? Definition extends ((...args: never[]) => unknown) ? never : Definition extends OfficialAwareDefinition<C$1, X$1> ? Definition extends ExtensionAdmission<Definition, C$1, X$1> ? ApplyClientExtensions<AppliedClientConfig<C$1, Definition>, AppliedExtensionState<C$1, X$1, Definition>, RemainingDefinitions> : never : never : never;
6258
6397
  /**
@@ -9425,7 +9564,7 @@ type ForeignKeyScalarKeys<M$1 extends AnyModel> = { [K in keyof ModelRelations<M
9425
9564
  readonly fields: readonly (infer ScalarKey extends string)[];
9426
9565
  };
9427
9566
  } ? ScalarKey : never }[keyof ModelRelations<M$1>];
9428
- type RequiredForeignKeyMembers<M$1 extends AnyModel, Members extends string> = Extract<Members, RequiredModelScalarKeys<M$1>>;
9567
+ type RequiredForeignKeyMembers<M$1 extends AnyModel, Members$1 extends string> = Extract<Members$1, RequiredModelScalarKeys<M$1>>;
9429
9568
  /**
9430
9569
  * One singular stored reference, as the key sets a create payload may satisfy
9431
9570
  * its non-produced columns with. An empty slot still needs every non-null member;
@@ -9501,19 +9640,31 @@ type CreateSchema<M$1 extends AnyModel, F$1 extends ScalarSchemas<M$1>> = V$1.Ob
9501
9640
  requiresOneOfKeySets: readonly CreateRequirementGroup<M$1>[];
9502
9641
  }>;
9503
9642
  //#endregion
9643
+ //#region src/validation/primitives/non-nullable.d.ts
9644
+ interface NonNullableSchema<TWrapped extends VibSchema<any, any>, TInput = NonNullable<InferInput<TWrapped>>, TOutput = NonNullable<InferOutput<TWrapped>>> extends VibSchema<TInput, TOutput> {
9645
+ readonly type: "nonNullable";
9646
+ readonly wrapped: TWrapped;
9647
+ }
9648
+ //#endregion
9504
9649
  //#region src/validation/model/core/filter.d.ts
9505
9650
  type ModelStateOf$4<M$1 extends AnyModel> = M$1["~"]["state"];
9506
9651
  type UniqueScalarSchemas<M$1 extends AnyModel, F$1 extends ScalarSchemas<M$1>> = Pick<F$1["scalars"], Extract<keyof F$1["scalars"], keyof ModelStateOf$4<M$1>["uniques"]>>;
9507
9652
  type ScalarFilterSchema<M$1 extends AnyModel, F$1 extends ScalarSchemas<M$1>> = V$1.FromObject<F$1["scalars"], "filter">;
9508
- type UniqueFilterSchema<M$1 extends AnyModel, F$1 extends ScalarSchemas<M$1>> = V$1.FromObject<UniqueScalarSchemas<M$1, F$1>, "base">;
9653
+ /** A field's value schema in a unique selector: never `null`. */
9654
+ type UniqueMember<S$1> = S$1 extends {
9655
+ readonly base: infer Base extends VibSchema<any, any>;
9656
+ } ? NonNullableSchema<Base> : never;
9657
+ type UniqueFilterSchema<M$1 extends AnyModel, F$1 extends ScalarSchemas<M$1>> = V$1.Object<{ [K in keyof UniqueScalarSchemas<M$1, F$1>]: UniqueMember<UniqueScalarSchemas<M$1, F$1>[K]> }>;
9509
9658
  type RelationFilterSchema<M$1 extends AnyModel, F$1 extends ScalarSchemas<M$1>> = V$1.FromObject<F$1["relations"], "filter">;
9510
9659
  /**
9511
9660
  * Build compound constraint filter schema
9512
9661
  * Creates an object schema where each compound key maps to an optional object of field base schemas
9513
9662
  */
9514
- type CompoundConstraintEntries<M$1 extends AnyModel> = (ModelStateOf$4<M$1>["compoundId"] extends Record<string, ObjectSchema<any>> ? ModelStateOf$4<M$1>["compoundId"] : Record<never, never>) & (ModelStateOf$4<M$1>["compoundUniques"] extends Record<string, ObjectSchema<any>> ? ModelStateOf$4<M$1>["compoundUniques"] : Record<never, never>);
9663
+ /** A declared compound selector with every member's `null` removed. */
9664
+ type NonNullSelectors<Selectors> = { [Name in keyof Selectors]: Selectors[Name] extends ObjectSchema<infer Members, infer Options> ? ObjectSchema<{ [Member in keyof Members]: Members[Member] extends VibSchema<any, any> ? NonNullableSchema<Members[Member]> : Members[Member] }, Options> : Selectors[Name] };
9665
+ type CompoundConstraintEntries<M$1 extends AnyModel> = (ModelStateOf$4<M$1>["compoundId"] extends Record<string, ObjectSchema<any>> ? NonNullSelectors<ModelStateOf$4<M$1>["compoundId"]> : Record<never, never>) & (ModelStateOf$4<M$1>["compoundUniques"] extends Record<string, ObjectSchema<any>> ? NonNullSelectors<ModelStateOf$4<M$1>["compoundUniques"]> : Record<never, never>);
9515
9666
  type CompoundConstraintFilterSchema<M$1 extends AnyModel> = ObjectSchema<CompoundConstraintEntries<M$1>>;
9516
- type CompoundIdFilterSchema<M$1 extends AnyModel> = V$1.Object<ModelStateOf$4<M$1>["compoundId"]>;
9667
+ type CompoundIdFilterSchema<M$1 extends AnyModel> = V$1.Object<NonNullSelectors<ModelStateOf$4<M$1>["compoundId"]>>;
9517
9668
  //#endregion
9518
9669
  //#region src/validation/model/core/projection.d.ts
9519
9670
  type ModelStateOf$3<M$1 extends AnyModel> = M$1["~"]["state"];
@@ -11029,6 +11180,70 @@ type StampedOperation = "create" | "createMany" | "update" | "updateMany" | "ups
11029
11180
  * §7.5 and §7.1).
11030
11181
  */
11031
11182
  type StampedOperations<C$1 extends VibORMConfig, ClientDefaults, Controls$1, Data$1, K$1 extends keyof ClientSchema<C$1>> = { [O in StampedOperation]: Operation$1<O, ClientSchema<C$1>[K$1], ClientDefaultOmit<C$1, K$1>, ClientDefaults, PlacedOperationControls<Controls$1, K$1, O>, StampedPayload<O, OperationPayload<O, ClientSchema<C$1>[K$1]>, ClientSchema<C$1>[K$1], StampedFieldNames<Data$1, K$1>, Stamps<Data$1, ClientSchema<C$1>>>> };
11183
+ /**
11184
+ * The operations whose rows a chain's computed fields reach, and whose
11185
+ * `select` and `omit` name them.
11186
+ */
11187
+ type ComputedOperation = RowOperation | "createMany" | "updateMany" | "deleteMany";
11188
+ /** What a computed result type reads: the chain's fields and the schema. */
11189
+ interface ComputedResultContext<Result$1, S$1, ModelName$1> {
11190
+ readonly result: Result$1;
11191
+ readonly schema: S$1;
11192
+ readonly model: ModelName$1;
11193
+ }
11194
+ /**
11195
+ * One model's projecting operations on a client whose chain declares
11196
+ * `result`: `select` and `omit` also name the computed fields, and the rows
11197
+ * returned carry them, nested relation rows included. Only a chain with
11198
+ * `result` reaches this type, so every other client keeps its own
11199
+ * operation types untouched.
11200
+ */
11201
+ type ComputedOperations<C$1 extends VibORMConfig, ClientDefaults, Controls$1, Data$1, K$1 extends keyof ClientSchema<C$1>, Result$1> = { [O in ComputedOperation]: ComputedOperationMethod<O, ClientSchema<C$1>[K$1], ClientDefaultOmit<C$1, K$1>, ClientDefaults, PlacedOperationControls<Controls$1, K$1, O>, WithComputedKeys<O extends StampedOperation ? [Data$1] extends [never] ? OperationPayload<O, ClientSchema<C$1>[K$1]> : StampedPayload<O, OperationPayload<O, ClientSchema<C$1>[K$1]>, ClientSchema<C$1>[K$1], StampedFieldNames<Data$1, K$1>, Stamps<Data$1, ClientSchema<C$1>>> : OperationPayload<O, ClientSchema<C$1>[K$1]>, Extract<keyof ModelResultFields<Result$1, K$1>, string>>, ComputedResultContext<Result$1, ClientSchema<C$1>, K$1>> };
11202
+ type ComputedOperationMethod<O$1 extends Operations, M$1 extends Model$1<any>, DefaultOmit, ClientDefaults, Controls$1, Payload, Context> = undefined extends Payload ? <Arg extends Payload>(args?: WithControlArgs<NoExtraOperationKeys<O$1, Exclude<Arg, undefined>, Exclude<Payload, undefined>, M$1, Controls$1>, Controls$1>) => PendingOperation<WithComputedResult<OperationResultWithClientDefaults<O$1, M$1, Arg, DefaultOmit, ClientDefaults>, M$1, Arg, Context>> : <Arg extends Payload>(args: WithControlArgs<NoExtraOperationKeys<O$1, Arg, Payload, M$1, Controls$1>, Controls$1>) => PendingOperation<WithComputedResult<OperationResultWithClientDefaults<O$1, M$1, Arg, DefaultOmit, ClientDefaults>, M$1, Arg, Context>>;
11203
+ /** A payload whose `select` and `omit` also name the computed fields. */
11204
+ type WithComputedKeys<Payload, Names$1 extends string> = Payload extends object ? Omit<Payload, "select" | "omit"> & { [Key in Extract<keyof Payload, "select" | "omit">]?: (NonNullable<Payload[Key]> & { readonly [Name in Names$1]?: boolean }) | Extract<Payload[Key], undefined> } : Payload;
11205
+ /**
11206
+ * An operation's value with the computed fields added to each row: a list
11207
+ * item by item, `null` and `{ count }` as they are.
11208
+ */
11209
+ type WithComputedResult<Value, M$1, Args, Context> = Value extends readonly (infer Row)[] ? ComputedRow<Row, M$1, Args, Context>[] : Value extends null | BatchPayload ? Value : ComputedRow<Value, M$1, Args, Context>;
11210
+ /** The computed fields of one model: by name at the root, by surface below. */
11211
+ type ComputedFieldsFor<M$1, Context> = Context extends ComputedResultContext<infer Result, infer S, infer ModelName> ? [ModelName] extends [never] ? SurfaceNames<M$1, S> extends infer Names ? [Names] extends [never] ? Record<never, never> : OnlyName<Names> extends infer Name ? [Name] extends [never] ? AmbiguousReplacements<M$1, Result, Names> : ModelResultFields<Result, Name> : never : never : ModelResultFields<Result, ModelName> : never;
11212
+ /**
11213
+ * The fields of a row whose model shares its surface with another: only the
11214
+ * ones that replace a column, each typed as that column or any candidate's
11215
+ * computed value. A field that adds a key is left out, as the row may be of
11216
+ * a model without it.
11217
+ */
11218
+ type AmbiguousReplacements<M$1, Result$1, Names$1> = M$1 extends Model$1<infer State> ? { [Key in ReplacedColumns<Result$1, Names$1, State>]: (State["scalars"][Key] extends Scalar ? InferScalarOutput<State["scalars"][Key]> : never) | ComputedTypeAt<Result$1, Names$1, Key> } : never;
11219
+ type ReplacedColumns<Result$1, Names$1, State$1 extends ModelState> = Names$1 extends unknown ? Extract<keyof ModelResultFields<Result$1, Names$1>, keyof State$1["scalars"]> : never;
11220
+ type ComputedTypeAt<Result$1, Names$1, Key$1> = Names$1 extends unknown ? Key$1 extends keyof ModelResultFields<Result$1, Names$1> ? ModelResultFields<Result$1, Names$1>[Key$1] : never : never;
11221
+ /**
11222
+ * The schema's names whose model has `M`'s shallow surface. The public model
11223
+ * types carry no identity, so two models with the same scalar and relation
11224
+ * keys are indistinguishable here.
11225
+ */
11226
+ type SurfaceNames<M$1, S$1> = M$1 extends Model$1<any> ? { [K in keyof S$1]: S$1[K] extends Model$1<any> ? true extends SameModelResultSurface<ModelResultSurface<M$1>, ModelResultSurface<S$1[K]>> ? K : never : never }[keyof S$1] : never;
11227
+ /**
11228
+ * The one name, or `never` when none or several match: a nested row of a
11229
+ * model that shares its surface is typed with no added field rather than
11230
+ * with another model's (it carries its own at runtime).
11231
+ */
11232
+ type OnlyName<Names$1, All = Names$1> = [Names$1] extends [never] ? never : Names$1 extends unknown ? [All] extends [Names$1] ? Names$1 : never : never;
11233
+ /** The context one relation level down: the model is found by its surface. */
11234
+ type NestedComputedContext<Context> = Context extends ComputedResultContext<infer Result, infer S, unknown> ? ComputedResultContext<Result, S, never> : never;
11235
+ /** The computed fields one node's projection keeps; `omit` subtracts from both. */
11236
+ type KeptComputedFields<Fields$1, Args, Selection$1 = NodeSelect<Args>> = [Selection$1] extends [undefined] ? ApplyOmit<Fields$1, NodeOmit<Args>> : undefined extends Selection$1 ? Partial<Fields$1> : ApplyOmit<{ [K in keyof Selection$1 & keyof Fields$1 as Selection$1[K] extends true ? K : never]: Fields$1[K] } & { [K in keyof Selection$1 & keyof Fields$1 as Selection$1[K] extends true ? never : true extends Selection$1[K] ? K : never]?: Fields$1[K] }, NodeOmit<Args>>;
11237
+ /** The relations one node projects, with the node each one states. */
11238
+ type ProjectedRelations<Args> = [NodeSelect<Args>] extends [undefined] ? NodeInclude<Args> : NodeSelect<Args>;
11239
+ /**
11240
+ * One row of `M` with its computed fields, a field replacing a column it
11241
+ * shadows, and its projected relation rows rebuilt for their own models.
11242
+ * A recursive relation's deeper levels keep their columns' type only.
11243
+ */
11244
+ type ComputedRow<Row$1, M$1, Args, Context, Added = KeptComputedFields<ComputedFieldsFor<M$1, Context>, Args>, Relations = ProjectedRelations<Args>> = Row$1 extends unknown ? Prettify<Omit<Row$1, keyof Added | RebuiltRelationKeys<M$1, Relations>> & Added & { [Key in RebuiltRelationKeys<M$1, Relations> & keyof Row$1]: WithComputedResult<Row$1[Key], RelationTarget<M$1, Key>, Relations[Key & keyof Relations] extends true ? undefined : Relations[Key & keyof Relations], NestedComputedContext<Context>> }> : never;
11245
+ /** The relation keys of a projection whose rows are rebuilt. */
11246
+ type RebuiltRelationKeys<M$1, Relations> = Relations extends object ? { [Key in keyof Relations]: [RelationTarget<M$1, Key>] extends [never] ? never : Relations[Key] extends true | object ? Key : never }[keyof Relations] : never;
11032
11247
  /**
11033
11248
  * The call's own clauses, rebuilt: a create's rows, and an update's for the
11034
11249
  * creates they nest.
@@ -11542,7 +11757,7 @@ type NoExtraOperationKeys<O$1 extends Operations, Arg, Payload, M$1 extends Mode
11542
11757
  * not batchable.
11543
11758
  */
11544
11759
  type OperationMethod<O$1 extends Operations, M$1 extends Model$1<any>, DefaultOmit, ClientDefaults, Controls$1, Payload, Pending extends boolean> = undefined extends Payload ? <Arg extends Payload>(args?: WithControlArgs<NoExtraOperationKeys<O$1, Exclude<Arg, undefined>, Exclude<Payload, undefined>, M$1, Controls$1>, Controls$1>) => OperationCarrier<OperationResultWithClientDefaults<O$1, M$1, Arg, DefaultOmit, ClientDefaults>, Pending> : <Arg extends Payload>(args: WithControlArgs<NoExtraOperationKeys<O$1, Arg, Payload, M$1, Controls$1>, Controls$1>) => OperationCarrier<OperationResultWithClientDefaults<O$1, M$1, Arg, DefaultOmit, ClientDefaults>, Pending>;
11545
- type OperationCarrier<Result, Pending extends boolean> = Pending extends true ? PendingOperation<Result> : Promise<Result>;
11760
+ type OperationCarrier<Result$1, Pending extends boolean> = Pending extends true ? PendingOperation<Result$1> : Promise<Result$1>;
11546
11761
  type Operation$1<O$1 extends Operations, M$1 extends Model$1<any>, DefaultOmit = undefined, ClientDefaults = never, Controls$1 = NoControls, Payload = OperationPayload<O$1, M$1>> = OperationMethod<O$1, M$1, DefaultOmit, ClientDefaults, Controls$1, Payload, true>;
11547
11762
  type CachedOperation<O$1 extends Operations, M$1 extends Model$1<any>, DefaultOmit = undefined, ClientDefaults = never, Controls$1 = NoControls> = OperationMethod<O$1, M$1, DefaultOmit, ClientDefaults, Controls$1, OperationPayload<O$1, M$1>, false>;
11548
11763
  /**
@@ -11640,6 +11855,8 @@ declare class SavepointQueue {
11640
11855
  private queue;
11641
11856
  private head;
11642
11857
  private processing;
11858
+ /** Whether a job holds the queue (runs or waits to be flushed). */
11859
+ get busy(): boolean;
11643
11860
  /**
11644
11861
  * Enqueue a savepoint operation to be executed sequentially.
11645
11862
  * Operations enqueued in the same tick are batched and executed in order.
@@ -11698,11 +11915,11 @@ interface DriverResultParser {
11698
11915
  * the trusted observer and starts the executor inside its span.
11699
11916
  */
11700
11917
  interface OfficialStatementExecutionGate {
11701
- execute<Result>(execution: StatementExecution, executor: () => Promise<Result>): Promise<Result>;
11918
+ execute<Result$1>(execution: StatementExecution, executor: () => Promise<Result$1>): Promise<Result$1>;
11702
11919
  }
11703
11920
  /** @internal One driver lifecycle dispatch, gated the same way. */
11704
11921
  interface OfficialDriverLifecycleExecutionGate {
11705
- execute<Result>(executor: () => Promise<Result>): Promise<Result>;
11922
+ execute<Result$1>(executor: () => Promise<Result$1>): Promise<Result$1>;
11706
11923
  }
11707
11924
  /**
11708
11925
  * Abstract base class for drivers with lazy client initialization.
@@ -11841,13 +12058,13 @@ declare abstract class DriverInstrumentationBase<TClient, TTransaction> {
11841
12058
  /** Whether trusted provenance carries at least one protected observer. */
11842
12059
  protected hasTrustedObservers(context: QueryExecutionContext | undefined): boolean;
11843
12060
  /** Observe one physical statement without exposing SQL or provider state. */
11844
- protected observeTrustedStatement<Result>(context: QueryExecutionContext, child: (gate: OfficialStatementExecutionGate | undefined) => Promise<Result>, readCompletionFacts?: ObservationCompletionFactsReader): Promise<Result>;
12061
+ protected observeTrustedStatement<Result$1>(context: QueryExecutionContext, child: (gate: OfficialStatementExecutionGate | undefined) => Promise<Result$1>, readCompletionFacts?: ObservationCompletionFactsReader): Promise<Result$1>;
11845
12062
  /** Observe one driver-owned lifecycle boundary without exposing its state. */
11846
- protected observeTrustedDriverLifecycle<Result>(kind: Extract<LifecycleUnitKind, "connection" | "savepoint" | "transaction">, context: QueryExecutionContext, boundary: LifecycleBoundary, child: (gate: OfficialDriverLifecycleExecutionGate | undefined) => Promise<Result>, readCompletionFacts?: ObservationCompletionFactsReader): Promise<Result>;
12063
+ protected observeTrustedDriverLifecycle<Result$1>(kind: Extract<LifecycleUnitKind, "connection" | "savepoint" | "transaction">, context: QueryExecutionContext, boundary: LifecycleBoundary, child: (gate: OfficialDriverLifecycleExecutionGate | undefined) => Promise<Result$1>, readCompletionFacts?: ObservationCompletionFactsReader): Promise<Result$1>;
11847
12064
  /** Apply a deferred transform to an internally prepared typed statement. */
11848
12065
  protected materializeTrustedBatchQuery(query: BatchQuery, context: QueryExecutionContext): BatchQuery;
11849
12066
  /** Form one protected statement onion around one native typed batch call. */
11850
- protected observeTrustedBatchStatements<Result>(queries: readonly BatchQuery[], context: QueryExecutionContext, child: (queries: readonly BatchQuery[], gate: OfficialStatementExecutionGate | undefined) => Promise<Result>, readCompletionFacts?: ObservationCompletionFactsReader): Promise<Result>;
12067
+ protected observeTrustedBatchStatements<Result$1>(queries: readonly BatchQuery[], context: QueryExecutionContext, child: (queries: readonly BatchQuery[], gate: OfficialStatementExecutionGate | undefined) => Promise<Result$1>, readCompletionFacts?: ObservationCompletionFactsReader): Promise<Result$1>;
11851
12068
  /** Build one private provider-dispatch gate for the official statement rail. */
11852
12069
  private createOfficialStatementExecutionGate;
11853
12070
  /** Build one late dispatch gate without moving the lifecycle across its queue. */
@@ -11896,6 +12113,13 @@ declare abstract class DriverTransactionBase<TClient, TTransaction> extends Driv
11896
12113
  protected runTransactionBody<T$1>(body: () => Promise<T$1>): Promise<T$1>;
11897
12114
  protected abstract createTransactionBoundDriver(tx: TTransaction, context: QueryExecutionContext): TransactionScopeDriver<TClient, TTransaction>;
11898
12115
  protected assertBaseOperationAllowedDuringTransaction(context: QueryExecutionContext): void;
12116
+ /**
12117
+ * Whether the caller runs inside this driver's own callback transaction,
12118
+ * holding its single connection: an operation on the originating client is
12119
+ * refused there ({@link assertBaseOperationAllowedDuringTransaction}), and
12120
+ * one that waited for the connection instead would wait for itself.
12121
+ */
12122
+ holdsConnectionScope(): boolean;
11899
12123
  /** The refusal above, out of line: outside a transaction it never runs. */
11900
12124
  private transactionBoundError;
11901
12125
  private runConnectionTransactionLease;
@@ -11935,7 +12159,7 @@ declare abstract class DriverTransactionBase<TClient, TTransaction> extends Driv
11935
12159
  /** One typed (or, for `_executeRaw`, raw) provider call, normalized. */
11936
12160
  private executeNormalizedProvider;
11937
12161
  /** The one typed statement lifecycle, shared by public and internal transport. */
11938
- protected executeTypedStatement<Result>(query: Sql, context: QueryExecutionContext | undefined, executeProvider: (client: TClient | TTransaction, sql: string, executionParams: unknown[], executionContext: QueryExecutionContext) => Promise<Result>): Promise<Result>;
12162
+ protected executeTypedStatement<Result$1>(query: Sql, context: QueryExecutionContext | undefined, executeProvider: (client: TClient | TTransaction, sql: string, executionParams: unknown[], executionContext: QueryExecutionContext) => Promise<Result$1>): Promise<Result$1>;
11939
12163
  /**
11940
12164
  * One statement's dispatch: observed when a trusted observer wants it, and
11941
12165
  * queued behind the connection's owner on a single-connection driver.
@@ -12891,6 +13115,14 @@ interface DatabaseAdapter {
12891
13115
  * element type to spell at all.
12892
13116
  */
12893
13117
  enumValue: (values: unknown[]) => Sql;
13118
+ /**
13119
+ * The values a one-column `query` answers, as one array, empty where it
13120
+ * answers none (PostgreSQL `ARRAY(…)`). A row tests a key set held this
13121
+ * way by {@link has} rather than by joining it: the array is computed once
13122
+ * per statement, where a joined set is read again for each row of a
13123
+ * correlated subquery. Absent where the dialect has no array value.
13124
+ */
13125
+ ofRows?: (query: Sql) => Sql;
12894
13126
  /** Check if array contains value */
12895
13127
  has: (column: Sql, value: Sql) => Sql;
12896
13128
  /** Check if array contains all values */
@@ -13049,12 +13281,17 @@ interface DatabaseAdapter {
13049
13281
  * Build WITH clause: WITH name AS (query), ... A member `inlined` is read
13050
13282
  * correlated to each outer row through its own columns: PostgreSQL would
13051
13283
  * materialize a member read twice and scan it, without an index, once
13052
- * per row, so it is written `NOT MATERIALIZED` there.
13284
+ * per row, so it is written `NOT MATERIALIZED` there. A member
13285
+ * `inlined: false` is computed once: SQLite would inline it at every
13286
+ * use, so it is written `MATERIALIZED` there. Without `inlined`, the
13287
+ * database decides. A `recursive` member's query is its two terms,
13288
+ * `anchor UNION recursive`, and makes the clause `WITH RECURSIVE`.
13053
13289
  */
13054
13290
  with: (definitions: {
13055
13291
  name: string;
13056
13292
  query: Sql;
13057
13293
  inlined?: boolean;
13294
+ recursive?: boolean;
13058
13295
  }[]) => Sql;
13059
13296
  /**
13060
13297
  * Build recursive CTE: WITH RECURSIVE name AS (anchor UNION ALL recursive).
@@ -13408,6 +13645,7 @@ declare class MySQLAdapter implements DatabaseAdapter {
13408
13645
  name: string;
13409
13646
  query: Sql;
13410
13647
  inlined?: boolean;
13648
+ recursive?: boolean;
13411
13649
  }[]) => Sql;
13412
13650
  recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
13413
13651
  };
@@ -13465,6 +13703,8 @@ declare class MySQLAdapter implements DatabaseAdapter {
13465
13703
  supportsMutationTargetInSubquery: boolean;
13466
13704
  supportsMutationRowLimit: boolean;
13467
13705
  supportsRowLocks: boolean;
13706
+ locksMissingKeys: boolean;
13707
+ boundsRecursionIterations: boolean;
13468
13708
  };
13469
13709
  lastInsertId: () => Sql;
13470
13710
  vector: {
@@ -13592,6 +13832,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
13592
13832
  literal: (items: Sql[]) => Sql;
13593
13833
  value: (values: unknown[], temporal?: "date" | "datetime") => Sql;
13594
13834
  enumValue: (values: unknown[]) => Sql;
13835
+ ofRows: (query: Sql) => Sql;
13595
13836
  has: (column: Sql, value: Sql) => Sql;
13596
13837
  hasEvery: (column: Sql, values: Sql) => Sql;
13597
13838
  hasSome: (column: Sql, values: Sql) => Sql;
@@ -13646,6 +13887,7 @@ declare class PostgresAdapter implements DatabaseAdapter {
13646
13887
  name: string;
13647
13888
  query: Sql;
13648
13889
  inlined?: boolean;
13890
+ recursive?: boolean;
13649
13891
  }[]) => Sql;
13650
13892
  recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
13651
13893
  };
@@ -13760,6 +14002,19 @@ interface SQLiteAdapterOptions {
13760
14002
  * to `false`.
13761
14003
  */
13762
14004
  readonly sharedRelationBodies?: boolean;
14005
+ /**
14006
+ * The most terms one compound `SELECT` may chain
14007
+ * (`capabilities.compoundSelectTerms`): Cloudflare D1 compiles SQLite with
14008
+ * 5 and refuses a sixth ("too many terms in compound SELECT"). Defaults to
14009
+ * SQLite's own bound, which the engine never reaches.
14010
+ */
14011
+ readonly compoundSelectTerms?: number;
14012
+ /**
14013
+ * Where bodies are shared, the relations a statement may reference before
14014
+ * its repeated walks become reaching sets and its rows join the key sets
14015
+ * they test (`capabilities.relationsPerStatement`). Absent: unbounded.
14016
+ */
14017
+ readonly relationsPerStatement?: number;
13763
14018
  }
13764
14019
  declare function sqliteJsonEquals(left: Sql, right: Sql): Sql;
13765
14020
  declare class SQLiteAdapter implements DatabaseAdapter {
@@ -13767,7 +14022,9 @@ declare class SQLiteAdapter implements DatabaseAdapter {
13767
14022
  constructor({
13768
14023
  temporaryObjects,
13769
14024
  deepExpressions,
13770
- sharedRelationBodies
14025
+ sharedRelationBodies,
14026
+ compoundSelectTerms,
14027
+ relationsPerStatement
13771
14028
  }?: SQLiteAdapterOptions);
13772
14029
  raw: (sqlString: string) => Sql;
13773
14030
  identifiers: {
@@ -13936,6 +14193,7 @@ declare class SQLiteAdapter implements DatabaseAdapter {
13936
14193
  name: string;
13937
14194
  query: Sql;
13938
14195
  inlined?: boolean;
14196
+ recursive?: boolean;
13939
14197
  }[]) => Sql;
13940
14198
  recursive: (name: string, anchor: Sql, recursive: Sql, union?: "all" | "distinct") => Sql;
13941
14199
  };
@@ -13998,4 +14256,4 @@ declare const mysqlAdapter: MySQLAdapter;
13998
14256
  declare const postgresAdapter: PostgresAdapter;
13999
14257
  declare const sqliteAdapter: SQLiteAdapter;
14000
14258
  //#endregion
14001
- export { ModelOperationInput as $, AutoGenerate as $n, ValidationErrorSource as $r, AccumulatedExtensionState as $t, Schema$1 as A, CacheConfigurationError as Ai, BatchQuery as An, BaseBlobSchema as Ar, DriverConfig as At, VariantToOneRelation as B, wrapError as Bi, ModelFieldRefs as Bn, JsonNull as Br, CountResultType as Bt, Client as C, UniqueConstraintError as Ci, WaitUntilFn as Cn, IsoDateSchema as Cr, s as Ct, OperationPayloadSchema as D, isNotNullConstraintError as Di, BatchTransactionOptions as Dn, EnumSchema as Dr, renderSchemaType as Dt, OperationPayload as E, isForeignKeyError as Ei, sqliteResultParser as En, BaseEnumSchema as Er, renderOperationResultType as Et, LinkedClientConfig as F, VibORMError as Fi, V$1 as Fn, toJsonSchema as Fr, VibORMClient as Ft, ParseResult as G, GeoPolygon as Gi, IndexOptions as Gn, inferred as Gr, DefinitionControls as Gt, BigIntScalar as H, GeoArea as Hi, isFieldRef as Hn, JsonNullSentinel as Hr, InferSelectInclude as Ht, Links$1 as I, VibORMErrorCode as Ii, v as In, createSchemaRegistry as Ir, VibORMConfig as It, SchemaRegistryOperation as J, MYSQL as Ji, Model$1 as Jn, JunctionReferentialAction as Jr, RowsVerbs as Jt, Prettify as K, DecimalDescriptor as Ki, IndexType as Kn, AnyRelation as Kr, NoControls as Kt, RelationLinks as L, isRetryableError as Li, StringSchema as Ln, AnyJsonNullSentinel as Lr, createClient as Lt, ClientSchema as M, CacheInvalidTTLError as Mi, Dialect as Mn, BaseBigIntSchema as Mr, ExtendedOperationResult as Mt, FlatSchema as N, CacheOperationNotCacheableError as Ni, QueryExecutionContext as Nn, BigIntSchema as Nr, ExtensionState as Nt, OperationResult as O, isUniqueConstraintError as Oi, DriverTransactionOptions as On, BaseBooleanSchema as Or, validateOperationPayload as Ot, Linked as P, PrismaErrorCode as Pi, QueryResult as Pn, createJsonSchemaConverter as Pr, NoExtraDriverConfigKeys as Pt, ModelCoreSchemas as Q, SQLITE as Qi, DecimalSchema as Qn, ValidationError as Qr, StatementHandler as Qt, ModelShape as R, isVibORMError as Ri, AnyFieldRef as Rn, AnyNull as Rr, AggregateResultType as Rt, CachedClient as S, NotNullConstraintError as Si, CacheSetOptions as Sn, BaseIsoTimestampSchema as Sr, ModelToManyRelation as St, MutationOperations as T, isCheckConstraintError as Ti, WithCacheOptions as Tn, IsoTimestampSchema as Tr, getOperationPayloadSchema as Tt, InferInput as U, GeoBounds as Ui, AnyModel as Un, isJsonNullSentinel as Ur, defaultOmit as Ut, type Scalar as V, DiagnosticDisclosure as Vi, createModelFieldRefs as Vn, JsonNullKind as Vr, GroupByResultType as Vt, InferOutput as W, GeoPoint as Wi, IndexDefinition as Wn, JsonSchema$1 as Wr, OfficialCacheExtension as Wt, ModelArgsSchemas as X, NativeTypeMap as Xi, ModelState as Xn, RelationCardinality as Xr, defineExtension as Xt, VibSchema as Y, NativeType as Yi, ModelInternal as Yn, ReferentialAction as Yr, ClientExtension as Yt, ModelCoreInput as Z, PG as Zi, UpdateState as Zn, RelationSlot as Zr, StatementContext as Zt, ObservationCompletion as _, isUnsupportedOperationError as _i, UnwrapPendingOperation as _n, InputJsonValue as _r, DateScalar as _t, PostgresAdapter as a, FeatureNotSupportedError as ai, MergeExtensionState as an, UpdateState$1 as ar, CoreSchemas as at, OFFICIAL_INSTRUMENTATION_NAME as b, CheckConstraintError as bi, CacheDriver as bn, BaseIsoDateSchema as br, ModelToOneRelation as bt, Operation as c, NestedWriteError as ci, validateSchemaOrThrow as cn, VectorSchema as cr, StringScalar as ct, MigrationSessionAttestation as d, QueryEngineError as di, SchemaValidationIssue as dn, ObjectSchema as dr, JsonScalar as dt, isValidationError as ei, ClientExtensionState as en, AutoGenerateType as er, ModelRelationNestedInput as et, SQLITE_MIGRATION_CAPABILITY as f, QueryError as fi, Severity as fn, BaseIntegerSchema as fr, IntScalar as ft, MigrationNamespaceAttestation as g, isPendingOperationError as gi, PendingOperation as gn, BaseJsonSchema as gr, DateTimeScalar as gt, DriverResultParser as h, isNotFoundError as hi, Schema$3 as hn, NumberSchema as hr, TimeScalar as ht, SQLiteAdapter as i, ConnectionError as ii, ExtensionResultConsumerState as in, ScalarType as ir, ArgsSchemas as it, ValidatedOperationPayload as j, CacheInvalidKeyError as ji, CommittedBatchNotification as jn, BlobSchema as jr, ExtendedClient as jt, Operations as k, isValueTooLongError as ki, TransactionOptionSupport as kn, BooleanSchema as kr, ClientTypeState as kt, AnyDriver as l, NotFoundError as li, SchemaValidationError as ln, BasePointSchema as lr, PointScalar as lt, PinnedSessionReservation as m, isClientInitializationError as mi, DateTimePhysicalForm as mn, IntegerSchema as mr, DecimalScalar as mt, postgresAdapter as n, TransactionError as ni, ExtensionCacheState as nn, InitialScalarState as nr, ModelStateSchemas as nt, MySQLAdapter as o, ForbiddenError as oi, RawOperation as on, parse as or, NumericScalar as ot, SqliteMigrationCapability as p, UnsupportedOperationError as pi, ValidationResult$1 as pn, BaseNumberSchema as pr, EnumScalar as pt, SchemaRegistryLookup as q, Decimal as qi, InitialModelState as qn, Getter as qr, PlacedControl as qt, sqliteAdapter as r, ClientInitializationError as ri, ExtensionContributionState as rn, ScalarState as rr, ScalarSchemas as rt, DatabaseAdapter as s, NestedWriteAssertionError as si, validateSchema as sn, BaseVectorSchema as sr, VectorScalar as st, mysqlAdapter as t, InvalidTransactionInputError as ti, EmptyClientExtensionState as tn, GeneratorDefaultBrand as tr, ModelSchemas as tt, Driver as u, PendingOperationError as ui, isSchemaValidationError as un, PointSchema as ur, NumberScalar as ut, ObservationUnit as v, MigrationError as vi, UnwrapPendingOperations as vn, JsonSchema as vr, BooleanScalar as vt, InferDatabase as w, ValueTooLongError as wi, CacheInvalidationOptions as wn, IsoTimeSchema as wr, getSchemas as wt, CacheableOperations as x, ForeignKeyError as xi, CacheEntry as xn, BaseIsoTimeSchema as xr, ReferencesStage as xt, ObserveHandler as y, isMigrationError as yi, isPendingOperation as yn, JsonValue as yr, BlobScalar as yt, VariantToManyRelation as z, toPrismaErrorCode as zi, FieldRef as zn, DbNull as zr, BatchPayload as zt };
14259
+ export { ModelOperationInput as $, AutoGenerate as $n, ValidationErrorSource as $r, ExtensionResultConsumerState as $t, Schema$1 as A, CacheConfigurationError as Ai, BatchQuery as An, BaseBlobSchema as Ar, DriverConfig as At, VariantToOneRelation as B, wrapError as Bi, ModelFieldRefs as Bn, JsonNull as Br, DefinitionControls as Bt, Client as C, UniqueConstraintError as Ci, WaitUntilFn as Cn, IsoDateSchema as Cr, s as Ct, OperationPayloadSchema as D, isNotNullConstraintError as Di, BatchTransactionOptions as Dn, EnumSchema as Dr, renderSchemaType as Dt, OperationPayload as E, isForeignKeyError as Ei, sqliteResultParser as En, BaseEnumSchema as Er, renderOperationResultType as Et, LinkedClientConfig as F, VibORMError as Fi, V$1 as Fn, toJsonSchema as Fr, VibORMClient as Ft, ParseResult as G, GeoPolygon as Gi, IndexOptions as Gn, inferred as Gr, defineExtension as Gt, BigIntScalar as H, GeoArea as Hi, isFieldRef as Hn, JsonNullSentinel as Hr, PlacedControl as Ht, Links$1 as I, VibORMErrorCode as Ii, v as In, createSchemaRegistry as Ir, VibORMConfig as It, SchemaRegistryOperation as J, MYSQL as Ji, Model$1 as Jn, JunctionReferentialAction as Jr, AccumulatedExtensionState as Jt, Prettify as K, DecimalDescriptor as Ki, IndexType as Kn, AnyRelation as Kr, StatementContext as Kt, RelationLinks as L, isRetryableError as Li, StringSchema as Ln, AnyJsonNullSentinel as Lr, createClient as Lt, ClientSchema as M, CacheInvalidTTLError as Mi, Dialect as Mn, BaseBigIntSchema as Mr, ExtendedOperationResult as Mt, FlatSchema as N, CacheOperationNotCacheableError as Ni, QueryExecutionContext as Nn, BigIntSchema as Nr, ExtensionState as Nt, OperationResult as O, isUniqueConstraintError as Oi, DriverTransactionOptions as On, BaseBooleanSchema as Or, validateOperationPayload as Ot, Linked as P, PrismaErrorCode as Pi, QueryResult as Pn, createJsonSchemaConverter as Pr, NoExtraDriverConfigKeys as Pt, ModelCoreSchemas as Q, SQLITE as Qi, DecimalSchema as Qn, ValidationError as Qr, ExtensionContributionState as Qt, ModelShape as R, isVibORMError as Ri, AnyFieldRef as Rn, AnyNull as Rr, defaultOmit as Rt, CachedClient as S, NotNullConstraintError as Si, CacheSetOptions as Sn, BaseIsoTimestampSchema as Sr, ModelToManyRelation as St, MutationOperations as T, isCheckConstraintError as Ti, WithCacheOptions as Tn, IsoTimestampSchema as Tr, getOperationPayloadSchema as Tt, InferInput as U, GeoBounds as Ui, AnyModel as Un, isJsonNullSentinel as Ur, RowsVerbs as Ut, type Scalar as V, DiagnosticDisclosure as Vi, createModelFieldRefs as Vn, JsonNullKind as Vr, NoControls as Vt, InferOutput as W, GeoPoint as Wi, IndexDefinition as Wn, JsonSchema$1 as Wr, ClientExtension as Wt, ModelArgsSchemas as X, NativeTypeMap as Xi, ModelState as Xn, RelationCardinality as Xr, EmptyClientExtensionState as Xt, VibSchema as Y, NativeType as Yi, ModelInternal as Yn, ReferentialAction as Yr, ClientExtensionState as Yt, ModelCoreInput as Z, PG as Zi, UpdateState as Zn, RelationSlot as Zr, ExtensionCacheState as Zt, ObservationCompletion as _, isUnsupportedOperationError as _i, UnwrapPendingOperation as _n, InputJsonValue as _r, DateScalar as _t, PostgresAdapter as a, FeatureNotSupportedError as ai, InferSelectInclude as an, UpdateState$1 as ar, CoreSchemas as at, OFFICIAL_INSTRUMENTATION_NAME as b, CheckConstraintError as bi, CacheDriver as bn, BaseIsoDateSchema as br, ModelToOneRelation as bt, Operation as c, NestedWriteError as ci, validateSchemaOrThrow as cn, VectorSchema as cr, StringScalar as ct, MigrationSessionAttestation as d, QueryEngineError as di, SchemaValidationIssue as dn, ObjectSchema as dr, JsonScalar as dt, isValidationError as ei, MergeExtensionState as en, AutoGenerateType as er, ModelRelationNestedInput as et, SQLITE_MIGRATION_CAPABILITY as f, QueryError as fi, Severity as fn, BaseIntegerSchema as fr, IntScalar as ft, MigrationNamespaceAttestation as g, isPendingOperationError as gi, PendingOperation as gn, BaseJsonSchema as gr, DateTimeScalar as gt, DriverResultParser as h, isNotFoundError as hi, Schema$3 as hn, NumberSchema as hr, TimeScalar as ht, SQLiteAdapter as i, ConnectionError as ii, GroupByResultType as in, ScalarType as ir, ArgsSchemas as it, ValidatedOperationPayload as j, CacheInvalidKeyError as ji, CommittedBatchNotification as jn, BlobSchema as jr, ExtendedClient as jt, Operations as k, isValueTooLongError as ki, TransactionOptionSupport as kn, BooleanSchema as kr, ClientTypeState as kt, AnyDriver as l, NotFoundError as li, SchemaValidationError as ln, BasePointSchema as lr, PointScalar as lt, PinnedSessionReservation as m, isClientInitializationError as mi, DateTimePhysicalForm as mn, IntegerSchema as mr, DecimalScalar as mt, postgresAdapter as n, TransactionError as ni, BatchPayload as nn, InitialScalarState as nr, ModelStateSchemas as nt, MySQLAdapter as o, ForbiddenError as oi, RawOperation as on, parse as or, NumericScalar as ot, SqliteMigrationCapability as p, UnsupportedOperationError as pi, ValidationResult$1 as pn, BaseNumberSchema as pr, EnumScalar as pt, SchemaRegistryLookup as q, Decimal as qi, InitialModelState as qn, Getter as qr, StatementHandler as qt, sqliteAdapter as r, ClientInitializationError as ri, CountResultType as rn, ScalarState as rr, ScalarSchemas as rt, DatabaseAdapter as s, NestedWriteAssertionError as si, validateSchema as sn, BaseVectorSchema as sr, VectorScalar as st, mysqlAdapter as t, InvalidTransactionInputError as ti, AggregateResultType as tn, GeneratorDefaultBrand as tr, ModelSchemas as tt, Driver as u, PendingOperationError as ui, isSchemaValidationError as un, PointSchema as ur, NumberScalar as ut, ObservationUnit as v, MigrationError as vi, UnwrapPendingOperations as vn, JsonSchema as vr, BooleanScalar as vt, InferDatabase as w, ValueTooLongError as wi, CacheInvalidationOptions as wn, IsoTimeSchema as wr, getSchemas as wt, CacheableOperations as x, ForeignKeyError as xi, CacheEntry as xn, BaseIsoTimeSchema as xr, ReferencesStage as xt, ObserveHandler as y, isMigrationError as yi, isPendingOperation as yn, JsonValue as yr, BlobScalar as yt, VariantToManyRelation as z, toPrismaErrorCode as zi, FieldRef as zn, DbNull as zr, OfficialCacheExtension as zt };