viborm 1.2.4 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/README.md +6 -1
  2. package/dist/{adapter-internals-n3Mf3css.mjs → adapter-internals-AGgQRu5t.mjs} +1 -1
  3. package/dist/{adapter-internals-n3Mf3css.mjs.map → adapter-internals-AGgQRu5t.mjs.map} +1 -1
  4. package/dist/adapter-namespace-BpMbLKpL.mjs +2 -0
  5. package/dist/{adapter-namespace-DqkJQdrD.mjs.map → adapter-namespace-BpMbLKpL.mjs.map} +1 -1
  6. package/dist/adapters.d.mts +1 -1
  7. package/dist/adapters.mjs +1 -1
  8. package/dist/{array-literal-BsbbSLw3.mjs → array-literal-BKdLfNzM.mjs} +1 -1
  9. package/dist/{array-literal-BsbbSLw3.mjs.map → array-literal-BKdLfNzM.mjs.map} +1 -1
  10. package/dist/{base-AdXAoy6l.mjs → base-D3m1S7Uc.mjs} +2 -2
  11. package/dist/{base-AdXAoy6l.mjs.map → base-D3m1S7Uc.mjs.map} +1 -1
  12. package/dist/{batch-refs-4L8ECdPU.mjs → batch-refs-B4zn-FAu.mjs} +2 -2
  13. package/dist/{batch-refs-4L8ECdPU.mjs.map → batch-refs-B4zn-FAu.mjs.map} +1 -1
  14. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs → bind-parameter-capacity-qfEejeOX.mjs} +2 -2
  15. package/dist/{bind-parameter-capacity-CjPgqnmx.mjs.map → bind-parameter-capacity-qfEejeOX.mjs.map} +1 -1
  16. package/dist/builder-Df24l2Bd.mjs +2 -0
  17. package/dist/builder-Df24l2Bd.mjs.map +1 -0
  18. package/dist/bun-sql.d.mts +3 -1
  19. package/dist/bun-sql.mjs +1 -1
  20. package/dist/bun-sql.mjs.map +1 -1
  21. package/dist/bun-sqlite.d.mts +1 -1
  22. package/dist/bun-sqlite.mjs +1 -1
  23. package/dist/cache/cloudflare-kv.d.mts +1 -1
  24. package/dist/cache/cloudflare-kv.mjs +1 -1
  25. package/dist/cache/memory.d.mts +1 -1
  26. package/dist/cache/memory.mjs +1 -1
  27. package/dist/{cache-BO57X0TT.mjs → cache-CIPRF-pz.mjs} +2 -2
  28. package/dist/{cache-BO57X0TT.mjs.map → cache-CIPRF-pz.mjs.map} +1 -1
  29. package/dist/cache.d.mts +1 -1
  30. package/dist/cache.mjs +1 -1
  31. package/dist/cache.mjs.map +1 -1
  32. package/dist/{canonical-json-rfC2Dg0X.mjs → canonical-json-BReb5nFO.mjs} +2 -2
  33. package/dist/{canonical-json-rfC2Dg0X.mjs.map → canonical-json-BReb5nFO.mjs.map} +1 -1
  34. package/dist/chain-C7c1YTXD.mjs +2 -0
  35. package/dist/chain-C7c1YTXD.mjs.map +1 -0
  36. package/dist/cli.mjs +2 -2
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/{client-CUnPXifK.d.mts → client-70MrTq1E.d.mts} +3 -3
  39. package/dist/client-DM1UHfYG.mjs +49 -0
  40. package/dist/{client-B3VWFhv_.mjs.map → client-DM1UHfYG.mjs.map} +1 -1
  41. package/dist/client-_WKrPNmm.mjs +2 -0
  42. package/dist/client-_WKrPNmm.mjs.map +1 -0
  43. package/dist/client.d.mts +2 -2
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-CK41KO7t.mjs → clock-C24RcpwO.mjs} +1 -1
  46. package/dist/{clock-CK41KO7t.mjs.map → clock-C24RcpwO.mjs.map} +1 -1
  47. package/dist/config.d.mts +2 -2
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-Da-efekX.mjs +2 -0
  50. package/dist/controls-Da-efekX.mjs.map +1 -0
  51. package/dist/{current-DyzK6OCh.mjs → current-oXcxSCBQ.mjs} +1 -1
  52. package/dist/{current-DyzK6OCh.mjs.map → current-oXcxSCBQ.mjs.map} +1 -1
  53. package/dist/d1.d.mts +1 -1
  54. package/dist/d1.mjs +1 -1
  55. package/dist/d1.mjs.map +1 -1
  56. package/dist/{datetime-physical-codec-oIhiYZEP.mjs → datetime-physical-codec-BEqQbIP_.mjs} +2 -2
  57. package/dist/{datetime-physical-codec-oIhiYZEP.mjs.map → datetime-physical-codec-BEqQbIP_.mjs.map} +1 -1
  58. package/dist/driver-B9fIori_.mjs +2 -0
  59. package/dist/driver-B9fIori_.mjs.map +1 -0
  60. package/dist/{driver-B19QlFqn.mjs → driver-CPD0Xxw2.mjs} +2 -2
  61. package/dist/{driver-B19QlFqn.mjs.map → driver-CPD0Xxw2.mjs.map} +1 -1
  62. package/dist/driver.d.mts +1 -1
  63. package/dist/driver.mjs +1 -1
  64. package/dist/error-mapping-C9WgitPi.mjs +2 -0
  65. package/dist/error-mapping-C9WgitPi.mjs.map +1 -0
  66. package/dist/every-1pKZteeB.mjs +2 -0
  67. package/dist/{every-o-Nu9Em8.mjs.map → every-1pKZteeB.mjs.map} +1 -1
  68. package/dist/{execution-context-BKR3bgES.mjs → execution-context-rJXTRVrJ.mjs} +1 -1
  69. package/dist/{execution-context-BKR3bgES.mjs.map → execution-context-rJXTRVrJ.mjs.map} +1 -1
  70. package/dist/{fs-estate-CAhDg7nY.mjs → fs-estate-i8Zlr1OQ.mjs} +2 -2
  71. package/dist/{fs-estate-CAhDg7nY.mjs.map → fs-estate-i8Zlr1OQ.mjs.map} +1 -1
  72. package/dist/{geo-area-codec-1SY9im7O.mjs → geo-area-codec-CbkmFArQ.mjs} +2 -2
  73. package/dist/{geo-area-codec-1SY9im7O.mjs.map → geo-area-codec-CbkmFArQ.mjs.map} +1 -1
  74. package/dist/geo-point-codec-DyEHMdJg.mjs +2 -0
  75. package/dist/geo-point-codec-DyEHMdJg.mjs.map +1 -0
  76. package/dist/hydration-DsyHNSDS.mjs +2 -0
  77. package/dist/{hydration-CAxOL4aI.mjs.map → hydration-DsyHNSDS.mjs.map} +1 -1
  78. package/dist/identifier-conversion-DaZ9yNpv.mjs +2 -0
  79. package/dist/{identifier-conversion-GgbwHc2G.mjs.map → identifier-conversion-DaZ9yNpv.mjs.map} +1 -1
  80. package/dist/{identity-CLFhCTZx.mjs → identity-oQvIe7u8.mjs} +2 -2
  81. package/dist/{identity-CLFhCTZx.mjs.map → identity-oQvIe7u8.mjs.map} +1 -1
  82. package/dist/{index-B0b7asA4.d.mts → index-VsM29vYN.d.mts} +5257 -4915
  83. package/dist/index.d.mts +3 -3
  84. package/dist/index.mjs +1 -1
  85. package/dist/index.mjs.map +1 -1
  86. package/dist/instrumentation.d.mts +1 -1
  87. package/dist/instrumentation.mjs +1 -1
  88. package/dist/{invariant-BnLYqsHO.mjs → invariant-D57gi_yW.mjs} +1 -1
  89. package/dist/{invariant-BnLYqsHO.mjs.map → invariant-D57gi_yW.mjs.map} +1 -1
  90. package/dist/{json-number-CGXpPu4D.mjs → json-number-DvmiNx0n.mjs} +1 -1
  91. package/dist/{json-number-CGXpPu4D.mjs.map → json-number-DvmiNx0n.mjs.map} +1 -1
  92. package/dist/key-D_kagnFv.mjs +2 -0
  93. package/dist/{key-BeoOwGr3.mjs.map → key-D_kagnFv.mjs.map} +1 -1
  94. package/dist/{libsql-Drp-zaxq.mjs → libsql-DFAoHXrI.mjs} +3 -3
  95. package/dist/{libsql-Drp-zaxq.mjs.map → libsql-DFAoHXrI.mjs.map} +1 -1
  96. package/dist/libsql.d.mts +1 -1
  97. package/dist/libsql.mjs +1 -1
  98. package/dist/{memory-CDTUZQWL.mjs → memory-GTWgeDNY.mjs} +2 -2
  99. package/dist/{memory-CDTUZQWL.mjs.map → memory-GTWgeDNY.mjs.map} +1 -1
  100. package/dist/migrations/mysql.d.mts +5 -5
  101. package/dist/migrations/mysql.mjs +1 -1
  102. package/dist/migrations/postgres.d.mts +5 -5
  103. package/dist/migrations/postgres.mjs +1 -1
  104. package/dist/migrations/sqlite.d.mts +5 -5
  105. package/dist/migrations/sqlite.mjs +1 -1
  106. package/dist/migrations/storage/durable-object.d.mts +1 -1
  107. package/dist/migrations/storage/durable-object.mjs +1 -1
  108. package/dist/migrations/storage/fs.d.mts +1 -1
  109. package/dist/migrations/storage/fs.mjs +1 -1
  110. package/dist/migrations/storage/r2.d.mts +1 -1
  111. package/dist/migrations/storage/r2.mjs +1 -1
  112. package/dist/migrations/tenant.d.mts +3 -3
  113. package/dist/migrations/tenant.mjs +1 -1
  114. package/dist/{migrations-DTObIjAm.mjs → migrations-Bn1SatyB.mjs} +2 -2
  115. package/dist/{migrations-DTObIjAm.mjs.map → migrations-Bn1SatyB.mjs.map} +1 -1
  116. package/dist/migrations.d.mts +5 -5
  117. package/dist/migrations.mjs +1 -1
  118. package/dist/mysql-adapter-C6c5govr.mjs +2 -0
  119. package/dist/{mysql-adapter-DkJPfoGf.mjs.map → mysql-adapter-C6c5govr.mjs.map} +1 -1
  120. package/dist/{mysql-D7zC03yD.mjs → mysql-xChEivOe.mjs} +6 -6
  121. package/dist/{mysql-D7zC03yD.mjs.map → mysql-xChEivOe.mjs.map} +1 -1
  122. package/dist/mysql2.d.mts +1 -1
  123. package/dist/mysql2.mjs +1 -1
  124. package/dist/{native-types-veeTk36s.mjs → native-types-asNCr26n.mjs} +1 -1
  125. package/dist/{native-types-veeTk36s.mjs.map → native-types-asNCr26n.mjs.map} +1 -1
  126. package/dist/neon-http.d.mts +3 -1
  127. package/dist/neon-http.mjs +1 -1
  128. package/dist/neon-http.mjs.map +1 -1
  129. package/dist/{object-store-DQR6bTBY.mjs → object-store-ChYHlOMD.mjs} +2 -2
  130. package/dist/{object-store-DQR6bTBY.mjs.map → object-store-ChYHlOMD.mjs.map} +1 -1
  131. package/dist/{object-store-DMFXXQEC.d.mts → object-store-D9mvOHP4.d.mts} +4 -4
  132. package/dist/{observation-DUSm7oXK.mjs → observation-Co72iCd1.mjs} +2 -2
  133. package/dist/{observation-DUSm7oXK.mjs.map → observation-Co72iCd1.mjs.map} +1 -1
  134. package/dist/permissions.d.mts +424 -0
  135. package/dist/permissions.mjs +2 -0
  136. package/dist/permissions.mjs.map +1 -0
  137. package/dist/pg.d.mts +9 -1
  138. package/dist/pg.mjs +1 -1
  139. package/dist/pg.mjs.map +1 -1
  140. package/dist/pglite.d.mts +3 -1
  141. package/dist/pglite.mjs +1 -1
  142. package/dist/pglite.mjs.map +1 -1
  143. package/dist/{physical-6V_LNU3L.mjs → physical-CAOaNM4R.mjs} +2 -2
  144. package/dist/{physical-6V_LNU3L.mjs.map → physical-CAOaNM4R.mjs.map} +1 -1
  145. package/dist/{pinned-session-CLxj5M5e.mjs → pinned-session-BTplL3iZ.mjs} +2 -2
  146. package/dist/{pinned-session-CLxj5M5e.mjs.map → pinned-session-BTplL3iZ.mjs.map} +1 -1
  147. package/dist/planetscale.d.mts +1 -1
  148. package/dist/planetscale.mjs +1 -1
  149. package/dist/{planner-C0Q7ks-V.d.mts → planner-C1NzLBge.d.mts} +1 -1
  150. package/dist/{postgres-Dv-QnnbD.mjs → postgres-BqAxDWTQ.mjs} +4 -4
  151. package/dist/{postgres-Dv-QnnbD.mjs.map → postgres-BqAxDWTQ.mjs.map} +1 -1
  152. package/dist/postgres-adapter-CGthb5yh.mjs +2 -0
  153. package/dist/postgres-adapter-CGthb5yh.mjs.map +1 -0
  154. package/dist/postgres-adapter-CxEit2-v.mjs +2 -0
  155. package/dist/postgres-adapter-CxEit2-v.mjs.map +1 -0
  156. package/dist/{postgres-result-7F0DllQe.mjs → postgres-result-KyBKBNJr.mjs} +2 -2
  157. package/dist/{postgres-result-7F0DllQe.mjs.map → postgres-result-KyBKBNJr.mjs.map} +1 -1
  158. package/dist/postgres.d.mts +3 -1
  159. package/dist/postgres.mjs +1 -1
  160. package/dist/postgres.mjs.map +1 -1
  161. package/dist/{provider-limits-BHATED_m.mjs → provider-limits-Da00ilvv.mjs} +2 -2
  162. package/dist/{provider-limits-BHATED_m.mjs.map → provider-limits-Da00ilvv.mjs.map} +1 -1
  163. package/dist/{result-parsing-DRXC89ek.mjs → result-parsing-8wEK3GY1.mjs} +1 -1
  164. package/dist/{result-parsing-DRXC89ek.mjs.map → result-parsing-8wEK3GY1.mjs.map} +1 -1
  165. package/dist/result-shape-CDgX_vzn.mjs +2 -0
  166. package/dist/result-shape-CDgX_vzn.mjs.map +1 -0
  167. package/dist/scalar-S8yMvdmx.mjs +4 -0
  168. package/dist/scalar-S8yMvdmx.mjs.map +1 -0
  169. package/dist/schema/json.d.mts +1 -1
  170. package/dist/schema/json.mjs +1 -1
  171. package/dist/schema/json.mjs.map +1 -1
  172. package/dist/schema-9N9jQlVL.mjs +2 -0
  173. package/dist/{schema-Cjem1-0f.mjs.map → schema-9N9jQlVL.mjs.map} +1 -1
  174. package/dist/{schema-introspection-DEYGC2qg.mjs → schema-introspection-CyXKReK1.mjs} +4 -4
  175. package/dist/{schema-introspection-DEYGC2qg.mjs.map → schema-introspection-CyXKReK1.mjs.map} +1 -1
  176. package/dist/schema.d.mts +1 -1
  177. package/dist/schema.mjs +1 -1
  178. package/dist/{select-assembly-f1UGoblh.mjs → select-assembly-CkGe2ABs.mjs} +2 -2
  179. package/dist/{select-assembly-f1UGoblh.mjs.map → select-assembly-CkGe2ABs.mjs.map} +1 -1
  180. package/dist/{settle-B9Vg1FnP.mjs → settle-CS_k6Ztm.mjs} +2 -2
  181. package/dist/{settle-B9Vg1FnP.mjs.map → settle-CS_k6Ztm.mjs.map} +1 -1
  182. package/dist/soft-delete.d.mts +27 -96
  183. package/dist/soft-delete.mjs +1 -1
  184. package/dist/soft-delete.mjs.map +1 -1
  185. package/dist/sql-Bhxq9arK.mjs +2 -0
  186. package/dist/sql-Bhxq9arK.mjs.map +1 -0
  187. package/dist/{sql-BvfwUKIh.d.mts → sql-EsoN_7Et.d.mts} +24 -0
  188. package/dist/{sql-statement-tokens-BBcoGmJb.mjs → sql-statement-tokens-CFi1y3bK.mjs} +1 -1
  189. package/dist/{sql-statement-tokens-BBcoGmJb.mjs.map → sql-statement-tokens-CFi1y3bK.mjs.map} +1 -1
  190. package/dist/sql.d.mts +1 -1
  191. package/dist/sql.mjs +1 -1
  192. package/dist/sqlite-adapter-BXAJy3mI.mjs +2 -0
  193. package/dist/sqlite-adapter-BXAJy3mI.mjs.map +1 -0
  194. package/dist/{sqlite-utils-DlgokMJN.mjs → sqlite-utils-D_cypcyW.mjs} +2 -2
  195. package/dist/{sqlite-utils-DlgokMJN.mjs.map → sqlite-utils-D_cypcyW.mjs.map} +1 -1
  196. package/dist/sqlite3.d.mts +3 -1
  197. package/dist/sqlite3.mjs +1 -1
  198. package/dist/sqlite3.mjs.map +1 -1
  199. package/dist/{standard-sql-Bk4RZPqJ.mjs → standard-sql-CoGqv-iX.mjs} +3 -3
  200. package/dist/standard-sql-CoGqv-iX.mjs.map +1 -0
  201. package/dist/{suppressed-failure-BwULh-8h.mjs → suppressed-failure-Bdo2aK81.mjs} +1 -1
  202. package/dist/{suppressed-failure-BwULh-8h.mjs.map → suppressed-failure-Bdo2aK81.mjs.map} +1 -1
  203. package/dist/to-many-C1PuFIpf.mjs +2 -0
  204. package/dist/to-many-C1PuFIpf.mjs.map +1 -0
  205. package/dist/{transaction-Bnl6ULTw.mjs → transaction-4dfqals6.mjs} +2 -2
  206. package/dist/{transaction-Bnl6ULTw.mjs.map → transaction-4dfqals6.mjs.map} +1 -1
  207. package/dist/{transaction-operation-CKK3l_9x.mjs → transaction-operation-CU1zlxiG.mjs} +2 -2
  208. package/dist/{transaction-operation-CKK3l_9x.mjs.map → transaction-operation-CU1zlxiG.mjs.map} +1 -1
  209. package/dist/{types-C4v6iAmY.mjs → types-C5Oxz9yp.mjs} +1 -1
  210. package/dist/{types-C4v6iAmY.mjs.map → types-C5Oxz9yp.mjs.map} +1 -1
  211. package/dist/{utils-CZNaOZR7.mjs → utils-CtFUE8UN.mjs} +4 -4
  212. package/dist/{utils-CZNaOZR7.mjs.map → utils-CtFUE8UN.mjs.map} +1 -1
  213. package/dist/v-CYTUI0H5.mjs +2 -0
  214. package/dist/v-CYTUI0H5.mjs.map +1 -0
  215. package/dist/validation-BQtO6srU.mjs +2 -0
  216. package/dist/{validation-PF9-_nKd.mjs.map → validation-BQtO6srU.mjs.map} +1 -1
  217. package/dist/validation-BamBwne9.mjs +2 -0
  218. package/dist/validation-BamBwne9.mjs.map +1 -0
  219. package/dist/validation.d.mts +1 -1
  220. package/dist/validation.mjs +1 -1
  221. package/dist/validator-DgffZq9C.mjs +2 -0
  222. package/dist/validator-DgffZq9C.mjs.map +1 -0
  223. package/dist/version-CXuJzC-q.mjs +2 -0
  224. package/dist/{version-nt0parEY.mjs.map → version-CXuJzC-q.mjs.map} +1 -1
  225. package/package.json +35 -9
  226. package/dist/adapter-namespace-DqkJQdrD.mjs +0 -2
  227. package/dist/builder-Ycvq3ETg.mjs +0 -2
  228. package/dist/builder-Ycvq3ETg.mjs.map +0 -1
  229. package/dist/chain-Dh0FV72b.mjs +0 -2
  230. package/dist/chain-Dh0FV72b.mjs.map +0 -1
  231. package/dist/client-B3VWFhv_.mjs +0 -49
  232. package/dist/client-BLiBmykn.mjs +0 -2
  233. package/dist/client-BLiBmykn.mjs.map +0 -1
  234. package/dist/controls-DXgIn4zh.mjs +0 -2
  235. package/dist/controls-DXgIn4zh.mjs.map +0 -1
  236. package/dist/driver-BlnKXPFF.mjs +0 -2
  237. package/dist/driver-BlnKXPFF.mjs.map +0 -1
  238. package/dist/error-mapping-CnPCv1dm.mjs +0 -2
  239. package/dist/error-mapping-CnPCv1dm.mjs.map +0 -1
  240. package/dist/every-o-Nu9Em8.mjs +0 -2
  241. package/dist/geo-point-codec-lhxH42SK.mjs +0 -2
  242. package/dist/geo-point-codec-lhxH42SK.mjs.map +0 -1
  243. package/dist/hydration-CAxOL4aI.mjs +0 -2
  244. package/dist/identifier-conversion-GgbwHc2G.mjs +0 -2
  245. package/dist/identifier-hQCs8M1n.mjs +0 -2
  246. package/dist/identifier-hQCs8M1n.mjs.map +0 -1
  247. package/dist/key-BeoOwGr3.mjs +0 -2
  248. package/dist/mysql-adapter-DkJPfoGf.mjs +0 -2
  249. package/dist/postgres-adapter-B3SQvcV1.mjs +0 -2
  250. package/dist/postgres-adapter-B3SQvcV1.mjs.map +0 -1
  251. package/dist/postgres-adapter-CQD2oGuD.mjs +0 -2
  252. package/dist/postgres-adapter-CQD2oGuD.mjs.map +0 -1
  253. package/dist/registration-preflight-DEjv050M.mjs +0 -4
  254. package/dist/registration-preflight-DEjv050M.mjs.map +0 -1
  255. package/dist/result-shape-CTNdNSW3.mjs +0 -2
  256. package/dist/result-shape-CTNdNSW3.mjs.map +0 -1
  257. package/dist/scalar-U0wD5bKy.mjs +0 -2
  258. package/dist/scalar-U0wD5bKy.mjs.map +0 -1
  259. package/dist/schema-Cjem1-0f.mjs +0 -2
  260. package/dist/sql-Bp7jicEX.mjs +0 -2
  261. package/dist/sql-Bp7jicEX.mjs.map +0 -1
  262. package/dist/sqlite-adapter-CW_3l6ea.mjs +0 -2
  263. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +0 -1
  264. package/dist/standard-sql-Bk4RZPqJ.mjs.map +0 -1
  265. package/dist/terminal-C8cq1WWX.mjs +0 -2
  266. package/dist/terminal-C8cq1WWX.mjs.map +0 -1
  267. package/dist/v-D5Z06FKN.mjs +0 -2
  268. package/dist/v-D5Z06FKN.mjs.map +0 -1
  269. package/dist/validation-Dk9Q_-C7.mjs +0 -2
  270. package/dist/validation-Dk9Q_-C7.mjs.map +0 -1
  271. package/dist/validation-PF9-_nKd.mjs +0 -2
  272. package/dist/validator-X9-bwtRo.mjs +0 -2
  273. package/dist/validator-X9-bwtRo.mjs.map +0 -1
  274. package/dist/version-nt0parEY.mjs +0 -2
  275. /package/dist/{contract-CIIqgFyb.d.mts → contract-Dw0FR78e.d.mts} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"file":"v-D5Z06FKN.mjs","names":["result","value","describe","v","v"],"sources":["../src/validation/primitives/array.ts","../src/validation/primitives/blob.ts","../src/validation/primitives/boolean.ts","../src/validation/primitives/date.ts","../src/validation/primitives/decimal.ts","../src/validation/primitives/enum.ts","../src/validation/primitives/from-object.ts","../src/validation/primitives/iso.ts","../src/validation/primitives/json.ts","../src/validation/primitives/json-null.ts","../src/validation/primitives/lazy.ts","../src/validation/primitives/literal.ts","../src/validation/primitives/nullable.ts","../src/validation/primitives/omit.ts","../src/validation/primitives/filter-depth.ts","../src/validation/primitives/operand.ts","../src/validation/primitives/pipe.ts","../src/validation/primitives/point.ts","../src/validation/primitives/record.ts","../src/validation/primitives/refused.ts","../src/validation/primitives/transform.ts","../src/validation/primitives/shorthand.ts","../src/validation/primitives/union.ts","../src/validation/primitives/single-or-array.ts","../src/validation/primitives/string.ts","../src/validation/primitives/vector.ts","../src/validation/primitives/v.ts"],"sourcesContent":["import type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, validateArray } from \"./helpers\";\n\n// =============================================================================\n// Array Schema\n// =============================================================================\n\nexport interface ArraySchema<\n TItem extends VibSchema<any, any>,\n TInput = InferInput<TItem>[],\n TOutput = InferOutput<TItem>[],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"array\";\n readonly item: TItem;\n}\n\n/**\n * Create an array schema that validates each item.\n *\n * @example\n * const tags = v.array(v.string());\n * const scores = v.array(v.number());\n */\nexport function array<TItem extends VibSchema<any, any>>(\n item: TItem\n): ArraySchema<TItem> {\n // Cache the validate function directly\n const validate = item[\"~standard\"].validate;\n\n const schema = createSchema<InferInput<TItem>[], InferOutput<TItem>[]>(\n \"array\",\n (value) => validateArray(value, validate)\n ) as ArraySchema<TItem>;\n\n (schema as any).item = item;\n\n return schema;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isUint8Array } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Blob Schema (Uint8Array, including Node Buffer subclasses)\n// =============================================================================\n\nexport interface BaseBlobSchema<\n Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n > {}\n\nexport interface BlobSchema<TInput = Uint8Array, TOutput = Uint8Array>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"blob\";\n}\n\n// Pre-computed error for fast path\nconst BLOB_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected Uint8Array\" })]),\n});\n\n// %TypedArray%.prototype owns the metadata accessors. Start lookup there so a\n// genuine foreign view cannot redirect normalization through hostile own\n// properties.\nconst typedArrayPrototype: object = Object.getPrototypeOf(Uint8Array.prototype);\n\nfunction localBufferPrototype(): object | undefined {\n try {\n const bufferConstructor: unknown = Reflect.get(globalThis, \"Buffer\");\n if (typeof bufferConstructor !== \"function\") return;\n const prototype: unknown = Reflect.get(bufferConstructor, \"prototype\");\n if (\n prototype !== null &&\n typeof prototype === \"object\" &&\n Object.getPrototypeOf(prototype) === Uint8Array.prototype\n ) {\n return prototype;\n }\n } catch {\n return;\n }\n}\n\nconst trustedBufferPrototype = localBufferPrototype();\n\nfunction hasOwnViewMetadata(value: Uint8Array): boolean {\n return (\n Object.getOwnPropertyDescriptor(value, \"buffer\") !== undefined ||\n Object.getOwnPropertyDescriptor(value, \"byteOffset\") !== undefined ||\n Object.getOwnPropertyDescriptor(value, \"byteLength\") !== undefined\n );\n}\n\nfunction hasTrustedLocalPrototype(value: Uint8Array): boolean {\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === Uint8Array.prototype ||\n prototype === trustedBufferPrototype) &&\n !hasOwnViewMetadata(value)\n );\n}\n\n/**\n * Validate binary data without requiring a Node Buffer global. Node Buffers\n * inherit from Uint8Array and therefore pass this same runtime check.\n */\nexport function validateBlob(value: unknown) {\n try {\n if (!isUint8Array(value)) return BLOB_ERROR;\n\n // Read the internal view through %TypedArray%.prototype. This proves the\n // slots without `instanceof` or caller-visible metadata and bypasses\n // hostile own properties on a genuine local or foreign Uint8Array.\n const buffer: ArrayBufferLike = Reflect.get(\n typedArrayPrototype,\n \"buffer\",\n value\n );\n const byteOffset: number = Reflect.get(\n typedArrayPrototype,\n \"byteOffset\",\n value\n );\n const byteLength: number = Reflect.get(\n typedArrayPrototype,\n \"byteLength\",\n value\n );\n // Only the two exact local prototype paths may retain identity. An\n // intermediate/custom prototype can be a stateful Proxy that agrees with\n // one metadata read and lies to the driver later, so it is never treated as\n // proof. Construct after classification so a detached backing buffer is a\n // refusal rather than a successful detached value.\n const keepsIdentity = hasTrustedLocalPrototype(value);\n const normalized = new Uint8Array(buffer, byteOffset, byteLength);\n // Keep the established plain-local/Node-Buffer identity contract only on\n // the exact trusted path. Every other admitted view normalizes locally.\n if (keepsIdentity) {\n return ok(value);\n }\n return ok(normalized);\n } catch {\n return BLOB_ERROR;\n }\n}\n\n/**\n * Create a blob schema for binary data.\n *\n * @example\n * const avatar = v.blob();\n * const optionalBlob = v.blob({ optional: true });\n * const nullableBlob = v.blob({ nullable: true });\n */\nexport function blob<\n const Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n>(\n options?: Opts\n): BlobSchema<ComputeInput<Uint8Array, Opts>, ComputeOutput<Uint8Array, Opts>> {\n return buildSchema(\"blob\", validateBlob, options) as BlobSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n >;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isBoolean } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Boolean Schema\n// =============================================================================\n\nexport interface BaseBooleanSchema<\n Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n > {}\n\nexport interface BooleanSchema<TInput = boolean, TOutput = boolean>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"boolean\";\n}\n\n// Pre-computed error for fast path\nconst BOOLEAN_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected boolean\" })]),\n});\n\n/**\n * Validate that a value is a boolean.\n */\nfunction validateBoolean(value: unknown) {\n return isBoolean(value) ? ok(value) : BOOLEAN_ERROR;\n}\n\n/**\n * Create a boolean schema.\n *\n * @example\n * const active = v.boolean();\n * const optionalFlag = v.boolean({ optional: true });\n */\nexport function boolean(): BooleanSchema<boolean, boolean>;\nexport function boolean<const Opts extends ScalarOptions<boolean, any>>(\n options: Opts\n): BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>>;\nexport function boolean<\n const Opts extends ScalarOptions<boolean, any> | undefined,\n>(\n options?: Opts\n): BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>> {\n return buildSchema(\"boolean\", validateBoolean, options) as BooleanSchema<\n ComputeInput<boolean, Opts>,\n ComputeOutput<boolean, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateBoolean };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isDate } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Date Schema (JavaScript Date objects)\n// =============================================================================\n\nexport interface DateSchema<TInput = Date, TOutput = Date>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"date\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_DATE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected Date\" })]),\n});\nconst INVALID_DATE_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected valid Date\" })]),\n});\n\n/**\n * Validate that a value is a JavaScript Date object.\n */\nfunction validateDate(value: unknown) {\n if (!isDate(value)) return NOT_DATE_ERROR;\n const time = Date.prototype.getTime.call(value);\n if (Number.isNaN(time)) return INVALID_DATE_ERROR;\n if (value instanceof Date) return ok(value);\n // A Date from another realm names this exact instant but fails every local\n // `instanceof` downstream; a local Date at the same instant does not.\n return ok(new Date(time));\n}\n\n/**\n * Create a date schema for JavaScript Date objects.\n *\n * @example\n * const createdAt = v.date();\n * const optionalDate = v.date({ optional: true });\n */\nexport function date<\n const Opts extends ScalarOptions<Date, any> | undefined = undefined,\n>(\n options?: Opts\n): DateSchema<ComputeInput<Date, Opts>, ComputeOutput<Date, Opts>> {\n return buildSchema(\"date\", validateDate, options) as DateSchema<\n ComputeInput<Date, Opts>,\n ComputeOutput<Date, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateDate };\n","import { discardAsyncValidationResult } from \"../parse-failure\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationFailure,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { type DecimalDescriptor, toDecimal } from \"./decimal-codec\";\nimport {\n admitDecimal,\n canonicalDecimalText,\n DECIMAL_INPUT_REFUSAL,\n type Decimal,\n domainRefusal,\n} from \"./decimal-value\";\nimport { buildSchema, fail, ok, standardSchemaFailure } from \"./helpers\";\n\n// =============================================================================\n// Decimal Schema\n// =============================================================================\n\n/**\n * What a decimal accepts on the way IN: the public value type, or its lossless\n * spelling. A JavaScript number is a double and is refused.\n */\nexport type DecimalInput = Decimal | string;\n\n/**\n * What a VALIDATED decimal is inside the engine: the canonical private string.\n *\n * This is not a public result mode. It is the one logical representation SQL\n * binding, cursors, row keys, cache keys, race pins, and link folds all key on,\n * because two distinct `Decimal` instances naming the same number must be the\n * same identity. The public `Decimal` is constructed once per selected value at\n * the typed result boundary, never here.\n */\nexport type DecimalOutput = string;\n\n/**\n * Decimal schema options: the ordinary scalar options plus the field's declared\n * fixed-decimal domain. The domain is optional at this level because the\n * primitive is also the unconstrained value grammar the codec is built on; the\n * PUBLIC surface, `s.decimal({ precision, scale })`, always declares one.\n */\nexport interface DecimalOptions<TSchemaOut = Decimal>\n extends ScalarOptions<Decimal, DecimalOutput, TSchemaOut> {\n decimal?: DecimalDescriptor | undefined;\n}\n\n/**\n * A custom `.schema()` REFINES the Decimal the base already built; it does not\n * redefine what the field accepts or what the pipeline emits. So neither\n * computed side may take its types from the schema the way every other scalar's\n * does: input stays `Decimal | string`, output stays canonical text.\n */\ntype DecimalValueOptions<Opts> =\n Opts extends ScalarOptions<any, any, any>\n ? Omit<Opts, \"schema\"> & { schema?: undefined }\n : undefined;\n\ntype ReadonlyDecimalList<T> = T extends DecimalInput[]\n ? readonly DecimalInput[]\n : T;\n\nexport type DecimalComputeInput<Opts> = ReadonlyDecimalList<\n ComputeInput<DecimalInput, DecimalValueOptions<Opts>>\n>;\n\nexport type DecimalComputeOutput<Opts> = ComputeOutput<\n DecimalOutput,\n DecimalValueOptions<Opts>\n>;\n\nexport interface DecimalSchema<TInput = DecimalInput, TOutput = DecimalOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"decimal\";\n readonly acceptsUndefined: boolean;\n readonly options:\n | { readonly decimal?: DecimalDescriptor | undefined }\n | undefined;\n}\n\n/** The FIELD boundary's refusal, in the value module's own words. */\nconst DECIMAL_ERROR: ValidationFailure = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: DECIMAL_INPUT_REFUSAL })]),\n});\n\nconst DECIMAL_VALUE_ERROR =\n \"Expected a Decimal: a custom decimal schema may refine or brand the value it is given, but not return a string, a number, or a value of any other type\";\n\n/**\n * Validate a decimal and NORMALIZE it to its canonical string in one step, so\n * everything downstream — binding, SQL comparison, identity, storage — sees one\n * spelling.\n */\nfunction validateDecimal(value: unknown): ValidationResult<string> {\n const canonical = admitDecimal(value);\n return canonical === undefined ? DECIMAL_ERROR : ok(canonical);\n}\n\n/**\n * The decimal's own validator chain, built HERE rather than composed by\n * `buildValidator`'s option handling, because the ORDER is the contract:\n *\n * base (exact grammar, canonical text)\n * -> the custom schema, which observes a real `Decimal` (plan 2.3)\n * -> the DESCRIPTOR, last, on whatever that schema returned\n *\n * `buildValidator` runs a custom schema after the base and has no hook after\n * it, and validation Rule 4 forbids patching one on afterwards: every decimal\n * filter and update schema is a union, and a union captures each member's\n * `~standard.validate` at construction. So the whole value chain exists before\n * the schema object does, and `buildValidator` is handed only the\n * nullable/optional/array/default wrapping it uniquely owns.\n */\nfunction buildDecimalValueValidator(\n options: DecimalOptions<any> | undefined\n): (value: unknown) => ValidationResult<string> {\n const custom = options?.schema;\n const descriptor = options?.decimal;\n let validate = validateDecimal;\n\n if (custom !== undefined) {\n const refine = custom[\"~standard\"].validate;\n const base = validate;\n validate = (value) => {\n const parsed = base(value);\n if (parsed.issues) return parsed;\n const refined = refine(toDecimal(parsed.value));\n if (\"then\" in refined) {\n discardAsyncValidationResult(refined);\n return fail(\"Async schemas are not supported\");\n }\n if (refined.issues) {\n return standardSchemaFailure(refined.issues);\n }\n // The return position admits only a Decimal: a string, a number or a\n // decimal-shaped object the constructor never built is a different\n // value family, so the brand reader alone answers here.\n const canonical = canonicalDecimalText(refined.value);\n return canonical === undefined\n ? fail(DECIMAL_VALUE_ERROR)\n : ok(canonical);\n };\n }\n\n if (descriptor !== undefined) {\n const base = validate;\n validate = (value) => {\n const parsed = base(value);\n if (parsed.issues) return parsed;\n const refusal = domainRefusal(\n parsed.value,\n descriptor.precision,\n descriptor.scale\n );\n return refusal === undefined ? parsed : fail(refusal);\n };\n }\n\n return validate;\n}\n\n/**\n * Create a decimal schema: exact decimal in, canonical decimal string out.\n *\n * @example\n * const price = v.decimal({ decimal: { precision: 10, scale: 2 } });\n * const optionalPrice = v.decimal({ optional: true });\n */\nexport function decimal(): DecimalSchema<DecimalInput, DecimalOutput>;\nexport function decimal<const Opts extends DecimalOptions<any>>(\n options: Opts\n): DecimalSchema<DecimalComputeInput<Opts>, DecimalComputeOutput<Opts>>;\nexport function decimal(options?: DecimalOptions<any>): VibSchema<any, any> {\n // The custom schema is already composed into the value validator above, so it\n // is withheld from the wrapping options — `buildValidator` running it again\n // would re-refine a canonical STRING with a schema that expects a Decimal.\n // Everything the wrappers do own — nullable, optional, array, default —\n // passes through untouched.\n const wrapping =\n options === undefined ? undefined : { ...options, schema: undefined };\n return buildSchema(\"decimal\", buildDecimalValueValidator(options), wrapping);\n}\n\nexport { validateDecimal };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isString } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Enum Schema\n// =============================================================================\nexport type EnumValues<S extends VibSchema> =\n S extends EnumSchema<infer TValues, any, any> ? TValues : never;\nexport type BaseEnumSchema<\n TValues extends readonly string[],\n Opts extends ScalarOptions<TValues[number], any> | undefined = undefined,\n> = EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n>;\n\nexport interface EnumSchema<\n TValues extends readonly string[],\n TInput = TValues[number],\n TOutput = TValues[number],\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"enum\";\n readonly values: TValues;\n}\n\n/**\n * Create an enum schema that validates a value is one of the allowed strings.\n *\n * The values may be a readonly tuple (`[\"a\", \"b\"] as const`). The mutable arm\n * of the constraint keeps an inline literal inferred as a mutable tuple, so\n * the types of existing schemas do not change.\n *\n * @example\n * const status = v.enum_([\"active\", \"inactive\", \"pending\"]);\n */\n// @__NO_SIDE_EFFECTS__\nexport function enum_<\n const TValues extends string[] | readonly string[],\n const Opts extends\n | ScalarOptions<TValues[number], any>\n | undefined = undefined,\n>(\n values: TValues,\n options?: Opts\n): EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n> {\n // Create a Set for O(1) lookup\n const valueSet = new Set<TValues[number]>(values);\n\n // Create base validator\n const baseValidate = (value: unknown) => {\n if (isString(value) && valueSet.has(value)) {\n return ok(value as TValues[number]);\n }\n return {\n issues: [\n {\n message: `Expected one of: ${values.join(\" | \")}`,\n },\n ],\n };\n };\n\n const schema = buildSchema(\"enum\", baseValidate, options, {\n values,\n }) as EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n >;\n\n return schema;\n}\n","import { ValidationError } from \"@errors\";\nimport type { Cast, ThunkCast, VibSchema } from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Path Utilities for Nested Object Access\n// =============================================================================\n\n/**\n * Gets the value at a dot path in an object type.\n * Supports nested paths like \"create.name\" or \"create.friends\".\n */\ntype PathValue<T, P extends string> = P extends `${infer Key}.${infer Rest}`\n ? Key extends keyof T\n ? T[Key] extends Record<string, any>\n ? PathValue<T[Key], Rest>\n : never\n : never\n : P extends keyof T\n ? T[P]\n : never;\n\n/**\n * Recursively extracts all dot paths that lead to VibSchema or ThunkCast instances.\n * Returns a union of all valid paths (e.g., \"create\" | \"create.name\").\n * Limited to 5 levels of nesting to avoid infinite recursion.\n */\ntype PathsToSchemas<\n T extends string,\n Prefix extends string = \"\",\n Depth extends readonly unknown[] = [],\n> = Depth[\"length\"] extends 5\n ? never\n : // Check if T is a VibSchema\n T extends VibSchema<any, any>\n ? Prefix\n : // Check if T is a ThunkCast (function returning Cast)\n T extends ThunkCast<any, any>\n ? Prefix\n : T extends () => Cast<any, any>\n ? Prefix\n : // Otherwise recurse into object properties\n T extends Record<string, any>\n ? {\n [K in keyof T]: K extends string\n ? PathsToSchemas<\n T[K],\n Prefix extends \"\" ? K : `${Prefix}.${K}`,\n [...Depth, unknown]\n >\n : never;\n }[keyof T]\n : never;\n\n/**\n * Normalize a schema entry to VibSchema.\n * Handles both direct VibSchema and ThunkCast (unwrapping the thunk's return type).\n */\ntype NormalizeSchemaEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\n/**\n * Gets the schema type at a specific path for a specific key.\n * Handles both VibSchema and ThunkCast entries.\n */\ntype SchemaAtPath<\n TObject extends Record<string, any>,\n TPath extends string,\n K extends keyof TObject,\n> = NormalizeSchemaEntry<PathValue<TObject[K], TPath>>;\n\n/**\n * Extracts all valid paths that lead to schemas from all keys in the object.\n */\nexport type AllPathsToSchemas<TObject extends Record<string, any>> = {\n [K in keyof TObject]: K extends string ? PathsToSchemas<TObject[K]> : never;\n}[keyof TObject];\n\n// =============================================================================\n// FromObject Schema Types\n// =============================================================================\n\n/**\n * Options for fromObject schemas (same as ObjectOptions).\n */\nexport type FromObjectOptions<T = unknown> = ObjectOptions<T>;\n\n/**\n * Compute the entries type from an object and path.\n */\ntype ComputeEntries<\n TObject extends Record<string, any>,\n TPath extends string,\n> = {\n [K in keyof TObject]: SchemaAtPath<TObject, TPath, K>;\n};\n\n// =============================================================================\n// FromObject Schema Implementation\n// =============================================================================\n\n/**\n * Runtime helper to get a nested value by dot path.\n */\nfunction getNestedValue(obj: any, path: string): any {\n const parts = path.split(\".\");\n let current = obj;\n for (const part of parts) {\n if (current === null || current === undefined) {\n return undefined;\n }\n current = current[part];\n }\n return current;\n}\n\n/**\n * Whether `path` names a property of `value`, including one that holds\n * `undefined` — a member that DECLARES it has no schema there (an insert-only\n * scalar's `update`) is not a path typo, and contributes no entry.\n */\nfunction declaresPath(value: unknown, path: string): boolean {\n const cut = path.lastIndexOf(\".\");\n const parent = cut === -1 ? value : getNestedValue(value, path.slice(0, cut));\n return isRecord(parent) && path.slice(cut + 1) in parent;\n}\n\n/**\n * Project entries without constructing an object validator that a composer\n * would immediately discard. The public builder uses this same path boundary.\n */\nexport function entriesFromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n>(sourceObject: TObject, path: TPath): ComputeEntries<TObject, TPath> {\n const result: Record<string, VibSchema<any, any>> = {};\n for (const key of Object.keys(sourceObject)) {\n const value = getNestedValue(sourceObject[key], path);\n if (value !== undefined) {\n result[key] = value;\n }\n }\n if (Object.keys(sourceObject).length > 0 && Object.keys(result).length === 0)\n refuseUnmatchedPath(sourceObject, path);\n // The runtime path projection is the boundary that establishes this mapping.\n return result as ComputeEntries<TObject, TPath>;\n}\n\n/**\n * Creates an object schema by extracting schemas from a record using a dot path.\n * This is a convenient way to build an object schema from a record with proper type inference.\n *\n * @param sourceObject - Source object containing nested schemas\n * @param path - Dot path to extract schemas (e.g., \"create\", \"filter.where\")\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // Given a record of models with nested schemas:\n * const models = {\n * user: { create: v.string(), update: v.string() },\n * post: { create: v.number(), update: v.number() },\n * };\n *\n * // Extract all \"create\" schemas into a single object schema:\n * const createSchema = fromObject(models, \"create\");\n * // Validates: { user: string, post: number }\n *\n * // With options:\n * const optionalSchema = fromObject(models, \"create\", { optional: true });\n * // Validates: { user: string, post: number } | undefined\n *\n * @example\n * // Nested paths work too:\n * const nestedModels = {\n * user: { schemas: { create: v.string() } },\n * post: { schemas: { create: v.number() } },\n * };\n * const nestedSchema = fromObject(nestedModels, \"schemas.create\");\n * // Validates: { user: string, post: number }\n */\nexport function fromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n // TPath extends AllPathsToSchemas<TObject>,\n const TOpts extends FromObjectOptions | undefined = undefined,\n>(\n sourceObject: TObject,\n path: TPath,\n options?: TOpts\n): ObjectSchema<ComputeEntries<TObject, TPath>, TOpts> {\n return object(entriesFromObject(sourceObject, path), options);\n}\n\nexport type { ComputeEntries as ComputeEntriesFromObject };\n\n/** An empty projection, refused unless some source declares the path empty. */\nfunction refuseUnmatchedPath(\n sourceObject: Record<string, unknown>,\n path: string\n): void {\n if (Object.values(sourceObject).some((value) => declaresPath(value, path)))\n return;\n throw new ValidationError(\n { kind: \"schema-builder\", builder: \"fromObject\", path },\n [\n {\n path,\n message: `fromObject path \"${path}\" did not match any entries in the source object`,\n },\n ]\n );\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isDate, isString } from \"../value-guards\";\nimport {\n isDateTimeClock,\n isDateTimeInstant,\n isGregorianCalendarDate,\n} from \"./datetime-values\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// ISO Format Validators\n// =============================================================================\n\n// ISO timestamp regex: 2023-12-15T10:30:00.000Z\nconst ISO_TIMESTAMP_REGEX =\n /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(?:\\.\\d{1,3})?(?:Z|[+-](\\d{2}):(\\d{2}))$/;\n\n// ISO date regex: 2023-12-15\nconst ISO_DATE_REGEX = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\n// ISO time regex: 10:30:00 or 10:30:00.000\nconst ISO_TIME_REGEX = /^\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?$/;\n\n// Pre-computed errors\nconst NOT_STRING_OR_DATE_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected string or Date\" }),\n ]),\n});\n\n// =============================================================================\n// ISO Timestamp Schema\n// =============================================================================\n\nexport interface BaseIsoTimestampSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimestampSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_timestamp\";\n}\n\n// Pre-computed errors\nconst INVALID_TIMESTAMP_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO timestamp format (YYYY-MM-DDTHH:mm:ss.sssZ)\",\n }),\n ]),\n});\nconst INVALID_TIMESTAMP_DATE = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Invalid date in ISO timestamp\" }),\n ]),\n});\n\n/**\n * Validate ISO timestamp format.\n * Accepts Date objects and converts them to ISO strings.\n */\nfunction validateIsoTimestamp(value: unknown) {\n // Handle Date objects - convert to ISO string\n if (isDate(value)) {\n const epochMilliseconds = Date.prototype.getTime.call(value);\n if (!isDateTimeInstant(epochMilliseconds)) {\n return INVALID_TIMESTAMP_DATE;\n }\n return ok(Date.prototype.toISOString.call(value));\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n const match = ISO_TIMESTAMP_REGEX.exec(value);\n if (!match) return INVALID_TIMESTAMP_FORMAT;\n const hasValidCalendarAndClock =\n isGregorianCalendarDate(\n Number(match[1]),\n Number(match[2]),\n Number(match[3])\n ) && isDateTimeClock(Number(match[4]), Number(match[5]), Number(match[6]));\n if (\n !hasValidCalendarAndClock ||\n Number(match[7] ?? 0) > 23 ||\n Number(match[8] ?? 0) > 59 ||\n !isDateTimeInstant(Date.parse(value))\n ) {\n return INVALID_TIMESTAMP_DATE;\n }\n return ok(new Date(value).toISOString());\n}\n\n/**\n * Create an ISO timestamp schema.\n * Accepts strings in format: 2023-12-15T10:30:00.000Z or Date objects.\n * Date objects are automatically converted to ISO strings.\n *\n * @example\n * const timestamp = v.isoTimestamp();\n * parse(timestamp, new Date()) // Returns ISO string\n */\nexport function isoTimestamp<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\n \"iso_timestamp\",\n validateIsoTimestamp,\n options\n ) as IsoTimestampSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Date Schema\n// =============================================================================\n\nexport interface BaseIsoDateSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoDateSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_date\";\n}\n\n// Pre-computed errors\nconst INVALID_DATE_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO date format (YYYY-MM-DD)\",\n }),\n ]),\n});\nconst INVALID_DATE = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid date\" })]),\n});\n\n/**\n * Validate ISO date format.\n * Accepts Date objects and converts them to ISO date strings (YYYY-MM-DD).\n */\nfunction validateIsoDate(value: unknown) {\n // Handle Date objects - convert to ISO date string\n if (isDate(value)) {\n if (!isDateTimeInstant(Date.prototype.getTime.call(value))) {\n return INVALID_DATE;\n }\n return ok(Date.prototype.toISOString.call(value).slice(0, 10));\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n const match = ISO_DATE_REGEX.exec(value);\n if (!match) return INVALID_DATE_FORMAT;\n if (\n !isGregorianCalendarDate(\n Number(match[1]),\n Number(match[2]),\n Number(match[3])\n )\n ) {\n return INVALID_DATE;\n }\n return ok(value);\n}\n\n/**\n * Create an ISO date schema.\n * Accepts strings in format: 2023-12-15 or Date objects.\n * Date objects are automatically converted to ISO date strings (YYYY-MM-DD).\n *\n * @example\n * const birthDate = v.isoDate();\n * parse(birthDate, new Date()) // Returns \"2023-12-15\"\n */\nexport function isoDate<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_date\", validateIsoDate, options) as IsoDateSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// =============================================================================\n// ISO Time Schema\n// =============================================================================\n\nexport interface BaseIsoTimeSchema<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n > {}\n\nexport interface IsoTimeSchema<TInput = string | Date, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"iso_time\";\n}\n\n// Pre-computed errors\nconst INVALID_TIME_FORMAT = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: \"Expected ISO time format (HH:mm:ss)\",\n }),\n ]),\n});\nconst INVALID_TIME = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Invalid time\" })]),\n});\n\n/**\n * Validate ISO time format.\n * Accepts Date objects and extracts the time portion (HH:mm:ss.sss).\n */\nfunction validateIsoTime(value: unknown) {\n // Handle Date objects - extract time portion\n if (isDate(value)) {\n if (Number.isNaN(Date.prototype.getTime.call(value))) return INVALID_TIME;\n // Extract HH:mm:ss.sss from ISO string\n const isoString = Date.prototype.toISOString.call(value);\n const timePart = isoString.split(\"T\")[1]!.replace(\"Z\", \"\");\n return ok(timePart);\n }\n\n if (!isString(value)) return NOT_STRING_OR_DATE_ERROR;\n if (!ISO_TIME_REGEX.test(value)) return INVALID_TIME_FORMAT;\n\n const parts = value.split(\":\");\n const hours = Number(parts[0]);\n const minutes = Number(parts[1]);\n const seconds = Math.trunc(Number(parts[2]));\n\n if (\n hours < 0 ||\n hours > 23 ||\n minutes < 0 ||\n minutes > 59 ||\n seconds < 0 ||\n seconds > 59\n ) {\n return INVALID_TIME;\n }\n return ok(value.padEnd(12, value.includes(\".\") ? \"0\" : \".000\"));\n}\n\n/**\n * Create an ISO time schema.\n * Accepts strings in format: 10:30:00 or Date objects.\n * Date objects are automatically converted to time strings (HH:mm:ss.sss).\n *\n * @example\n * const startTime = v.isoTime();\n * parse(startTime, new Date()) // Returns \"10:30:00.000\"\n */\nexport function isoTime<\n const Opts extends ScalarOptions<string, any> | undefined = undefined,\n>(\n options?: Opts\n): IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n> {\n return buildSchema(\"iso_time\", validateIsoTime, options) as IsoTimeSchema<\n ComputeInput<string | Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export validators for reuse\nexport { validateIsoTimestamp, validateIsoDate, validateIsoTime };\n","import { isFieldRef } from \"@schema/field-ref\";\nimport type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isBoolean, isNumber, isRecord, isString } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// JSON Schema\n// =============================================================================\n\n/**\n * JSON-compatible value type.\n * Represents any value that can be safely serialized to JSON.\n */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/** JSON serialization omits undefined object members and nulls array holes. */\nexport type JsonInput =\n | string\n | number\n | boolean\n | null\n | readonly (JsonInput | undefined)[]\n | { [key: string]: JsonInput | undefined };\n\n/**\n * A JSON value in WRITE position: everything `JsonValue` allows EXCEPT a bare\n * top-level `null`.\n *\n * Once `DbNull` and `JsonNull` exist, a top-level `null` no longer says which\n * of the two nulls it means, so it is not a legal write value — the same line\n * Prisma draws with its own `InputJsonValue`. Nested nulls are untouched:\n * `{ a: null }` is an ordinary document.\n */\nexport type InputJsonValue = Exclude<JsonInput, null>;\n\nexport interface BaseJsonSchema<\n Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<JsonInput, Opts>,\n ComputeOutput<JsonValue, Opts>\n > {}\n\nexport interface JsonSchema<TInput = JsonInput, TOutput = JsonValue>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"json\";\n}\n\n// Pre-computed errors for fast path\nconst NOT_JSON_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected JSON-compatible value\" }),\n ]),\n});\n\n/**\n * Check if a value is JSON-compatible (can be serialized without loss).\n * Rejects: undefined, functions, symbols, bigint, circular references.\n */\nconst INVALID_JSON = Symbol(\"invalid JSON\");\n\nfunction normalizeJson(\n value: unknown,\n seen = new WeakMap<object, JsonValue | typeof INVALID_JSON>()\n): JsonValue | typeof INVALID_JSON {\n if (value === null || isString(value) || isBoolean(value)) return value;\n if (isNumber(value)) return Number.isFinite(value) ? value : INVALID_JSON;\n if (!(isRecord(value) || Array.isArray(value))) return INVALID_JSON;\n if (isFieldRef(value)) return INVALID_JSON;\n const previous = seen.get(value);\n if (previous !== undefined) return previous;\n seen.set(value, INVALID_JSON); // A back-edge is a cycle; completed aliases are reusable.\n if (Array.isArray(value)) {\n const result: JsonValue[] = [];\n for (const original of value) {\n const member =\n original === undefined ? null : normalizeJson(original, seen);\n if (member === INVALID_JSON) return INVALID_JSON;\n result.push(member);\n }\n seen.set(value, result);\n return result;\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== null && prototype !== Object.prototype) return INVALID_JSON;\n const result: Record<string, JsonValue> = {};\n for (const key of Object.keys(value)) {\n const original = value[key];\n if (original === undefined) {\n continue;\n }\n const member = normalizeJson(original, seen);\n if (member === INVALID_JSON) return INVALID_JSON;\n Object.defineProperty(result, key, {\n value: member,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n }\n seen.set(value, result);\n return result;\n}\n\n/**\n * Validate that a value is JSON-compatible.\n */\nfunction validateJson(value: unknown): ValidationResult<JsonValue> {\n const normalized = normalizeJson(value);\n return normalized === INVALID_JSON ? NOT_JSON_ERROR : ok(normalized);\n}\n\n/**\n * Create a JSON schema that validates any JSON-compatible value.\n * Accepts: strings, numbers (finite), booleans, null, arrays, plain objects.\n * Rejects: undefined, functions, symbols, bigint, circular references, class instances.\n *\n * @example\n * const data = v.json();\n * const optionalData = v.json({ optional: true });\n * const nullableData = v.json({ nullable: true });\n */\n// @__NO_SIDE_EFFECTS__\nexport function json<\n const Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n>(\n options?: Opts\n): JsonSchema<ComputeInput<JsonInput, Opts>, ComputeOutput<JsonValue, Opts>> {\n return buildSchema<JsonInput, Opts | undefined>(\n \"json\",\n validateJson,\n options\n ) as JsonSchema<\n ComputeInput<JsonInput, Opts>,\n ComputeOutput<JsonValue, Opts>\n >;\n}\n\n// Export for reuse\nexport { validateJson };\n","// JSON null sentinel operand schemas\n// Admits `DbNull` / `JsonNull` / `AnyNull` into the exact JSON slots that can\n// mean something by them, and refuses them everywhere else BY NAME.\n\nimport {\n type AnyJsonNullSentinel,\n isJsonNullSentinel,\n JsonNull,\n type JsonNullKind,\n type JsonNullSentinel,\n} from \"@schema/json-null\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n/**\n * Why this is a brand-discriminated wrapper and not `v.union([...])`: a union\n * rewrites every existing operand failure into \"Value did not match any union\n * member: …\". Here the brand is the discriminator, so a non-sentinel value is\n * handed straight to the wrapped schema and keeps its exact message, and a\n * sentinel gets a sentinel-specific one. Same reasoning as\n * {@link file://./field-ref.ts}.\n */\nexport interface JsonNullOrSchema<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n InferInput<TSchema> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n > {\n readonly type: \"json_null_or\";\n /** The sentinel kinds this slot accepts. */\n readonly allowed: readonly JsonNullKind[];\n /** The operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\n/**\n * A JSON WRITE slot: the sentinels it accepts, the whole JSON document\n * language, and — deliberately — NOT a bare `null`.\n *\n * `null` is excluded from the INPUT type as well as refused at runtime, which\n * is Prisma's rule: its `InputJsonValue` documents that `null` is disallowed at\n * the top level of a JSON write because its meaning would be ambiguous, and\n * directs callers to `Prisma.JsonNull` / `Prisma.DbNull`\n * (`@prisma/client`, `runtime/client.d.ts`, the `InputJsonValue` doc comment;\n * https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/working-with-json-fields#using-null-values).\n * `null` is only excluded at the TOP level — `{ a: null }` is an ordinary\n * document and stays legal, exactly as in Prisma.\n */\nexport interface JsonWriteSchema<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n Exclude<InferInput<TSchema>, null> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n > {\n readonly type: \"json_write\";\n readonly allowed: readonly JsonNullKind[];\n readonly wrapped: TSchema;\n readonly acceptsUndefined: boolean;\n}\n\nconst ALL_KINDS: readonly JsonNullKind[] = [\"DbNull\", \"JsonNull\", \"AnyNull\"];\n\n/** `DbNull, JsonNull or AnyNull` — for the refusal messages. */\nfunction listKinds(kinds: readonly JsonNullKind[]): string {\n if (kinds.length === 1) return kinds[0] as string;\n return `${kinds.slice(0, -1).join(\", \")} or ${kinds.at(-1)}`;\n}\n\n/**\n * The refusal a disallowed sentinel gets. It names the token the caller used\n * and the ones this slot would have accepted, because the whole point of the\n * sentinels is that \"null\" alone never says enough.\n */\nfunction refuseSentinel(\n sentinel: AnyJsonNullSentinel,\n allowed: readonly JsonNullKind[],\n where: string\n) {\n const rejected = ALL_KINDS.filter((kind) => !allowed.includes(kind));\n const reason =\n rejected.length === ALL_KINDS.length\n ? `JSON null sentinels are not supported in ${where}`\n : `${sentinel.kind} is not supported in ${where}; that slot accepts ${listKinds(allowed)}`;\n return fail(`${reason}.`);\n}\n\nfunction checkSentinel(\n value: AnyJsonNullSentinel,\n allowed: readonly JsonNullKind[],\n where: string\n) {\n return allowed.includes(value.kind)\n ? ok(value)\n : refuseSentinel(value, allowed, where);\n}\n\nfunction copyOptionality(\n schema: object,\n wrapped: VibSchema<any, any>,\n allowed: readonly JsonNullKind[]\n): void {\n (schema as { allowed: readonly JsonNullKind[] }).allowed = allowed;\n (schema as { wrapped: VibSchema<any, any> }).wrapped = wrapped;\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n}\n\n/**\n * A JSON FILTER operand that also accepts the sentinels in `allowed`.\n *\n * A bare `null` is NOT intercepted here: it keeps whatever the wrapped operand\n * already meant (at the document root, \"the column IS NULL\"; under a `path`,\n * \"the value at that path is the JSON null\"). That behavior predates the\n * sentinels and stays pinned — see the regression witnesses in\n * `tests/drivers/json-null-sentinel-behavior.ts`.\n */\nexport function jsonNullOr<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n>(\n allowed: readonly TAllowed[],\n wrapped: TSchema,\n where: string\n): JsonNullOrSchema<TAllowed, TSchema> {\n const schema = createSchema<\n InferInput<TSchema> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n >(\"json_null_or\", (value) => {\n if (isJsonNullSentinel(value)) {\n return checkSentinel(value, allowed, where) as never;\n }\n return validateSchema(wrapped, value) as never;\n }) as JsonNullOrSchema<TAllowed, TSchema>;\n\n copyOptionality(schema, wrapped, allowed);\n return schema;\n}\n\n/**\n * A JSON WRITE slot: sentinels in `allowed`, any JSON document, no bare `null`.\n *\n * The bare-`null` refusal is the reason this is not just `jsonNullOr`. See\n * {@link JsonWriteSchema} for the rule and its citation.\n *\n * An OMITTED key is untouched: `undefined` falls through to the wrapped schema,\n * which applies the field's own default — for a nullable JSON field that\n * default is the database NULL, which is exactly what `DbNull` names. Only a\n * `null` the CALLER spelled is ambiguous, and only that one is refused.\n */\nexport function jsonWrite<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n>(\n allowed: readonly TAllowed[],\n wrapped: TSchema,\n where: string,\n nullRefusal: string\n): JsonWriteSchema<TAllowed, TSchema> {\n const schema = createSchema<\n Exclude<InferInput<TSchema>, null> | JsonNullSentinel<TAllowed>,\n InferOutput<TSchema> | JsonNullSentinel<TAllowed>\n >(\"json_write\", (value) => {\n if (isJsonNullSentinel(value)) {\n return checkSentinel(value, allowed, where) as never;\n }\n if (value === null) return fail(nullRefusal) as never;\n const result = validateSchema(wrapped, value);\n // A supplied document transformed to null is JSON null; omitted nullable\n // defaults keep their separate SQL NULL path.\n return (\n !result.issues && result.value === null && value !== undefined\n ? checkSentinel(JsonNull, allowed, where)\n : result\n ) as never;\n }) as JsonWriteSchema<TAllowed, TSchema>;\n\n copyOptionality(schema, wrapped, allowed);\n return schema;\n}\n","import type { VibSchema } from \"../types\";\nimport { isFunction } from \"../value-guards\";\n\n/**\n * Creates a lazy schema that defers evaluation until first access.\n * The schema is cached after first resolution.\n *\n * Uses a Proxy to transparently forward all property access, method calls,\n * and operations to the wrapped schema. This ensures the lazy schema\n * behaves identically to the wrapped type.\n *\n * The returned schema is typed as T, so it's transparent to consumers -\n * InferInput and InferOutput work as if it were the wrapped schema.\n *\n * @param factory - A function that returns the schema to wrap\n * @returns A schema typed as T that lazily resolves on first access\n */\nexport function lazy<T extends VibSchema>(factory: () => T): T {\n let build: (() => T) | undefined = factory;\n let value: T;\n\n const resolve = (): T => {\n if (build) {\n value = build();\n build = undefined;\n }\n return value;\n };\n\n // Use a Proxy to transparently forward all operations to the resolved schema\n const proxy = new Proxy({} as T, {\n get(_target, prop, receiver) {\n const resolved = resolve();\n const value = Reflect.get(resolved, prop, receiver);\n // Bind methods to the resolved schema to preserve `this` context\n return isFunction(value) ? value.bind(resolved) : value;\n },\n\n has(_target, prop) {\n return Reflect.has(resolve(), prop);\n },\n\n ownKeys(_target) {\n return Reflect.ownKeys(resolve());\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n return Reflect.getOwnPropertyDescriptor(resolve(), prop);\n },\n\n getPrototypeOf(_target) {\n return Reflect.getPrototypeOf(resolve());\n },\n });\n\n return proxy;\n}\n\n/**\n * Lightweight deferred schema reference.\n *\n * Unlike `lazy()` (a Proxy that resolves on ANY property access — including\n * the object validator's duck-typing reads), `lazyRef` exposes a static\n * `type` and a `~standard.validate` that only builds the wrapped schema when\n * the validator is first CALLED. Used for args→core schema cross-references\n * so an operation only constructs the core schemas its arguments actually\n * use (e.g. `findUnique({ where })` never builds select/include).\n *\n * NOT a general-purpose wrapper: it reports no `acceptsUndefined`/default\n * metadata, so it must only wrap schemas with no default value (true for all\n * core schema references).\n */\nexport function lazyRef<T extends VibSchema>(factory: () => T): T {\n let build: (() => T) | undefined = factory;\n let value: T;\n const resolve = (): T => {\n if (build) {\n value = build();\n build = undefined;\n }\n return value;\n };\n\n return {\n type: \"lazyRef\",\n /**\n * JSON-schema conversion unwraps through this (resolves on demand) — see\n * the `lazyRef` case in {@link file://../json-schema/converters.ts}. A\n * reference that points BACK at a schema still being converted (a scalar\n * filter's `not`) is closed there with a `$ref`, so unwrapping terminates.\n */\n get wrapped() {\n return resolve();\n },\n // Introspection surface (resolves on demand). Deliberately NOT exposed:\n // `options`/`acceptsUndefined`/`default` — the object validator\n // duck-types those during resolve(), and resolving getters there would\n // rebuild the wrapped schema eagerly, defeating the laziness.\n get entries() {\n return (resolve() as { entries?: unknown }).entries;\n },\n \"~standard\": {\n version: 1,\n vendor: \"viborm\",\n validate: (value: unknown) => resolve()[\"~standard\"].validate(value),\n get jsonSchema() {\n return resolve()[\"~standard\"].jsonSchema;\n },\n },\n } as unknown as T;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Literal Schema\n// =============================================================================\n\nexport type LiteralValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | bigint;\n\nexport interface LiteralSchema<T extends LiteralValue, TInput = T, TOutput = T>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"literal\";\n readonly value: T;\n}\n\n/**\n * Create a literal schema that matches an exact value.\n *\n * @example\n * const admin = v.literal(\"admin\");\n * const zero = v.literal(0);\n * const isTrue = v.literal(true);\n */\nexport function literal<\n const T extends LiteralValue,\n const Opts extends ScalarOptions<T, any> | undefined = undefined,\n>(\n expected: T,\n options?: Opts\n): LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>> {\n // Pre-compute error for fast path\n const expectedStr = expected === null ? \"null\" : String(expected);\n const errorResult = Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected literal: ${expectedStr}`,\n }),\n ]),\n });\n\n // Create base validator\n const baseValidate = (value: unknown) =>\n value === expected ? ok(value as T) : errorResult;\n\n return buildSchema(\"literal\", baseValidate, options, {\n value: expected,\n }) as LiteralSchema<T, ComputeInput<T, Opts>, ComputeOutput<T, Opts>>;\n}\n","import type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { createSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// Nullable Schema\n// =============================================================================\n\nexport interface NullableSchema<\n TWrapped extends VibSchema<any, any>,\n TInput = InferInput<TWrapped> | null,\n TOutput = InferOutput<TWrapped> | null,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"nullable\";\n readonly wrapped: TWrapped;\n}\n\n/**\n * Create a nullable schema that allows null values.\n *\n * @example\n * const nullableName = v.nullable(v.string());\n */\nexport function nullable<TWrapped extends VibSchema<any, any>>(\n wrapped: TWrapped\n): NullableSchema<TWrapped> {\n // Cache validate function directly\n const validate = wrapped[\"~standard\"].validate;\n\n const schema = createSchema(\n \"nullable\",\n (value): ValidationResult<InferOutput<TWrapped> | null> => {\n // Handle null - fast path\n if (value === null) {\n return ok(null);\n }\n\n // Delegate to wrapped schema (cast to our result type)\n return validate(value) as ValidationResult<InferOutput<TWrapped>>;\n }\n ) as NullableSchema<TWrapped>;\n\n // Add reference\n (schema as any).wrapped = wrapped;\n\n return schema;\n}\n\n/**\n * Conditionally wrap a schema in nullable based on a boolean flag.\n * Useful for building schemas dynamically where nullability is determined at compile time.\n *\n * @example\n * const schema = v.maybeNullable(v.string(), true); // NullableSchema<StringSchema>\n * const schema2 = v.maybeNullable(v.string(), false); // StringSchema\n */\nexport function maybeNullable<\n TWrapped extends VibSchema<any, any>,\n TIsNullable extends boolean,\n>(\n wrapped: TWrapped,\n isNullable: TIsNullable\n): TIsNullable extends true ? NullableSchema<TWrapped> : TWrapped {\n if (isNullable) {\n return nullable(wrapped) as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n }\n return wrapped as TIsNullable extends true\n ? NullableSchema<TWrapped>\n : TWrapped;\n}\n","import { type ObjectSchema, object } from \"./object\";\nimport type { V } from \"./v\";\n\n/**\n * Create a new object schema with specific keys omitted.\n *\n * @param schema - The source object schema\n * @param keys - Array of keys to omit from the schema\n * @returns A new object schema without the specified keys\n *\n * @example\n * const user = v.object({\n * id: v.string(),\n * name: v.string(),\n * password: v.string(),\n * });\n *\n * const publicUser = v.omit(user, ['password']);\n * // { id?: string; name?: string }\n */\nexport function omit<\n TSchema extends ObjectSchema<any, any>,\n const TKeys extends readonly (keyof TSchema[\"entries\"])[] | undefined,\n>(schema: TSchema, keys: TKeys): V.Omit<TSchema, TKeys> {\n return object(schema.entries, {\n ...(schema.options || {}),\n omit: keys,\n }) as V.Omit<TSchema, TKeys>;\n}\n","import type { VibSchema } from \"../types\";\nimport { fail } from \"./helpers\";\n\n// Filter parsing is synchronous. Bound semantic filter containers before\n// descending, including scalar `not`, without restricting JSON data depth.\nlet activeDepth = 0;\nconst MAX_FILTER_DEPTH = 16;\n\nexport function limitFilterDepth<S extends VibSchema>(schema: S): S {\n const validate = schema[\"~standard\"].validate;\n Object.defineProperty(schema[\"~standard\"], \"validate\", {\n value: (value: unknown) => {\n if (activeDepth >= MAX_FILTER_DEPTH)\n return fail(`Filter nesting exceeds ${MAX_FILTER_DEPTH} levels`);\n activeDepth++;\n try {\n return validate(value);\n } finally {\n activeDepth--;\n }\n },\n });\n return schema;\n}\n","// Comparison Operand Schemas\n//\n// A comparison operand is the right-hand side of a scalar filter: the thing a\n// column is compared AGAINST. Four kinds live here, and this file is the only\n// place that decides which of them a given position accepts:\n//\n// 1. a plain value `{ views: { gt: 10 } }`\n// 2. a field reference `{ views: { gt: <FieldRef> } }` -> another column\n// 3. an SQL fragment `{ views: { gt: sql`…` } }` -> escape hatch\n// 4. a callback `{ views: { gt: (ctx) => … } }` -> sugar for 2 and 3\n//\n// The callback is RESOLVED HERE, during validation: it is invoked once and its\n// return value substituted, so the query engine's operand invariant stays\n// exactly \"plain value | FieldRef | Sql\" and no function ever reaches it. That\n// is what keeps validation the single home for payload normalization — the\n// engine does not learn a fourth operand kind, and neither does the cache key.\n\nimport {\n type AnyFieldRef,\n createModelFieldRefs,\n type FieldRef,\n fieldRefPayload,\n isFieldRef,\n type ModelFieldRefs,\n} from \"@schema/field-ref\";\nimport type { AnyModel } from \"@schema/model\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport { isSql, type Sql, sql } from \"@sql\";\nimport { discardAsyncValidationResult } from \"../parse-failure\";\nimport type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { isFunction, isRecord } from \"../value-guards\";\nimport { limitFilterDepth } from \"./filter-depth\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n// =============================================================================\n// THE CALLBACK CONTEXT\n// =============================================================================\n\n/**\n * What a comparison-operand callback is handed.\n *\n * `fields` is the CURRENT model's reference table — the model whose filter the\n * operand sits in, which for a nested relation filter is the relation's TARGET,\n * not the root. Correlated references to an enclosing scope are deliberately\n * absent: a field reference compares two columns of the SAME row, and widening\n * that is a separate decision.\n *\n * `sql` is the ordinary tagged template; interpolations inside a fragment ride\n * along as bound parameters (see {@link file://../../sql/sql.ts}).\n *\n * PURITY IS THE CONTRACT for the callback handed this context. Validation may\n * run a payload's callbacks more than once — `upsert` re-parses its taken arm\n * (the C2 residue), so a callback under `upsert.update` can be invoked twice\n * for one call. A callback that counts its calls, mutates outer state, or\n * returns a different fragment each time gets exactly what it asks for; a pure\n * one is indistinguishable from a literal token, which is the whole point of\n * the sugar.\n */\nexport interface OperandCtx<TModel> {\n readonly fields: ModelFieldRefs<string, TModel>;\n readonly sql: typeof sql;\n}\n\n/** An operand context for an unknown model — the type-level default. */\nexport type AnyOperandCtx = OperandCtx<any>;\n\n// =============================================================================\n// THE PER-MODEL SCOPE\n// =============================================================================\n\n/**\n * The model whose filter is currently being validated.\n *\n * WHY AN AMBIENT SCOPE RATHER THAN A BAKED-IN CONTEXT: scalar filter schemas are\n * INTERNED across models on purpose (see `validation/scalars/intern.ts`) — two\n * `s.string()` fields on different models share one filter tree — so an operand\n * schema cannot carry a model. What IS per-model is the `where` schema that\n * contains it, and every re-scoping boundary is one of those (a nested relation\n * filter embeds the TARGET model's `where`). So the boundary pushes the model\n * and the operand reads it. Validation is synchronous and depth-first, which is\n * what makes a single slot with save/restore exact rather than merely likely.\n */\nlet activeModel: AnyModel | undefined;\n\n/** Contexts are built on first use and memoized per model. */\nconst contexts = new WeakMap<AnyModel, AnyOperandCtx>();\n\n/**\n * Run `validate` with `model` as the operand scope, restoring the previous one\n * afterwards. Re-entrant: a nested relation filter pushes its own target and\n * pops back to the parent.\n */\nexport function runInOperandScope<T>(model: AnyModel, validate: () => T): T {\n const previous = activeModel;\n activeModel = model;\n try {\n return validate();\n } finally {\n activeModel = previous;\n }\n}\n\n/**\n * Re-close a schema onto a model: everything validated through it resolves its\n * operand callbacks against `model`.\n *\n * The wrap is applied IN PLACE, and both reasons matter. The schema is a\n * freshly built, model-owned object whose `entries` / `extend` surface its own\n * factory and the factories above it still read, so returning a different object\n * would either lose that surface or force a copy of every entry. And a `where`\n * is SELF-REFERENTIAL — its `AND`/`OR`/`NOT` thunks close over the very const\n * being returned — so a copy would leave the recursion pointing at the\n * unwrapped original.\n */\nexport function scopeOperands<S extends VibSchema<any, any>>(\n schema: S,\n model: AnyModel\n): S {\n const standard = schema[\"~standard\"] as {\n validate: (value: unknown) => unknown;\n };\n const inner = standard.validate;\n standard.validate = (value: unknown) =>\n runInOperandScope(model, () => inner(value));\n return limitFilterDepth(schema);\n}\n\n/** The context for the model in scope, or `undefined` outside any filter. */\nfunction currentContext(): AnyOperandCtx | undefined {\n const model = activeModel;\n if (!model) return undefined;\n const cached = contexts.get(model);\n if (cached) return cached;\n const context: AnyOperandCtx = {\n fields: createModelFieldRefs(model[\"~\"].names.ts ?? \"unknown\", model),\n sql,\n };\n contexts.set(model, context);\n return context;\n}\n\n// =============================================================================\n// THE OPERAND SCHEMA\n// =============================================================================\n\n/**\n * A comparison operand: the wrapped scalar schema, a field reference of\n * `TType`, an SQL fragment, or a callback returning one of the latter two.\n *\n * This is deliberately not `v.union([...])`: a union would rewrite every\n * existing operand's failure message into \"Value did not match any union\n * member: …\". Here each non-value kind is recognized by its own discriminator,\n * so an ordinary bad value is handed straight to the wrapped schema and keeps\n * its exact message.\n *\n * The reference's MODEL is not checked here — scalar filter schemas are interned\n * across models and carry no model identity (see `validation/scalars/intern.ts`);\n * the same-model rule is a query-scope property and is enforced by the\n * where-builder before any I/O. See {@link file://../../schema/field-ref.ts}.\n */\nexport interface ComparisonOperandSchema<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends AnyOperandCtx = AnyOperandCtx,\n> extends VibSchema<\n | InferInput<TSchema>\n | FieldRef<string, TType>\n | Sql\n | ((ctx: TCtx) => FieldRef<string, TType> | Sql),\n InferOutput<TSchema> | FieldRef<string, TType> | Sql\n > {\n readonly type: \"comparison_operand\";\n /** The scalar type a reference must carry to be accepted. */\n readonly fieldType: TType;\n /** The literal-operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\nconst CALLBACK_OUT_OF_SCOPE =\n \"A filter callback is only meaningful inside a model filter, where the model whose columns it names is known.\";\n\nconst RETURN_REFUSAL =\n \"A filter callback must return a field reference (ctx.fields.<field>) or an SQL fragment (ctx.sql`…`)\";\n\nfunction describe(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"an array\";\n return `a value of type '${typeof value}'`;\n}\n\nfunction resolveCallback(\n callback: (ctx: AnyOperandCtx) => unknown,\n fieldType: ScalarType\n) {\n const context = currentContext();\n if (!context) {\n return fail(CALLBACK_OUT_OF_SCOPE);\n }\n\n let returned: unknown;\n try {\n returned = callback(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return fail(`Filter callback threw: ${message}`);\n }\n\n if (isFieldRef(returned)) {\n return checkRef(returned, fieldType);\n }\n if (isSql(returned)) {\n return ok(returned);\n }\n if (isRecord(returned) && isFunction(returned.then)) {\n discardAsyncValidationResult(returned);\n return fail(\n `${RETURN_REFUSAL}; it returned a promise. Validation is synchronous, so a filter callback cannot be async.`\n );\n }\n return fail(`${RETURN_REFUSAL}; it returned ${describe(returned)}.`);\n}\n\n/**\n * Build a comparison operand around a scalar schema.\n *\n * ATTACH IT ONLY WHERE THE ENGINE CAN COMPILE THE RESULT. Acceptance that\n * outruns the builder is accept-and-ignore with extra steps: today that means\n * `equals` / `not` / `lt` / `lte` / `gt` / `gte` on non-list scalar filters, and\n * nothing else. `in` / `notIn` and the list operators take VALUES, `having` is\n * an aggregate over a group rather than a column of one row, and the string\n * predicates keep the narrower {@link fieldRefOr} (a reference, no fragment).\n */\nexport function comparisonOperand<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends AnyOperandCtx = AnyOperandCtx,\n>(\n fieldType: TType,\n wrapped: TSchema\n): ComparisonOperandSchema<TType, TSchema, TCtx> {\n const schema = createSchema<\n | InferInput<TSchema>\n | FieldRef<string, TType>\n | Sql\n | ((ctx: TCtx) => FieldRef<string, TType> | Sql),\n InferOutput<TSchema> | FieldRef<string, TType> | Sql\n >(\"comparison_operand\", (value) => {\n if (isFunction(value)) {\n return resolveCallback(\n value as (ctx: AnyOperandCtx) => unknown,\n fieldType\n ) as never;\n }\n if (isFieldRef(value)) {\n return checkRef(value, fieldType) as never;\n }\n if (isSql(value)) {\n return ok(value) as never;\n }\n return validateSchema(wrapped, value) as never;\n }) as ComparisonOperandSchema<TType, TSchema, TCtx>;\n\n (schema as { fieldType: TType }).fieldType = fieldType;\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n // Neither a reference, a fragment, nor a callback is ever a default;\n // optionality is entirely the wrapped schema's business, so mirror it for the\n // object validator's fast path.\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n\n return schema;\n}\n\n// =============================================================================\n// FIELD-REFERENCE-ONLY OPERAND\n// =============================================================================\n\n/**\n * A comparison operand that accepts EITHER a field reference of `TType` or the\n * wrapped scalar schema — no fragment, no callback.\n *\n * This is what the string predicates (`contains` / `startsWith` / `endsWith`)\n * take: the builder compiles a referenced column there, so the reference stays,\n * while the fragment and its callback sugar are drawn at the comparison\n * operators only.\n */\nexport interface FieldRefOrSchema<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n> extends VibSchema<\n InferInput<TSchema> | FieldRef<string, TType>,\n InferOutput<TSchema> | FieldRef<string, TType>\n > {\n readonly type: \"field_ref_or\";\n /** The scalar type a reference must carry to be accepted. */\n readonly fieldType: TType;\n /** The literal-operand schema this wraps. */\n readonly wrapped: TSchema;\n /** Mirrors the wrapped schema, for the object validator's absent-key path. */\n readonly acceptsUndefined: boolean;\n}\n\nexport function fieldRefOr<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n>(fieldType: TType, wrapped: TSchema): FieldRefOrSchema<TType, TSchema> {\n const schema = createSchema<\n InferInput<TSchema> | FieldRef<string, TType>,\n InferOutput<TSchema> | FieldRef<string, TType>\n >(\"field_ref_or\", (value) => {\n if (isFieldRef(value)) {\n return checkRef(value, fieldType);\n }\n return validateSchema(wrapped, value) as never;\n }) as FieldRefOrSchema<TType, TSchema>;\n\n (schema as { fieldType: TType }).fieldType = fieldType;\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n // A reference is never a default; optionality is entirely the wrapped\n // schema's business, so mirror it for the object validator's fast path.\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined === true;\n\n return schema;\n}\n\n// =============================================================================\n// RE-CLOSING WRAPPER\n// =============================================================================\n\n/**\n * Re-closes a schema that transitively opened a non-value operand.\n *\n * Scalar filter schemas are shared: `having` reuses the very same interned\n * filter a `where` uses. Prisma does not allow field references in\n * `having`/`groupBy` (a HAVING operand is an aggregate over a group, not a\n * column of one row), and neither do we — so the reuse site wraps itself and\n * fails closed instead of inheriting the operand by accident.\n */\nexport interface NoFieldRefSchema<TSchema extends VibSchema<any, any>>\n extends VibSchema<InferInput<TSchema>, InferOutput<TSchema>> {\n readonly type: \"no_field_ref\";\n readonly wrapped: TSchema;\n readonly acceptsUndefined: boolean;\n}\n\nfunction closeOperands<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string,\n fragments: boolean\n): NoFieldRefSchema<TSchema> {\n const standard = wrapped[\"~standard\"];\n const captured = {\n \"~standard\": {\n version: standard.version,\n vendor: standard.vendor,\n validate: standard.validate,\n },\n };\n const schema = createSchema<InferInput<TSchema>, InferOutput<TSchema>>(\n \"no_field_ref\",\n (value) => {\n const inputOperand = findOpaqueOperand(value, fragments);\n if (inputOperand)\n return fail(`${inputOperand} is not supported in ${where}.`);\n const result = validateSchema(captured, value);\n if (result.issues) return result as never;\n const found = findOpaqueOperand(\n (result as { value: unknown }).value,\n fragments\n );\n if (found) {\n return fail(`${found} is not supported in ${where}.`);\n }\n return result as never;\n }\n ) as NoFieldRefSchema<TSchema>;\n\n (schema as { wrapped: TSchema }).wrapped = wrapped;\n (schema as { acceptsUndefined: boolean }).acceptsUndefined =\n (wrapped as { acceptsUndefined?: boolean }).acceptsUndefined ?? false;\n\n return schema;\n}\n\n/**\n * Close a schema to field references only.\n *\n * For the sites whose wrapped schema legitimately holds ARBITRARY DATA — the\n * JSON operand and JSON write data. Only the branded token is looked for there,\n * because it is the only non-value an ordinary document cannot also be: a real\n * `Sql` is a class instance and `v.json` already rejects it as\n * non-JSON-compatible, while a plain `{ strings: […], values: […] }` document\n * that merely LOOKS like a fragment is honest user data and must stay accepted.\n */\nexport function noFieldRef<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string\n): NoFieldRefSchema<TSchema> {\n return closeOperands(wrapped, where, false);\n}\n\n/**\n * Close a schema to field references AND SQL fragments.\n *\n * For the sites whose wrapped schema is a SCALAR FILTER — `having`, where a\n * fragment is refused for the same reason a reference is: whatever it names, it\n * is not the aggregate the group is keyed by. A plain object cannot be a legal\n * scalar operand in the first place, so there is no honest value here for the\n * structural fragment check to misread.\n */\nexport function noOperandExpression<TSchema extends VibSchema<any, any>>(\n wrapped: TSchema,\n where: string\n): NoFieldRefSchema<TSchema> {\n return closeOperands(wrapped, where, true);\n}\n\n/**\n * Exhaustive, cycle-safe search for a field-reference token or an SQL fragment\n * inside an already-validated value; returns how to name the one it found.\n *\n * There is deliberately NO depth cap. An earlier version stopped at four levels\n * on the premise that \"filter values nest at most a couple of levels\" — false\n * on this branch, where scalar `not` nests arbitrarily\n * (`{ not: { not: { … { gt: ref } } } }`, see `buildNegatableFilterSchema`). A\n * five-deep chain therefore walked straight past the guard and emitted the\n * referenced column into HAVING: Postgres rejected the ungrouped column,\n * SQLite/LibSQL accepted it and returned a silently wrong row. A guard that\n * stops looking is accept-and-ignore, which is precisely what this wrapper\n * exists to prevent.\n *\n * Termination comes from structure, not from a budget: every object and array\n * is visited at most once (`seen`), so the walk is linear in the number of\n * distinct nodes the caller already materialized — the same order the\n * `validateSchema` call directly above just spent walking the very same value.\n * The worklist is explicit rather than recursive so a pathologically deep\n * payload cannot overflow the stack here. Binary payloads are skipped whole:\n * bytes cannot be a reference, and `Object.keys` on a typed array would\n * enumerate every index.\n */\nfunction findOpaqueOperand(\n root: unknown,\n fragments: boolean\n): string | undefined {\n const seen = new WeakSet<object>();\n const pending: unknown[] = [root];\n\n while (pending.length > 0) {\n const value = pending.pop();\n if (fragments && typeof value === \"function\") return \"A filter callback\";\n if (typeof value !== \"object\" || value === null) continue;\n if (isFieldRef(value)) {\n const payload = fieldRefPayload(value);\n return `Field reference '${payload.model}.${payload.field}'`;\n }\n if (fragments && isSql(value)) return \"An SQL fragment\";\n if (seen.has(value)) continue;\n seen.add(value);\n\n if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) pending.push(item);\n continue;\n }\n\n for (const key of Object.keys(value)) {\n pending.push((value as Record<string, unknown>)[key]);\n }\n }\n\n return undefined;\n}\n\nfunction checkRef(ref: AnyFieldRef, fieldType: ScalarType) {\n const payload = fieldRefPayload(ref);\n if (payload.list) {\n return fail(\n `Field reference '${payload.model}.${payload.field}' is a list field; list fields cannot be used as a comparison operand.`\n );\n }\n if (payload.type !== fieldType) {\n return fail(\n `Field reference '${payload.model}.${payload.field}' is of type '${payload.type}', but a '${fieldType}' operand is required here.`\n );\n }\n return ok(ref) as never;\n}\n","import type { InferInput, InferOutput, VibSchema } from \"../types\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n// =============================================================================\n// Pipe Schema\n// =============================================================================\n\n/**\n * Transform action interface.\n */\nexport interface TransformAction<TIn, TOut> {\n readonly type: \"transform\";\n readonly transform: (value: TIn) => TOut;\n}\n\n/**\n * Create a transform action for use with pipe.\n *\n * @example\n * const upperCase = v.pipe(v.string(), v.transform(s => s.toUpperCase()));\n */\nexport function transform<TIn, TOut>(\n fn: (value: TIn) => TOut\n): TransformAction<TIn, TOut> {\n return {\n type: \"transform\",\n transform: fn,\n };\n}\n\n/**\n * Pipe action types.\n */\nexport type PipeAction<TIn, TOut> = TransformAction<TIn, TOut>;\n\n/**\n * Pipe schema interface.\n */\nexport interface PipeSchema<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n TInput = InferInput<TSchema>,\n TOutput = TActions extends readonly [...any[], PipeAction<any, infer TLast>]\n ? TLast\n : InferOutput<TSchema>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"pipe\";\n readonly schema: TSchema;\n readonly actions: TActions;\n}\n\n/**\n * Infer the final output type from a chain of actions.\n */\ntype InferPipeOutput<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n> = TActions extends readonly []\n ? InferOutput<TSchema>\n : TActions extends readonly [PipeAction<any, infer TOut>]\n ? TOut\n : TActions extends readonly [PipeAction<any, infer TMid>, ...infer TRest]\n ? TRest extends readonly PipeAction<any, any>[]\n ? InferPipeOutput<VibSchema<TMid, TMid>, TRest>\n : TMid\n : InferOutput<TSchema>;\n\n/**\n * Create a pipe schema that chains a base schema with transform actions.\n *\n * @example\n * const trimmedString = v.pipe(v.string(), v.transform(s => s.trim()));\n * const isoDate = v.pipe(v.date(), v.transform(d => d.toISOString()));\n */\nexport function pipe<\n TSchema extends VibSchema<any, any>,\n const TActions extends readonly PipeAction<any, any>[],\n>(\n schema: TSchema,\n ...actions: TActions\n): PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n> {\n const pipeSchema = createSchema<\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >(\"pipe\", (value) => {\n const result = validateSchema(schema, value);\n if (result.issues) {\n return result as any;\n }\n\n let current: unknown = (result as { value: unknown }).value;\n for (const action of actions) {\n if (action.type === \"transform\") {\n try {\n current = action.transform(current);\n } catch (e) {\n return fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n }\n\n return ok(current as InferPipeOutput<TSchema, TActions>);\n }) as PipeSchema<\n TSchema,\n TActions,\n InferInput<TSchema>,\n InferPipeOutput<TSchema, TActions>\n >;\n\n (pipeSchema as any).schema = schema;\n (pipeSchema as any).actions = actions;\n\n return pipeSchema;\n}\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { type GeoPoint, validateGeoPoint } from \"./geo-point-codec\";\nimport { buildSchema } from \"./helpers\";\n\n// =============================================================================\n// GeoPoint Schema ({ longitude: number, latitude: number })\n// =============================================================================\n\nexport interface BasePointSchema<\n Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<GeoPoint, Opts>,\n ComputeOutput<GeoPoint, Opts>\n > {}\n\nexport interface PointSchema<TInput = GeoPoint, TOutput = GeoPoint>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"point\";\n}\n\n/**\n * Create a point schema for EPSG:4326 longitude/latitude coordinates.\n *\n * @example\n * const location = v.point();\n * const optionalPoint = v.point({ optional: true });\n * const pointArray = v.point({ array: true });\n */\nexport function point<\n const Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n>(\n options?: Opts\n): PointSchema<ComputeInput<GeoPoint, Opts>, ComputeOutput<GeoPoint, Opts>> {\n return buildSchema(\"point\", validateGeoPoint, options) as PointSchema<\n ComputeInput<GeoPoint, Opts>,\n ComputeOutput<GeoPoint, Opts>\n >;\n}\n","import type {\n Cast,\n InferInput,\n InferOutput,\n ThunkCast,\n VibSchema,\n} from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\nimport { type ObjectOptions, type ObjectSchema, object } from \"./object\";\n\n// =============================================================================\n// Record Schema (dynamic keys)\n// =============================================================================\n\nexport interface RecordSchema<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n TInput = Record<InferInput<TKey>, InferInput<TValue>>,\n TOutput = Record<InferOutput<TKey>, InferOutput<TValue>>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"record\";\n readonly key: TKey;\n readonly value: TValue;\n}\n\n/**\n * Create a record schema that validates keys and values.\n *\n * @example\n * const stringRecord = v.record(v.string(), v.number());\n * // Validates: { foo: 1, bar: 2 }\n */\nexport function record<\n TKey extends VibSchema<string, string>,\n TValue extends VibSchema<any, any>,\n>(key: TKey, value: TValue): RecordSchema<TKey, TValue> {\n const schema = createSchema<\n Record<InferInput<TKey>, InferInput<TValue>>,\n Record<InferOutput<TKey>, InferOutput<TValue>>\n >(\"record\", (input) => {\n if (!isRecord(input)) {\n return fail(\n `Expected object, received ${\n Array.isArray(input) ? \"array\" : typeof input\n }`\n );\n }\n\n const output: Record<string, unknown> = {};\n\n for (const [k, v] of Object.entries(input)) {\n const keyResult = validateSchema(key, k);\n if (keyResult.issues) {\n return fail(`Invalid key \"${k}\": ${keyResult.issues[0]!.message}`, [k]);\n }\n\n const valueResult = validateSchema(value, v);\n if (valueResult.issues) {\n const issue = valueResult.issues[0]!;\n // Use concat instead of spread for better performance\n const newPath = issue.path\n ? ([k] as PropertyKey[]).concat(issue.path)\n : [k];\n return fail(issue.message, newPath);\n }\n\n output[(keyResult as { value: string }).value] = (\n valueResult as { value: unknown }\n ).value;\n }\n\n return ok(output as Record<InferOutput<TKey>, InferOutput<TValue>>);\n }) as RecordSchema<TKey, TValue>;\n\n (schema as any).key = key;\n (schema as any).value = value;\n\n return schema;\n}\n\n// =============================================================================\n// FromKeys Schema (static keys with same value schema)\n// =============================================================================\n\n/**\n * Schema entry type - VibSchema or ThunkCast for circular references.\n */\ntype SchemaEntry =\n | VibSchema<any, any>\n | ThunkCast<any, any>\n | (() => Cast<any, any>);\n\n/**\n * Normalize a schema entry to VibSchema for type extraction.\n */\ntype NormalizeEntry<T> =\n T extends VibSchema<infer I, infer O>\n ? VibSchema<I, O>\n : T extends ThunkCast<infer I, infer O>\n ? VibSchema<I, O>\n : T extends () => Cast<infer I, infer O>\n ? VibSchema<I, O>\n : never;\n\n/**\n * Compute entries from a tuple of keys and a schema.\n */\nexport type ComputeEntriesFromKeys<\n TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n> = {\n [K in TKeys[number]]: NormalizeEntry<TSchema>;\n};\n\n/**\n * Options for fromKeys (same as ObjectOptions).\n */\nexport type FromKeysOptions<T = unknown> = ObjectOptions<T>;\n\n/** Project entries for composition without constructing a temporary schema. */\nexport function entriesFromKeys<\n const TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n>(keys: TKeys, schema: TSchema): ComputeEntriesFromKeys<TKeys, TSchema> {\n const entries: Record<string, SchemaEntry> = {};\n for (const key of keys) {\n entries[key] = schema;\n }\n // Preserve the builder's existing thunk-normalized inference boundary.\n return entries as unknown as ComputeEntriesFromKeys<TKeys, TSchema>;\n}\n\n/**\n * Creates an object schema from an array of keys, all mapping to the same schema.\n * This is a convenient wrapper around `object()` for creating uniform schemas.\n *\n * @param keys - Array of key names (use `as const` for type inference)\n * @param schema - Schema to use for all keys (can be a thunk for circular refs)\n * @param options - Schema options (same as object schema)\n *\n * @example\n * // All keys have the same string schema\n * const schema = v.fromKeys([\"name\", \"email\", \"bio\"] as const, v.string());\n * // → ObjectSchema<{ name: string, email: string, bio: string }>\n *\n * @example\n * // With options\n * const optionalSchema = v.fromKeys(\n * [\"user\", \"post\"] as const,\n * v.number(),\n * { partial: false }\n * );\n * // → ObjectSchema<{ user: number, post: number }> (all required)\n *\n * @example\n * // With thunks for circular references\n * const nodeSchema: VibSchema<any, any> = v.object({ value: v.string() });\n * const schema = v.fromKeys(\n * [\"left\", \"right\"] as const,\n * () => nodeSchema,\n * { optional: true }\n * );\n */\nexport function fromKeys<\n const TKeys extends readonly string[],\n TSchema extends SchemaEntry,\n const TOpts extends FromKeysOptions | undefined = undefined,\n>(\n keys: TKeys,\n schema: TSchema,\n options?: TOpts\n): ObjectSchema<ComputeEntriesFromKeys<TKeys, TSchema>, TOpts> {\n return object(entriesFromKeys(keys, schema), options);\n}\n","import type { VibSchema } from \"../types\";\nimport { createSchema, fail } from \"./helpers\";\n\n/**\n * A key that EXISTS on an object schema but accepts NOTHING.\n *\n * Leaving a key out already rejects it — with `Unknown key: gt`, which reads\n * like a typo. Some keys are absent for a reason worth telling the caller:\n * ordered comparison on an enum cannot answer the same on every provider\n * (see {@link file://../scalars/enum.ts}), `_distance` is only meaningful under\n * a vector order (see {@link file://../model/core/orderby.ts}). Spelling those\n * out as a refusal turns a shrug into an explanation, and keeps the key in the\n * schema where the reason can be read.\n *\n * Input and output are both `never`, so TypeScript refuses the key too —\n * the runtime refusal is the backstop for untyped callers.\n *\n * @param reason - the message the caller sees, stating WHY, not just \"no\"\n */\nexport function refused(reason: string): VibSchema<never, never> {\n return createSchema<never, never>(\"refused\", () => fail(reason));\n}\n","import type {\n InferInput,\n InferOutput,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { createSchema, fail, ok, validateSchema } from \"./helpers\";\n\n// =============================================================================\n// Transform Schema Wrapper\n// =============================================================================\n\n/**\n * Schema that wraps another schema and transforms its output.\n */\nexport interface TransformSchema<TInput, TOutput>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"transform\";\n}\n\n/**\n * Wrap a schema with a transform function.\n * Validates with the wrapped schema, then applies the transform to the output.\n *\n * @param schema - The base schema to validate with\n * @param fn - Transform function: (validatedValue) => newValue\n *\n * @example\n * // String to uppercase\n * const upper = v.coerce(v.string(), s => s.toUpperCase());\n *\n * @example\n * // Parse string to number\n * const parseNum = v.coerce(v.string(), s => parseInt(s, 10));\n * type Out = InferOutput<typeof parseNum>; // number\n *\n * @example\n * // Date to ISO string\n * const isoDate = v.coerce(v.date(), d => d.toISOString());\n * type Out = InferOutput<typeof isoDate>; // string\n *\n * @example\n * // Extract property from object\n * const getName = v.coerce(\n * v.object({ name: v.string(), age: v.number() }),\n * obj => obj.name\n * );\n * type Out = InferOutput<typeof getName>; // string\n */\nexport function coerce<S extends VibSchema<any, any>, TOut>(\n schema: S,\n fn: (value: S[\" vibInferred\"][\"1\"]) => TOut\n): TransformSchema<InferInput<S>, TOut> & { wrapped: S } {\n const transformSchema = createSchema<InferInput<S>, TOut>(\n \"transform\",\n (value): ValidationResult<TOut> => {\n const result = validateSchema(schema, value);\n // The wrapped schema's issues keep their paths: a refusal inside a\n // coerced object names the member that refused.\n if (result.issues) return { issues: result.issues };\n try {\n return ok(fn((result as { value: InferOutput<S> }).value));\n } catch (e) {\n return fail(\n `Transform failed: ${e instanceof Error ? e.message : String(e)}`\n );\n }\n }\n ) as TransformSchema<InferInput<S>, TOut> & { wrapped: S };\n\n (transformSchema as any).wrapped = schema;\n // Inherit acceptsUndefined from wrapped schema\n (transformSchema as any).acceptsUndefined =\n (schema as any).acceptsUndefined === true;\n\n return transformSchema;\n}\n\n/**\n * Alias for coerce - transform wrapper.\n */\nexport const map = coerce;\n","// Shorthand Coercion Schemas\n// Utilities for coercing simple values to structured objects\n\nimport type { VibSchema } from \"../types\";\nimport { coerce } from \"./transform\";\n\n/**\n * Coerces a value to a filter object with `equals` key.\n * Used for shorthand filter syntax: `\"value\"` -> `{ equals: \"value\" }`\n */\nexport const shorthandFilter = <S extends VibSchema>(schema: S) =>\n coerce(schema, (val: S[\" vibInferred\"][\"1\"]) => ({ equals: val }));\n\n/**\n * Coerces a value to an update object with `set` key.\n * Used for shorthand update syntax: `\"value\"` -> `{ set: \"value\" }`\n */\nexport const shorthandUpdate = <S extends VibSchema>(schema: S) =>\n coerce(schema, (val: S[\" vibInferred\"][\"1\"]) => ({ set: val }));\n\n/**\n * Coerces a single value to an array.\n * Used for shorthand array syntax: `\"value\"` -> `[\"value\"]`\n */\nexport const shorthandArray = <S extends VibSchema>(schema: S) =>\n coerce(\n schema,\n (val: S[\" vibInferred\"][\"1\"]) => [val] as [S[\" vibInferred\"][\"1\"]]\n );\n","import { discardAsyncValidationResult } from \"../parse-failure\";\nimport type {\n InferInput,\n InferOutput,\n ValidationIssue,\n ValidationResult,\n VibSchema,\n} from \"../types\";\nimport { isRecord } from \"../value-guards\";\nimport { createSchema, fail } from \"./helpers\";\n\n// =============================================================================\n// Union Schema\n// =============================================================================\n\nconst ASYNC_REFUSAL: readonly ValidationIssue[] = Object.freeze([\n Object.freeze({ message: \"Async schemas are not supported\" }),\n]);\n\nexport interface UnionSchema<\n TOptions extends readonly VibSchema<any, any>[],\n TInput = TOptions[number][\" vibInferred\"][\"0\"],\n TOutput = InferOutput<TOptions[number]>,\n> extends VibSchema<TInput, TOutput> {\n readonly type: \"union\";\n readonly options: TOptions;\n}\n\n/**\n * The tag of a TAGGED union: one key at which every member is an object whose\n * entry is a required literal, each a different one. A value carrying one of\n * those literals was written for that member alone.\n */\ninterface Tags {\n readonly key: string;\n readonly members: ReadonlyMap<unknown, VibSchema[\"~standard\"][\"validate\"]>;\n}\n\nfunction tagsOf(options: readonly VibSchema<any, any>[]): Tags | undefined {\n let key: string | undefined;\n const members = new Map<unknown, VibSchema[\"~standard\"][\"validate\"]>();\n for (const option of options) {\n const {\n type,\n entries,\n options: shape,\n } = option as {\n type?: string;\n entries?: Record<string, unknown>;\n options?: { array?: boolean; omit?: readonly string[] };\n };\n if (type !== \"object\" || !entries || shape?.array === true) return;\n key ??= Object.keys(entries).find((name) => isLiteral(entries[name]));\n const tag = key === undefined ? undefined : entries[key];\n if (!(isLiteral(tag) && tag.acceptsUndefined !== true)) return;\n if (members.has(tag.value) || shape?.omit?.includes(key!)) return;\n members.set(tag.value, option[\"~standard\"].validate);\n }\n return key === undefined || members.size < 2 ? undefined : { key, members };\n}\n\nfunction isLiteral(\n entry: unknown\n): entry is { type: \"literal\"; value: unknown; acceptsUndefined?: boolean } {\n return isRecord(entry) && entry.type === \"literal\";\n}\n\ntype MemberResult = ReturnType<VibSchema[\"~standard\"][\"validate\"]>;\n\n/** A member's result, an async member's promise being a refusal. */\nfunction settled(result: MemberResult): ValidationResult<unknown> {\n if (!(\"then\" in result)) return result as ValidationResult<unknown>;\n discardAsyncValidationResult(result);\n return { issues: ASYNC_REFUSAL };\n}\n\n/** A member's first issue, spelled with its path for a refusal that lists several. */\nfunction describe({ message, path }: ValidationIssue): string {\n return path?.length ? `${path.join(\".\")}: ${message}` : message;\n}\n\n/**\n * Create a union schema that validates against multiple options.\n * Returns the result of the first matching schema.\n *\n * A refusal names the member the value was written for. In a tagged union\n * (every member an object with its own literal at one key) that is the member\n * its tag names, and only that member runs. Otherwise it is the member whose\n * first issue reads DEEPEST into the value (`{ gt: \"3\" }` is refused at `gt`\n * by the operator object, not at the root by the shorthand). Members that\n * refused equally deep leave no such member, and the refusal lists what each\n * one said, once (one issue, path kept, when they all said the same).\n *\n * @example\n * const stringOrNumber = v.union([v.string(), v.number()]);\n */\nexport function union<const TOptions extends readonly VibSchema<any, any>[]>(\n options: TOptions\n): UnionSchema<TOptions> {\n const validators = options.map((option) => option[\"~standard\"].validate);\n // Read on first use: a union nothing validates through never inspects its\n // members. Members whose entries are still unresolved thunks then read as\n // untagged for good, and the depth rule alone names the member.\n let tags: Tags | undefined | null = null;\n const schema = createSchema<\n InferInput<TOptions[number]>,\n InferOutput<TOptions[number]>\n >(\"union\", (value) => {\n if (tags === null) tags = tagsOf(options);\n const tagged = tags && isRecord(value) && tags.members.get(value[tags.key]);\n if (tagged) {\n return settled(tagged(value)) as ValidationResult<\n InferOutput<TOptions[number]>\n >;\n }\n // Success returns the matching member's result as-is. Nothing about a\n // refusal is allocated until a second member refuses as deep as the first,\n // so the common \"first member misses, second matches\" pattern stays free.\n let deepest: readonly ValidationIssue[] | undefined;\n let depth = -1;\n let tied: string[] | undefined;\n\n for (const validate of validators) {\n const result = settled(validate(value));\n if (!result.issues) {\n return result as { value: InferOutput<TOptions[number]> };\n }\n const { issues } = result;\n const reach = issues[0]!.path?.length ?? 0;\n if (reach > depth) {\n deepest = issues;\n depth = reach;\n tied = undefined;\n } else if (reach === depth) {\n const said = describe(issues[0]!);\n tied ??= [describe(deepest![0]!)];\n if (!tied.includes(said)) tied.push(said);\n }\n }\n\n if (tied && tied.length > 1) return fail(tied.join(\", or \"));\n return deepest\n ? { issues: deepest }\n : fail(\"Expected no value: the union has no member\");\n }) as UnionSchema<TOptions>;\n\n (schema as any).options = options;\n\n return schema;\n}\n","// Single or Array Schema\n// Accepts either a single value or an array of values, normalizes to array\n\nimport type { VibSchema } from \"../types\";\nimport { array } from \"./array\";\nimport { coerce } from \"./transform\";\nimport { union } from \"./union\";\n\n/**\n * Creates a schema that accepts either a single value or an array of values.\n * Single values are coerced to a single-element array for consistent output.\n *\n * @example\n * const schema = v.singleOrArray(v.string());\n * // Accepts: \"foo\" -> [\"foo\"]\n * // Accepts: [\"foo\", \"bar\"] -> [\"foo\", \"bar\"]\n */\nexport const singleOrArray = <S extends VibSchema>(schema: S) => {\n return union([\n coerce(schema, (v: S[\" vibInferred\"][\"1\"]) => [v]),\n array(schema),\n ]);\n};\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isString } from \"../value-guards\";\nimport { buildSchema, ok } from \"./helpers\";\n\n// =============================================================================\n// String Schema\n// =============================================================================\nexport interface StringSchema<TInput = string, TOutput = string>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"string\";\n}\n\n// Pre-computed error for fast path (avoid allocation on error)\nconst STRING_ERROR = Object.freeze({\n issues: Object.freeze([Object.freeze({ message: \"Expected string\" })]),\n});\n\n/**\n * Validate that a value is a string.\n */\nfunction validateString(value: unknown) {\n return isString(value) ? ok(value) : STRING_ERROR;\n}\n\n/**\n * Create a string schema.\n *\n * @example\n * const name = v.string();\n * const optionalName = v.string({ optional: true });\n * const tags = v.string({ array: true });\n */\nexport function string(): StringSchema<string, string>;\nexport function string<const Opts extends ScalarOptions<string, any>>(\n options: Opts\n): StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>>;\nexport function string<\n const Opts extends ScalarOptions<string, any> | undefined,\n>(\n options?: Opts\n): StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>> {\n return buildSchema(\"string\", validateString, options) as StringSchema<\n ComputeInput<string, Opts>,\n ComputeOutput<string, Opts>\n >;\n}\n\n// Export the validate function for reuse\nexport { validateString };\n","import type {\n ComputeInput,\n ComputeOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport { isNumber } from \"../value-guards\";\nimport { buildSchema, fail, ok } from \"./helpers\";\n\n// =============================================================================\n// Vector Schema (array of numbers for embeddings/ML)\n// =============================================================================\n\nexport interface BaseVectorSchema<\n Opts extends ScalarOptions<number[], any> | undefined = undefined,\n> extends VibSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > {}\n\nexport interface VectorSchema<TInput = number[], TOutput = number[]>\n extends VibSchema<TInput, TOutput> {\n readonly type: \"vector\";\n}\n\n// Pre-computed error for fast path\nconst NOT_ARRAY_ERROR = Object.freeze({\n issues: Object.freeze([\n Object.freeze({ message: \"Expected array of numbers\" }),\n ]),\n});\n\n/**\n * Validate that a value is a vector (array of numbers).\n * Optionally check for specific dimensions.\n */\nfunction createVectorValidator(dimensions?: number) {\n // Pre-compute dimension error if applicable\n const dimensionError =\n dimensions !== undefined\n ? Object.freeze({\n issues: Object.freeze([\n Object.freeze({\n message: `Expected vector of ${dimensions} dimensions`,\n }),\n ]),\n })\n : null;\n\n return (value: unknown) => {\n if (!Array.isArray(value)) return NOT_ARRAY_ERROR;\n\n const len = value.length;\n for (let i = 0; i < len; i++) {\n if (!(isNumber(value[i]) && Number.isFinite(value[i]))) {\n return fail(`Expected finite number at index ${i}`);\n }\n }\n\n if (dimensionError && len !== dimensions) return dimensionError;\n\n return ok(value as number[]);\n };\n}\n\n/**\n * Create a vector schema for arrays of numbers (embeddings, coordinates, etc.)\n *\n * @param dimensions - Optional fixed number of dimensions\n * @param options - Schema options\n *\n * @example\n * const embedding = v.vector(); // Any length\n * const embedding3d = v.vector(3); // Exactly 3 dimensions\n * const optionalVector = v.vector(undefined, { optional: true });\n */\nexport function vector<\n const Opts extends ScalarOptions<number[], any> | undefined = undefined,\n>(\n dimensions?: number,\n options?: Opts\n): VectorSchema<ComputeInput<number[], Opts>, ComputeOutput<number[], Opts>> & {\n dimensions?: number;\n} {\n const baseValidate = createVectorValidator(dimensions);\n return buildSchema(\"vector\", baseValidate, options, {\n dimensions,\n }) as VectorSchema<\n ComputeInput<number[], Opts>,\n ComputeOutput<number[], Opts>\n > & { dimensions?: number };\n}\n\n// Export validator for reuse\nexport { createVectorValidator as validateVector };\n","// =============================================================================\n// VibORM Validation - Runtime and Type-Level Namespace\n// =============================================================================\n\nimport type { JsonNullKind } from \"@schema/json-null\";\nimport type { ScalarType } from \"@schema/scalars/common\";\nimport type {\n ComputeInput,\n ComputeOutput,\n InferInput,\n InferOutput,\n ScalarOptions,\n VibSchema,\n} from \"../types\";\nimport type { ArraySchema } from \"./array\";\nimport { array } from \"./array\";\nimport type { BigIntSchema } from \"./bigint\";\nimport { bigint } from \"./bigint\";\nimport type { BlobSchema } from \"./blob\";\nimport { blob } from \"./blob\";\nimport type { BooleanSchema } from \"./boolean\";\nimport { boolean } from \"./boolean\";\nimport type { DateSchema } from \"./date\";\nimport { date } from \"./date\";\nimport type {\n DecimalComputeInput,\n DecimalComputeOutput,\n DecimalOptions,\n DecimalSchema,\n} from \"./decimal\";\nimport { decimal } from \"./decimal\";\nimport type { EnumSchema } from \"./enum\";\nimport { enum_ } from \"./enum\";\nimport type { ComputeEntriesFromObject } from \"./from-object\";\nimport { fromObject } from \"./from-object\";\nimport type { GeoPoint } from \"./geo-point-codec\";\nimport type { IsoDateSchema, IsoTimeSchema, IsoTimestampSchema } from \"./iso\";\nimport { isoDate, isoTime, isoTimestamp } from \"./iso\";\nimport type { JsonInput, JsonSchema, JsonValue } from \"./json\";\nimport { json } from \"./json\";\nimport type { JsonNullOrSchema, JsonWriteSchema } from \"./json-null\";\nimport { jsonNullOr, jsonWrite } from \"./json-null\";\nimport { lazy, lazyRef } from \"./lazy\";\nimport type { LiteralSchema, LiteralValue } from \"./literal\";\nimport { literal } from \"./literal\";\nimport type { NullableSchema } from \"./nullable\";\nimport { maybeNullable, nullable } from \"./nullable\";\nimport type { IntegerSchema, NumberSchema } from \"./number\";\nimport { integer, number } from \"./number\";\nimport type {\n ObjectOptions,\n ObjectSchema,\n OmittedObjectSchema,\n} from \"./object\";\nimport { object } from \"./object\";\nimport { omit } from \"./omit\";\nimport type {\n ComparisonOperandSchema,\n FieldRefOrSchema,\n NoFieldRefSchema,\n OperandCtx,\n} from \"./operand\";\nimport {\n comparisonOperand,\n fieldRefOr,\n noFieldRef,\n noOperandExpression,\n} from \"./operand\";\nimport type { OptionalSchema, WrappableSchema } from \"./optional\";\nimport { optional } from \"./optional\";\nimport type { PipeAction, PipeSchema } from \"./pipe\";\nimport { pipe, transform as transformAction } from \"./pipe\";\nimport type { PointSchema } from \"./point\";\nimport { point } from \"./point\";\nimport type { ComputeEntriesFromKeys, RecordSchema } from \"./record\";\nimport { fromKeys, record } from \"./record\";\nimport { refused } from \"./refused\";\nimport { shorthandArray, shorthandFilter, shorthandUpdate } from \"./shorthand\";\nimport { singleOrArray } from \"./single-or-array\";\nimport type { StringSchema } from \"./string\";\nimport { string } from \"./string\";\nimport type { TransformSchema } from \"./transform\";\nimport { coerce, map } from \"./transform\";\nimport type { UnionSchema } from \"./union\";\nimport { union } from \"./union\";\nimport type { VectorSchema } from \"./vector\";\nimport { vector } from \"./vector\";\n\ntype OmitOptions<\n TOptions extends ObjectOptions | undefined,\n TKeys extends readonly PropertyKey[] | undefined,\n> = (TOptions extends ObjectOptions ? Omit<TOptions, \"omit\"> : object) & {\n omit: TKeys;\n};\n\n// =============================================================================\n// Runtime Namespace (v.string(), v.number(), etc.)\n// =============================================================================\n\n/**\n * VibORM validation namespace.\n *\n * @example\n * import { v } from \"viborm/validation\";\n *\n * const user = v.object({\n * name: v.string(),\n * age: v.number({ optional: true }),\n * email: v.string(),\n * createdAt: v.date(),\n * });\n *\n * // Circular references use thunks\n * const node = v.object({\n * value: v.string(),\n * parent: () => node, // Thunk for self-reference\n * });\n */\nexport const v = {\n // Scalars\n string,\n number,\n integer,\n boolean,\n bigint,\n decimal,\n literal,\n enum: enum_,\n json,\n // Date & Time\n date,\n isoTimestamp,\n isoDate,\n isoTime,\n // Blob, Vector, Point\n blob,\n vector,\n point,\n // Wrappers\n array,\n nullable,\n maybeNullable,\n optional,\n // Objects\n object,\n omit,\n fromObject,\n // Composition\n union,\n pipe,\n transformAction,\n record,\n fromKeys,\n // Transform wrappers\n coerce,\n map,\n // Lazy evaluation\n lazy,\n lazyRef,\n // Single or array\n singleOrArray,\n // Shorthand coercions\n shorthandFilter,\n shorthandUpdate,\n shorthandArray,\n // Comparison operands: field references (Prisma FieldRef parity), SQL\n // fragments, and the callback that sugars both\n comparisonOperand,\n fieldRefOr,\n noFieldRef,\n noOperandExpression,\n // JSON null sentinels (Prisma DbNull/JsonNull/AnyNull parity)\n jsonNullOr,\n jsonWrite,\n // Keys that exist only to explain why they are refused\n refused,\n} as const;\n\nexport default v;\n\n// =============================================================================\n// Type-Level Namespace (V.String, V.Number, etc.)\n// =============================================================================\n\n/**\n * V Namespace - Type-level schema constructors for explicit type annotations.\n *\n * These mirror the runtime v.* functions but produce types directly without\n * needing to serialize the full schema structure in .d.ts files.\n *\n * @example\n * ```typescript\n * // In a .d.ts file:\n * import type { V } from \"@validation\";\n *\n * export type UserSchema = V.Object<{\n * id: V.String;\n * name: V.String<{ optional: true }>;\n * age: V.Number;\n * }>;\n * ```\n */\nexport namespace V {\n // =========================================================================\n // Scalar Types\n // =========================================================================\n\n /**\n * Type-level string schema.\n * @example V.String - Required string\n * @example V.String<{ optional: true }> - Optional string\n * @example V.String<{ nullable: true }> - Nullable string\n * @example V.String<{ array: true }> - Array of strings\n */\n export type String<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = StringSchema<ComputeInput<string, Opts>, ComputeOutput<string, Opts>>;\n\n /**\n * Type-level number schema.\n * @example V.Number - Required number\n * @example V.Number<{ optional: true }> - Optional number\n */\n export type Number<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n > = NumberSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\n\n /**\n * Type-level integer schema.\n */\n export type Integer<\n Opts extends ScalarOptions<number, any> | undefined = undefined,\n > = IntegerSchema<ComputeInput<number, Opts>, ComputeOutput<number, Opts>>;\n\n /**\n * Type-level decimal schema. Input and output differ on purpose: a decimal\n * accepts `Decimal | string` and validates to the canonical private\n * string every identity owner keys on. The public `Decimal` result is built\n * once per selected value at the typed result boundary, not here.\n * @example V.Decimal - Required decimal\n * @example V.Decimal<{ nullable: true }> - Nullable decimal\n * @example V.Decimal<{ decimal: { precision: 10; scale: 2 } }> - A declared domain\n */\n export type Decimal<\n Opts extends DecimalOptions<any> | undefined = undefined,\n > = DecimalSchema<DecimalComputeInput<Opts>, DecimalComputeOutput<Opts>>;\n\n /**\n * Type-level boolean schema.\n */\n export type Boolean<\n Opts extends ScalarOptions<boolean, any> | undefined = undefined,\n > = BooleanSchema<ComputeInput<boolean, Opts>, ComputeOutput<boolean, Opts>>;\n\n /**\n * Type-level bigint schema.\n */\n export type BigInt<\n Opts extends ScalarOptions<bigint, any> | undefined = undefined,\n > = BigIntSchema<ComputeInput<bigint, Opts>, ComputeOutput<bigint, Opts>>;\n\n // =========================================================================\n // Date & Time Types\n // =========================================================================\n\n /**\n * Type-level Date schema (JavaScript Date object).\n */\n export type Date<\n Opts extends ScalarOptions<globalThis.Date, any> | undefined = undefined,\n > = DateSchema<\n ComputeInput<globalThis.Date, Opts>,\n ComputeOutput<globalThis.Date, Opts>\n >;\n\n /**\n * Type-level ISO timestamp schema (accepts string | Date, outputs string).\n */\n export type IsoTimestamp<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoTimestampSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n /**\n * Type-level ISO date schema (accepts string | Date, outputs string YYYY-MM-DD).\n */\n export type IsoDate<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoDateSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n /**\n * Type-level ISO time schema (accepts string | Date, outputs string HH:MM:SS).\n */\n export type IsoTime<\n Opts extends ScalarOptions<string, any> | undefined = undefined,\n > = IsoTimeSchema<\n ComputeInput<string | globalThis.Date, Opts>,\n ComputeOutput<string, Opts>\n >;\n\n // =========================================================================\n // Special Types\n // =========================================================================\n\n /**\n * Type-level JSON schema.\n */\n export type Json<\n Opts extends ScalarOptions<JsonInput, any> | undefined = undefined,\n > = JsonSchema<ComputeInput<JsonInput, Opts>, ComputeOutput<JsonValue, Opts>>;\n\n /**\n * Type-level blob schema (Uint8Array or Buffer-like).\n */\n export type Blob<\n Opts extends ScalarOptions<Uint8Array, any> | undefined = undefined,\n > = BlobSchema<\n ComputeInput<Uint8Array, Opts>,\n ComputeOutput<Uint8Array, Opts>\n >;\n\n /**\n * Type-level vector schema (number array for embeddings).\n */\n export type Vector<\n Opts extends ScalarOptions<number[], any> | undefined = undefined,\n > = VectorSchema<ComputeInput<number[], Opts>, ComputeOutput<number[], Opts>>;\n\n /**\n * Type-level point schema (geographic coordinates).\n */\n export type Point<\n Opts extends ScalarOptions<GeoPoint, any> | undefined = undefined,\n > = PointSchema<ComputeInput<GeoPoint, Opts>, ComputeOutput<GeoPoint, Opts>>;\n\n // =========================================================================\n // Composition Types\n // =========================================================================\n\n /**\n * Type-level object schema.\n * @example V.Object<{ name: V.String; age: V.Number }>\n * @example V.Object<{ name: V.String }, { partial: false }> - All required\n */\n export type Object<\n TEntries,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<TEntries, TOpts>;\n\n /**\n * Type-level omit schema - creates a new object schema with keys removed.\n * @example V.Omit<UserSchema, [\"password\"]> - User without password field\n */\n export type Omit<\n TSchema extends ObjectSchema<any, any>,\n TKeys extends readonly (keyof TSchema[\"entries\"])[] | undefined,\n > = OmittedObjectSchema<\n TSchema[\"entries\"],\n OmitOptions<TSchema[\"options\"], TKeys>,\n TKeys\n >;\n\n /**\n * Type-level from object schema.\n * @example V.FromObject<{ name: V.String }, \"name\"> - Object with name field\n */\n export type FromObject<\n TObject extends Record<string, any>,\n TPath extends string,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<ComputeEntriesFromObject<TObject, TPath>, TOpts>;\n\n export type FromKeys<\n TKeys extends string[],\n TSchema extends VibSchema<any, any>,\n TOpts extends ObjectOptions | undefined = undefined,\n > = ObjectSchema<ComputeEntriesFromKeys<TKeys, TSchema>, TOpts>;\n\n /**\n * Type-level array schema.\n * @example V.Array<V.String> - Array of strings\n */\n export type Array<TItem extends VibSchema<any, any>> = ArraySchema<TItem>;\n\n /**\n * Type-level union schema.\n * @example V.Union<[V.String, V.Number]>\n */\n export type Union<TOptions extends readonly VibSchema<any, any>[]> =\n UnionSchema<TOptions>;\n\n /**\n * Type-level enum schema.\n * @example V.Enum<[\"active\", \"inactive\", \"pending\"]>\n */\n export type Enum<\n TValues extends readonly string[],\n Opts extends ScalarOptions<TValues[number], any> | undefined = undefined,\n > = EnumSchema<\n TValues,\n ComputeInput<TValues[number], Opts>,\n ComputeOutput<TValues[number], Opts>\n >;\n\n /**\n * Type-level literal schema.\n * @example V.Literal<\"active\">\n */\n export type Literal<TValue extends LiteralValue> = LiteralSchema<TValue>;\n\n /**\n * Type-level record schema (dictionary with uniform value type).\n * @example V.Record<V.String, V.Number>\n */\n export type VRecord<\n TKey extends VibSchema<any, string>,\n TValue extends VibSchema<any, any>,\n > = RecordSchema<TKey, TValue>;\n\n // =========================================================================\n // Wrapper Types\n // =========================================================================\n\n /**\n * Type-level optional schema.\n * @example V.Optional<V.String> - string | undefined\n */\n export type Optional<\n TWrapped extends WrappableSchema,\n TDefault = undefined,\n > = OptionalSchema<TWrapped, TDefault>;\n\n /**\n * Type-level nullable schema.\n * @example V.Nullable<V.String> - string | null\n */\n export type Nullable<TWrapped extends VibSchema<any, any>> =\n NullableSchema<TWrapped>;\n\n export type MaybeNullable<\n TWrapped extends VibSchema<any, any>,\n TIsNullable extends boolean,\n > = TIsNullable extends true ? NullableSchema<TWrapped> : TWrapped;\n\n // =========================================================================\n // Transform Types\n // =========================================================================\n\n /**\n * Type-level transform schema.\n * @example V.Transform<string, number> - transforms string input to number output\n */\n export type Transform<TInput, TOutput> = TransformSchema<TInput, TOutput>;\n\n /**\n * Type-level pipe schema for chaining validations.\n * @example V.Pipe<V.String, [TrimAction, LowercaseAction]>\n */\n export type Pipe<\n TSchema extends VibSchema<any, any>,\n TActions extends readonly PipeAction<any, any>[],\n > = PipeSchema<TSchema, TActions>;\n\n export type Coerce<\n TWrapped extends VibSchema<any, any>,\n TOutput,\n > = TransformSchema<InferInput<TWrapped>, TOutput> & { wrapped: TWrapped };\n\n export type ShorthandFilter<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n { equals: TWrapped[\" vibInferred\"][\"1\"] }\n >;\n export type ShorthandUpdate<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n { set: TWrapped[\" vibInferred\"][\"1\"] }\n >;\n export type ShorthandArray<TWrapped extends VibSchema<any, any>> = Coerce<\n TWrapped,\n [TWrapped[\" vibInferred\"][\"1\"]]\n >;\n\n /**\n * Type-level comparison operand that also accepts a field reference of the\n * given scalar type.\n * @example V.FieldRefOr<\"int\", V.Integer>\n */\n export type FieldRefOr<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n > = FieldRefOrSchema<TType, TSchema>;\n\n /**\n * Type-level comparison operand: the value, a field reference of the given\n * scalar type, an SQL fragment, or a callback returning one of the latter two\n * from `TCtx` — the context of the model being filtered.\n * @example V.ComparisonOperand<\"int\", V.Integer, V.OperandCtx<typeof post>>\n */\n export type ComparisonOperand<\n TType extends ScalarType,\n TSchema extends VibSchema<any, any>,\n TCtx extends OperandCtx<any> = OperandCtx<any>,\n > = ComparisonOperandSchema<TType, TSchema, TCtx>;\n\n /**\n * Type-level operand callback context: `{ fields, sql }` keyed to the scalars\n * of the model being filtered.\n */\n export type Operand<TModel> = OperandCtx<TModel>;\n\n /**\n * Type-level re-closing wrapper: same shape as the wrapped schema, but a\n * field reference anywhere inside the parsed value is rejected.\n */\n export type NoFieldRef<TSchema extends VibSchema<any, any>> =\n NoFieldRefSchema<TSchema>;\n\n /**\n * Type-level JSON filter operand that also accepts the named JSON null\n * sentinels (`DbNull` / `JsonNull` / `AnyNull`).\n * @example V.JsonNullOr<\"DbNull\" | \"JsonNull\" | \"AnyNull\", V.Json>\n */\n export type JsonNullOr<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n > = JsonNullOrSchema<TAllowed, TSchema>;\n\n /**\n * Type-level JSON write slot: the sentinels in `TAllowed`, the whole JSON\n * document language, and no bare top-level `null` (Prisma's rule).\n */\n export type JsonWrite<\n TAllowed extends JsonNullKind,\n TSchema extends VibSchema<any, any>,\n > = JsonWriteSchema<TAllowed, TSchema>;\n\n export type SingleOrArray<TWrapped extends VibSchema<any, any>> = V.Union<\n readonly [\n V.Coerce<TWrapped, [TWrapped[\" vibInferred\"][\"1\"]]>,\n V.Array<TWrapped>,\n ]\n >;\n\n // =========================================================================\n // Utility Types\n // =========================================================================\n\n /**\n * Extract input type from a V.* type or VibSchema.\n */\n export type Input<T> = InferInput<T>;\n\n /**\n * Extract output type from a V.* type or VibSchema.\n */\n export type Output<T> = InferOutput<T>;\n\n /**\n * Any VibSchema - useful for generic constraints.\n */\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IAAI,CAMvD,OAFI,GAAkB,IAAQ,EAAmB,EAE1C,EAAG,EAAkB,EAehC,SAAgB,OAGd,EACA,EAGA,CAEA,OAAO,EAAY,SADE,sBAAsB,EAAW,CACX,EAAS,CAClD,aACD,CAAC,CC+BJ,MAAa,EAAI,CAEf,OACA,UACA,UACA,QACA,UACA,QACA,QACA,KAAM,MACN,KAEA,KACA,aACA,QACA,QAEA,KACA,OACA,MAEA,MACA,SACA,cACA,YAEA,SACA,KACA,WAEA,MACA,KACA,gBAAA,UACA,OACA,SAEA,OACA,OAEA,KACA,QAEA,cAEA,gBACA,gBACA,eAGA,kBACA,WACA,WACA,oBAEA,WACA,UAEA,QACD,CAED,IAAA,GAAe"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t,t as n}from"./base-AdXAoy6l.mjs";var ConnectionError=class extends n{static diagnosticName=`ConnectionError`;constructor(e,n){super(e,n?.code??t.CONNECTION_FAILED,n)}},ClientInitializationError=class extends n{static diagnosticName=`ClientInitializationError`;constructor(e,n){super(e,t.CLIENT_INITIALIZATION,n)}};function isClientInitializationError(e){return e instanceof ClientInitializationError}var QueryError=class extends n{static diagnosticName=`QueryError`;constructor(e,n){super(e,n?.code??t.QUERY_FAILED,n)}},NotFoundError=class extends n{static diagnosticName=`NotFoundError`;constructor(e,n,r){super(`No ${e} record found for ${n}`,t.RECORD_NOT_FOUND,{meta:{...r?.meta,model:e,operation:n}})}},NestedWriteError=class extends n{static diagnosticName=`NestedWriteError`;constructor(e,n,r){super(e,r?.code??t.NESTED_WRITE_FAILED,{cause:r?.cause,diagnostics:r?.diagnostics,meta:{...r?.meta,relation:n}})}};const r=`Nested write assertion failed: a batch precondition (e.g. a connect/disconnect target or ownership check) did not hold.`;var NestedWriteAssertionError=class extends n{static diagnosticName=`NestedWriteAssertionError`;constructor(e,n){super(e,t.NESTED_WRITE_ASSERTION_FAILED,n)}},FeatureNotSupportedError=class extends n{static diagnosticName=`FeatureNotSupportedError`;constructor(e,n,r){let i=r?`${e}.${n} is not supported. ${r}`:`${e}.${n} is not supported by this driver.`;super(i,t.FEATURE_NOT_SUPPORTED,{meta:{feature:e,method:n}})}},i=class PendingOperationError extends n{static diagnosticName=`PendingOperationError`;constructor(e,t,n){super(e,t,n)}static alreadyExecutedWithDriver(e,n){return new PendingOperationError(`Cannot await a PendingOperation that was already executed with executeWith(). The ${e}.${n}() operation was already executed in a transaction context. Create a new operation if you need to execute outside the transaction.`,t.OPERATION_ALREADY_EXECUTED,{meta:{model:e,operation:n}})}static alreadyExecutedDefault(e,n){return new PendingOperationError(`Cannot call executeWith() on a PendingOperation that was already awaited. The ${e}.${n}() operation was already executed outside a transaction. Create a new operation for transaction execution.`,t.OPERATION_EXECUTION_CONFLICT,{meta:{model:e,operation:n}})}static differentDriverConflict(e,n){return new PendingOperationError(`Cannot call executeWith() with a different driver. The ${e}.${n}() operation was already executed in another transaction context.`,t.OPERATION_EXECUTION_CONFLICT,{meta:{model:e,operation:n}})}static clientMismatch(e,n){return new PendingOperationError(`Cannot execute ${e}.${n}() in this transaction: the operation was created by a different client instance. All operations in \$transaction([...]) must come from the same client.`,t.OPERATION_CLIENT_MISMATCH,{meta:{model:e,operation:n}})}static scopeMismatch(e,n){return new PendingOperationError(`Cannot execute ${e}.${n}() in this transaction: the operation was created outside this transaction scope. Create the operation from the client provided to this transaction callback.`,t.OPERATION_SCOPE_MISMATCH,{meta:{model:e,operation:n}})}};function isPendingOperationError(e){return e instanceof i}var QueryEngineError=class extends n{static diagnosticName=`QueryEngineError`;constructor(e,n){super(e,n?.code??t.INTERNAL_ERROR,n)}},UnsupportedOperationError=class extends QueryEngineError{static diagnosticName=`UnsupportedOperationError`;constructor(e,n){super(e,{...n,code:t.UNSUPPORTED_OPERATION})}};function isUnsupportedOperationError(e){return e instanceof UnsupportedOperationError}function isNotFoundError(e){return e instanceof NotFoundError}function retainWriteOutcomeFailure(e,t,n=`Query execution and write-outcome publication both failed.`){let r=t instanceof AggregateError?[...t.errors]:[t];return AggregateError([e,...r],n,{cause:e})}const a={literal:()=>{throw new FeatureNotSupportedError(`vector`,`literal`,`Load the pgvector extension.`)},l2:()=>{throw new FeatureNotSupportedError(`vector`,`l2`,`Load the pgvector extension.`)},cosine:()=>{throw new FeatureNotSupportedError(`vector`,`cosine`,`Load the pgvector extension.`)}},o={createManyAndReturn:`createMany`,updateManyAndReturn:`updateMany`,deleteManyAndReturn:`deleteMany`};function publicOperationName(e){return o[e]??e}var ValidationError=class extends n{static diagnosticName=`ValidationError`;issues;source;operation;constructor(e,n,r){let i=n.length===1?[n[0].path,n[0].message].filter(Boolean).join(`: `):`${n.length} validation errors`,a=normalizeSource(e,r?.meta),o=a.kind===`operation`?a.operation:void 0,s=validationSubject(a);super(`Validation failed for ${s}: ${i}`,o?t.VALIDATION_FAILED:t.INVALID_INPUT,{cause:r?.cause,diagnostics:r?.diagnostics,validation:{source:a,issues:n},meta:o?{...r?.meta,operation:o}:{...r?.meta}}),this.issues=n,this.source=a,this.operation=o}};function normalizeSource(e,t){if(typeof e==`string`){let n=typeof t?.model==`string`?t.model:void 0;return Object.freeze({kind:`operation`,operation:publicOperationName(e),...n?{model:n}:{}})}return e.kind===`operation`?Object.freeze({...e,operation:publicOperationName(e.operation)}):Object.freeze({...e})}function validationSubject(e){return e.kind===`operation`?e.model?`${e.model}.${e.operation}`:e.operation:e.kind===`registry`?`schema registry`:e.kind===`schema-builder`?e.builder:`JSON Schema`}function isValidationError(e){return e instanceof ValidationError}export{isUnsupportedOperationError as _,FeatureNotSupportedError as a,NestedWriteError as c,QueryEngineError as d,QueryError as f,isPendingOperationError as g,isNotFoundError as h,ConnectionError as i,NotFoundError as l,isClientInitializationError as m,isValidationError as n,r as o,UnsupportedOperationError as p,ClientInitializationError as r,NestedWriteAssertionError as s,ValidationError as t,i as u,retainWriteOutcomeFailure as v,a as y};
2
- //# sourceMappingURL=validation-Dk9Q_-C7.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"validation-Dk9Q_-C7.mjs","names":[],"sources":["../src/errors/query.ts","../src/errors/validation.ts"],"sourcesContent":["import {\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n type VibORMErrorOptions,\n} from \"./base\";\n\n/**\n * Every code {@link ConnectionError} can carry. `CLIENT_INITIALIZATION` is NOT here — it has\n * its own class ({@link ClientInitializationError}).\n */\nexport type ConnectionErrorCode =\n | typeof VibORMErrorCode.CONNECTION_FAILED\n | typeof VibORMErrorCode.CONNECTION_TIMEOUT\n | typeof VibORMErrorCode.CONNECTION_CLOSED\n | typeof VibORMErrorCode.CONNECTION_CAPACITY;\n\n/**\n * Connection-related errors\n */\nexport class ConnectionError extends VibORMError {\n static override readonly diagnosticName = \"ConnectionError\";\n\n /** Discriminant: one of {@link ConnectionErrorCode}, never a code outside the family. */\n declare readonly code: ConnectionErrorCode;\n\n constructor(\n message: string,\n options?: VibORMErrorOptions & { code?: ConnectionErrorCode | undefined }\n ) {\n super(message, options?.code ?? VibORMErrorCode.CONNECTION_FAILED, options);\n }\n}\n\n/**\n * Client construction failures (Prisma P1012)\n *\n * Raised while a client is being built or while its schema-shaped surface is being resolved:\n * a missing driver, a schema that fails name hydration, or an access to a model the schema\n * does not define. These are configuration faults, not query faults — nothing has reached the\n * database yet.\n *\n * Prisma raises `PrismaClientInitializationError` for the same category and exposes its code\n * on `errorCode`; P1012 is Prisma's \"Schema validation error\", the closest documented code for\n * a client that cannot be constructed from the given schema and configuration. VibORM\n * publishes it through the shared `prismaCode` getter.\n */\nexport class ClientInitializationError extends VibORMError {\n static override readonly diagnosticName = \"ClientInitializationError\";\n\n /** Literal discriminant: this class always carries `CLIENT_INITIALIZATION`. */\n declare readonly code: typeof VibORMErrorCode.CLIENT_INITIALIZATION;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.CLIENT_INITIALIZATION, options);\n }\n}\n\n/**\n * Type guard for client initialization errors\n */\nexport function isClientInitializationError(\n error: unknown\n): error is ClientInitializationError {\n return error instanceof ClientInitializationError;\n}\n\n/**\n * Every code {@link QueryError} can carry.\n *\n * The `V2xxx` query family plus `INVALID_INPUT`, which the raw-SQL helpers raise through this\n * class when a caller hands `$queryRaw` something that is neither a tagged template nor an\n * `Sql` fragment, or a raw/provider parameter boundary refuses an invalid\n * `Date` (`client/raw.ts`, `drivers/provider-parameter-snapshot.ts`) — measured\n * at the construction sites, not assumed.\n */\nexport type QueryErrorCode =\n | typeof VibORMErrorCode.QUERY_FAILED\n | typeof VibORMErrorCode.QUERY_TIMEOUT\n | typeof VibORMErrorCode.QUERY_SYNTAX\n | typeof VibORMErrorCode.QUERY_SCHEMA_MISMATCH\n | typeof VibORMErrorCode.QUERY_OUT_OF_RANGE\n | typeof VibORMErrorCode.QUERY_RESULT_INVALID\n | typeof VibORMErrorCode.INVALID_INPUT;\n\n/**\n * Query execution errors\n */\nexport class QueryError extends VibORMError {\n static override readonly diagnosticName = \"QueryError\";\n\n /** Discriminant: one of {@link QueryErrorCode}, never a code outside the family. */\n declare readonly code: QueryErrorCode;\n\n constructor(\n message: string,\n options?: VibORMErrorOptions & { code?: QueryErrorCode | undefined }\n ) {\n super(message, options?.code ?? VibORMErrorCode.QUERY_FAILED, options);\n }\n}\n\n/**\n * Record not found (for OrThrow operations)\n */\nexport class NotFoundError extends VibORMError {\n static override readonly diagnosticName = \"NotFoundError\";\n\n /** Literal discriminant: this class always carries `RECORD_NOT_FOUND`. */\n declare readonly code: typeof VibORMErrorCode.RECORD_NOT_FOUND;\n\n constructor(\n model: string,\n operation: string,\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(\n `No ${model} record found for ${operation}`,\n VibORMErrorCode.RECORD_NOT_FOUND,\n {\n meta: { ...options?.meta, model, operation },\n }\n );\n }\n}\n\n/**\n * Every code {@link NestedWriteError} can carry.\n *\n * `NESTED_WRITE_ASSERTION_FAILED` is in the union even though\n * {@link NestedWriteAssertionError} owns that code as a class: the un-attributable batch floor\n * (`OperationExecutor.attributeGuardFailure`, `query-engine/batch-error-attribution.ts`)\n * deliberately re-raises the V7006 floor as a `NestedWriteError` so the surfaced error carries\n * the assertion code without claiming the driver-mapped class. Measured at the construction\n * sites; the two are told apart by class, not by code.\n */\nexport type NestedWriteErrorCode =\n | typeof VibORMErrorCode.NESTED_WRITE_FAILED\n | typeof VibORMErrorCode.NESTED_CREATE_FAILED\n | typeof VibORMErrorCode.NESTED_UPDATE_FAILED\n | typeof VibORMErrorCode.NESTED_DELETE_FAILED\n | typeof VibORMErrorCode.NESTED_CONNECT_FAILED\n | typeof VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED;\n\n/**\n * Nested write operation errors\n */\nexport class NestedWriteError extends VibORMError {\n static override readonly diagnosticName = \"NestedWriteError\";\n\n /** Discriminant: one of {@link NestedWriteErrorCode}, never a code outside the family. */\n declare readonly code: NestedWriteErrorCode;\n\n constructor(\n message: string,\n relation: string,\n options?: VibORMErrorOptions & { code?: NestedWriteErrorCode | undefined }\n ) {\n super(message, options?.code ?? VibORMErrorCode.NESTED_WRITE_FAILED, {\n cause: options?.cause,\n diagnostics: options?.diagnostics,\n meta: { ...options?.meta, relation },\n });\n }\n}\n\n/**\n * The batch assertion-abort floor sentence — one home for the three layers that\n * say it: the executor's guard-free-ladder floor, merged-batch attribution's\n * un-attributable floor, and driver error mapping's assertion translation.\n * The wording matches V1's frozen runtime verbatim; edit it nowhere else.\n */\nexport const NESTED_WRITE_ASSERTION_FLOOR_MESSAGE =\n \"Nested write assertion failed: a batch precondition (e.g. a connect/disconnect target or ownership check) did not hold.\";\n\n/**\n * Batch-plan nested-write assertion failures\n *\n * Atomic batch plans encode preconditions (connect/disconnect targets must\n * exist, correlation checks) as SQL statements that error on purpose when the\n * precondition fails (adapter.assertions). Each dialect surfaces a different\n * raw error (PG: division by zero, MySQL/SQLite: invalid JSON); the driver\n * error mapping normalizes all of them to this type.\n */\nexport class NestedWriteAssertionError extends VibORMError {\n static override readonly diagnosticName = \"NestedWriteAssertionError\";\n\n /** Literal discriminant: this class always carries `NESTED_WRITE_ASSERTION_FAILED`. */\n declare readonly code: typeof VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED;\n\n constructor(message: string, options?: VibORMErrorOptions) {\n super(message, VibORMErrorCode.NESTED_WRITE_ASSERTION_FAILED, options);\n }\n}\n\n/**\n * Feature not supported errors\n */\nexport class FeatureNotSupportedError extends VibORMError {\n static override readonly diagnosticName = \"FeatureNotSupportedError\";\n\n /** Literal discriminant: this class always carries `FEATURE_NOT_SUPPORTED`. */\n declare readonly code: typeof VibORMErrorCode.FEATURE_NOT_SUPPORTED;\n\n constructor(feature: string, method: string, suggestion?: string) {\n const message = suggestion\n ? `${feature}.${method} is not supported. ${suggestion}`\n : `${feature}.${method} is not supported by this driver.`;\n super(message, VibORMErrorCode.FEATURE_NOT_SUPPORTED, {\n meta: { feature, method },\n });\n }\n}\n\n/**\n * Pending operation execution errors\n *\n * Thrown when attempting to execute a PendingOperation in an invalid way,\n * such as awaiting after executeWith() or calling executeWith() after await.\n */\n/** Every code {@link PendingOperationError} can carry. */\nexport type PendingOperationErrorCode =\n | typeof VibORMErrorCode.OPERATION_ALREADY_EXECUTED\n | typeof VibORMErrorCode.OPERATION_EXECUTION_CONFLICT\n | typeof VibORMErrorCode.OPERATION_CLIENT_MISMATCH\n | typeof VibORMErrorCode.OPERATION_SCOPE_MISMATCH;\n\nexport class PendingOperationError extends VibORMError {\n static override readonly diagnosticName = \"PendingOperationError\";\n\n /** Discriminant: one of {@link PendingOperationErrorCode}, never a code outside the family. */\n declare readonly code: PendingOperationErrorCode;\n\n // biome-ignore lint/complexity/noUselessConstructor: not a forwarder — it narrows the public signature, restricting `code` to PendingOperationErrorCode and `options` to `{ meta }`; deleting it would widen the constructor back to the base's VibORMErrorCode plus `cause`/`diagnostics`.\n constructor(\n message: string,\n code: PendingOperationErrorCode,\n options?: { meta?: VibORMErrorMeta }\n ) {\n super(message, code, options);\n }\n\n /**\n * Create error for attempting to await after executeWith()\n */\n static alreadyExecutedWithDriver(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n \"Cannot await a PendingOperation that was already executed with executeWith(). \" +\n `The ${model}.${operation}() operation was already executed in a transaction context. ` +\n \"Create a new operation if you need to execute outside the transaction.\",\n VibORMErrorCode.OPERATION_ALREADY_EXECUTED,\n { meta: { model, operation } }\n );\n }\n\n /**\n * Create error for attempting executeWith() after await\n */\n static alreadyExecutedDefault(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n \"Cannot call executeWith() on a PendingOperation that was already awaited. \" +\n `The ${model}.${operation}() operation was already executed outside a transaction. ` +\n \"Create a new operation for transaction execution.\",\n VibORMErrorCode.OPERATION_EXECUTION_CONFLICT,\n { meta: { model, operation } }\n );\n }\n\n /**\n * Create error for attempting executeWith() with a different driver\n */\n static differentDriverConflict(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n \"Cannot call executeWith() with a different driver. \" +\n `The ${model}.${operation}() operation was already executed in another transaction context.`,\n VibORMErrorCode.OPERATION_EXECUTION_CONFLICT,\n { meta: { model, operation } }\n );\n }\n\n /**\n * Create error for operations from different clients in $transaction\n */\n static clientMismatch(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n `Cannot execute ${model}.${operation}() in this transaction: ` +\n \"the operation was created by a different client instance. \" +\n \"All operations in $transaction([...]) must come from the same client.\",\n VibORMErrorCode.OPERATION_CLIENT_MISMATCH,\n { meta: { model, operation } }\n );\n }\n\n /** Create error for mixing root and transaction-bound operation scopes. */\n static scopeMismatch(\n model: string,\n operation: string\n ): PendingOperationError {\n return new PendingOperationError(\n `Cannot execute ${model}.${operation}() in this transaction: ` +\n \"the operation was created outside this transaction scope. \" +\n \"Create the operation from the client provided to this transaction callback.\",\n VibORMErrorCode.OPERATION_SCOPE_MISMATCH,\n { meta: { model, operation } }\n );\n }\n}\n\n/**\n * Type guard for pending operation errors\n */\nexport function isPendingOperationError(\n error: unknown\n): error is PendingOperationError {\n return error instanceof PendingOperationError;\n}\n\n/**\n * Internal query engine error\n */\n/**\n * Every code a {@link QueryEngineError} can carry — its own `INTERNAL_ERROR`, plus the\n * `UNSUPPORTED_OPERATION` its {@link UnsupportedOperationError} subclass narrows to. A wider\n * type here would be a lie about the class; a narrower one would make the subclass's `code`\n * an illegal override.\n */\nexport type QueryEngineErrorCode =\n | typeof VibORMErrorCode.INTERNAL_ERROR\n | typeof VibORMErrorCode.UNSUPPORTED_OPERATION;\n\nexport class QueryEngineError extends VibORMError {\n // Annotated `string` (not the literal) so a subclass may narrow it — the\n // pattern VibORMError itself uses for its subclasses.\n static override readonly diagnosticName: string = \"QueryEngineError\";\n\n /**\n * Discriminant. `INTERNAL_ERROR` for a bare engine error; the\n * {@link UnsupportedOperationError} subclass narrows it to `UNSUPPORTED_OPERATION`, which is\n * why this is the family and not a single literal — a code check alone cannot separate the\n * two, so {@link classifyFailure} separates them by class.\n */\n declare readonly code: QueryEngineErrorCode;\n\n constructor(\n message: string,\n options?: {\n cause?: Error | undefined;\n meta?: VibORMErrorMeta | undefined;\n /** Subclass seam: a distinct taxonomy code (default INTERNAL_ERROR). */\n code?: QueryEngineErrorCode | undefined;\n }\n ) {\n super(message, options?.code ?? VibORMErrorCode.INTERNAL_ERROR, options);\n }\n}\n\n/**\n * A payload SHAPE the query engine deliberately does not express — a documented\n * capability boundary (a compound key or non-literal fold past a proven surface,\n * an inexpressible sub-shape, a parity refusal), NOT an engine crash. Distinct\n * from {@link FeatureNotSupportedError} (a dialect/driver capability gap): this\n * is shape-capability. It extends {@link QueryEngineError} so pre-existing\n * `instanceof QueryEngineError` handling keeps working, but carries its own\n * name and code (`V8003 UNSUPPORTED_OPERATION`) so a deliberate refusal is\n * distinguishable from `V9001 INTERNAL_ERROR` programmatically and in logs.\n * Users can `instanceof UnsupportedOperationError` (exported from the package\n * root) to branch on it.\n */\nexport class UnsupportedOperationError extends QueryEngineError {\n static override readonly diagnosticName = \"UnsupportedOperationError\";\n\n /** Literal discriminant: this class always carries `UNSUPPORTED_OPERATION`. */\n declare readonly code: typeof VibORMErrorCode.UNSUPPORTED_OPERATION;\n\n constructor(\n message: string,\n options?: {\n cause?: Error | undefined;\n meta?: VibORMErrorMeta | undefined;\n }\n ) {\n super(message, {\n ...options,\n code: VibORMErrorCode.UNSUPPORTED_OPERATION,\n });\n }\n}\n\n/**\n * Type guard for unsupported-operation (shape-capability) refusals\n */\nexport function isUnsupportedOperationError(\n error: unknown\n): error is UnsupportedOperationError {\n return error instanceof UnsupportedOperationError;\n}\n\n/**\n * Type guard for not found errors\n */\nexport function isNotFoundError(error: unknown): error is NotFoundError {\n return error instanceof NotFoundError;\n}\n\n/**\n * Keep the execution failure primary while retaining every listener failure.\n *\n * ONE composition for the whole estate, stated at the boundary all three of its\n * consumers already depend on: the client (`client.ts`, `raw.ts`,\n * `array-transaction.ts`), the query engine's deferred operation\n * (`pending-operation.ts`) and the candidate engine's operation context. It is\n * pure — a primary, the listener failures flattened out of the publication\n * owner's aggregate, and the primary again as `cause` — so it belongs beside the\n * query failures it composes rather than inside the extension publication owner\n * that raises one half of it. The candidate engine takes no `@extensions`\n * import anywhere today, and importing that owner would add\n * `src/extensions/query.ts` and `src/query-engine/routed-operations.ts` to\n * `raptor3/shared/operation-context.ts`'s runtime closure (181 → 183). A\n * directory cycle is not what this placement avoids: the engine→extensions\n * runtime edge already exists — `query-engine/pending-operation.ts` holds it\n * for the shipped path — and is pre-existing. A second restatement inside the\n * engine was the duplication FC-05 deleted.\n */\nexport function retainWriteOutcomeFailure(\n primary: unknown,\n outcomeFailure: unknown,\n message = \"Query execution and write-outcome publication both failed.\"\n): AggregateError {\n const suppressed =\n outcomeFailure instanceof AggregateError\n ? [...outcomeFailure.errors]\n : [outcomeFailure];\n return new AggregateError([primary, ...suppressed], message, {\n cause: primary,\n });\n}\n\n/**\n * Unsupported vector operations\n *\n * Use this to override adapter.vector when pgvector is not available.\n */\nexport const unsupportedVector = {\n literal: (): never => {\n throw new FeatureNotSupportedError(\n \"vector\",\n \"literal\",\n \"Load the pgvector extension.\"\n );\n },\n l2: (): never => {\n throw new FeatureNotSupportedError(\n \"vector\",\n \"l2\",\n \"Load the pgvector extension.\"\n );\n },\n cosine: (): never => {\n throw new FeatureNotSupportedError(\n \"vector\",\n \"cosine\",\n \"Load the pgvector extension.\"\n );\n },\n};\n","import type { Operation } from \"../query-engine/types\";\nimport {\n VibORMError,\n VibORMErrorCode,\n type VibORMErrorMeta,\n type VibORMErrorOptions,\n} from \"./base\";\n\n/**\n * Validation issue details\n */\nexport interface ValidationIssue {\n path: string;\n message: string;\n}\n\n/** The boundary that rejected a value. */\nexport type ValidationErrorSource =\n | {\n readonly kind: \"operation\";\n readonly operation: Operation;\n readonly model?: string | undefined;\n }\n | {\n readonly kind: \"registry\";\n readonly model?: string | undefined;\n readonly property?: string | undefined;\n }\n | {\n readonly kind: \"schema-builder\";\n readonly builder: string;\n readonly path: string;\n }\n | {\n readonly kind: \"json-schema\";\n readonly target?: string | undefined;\n readonly schemaType?: string | undefined;\n };\n\n/**\n * The INTERNAL operation names that have no client spelling, mapped to the name\n * a caller can actually type.\n *\n * `createManyAndReturn` / `updateManyAndReturn` / `deleteManyAndReturn` name the\n * row-returning ARM of a bulk write inside the engine (maintainer decision D-1:\n * the public surface is `createMany` / `updateMany` / `deleteMany` with a\n * `select`). The client refuses those names outright — `pending-operation.ts`\n * answers `Unknown operation 'createManyAndReturn'` — so an error that named one\n * would send a caller to fix an operation the same client says does not exist.\n * Every user-facing name goes through {@link publicOperationName}; anything not\n * in this map is already its own public spelling.\n */\nconst PUBLIC_OPERATION_NAME: Readonly<Partial<Record<Operation, Operation>>> = {\n createManyAndReturn: \"createMany\",\n updateManyAndReturn: \"updateMany\",\n deleteManyAndReturn: \"deleteMany\",\n};\n\n/**\n * The client spelling of an operation — identity for every name a caller can\n * type, and the public family name for the three internal row-returning arms.\n */\nexport function publicOperationName(operation: Operation): Operation {\n return PUBLIC_OPERATION_NAME[operation] ?? operation;\n}\n\n/**\n * Input validation errors\n */\nexport class ValidationError extends VibORMError {\n static override readonly diagnosticName = \"ValidationError\";\n\n /** Operation failures use V4001; other validation boundaries use V4002. */\n declare readonly code:\n | typeof VibORMErrorCode.VALIDATION_FAILED\n | typeof VibORMErrorCode.INVALID_INPUT;\n\n /** Validation issues */\n readonly issues: ValidationIssue[];\n /** Boundary that rejected the value. */\n readonly source: ValidationErrorSource;\n /**\n * Operation that failed validation, in its CLIENT spelling — a bulk write\n * validated through its internal row-returning arm still reports the family\n * name the caller used (see {@link publicOperationName}).\n */\n readonly operation?: Operation | undefined;\n\n constructor(\n sourceOrOperation: Operation | ValidationErrorSource,\n issues: ValidationIssue[],\n options?: VibORMErrorOptions\n ) {\n const issuesSummary =\n issues.length === 1\n ? [issues[0]!.path, issues[0]!.message].filter(Boolean).join(\": \")\n : `${issues.length} validation errors`;\n const source = normalizeSource(sourceOrOperation, options?.meta);\n const operation =\n source.kind === \"operation\" ? source.operation : undefined;\n const subject = validationSubject(source);\n super(\n `Validation failed for ${subject}: ${issuesSummary}`,\n operation\n ? VibORMErrorCode.VALIDATION_FAILED\n : VibORMErrorCode.INVALID_INPUT,\n {\n cause: options?.cause,\n diagnostics: options?.diagnostics,\n validation: { source, issues },\n meta: operation\n ? { ...options?.meta, operation }\n : { ...options?.meta },\n }\n );\n this.issues = issues;\n this.source = source;\n this.operation = operation;\n }\n}\n\nfunction normalizeSource(\n sourceOrOperation: Operation | ValidationErrorSource,\n meta: VibORMErrorMeta | undefined\n): ValidationErrorSource {\n if (typeof sourceOrOperation === \"string\") {\n const model = typeof meta?.model === \"string\" ? meta.model : undefined;\n return Object.freeze({\n kind: \"operation\",\n operation: publicOperationName(sourceOrOperation),\n ...(model ? { model } : {}),\n });\n }\n\n if (sourceOrOperation.kind === \"operation\") {\n return Object.freeze({\n ...sourceOrOperation,\n operation: publicOperationName(sourceOrOperation.operation),\n });\n }\n\n return Object.freeze({ ...sourceOrOperation });\n}\n\nfunction validationSubject(source: ValidationErrorSource): string {\n if (source.kind === \"operation\")\n return source.model\n ? `${source.model}.${source.operation}`\n : source.operation;\n if (source.kind === \"registry\") return \"schema registry\";\n if (source.kind === \"schema-builder\") return source.builder;\n return \"JSON Schema\";\n}\n\n/**\n * Type guard for validation errors\n */\nexport function isValidationError(error: unknown): error is ValidationError {\n return error instanceof ValidationError;\n}\n"],"mappings":"wFAoBA,IAAa,gBAAb,cAAqC,CAAY,CAC/C,OAAyB,eAAiB,kBAK1C,YACE,EACA,EACA,CACA,MAAM,EAAS,GAAS,MAAQ,EAAgB,kBAAmB,EAAQ,GAiBlE,0BAAb,cAA+C,CAAY,CACzD,OAAyB,eAAiB,4BAK1C,YAAY,EAAiB,EAA8B,CACzD,MAAM,EAAS,EAAgB,sBAAuB,EAAQ,GAOlE,SAAgB,4BACd,EACoC,CACpC,OAAO,aAAiB,0BAwB1B,IAAa,WAAb,cAAgC,CAAY,CAC1C,OAAyB,eAAiB,aAK1C,YACE,EACA,EACA,CACA,MAAM,EAAS,GAAS,MAAQ,EAAgB,aAAc,EAAQ,GAO7D,cAAb,cAAmC,CAAY,CAC7C,OAAyB,eAAiB,gBAK1C,YACE,EACA,EACA,EACA,CACA,MACE,MAAM,EAAM,oBAAoB,IAChC,EAAgB,iBAChB,CACE,KAAM,CAAE,GAAG,GAAS,KAAM,QAAO,YAAW,CAC7C,CACF,GAyBQ,iBAAb,cAAsC,CAAY,CAChD,OAAyB,eAAiB,mBAK1C,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,GAAS,MAAQ,EAAgB,oBAAqB,CACnE,MAAO,GAAS,MAChB,YAAa,GAAS,YACtB,KAAM,CAAE,GAAG,GAAS,KAAM,WAAU,CACrC,CAAC,GAUN,MAAa,EACX,0HAWF,IAAa,0BAAb,cAA+C,CAAY,CACzD,OAAyB,eAAiB,4BAK1C,YAAY,EAAiB,EAA8B,CACzD,MAAM,EAAS,EAAgB,8BAA+B,EAAQ,GAO7D,yBAAb,cAA8C,CAAY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CAC9B,KAAM,EACF,CAAE,GAAG,GAAS,KAAM,YAAW,CAC/B,CAAE,GAAG,GAAS,KAAM,CACzB,CACF,CACD,KAAK,OAAS,EACd,KAAK,OAAS,EACd,KAAK,UAAY,IAIrB,SAAS,gBACP,EACA,EACuB,CACvB,GAAI,OAAO,GAAsB,SAAU,CACzC,IAAM,EAAQ,OAAO,GAAM,OAAU,SAAW,EAAK,MAAQ,IAAA,GAC7D,OAAO,OAAO,OAAO,CACnB,KAAM,YACN,UAAW,oBAAoB,EAAkB,CACjD,GAAI,EAAQ,CAAE,QAAO,CAAG,EAAE,CAC3B,CAAC,CAUJ,OAPI,EAAkB,OAAS,YACtB,OAAO,OAAO,CACnB,GAAG,EACH,UAAW,oBAAoB,EAAkB,UAAU,CAC5D,CAAC,CAGG,OAAO,OAAO,CAAE,GAAG,EAAmB,CAAC,CAGhD,SAAS,kBAAkB,EAAuC,CAOhE,OANI,EAAO,OAAS,YACX,EAAO,MACV,GAAG,EAAO,MAAM,GAAG,EAAO,YAC1B,EAAO,UACT,EAAO,OAAS,WAAmB,kBACnC,EAAO,OAAS,iBAAyB,EAAO,QAC7C,cAMT,SAAgB,kBAAkB,EAA0C,CAC1E,OAAO,aAAiB"}
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{i as t,o as n}from"./value-guards-CK9guf2Z.mjs";import{G as r,Y as i,Z as a}from"./geo-point-codec-lhxH42SK.mjs";const o=` vibInferred`,isPromiseLike=e=>n(e)&&`then`in e&&t(e.then),s={issues:[{message:`Async validation is not supported`}]},c={issues:[{message:`Schema returned a malformed validation result`}]};function parse(e,t,o){try{let a=r(o?.allIssues===!0,()=>e[`~standard`].validate(t));if(isPromiseLike(a))return i(a),s;if(!n(a))return c;let l=Reflect.get(a,`issues`);return l===void 0?`value`in a?{value:Reflect.get(a,`value`)}:c:Array.isArray(l)?{issues:l}:c}catch(e){return a(e)}}export{o as n,parse as t};
2
- //# sourceMappingURL=validation-PF9-_nKd.mjs.map
@@ -1,2 +0,0 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{_ as t}from"./terminal-C8cq1WWX.mjs";import{t as n}from"./identifier-hQCs8M1n.mjs";import{c as r,f as i,m as a,n as o,t as s,v as c}from"./registration-preflight-DEjv050M.mjs";import{J as l,P as u,ot as d,tt as f}from"./geo-point-codec-lhxH42SK.mjs";import{n as p,o as m}from"./native-types-veeTk36s.mjs";import{a as h,n as g,r as _,t as v}from"./physical-6V_LNU3L.mjs";function generateJunctionTableName(e,t){let n=[e.toLowerCase(),t.toLowerCase()].sort();return`${n[0]}_${n[1]}`}function generateJunctionFieldName(e){return`${e.toLowerCase()}Id`}var JunctionPhysicalNameError=class extends Error{kind;constructor(e,t){super(t),this.name=`JunctionPhysicalNameError`,this.kind=e}};function automaticForeignKeyIndexName(e,t,n){let r=`${e}_${t.join(`_`)}_idx`,i=n.has(r)?`${e}_${t.join(`_`)}_fkey_idx`:r;return n.has(i)?void 0:i}function getJunctionConstraintName(e,t,r){let i=`${e}_${t.token}_${r}`;if(!n(i))throw new JunctionPhysicalNameError(`invalidIdentifier`,`Generated junction ${r} name '${i}' is not a valid SQL identifier.`);return i}function expandJunctionFieldGroups(e,t,r,i,a,o){if(a.length===0)throw Error(`Model '${e}' has no primary key; a junction side requires a complete row key.`);if(o.length===0)throw Error(`Model '${t}' has no primary key; a junction side requires a complete row key.`);for(let e of[r,i])if(!n(e))throw new JunctionPhysicalNameError(`invalidIdentifier`,`Junction side prefix '${e}' is not a valid SQL identifier.`);let s=junctionFieldGroup(r,a.length),c=junctionFieldGroup(i,o.length),l=new Map;for(let e of[...s.fields,...c.fields]){if(!n(e))throw new JunctionPhysicalNameError(`invalidIdentifier`,`Expanded junction field '${e}' is not a valid SQL identifier.`);let t=e.toLowerCase(),r=l.get(t);if(r!==void 0)throw new JunctionPhysicalNameError(`collision`,`Junction fields '${r}' and '${e}' collide after compound-prefix expansion.`);l.set(t,e)}return{source:s,target:c}}function junctionSourceSideIsFirst(e,t,n,r){let i=e.toLowerCase(),a=n.toLowerCase();return i===a?t.join(`\0`)<=r.join(`\0`):i<a}function junctionFieldGroup(e,t){return{token:e,fields:t===1?[e]:Array.from({length:t},(t,n)=>`${e}_${n+1}`)}}function resolveOrdinaryJunctionNames(e){let t=e.overrides,n=e.sourceModelName===e.targetModelName,r=generateJunctionTableName(e.sourceModelName,e.targetModelName);return{table:t?.table??(e.pairName?`${r}_${e.pairName}`:r),sourceToken:t?.source??defaultSideToken(n,e.sourceField,e.sourceModelName,e.sourceRowKeyIsCompound),targetToken:t?.target??defaultSideToken(n,e.targetField,e.targetModelName,e.targetRowKeyIsCompound)}}function defaultSideToken(e,t,n,r){return e?r?t:`${t}Id`:r?n.toLowerCase():generateJunctionFieldName(n)}const y=new WeakMap;function getModelKeyCatalog(e){let t=y.get(e);if(t)return t;let n=buildModelKeyCatalog(e);return y.set(e,n),n}function findAddressableKey(e,t){for(let n of getModelKeyCatalog(e).addressableKeys)if((n.name??n.fields[0])===t)return n}const b=[`AND`,`OR`,`NOT`];function getAmbiguousPublicSelectorNames(e){let t=e[`~`].state,n=new Set([...Object.keys(t.shape),...b]),r=new Set,i=[...Object.keys(t.compoundId??{}),...Object.keys(t.compoundUniques??{})];for(let e of i)n.has(e)&&r.add(e),n.add(e);return[...r]}function findReferenceableKey(e,t){let n;for(let r of getModelKeyCatalog(e).referenceableKeys)if(!(r.length!==t.length||!r.every(e=>t.includes(e)))){if(r.every((e,n)=>e===t[n]))return r;n??=r}return n}function buildModelKeyCatalog(e){let t=e[`~`].state,n=[],r;for(let e of Object.keys(t.uniques)){let i=t.scalars[e]?.[`~`].state.isId===!0,a=i?{kind:`primary`,fields:[e]}:{kind:`unique`,fields:[e]};i&&!r&&(r=a),n.push(a)}let i=t.compoundId??{},a,o=!0;for(let[e,t]of Object.entries(i)){let r={kind:`primary`,name:e,fields:Object.keys(t.entries)};o&&(o=!1,e&&r.fields.length>0&&(a=r)),n.push(r)}let s=t.compoundUniques??{};for(let[e,t]of Object.entries(s))n.push({kind:`compoundUnique`,name:e,fields:Object.keys(t.entries)});let l=new Set(Object.keys(t.uniques));for(let e of Object.values(i))for(let t of Object.keys(e.entries))l.add(t);for(let e of Object.values(s))for(let t of Object.keys(e.entries))l.add(t);let u=[...n.map(e=>e.fields),...t.indexes.filter(e=>e.options.unique&&c(e.options)).map(e=>e.fields)];return{rowKey:a??r,addressableKeys:n,referenceableKeys:u,uniqueOverlapFields:[...l]}}function resolveJunctionTopology(e){let t=expandJunctionFieldGroups(e.source.modelName,e.target.modelName,e.source.token,e.target.token,e.source.rowKey,e.target.rowKey);return deriveJunctionTopology({table:e.table,source:sideFacts(e.source,t.source),target:sideFacts(e.target,t.target),pairName:e.pairName})}function resolveVariantMemberNames(e){return e.junction?{table:e.junction.table,sourceToken:e.junction.source,targetToken:e.junction.target}:{table:`${e.ownerTableName}_${e.relationField}_${e.publicType}`,sourceToken:e.ownerRowKeyIsCompound?e.ownerModelName.toLowerCase():generateJunctionFieldName(e.ownerModelName),targetToken:e.targetRowKeyIsCompound?e.publicType.toLowerCase():generateJunctionFieldName(e.publicType)}}function sideFacts(e,t){return{...e,token:t.token,fields:t.fields}}function deriveJunctionTopology(e){let{table:t,source:n,target:r,pairName:i}=e,a=junctionSourceSideIsFirst(n.modelName,n.fields,r.modelName,r.fields),o=a?r:n,s,c,l,u;return{table:t,source:resolveSide(n),target:resolveSide(r),sourceIsFirst:a,pairName:i,foreignKeyName(e){if(n.token===r.token)throw new JunctionPhysicalNameError(`collision`,`Junction sides of '${t}' share naming token '${n.token}' and would derive the same foreign-key constraint name.`);return e===`source`?(s??=getJunctionConstraintName(t,n,`fkey`),s):(c??=getJunctionConstraintName(t,r,`fkey`),c)},reverseIndexName(){return l??=getJunctionConstraintName(t,o,`idx`),l},uniqueTargetName(){return u??=getJunctionConstraintName(t,r,`key`),u}}}function resolveSide({fields:e,rowKey:t,...n}){return{...n,members:t.map((t,n)=>({junctionField:e[n],referencedField:t}))}}function checkStoredReference(e){let{modelName:t,model:n,relationName:r,targetName:i,target:a}=e,{fields:o,references:s,onDelete:c,onUpdate:l}=e.foreignKey,d=[],f=n[`~`].state.scalars,p=a[`~`].state.scalars,m=[],h=!0;for(let[e,n]of o.entries()){let a=f[n];if(!a){h=!1,d.push(fk001(t,r,n));continue}if(isDecimalList(a)){h=!1,d.push(fk010(t,r,n));continue}a[`~`].state.type===`point`&&(h=!1,d.push(fk011(t,r,n))),a[`~`].state.nullable&&m.push(n);let o=s[e],c=p[o];if(!c){h=!1,d.push(fk002(t,r,i,o));continue}let l=a[`~`].state,g=c[`~`].state,_=l.type,y=g.type,b=l.array===!0,x=g.array===!0,S=l.decimal,C=g.decimal,w=_===y&&b!==x,T=_===`decimal`&&y===`decimal`&&!u(S,C),E=_===`datetime`&&!b?v(a[`~`].nativeType):void 0,D=y===`datetime`&&!x?v(c[`~`].nativeType):void 0,O=E!==void 0&&D!==void 0&&E!==D;(_!==y||w||T||O)&&(h=!1,d.push(fk003({modelName:t,relationName:r,targetName:i,foreignField:n,referencedField:o,localState:l,remoteState:g,localDateTimeForm:E,remoteDateTimeForm:D,arrayShapeMismatch:w,decimalDomainMismatch:T,dateTimeDomainMismatch:O})))}let g=findReferenceableKey(a,s);if(g||(h=!1,d.push(fk005(t,r,i,s))),c===`setNull`||l===`setNull`)for(let e of o){let n=f[e];n&&!n[`~`].state.nullable&&(h=!1,d.push(ra004(t,r,e)))}c===`cascade`&&m.length===0&&d.push(ra003(t,r));let _=o.map((e,t)=>({foreignField:e,referencedField:s[t]}));g&&_.sort((e,t)=>g.indexOf(e.referencedField)-g.indexOf(t.referencedField));let[y,...b]=_;return{reference:h&&y?{members:[y,...b],...c?{onDelete:c}:{},...l?{onUpdate:l}:{}}:void 0,issues:d,nullableForeignFields:m}}function isDecimalList(e){let t=e[`~`].state;return t.type===`decimal`&&t.array===!0}function fk001(e,t,n){return{code:`FK001`,message:`FK '${n}' in '${t}' not in '${e}'`,severity:`error`,model:e,relation:t,field:n,repair:`Declare a scalar '${n}' on '${e}' or name an existing one in .fields(...)`}}function fk010(e,t,n){return{code:`FK010`,message:`FK '${n}' in '${t}' is a fixed-decimal list, which cannot be a foreign-key member`,severity:`error`,model:e,relation:t,field:n,repair:`Store the reference in a scalar decimal (or another scalar type) on '${e}'`}}function fk011(e,t,n){return{code:`FK011`,message:`FK '${n}' in '${t}' is a GeoPoint, which cannot be a foreign-key member`,severity:`error`,model:e,relation:t,field:n,repair:`Store relation identity in a portable scalar key on '${e}'`}}function fk002(e,t,n,r){return{code:`FK002`,message:`Reference '${r}' not in '${n}'`,severity:`error`,model:e,relation:t,field:r,repair:`Reference a scalar declared on '${n}'`}}function describeMember(e,t){return e.array===!0?`${e.type}[]`:e.type===`decimal`&&e.decimal?`decimal(${e.decimal.precision},${e.decimal.scale})`:t?`datetime(${t})`:e.type}function fk003(e){let{foreignField:t,referencedField:n,targetName:r}=e,i=describeMember(e.localState,e.localDateTimeForm),a=describeMember(e.remoteState,e.remoteDateTimeForm),o=e.decimalDomainMismatch?`decimal precision and scale`:e.arrayShapeMismatch?`scalar/list shape`:e.dateTimeDomainMismatch?`SQLite DateTime physical form`:`scalar type`;return{code:`FK003`,message:`Type mismatch: '${t}' (${i}) → '${n}' (${a}) in ${r}`,severity:`error`,model:e.modelName,relation:e.relationName,repair:`Give '${t}' the same ${o} as '${r}.${n}'`}}function fk005(e,t,n,r){return{code:`FK005`,message:`[${r.join(`, `)}] in '${n}' should be unique/ID`,severity:`error`,model:e,relation:t,repair:`Declare the referenced tuple on '${n}' with .id(), .unique(), or a compound key`}}function ra004(e,t,n){return{code:`RA004`,message:`SET NULL on '${t}' but '${n}' not nullable`,severity:`error`,model:e,relation:t,repair:`Make '${n}' .nullable() or choose another referential action`}}function ra003(e,t){return{code:`RA003`,message:`CASCADE on required '${t}' may cause data loss`,severity:`warning`,model:e,relation:t}}function getRelationValues(e){return Object.values(e[`~`].state.relations)}function getScalars(e){return Object.entries(e[`~`].state.scalars)}const x=new Set([`string`,`int`,`bigint`,`decimal`]);function issue(e,t,n,r,i){return{code:e,message:t,severity:`error`,model:n,relation:r,repair:i}}function collectReservedPhysicalNames(e){let t=new Set;for(let[n,r]of e.schema){let i=r[`~`].state.tableName??n;for(let e of r[`~`].state.indexes)t.add(e.options.name??`${i}_${e.fields.join(`_`)}_idx`);let a=getScalars(r);(a.some(([,e])=>e[`~`].state.isId)||r[`~`].state.compoundId)&&t.add(`${i}_pkey`);for(let[e,n]of a)if(n[`~`].state.isUnique&&!n[`~`].state.isId){let r=n[`~`].state.columnName??e;t.add(`${i}_${r}_key`)}for(let e of Object.keys(r[`~`].state.compoundUniques??{}))t.add(`${i}_${e}_key`);for(let n of automaticForeignKeyIndexNames(r,i,e.storedReferences))t.add(n)}for(let n of e.ctx.tableToModels.keys())t.add(n);for(let n of e.junctionNames)t.add(n);return t}function automaticForeignKeyIndexNames(e,t,n){let r=e[`~`].state,columnName=e=>r.scalars[e]?.[`~`].state.columnName??e,i=getScalars(e).filter(([,e])=>e[`~`].state.isId).map(([e])=>columnName(e)),a=r.compoundId??{},[o]=Object.values(a);o&&i.push(...Object.keys(o.entries).map(columnName));let s=getScalars(e).filter(([,e])=>e[`~`].state.isUnique).map(([e])=>[columnName(e)]);if(r.compoundUniques)for(let e of Object.keys(r.compoundUniques)){let t=r.compoundUniques[e];t?.entries&&s.push(Object.keys(t.entries).map(columnName))}let c=r.indexes.map(e=>{let n=e.options.name;return{name:typeof n==`string`?n:`${t}_${e.fields.join(`_`)}_idx`,columns:e.fields.map(columnName),where:e.options.where}}),l=n.filter(t=>t.owner===e),u=[i,...s,...l.filter(e=>e.unique).map(e=>e.fields.map(columnName)),...c.filter(e=>!e.where).map(e=>e.columns)],d=new Set(c.map(e=>e.name)),f=[];for(let e of l){if(e.unique)continue;let n=e.fields.map(columnName);if(u.some(e=>n.every((t,n)=>e[n]===t)))continue;let r=automaticForeignKeyIndexName(t,n,d);r!==void 0&&(d.add(r),f.push(r))}return f}function checkVariantRowStorage(e){let{modelName:t,relationName:r}=e,i=[],a=`${r}_type`,s=`${r}_id`,c=`${e.ownerTable}_${r}_poly_idx`,l=n(a)&&n(s)&&n(c)&&!e.reservedColumns.has(a)&&!e.reservedColumns.has(s)&&!e.reservedIndexes.has(c)&&e.indexNameCounts.get(c)===1;l||i.push(issue(`P008`,`Variant relation '${r}' in '${t}' has invalid or colliding generated storage names`,t,r,`Rename the relation field or .map() the owner table so '${a}', '${s}' and '${c}' are free`)),e.reservedColumns.add(a),e.reservedColumns.add(s),e.reservedIndexes.add(c);let u=new Map,d=[];for(let n of e.members){let e=singlePrimaryKey(n.target);if(!e){i.push(issue(`P009`,`Variant '${n.variant}' in '${t}.${r}' requires one scalar primary key`,t,r,`Give the '${n.variant}' target a single scalar .id() field`));continue}u.set(n.variant,e.field),d.push({model:n.target,field:e.field,scalar:e.scalar})}let f=d[0],p=f!==void 0&&d.every(e=>hasCompatibleVariantIdentity(f.scalar,e.scalar));d.length>0&&!p&&i.push(issue(`P002`,`Variant targets in '${t}.${r}' require one compatible portable primary-key representation`,t,r,`Give every variant target the same portable scalar id representation: one shared string, int, or bigint type, or decimal IDs with identical precision and scale`));let m=l&&p&&u.size===e.members.length,h=e.optional;return{storage:m&&f?{typeColumn:{name:a,scalar:o(),nullable:h},idColumn:{name:s,scalar:f.scalar,nullable:h,reference:{model:f.model,field:f.field}},indexName:c}:void 0,referencedFields:u,issues:i}}function hasCompatibleVariantIdentity(e,t){let n=e[`~`].state,r=t[`~`].state;if(!x.has(r.type)||r.array===!0||t[`~`].nativeType!==void 0||r.type!==n.type)return!1;if(r.type!==`decimal`)return!0;let i=n.decimal,a=r.decimal;return i!==void 0&&a!==void 0&&u(a,i)}function variantRowIndexName(e,t){return`${e}_${t}_poly_idx`}function singlePrimaryKey(e){if(e[`~`].state.compoundId&&Object.keys(e[`~`].state.compoundId).length>0)return;let t=getScalars(e).filter(([,e])=>e[`~`].state.isId);if(t.length!==1)return;let[n,r]=t[0];return{field:n,scalar:r}}function checkVariantMemberJunctions(e){let{modelName:t,relationName:r}=e,i=[],o=new Map,s=getModelKeyCatalog(e.model).rowKey?.fields;if(!s?.length)return i.push(issue(`P018`,`Variant relation '${r}' in '${t}' requires a complete owner row key for its member junctions`,t,r,`Declare a primary key on '${t}'`)),{topologies:o,issues:i};for(let c of e.members){let l=getModelKeyCatalog(c.target).rowKey?.fields;if(!l?.length){i.push(issue(`P009`,`Variant '${c.variant}' in '${t}.${r}' requires a complete row key`,t,r,`Declare a primary key on '${c.targetName}'`));continue}let u=resolveVariantMemberNames({ownerTableName:e.ownerTable,ownerModelName:t,relationField:r,publicType:c.variant,ownerRowKeyIsCompound:s.length>1,targetRowKeyIsCompound:l.length>1,junction:c.junction});try{let a=resolveJunctionTopology({table:u.table,source:{model:e.model,modelName:t,rowKey:s,token:u.sourceToken},target:{model:c.target,modelName:c.targetName,rowKey:l,token:u.targetToken},pairName:`${t}.${r}.${c.variant}`}),d=a.foreignKeyName(`source`),f=a.foreignKeyName(`target`),p=a.reverseIndexName(),m=a.uniqueTargetName(),h=[u.table,p].find(t=>!n(t)||e.reservedColumns.has(t)||e.reservedIndexes.has(t)||e.memberNameCounts.get(t)>1);if(e.reservedIndexes.add(u.table),e.reservedIndexes.add(d),e.reservedIndexes.add(f),e.reservedIndexes.add(p),e.reservedIndexes.add(m),h!==void 0){i.push(issue(`P019`,`Variant '${c.variant}' in '${t}.${r}' has an invalid or colliding junction name '${h}'`,t,r,`Give this variant an explicit .through({ ${c.variant}: { table, source, target } }) entry`));continue}o.set(c.variant,a)}catch(n){e.reservedIndexes.add(u.table),i.push(issue(`P019`,a(n).message,t,r,`Give this variant an explicit .through({ ${c.variant}: { table, source, target } }) entry`))}}return{topologies:o,issues:i}}function planVariantMemberNames(e){let t=getModelKeyCatalog(e.model).rowKey?.fields,n=getModelKeyCatalog(e.member.target).rowKey?.fields;if(!(t?.length&&n?.length))return;let r=resolveVariantMemberNames({ownerTableName:e.ownerTable,ownerModelName:e.modelName,relationField:e.relationName,publicType:e.member.variant,ownerRowKeyIsCompound:t.length>1,targetRowKeyIsCompound:n.length>1,junction:e.member.junction});try{let i=resolveJunctionTopology({table:r.table,source:{model:e.model,modelName:e.modelName,rowKey:t,token:r.sourceToken},target:{model:e.member.target,modelName:e.member.targetName,rowKey:n,token:r.targetToken},pairName:void 0});return{names:r,claims:[r.table,i.foreignKeyName(`source`),i.foreignKeyName(`target`),i.reverseIndexName()]}}catch{return{names:r,claims:[r.table]}}}function foreignKeyOnDelete(e){if(e.reference.onDelete!==void 0)return e.reference.onDelete;let t=e.owner.source[`~`].state.scalars;return e.reference.members.every(e=>t[e.foreignField]?.[`~`].state.nullable===!0)?`setNull`:`restrict`}function junctionOnDelete(e){return e.onDelete??`cascade`}function*resolvedEdges(e){for(let[t,n]of e)for(let[e,r]of n){if(r.member)continue;let n=r.edge,i=n.kind===`foreignKey`?n.owner:n.kind===`junction`?n.endpoints[0]:n.carrier;i.source===t&&i.field===e&&(yield n)}}const isVariantMember=e=>e.variant!==void 0;function resolveSchemaRelations(e,t,n=!1){let r=[],i=registerModels(e),a=collectSlotNodes(i.models),o=settleTargets(a,i.byIdentity,r);if(o.cause)return{ok:!1,issues:r,cause:o.cause};let s=o.endpoints,c=new Map;for(let e of s){let t=c.get(e.node.slot.source);t?t.push(e):c.set(e.node.slot.source,[e])}let l=new Map,u=new Map;for(let e of s){let t=(c.get(e.target)??[]).filter(t=>t.target===e.node.slot.source&&t.node!==e.node&&!(t.variant!==void 0&&e.variant!==void 0));l.set(e,t),u.set(e,decide(e,t))}reportPairingIssues(s,l,u,r);let d={edges:[],slots:[],storedReferences:[],junctionTables:new Map,junctionNames:[],issues:r};for(let e of s){let t=u.get(e);if(t?.kind!==`paired`)continue;let n=t.partner;if(e.variant!==void 0||n.variant!==void 0||u.get(n)?.kind!==`paired`||e.order>n.order)continue;let r=resolveOrdinaryPair(e,n,d);r&&(d.edges.push(r),d.slots.push({slot:e.node.slot,edge:r},{slot:n.node.slot,edge:r}))}if(reportJunctionTableClaims(d,t,n),n||reportRequiredCycles(d,i.byIdentity),resolveVariantCarriers({schema:e,context:t,nodes:a,endpoints:s,verdicts:u},d),r.some(e=>e.severity===`error`))return{ok:!1,issues:r};let f=buildIndex(i.models,d.slots),p=deriveIdDomains(f,t);return p.issues.length>0?{ok:!1,issues:[...r,...p.issues]}:{ok:!0,index:f,issues:r}}function registerModels(e){let t=new Map,n=new Map;for(let[r,i]of e)t.set(r,i),n.set(i,{model:i,name:r});return{models:t,byIdentity:n}}function collectSlotNodes(e){let t=[],n=0;for(let[r,i]of e){let e=i[`~`].state.relations;for(let[a,o]of Object.entries(e))t.push({slot:{source:i,field:a},modelName:r,field:a,order:n++,state:o[`~`].state,relation:o})}return t}function settleTargets(e,t,n){let r=[],i=0;for(let o of e){if(o.state.target.kind===`model`){let e;try{e=o.relation[`~`].settleTarget()}catch(e){return n.push(thrownTargetIssue(`R006`,o,void 0,e)),{endpoints:r,cause:a(e)}}let s=t.get(e);if(!s){n.push(unregisteredTargetIssue(o));continue}r.push(makeEndpoint(o,void 0,s,i++));continue}let e=settleVariantTargets(o,t,n,r);if(e)return{endpoints:r,cause:e};i=r.length}return{endpoints:r,cause:void 0}}function settleVariantTargets(e,t,n,r){let i=e.state.target,o=r.length;for(let s of Object.keys(i.entries)){let i;try{i=e.relation[`~`].settleTarget(s)}catch(t){return n.push(thrownTargetIssue(`P001`,e,s,t)),a(t)}let c=t.get(i);if(!c){n.push({code:`P001`,message:`Variant '${s}' in '${e.modelName}.${e.field}' is not registered in the schema`,severity:`error`,model:e.modelName,relation:e.field,repair:`Register the '${s}' target model in the schema`});continue}r.push(makeEndpoint(e,s,c,o++))}}function unregisteredTargetIssue(e){return{code:`R006`,message:`'${e.field}' in '${e.modelName}' targets a model that is not registered in the schema`,severity:`error`,model:e.modelName,relation:e.field,repair:`Register the target model in the schema passed to the client`}}function makeEndpoint(e,t,n,r){return{node:e,variant:t,target:n.model,targetName:n.name,name:e.state.name,cardinality:e.state.cardinality,order:r}}function thrownTargetIssue(e,t,n,r){return{code:e,message:`Target getter for ${n?`variant '${n}' of `:``}'${t.modelName}.${t.field}' threw: ${a(r).message}`,severity:`error`,model:t.modelName,relation:t.field,repair:`Make the target getter return a registered model without throwing`}}function decide(e,t){let n=matching(e,t),[r]=n;return r&&n.length===1?{kind:`paired`,partner:r}:n.length>1?{kind:`ambiguous`}:t.length===0||e.variant!==void 0?{kind:`missing`}:{kind:`nameMismatch`}}function matching(e,t){return t.filter(t=>t.name===e.name)}function reportPairingIssues(e,t,n,r){for(let i of e){let e=n.get(i),a=t.get(i);if(e?.kind===`missing`){if(i.variant!==void 0)continue;r.push(missingInverseIssue(i));continue}if(e?.kind===`ambiguous`){let e=matching(i,a);r.push(competingInverseIssue(i,e));continue}e?.kind===`nameMismatch`&&(a.filter(e=>n.get(e)?.kind===`nameMismatch`).some(e=>e.order<i.order)||r.push(nameMismatchIssue(i,a)))}}function describe(e){return e.variant===void 0?`'${e.node.modelName}.${e.node.field}'`:`Variant '${e.variant}' of '${e.node.modelName}.${e.node.field}'`}function path(e){return e.variant===void 0?`${e.node.modelName}.${e.node.field}`:`${e.node.modelName}.${e.node.field}.${e.variant}`}function label(e){return e===void 0?`no name`:`'${e}'`}function resolveOrdinaryPair(e,t,n){let r=n.issues,i=[e.node.slot,t.node.slot];if(e.cardinality===`many`&&t.cardinality===`many`)return resolveJunctionEdge(e,t,i,n);for(let n of[e,t])if(n.node.state.junction!==void 0){r.push(misplaced(n,`junction configuration`,`an ordinary junction pair`));return}let a=[e,t].filter(e=>e.node.state.foreignKey!==void 0);if(a.length===2){r.push(doubleOwnerIssue(e,t));return}let o=a[0];if(!o){let[n,i]=[e,t].filter(e=>e.cardinality===`one`),a=n&&!i?n:e;r.push(missingForeignKeyIssue(a));return}let s=o===e?t:e,c=o.node.state.foreignKey,l=checkStoredReference({modelName:o.node.modelName,model:o.node.slot.source,relationName:o.node.field,targetName:s.node.modelName,target:s.node.slot.source,foreignKey:c});r.push(...l.issues);let u=e.cardinality===`one`&&t.cardinality===`one`;if(!u&&declaresUniqueKey(o.node.slot.source,c.fields)){r.push(uniqueCollectionKeyIssue(o,s,c));return}if(l.reference)return n.storedReferences.push({owner:o.node.slot.source,fields:l.reference.members.map(e=>e.foreignField),unique:u}),{kind:`foreignKey`,endpoints:i,owner:o.node.slot,reference:l.reference,unique:u}}function resolveJunctionEdge(e,t,n,r){let i=r.issues,o=[e,t].filter(e=>e.node.state.junction!==void 0);if(o.length===2){i.push({code:`R011`,message:`'${e.node.modelName}.${e.node.field}' and '${t.node.modelName}.${t.node.field}' both configure this junction; exactly one endpoint owns every override`,severity:`error`,model:e.node.modelName,relation:e.node.field,candidates:[path(e),path(t)],repair:`Keep the junction configuration on one endpoint only`});return}let s=o[0],c=s===void 0?void 0:s===e?s.node.state.junction:mirrorOverrides(s.node.state.junction),l=getModelKeyCatalog(e.node.slot.source).rowKey?.fields??[],u=getModelKeyCatalog(t.node.slot.source).rowKey?.fields??[],d=resolveOrdinaryJunctionNames({sourceModelName:e.node.modelName,targetModelName:t.node.modelName,sourceField:e.node.field,targetField:t.node.field,sourceRowKeyIsCompound:l.length>1,targetRowKeyIsCompound:u.length>1,pairName:e.name,overrides:c});claimJunctionTable(r,d.table,e,t);try{let i=resolveJunctionTopology({table:d.table,source:{model:e.node.slot.source,modelName:e.node.modelName,rowKey:l,token:d.sourceToken,...sideActions(c,`source`)},target:{model:t.node.slot.source,modelName:t.node.modelName,rowKey:u,token:d.targetToken,...sideActions(c,`target`)},pairName:e.name});return i.foreignKeyName(`source`),i.foreignKeyName(`target`),r.junctionNames.push(d.table,i.reverseIndexName()),{kind:`junction`,endpoints:n,topology:i}}catch(t){i.push({code:t instanceof JunctionPhysicalNameError&&t.kind===`collision`?`JT003`:`JT002`,message:a(t).message,severity:`error`,model:e.node.modelName,relation:e.node.field,repair:`Give this junction an explicit .through(...) table and distinct .source(...)/.target(...) tokens`});return}}function claimJunctionTable(e,t,n,r){let i=e.junctionTables.get(t),a=`${path(n)}, ${path(r)}`;i?i.push(a):e.junctionTables.set(t,[a])}function reportJunctionTableClaims(e,t,n){for(let[r,i]of e.junctionTables){let a=t.tableToModels.get(r);a&&e.issues.push({code:`JT003`,message:`Junction '${r}' for ${i.join(`; `)} collides with the table of registered model ${a.join(`, `)}`,severity:`error`,candidates:a,repair:`Choose an unoccupied .through(...) table or map the model to a distinct table`}),!(n||i.length<2)&&e.issues.push({code:`JT001`,message:`Junction '${r}' is claimed by more than one relation pair: ${i.join(`; `)}`,severity:`error`,candidates:i,repair:`Give each pair its own .through(...) table or a distinct .name(...)`})}}function reportRequiredCycles(e,t){let n=new Map;for(let e of t.values())n.set(e.name,[]);for(let r of e.edges){if(r.kind!==`foreignKey`)continue;let e=r.owner,i=e.source[`~`].state.scalars;if(!r.reference.members.every(e=>i[e.foreignField]?.[`~`].state.nullable!==!0))continue;let[a,o]=r.endpoints,s=a===e?o:a,c=t.get(e.source)?.name,l=t.get(s.source)?.name;c!==void 0&&l!==void 0&&n.get(c)?.push(l)}let r=new Set,i=new Set,a=new Set,walk=(t,o)=>{if(i.has(t)){let n=[...o.slice(o.indexOf(t)),t],r=[...n].sort().join(`->`);if(a.has(r))return;a.add(r),e.issues.push(requiredCycleIssue(n));return}if(!r.has(t)){r.add(t),i.add(t),o.push(t);for(let e of n.get(t))walk(e,o);i.delete(t),o.pop()}};for(let e of n.keys())r.has(e)||walk(e,[])}function mirrorOverrides(e){return{...e.table===void 0?{}:{table:e.table},...e.target===void 0?{}:{source:e.target},...e.source===void 0?{}:{target:e.source},...e.onDelete===void 0?{}:{onDelete:swapSides(e.onDelete)},...e.onUpdate===void 0?{}:{onUpdate:swapSides(e.onUpdate)}}}function swapSides(e){return{source:e.target,target:e.source}}function sideActions(e,t){let n=e?.onDelete?.[t],r=e?.onUpdate?.[t];return{...n===void 0?{}:{onDelete:n},...r===void 0?{}:{onUpdate:r}}}function misplaced(e,t,n){return{code:`R012`,message:`${describe(e)} declares ${t}, which only ${n} may carry`,severity:`error`,model:e.node.modelName,relation:e.node.field,repair:`Remove ${t} from '${e.node.modelName}.${e.node.field}'`}}function declaresUniqueKey(e,t){return findReferenceableKey(e,t)!==void 0}function resolveVariantCarriers(e,t){let n=[],r=new Map;for(let t of e.nodes){let e=t.state.target;e.kind===`variants`&&(n.push(t),r.set(t,e.entries))}n.length!==0&&resolveCarriers(e,t,n,r)}function resolveCarriers(e,t,n,r){let i=new Map;for(let e of n)i.set(e,[]);for(let t of e.endpoints)isVariantMember(t)&&i.get(t.node).push(t);let a=new Map,o=new Map;for(let[e,t]of i){if(e.state.cardinality===`one`){let t=variantRowIndexName(tableOf(e),e.field);o.set(t,(o.get(t)??0)+1);continue}for(let n of t){let t=planVariantMemberNames({model:e.slot.source,modelName:e.modelName,ownerTable:tableOf(e),relationName:e.field,member:memberInput(r.get(e),n)});for(let e of t?.claims??[])a.set(e,(a.get(e)??0)+1)}}let s=collectReservedPhysicalNames({schema:e.schema,ctx:e.context,junctionNames:t.junctionNames,storedReferences:t.storedReferences});for(let[n,c]of i){let i=new Set(getScalars(n.slot.source).map(([e,t])=>t[`~`].state.columnName??e)),l=bindMembers(c,e,t),u=n.state.cardinality===`one`?resolveRowCarrier({carrier:n,entries:r.get(n),members:c,bound:l,reservedColumns:i,reservedIndexes:s,indexNameCounts:o,publication:t}):resolveMemberJunctionCarrier({carrier:n,entries:r.get(n),members:c,bound:l,reservedColumns:i,reservedIndexes:s,memberNameCounts:a,publication:t});if(u){if(t.edges.push(u),t.slots.push({slot:n.slot,edge:u}),u.kind===`variantRowCarrier`){for(let e of u.members)e.inverse&&t.slots.push({slot:e.inverse,edge:u,member:e});continue}for(let e of u.members)e.inverse&&t.slots.push({slot:e.inverse,edge:u,member:e})}}}function bindMembers(e,t,n){let r=new Map;for(let i of e){let e=t.verdicts.get(i);if(e?.kind!==`paired`)continue;let a=e.partner;if(t.verdicts.get(a)?.kind===`paired`){if(a.node.state.foreignKey!==void 0){n.issues.push(misplaced(a,`a foreign key`,`an ordinary edge's owner`));continue}if(a.node.state.junction!==void 0){n.issues.push(misplaced(a,`junction configuration`,`an ordinary junction pair`));continue}r.set(i.variant,a)}}return r}function resolveRowCarrier(e){let{carrier:t,members:n,bound:r,publication:i}=e,a=new Set([...r.values()].map(e=>e.cardinality));if(a.size>1){i.issues.push({code:`P012`,message:`Variant relation '${t.field}' in '${t.modelName}' cannot mix to-one and to-many inverses; one composite index serves the whole carrier`,severity:`error`,model:t.modelName,relation:t.field,repair:`Give every bound inverse of this carrier the same cardinality`});return}let o=checkVariantRowStorage({modelName:t.modelName,ownerTable:tableOf(t),relationName:t.field,optional:t.state.optional===!0,members:n.map(e=>({variant:e.variant,target:e.target})),reservedColumns:e.reservedColumns,reservedIndexes:e.reservedIndexes,indexNameCounts:e.indexNameCounts});if(i.issues.push(...o.issues),!o.storage)return;let s=e.entries,c=[];for(let e of n){let t=e.variant,n=o.referencedFields.get(t),i=s[t],a=r.get(t);c.push({variant:t,entry:i,targetModel:e.target,referencedField:n,...a?{inverse:a.node.slot}:{}})}let[l,...u]=c;return{kind:`variantRowCarrier`,carrier:t.slot,members:[l,...u],uniqueTarget:a.has(`one`),storage:o.storage}}function resolveMemberJunctionCarrier(e){let{carrier:t,members:n,bound:r,publication:i}=e,a=checkVariantMemberJunctions({modelName:t.modelName,model:t.slot.source,ownerTable:tableOf(t),relationName:t.field,members:n.map(t=>memberInput(e.entries,t)),reservedColumns:e.reservedColumns,reservedIndexes:e.reservedIndexes,memberNameCounts:e.memberNameCounts});i.issues.push(...a.issues);let o=e.entries,s=[];for(let e of n){let t=e.variant,n=a.topologies.get(t),i=o[t];if(!(n&&i))return;let c=r.get(t);s.push({variant:t,entry:i,uniqueTarget:c?.cardinality===`one`,topology:n,...c?{inverse:c.node.slot}:{}})}let[c,...l]=s;if(c)return{kind:`variantJunctionCarrier`,carrier:t.slot,members:[c,...l]}}function memberInput(e,t){return{variant:t.variant,target:t.target,targetName:t.targetName,junction:e[t.variant]?.junction}}function tableOf(e){return e.slot.source[`~`].state.tableName??e.modelName}function buildIndex(e,t){let n=new Map;for(let e of t){let t=n.get(e.slot.source);t?t.set(e.slot.field,e):n.set(e.slot.source,new Map([[e.slot.field,e]]))}let r=new Map;for(let t of e.values()){let e=n.get(t),i=new Map,a=t[`~`].state.relations;for(let t of Object.keys(a)){let n=e?.get(t);n&&i.set(t,n)}r.set(t,i)}return r}function missingInverseIssue(e){return{code:`R002`,message:`'${e.node.modelName}.${e.node.field}' has no inverse relation in '${e.targetName}'`,severity:`error`,model:e.node.modelName,relation:e.node.field,repair:`Declare a slot on '${e.targetName}' whose target is '${e.node.modelName}'`}}function competingInverseIssue(e,t){return{code:`R009`,message:`${describe(e)} has ${t.length} competing inverse candidates in '${e.targetName}'`,severity:`error`,model:e.node.modelName,relation:e.node.field,candidates:t.map(path),repair:`Give each intended pair the same distinct .name(...) on both endpoints`}}function nameMismatchIssue(e,t){return{code:`R010`,message:`${describe(e)} claims relation name ${label(e.name)}, but no candidate in '${e.targetName}' claims the same name`,severity:`error`,model:e.node.modelName,relation:e.node.field,candidates:t.map(path),repair:`Spell the same .name(...) on both endpoints, or omit it on both`}}function doubleOwnerIssue(e,t){return{code:`CM003`,message:`'${e.node.modelName}.${e.node.field}' and '${t.node.modelName}.${t.node.field}' both complete a foreign key; exactly one endpoint owns it`,severity:`error`,model:e.node.modelName,relation:e.node.field,candidates:[path(e),path(t)],repair:`Drop .fields(...).references(...) from one endpoint`}}function missingForeignKeyIssue(e){return{code:`FK004`,message:`'${e.node.modelName}.${e.node.field}' stores no foreign key; one endpoint of this edge must complete .fields(...).references(...)`,severity:`error`,model:e.node.modelName,relation:e.node.field,repair:`Complete .fields(...).references(...) on '${e.node.modelName}.${e.node.field}'`}}function uniqueCollectionKeyIssue(e,t,n){return{code:`FK009`,message:`'${e.node.modelName}.${e.node.field}' stores a unique foreign key, which contradicts the collection '${t.node.modelName}.${t.node.field}' declares`,severity:`error`,model:e.node.modelName,relation:e.node.field,repair:`Drop the unique key on [${n.fields.join(`, `)}], or declare '${t.node.modelName}.${t.node.field}' with s.toOne`}}function requiredCycleIssue(e){return{code:`CM002`,message:`Circular required relations: ${e.join(` → `)}`,severity:`error`,repair:`Make one foreign key in the cycle nullable`}}const S=new WeakMap;function buildReferenceGraph(e){let t=new Map;for(let n of resolvedEdges(e)){if(n.kind!==`foreignKey`)continue;let e=n.owner,r=n.endpoints[0]===e?n.endpoints[1]:n.endpoints[0],i=t.get(e.source);i===void 0&&(i=new Map,t.set(e.source,i));for(let e of n.reference.members){let t=i.get(e.foreignField);t===void 0&&(t=[],i.set(e.foreignField,t)),t.push({model:r.source,field:e.referencedField})}}return t}function declaredDomainOf(e,t){return _(e[`~`].state.scalars[t]?.[`~`].state)}function nameOf(e,t){return e?.modelToName.get(t)??t[`~`].names.ts??`model`}function deriveIdDomains(e,t){let n=new Map,r=[],i=!1;for(let t of e.keys()){for(let e of Object.keys(t[`~`].state.scalars))if(declaredDomainOf(t,e)!==void 0){i=!0;break}if(i)break}return i?deriveDeclaredIdDomains(e,t,n,r):(S.set(e,n),{domains:n,issues:r})}function deriveDeclaredIdDomains(e,t,n,r){let i=buildReferenceGraph(e),a=new Map,o=new Map,s=[],c=0,marker=e=>`${nameOf(t,e.model)}.${e.field}`,publish=(e,t)=>{let r=a.get(e.model);if(r===void 0&&(r=new Map,a.set(e.model,r)),r.set(e.field,t),t!==void 0){let r=n.get(e.model);r===void 0&&(r=new Map,n.set(e.model,r)),r.set(e.field,t)}},settleComponent=e=>{let n,o,s=!1;for(let c of e){let e=marker(c),l=declaredDomainOf(c.model,c.field),u=l===void 0?[]:[{domain:l,from:e}];for(let e of i.get(c.model)?.get(c.field)??[]){let t=a.get(e.model);t?.has(e.field)===!0&&u.push({domain:t.get(e.field),from:marker(e)})}for(let i of u){if(o===void 0){n=i.domain,o=i.from;continue}if(d(n,i.domain))continue;s=!0;let a=i.from===e?o:i.from;r.push({code:`FK012`,message:`'${e}' would hold ${describeIdDomain2(n)} through '${o}' and ${describeIdDomain2(i.domain)} through '${i.from}'. A column stores one identifier domain.`,severity:`error`,model:nameOf(t,c.model),field:c.field,candidates:[o,i.from],repair:l===void 0?`Give every key '${e}' references the same identifier format, prefix and length`:`Declare '${e}' with the same identifier format, prefix and length as '${a}', or declare nothing and let it derive`})}}for(let t of e)publish(t,s?void 0:n)},connect=e=>{let t=c;c+=1;let n=o.get(e.model);n===void 0&&(n=new Map,o.set(e.model,n)),n.set(e.field,t),s.push(e);let r=t;for(let t of i.get(e.model)?.get(e.field)??[]){let e=o.get(t.model)?.get(t.field);e===void 0?r=Math.min(r,connect(t)):a.get(t.model)?.has(t.field)!==!0&&(r=Math.min(r,e))}return r===t&&settleComponent(s.splice(s.indexOf(e))),r},resolve=(e,t)=>(a.get(e)?.has(t)!==!0&&connect({model:e,field:t}),a.get(e)?.get(t));for(let[e,t]of i)for(let n of t.keys())resolve(e,n);for(let[e,n]of i)for(let[i,a]of n){let n=resolve(e,i);if(n===void 0)continue;let o=e[`~`].state.scalars[i]?.[`~`].nativeType;for(let s of a){let a=s.model[`~`].state.scalars[s.field]?.[`~`].nativeType,c=storageDisagreement(n,o,a);if(c===void 0)continue;let l=`${nameOf(t,e)}.${i}`,u=`${nameOf(t,s.model)}.${s.field}`;r.push({code:`FK012`,message:`'${l}' would store ${f(n)} as ${c.own} on ${c.dialect} and the key it references, '${u}', as ${c.theirs}. A foreign key stores its key's values in the key's own physical form.`,severity:`error`,model:nameOf(t,e),field:i,candidates:[l,u],repair:`Give '${l}' the same ${c.dialect} native type as '${u}' (${c.theirs})`})}}for(let n of resolvedEdges(e)){if(n.kind!==`variantRowCarrier`)continue;let e=`${nameOf(t,n.carrier.source)}.${n.carrier.field}`,[i,...a]=n.members,o=resolve(i.targetModel,i.referencedField),s=`${nameOf(t,i.targetModel)}.${i.referencedField}`;for(let i of a){let a=resolve(i.targetModel,i.referencedField);if(d(o,a))continue;let c=`${nameOf(t,i.targetModel)}.${i.referencedField}`;r.push({code:`P002`,message:`The one id column of '${e}' would hold ${describeIdDomain2(o)} through '${s}' and ${describeIdDomain2(a)} through '${c}'. A column stores one identifier domain.`,severity:`error`,model:nameOf(t,n.carrier.source),relation:n.carrier.field,candidates:[s,c],repair:`Give every variant target of '${e}' the same identifier format, prefix and length`}),s=c}}for(let n of e.keys()){let e=n[`~`].state.scalars;for(let i of Object.keys(e)){let a=resolve(n,i);a!==void 0&&refuseUnusableNativeType(n,i,e[i]?.[`~`].nativeType,a,t,r)}}return r.length===0&&S.set(e,n),{domains:n,issues:r}}function refuseUnusableNativeType(e,t,n,r,i,a){for(let o of p){let s=m(n,o);if(s===void 0||h(r,n,o)!==void 0)continue;let c=`${nameOf(i,e)}.${t}`;a.push({code:`F013`,message:`'${c}' holds ${f(r)}, which cannot live in the ${o} column '${s.type}'.`,severity:`error`,model:nameOf(i,e),field:t,repair:`Declare '${c}' with one of: ${g(r.format,o)} — or drop the native type and take the automatic column.`})}}function storageDisagreement(e,t,n){for(let r of p){let i=h(e,t,r),a=h(e,n,r);if(!(i===void 0||a===void 0)&&i.representation!==a.representation)return{dialect:r,own:i.columnType,theirs:a.columnType}}}function describeIdDomain2(e){return e===void 0?`no identifier domain`:f(e)}function idDomainsOf(e){return S.get(e)||deriveIdDomains(e).domains}function idDomainOf(e,t,n){let r=declaredDomainOf(e,t);return r!==void 0||n===void 0?r:idDomainsOf(n).get(e)?.get(t)}function validateFieldNames(e,t){let r=[];for(let i of Object.keys(t[`~`].state.shape))n(i)||r.push({code:`F001`,message:`Field '${i}' in '${e}' is invalid identifier`,severity:`error`,model:e,field:i});return r}function modelHasFields(e,t,n){return Object.keys(n[`~`].state.scalars).length===0?[{code:`M002`,message:`'${t}' must have at least one field`,severity:`error`,model:t}]:[]}function modelNameValid(e,t,r){return n(t)?[]:[{code:`M005`,message:`'${t}' is not a valid identifier`,severity:`error`,model:t}]}function modelMappedNameValid(e,t,r){let i=r[`~`].state.tableName;return i!==void 0&&!n(i)?[{code:`M007`,message:`Mapped table name '${String(i)}' on '${t}' is not a valid identifier`,severity:`error`,model:t}]:[]}function modelNameNotReserved(e,t,n){return t===`then`?[{code:`M006`,message:`Model 'then' conflicts with the client's Promise-assimilation hook; rename the model key and use .map("then") to retain the table name`,severity:`error`,model:t}]:[]}function getCompoundIdFields(e){let t=e[`~`].state.compoundId;if(!t)return[];let n=t;return Object.keys(Object.values(n)[0].entries)}function getCompoundUniques(e){let t=e[`~`].state.compoundUniques;return t?Object.entries(t).map(([e,t])=>({name:e,fields:Object.keys(t.entries)})):[]}function validateFieldsSinglePass(e,i,a){let o=validateFieldNames(i,a),s=0,c=new Map;for(let[e,u]of getScalars(a)){let a=u[`~`].state;a.columnName!==void 0&&!n(a.columnName)&&o.push({code:`F009`,message:`Mapped column name '${String(a.columnName)}' for '${e}' in '${i}' is not a valid identifier`,severity:`error`,model:i,field:e}),a.isId&&s++;let d=a.columnName??e;if(c.has(d)||c.set(d,[]),c.get(d).push(e),a.hasDefault&&a.default!==void 0&&typeof a.default!=`function`&&a.type!==`decimal`){let n=a.type===`json`?t(a.default):void 0;(n===void 0?l(u[`~`].state.base,a.default):n===`JsonNull`||n===`DbNull`&&a.nullable?{value:a.default,issues:void 0}:{issues:[{message:`JSON default names a null this column cannot store`}]}).issues&&o.push({code:`F004`,message:`Default value for '${e}' in '${i}' doesn't match type`,severity:`error`,model:i,field:e})}a.isId&&a.nullable&&o.push({code:`F006`,message:`ID '${e}' in '${i}' cannot be nullable`,severity:`error`,model:i,field:e}),a.isId&&a.array&&o.push({code:`F007`,message:`ID '${e}' in '${i}' cannot be array`,severity:`error`,model:i,field:e}),!a.isId&&(a.autoGenerate?.kind===`increment`||r(a.default))&&o.push({code:`F008`,message:`Generated default on non-key '${e}' in '${i}'; verify generation is intended`,severity:`warning`,model:i,field:e})}let u=Object.keys(a[`~`].state.compoundId??{}).length,d=u>0;s===0&&!d&&o.push({code:`M001`,message:`'${i}' must have an ID field (or use .id() for compound key)`,severity:`error`,model:i}),(s>1||s>0&&d||u>1)&&o.push({code:`F002`,message:`'${i}' has conflicting ID definitions (use either single field .id() or model .id())`,severity:`error`,model:i});for(let[e,t]of c)t.length>1&&o.push({code:`F003`,message:`Column '${e}' used by multiple fields in '${i}': ${t.join(`, `)}`,severity:`error`,model:i});return o}function indexFieldsExist(e,t,n){let r=[],i=new Set(Object.keys(n[`~`].state.scalars));for(let e of n[`~`].state.indexes)for(let n of e.fields)i.has(n)||r.push({code:`I001`,message:`Index field '${n}' not in '${t}'`,severity:`error`,model:t,field:n});return r}function indexNameUnique(e,t,n){let r=new Map;for(let e of n[`~`].state.indexes)e.options.name&&r.set(e.options.name,(r.get(e.options.name)??0)+1);let i=[];for(let[e,n]of r)n>1&&i.push({code:`I002`,message:`Index name '${e}' duplicated in '${t}'`,severity:`error`,model:t});return i}function compoundConstraintsNonEmpty(e,t,n){let r=[],i=getCompoundIdFields(n);n[`~`].state.compoundId&&i.length===0&&r.push({code:`I003`,message:`Compound ID in '${t}' must contain at least one field`,severity:`error`,model:t});let a=getCompoundUniques(n);for(let e of a)e.fields.length===0&&r.push({code:`I003`,message:`Compound unique '${e.name}' in '${t}' must contain at least one field`,severity:`error`,model:t});return r}const C={_count:`relation counts`,_distance:`distance results`};function memberNamesAreNotReserved(e,t,n){let r=n[`~`].state.shape;return Object.entries(C).filter(([e])=>Object.hasOwn(r,e)).map(([e,n])=>({code:`F010`,message:`Model '${t}' declares a member named '${e}'; '${e}' is reserved for ${n}. Rename it, and use .map("${e}") on a renamed scalar to keep its column name.`,severity:`error`,model:t,field:e}))}function publicSelectorNamesAreUnambiguous(e,t,n){return getAmbiguousPublicSelectorNames(n).map(e=>({code:`I006`,message:`Public selector name '${e}' is ambiguous in '${t}'; a compound selector must not reuse a model field, logical filter, or another compound selector name`,severity:`error`,model:t}))}function decimalListsAreNotKeyMembers(t,n,r){let i=r[`~`].state.scalars,a=e(e=>{let t=i[e]?.[`~`].state;return t?.type===`decimal`&&t.array===!0},`isDecimalList`),o=[];for(let e of r[`~`].state.indexes)for(let t of e.fields)o.push({field:t,position:`an index`});for(let e of getCompoundIdFields(r))o.push({field:e,position:`a compound ID`});for(let e of getCompoundUniques(r))for(let t of e.fields)o.push({field:t,position:`unique '${e.name}'`});let s=[];for(let{field:e,position:t}of o)a(e)&&s.push({code:`I004`,message:`'${e}' in '${n}' is a fixed-decimal list, which cannot be a member of ${t}`,severity:`error`,model:n,field:e});return s}function geoPointRolesArePortable(e,t,n){let r=n[`~`].state,isPoint=e=>r.scalars[e]?.[`~`].state.type===`point`,i=[];for(let[e,r]of getScalars(n)){let n=r[`~`].state;n.type===`point`&&(n.isId||n.isUnique)&&i.push({code:`I005`,message:`GeoPoint '${e}' in '${t}' cannot be an ID or unique field`,severity:`error`,model:t,field:e})}for(let e of getCompoundIdFields(n))isPoint(e)&&i.push({code:`I005`,message:`GeoPoint '${e}' in '${t}' cannot be a compound ID member`,severity:`error`,model:t,field:e});for(let e of getCompoundUniques(n))for(let n of e.fields)isPoint(n)&&i.push({code:`I005`,message:`GeoPoint '${n}' in '${t}' cannot be a member of unique '${e.name}'`,severity:`error`,model:t,field:n});for(let e of r.indexes){let n=e.fields.filter(isPoint),a=n.length===1?r.scalars[n[0]]?.[`~`].state:void 0;if(e.fields.length===1&&n.length===1&&a?.nullable===!1&&e.options.type===`spatial`&&e.options.unique===void 0&&e.options.where===void 0||n.length===0&&e.options.type!==`spatial`)continue;let o=n[0]??e.fields[0];i.push({code:`I005`,message:`A spatial index in '${t}' must contain exactly one non-null GeoPoint and cannot be unique or partial`,severity:`error`,model:t,...o?{field:o}:{}})}return i}const w=[modelHasFields,modelNameValid,modelNameNotReserved,modelMappedNameValid,validateFieldsSinglePass,indexFieldsExist,indexNameUnique,compoundConstraintsNonEmpty,publicSelectorNamesAreUnambiguous,memberNamesAreNotReserved,decimalListsAreNotKeyMembers,geoPointRolesArePortable];function noOrphanFkFields(e,t,n){let r=[],i=new Set;for(let e of getRelationValues(n))for(let t of e[`~`].state.foreignKey?.fields??[])i.add(t);let a=new Set(getCompoundIdFields(n));for(let e of getCompoundUniques(n))for(let t of e.fields)a.add(t);for(let[e,o]of getScalars(n))e.endsWith(`Id`)&&!i.has(e)&&!a.has(e)&&!o[`~`].state.isId&&r.push({code:`CM001`,message:`'${e}' in '${t}' looks like FK but no relation uses it`,severity:`warning`,model:t,field:e});return r}const T=/_type$|Type$/;function polymorphicRelationWarning(e,t,n){let r=[],i=Object.keys(n[`~`].state.scalars);for(let e of i){if(!(e.endsWith(`_type`)||e.endsWith(`Type`)))continue;let a=e.replace(T,``),o=i.find(e=>e===`${a}_id`||e===`${a}Id`);o&&(getRelationValues(n).some(e=>e[`~`].state.foreignKey?.fields.includes(o))||r.push({code:`CM004`,message:`'${e}' + '${o}' in '${t}' looks like polymorphic pattern (not type-safe)`,severity:`warning`,model:t,field:e}))}return r}const E=[noOrphanFkFields,polymorphicRelationWarning],D=[...w,...E];function buildContext(e){let t=new Map,n=new Map;for(let[r,i]of e){t.set(i,r);let e=i[`~`].state.tableName??r;n.has(e)||n.set(e,[]),n.get(e).push(r)}return{modelToName:t,tableToModels:n}}var SchemaValidator=class{#e=new Map;#t;register(e,t){let n=this.#e.get(e);if(n){if(n===t)return this.#t=void 0,this;throw validationError([{code:`M003`,message:`Model name '${e}' is duplicated`,severity:`error`,model:e}])}return this.#e.set(e,t),this.#t=void 0,this}registerAll(e){for(let[t,n]of Object.entries(e))this.register(t,n);return this}resolve(){return this.#t??=resolveRegistered(this.#e,buildContext(this.#e)),this.#t}validate(e=D){let t=[],n=[];for(let r of schemaIssues(this.#e,buildContext(this.#e),this.resolve(),e))(r.severity===`error`?t:n).push(r);return{valid:t.length===0,errors:t,warnings:n}}validateOrThrow(e=D){let t=this.validate(e),n=this.resolve();if(t.valid&&n.ok)return n.index;throw validationError(t.errors,n.ok?void 0:n.cause)}};function resolveRegistered(e,t){let n=s(e);return n?{ok:!1,issues:[n]}:resolveSchemaRelations(e,t)}function schemaIssues(e,t,n,r){let i=[];for(let[e,n]of t.tableToModels)n.length>1&&i.push(sharedTableIssue(e,n));for(let e of n.issues)i.push(e);for(let[n,a]of e)for(let o of r){let r;try{r=o(e,n,a,t)}catch(e){throw ruleFailure(o,n,e)}for(let e of r)i.push(e)}return i}function validateSchema(e){return new SchemaValidator().registerAll(e).validate()}function validateSchemaOrThrow(e){validateResolvedSchemaOrThrow(e,D)}function validateResolvedSchemaOrThrow(e,t){return new SchemaValidator().registerAll(e).validateOrThrow(t)}const O=[publicSelectorNamesAreUnambiguous,memberNamesAreNotReserved];function resolveSchemaOrThrow(e){let t=new Map(Object.entries(e)),n=buildContext(t),r=resolveRegistered(t,n),i=schemaIssues(t,n,r,O).filter(e=>e.severity===`error`);if(i.length===0&&r.ok)return r.index;throw validationError(i,r.ok?void 0:r.cause)}function resolveCheckedSchemaOrThrow(e){let t=new Map(Object.entries(e)),n=resolveSchemaRelations(t,buildContext(t),!0);if(n.ok)return n.index;throw validationError(n.issues.filter(e=>e.severity===`error`),n.cause)}function validationError(e,t){return new i(e,t?{cause:t}:void 0)}function sharedTableIssue(e,t){return{code:`M004`,message:`Table name '${e}' used by multiple models: ${t.join(`, `)}`,severity:`error`}}function ruleFailure(e,t,n){let r=n instanceof Error?n.message:String(n);return new i([{code:`S001`,message:`Schema rule '${e.name||`anonymous`}' failed for '${t}': ${r}`,severity:`error`,model:t}],n instanceof Error?{cause:n}:void 0)}export{validateSchemaOrThrow as a,idDomainsOf as c,resolvedEdges as d,findAddressableKey as f,validateSchema as i,foreignKeyOnDelete as l,automaticForeignKeyIndexName as m,resolveSchemaOrThrow as n,D as o,getModelKeyCatalog as p,validateResolvedSchemaOrThrow as r,idDomainOf as s,resolveCheckedSchemaOrThrow as t,junctionOnDelete as u};
2
- //# sourceMappingURL=validator-X9-bwtRo.mjs.map