viborm 1.0.0 → 1.2.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 (300) hide show
  1. package/README.md +4 -3
  2. package/dist/{adapter-namespace-DMhEF6my.mjs → adapter-namespace-DqkJQdrD.mjs} +2 -2
  3. package/dist/{adapter-namespace-DMhEF6my.mjs.map → adapter-namespace-DqkJQdrD.mjs.map} +1 -1
  4. package/dist/adapters.d.mts +1 -1
  5. package/dist/adapters.mjs +1 -1
  6. package/dist/{array-literal-D9FexFqy.mjs → array-literal-BsbbSLw3.mjs} +1 -1
  7. package/dist/{array-literal-D9FexFqy.mjs.map → array-literal-BsbbSLw3.mjs.map} +1 -1
  8. package/dist/base-AdXAoy6l.mjs +2 -0
  9. package/dist/base-AdXAoy6l.mjs.map +1 -0
  10. package/dist/batch-refs-4L8ECdPU.mjs +2 -0
  11. package/dist/batch-refs-4L8ECdPU.mjs.map +1 -0
  12. package/dist/bind-parameter-capacity-CjPgqnmx.mjs +2 -0
  13. package/dist/{bind-parameter-capacity-DzMcIB95.mjs.map → bind-parameter-capacity-CjPgqnmx.mjs.map} +1 -1
  14. package/dist/builder-Ycvq3ETg.mjs +2 -0
  15. package/dist/builder-Ycvq3ETg.mjs.map +1 -0
  16. package/dist/bun-sql.d.mts +19 -2
  17. package/dist/bun-sql.mjs +1 -1
  18. package/dist/bun-sql.mjs.map +1 -1
  19. package/dist/bun-sqlite.d.mts +9 -8
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/bun-sqlite.mjs.map +1 -1
  22. package/dist/cache/cloudflare-kv.d.mts +1 -1
  23. package/dist/cache/cloudflare-kv.mjs +1 -1
  24. package/dist/cache/memory.d.mts +1 -1
  25. package/dist/cache/memory.mjs +1 -1
  26. package/dist/cache/memory.mjs.map +1 -1
  27. package/dist/cache-BO57X0TT.mjs +2 -0
  28. package/dist/cache-BO57X0TT.mjs.map +1 -0
  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 +2 -0
  33. package/dist/canonical-json-rfC2Dg0X.mjs.map +1 -0
  34. package/dist/chain-Dh0FV72b.mjs +2 -0
  35. package/dist/chain-Dh0FV72b.mjs.map +1 -0
  36. package/dist/cli.mjs +5 -6
  37. package/dist/cli.mjs.map +1 -1
  38. package/dist/client-BLiBmykn.mjs +2 -0
  39. package/dist/client-BLiBmykn.mjs.map +1 -0
  40. package/dist/client-CCgfcp5A.mjs +52 -0
  41. package/dist/client-CCgfcp5A.mjs.map +1 -0
  42. package/dist/client-CRBo95D0.d.mts +610 -0
  43. package/dist/client.d.mts +1 -1
  44. package/dist/client.mjs +1 -1
  45. package/dist/{clock-W8H2Khng.mjs → clock-CK41KO7t.mjs} +1 -1
  46. package/dist/{clock-W8H2Khng.mjs.map → clock-CK41KO7t.mjs.map} +1 -1
  47. package/dist/config.d.mts +3 -3
  48. package/dist/config.mjs +1 -1
  49. package/dist/controls-DXgIn4zh.mjs +2 -0
  50. package/dist/controls-DXgIn4zh.mjs.map +1 -0
  51. package/dist/d1.d.mts +1 -1
  52. package/dist/d1.mjs +1 -1
  53. package/dist/d1.mjs.map +1 -1
  54. package/dist/datetime-physical-codec-oIhiYZEP.mjs +2 -0
  55. package/dist/datetime-physical-codec-oIhiYZEP.mjs.map +1 -0
  56. package/dist/driver-B19QlFqn.mjs +2 -0
  57. package/dist/{driver-CRaDT4B7.mjs.map → driver-B19QlFqn.mjs.map} +1 -1
  58. package/dist/driver-BlnKXPFF.mjs +2 -0
  59. package/dist/driver-BlnKXPFF.mjs.map +1 -0
  60. package/dist/driver.d.mts +2 -2
  61. package/dist/driver.mjs +1 -1
  62. package/dist/error-mapping-CnPCv1dm.mjs +2 -0
  63. package/dist/error-mapping-CnPCv1dm.mjs.map +1 -0
  64. package/dist/every-4KE0p2Gw.mjs +2 -0
  65. package/dist/every-4KE0p2Gw.mjs.map +1 -0
  66. package/dist/execution-context-BKR3bgES.mjs +2 -0
  67. package/dist/execution-context-BKR3bgES.mjs.map +1 -0
  68. package/dist/fs-estate-CAhDg7nY.mjs +2 -0
  69. package/dist/fs-estate-CAhDg7nY.mjs.map +1 -0
  70. package/dist/{geo-area-codec-B4DRInvA.mjs → geo-area-codec-1SY9im7O.mjs} +2 -2
  71. package/dist/{geo-area-codec-B4DRInvA.mjs.map → geo-area-codec-1SY9im7O.mjs.map} +1 -1
  72. package/dist/geo-point-codec-lhxH42SK.mjs +2 -0
  73. package/dist/geo-point-codec-lhxH42SK.mjs.map +1 -0
  74. package/dist/{hydration-D6JICBQG.mjs → hydration-CAxOL4aI.mjs} +2 -2
  75. package/dist/{hydration-D6JICBQG.mjs.map → hydration-CAxOL4aI.mjs.map} +1 -1
  76. package/dist/identifier-conversion-GgbwHc2G.mjs +2 -0
  77. package/dist/identifier-conversion-GgbwHc2G.mjs.map +1 -0
  78. package/dist/{identifier-EsWKVHXi.mjs → identifier-hQCs8M1n.mjs} +2 -2
  79. package/dist/{identifier-EsWKVHXi.mjs.map → identifier-hQCs8M1n.mjs.map} +1 -1
  80. package/dist/identity-CLFhCTZx.mjs +2 -0
  81. package/dist/identity-CLFhCTZx.mjs.map +1 -0
  82. package/dist/{index-T0YKKw66.d.mts → index-C_XLSTy2.d.mts} +723 -400
  83. package/dist/index.d.mts +2 -2
  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/instrumentation.mjs.map +1 -1
  89. package/dist/{invariant-DCsftyml.mjs → invariant-BnLYqsHO.mjs} +1 -1
  90. package/dist/{invariant-DCsftyml.mjs.map → invariant-BnLYqsHO.mjs.map} +1 -1
  91. package/dist/{json-number-C10HFiy6.mjs → json-number-CGXpPu4D.mjs} +1 -1
  92. package/dist/{json-number-C10HFiy6.mjs.map → json-number-CGXpPu4D.mjs.map} +1 -1
  93. package/dist/key-BeoOwGr3.mjs +2 -0
  94. package/dist/key-BeoOwGr3.mjs.map +1 -0
  95. package/dist/libsql-Bu_IdFU1.mjs +11 -0
  96. package/dist/libsql-Bu_IdFU1.mjs.map +1 -0
  97. package/dist/libsql.d.mts +8 -3
  98. package/dist/libsql.mjs +1 -1
  99. package/dist/libsql.mjs.map +1 -1
  100. package/dist/memory-D4yxtCPK.mjs +2 -0
  101. package/dist/memory-D4yxtCPK.mjs.map +1 -0
  102. package/dist/migrations/mysql.d.mts +6 -0
  103. package/dist/migrations/mysql.mjs +2 -0
  104. package/dist/migrations/mysql.mjs.map +1 -0
  105. package/dist/migrations/postgres.d.mts +6 -0
  106. package/dist/migrations/postgres.mjs +2 -0
  107. package/dist/migrations/postgres.mjs.map +1 -0
  108. package/dist/migrations/sqlite.d.mts +6 -0
  109. package/dist/migrations/sqlite.mjs +2 -0
  110. package/dist/migrations/sqlite.mjs.map +1 -0
  111. package/dist/migrations/storage/durable-object.d.mts +17 -0
  112. package/dist/migrations/storage/durable-object.mjs +2 -0
  113. package/dist/migrations/storage/durable-object.mjs.map +1 -0
  114. package/dist/migrations/storage/fs.d.mts +6 -1
  115. package/dist/migrations/storage/fs.mjs +1 -1
  116. package/dist/migrations/storage/r2.d.mts +14 -0
  117. package/dist/migrations/storage/r2.mjs +2 -0
  118. package/dist/migrations/storage/r2.mjs.map +1 -0
  119. package/dist/migrations/tenant.d.mts +92 -0
  120. package/dist/migrations/tenant.mjs +2 -0
  121. package/dist/migrations/tenant.mjs.map +1 -0
  122. package/dist/{migrations-BWZSBMZh.mjs → migrations-DTObIjAm.mjs} +2 -2
  123. package/dist/migrations-DTObIjAm.mjs.map +1 -0
  124. package/dist/migrations.d.mts +6 -559
  125. package/dist/migrations.mjs +1 -1
  126. package/dist/migrations.mjs.map +1 -1
  127. package/dist/mysql-CibPaHSp.mjs +99 -0
  128. package/dist/mysql-CibPaHSp.mjs.map +1 -0
  129. package/dist/mysql-adapter-DkJPfoGf.mjs +2 -0
  130. package/dist/mysql-adapter-DkJPfoGf.mjs.map +1 -0
  131. package/dist/mysql2.d.mts +1 -3
  132. package/dist/mysql2.mjs +1 -1
  133. package/dist/mysql2.mjs.map +1 -1
  134. package/dist/neon-http.d.mts +1 -1
  135. package/dist/neon-http.mjs +1 -1
  136. package/dist/neon-http.mjs.map +1 -1
  137. package/dist/object-store-DQR6bTBY.mjs +2 -0
  138. package/dist/object-store-DQR6bTBY.mjs.map +1 -0
  139. package/dist/object-store-DyYOCtmX.d.mts +156 -0
  140. package/dist/observation-DUSm7oXK.mjs +2 -0
  141. package/dist/observation-DUSm7oXK.mjs.map +1 -0
  142. package/dist/pg.d.mts +37 -12
  143. package/dist/pg.mjs +1 -1
  144. package/dist/pg.mjs.map +1 -1
  145. package/dist/pglite.d.mts +2 -1
  146. package/dist/pglite.mjs +1 -1
  147. package/dist/pglite.mjs.map +1 -1
  148. package/dist/physical-6V_LNU3L.mjs +2 -0
  149. package/dist/{physical-BkelResN.mjs.map → physical-6V_LNU3L.mjs.map} +1 -1
  150. package/dist/pinned-session-CLxj5M5e.mjs +2 -0
  151. package/dist/pinned-session-CLxj5M5e.mjs.map +1 -0
  152. package/dist/planetscale.d.mts +1 -1
  153. package/dist/planetscale.mjs +1 -1
  154. package/dist/planetscale.mjs.map +1 -1
  155. package/dist/{planner-B11VjIin.d.mts → planner-C6Lfsasx.d.mts} +57 -3
  156. package/dist/postgres-adapter-B3SQvcV1.mjs +2 -0
  157. package/dist/postgres-adapter-B3SQvcV1.mjs.map +1 -0
  158. package/dist/postgres-adapter-CQD2oGuD.mjs +2 -0
  159. package/dist/postgres-adapter-CQD2oGuD.mjs.map +1 -0
  160. package/dist/postgres-oqNW9xqo.mjs +415 -0
  161. package/dist/postgres-oqNW9xqo.mjs.map +1 -0
  162. package/dist/{postgres-result-Dc_iW3Hb.mjs → postgres-result-7F0DllQe.mjs} +2 -2
  163. package/dist/{postgres-result-Dc_iW3Hb.mjs.map → postgres-result-7F0DllQe.mjs.map} +1 -1
  164. package/dist/postgres.d.mts +11 -1
  165. package/dist/postgres.mjs +1 -1
  166. package/dist/postgres.mjs.map +1 -1
  167. package/dist/provider-limits-BHATED_m.mjs +2 -0
  168. package/dist/provider-limits-BHATED_m.mjs.map +1 -0
  169. package/dist/registration-preflight-DEjv050M.mjs +4 -0
  170. package/dist/registration-preflight-DEjv050M.mjs.map +1 -0
  171. package/dist/result-shape-CTNdNSW3.mjs +2 -0
  172. package/dist/result-shape-CTNdNSW3.mjs.map +1 -0
  173. package/dist/scalar-U0wD5bKy.mjs +2 -0
  174. package/dist/{scalar-BTktMqvO.mjs.map → scalar-U0wD5bKy.mjs.map} +1 -1
  175. package/dist/schema/json.d.mts +1 -1
  176. package/dist/schema/json.mjs +1 -1
  177. package/dist/schema/json.mjs.map +1 -1
  178. package/dist/schema-Cjem1-0f.mjs +2 -0
  179. package/dist/{schema-BFNcMdO6.mjs.map → schema-Cjem1-0f.mjs.map} +1 -1
  180. package/dist/schema-introspection-DEYGC2qg.mjs +6 -0
  181. package/dist/schema-introspection-DEYGC2qg.mjs.map +1 -0
  182. package/dist/schema.d.mts +1 -1
  183. package/dist/schema.mjs +1 -1
  184. package/dist/{select-assembly-BgqlrePH.mjs → select-assembly-f1UGoblh.mjs} +2 -2
  185. package/dist/select-assembly-f1UGoblh.mjs.map +1 -0
  186. package/dist/settle-B9Vg1FnP.mjs +2 -0
  187. package/dist/settle-B9Vg1FnP.mjs.map +1 -0
  188. package/dist/soft-delete.d.mts +1 -1
  189. package/dist/{sql--69HUgel.mjs → sql-Bp7jicEX.mjs} +1 -1
  190. package/dist/{sql--69HUgel.mjs.map → sql-Bp7jicEX.mjs.map} +1 -1
  191. package/dist/{sql-statement-tokens-CykxFmOJ.mjs → sql-statement-tokens-BBcoGmJb.mjs} +1 -1
  192. package/dist/{sql-statement-tokens-CykxFmOJ.mjs.map → sql-statement-tokens-BBcoGmJb.mjs.map} +1 -1
  193. package/dist/sql.d.mts +1 -1
  194. package/dist/sql.mjs +1 -1
  195. package/dist/sqlite-adapter-CW_3l6ea.mjs +2 -0
  196. package/dist/sqlite-adapter-CW_3l6ea.mjs.map +1 -0
  197. package/dist/sqlite-utils-DlgokMJN.mjs +2 -0
  198. package/dist/sqlite-utils-DlgokMJN.mjs.map +1 -0
  199. package/dist/sqlite3.d.mts +2 -8
  200. package/dist/sqlite3.mjs +1 -1
  201. package/dist/sqlite3.mjs.map +1 -1
  202. package/dist/standard-sql-Bk4RZPqJ.mjs +6 -0
  203. package/dist/standard-sql-Bk4RZPqJ.mjs.map +1 -0
  204. package/dist/{suppressed-failure-BPxfHTMc.mjs → suppressed-failure-BwULh-8h.mjs} +1 -1
  205. package/dist/{suppressed-failure-BPxfHTMc.mjs.map → suppressed-failure-BwULh-8h.mjs.map} +1 -1
  206. package/dist/{terminal-BbRi0CNZ.mjs → terminal-C8cq1WWX.mjs} +2 -2
  207. package/dist/{terminal-BbRi0CNZ.mjs.map → terminal-C8cq1WWX.mjs.map} +1 -1
  208. package/dist/{transaction-oskVwmsf.mjs → transaction-Bnl6ULTw.mjs} +2 -2
  209. package/dist/transaction-Bnl6ULTw.mjs.map +1 -0
  210. package/dist/{transaction-operation-BC7aua5V.mjs → transaction-operation-CKK3l_9x.mjs} +2 -2
  211. package/dist/transaction-operation-CKK3l_9x.mjs.map +1 -0
  212. package/dist/{utils-DfztpPvR.mjs → utils-CZNaOZR7.mjs} +4 -3
  213. package/dist/utils-CZNaOZR7.mjs.map +1 -0
  214. package/dist/v-D5Z06FKN.mjs +2 -0
  215. package/dist/v-D5Z06FKN.mjs.map +1 -0
  216. package/dist/validation-Dk9Q_-C7.mjs +2 -0
  217. package/dist/validation-Dk9Q_-C7.mjs.map +1 -0
  218. package/dist/validation-PF9-_nKd.mjs +2 -0
  219. package/dist/{validation-tgjL_9n8.mjs.map → validation-PF9-_nKd.mjs.map} +1 -1
  220. package/dist/validation.d.mts +1 -1
  221. package/dist/validation.mjs +1 -1
  222. package/dist/validator-X9-bwtRo.mjs +2 -0
  223. package/dist/{validator-DMlEScV3.mjs.map → validator-X9-bwtRo.mjs.map} +1 -1
  224. package/dist/value-guards-CK9guf2Z.mjs +2 -0
  225. package/dist/value-guards-CK9guf2Z.mjs.map +1 -0
  226. package/dist/version-JDaZht4U.mjs +2 -0
  227. package/dist/{version-Cr80LFvx.mjs.map → version-JDaZht4U.mjs.map} +1 -1
  228. package/package.json +75 -34
  229. package/dist/base-vfur-DaU.mjs +0 -2
  230. package/dist/base-vfur-DaU.mjs.map +0 -1
  231. package/dist/batch-refs-BY51FIXm.mjs +0 -6
  232. package/dist/batch-refs-BY51FIXm.mjs.map +0 -1
  233. package/dist/bind-parameter-capacity-DzMcIB95.mjs +0 -2
  234. package/dist/builder-bPfagDQV.mjs +0 -2
  235. package/dist/builder-bPfagDQV.mjs.map +0 -1
  236. package/dist/chain-uIFlkkXS.mjs +0 -2
  237. package/dist/chain-uIFlkkXS.mjs.map +0 -1
  238. package/dist/client-NleI4Nm-.mjs +0 -434
  239. package/dist/client-NleI4Nm-.mjs.map +0 -1
  240. package/dist/client-tjSMPjeZ.mjs +0 -2
  241. package/dist/client-tjSMPjeZ.mjs.map +0 -1
  242. package/dist/controls-BhxRnPYS.mjs +0 -2
  243. package/dist/controls-BhxRnPYS.mjs.map +0 -1
  244. package/dist/decimal-12NERGYZ.mjs +0 -3
  245. package/dist/decimal-12NERGYZ.mjs.map +0 -1
  246. package/dist/driver-CRaDT4B7.mjs +0 -2
  247. package/dist/driver-options-DxlB1tms.mjs +0 -2
  248. package/dist/driver-options-DxlB1tms.mjs.map +0 -1
  249. package/dist/driver-yCYqzIQg.mjs +0 -2
  250. package/dist/driver-yCYqzIQg.mjs.map +0 -1
  251. package/dist/error-mapping-BWzb-l02.mjs +0 -2
  252. package/dist/error-mapping-BWzb-l02.mjs.map +0 -1
  253. package/dist/execution-context-BPk0YLhd.mjs +0 -2
  254. package/dist/execution-context-BPk0YLhd.mjs.map +0 -1
  255. package/dist/fs-estate-3Bu_K9mk.d.mts +0 -7
  256. package/dist/fs-estate-BcjgY4iY.mjs +0 -2
  257. package/dist/fs-estate-BcjgY4iY.mjs.map +0 -1
  258. package/dist/geo-point-codec-DUTTtlav.mjs +0 -2
  259. package/dist/geo-point-codec-DUTTtlav.mjs.map +0 -1
  260. package/dist/identifiers-By-JRCb5.mjs +0 -2
  261. package/dist/identifiers-By-JRCb5.mjs.map +0 -1
  262. package/dist/key-DKaqPb8w.mjs +0 -2
  263. package/dist/key-DKaqPb8w.mjs.map +0 -1
  264. package/dist/migrations-BWZSBMZh.mjs.map +0 -1
  265. package/dist/mysql-adapter-D9FoHlWE.mjs +0 -2
  266. package/dist/mysql-adapter-D9FoHlWE.mjs.map +0 -1
  267. package/dist/observation-CLp8ylmL.mjs +0 -2
  268. package/dist/observation-CLp8ylmL.mjs.map +0 -1
  269. package/dist/physical-BkelResN.mjs +0 -2
  270. package/dist/pinned-session-Ca7C9yxY.mjs +0 -2
  271. package/dist/pinned-session-Ca7C9yxY.mjs.map +0 -1
  272. package/dist/postgres-adapter-T2Iko-vt.mjs +0 -2
  273. package/dist/postgres-adapter-T2Iko-vt.mjs.map +0 -1
  274. package/dist/registration-preflight-BrA3EWvq.mjs +0 -4
  275. package/dist/registration-preflight-BrA3EWvq.mjs.map +0 -1
  276. package/dist/result-shape-DKTu8yre.mjs +0 -2
  277. package/dist/result-shape-DKTu8yre.mjs.map +0 -1
  278. package/dist/scalar-BTktMqvO.mjs +0 -2
  279. package/dist/schema-BFNcMdO6.mjs +0 -2
  280. package/dist/schema-introspection-DsXPfCst.mjs +0 -6
  281. package/dist/schema-introspection-DsXPfCst.mjs.map +0 -1
  282. package/dist/select-assembly-BgqlrePH.mjs.map +0 -1
  283. package/dist/sqlite-adapter-HqO3GpAK.mjs +0 -2
  284. package/dist/sqlite-adapter-HqO3GpAK.mjs.map +0 -1
  285. package/dist/sqlite-utils-D26BFuJJ.mjs +0 -2
  286. package/dist/sqlite-utils-D26BFuJJ.mjs.map +0 -1
  287. package/dist/transaction-operation-BC7aua5V.mjs.map +0 -1
  288. package/dist/transaction-oskVwmsf.mjs.map +0 -1
  289. package/dist/transactions-gjmrWN5W.mjs +0 -2
  290. package/dist/transactions-gjmrWN5W.mjs.map +0 -1
  291. package/dist/utils-DfztpPvR.mjs.map +0 -1
  292. package/dist/v-B2WwtcRz.mjs +0 -2
  293. package/dist/v-B2WwtcRz.mjs.map +0 -1
  294. package/dist/validation-Du6j0Q38.mjs +0 -2
  295. package/dist/validation-Du6j0Q38.mjs.map +0 -1
  296. package/dist/validation-tgjL_9n8.mjs +0 -2
  297. package/dist/validator-DMlEScV3.mjs +0 -2
  298. package/dist/version-Cr80LFvx.mjs +0 -2
  299. /package/dist/{contract-BHUOUAZ-.d.mts → contract-CIIqgFyb.d.mts} +0 -0
  300. /package/dist/{sql--yhoVvRM.d.mts → sql-BvfwUKIh.d.mts} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility; options.prepare: true opts into\n * the provider's prepared-statement reuse on compatible sessions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport { PostgresAdapter } from \"@adapters/databases/postgres/postgres-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport {\n ClientInitializationError,\n unsupportedVector,\n VibORMErrorCode,\n} from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport { Driver, type QueryExecutionContext } from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n const adapter = new PostgresAdapter(namespace, options.postgis === true);\n adapter.capabilities.supportsVector = options.pgvector === true;\n if (!options.pgvector) adapter.vector = unsupportedVector;\n defineImmutableDriverFact(this, \"adapter\", adapter);\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n const { databaseUrl, options } = this.driverOptions;\n if (databaseUrl) {\n const {\n host: _host,\n hostname: _hostname,\n port: _port,\n user: _user,\n username: _username,\n pass: _pass,\n password: _password,\n database: _database,\n db: _db,\n ...transportOptions\n } = options ?? {};\n return postgres(databaseUrl, withVibormTypes(transportOptions));\n }\n return postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"execute\";\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n const result = await client.unsafe<T[]>(\n sqlStr,\n encodeListParameters(params),\n { prepare: this.driverOptions.options?.prepare === true }\n );\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? \"executeRaw\";\n const result = await client.unsafe<T[]>(sqlStr, params, {\n prepare: this.driverOptions.options?.prepare === true,\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with leases,\n // never caller SQL; the callback above has provably not entered.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n const lease = await acquireWithMaxWait(\n () => client.reserve(),\n (late) => late.release(),\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n lease.release();\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (attempt === 1 || !this.isConnectionFailure(cleanup)) break;\n }\n }\n // Only this wrapper is quarantined; the shared native pool stays borrowed.\n this.transactionCleanupFailed(\n normalizeDriverError(primary, {\n driverName: this.driverName,\n dialect: this.dialect,\n })\n );\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n await client.end();\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n databaseUrl,\n pgvector,\n postgis,\n namespace,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"8pBA+DA,MAAa,EAAqD,CAKhE,UAAW,CACT,GAAI,KACJ,KAAM,CAAC,KAAM,KAAM,KAAK,CACxB,UAAY,GACV,aAAiB,KAAO,EAAM,aAAa,CAAG,OAAO,EAAM,CAC7D,MAAQ,GAAkB,EAC3B,CAMD,KAAM,CACJ,GAAI,IACJ,KAAM,CAAC,IAAK,KAAK,CACjB,UAAY,GACV,OAAO,GAAU,SAAW,EAAQ,KAAK,UAAU,EAAM,CAC3D,MAAQ,GAAkB,KAAK,MAAM,EAAM,CAC5C,CACF,CAID,SAAS,qBAAqB,EAA8B,CAC1D,OAAO,EAAO,IAAK,GACjB,MAAM,QAAQ,EAAM,CAChB,IAAI,EAAM,IAAK,GAAY,IAAW,KAAO,OAAS,IAAI,OAAO,EAAO,CAAC,QAAQ,MAAO,OAAO,CAAC,QAAQ,KAAM,MAAM,CAAC,GAAI,CAAC,KAAK,IAAI,CAAC,GACpI,EACL,CAGH,MAAM,iBAAmB,EAA2B,EAAE,IAAuB,CAC3E,GAAG,EACH,MAAO,CAAE,GAAG,EAAa,GAAG,EAAQ,MAAO,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C,GAAI,GAAa,EAAG,MACpB,GAAI,EACY,MAAM,MACZ,EAAO,SAAS,CACrB,GAAS,EAAK,SAAS,CACxB,EACA,CAAE,WAAY,KAAK,WAAY,KAAM,WAAY,CAClD,EACK,SAAS,CACf,aACO,EAAS,CAEhB,GADA,EAAsB,EAAS,EAAQ,CACnC,IAAY,GAAK,CAAC,KAAK,oBAAoB,EAAQ,CAAE,OAI7D,KAAK,yBACH,EAAqB,EAAS,CAC5B,WAAY,KAAK,WACjB,QAAS,KAAK,QACf,CAAC,CACH,CAeH,MAAyB,eAEvB,CACA,IAAM,EAAS,MAAM,KAAK,UAAU,CAAE,UAAW,gBAAiB,CAAC,CACnE,GAAI,cAAc,EAAO,CACvB,MAAM,EAA+B,KAAK,WAAW,CAEvD,IAAM,EAAW,MAAM,EAAO,SAAS,CACvC,MAAO,CACL,QAAS,EACT,QAAU,GACR,EAA+B,CAC7B,WAAY,KAAK,WACjB,UACA,UAAa,EAAS,OAAO,kCAAkC,CAC/D,YAAe,EAAS,SAAS,CAKjC,oBACE,IAAW,KAAK,eACZ,IAAA,GACA,SAAY,CAQV,KAAK,OAAS,KACd,KAAK,YAAc,KACnB,MAAM,EAAO,KAAK,EAE3B,CAAC,CACL,GAQL,SAAgB,aACd,EAOC,CACD,GAAM,CAAE,SAAQ,UAAU,EAAE,CAAE,WAAU,UAAS,eAAgB,EAYjE,OAAO,EAAmD,EAT3C,IAAI,eAAe,CAChC,SACA,UACA,cACA,WACA,UACA,UARgB,EAAuB,EAAO,CAS/C,CAAC,CAEuE"}
1
+ {"version":3,"file":"postgres.mjs","names":[],"sources":["../src/drivers/postgres/index.ts"],"sourcesContent":["/**\n * PostgreSQL Driver (postgres.js)\n *\n * Driver implementation for postgres.js - a modern, fast PostgreSQL client.\n *\n * Generated statements use unsafe(query, values, queryOptions). Preparation\n * defaults to false for pooler compatibility; options.prepare: true opts into\n * the provider's prepared-statement reuse on compatible sessions.\n */\n\nimport type { DatabaseAdapter } from \"@adapters/database-adapter\";\nimport {\n createClientFromDriverConfig,\n type DriverConfig,\n type LinkedClientConfig,\n type NoExtraDriverConfigKeys,\n type VibORMClient,\n} from \"@client/client\";\nimport type { Schema } from \"@client/types\";\nimport { ClientInitializationError, VibORMErrorCode } from \"@errors\";\nimport postgres, {\n type Options as PostgresOptionsType,\n type Sql as PostgresSql,\n} from \"postgres\";\nimport {\n Driver,\n type MigrationSessionAttestation,\n type QueryExecutionContext,\n} from \"../driver\";\nimport { normalizeDriverError } from \"../error-mapping\";\nimport { getExecutionTransactionPhases } from \"../execution-context\";\nimport {\n acquireWithMaxWait,\n type DriverTransactionOptions,\n defineImmutableDriverFact,\n nestedTransactionDispatchError,\n normalizePostgresRowCount,\n type PinnedSessionReservation,\n releaseReservedPostgresSession,\n resolveMigrationSessionAttestationOption,\n resolveNamespaceOption,\n runProviderManagedTransaction,\n type TransactionOptionSupport,\n withSuppressedFailure,\n} from \"../shared\";\nimport {\n refuseEmptyDatabaseUrl,\n refuseUnknownDriverConfigKeys,\n systemRootAsVerifyFull,\n} from \"../shared/driver-options\";\nimport { CLEANUP_BOUND_MS } from \"../shared/pinned-session\";\nimport { installPostgresAdapter } from \"../shared/postgres-adapter\";\nimport type { QueryResult } from \"../types\";\n\nexport type PostgresOptions = PostgresOptionsType<\n Record<string, postgres.PostgresType>\n>;\n\ntype PostgresTransaction = postgres.TransactionSql<Record<string, unknown>>;\n\nexport interface PostgresDriverOptions {\n client?: PostgresSql<Record<string, unknown>>;\n options?: PostgresOptions;\n pgvector?: boolean;\n postgis?: boolean;\n databaseUrl?: string;\n /** The PostgreSQL schema this driver's persistent objects live in. Defaults to `public`. */\n namespace?: string;\n /**\n * Your claim, at your risk, that every connection this client opens is one\n * server session for its whole life. It lifts migrations' refusal of\n * Cloudflare Hyperdrive and Neon `-pooler` hosts; application queries never\n * need it.\n */\n migrationSessionAttestation?: MigrationSessionAttestation;\n}\n\nexport const vibormTypes: Record<string, postgres.PostgresType> = {\n // TIMESTAMP WITHOUT TIME ZONE (1114): postgres.js builds process-local\n // Dates, shifting the stored UTC wall clock by the process timezone. Keep\n // the raw string — the shared result parser builds a UTC Date from it,\n // matching every other driver. (DATE already arrives as a string.)\n timestamp: {\n to: 1114,\n from: [1082, 1114, 1184],\n serialize: (value: unknown) =>\n value instanceof Date ? value.toISOString() : String(value),\n parse: (value: string) => value,\n },\n // The adapter binds a `JsonParameter` carrier (src/sql/json-parameter.ts),\n // which the object arm serializes to its canonical text via `toJSON`. The\n // string arm exists for raw SQL: a caller's own JSON text bound to a\n // json/jsonb parameter must not be JSON.stringify'd a second time once the\n // server declares the param type — that double-encodes the stored value.\n json: {\n to: 114,\n from: [114, 3802],\n serialize: (value: unknown) =>\n typeof value === \"string\" ? value : JSON.stringify(value),\n parse: (value: string) => JSON.parse(value),\n },\n};\n\n/** Bind validated one-dimensional lists as PostgreSQL text, letting SQL infer\n * the column type; postgres.js otherwise guesses bigint[]/boolean[] wrongly. */\nfunction encodeListParameters(params: unknown[]): unknown[] {\n return params.map((value) =>\n Array.isArray(value)\n ? `{${value.map((member) => (member === null ? \"NULL\" : `\"${String(member).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`)).join(\",\")}}`\n : value\n );\n}\n\nconst withVibormTypes = (options: PostgresOptions = {}): PostgresOptions => ({\n ...options,\n types: { ...vibormTypes, ...options.types },\n});\n\nexport type PostgresClientConfig<C extends DriverConfig> =\n PostgresDriverOptions & C;\n\nconst POSTGRES_CONFIG_KEYS: Record<keyof PostgresDriverOptions, true> = {\n client: true,\n options: true,\n pgvector: true,\n postgis: true,\n databaseUrl: true,\n namespace: true,\n migrationSessionAttestation: true,\n};\n\ntype PostgresClient = PostgresSql<Record<string, unknown>>;\n\nconst isTransaction = (\n client: PostgresClient | PostgresTransaction\n): client is PostgresTransaction => {\n return \"savepoint\" in client;\n};\n\n// ============================================================\n// DRIVER IMPLEMENTATION\n// ============================================================\n\nexport class PostgresDriver extends Driver<\n PostgresClient,\n PostgresTransaction\n> {\n declare readonly adapter: DatabaseAdapter;\n readonly maxBindParametersPerStatement: number | undefined = 65_533;\n\n private readonly driverOptions: PostgresDriverOptions;\n /**\n * The EXACT transport the caller supplied, or absent when this driver makes\n * its own. Identity, settled here from ONE read, is the whole ownership\n * answer: the caller's options object is theirs to change, and a `client`\n * getter answering differently on a second read used to leave this driver\n * holding the caller's transport while believing it had made its own.\n */\n private readonly suppliedClient: PostgresClient | undefined;\n\n constructor(options: PostgresDriverOptions = {}) {\n super(\"postgresql\", \"postgres\");\n const namespace = resolveNamespaceOption(options);\n this.driverOptions = {\n databaseUrl: options.databaseUrl,\n options: { ...options.options },\n };\n this.suppliedClient = options.client;\n const { host, hostname } = this.driverOptions.options ?? {};\n refuseEmptyDatabaseUrl(\n \"postgres\",\n options,\n Boolean(this.suppliedClient || host || hostname)\n );\n\n if (this.suppliedClient) {\n for (const oid of [1082, 1114, 1184]) {\n if (\n this.suppliedClient.options?.parsers[oid] !==\n vibormTypes.timestamp?.parse\n ) {\n throw new ClientInitializationError(\n \"A supplied postgres.js client must use VibORM temporal parsers; construct postgres(url, { types: vibormTypes }).\",\n { meta: { driver: \"postgres\", operation: \"configuration\" } }\n );\n }\n }\n this.client = this.suppliedClient;\n }\n\n installPostgresAdapter(this, namespace, options);\n defineImmutableDriverFact(\n this,\n \"migrationSessionAttestation\",\n resolveMigrationSessionAttestationOption(options)\n );\n }\n\n /** Every host or URL this driver's client connects through, for migration admission. */\n protected override migrationSessionEndpoints(): readonly unknown[] {\n const { databaseUrl, options } = this.driverOptions;\n return [\n databaseUrl,\n options?.host,\n options?.hostname,\n ...(this.suppliedClient?.options.host ?? []),\n ];\n }\n\n /**\n * The transport this driver connects through.\n *\n * A caller's transport is RETURNED rather than replaced: reconnecting after a\n * `$disconnect()` used to build a second one behind their back — a transport\n * they never asked for, pointed at whatever their options record said by\n * then, and then never closed, because the ownership question was still\n * answered \"supplied\".\n */\n protected async initClient(): Promise<PostgresClient> {\n if (this.suppliedClient !== undefined) {\n return this.suppliedClient;\n }\n // postgres.js reads the URL for the keys it carries and lets every key\n // set in options win, which is the documented precedence.\n const { databaseUrl, options } = this.driverOptions;\n return databaseUrl\n ? postgres(systemRootAsVerifyFull(databaseUrl), withVibormTypes(options))\n : postgres(withVibormTypes(options));\n }\n\n /**\n * A supplied transport belongs to the caller, who may be sharing it with\n * other clients — two schema-scoped estates over one transport is the\n * documented shape — and §5.3's rule is that VibORM never changes a caller's\n * connection state. `$disconnect()` used to end it regardless, so\n * disconnecting one client tore down every other consumer of that transport.\n *\n * The test is on the transport's IDENTITY against what construction\n * captured, so it answers for the transport actually being closed rather than\n * for whatever the caller's record says now.\n */\n protected async closeClient(sql: PostgresClient): Promise<void> {\n if (sql === this.suppliedClient) {\n return;\n }\n await sql.end();\n }\n\n protected async execute<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[],\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n // postgres.js unsafe() takes (query, parameters?, queryOptions?)\n // parameters must be cast as postgres expects specific types\n return this.executeQuery(\n client,\n sqlStr,\n encodeListParameters(params),\n context,\n \"execute\"\n );\n }\n\n protected async executeRaw<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context?: QueryExecutionContext\n ): Promise<QueryResult<T>> {\n return this.executeQuery(client, sqlStr, params, context, \"executeRaw\");\n }\n\n private async executeQuery<T>(\n client: PostgresClient | PostgresTransaction,\n sqlStr: string,\n params: unknown[] | undefined,\n context: QueryExecutionContext | undefined,\n fallbackOperation: \"execute\" | \"executeRaw\"\n ): Promise<QueryResult<T>> {\n const operation = context?.operation ?? fallbackOperation;\n const result = await client.unsafe<T[]>(sqlStr, params, {\n prepare: this.driverOptions.options?.prepare === true,\n });\n return {\n rows: result,\n rowCount: normalizePostgresRowCount(\n result.count,\n result.command,\n result,\n {\n provider: \"postgres\",\n operation,\n }\n ),\n };\n }\n\n /**\n * postgres.js owns BEGIN inside `client.begin()`, so the isolation level goes\n * in as the transaction's first statement. It also owns connection\n * acquisition inside that same call: there is no acquisition step VibORM can\n * bound or abandon, so `maxWait` is refused rather than faked.\n */\n protected override transactionOptionSupport(): TransactionOptionSupport {\n return {\n isolationLevel: \"post-begin\",\n timeout: true,\n maxWait: \"unsupported\",\n maxWaitReason:\n \"postgres.js acquires the connection inside client.begin(), which VibORM cannot observe or bound — the wait would be unbounded no matter what maxWait said\",\n };\n }\n\n protected async transaction<T>(\n client: PostgresClient | PostgresTransaction,\n fn: (tx: PostgresTransaction) => Promise<T>,\n context?: QueryExecutionContext,\n options?: DriverTransactionOptions\n ): Promise<T> {\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n\n return runProviderManagedTransaction({\n run: async (callback) => {\n let entered = false;\n try {\n return await client.begin((tx) => {\n entered = true;\n return callback(tx);\n });\n } catch (error) {\n if (!entered && this.isConnectionFailure(error))\n await this.recoverFailedBegin(\n client,\n error,\n options?.maxWaitMs ?? 5000\n );\n throw error;\n }\n },\n callback: fn,\n phases: getExecutionTransactionPhases(context),\n // The provider transaction primitive already rolls back/discards its\n // failed session. A transaction does not own this shared pool/database.\n close: async () => undefined,\n });\n }\n\n private isConnectionFailure(error: unknown): boolean {\n const failure = normalizeDriverError(error, {\n driverName: this.driverName,\n dialect: this.dialect,\n });\n return (\n failure.code === VibORMErrorCode.CONNECTION_FAILED ||\n failure.code === VibORMErrorCode.CONNECTION_TIMEOUT\n );\n }\n\n private async recoverFailedBegin(\n client: PostgresClient,\n primary: unknown,\n maxWaitMs: number\n ): Promise<void> {\n // postgres.js can retain a fatal response across reconnect, rejecting the\n // next acquisition before dispatch. Drain that startup error with leases,\n // never caller SQL; the callback above has provably not entered. A drain\n // that cannot connect needs no quarantine: a connection failure before the\n // callback leaves no live session, and the next lease that connects\n // clears the state.\n const deadline = Date.now() + maxWaitMs;\n for (let attempt = 0; attempt < 2; attempt++) {\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n try {\n const lease = await acquireWithMaxWait(\n () => client.reserve(),\n (late) => late.release(),\n remaining,\n { driverName: this.driverName, form: \"callback\" }\n );\n lease.release();\n return;\n } catch (cleanup) {\n withSuppressedFailure(primary, cleanup);\n if (!this.isConnectionFailure(cleanup)) break;\n }\n }\n }\n\n /**\n * One `reserve()` result — plan §3.5's pinned producer for postgres.js.\n *\n * postgres.js exposes no destroy for a reserved connection, so a condemned\n * session is reset with PostgreSQL's own instrument before it goes back:\n * `pg_advisory_unlock_all()` releases every advisory lock the session still\n * holds, which is the exact state that must not survive the release. When\n * that reset FAILS the session's lock state is unknown, and the shared rule\n * below is what keeps it out of the pool — the reset's failure is not\n * swallowed, because a session that may still hold VibORM's migration lock is\n * not something a caller can be left unaware of.\n */\n protected override async pinnedSession(): Promise<\n PinnedSessionReservation<PostgresClient | PostgresTransaction>\n > {\n const client = await this.getClient({ operation: \"pinnedSession\" });\n if (isTransaction(client)) {\n throw nestedTransactionDispatchError(this.driverName);\n }\n const reserved = await client.reserve();\n return {\n session: reserved,\n release: (discard, lost) =>\n releaseReservedPostgresSession({\n driverName: this.driverName,\n discard,\n lost,\n reset: () => reserved.unsafe(\"SELECT pg_advisory_unlock_all()\"),\n release: () => reserved.release(),\n // Ownership is the identity this driver settled at construction,\n // never a later read of the caller's options object: a `client` key\n // deleted after construction would otherwise make VibORM end a\n // transport it was handed.\n closeOwnedTransport:\n client === this.suppliedClient\n ? undefined\n : async () => {\n // Withdrawn BEFORE the close, never after it. `end()` can\n // reject — a socket already gone is the ordinary way — and\n // withdrawing afterwards left this exact transport installed,\n // so the next ordinary query ran on the connection whose\n // advisory-lock state is precisely what could not be\n // accounted for. The in-flight connect goes with it, because\n // `getClient()` answers from it when `client` is null.\n this.client = null;\n this.initPromise = null;\n // Bounded: an abandoned connection whose socket stopped\n // answering never finishes on its own, and `end()` without\n // a timeout waits for it. Past the bound postgres.js\n // terminates every connection of this transport.\n await client.end({ timeout: CLEANUP_BOUND_MS / 1000 });\n },\n }),\n };\n }\n}\n\n// ============================================================\n// CONVENIENCE FUNCTION\n// ============================================================\n\nexport function createClient<S extends Schema, C extends DriverConfig<S>>(\n config: PostgresClientConfig<C> &\n DriverConfig<S> &\n NoExtraDriverConfigKeys<C, PostgresDriverOptions, S>\n): VibORMClient<{\n [P in keyof LinkedClientConfig<\n C & { driver: PostgresDriver }\n >]: LinkedClientConfig<C & { driver: PostgresDriver }>[P];\n}> {\n refuseUnknownDriverConfigKeys(config, \"postgres\", POSTGRES_CONFIG_KEYS);\n const { client, options = {}, pgvector, postgis, databaseUrl } = config;\n const namespace = resolveNamespaceOption(config);\n const migrationSessionAttestation =\n resolveMigrationSessionAttestationOption(config);\n\n const driver = new PostgresDriver({\n client,\n options,\n // Present even when undefined: the driver refuses an empty one (parity-18).\n ...(Object.hasOwn(config, \"databaseUrl\") ? { databaseUrl } : {}),\n pgvector,\n postgis,\n namespace,\n migrationSessionAttestation,\n });\n\n return createClientFromDriverConfig<S, C, PostgresDriver>(config, driver);\n}\n"],"mappings":"imBA6EA,MAAa,EAAqD,CAKhE,UAAW,CACT,GAAI,KACJ,KAAM,CAAC,KAAM,KAAM,KAAK,CACxB,UAAY,GACV,aAAiB,KAAO,EAAM,aAAa,CAAG,OAAO,EAAM,CAC7D,MAAQ,GAAkB,EAC3B,CAMD,KAAM,CACJ,GAAI,IACJ,KAAM,CAAC,IAAK,KAAK,CACjB,UAAY,GACV,OAAO,GAAU,SAAW,EAAQ,KAAK,UAAU,EAAM,CAC3D,MAAQ,GAAkB,KAAK,MAAM,EAAM,CAC5C,CACF,CAID,SAAS,qBAAqB,EAA8B,CAC1D,OAAO,EAAO,IAAK,GACjB,MAAM,QAAQ,EAAM,CAChB,IAAI,EAAM,IAAK,GAAY,IAAW,KAAO,OAAS,IAAI,OAAO,EAAO,CAAC,QAAQ,MAAO,OAAO,CAAC,QAAQ,KAAM,MAAM,CAAC,GAAI,CAAC,KAAK,IAAI,CAAC,GACpI,EACL,CAGH,MAAM,iBAAmB,EAA2B,E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from"./geo-point-codec-lhxH42SK.mjs";function decimalDialectOf(e){return e===`postgresql`?`pg`:e===`mysql`?`mysql`:`sqlite`}function findDecimalProviderLimitRefusal(e,n){let r=decimalDialectOf(n);for(let[i,a]of Object.entries(e)){let e=a[`~`].state.scalars;for(let[a,o]of Object.entries(e)){let e=o[`~`].state;if(e.type!==`decimal`||e.decimal===void 0)continue;let s=t(r,e.decimal);if(s!==void 0)return{modelName:i,fieldName:a,dialect:n,descriptor:e.decimal,reason:s}}}}function describeDecimalProviderLimitRefusal(e){return`Decimal field '${e.modelName}.${e.fieldName}' cannot be stored by the '${e.dialect}' driver: ${e.reason}.`}export{findDecimalProviderLimitRefusal as n,describeDecimalProviderLimitRefusal as t};
2
+ //# sourceMappingURL=provider-limits-BHATED_m.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-limits-BHATED_m.mjs","names":[],"sources":["../src/schema/scalars/decimal/provider-limits.ts"],"sourcesContent":["/**\n * The ONE schema-plus-provider fixed-decimal admission decision.\n *\n * A decimal descriptor is a valid schema fact independently of provider\n * limits. The first boundary that combines a complete model map with a chosen\n * provider asks this pure owner whether every declared scalar or list fits.\n * It returns one structured refusal and performs no boundary-specific throw;\n * client and migration composition roots retain their own error classes.\n */\n\nimport type { AnyModel } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport {\n type DecimalDescriptor,\n type DecimalDialect,\n describeProviderLimitRefusal,\n} from \"@validation/primitives/decimal-codec\";\n\ntype ProviderDialect = \"postgresql\" | \"mysql\" | \"sqlite\";\n\nexport interface DecimalProviderLimitRefusal {\n readonly modelName: string;\n readonly fieldName: string;\n readonly dialect: ProviderDialect;\n readonly descriptor: DecimalDescriptor;\n readonly reason: string;\n}\n\n/** The driver's dialect in the decimal codec's physical vocabulary. */\nfunction decimalDialectOf(dialect: ProviderDialect): DecimalDialect {\n if (dialect === \"postgresql\") return \"pg\";\n if (dialect === \"mysql\") return \"mysql\";\n return \"sqlite\";\n}\n\n/** Return the first declared decimal domain the selected provider cannot hold. */\nexport function findDecimalProviderLimitRefusal(\n schema: Record<string, AnyModel>,\n dialect: ProviderDialect\n): DecimalProviderLimitRefusal | undefined {\n const decimalDialect = decimalDialectOf(dialect);\n for (const [modelName, model] of Object.entries(schema)) {\n const scalars: Record<string, Scalar> = model[\"~\"].state.scalars;\n for (const [fieldName, scalar] of Object.entries(scalars)) {\n const state = scalar[\"~\"].state;\n if (state.type !== \"decimal\" || state.decimal === undefined) continue;\n const reason = describeProviderLimitRefusal(\n decimalDialect,\n state.decimal\n );\n if (reason === undefined) continue;\n return {\n modelName,\n fieldName,\n dialect,\n descriptor: state.decimal,\n reason,\n };\n }\n }\n return undefined;\n}\n\n/** The shared diagnostic body; each composition root chooses its error model. */\nexport function describeDecimalProviderLimitRefusal(\n refusal: DecimalProviderLimitRefusal\n): string {\n return `Decimal field '${refusal.modelName}.${refusal.fieldName}' cannot be stored by the '${refusal.dialect}' driver: ${refusal.reason}.`;\n}\n"],"mappings":"4FA6BA,SAAS,iBAAiB,EAA0C,CAGlE,OAFI,IAAY,aAAqB,KACjC,IAAY,QAAgB,QACzB,SAIT,SAAgB,gCACd,EACA,EACyC,CACzC,IAAM,EAAiB,iBAAiB,EAAQ,CAChD,IAAK,GAAM,CAAC,EAAW,KAAU,OAAO,QAAQ,EAAO,CAAE,CACvD,IAAM,EAAkC,EAAM,KAAK,MAAM,QACzD,IAAK,GAAM,CAAC,EAAW,KAAW,OAAO,QAAQ,EAAQ,CAAE,CACzD,IAAM,EAAQ,EAAO,KAAK,MAC1B,GAAI,EAAM,OAAS,WAAa,EAAM,UAAY,IAAA,GAAW,SAC7D,IAAM,EAAS,EACb,EACA,EAAM,QACP,CACG,OAAW,IAAA,GACf,MAAO,CACL,YACA,YACA,UACA,WAAY,EAAM,QAClB,SACD,GAOP,SAAgB,oCACd,EACQ,CACR,MAAO,kBAAkB,EAAQ,UAAU,GAAG,EAAQ,UAAU,6BAA6B,EAAQ,QAAQ,YAAY,EAAQ,OAAO"}
@@ -0,0 +1,4 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./value-guards-CK9guf2Z.mjs";import{n,t as r}from"./base-AdXAoy6l.mjs";import{t as i}from"./validation-Dk9Q_-C7.mjs";import{a,c as o,d as s,i as c,l,n as u,r as d,t as f,u as p}from"./terminal-C8cq1WWX.mjs";import{t as m}from"./identifier-hQCs8M1n.mjs";import{Ct as h,St as g,Tt as ee,_t as te,bt as _,ct as v,dt as y,ft as b,gt as x,ht as S,lt as C,mt as w,pt as T,ut as ne,vt as E,wt as re,xt as D,yt as ie}from"./geo-point-codec-lhxH42SK.mjs";import{n as O}from"./v-D5Z06FKN.mjs";import{a as k,i as A,n as j,r as M,t as N}from"./native-types-veeTk36s.mjs";const P=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/,F=[`table`,`source`,`target`];function normalizeVariantEntries(e,t,n){c(t)||s(e,`target`,"A relation target is either `() => model` or a plain map of named `() => model` getters");let r=u(t);r.length===0&&s(e,`target`,`A variant map needs at least one variant`);let i=readStoredValues(e,r,n),a={};for(let n of r){m(n)||s(e,`target.${n}`,`Variant key '${n}' is not a valid schema identifier`);let r=p(e,t,n,`target.${n}`);typeof r!=`function`&&s(e,`target.${n}`,`Variant '${n}' must be a lazy getter; write \`() => model\` rather than the model itself`),a[n]=Object.freeze({getter:r,storedValue:i[n]??n})}return Object.freeze(a)}function readStoredValues(e,t,n){if(n===void 0)return{};c(n)||s(e,`options`,"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value"),d(u(n),[`values`])||s(e,`options`,"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value");let r=p(e,n,`values`,`options.values`);c(r)||s(e,`options.values`,"`values` must be a plain record keyed by every variant");let i=u(r);d(i,t)||s(e,`options.values`,`\`values\` must be exact over the variant keys ${renderKeys(t)}; it declares ${renderKeys(i)}`);let a={},o=new Set;for(let n of t){let t=p(e,r,n,`options.values.${n}`);(typeof t!=`string`||!P.test(t))&&s(e,`options.values.${n}`,`Stored value for variant '${n}' must match the stored-discriminator grammar`),o.has(t)&&s(e,`options.values.${n}`,`Stored value '${t}' is declared for more than one variant`),o.add(t),a[n]=t}return a}function renderKeys(e){return`[${e.map(e=>`'${e}'`).join(`, `)}]`}function foldMemberJunctions(e,t){let n=Object.keys(e);c(t)||s(`s.toMany`,`through`,"`.through()` takes a plain map keyed by every variant"),d(u(t),n)||s(`s.toMany`,`through`,`\`.through()\` must be exact over the variant keys ${renderKeys(n)}`);let r={};for(let[n,i]of Object.entries(e)){let e=p(`s.toMany`,t,n,`through.${n}`);r[n]=Object.freeze({...i,junction:readJunctionOverride(n,e)})}return Object.freeze(r)}function readJunctionOverride(e,t){let n=`through.${e}`;c(t)||s(`s.toMany`,n,`Member junction '${e}' must be a plain \`{ table, source, target }\` record`);let r=p(`s.toMany`,t,`table`,`${n}.table`),i=p(`s.toMany`,t,`source`,`${n}.source`),a=p(`s.toMany`,t,`target`,`${n}.target`);return(!d(u(t),F)||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)&&s(`s.toMany`,n,`Member junction '${e}' declares exactly \`table\`, \`source\` and \`target\`, all strings`),Object.freeze({table:r,source:i,target:a})}var I=class VariantToOne{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:f(e=>readVariantGetter(this.#e,e))})}name(e){return new VariantToOne({...this.#e,name:l(`s.toOne`,e)})}optional(){return new VariantToOne({...this.#e,optional:!0})}get"~"(){return this.#t}},L=class VariantToMany{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:f(e=>readVariantGetter(this.#e,e))})}name(e){return new VariantToMany({...this.#e,name:l(`s.toMany`,e)})}through(e){return new VariantToMany({...this.#e,target:{kind:`variants`,entries:foldMemberJunctions(this.#e.target.entries,e)}})}get"~"(){return this.#t}};function variantToOneTerminal(e){return new I(e)}function variantToManyTerminal(e){return new L(e)}function readVariantGetter(e,t){if(t===void 0)return;let n=e.target.entries[t];return n===void 0?void 0:n.getter}var R=class ModelToOne{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:f(()=>this.#e.target.getter)})}name(e){return new ModelToOne({...this.#e,name:l(`s.toOne`,e)})}fields(...e){return new z(this.#e,a(`s.toOne`,`fields`,e))}onDelete(e){return this.#n(`onDelete`,e)}onUpdate(e){return this.#n(`onUpdate`,e)}#n(e,t){let n=this.#e.foreignKey;return n===void 0&&s(`s.toOne`,e,`'${e}' is available only after \`.fields(...).references(...)\` declares a foreign key`),new ModelToOne({...this.#e,foreignKey:Object.freeze({...n,[e]:o(e,t)})})}get"~"(){return this.#t}},z=class PendingReferences{#e;#t;constructor(e,t){this.#e=e,this.#t=t}name(e){return new PendingReferences({...this.#e,name:l(`s.toOne`,e)},this.#t)}references(...e){let t=a(`s.toOne`,`references`,e);t.length!==this.#t.length&&refuseReferenceArity(t.length,this.#t.length);let n=this.#e.foreignKey,r={fields:this.#t,references:t,...n?.onDelete===void 0?{}:{onDelete:n.onDelete},...n?.onUpdate===void 0?{}:{onUpdate:n.onUpdate}};return new R({...this.#e,foreignKey:Object.freeze(r)})}};function isReferencesStage(e){return e instanceof z}function toOne(e,t){return typeof e==`function`?(arguments.length>1&&s(`s.toOne`,`options`,`A model-target relation takes exactly one argument`),new R({kind:`relation`,cardinality:`one`,target:{kind:`model`,getter:e}})):variantToOneTerminal({kind:`relation`,cardinality:`one`,target:{kind:`variants`,entries:normalizeVariantEntries(`s.toOne`,e,t)}})}function refuseReferenceArity(e,t){return s(`s.toOne`,`references`,`\`.references(...)\` declares ${e} field(s) against ${t} local field(s); a foreign key pairs them positionally`)}function emptyRecord(){return Object.create(null)}function put(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function own(e,t){if(!(e===void 0||!Object.hasOwn(e,t)))return e[t]}function isRelation(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);return typeof n==`object`&&!!n&&Reflect.get(n,`kind`)===`relation`}const B=new Set([`string`,`int`,`number`,`decimal`,`boolean`,`datetime`,`date`,`time`,`bigint`,`json`,`blob`,`vector`,`point`,`enum`]);function isScalar(e){if((typeof e!=`object`||!e)&&typeof e!=`function`)return!1;let t=Reflect.get(e,`~`);if(typeof t!=`object`||!t)return!1;let n=Reflect.get(t,`state`);if(typeof n!=`object`||!n)return!1;let r=Reflect.get(n,`type`);return typeof r==`string`&&B.has(r)}const extractScalarMap=e=>{let t=emptyRecord();for(let[n,r]of Object.entries(e))isScalar(r)&&(t[n]=r);return t},extractRelationMap=e=>{let t=emptyRecord();for(let[n,r]of Object.entries(e))isRelation(r)?t[n]=r:isReferencesStage(r)&&s(`s.model`,n,`Relation '${n}' started \`.fields(...)\` without \`.references(...)\`; complete the foreign key before using it as a model field`);return t},extractUniqueScalarMap=e=>{let t=emptyRecord();for(let[n,r]of Object.entries(e))isScalar(r)&&(r[`~`].state.isUnique||r[`~`].state.isId)&&(t[n]=r);return t},getNameFromKeys=(e,t)=>e??t.join(`_`);function isTotalIndex(e){return!e.where}const mergeIndexDefinitions=(e,t)=>[...e.indexes,t];function compoundMembers(e,t,n){refuseDuplicateModelKeyMembers(t,n);let r=emptyRecord();for(let i of t){let t=i in e.scalars?e.scalars[i]:void 0;if(!t)throw Error(i in e.relations?`${n} field '${i}' is a relation and cannot be a key member`:`${n} field '${i}' does not exist`);put(r,i,t[`~`].state.base)}return r}function withCompound(e,t,n,r,i){let a=snapshotModelKeyMembers(r,n),o=getNameFromKeys(i?.name,a);if(Object.hasOwn(e[t]??{},o))throw Error(`${n} name '${o}' is already used by another compound key; give this tuple a distinct name`);let s=compoundMembers(e,a,n);return new V({...e,[t]:{...e[t],[o]:O.object(s,{partial:!1})}})}function snapshotModelKeyMembers(e,t){if(!Array.isArray(e))throw Error(`${t} fields must be a dense array of strings`);let n=e.length,r=Array(n);for(let i=0;i<n;i++){if(!Object.hasOwn(e,i))throw Error(`${t} fields must be a dense array of strings`);let n=e[i];if(typeof n!=`string`)throw Error(`${t} fields must be a dense array of strings`);r[i]=n}return r}function snapshotIndexOptions(e){let t=e.name,n=e.unique,r=e.type,i=e.where;return{...t===void 0?{}:{name:t},...n===void 0?{}:{unique:n},...r===void 0?{}:{type:r},...i===void 0?{}:{where:i}}}function refuseDuplicateModelKeyMembers(e,t){if(new Set(e).size!==e.length)throw Error(`${t} cannot repeat a field in one tuple`)}var V=class Model{#e={};#t={fields:new Map};#n;#r;#i;#a;constructor(e){this.#n=e}map(e){return new Model({...this.#n,tableName:e})}omit(e){return new Model({...this.#n,omit:e})}index(e,t={}){let n=snapshotModelKeyMembers(e,`Index`);refuseDuplicateModelKeyMembers(n,`Index`);let r=snapshotIndexOptions(t);return new Model({...this.#n,indexes:mergeIndexDefinitions(this.#n,{fields:n,options:r})})}id(e,t){return withCompound(this.#n,`compoundId`,`Compound ID`,e,t)}unique(e,t){return withCompound(this.#n,`compoundUniques`,`Compound unique`,e,t)}extends(e){let t={...this.#n.shape,...e};return new Model({...this.#n,shape:t,scalars:extractScalarMap(t),relations:extractRelationMap(t),uniques:extractUniqueScalarMap(t)})}get"~"(){if(this.#a)return this.#a;let e=this;return this.#a={state:this.#n,get names(){return e.#e},get nameRegistry(){return e.#t},getFieldName:t=>{let n=e.#t.fields.get(t);if(n)return n;throw Error(`Scalar "${t}" not found in nameRegistry`)},get scalarFieldNames(){return e.#r??=Object.keys(e.#n.scalars)},get relationNames(){return e.#i??=Object.keys(e.#n.relations)}},this.#a}};const model=e=>new V({compoundId:void 0,compoundUniques:void 0,tableName:void 0,indexes:[],omit:void 0,shape:e,scalars:extractScalarMap(e),relations:extractRelationMap(e),uniques:extractUniqueScalarMap(e)});function getTableName(e,t=`unknown`){return e[`~`].names.sql??e[`~`].state.tableName??t}function getColumnName(e,t){return e[`~`].getFieldName(t).sql}var SchemaValidationError=class extends r{static diagnosticName=`SchemaValidationError`;issues;constructor(e,t){let r=Object.freeze(e.map(e=>Object.freeze(e.candidates?{...e,candidates:Object.freeze([...e.candidates])}:{...e}))),i=r.map(e=>[`[${e.code}] ${e.message}`,e.candidates?.length?`Candidates: ${e.candidates.join(`, `)}`:``,e.repair??``].filter(Boolean).join(`
2
+ `));super(`Schema validation failed:\n${i.join(`
3
+ `)}`,n.INVALID_INPUT,t?.cause?{cause:t.cause}:void 0),this.issues=r}toJSON(){return{...super.toJSON(),issues:this.issues}}};function isSchemaValidationError(e){return e instanceof SchemaValidationError}function thrownAsError(e){return e instanceof Error?e:Error(String(e))}const H=new WeakSet;function generatorDefault(e){return H.add(e),e}function refuseListGenerator(e){throw new i({kind:`schema-builder`,builder:e,path:`array`},[{path:`array`,message:`Scalar generation is not supported on lists; declare an explicit array default`}])}function nullableDefault(e){return e.hasDefault?e.default:null}function isGeneratorDefault(e){return typeof e==`function`&&H.has(e)}const updateState=(e,t)=>({...e[`~`].state,...t}),createDefaultState=(e,t)=>({type:e,nullable:!1,array:!1,hasDefault:!1,isId:!1,isUnique:!1,default:void 0,autoGenerate:void 0,disallowZero:!1,schema:void 0,columnName:void 0,optional:!1,withTimezone:!1,base:t}),U=[[],[1],[1,2]],W=/^\d+$/,G=/^[A-Za-z_][A-Za-z0-9_]*(\(\d+(,\d+)*\))?$/,K={pg:`PG`,mysql:`MYSQL`,sqlite:`SQLITE`};let q;function isNativeTypeInCatalog(e,t){q??=buildCatalogs();let n=q[e];if(n.exact.has(t))return!0;if(!G.test(t))return!1;let r=t.indexOf(`(`);if(r===-1)return n.templates.get(t)?.has(0)===!0;let i=t.slice(0,r),a=t.slice(r+1,-1).split(`,`).length;return n.templates.get(i)?.has(a)===!0}function nativeTypeRefusal(e){return`A \`native.type\` is written into DDL verbatim, so a document may carry only a native type from the '${e}' dialect's closed catalog — the values the ${K[e]} native-type constants produce. See the native types documentation (docs/schema/native-types).`}function refuse(e,t,n){throw new i({kind:`schema-builder`,builder:e,path:t},[{path:t,message:n}])}function admitNativeType(e,t){return t===void 0?void 0:admitDeclaredNativeType(e,t)}function admitDeclaredNativeType(e,n){if(t(n)||refuse(e,`nativeType`,"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)"),k(n)){let{db:t,type:r}=n;(!j.includes(t)||typeof r!=`string`)&&refuse(e,`nativeType`,`A tagged native type is \`{ db, type }\`: \`db\` one of ${j.join(`, `)} and \`type\` a string`);let i=j.find(e=>Object.hasOwn(n,e));return i!==void 0&&refuse(e,`nativeType.${i}`,`A tagged native type ('db: ${t}') cannot also carry a '${i}' entry: declare one tagged type, or a map by dialect (\`{ pg, mysql, sqlite }\`)`),n}return admitNativeTypeMap(e,n)}function admitNativeTypeMap(e,t){for(let n of Object.keys(t))j.some(e=>e===n)||refuse(e,`nativeType.${n}`,`'${n}' is not a dialect: a native-type map names only ${j.join(`, `)}`);let n={};return Object.hasOwn(t,`pg`)&&(n.pg=admitEntry(e,`pg`,t.pg)),Object.hasOwn(t,`mysql`)&&(n.mysql=admitEntry(e,`mysql`,t.mysql)),Object.hasOwn(t,`sqlite`)&&(n.sqlite=admitEntry(e,`sqlite`,t.sqlite)),Object.keys(n).length===0&&refuse(e,`nativeType`,`A native-type map names at least one dialect; omit the argument to keep every automatic column`),Object.freeze(n)}function admitEntry(e,n,r){let i=t(r)?r.db:void 0,a=t(r)?r.type:void 0;return(i!==n||typeof a!=`string`)&&refuse(e,`nativeType.${n}`,`The '${n}' entry must be a ${K[n]} native type (\`{ db: "${n}", type }\`)`),Object.freeze({db:n,type:a})}function buildCatalogs(){let e={pg:emptyCatalog(),mysql:emptyCatalog(),sqlite:emptyCatalog()};return walk(M,e.pg),walk(N,e.mysql),walk(A,e.sqlite),e}function emptyCatalog(){return{exact:new Set,templates:new Map}}function walk(e,t){if(typeof e==`function`){deriveFunction(e,t);return}let n=e.type;if(typeof n==`string`){t.exact.add(n);return}for(let n of Object.values(e))walk(n,t)}function deriveFunction(e,t){for(let n of U){let r=e(...n).type,i=r.indexOf(`(`);if(i===-1){admit(t,r,0);continue}let a=r.slice(i+1,-1).split(`,`);a.every(e=>W.test(e))&&admit(t,r.slice(0,i),a.length)}}function admit(e,t,n){let r=e.templates.get(t);if(r===void 0){e.templates.set(t,new Set([n]));return}r.add(n)}const J=new DataView(new ArrayBuffer(192));for(let[e,t]of[1,0,32898,0,32906,2147483648,2147516416,2147483648,32907,0,2147483649,0,2147516545,2147483648,32777,2147483648,138,0,136,0,2147516425,0,2147483658,0,2147516555,0,139,2147483648,32905,2147483648,32771,2147483648,32770,2147483648,128,2147483648,32778,0,2147483658,2147483648,2147516545,2147483648,32896,2147483648,2147483649,0,2147516424,2147483648].entries())J.setInt32(e*4,t,!0);const ae=new DataView(new Uint8Array([0,1,62,28,27,36,44,6,55,20,3,10,43,25,39,41,45,15,21,8,18,2,61,56,14]).buffer),oe=new DataView(new Uint8Array([0,10,20,5,15,16,1,11,21,6,7,17,2,12,22,23,8,18,3,13,14,24,9,19,4]).buffer),Y=new Uint8Array(200),X=new DataView(Y.buffer),Z=new DataView(new ArrayBuffer(200)),Q=new DataView(new ArrayBuffer(40));function permute(){for(let e=0;e<24;e++){for(let e=0;e<5;e++){let t=0,n=0;for(let r=0;r<25;r+=5)t^=X.getInt32((e+r)*8,!0),n^=X.getInt32((e+r)*8+4,!0);Q.setInt32(e*8,t,!0),Q.setInt32(e*8+4,n,!0)}for(let e=0;e<5;e++){let t=Q.getInt32((e+1)%5*8,!0),n=Q.getInt32((e+1)%5*8+4,!0),r=Q.getInt32((e+4)%5*8,!0)^(t<<1|n>>>31),i=Q.getInt32((e+4)%5*8+4,!0)^(n<<1|t>>>31);for(let t=0;t<25;t+=5){let n=(e+t)*8;X.setInt32(n,X.getInt32(n,!0)^r,!0),X.setInt32(n+4,X.getInt32(n+4,!0)^i,!0)}}Z.setInt32(0,X.getInt32(0,!0),!0),Z.setInt32(4,X.getInt32(4,!0),!0);for(let e=1;e<25;e++){let t=ae.getUint8(e),n=X.getInt32(e*8,!0),r=X.getInt32(e*8+4,!0),i=oe.getUint8(e)*8;if(t<32)Z.setInt32(i,n<<t|r>>>32-t,!0),Z.setInt32(i+4,r<<t|n>>>32-t,!0);else{let e=t-32;Z.setInt32(i,r<<e|n>>>32-e,!0),Z.setInt32(i+4,n<<e|r>>>32-e,!0)}}for(let e=0;e<25;e+=5)for(let t=0;t<5;t++){let n=(e+t)*8,r=(e+(t+1)%5)*8,i=(e+(t+2)%5)*8;X.setInt32(n,Z.getInt32(n,!0)^~Z.getInt32(r,!0)&Z.getInt32(i,!0),!0),X.setInt32(n+4,Z.getInt32(n+4,!0)^~Z.getInt32(r+4,!0)&Z.getInt32(i+4,!0),!0)}X.setInt32(0,X.getInt32(0,!0)^J.getInt32(e*8,!0),!0),X.setInt32(4,X.getInt32(4,!0)^J.getInt32(e*8+4,!0),!0)}}function absorb(e,t){for(let n=0;n<72;n+=4)X.setInt32(n,X.getInt32(n,!0)^e.getInt32(t+n,!0),!0);permute()}function sha3_512(e){Y.fill(0);let t=e.length,n=new DataView(e.buffer,e.byteOffset,t),r=Math.floor(t/72);for(let e=0;e<r;e++)absorb(n,e*72);let i=new Uint8Array(72),a=t-r*72;return i.set(e.subarray(r*72)),i[a]=6,i[71]=a===71?134:128,absorb(new DataView(i.buffer),0),Uint8Array.from(Y.subarray(0,64))}function uuidV4(){let e=globalThis.crypto;return typeof e?.randomUUID==`function`?e.randomUUID():E(re(D(w,`uuid`)))}const defaultUuid=e=>()=>S(e,uuidV4()),defaultUuidV7=e=>()=>S(e,E(ee(Date.now(),D(T,`uuidv7`))));function incrementUlidRandom(e){let t=Uint8Array.from(e),n=new DataView(t.buffer);for(let e=t.length-1;e>=0;e--){let r=n.getUint8(e)+1;if(n.setUint8(e,r&255),r<=255)return t}return g(`s.string().ulid`,`generate`,`This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier`)}function createUlidGenerator(e={}){let t=e.now??Date.now,n=e.random??(e=>D(e,`ulid`)),r;return()=>{let e=t();return r=r!==void 0&&e<=r.time?{time:r.time,random:incrementUlidRandom(r.random)}:{time:e,random:n(b)},te(h(r.time,r.random))}}const se=createUlidGenerator(),defaultUlid=e=>()=>S(e,se()),defaultKsuid=e=>()=>S(e,x(_(Math.floor(Date.now()/1e3),D(v,`ksuid`)))),defaultNanoid=(e,t)=>{let n=e??y;return(!Number.isInteger(n)||n<1||n>C)&&g(`s.string().nanoid`,`length`,`A nanoid length must be a whole number of characters between 1 and ${C}; received ${n}`),()=>{let e=``;for(let t of D(n,`nanoid`))e+=ne.charAt(t&63);return S(t,e)}},ce=new TextEncoder;function secureFloat(){let e=D(4,`cuid`);return new DataView(e.buffer,e.byteOffset,e.byteLength).getUint32(0,!0)/4294967296}function createEntropy(e,t){let n=``;for(;n.length<e;)n+=Math.floor(t()*36).toString(36);return n}function hashBase36(e){let t=0n;for(let n of sha3_512(ce.encode(e)))t=t<<8n|BigInt(n);return t.toString(36).slice(1)}function createFingerprint(e){return hashBase36(Object.keys(globalThis).toString()+createEntropy(32,e)).substring(0,32)}function createCuid2(e={}){let t=e.random??secureFloat,n=e.counter??createCounter(Math.floor(t()*476782367)),r=e.length??24,i=e.fingerprint??createFingerprint(t);return()=>{let e=`abcdefghijklmnopqrstuvwxyz`.charAt(Math.floor(t()*26)),a=Date.now().toString(36),o=n().toString(36);return e+hashBase36(a+createEntropy(r,t)+o+i).substring(1,r)}}function createCounter(e){let t=e;return()=>{let e=t;return t++,e}}let le;const defaultCuid=e=>()=>S(e,(le??=createCuid2())());function identifierGenerator(e){let{kind:t,prefix:n,length:r}=e;switch(t){case`uuid`:return defaultUuid(n);case`uuidv7`:return defaultUuidV7(n);case`ulid`:return defaultUlid(n);case`ksuid`:return defaultKsuid(n);case`nanoid`:return defaultNanoid(r,n);case`cuid`:return defaultCuid(n);default:return g(`s.string`,`generate`,`This generator is not a string identifier format`)}}const $=O.string();var ue=class StringScalar{state;_nativeType;constructor(e,t){this.state=e,this._nativeType=t}nullable(){return new StringScalar(updateState(this,{nullable:!0,hasDefault:!0,default:nullableDefault(this.state),optional:!0,base:O.string({nullable:!0,array:this.state.array,schema:this.state.schema})}),this._nativeType)}array(){return isGeneratorDefault(this.state.default)&&refuseListGenerator(`s.string`),new StringScalar(updateState(this,{array:!0,base:O.string({nullable:this.state.nullable,array:!0,schema:this.state.schema})}),this._nativeType)}id(e){let t=typeof e==`object`?e.generate:void 0,n=typeof e==`string`?e:e?.prefix,r=this.state.autoGenerate;r&&ie(n)&&refuseSecondIdPrefix(r);let i=r?{...r,generate:t??r.generate}:{kind:`ulid`,prefix:n,implicit:!0,generate:t};return this.withIdentifier(i,!0)}unique(){return new StringScalar(updateState(this,{isUnique:!0}),this._nativeType)}default(e){return new StringScalar(updateState(this,{hasDefault:!0,default:e,optional:!0}),this._nativeType)}schema(e){return new StringScalar(updateState(this,{schema:e,base:O.string({nullable:this.state.nullable,array:this.state.array,schema:e})}),this._nativeType)}map(e){return new StringScalar(updateState(this,{columnName:e}),this._nativeType)}uuid(e){return this.withFormat(`uuid`,e)}uuidv7(e){return this.withFormat(`uuidv7`,e)}ksuid(e){return this.withFormat(`ksuid`,e)}ulid(e){return this.withFormat(`ulid`,e)}cuid(e){return this.withFormat(`cuid`,e)}nanoid(e,t){return this.withFormat(`nanoid`,typeof e==`number`?{length:e,prefix:t}:e??{prefix:t})}withFormat(e,t){let n=typeof t==`string`?{prefix:t}:t;return this.withIdentifier({kind:e,prefix:n?.prefix,length:e===`nanoid`?n?.length:void 0,generate:n?.generate??this.state.autoGenerate?.generate},this.state.isId)}withIdentifier(e,t){let n=identifierGenerator(e),r=this.state.hasDefault&&!isGeneratorDefault(this.state.default),i=(e.generate===!0||t&&e.generate!==!1)&&!r;return this.state.array&&i&&refuseListGenerator(`s.string`),new StringScalar(updateState(this,{isId:t,isUnique:t||this.state.isUnique,autoGenerate:e,hasDefault:r||i,optional:r||i,default:i?generatorDefault(n):r?this.state.default:void 0}),this._nativeType)}_internal;get"~"(){return this._internal??={state:this.state,nativeType:this._nativeType}}};const string=e=>new ue(createDefaultState(`string`,$),admitNativeType(`s.string`,e));function refuseSecondIdPrefix(e){return g(`s.string().id`,`prefix`,`This field already declares a '${e.kind}' generator${e.prefix?` with the prefix '${e.prefix}'`:``}. A prefix is spelled once, on the call that declares the format`)}function preflightModelRegistrationIdentity(e){let t=new Map;for(let[n,r]of e){if(typeof r!=`object`||!r||!r[`~`]?.names||!r[`~`]?.state?.scalars)return{code:`M008`,message:`Schema entry '${n}' is not a model; pass an explicit object containing only s.model() definitions`,severity:`error`,model:n};let e=r[`~`].names.ts??t.get(r);if(e!==void 0&&e!==n)return doubleRegistrationIssue(e,n);t.set(r,n)}}function doubleRegistrationIssue(e,t){return{code:`M003`,message:`Model registered as '${e}' cannot also be registered as '${t}'; one model object binds one schema key`,severity:`error`,model:t}}export{toOne as C,put as S,variantToManyTerminal as T,getTableName as _,nativeTypeRefusal as a,emptyRecord as b,isGeneratorDefault as c,updateState as d,SchemaValidationError as f,getColumnName as g,V as h,isNativeTypeInCatalog as i,nullableDefault as l,thrownAsError as m,string as n,createDefaultState as o,isSchemaValidationError as p,admitNativeType as r,generatorDefault as s,preflightModelRegistrationIdentity as t,refuseListGenerator as u,isTotalIndex as v,normalizeVariantEntries as w,own as x,model as y};
4
+ //# sourceMappingURL=registration-preflight-DEjv050M.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registration-preflight-DEjv050M.mjs","names":["#state","#internal","state","#state","#internal","state","#withForeignKeyAction","#localFields","state","state","v","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames","state","catalogs","v","state","model"],"sources":["../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/record.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts","../src/schema/validation/error.ts","../src/schema/scalars/common.ts","../src/schema/scalars/native-catalog.ts","../src/validation/primitives/sha3.ts","../src/schema/scalars/string/autogenerate.ts","../src/schema/scalars/string/scalar.ts","../src/schema/registration-preflight.ts"],"sourcesContent":["// Variant target domains: the normalization owner and the two variant terminals.\n//\n// \"Polymorphic\" is not a relation family. It is the derived observation that a\n// declaration's TARGET DOMAIN holds named variants instead of one model, which\n// is why the two variant terminals are reached through the same `s.toOne` /\n// `s.toMany` factories as the model-target ones. What is irreducibly different\n// is the legal local configuration: a row-held variant to-one may be\n// `.optional()` and owns no public foreign key, and a member-junction variant\n// to-many names one junction per variant through an exact `.through(...)` map.\n\nimport type { Model } from \"@schema/model\";\nimport type { Scalar } from \"@schema/scalars/base\";\nimport { isValidSchemaIdentifier } from \"../identifier\";\nimport {\n createTargetSettlement,\n declaredKeys,\n hasExactKeys,\n isPlainRecord,\n normalizeRelationName,\n type RelationBuilder,\n readCallerProperty,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n Getter,\n RelationInternal,\n Replace,\n VariantEntry,\n VariantJunctionOverride,\n VariantManyEntry,\n VariantToManyState,\n VariantToOneState,\n} from \"./types\";\n\n/**\n * The stored-discriminator grammar. A stored value is written to a physical\n * column and read back by migrations and predicates, so it admits namespaced\n * and versioned spellings the public variant key does not.\n */\nconst STORED_VALUE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/;\n\nconst THROUGH_ENTRY_KEYS = [\"table\", \"source\", \"target\"] as const;\n\n// =============================================================================\n// FACTORY-LEVEL TYPES\n// =============================================================================\n\nexport type VariantGetterMap = Readonly<Record<string, Getter>>;\n\n/**\n * The map overload's phantom refusal.\n *\n * It is NOT redundant with {@link GetterOnly}. With the map overload first and\n * an unconstrained getter overload second, a structurally-map argument that\n * fails this guard would otherwise fall through to the getter overload, whose\n * conditional return answers `never` — and `never` is assignable to a model\n * shape, so the refusal would disappear entirely. This guard uniquely owns\n * \"structurally a map, but not a legal variant map\"; `GetterOnly` uniquely owns\n * \"not a map at all and not a getter\".\n */\nexport type VariantMapGuard<Entries> = string extends keyof Entries\n ? {\n readonly \"a variant map needs literal keys, not a string index signature\": never;\n }\n : [keyof Entries] extends [never]\n ? { readonly \"a variant map needs at least one variant\": never }\n : unknown;\n\nexport type VariantOptions<Entries> = {\n readonly values: { readonly [Key in keyof Entries]: string };\n};\n\n/**\n * The whole options bag is exact, not only `values`: a NON-FRESH bag with a\n * sibling key beside `values` sails through excess-property checking, so the\n * unknown keys are refused structurally.\n */\nexport type ExactVariantOptions<Options, Entries> = Options extends undefined\n ? unknown\n : Record<Exclude<keyof Options, \"values\">, never> & {\n readonly values: Record<\n Exclude<\n keyof (Options extends { readonly values: infer Values }\n ? Values\n : never),\n keyof Entries\n >,\n never\n >;\n };\n\n/**\n * Normalized entries carry the getter's exact type and a plain `string` stored\n * value: the stored discriminator is runtime storage, never a public result\n * discriminator, so carrying its literal would be a public type parameter no\n * consumer reads.\n */\nexport type NormalizedOneEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n };\n};\n\nexport type NormalizedManyEntries<Entries> = {\n readonly [Key in keyof Entries]: {\n readonly getter: Entries[Key];\n readonly storedValue: string;\n readonly junction?: VariantJunctionOverride;\n };\n};\n\ntype VariantEntriesOfState<State> = State extends {\n readonly target: { readonly entries: infer Entries };\n}\n ? Entries\n : never;\n\ntype VariantThroughMap<Entries> = {\n readonly [Key in keyof Entries]: VariantJunctionOverride;\n};\n\ntype ExactVariantThroughMap<Given, Entries> = Record<\n Exclude<keyof Given, keyof Entries>,\n never\n> & {\n readonly [Key in keyof Given]: Record<\n Exclude<keyof Given[Key], keyof VariantJunctionOverride>,\n never\n >;\n};\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACES\n// =============================================================================\n\n/** A slot that holds at most one membership across its variants. */\nexport type VariantToOneRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToOneRelation<Replace<State, { readonly name: Name }>>;\n optional(): VariantToOneRelation<Replace<State, { readonly optional: true }>>;\n};\n\n/**\n * A slot that holds a collection across its variants. No `.optional()`: an\n * empty collection is already the empty case.\n */\nexport type VariantToManyRelation<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): VariantToManyRelation<Replace<State, { readonly name: Name }>>;\n through<\n const ThroughMap extends VariantThroughMap<VariantEntriesOfState<State>>,\n >(\n map: ThroughMap &\n ExactVariantThroughMap<ThroughMap, VariantEntriesOfState<State>>\n ): VariantToManyRelation<State>;\n};\n\n// =============================================================================\n// NORMALIZATION\n// =============================================================================\n\n/**\n * Read the target map and its options ONCE, judge every structurally knowable\n * fact, and build the single normalized entry map. There is no separately\n * stored `targets`, `values` or `through` map to keep in sync.\n *\n * Every own property at both map levels is read exactly once here and pinned as\n * a plain value: a live accessor could otherwise answer validation with one\n * value and the storage builder with another. Reading a property's value does\n * not invoke a target thunk; getters are stored as functions and stay lazy.\n */\nexport function normalizeVariantEntries(\n builder: RelationBuilder,\n variants: unknown,\n options: unknown\n): Readonly<Record<string, VariantEntry>> {\n if (!isPlainRecord(variants)) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A relation target is either `() => model` or a plain map of named `() => model` getters\"\n );\n }\n const variantKeys = declaredKeys(variants);\n if (variantKeys.length === 0) {\n refuseRelationInput(\n builder,\n \"target\",\n \"A variant map needs at least one variant\"\n );\n }\n const storedValues = readStoredValues(builder, variantKeys, options);\n const entries: Record<string, VariantEntry> = {};\n for (const variantKey of variantKeys) {\n if (!isValidSchemaIdentifier(variantKey)) {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant key '${variantKey}' is not a valid schema identifier`\n );\n }\n const getter = readCallerProperty(\n builder,\n variants,\n variantKey,\n `target.${variantKey}`\n );\n if (typeof getter !== \"function\") {\n refuseRelationInput(\n builder,\n `target.${variantKey}`,\n `Variant '${variantKey}' must be a lazy getter; write \\`() => model\\` rather than the model itself`\n );\n }\n entries[variantKey] = Object.freeze({\n getter,\n storedValue: storedValues[variantKey] ?? variantKey,\n });\n }\n return Object.freeze(entries);\n}\n\n/**\n * The stored discriminator per variant: each public key by default, or the\n * exact `values` bag when one is supplied. An explicit `undefined` is\n * equivalent to omission; `{}` is not, because it declares an options bag\n * without the one option it may carry.\n */\nfunction readStoredValues(\n builder: RelationBuilder,\n variantKeys: readonly string[],\n options: unknown\n): Record<string, string> {\n if (options === undefined) return {};\n if (!isPlainRecord(options)) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value\"\n );\n }\n if (!hasExactKeys(declaredKeys(options), [\"values\"])) {\n refuseRelationInput(\n builder,\n \"options\",\n \"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value\"\n );\n }\n const values = readCallerProperty(\n builder,\n options,\n \"values\",\n \"options.values\"\n );\n if (!isPlainRecord(values)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n \"`values` must be a plain record keyed by every variant\"\n );\n }\n const valueKeys = declaredKeys(values);\n if (!hasExactKeys(valueKeys, variantKeys)) {\n refuseRelationInput(\n builder,\n \"options.values\",\n `\\`values\\` must be exact over the variant keys ${renderKeys(variantKeys)}; it declares ${renderKeys(valueKeys)}`\n );\n }\n const storedValues: Record<string, string> = {};\n const claimed = new Set<string>();\n for (const variantKey of variantKeys) {\n const storedValue = readCallerProperty(\n builder,\n values,\n variantKey,\n `options.values.${variantKey}`\n );\n if (typeof storedValue !== \"string\" || !STORED_VALUE.test(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value for variant '${variantKey}' must match the stored-discriminator grammar`\n );\n }\n if (claimed.has(storedValue)) {\n refuseRelationInput(\n builder,\n `options.values.${variantKey}`,\n `Stored value '${storedValue}' is declared for more than one variant`\n );\n }\n claimed.add(storedValue);\n storedValues[variantKey] = storedValue;\n }\n return storedValues;\n}\n\nfunction renderKeys(keys: readonly string[]): string {\n return `[${keys.map((key) => `'${key}'`).join(\", \")}]`;\n}\n\n/**\n * Fold one member-junction override into each normalized entry. The outer map\n * is exact over the variants and every inner value is exact — the runtime\n * mirror of the `.through()` type contract, and the reason there is no second\n * `through` map to keep in sync with the entries.\n */\nfunction foldMemberJunctions(\n entries: Readonly<Record<string, VariantEntry>>,\n through: unknown\n): Readonly<Record<string, VariantManyEntry>> {\n const variantKeys = Object.keys(entries);\n if (!isPlainRecord(through)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n \"`.through()` takes a plain map keyed by every variant\"\n );\n }\n if (!hasExactKeys(declaredKeys(through), variantKeys)) {\n refuseRelationInput(\n \"s.toMany\",\n \"through\",\n `\\`.through()\\` must be exact over the variant keys ${renderKeys(variantKeys)}`\n );\n }\n const folded: Record<string, VariantManyEntry> = {};\n for (const [variantKey, entry] of Object.entries(entries)) {\n const override = readCallerProperty(\n \"s.toMany\",\n through,\n variantKey,\n `through.${variantKey}`\n );\n folded[variantKey] = Object.freeze({\n ...entry,\n junction: readJunctionOverride(variantKey, override),\n });\n }\n return Object.freeze(folded);\n}\n\nfunction readJunctionOverride(\n variantKey: string,\n override: unknown\n): VariantJunctionOverride {\n const path = `through.${variantKey}`;\n if (!isPlainRecord(override)) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' must be a plain \\`{ table, source, target }\\` record`\n );\n }\n const table = readCallerProperty(\n \"s.toMany\",\n override,\n \"table\",\n `${path}.table`\n );\n const source = readCallerProperty(\n \"s.toMany\",\n override,\n \"source\",\n `${path}.source`\n );\n const target = readCallerProperty(\n \"s.toMany\",\n override,\n \"target\",\n `${path}.target`\n );\n if (\n !hasExactKeys(declaredKeys(override), THROUGH_ENTRY_KEYS) ||\n typeof table !== \"string\" ||\n typeof source !== \"string\" ||\n typeof target !== \"string\"\n ) {\n refuseRelationInput(\n \"s.toMany\",\n path,\n `Member junction '${variantKey}' declares exactly \\`table\\`, \\`source\\` and \\`target\\`, all strings`\n );\n }\n return Object.freeze({ table, source, target });\n}\n\n// =============================================================================\n// TERMINALS\n// =============================================================================\n\n/**\n * Private terminal machinery. None of the four terminal classes is exported\n * from its module, let alone from the package: callers see only the\n * capabilities the two factories return. The two constructor helpers below are\n * the whole cross-module surface.\n */\nclass VariantToOne {\n readonly #state: VariantToOneState;\n readonly #internal: RelationInternal<VariantToOneState>;\n\n constructor(state: VariantToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToOne {\n return new VariantToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n optional(): VariantToOne {\n return new VariantToOne({ ...this.#state, optional: true });\n }\n\n get \"~\"(): RelationInternal<VariantToOneState> {\n return this.#internal;\n }\n}\n\nclass VariantToMany {\n readonly #state: VariantToManyState;\n readonly #internal: RelationInternal<VariantToManyState>;\n\n constructor(state: VariantToManyState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement((variantKey) =>\n readVariantGetter(this.#state, variantKey)\n ),\n });\n }\n\n name(name: string): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n name: normalizeRelationName(\"s.toMany\", name),\n });\n }\n\n through(map: unknown): VariantToMany {\n return new VariantToMany({\n ...this.#state,\n target: {\n kind: \"variants\",\n entries: foldMemberJunctions(this.#state.target.entries, map),\n },\n });\n }\n\n get \"~\"(): RelationInternal<VariantToManyState> {\n return this.#internal;\n }\n}\n\n/** Construct the row-held variant terminal for `s.toOne`. */\nexport function variantToOneTerminal(state: VariantToOneState): AnyRelation {\n return new VariantToOne(state);\n}\n\n/** Construct the member-junction variant terminal for `s.toMany`. */\nexport function variantToManyTerminal(state: VariantToManyState): AnyRelation {\n return new VariantToMany(state);\n}\n\nfunction readVariantGetter(\n state: VariantToOneState | VariantToManyState,\n variantKey: string | undefined\n): unknown {\n if (variantKey === undefined) return undefined;\n const entry = state.target.entries[variantKey];\n return entry === undefined ? undefined : entry.getter;\n}\n\n// =============================================================================\n// RESOLVED VARIANT STORAGE COLUMN\n// =============================================================================\n// Resolution OUTPUT, not declaration state: one private column the variant\n// row-storage owner derives, carried on the resolved edge and read by the\n// serializer and the engine. The descriptors that used to sit beside it are\n// gone — the resolved edge IS the topology, and a second copy of it on the\n// model was a second answer to every question the edge already answers.\n\nexport interface PolymorphicStorageColumn {\n readonly name: string;\n readonly scalar: Scalar;\n readonly nullable: boolean;\n /**\n * The KEY this private column stands in for, when it stands in for one.\n *\n * A row carrier's id column holds every variant's primary key, and what\n * those keys hold — an identifier domain above all — may be DERIVED rather\n * than declared: the ordinary one-to-one child whose primary key IS its\n * parent foreign key declares nothing and still holds uuids. The scalar\n * alone cannot answer that (derivation is keyed by model and field, never by\n * a scalar instance two models may share), so the column carries the pair\n * the one lookup takes. Every variant's key agrees on the answer or the\n * carrier does not exist — that agreement is what the identifier-domain\n * derivation refuses when it fails — so the FIRST member's key is the\n * carrier's key.\n *\n * The type discriminator column stands in for no key and carries none.\n */\n readonly reference?: {\n readonly model: Model<any>;\n readonly field: string;\n };\n}\n","// `s.toOne` — one of the two relation factories.\n//\n// The factory states the SLOT CARDINALITY (one) and its argument states the\n// TARGET DOMAIN (one model, or named variants). Which endpoint owns a foreign\n// key, whether the pair is one-to-one or many-to-one, and whether a model-target\n// slot may be empty are DERIVED later by the full-schema topology owner.\n\nimport {\n type ExactVariantOptions,\n type NormalizedOneEntries,\n normalizeVariantEntries,\n type VariantGetterMap,\n type VariantMapGuard,\n type VariantOptions,\n type VariantToOneRelation,\n variantToOneTerminal,\n} from \"./polymorphic\";\nimport {\n createTargetSettlement,\n normalizeFieldTuple,\n normalizeReferentialAction,\n normalizeRelationName,\n refuseRelationInput,\n} from \"./terminal\";\nimport type {\n AnyRelation,\n ForeignKeyDeclaration,\n Getter,\n GetterOnly,\n ModelToOneState,\n NonEmptyFieldTuple,\n ReferentialAction,\n RelationInternal,\n Replace,\n} from \"./types\";\n\n// =============================================================================\n// TERMINAL CAPABILITY SURFACE\n// =============================================================================\n\n/**\n * Referential actions exist only once a complete reference exists — they act on\n * a foreign key, and there is no foreign key to act on before\n * `.references(...)` completes the pair.\n */\ntype ForeignKeyActions<State> = {\n onDelete<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onDelete: Action }> }\n >\n : State\n >;\n onUpdate<const Action extends ReferentialAction>(\n action: Action\n ): ModelToOneRelation<\n State extends { readonly foreignKey: infer FK }\n ? Replace<\n State,\n { readonly foreignKey: Replace<FK, { onUpdate: Action }> }\n >\n : State\n >;\n};\n\ntype ModelToOneCapabilities<State> = {\n readonly \"~\": RelationInternal<State>;\n name<const Name extends string>(\n name: Name\n ): ModelToOneRelation<Replace<State, { readonly name: Name }>>;\n fields<const Fields extends NonEmptyFieldTuple>(\n ...fields: Fields\n ): ReferencesStage<State, Fields>;\n};\n\n/**\n * A model-target singular slot. It exposes no `.optional()`: emptiness follows\n * from the nullability of a complete local foreign-key tuple, and a non-owning\n * singular view is derived nullable.\n */\nexport type ModelToOneRelation<State> = ModelToOneCapabilities<State> &\n (State extends { readonly foreignKey: ForeignKeyDeclaration }\n ? ForeignKeyActions<State>\n : unknown);\n\n/**\n * The transient value `.fields(...)` returns.\n *\n * It carries NO relation brand, so neither `ModelShape` nor any downstream\n * relation consumer can mistake an incomplete foreign key for trusted schema\n * state, and `s.model(...)` refuses it outright. It exposes only\n * `.references(...)` and `.name(...)`: a name must not be able to turn an\n * incomplete pair into schema truth.\n */\nexport type ReferencesStage<State, Fields extends NonEmptyFieldTuple> = {\n references<\n const References extends NonEmptyFieldTuple & {\n readonly length: Fields[\"length\"];\n },\n >(\n ...references: References\n ): ModelToOneRelation<\n Replace<\n State,\n {\n readonly foreignKey: Replace<\n State extends { readonly foreignKey: infer FK } ? FK : unknown,\n { readonly fields: Fields; readonly references: References }\n >;\n }\n >\n >;\n name<const Name extends string>(\n name: Name\n ): ReferencesStage<Replace<State, { readonly name: Name }>, Fields>;\n};\n\n// =============================================================================\n// PRIVATE TERMINALS\n// =============================================================================\n\nclass ModelToOne {\n readonly #state: ModelToOneState;\n readonly #internal: RelationInternal<ModelToOneState>;\n\n constructor(state: ModelToOneState) {\n this.#state = Object.freeze(state);\n this.#internal = Object.freeze({\n state: this.#state,\n settleTarget: createTargetSettlement(() => this.#state.target.getter),\n });\n }\n\n name(name: string): ModelToOne {\n return new ModelToOne({\n ...this.#state,\n name: normalizeRelationName(\"s.toOne\", name),\n });\n }\n\n fields(...fields: string[]): PendingReferences {\n return new PendingReferences(\n this.#state,\n normalizeFieldTuple(\"s.toOne\", \"fields\", fields)\n );\n }\n\n onDelete(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onDelete\", action);\n }\n\n onUpdate(action: ReferentialAction): ModelToOne {\n return this.#withForeignKeyAction(\"onUpdate\", action);\n }\n\n /**\n * The type surface hides both action setters until `.references(...)` has\n * completed a foreign key. This refusal covers the route a type pin cannot:\n * a JavaScript caller placing a referential action on a slot that owns no\n * foreign key, where the action would otherwise have nowhere to be stored and\n * would be silently dropped.\n */\n #withForeignKeyAction(\n action: \"onDelete\" | \"onUpdate\",\n value: ReferentialAction\n ): ModelToOne {\n const foreignKey = this.#state.foreignKey;\n if (foreignKey === undefined) {\n refuseRelationInput(\n \"s.toOne\",\n action,\n `'${action}' is available only after \\`.fields(...).references(...)\\` declares a foreign key`\n );\n }\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze({\n ...foreignKey,\n [action]: normalizeReferentialAction(action, value),\n }),\n });\n }\n\n get \"~\"(): RelationInternal<ModelToOneState> {\n return this.#internal;\n }\n}\n\n/**\n * The transient references stage. It has no `\"~\"` accessor by design: that\n * absence is what makes an incomplete chain unusable as a model member.\n */\nclass PendingReferences {\n readonly #state: ModelToOneState;\n readonly #localFields: NonEmptyFieldTuple;\n\n constructor(state: ModelToOneState, localFields: NonEmptyFieldTuple) {\n this.#state = state;\n this.#localFields = localFields;\n }\n\n name(name: string): PendingReferences {\n return new PendingReferences(\n { ...this.#state, name: normalizeRelationName(\"s.toOne\", name) },\n this.#localFields\n );\n }\n\n references(...references: string[]): ModelToOne {\n const referenced = normalizeFieldTuple(\"s.toOne\", \"references\", references);\n if (referenced.length !== this.#localFields.length)\n refuseReferenceArity(referenced.length, this.#localFields.length);\n // Completing a second stage replaces the pair atomically and preserves the\n // endpoint's name and referential actions; the prior terminal is untouched.\n const prior = this.#state.foreignKey;\n const foreignKey: ForeignKeyDeclaration = {\n fields: this.#localFields,\n references: referenced,\n ...(prior?.onDelete === undefined ? {} : { onDelete: prior.onDelete }),\n ...(prior?.onUpdate === undefined ? {} : { onUpdate: prior.onUpdate }),\n };\n return new ModelToOne({\n ...this.#state,\n foreignKey: Object.freeze(foreignKey),\n });\n }\n}\n\n/**\n * Is this model member a transient references stage?\n *\n * Deliberately nominal: a stage is only ever produced by `.fields(...)`, so an\n * `instanceof` test cannot be spoofed by a look-alike record, and the\n * `s.model(...)` boundary can refuse the one member shape that would otherwise\n * be silently dropped.\n */\nexport function isReferencesStage(value: unknown): boolean {\n return value instanceof PendingReferences;\n}\n\n// =============================================================================\n// FACTORY\n// =============================================================================\n\n/**\n * Declare a slot that holds AT MOST ONE membership.\n *\n * The map overload is declared first so a variant map is never swallowed by the\n * broad getter overload. Dispatch examines only the argument representation and\n * never invokes a getter.\n */\nexport function toOne<\n const Entries extends VariantGetterMap,\n const Options extends VariantOptions<Entries> | undefined = undefined,\n>(\n variants: Entries & VariantMapGuard<Entries>,\n options?: Options & ExactVariantOptions<Options, Entries>\n): VariantToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: {\n readonly kind: \"variants\";\n readonly entries: NormalizedOneEntries<Entries>;\n };\n}>;\nexport function toOne<const G>(getter: G & GetterOnly<G>): G extends Getter\n ? ModelToOneRelation<{\n readonly kind: \"relation\";\n readonly cardinality: \"one\";\n readonly target: { readonly kind: \"model\"; readonly getter: G };\n }>\n : never;\nexport function toOne(target: unknown, options?: unknown): AnyRelation {\n if (typeof target === \"function\") {\n // biome-ignore lint/complexity/noArguments: distinguishes omission from explicit undefined without changing the factory's public arity\n if (arguments.length > 1) {\n refuseRelationInput(\n \"s.toOne\",\n \"options\",\n \"A model-target relation takes exactly one argument\"\n );\n }\n return new ModelToOne({\n kind: \"relation\",\n cardinality: \"one\",\n target: { kind: \"model\", getter: target },\n });\n }\n return variantToOneTerminal({\n kind: \"relation\",\n cardinality: \"one\",\n target: {\n kind: \"variants\",\n entries: normalizeVariantEntries(\"s.toOne\", target, options),\n },\n });\n}\n\nfunction refuseReferenceArity(referenced: number, local: number): never {\n return refuseRelationInput(\n \"s.toOne\",\n \"references\",\n `\\`.references(...)\\` declares ${referenced} field(s) against ${local} local field(s); a foreign key pairs them positionally`\n );\n}\n","// Records keyed by DATA.\n//\n// A schema is built from maps whose keys come from somewhere else: a model\n// shape's field key, a document's model/field/variant key, an enum reference, a\n// default's own object keys. `record[key] = value` is not a safe way to build\n// such a map, because `__proto__` is an accessor on `Object.prototype`:\n// assigning through it sets a prototype and creates NO own key. The entry\n// disappears, and what is left is a well-formed object, so nothing downstream\n// can notice the loss.\n//\n// Reading has the mirror problem: `record[key]` resolves inherited members, so\n// a data key of `__proto__`, `constructor` or `toString` answers something the\n// map never held.\n//\n// One owner for both, used everywhere a key comes from data — the JSON\n// document's maps and `s.model(...)`'s classified member maps alike. It carries\n// no refusal: whether a key is a legal identifier is `isValidSchemaIdentifier`'s\n// question, asked at hydration and by the document reader, and the answer is the\n// same whichever way the key was written. The document READER needs neither\n// helper, because it asks that question before anything is written.\n\n/** A map with no inherited members, so a data key can only find what was put. */\nexport function emptyRecord<T>(): Record<string, T> {\n return Object.create(null);\n}\n\n/** Write one own key, whatever it is called. */\nexport function put<T>(target: Record<string, T>, key: string, value: T): void {\n Object.defineProperty(target, key, {\n value,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n}\n\n/** Read one own key, or nothing. */\nexport function own<T>(\n source: Record<string, T> | undefined,\n key: string\n): T | undefined {\n if (source === undefined || !Object.hasOwn(source, key)) return;\n return source[key];\n}\n","import { emptyRecord } from \"@schema/record\";\nimport type { AnyRelation } from \"@schema/relation\";\nimport { refuseRelationInput } from \"@schema/relation/terminal\";\n// Deep import: the references-stage predicate is the `s.model(...)` boundary's\n// own instrument and is deliberately not part of the relation package surface.\nimport { isReferencesStage } from \"@schema/relation/to-one\";\nimport type { Scalar } from \"@schema/scalars/base\";\n\n/**\n * Record of model fields - the canonical type for scalar and relation definitions.\n * A model field is either a scalar or a relation; ONE relation map holds both\n * target domains.\n */\nexport type AnyModelField = Scalar | AnyRelation;\nexport type ModelShape = Record<string, AnyModelField>;\n\n/**\n * The shape `s.model(...)` and `.extends(...)` accept: a model shape with no\n * member named `_count` or `_distance`, the names a selection's own outputs\n * reserve (relation counts, a distance). This is the compile-time spelling of\n * rule F010 for TypeScript callers; F010 (`memberNamesAreNotReserved`) stays\n * the contract for every caller. It constrains keys only and never reads a\n * member's type, so it cannot change what a shape infers. Each key's type is\n * its reason spelled as a string literal, so the diagnostic a caller reads\n * names it: no model member is a string, so nothing a shape can hold\n * satisfies it.\n */\nexport type DeclaredModelShape = ModelShape & {\n readonly _count?: \"`_count` is reserved for relation counts (F010)\";\n readonly _distance?: \"`_distance` is reserved for distance results (F010)\";\n};\n\nexport type NameFromKeys<\n TFields extends string[],\n TName extends string = \"\",\n> = TFields extends readonly [\n infer F extends string,\n ...infer R extends string[],\n]\n ? R extends []\n ? `${TName}_${F}`\n : NameFromKeys<R, TName extends \"\" ? F : `${TName}_${F}`>\n : never;\n\nexport interface CompoundConstraint<\n TFields extends string[],\n TName extends string | undefined = undefined,\n> {\n fields: TFields;\n name: TName extends undefined ? NameFromKeys<TFields> : TName;\n}\n\n/** Any compound constraint (for loose typing) */\nexport type AnyCompoundConstraint = CompoundConstraint<string[]>;\n\nexport type ToString<T> = T extends\n | string\n | number\n | bigint\n | boolean\n | null\n | undefined\n ? `${T}`\n : never;\n\nexport type StringKeyOf<T extends Record<string, any>> = {\n [K in keyof T]: K extends string ? K : never;\n}[keyof T];\n\nexport type ScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar ? ToString<K> : never;\n}[keyof T];\n\n/** Fixed-decimal list keys, which have value semantics but no key semantics. */\nexport type DecimalListScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"] extends { type: \"decimal\"; array: true }\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** GeoPoint keys have value semantics but no portable key/order semantics. */\nexport type PointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonNullablePointScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"type\"] extends \"point\"\n ? T[K][\"~\"][\"state\"][\"nullable\"] extends true\n ? never\n : ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type NonPointScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Scalar keys except fixed-decimal lists, which cannot be physical keys. */\nexport type NonDecimalListScalarKeys<T extends ModelShape> = Exclude<\n ScalarKeys<T>,\n string extends keyof T ? never : DecimalListScalarKeys<T>\n>;\n\n/** Scalar keys admitted in IDs, unique constraints, and foreign-key identity. */\nexport type PortableKeyScalarKeys<T extends ModelShape> = Exclude<\n NonDecimalListScalarKeys<T>,\n string extends keyof T ? never : PointScalarKeys<T>\n>;\n\n/** Extract relation keys from ModelState */\nexport type RelationKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends AnyRelation ? ToString<K> : never;\n}[keyof T];\n\nexport type RequiredScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"optional\"] extends true\n ? never\n : ToString<K>\n : never;\n}[keyof T];\n\nexport type UniqueScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"isId\"] extends true\n ? ToString<K>\n : T[K][\"~\"][\"state\"][\"isUnique\"] extends true\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\n/** Numeric scalar types for aggregations (avg, sum) */\nexport type NumericScalarType = \"int\" | \"number\" | \"decimal\" | \"bigint\";\n\n/** Extract keys of numeric scalars from a ModelShape */\nexport type NumericScalarKeys<T extends ModelShape> = {\n [K in keyof T]: T[K] extends Scalar\n ? T[K][\"~\"][\"state\"][\"array\"] extends true\n ? never\n : T[K][\"~\"][\"state\"][\"type\"] extends NumericScalarType\n ? ToString<K>\n : never\n : never;\n}[keyof T];\n\nexport type ScalarMap<T extends ModelShape> = {\n [K in ScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\nexport type RelationMap<T extends ModelShape> = {\n [K in RelationKeys<T>]: T[K] extends AnyRelation ? T[K] : never;\n};\n\nexport type UniqueScalarMap<T extends ModelShape> = {\n [K in UniqueScalarKeys<T>]: T[K] extends Scalar ? T[K] : never;\n};\n\n/**\n * ONE relation boundary, keyed on the internal brand.\n *\n * Trusted relation state originates only in `s.toOne` / `s.toMany`, and both\n * target domains carry `kind: \"relation\"` — so a model has one relation map and\n * no consumer has to ask which family a member belongs to. Scalars keep\n * `state.type`, so the two brands cannot collide.\n */\nfunction isRelation(value: unknown): value is AnyRelation {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n return (\n typeof state === \"object\" &&\n state !== null &&\n Reflect.get(state, \"kind\") === \"relation\"\n );\n}\n\nconst SCALAR_TYPES = new Set<string>([\n \"string\",\n \"int\",\n \"number\",\n \"decimal\",\n \"boolean\",\n \"datetime\",\n \"date\",\n \"time\",\n \"bigint\",\n \"json\",\n \"blob\",\n \"vector\",\n \"point\",\n \"enum\",\n]);\n\nfunction isScalar(value: unknown): value is Scalar {\n if (\n (typeof value !== \"object\" || value === null) &&\n typeof value !== \"function\"\n ) {\n return false;\n }\n const internal = Reflect.get(value, \"~\");\n if (typeof internal !== \"object\" || internal === null) return false;\n const state = Reflect.get(internal, \"state\");\n if (typeof state !== \"object\" || state === null) return false;\n const type = Reflect.get(state, \"type\");\n return typeof type === \"string\" && SCALAR_TYPES.has(type);\n}\n\n/**\n * The classified member maps are a PROJECTION of the shape: every member an\n * extractor recognizes appears in the map that claims it, under the key the\n * shape gave it. A shape key comes from the caller — a hand-written literal, a\n * generated schema, a JSON document's field name — so it can be any string, and\n * assigning into an ordinary object would lose a `__proto__` member to\n * `Object.prototype`'s setter. These maps come from `emptyRecord` and stay\n * private until complete: their null prototype makes every assignment an own\n * data entry, including `__proto__`, without defining a descriptor per member.\n *\n * Whether such a key is a LEGAL identifier is a separate question with a\n * separate owner (`isValidSchemaIdentifier`, enforced at hydration and by the\n * document reader). Keeping the member is what lets that owner name it.\n */\nexport const extractScalarMap = <T extends ModelShape>(fields: T) => {\n const scalars = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (isScalar(value)) {\n scalars[key] = value;\n }\n }\n return scalars as ScalarMap<T>;\n};\n\n/**\n * The `s.model(...)` member-classification boundary for relations.\n *\n * It gains exactly ONE refusal: a transient references stage — a chain that\n * started `.fields(...)` and never received `.references(...)` — is rejected\n * loudly rather than silently dropped, because that member declares a foreign\n * key the schema would then never have. Every other unrecognized member keeps\n * its existing silent-drop behavior; widening that is a separate decision.\n */\nexport const extractRelationMap = <T extends ModelShape>(fields: T) => {\n const relations = emptyRecord<AnyRelation>();\n for (const [key, value] of Object.entries(fields)) {\n if (isRelation(value)) {\n relations[key] = value;\n } else if (isReferencesStage(value)) {\n refuseRelationInput(\n \"s.model\",\n key,\n `Relation '${key}' started \\`.fields(...)\\` without \\`.references(...)\\`; complete the foreign key before using it as a model field`\n );\n }\n }\n return relations as RelationMap<T>;\n};\n\nexport const extractUniqueScalarMap = <T extends ModelShape>(fields: T) => {\n const uniques = emptyRecord<Scalar>();\n for (const [key, value] of Object.entries(fields)) {\n if (\n isScalar(value) &&\n (value[\"~\"].state.isUnique || value[\"~\"].state.isId)\n ) {\n uniques[key] = value;\n }\n }\n return uniques as UniqueScalarMap<T>;\n};\n\nexport const getNameFromKeys = <\n Name extends string | undefined,\n TFields extends any[],\n>(\n name: Name,\n fields: TFields\n) => {\n return (\n name ??\n (fields.join(\"_\") as Name extends undefined ? NameFromKeys<TFields> : Name)\n );\n};\n","// Model Class Implementation\n// Defines database models with scalars and relations\n\nimport type { ObjectSchema, VibSchema } from \"@validation\";\nimport v from \"@validation/primitives/v\";\nimport { emptyRecord, put } from \"../record\";\nimport type { AnyRelation } from \"../relation\";\nimport type { Scalar } from \"../scalars/base\";\nimport type { HydratedSchemaNames, SchemaNames } from \"../scalars/common\";\nimport {\n type DeclaredModelShape,\n extractRelationMap,\n extractScalarMap,\n extractUniqueScalarMap,\n getNameFromKeys,\n type ModelShape,\n type NameFromKeys,\n type NonNullablePointScalarKeys,\n type PortableKeyScalarKeys,\n type RelationMap,\n type ScalarMap,\n type StringKeyOf,\n type UniqueScalarMap,\n} from \"./helper\";\n// Re-export types from helpers for external use\n\n// =============================================================================\n// TYPE INFERENCE HELPER\n// =============================================================================\n\nexport interface ModelState {\n shape: ModelShape;\n compoundId:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n compoundUniques:\n | Record<string, ObjectSchema<Record<string, VibSchema>>>\n | undefined;\n tableName: string | undefined;\n indexes: IndexDefinition[];\n omit: Record<string, true> | undefined;\n scalars: Record<string, Scalar>;\n /** ONE canonical relation map, holding both target domains in shape order. */\n relations: Record<string, AnyRelation>;\n uniques: Record<string, Scalar>;\n}\n\n/** Initial model projections stay named when a consumer emits recursive graphs. */\nexport interface InitialModelState<Shape extends ModelShape>\n extends ModelState {\n shape: Shape;\n scalars: ScalarMap<Shape>;\n relations: RelationMap<Shape>;\n uniques: UniqueScalarMap<Shape>;\n omit: undefined;\n}\n\n/**\n * Internal accessor return type for Model[\"~\"]\n * Explicit type annotation to avoid TS7056 (type too complex to serialize)\n */\nexport interface ModelInternal<T extends ModelState> {\n state: T;\n names: SchemaNames;\n nameRegistry: {\n fields: Map<string, SchemaNames>;\n };\n getFieldName: (key: string) => HydratedSchemaNames;\n /** Cached scalar field names (computed once on first access) */\n scalarFieldNames: string[];\n /** Cached relation names (computed once on first access) */\n relationNames: string[];\n}\n\n/**\n * The index kinds a schema may declare. The union is the whole of what any\n * dialect accepts, not what all of them accept — `validateIndexType` in\n * `migrations/drivers/base.ts` refuses each one on the dialects whose\n * `supportsIndexTypes` does not list it, by name, at push time.\n *\n * `fulltext` and `spatial` are here because MySQL's whole round trip already\n * exists and only this union could not spell it: the emitter writes the\n * `FULLTEXT`/`SPATIAL` prefix and refuses to combine either with `UNIQUE`\n * (`mysql/index.ts`), the introspection reads them back and normalizes MySQL's\n * `RTREE` to `spatial` (`mysql/introspect.ts`), the migration snapshot's\n * `IndexDef` already carries both (`migrations/types.ts`), and the capability\n * list already declares them. See Phase 10 item 6 in\n * `docs/architecture/query-performance-plan.md`.\n */\nexport type IndexType =\n | \"btree\"\n | \"hash\"\n | \"gin\"\n | \"gist\"\n | \"fulltext\"\n | \"spatial\";\n\nexport interface IndexOptions {\n name?: string;\n unique?: boolean;\n type?: IndexType;\n where?: string; // For partial indexes (PostgreSQL)\n}\n\ntype OrdinaryIndexOptions = Omit<IndexOptions, \"type\"> & {\n type?: Exclude<IndexType, \"spatial\">;\n};\n\ntype GeoPointSpatialIndexOptions = {\n name?: string;\n type: \"spatial\";\n unique?: never;\n where?: never;\n};\n\nexport interface IndexDefinition<\n Keys extends string[] = string[],\n O extends IndexOptions = IndexOptions,\n> {\n fields: Keys;\n options: O;\n}\n\n/** A partial index cannot constrain rows excluded by its predicate. */\nexport function isTotalIndex(options: Pick<IndexOptions, \"where\">): boolean {\n return !options.where;\n}\n\nexport type UpdateIndexDefinition<\n State extends ModelState,\n Index extends IndexDefinition,\n> = [...State[\"indexes\"], Index];\n\n/** The name a compound `.id()` / `.unique()` constraint may be given. */\nexport interface CompoundKeyOptions {\n name?: string;\n}\n\n/**\n * An options bag that carries the surface's own keys and NOTHING else.\n *\n * A generic `O extends Options` is no guard on its own: when inference produces\n * a bag the constraint would reject, TypeScript CLAMPS `O` to the constraint and\n * only excess-property checking is left to catch the stray key — and that needs\n * a fresh object literal, so `.index([\"a\"], sharedIndexOptions)` sails through\n * with `uniqu: true` recorded as nothing at all. Demanding `never` for the\n * unknown keys refuses structurally instead, whatever the argument's freshness.\n * Same instrument as `UnknownOmitKeys` below.\n */\ntype ExactOptions<Given, Allowed> = Given &\n Record<Exclude<keyof Given, keyof Allowed>, never>;\n\n/**\n * The constraint name: the caller's `name` when they gave one, otherwise the\n * underscore-joined field names. Read off the options bag rather than a separate\n * inferred parameter so that ONE type parameter carries the whole literal — the\n * parameter `ExactOptions` needs in order to see the unknown keys.\n */\ntype CompoundKeyName<\n Keys extends string[],\n O extends CompoundKeyOptions,\n> = O extends { name: infer N extends string } ? N : NameFromKeys<Keys>;\n\nexport const mergeIndexDefinitions = <\n State extends ModelState,\n Index extends IndexDefinition,\n>(\n state: State,\n index: Index\n): UpdateIndexDefinition<State, Index> => {\n return [...state.indexes, index] as UpdateIndexDefinition<State, Index>;\n};\n\n// Publish the same completed state as fluent returns so a legacy explicit\n// Model<UpdateState<...>> annotation retains exact relation-link identity.\nexport type UpdateState<\n State extends ModelState,\n Update extends Partial<ModelState>,\n> = {\n [P in keyof (Omit<State, keyof Update> & Update)]: (Omit<\n State,\n keyof Update\n > &\n Update)[P];\n};\n\n/**\n * The keys a proposed `.omit()` names that this model does NOT have as a\n * scalar: the typos and the relation names.\n *\n * `Hidden` is inferred from the argument's own keys and is deliberately NOT\n * constrained to the scalar names. A constrained type parameter is no guard\n * here: when inference produces something the constraint rejects, TypeScript\n * silently CLAMPS the parameter to the constraint and only excess-property\n * checking — which needs a fresh object literal — is left to catch the bad\n * key. Anything non-fresh (`as const`, a spread, an annotated variable, a\n * widened `Record<string, true>`) then sails through and records a\n * hidden-column claim nobody wrote. Excluding the unknown keys and demanding\n * `never` for them refuses structurally instead, whatever the argument's\n * freshness, and a `never` the caller cannot produce is a compile error at the\n * offending key.\n *\n * Relations are absent from the accepted set because `State[\"scalars\"]` is the\n * scalar half of the shape (`ScalarMap`), the same source `.index()` /\n * `.id()` / `.unique()` key off. Reading it never touches a relation's\n * `getter`, the member that must not be resolved while two model consts still\n * refer to each other (see `RelationState.getter`).\n */\ntype UnknownOmitKeys<Hidden extends string, State extends ModelState> = Exclude<\n Hidden,\n StringKeyOf<State[\"scalars\"]>\n>;\n\n/**\n * This model's scalar names, each optionally flagged `true`.\n *\n * It carries NO refusal — `UnknownOmitKeys` does that — and it adds no\n * requirement, every key being optional. It is in the parameter for one\n * reason: an editor offers the keys of a CONCRETE contextual type, and\n * `Record<Hidden, true>` is not concrete until `Hidden` has been inferred from\n * the very literal being typed. Without this member `.omit({ ` autocompletes\n * the global scope; with it, the model's scalars.\n */\nexport type ModelOmitInput<State extends ModelState> = Partial<\n Record<StringKeyOf<State[\"scalars\"]>, true>\n>;\n\n/**\n * Merge a new compound constraint into the existing record so repeated\n * .id()/.unique() calls accumulate instead of replacing each other.\n * Resolves to just `Added` when nothing was set yet.\n */\ntype MergeCompound<Existing, Added> = Added &\n (Existing extends Record<string, ObjectSchema<Record<string, VibSchema>>>\n ? Existing\n : unknown);\n\n/**\n * Resolve compound-key members to their base schemas, refusing any name that\n * is not a scalar of the model AT THE DECLARING SITE. The typed surface\n * already refuses these names; this throw is the runtime backstop for\n * untyped callers and JSON documents (the document interpreter relocates it\n * onto the `ids[]`/`uniques[]` node that wrote it), and it must fire on the\n * rule-free paths (`serializeModels`, `generate`,\n * `push({ skipValidation: true })`) that never run the advisory rules. I003\n * keeps its own coverage: post-construction shape drift (`.extends()`\n * shadowing a key member) is invisible to this constructor.\n *\n * A module function rather than a `Model` method: adding members to the class\n * perturbs how TS compares mutually-recursive model instantiations.\n */\nfunction compoundMembers(\n state: ModelState,\n fields: readonly string[],\n label: string\n): Record<string, VibSchema> {\n refuseDuplicateModelKeyMembers(fields, label);\n const members = emptyRecord<VibSchema>();\n for (const fieldName of fields) {\n // `in` is exact here: both maps come from the extractors, which build\n // prototype-free records, so no key can resolve an inherited member.\n const scalar =\n fieldName in state.scalars ? state.scalars[fieldName] : undefined;\n if (!scalar) {\n throw new Error(\n fieldName in state.relations\n ? `${label} field '${fieldName}' is a relation and cannot be a key member`\n : `${label} field '${fieldName}' does not exist`\n );\n }\n put(members, fieldName, scalar[\"~\"].state.base);\n }\n return members;\n}\n\n/**\n * One compound ID or unique, written into its own slot. The first tuple of a\n * name is preserved before Record storage could overwrite it.\n */\nfunction withCompound(\n state: ModelState,\n slot: \"compoundId\" | \"compoundUniques\",\n label: \"Compound ID\" | \"Compound unique\",\n fields: readonly string[],\n options: CompoundKeyOptions | undefined\n): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, label);\n const name = getNameFromKeys(options?.name, storedFields);\n if (Object.hasOwn(state[slot] ?? {}, name)) {\n throw new Error(\n `${label} name '${name}' is already used by another compound key; give this tuple a distinct name`\n );\n }\n const fieldsRecord = compoundMembers(state, storedFields, label);\n return new Model({\n ...state,\n [slot]: {\n ...state[slot],\n [name]: v.object(fieldsRecord, { partial: false }),\n },\n });\n}\n\n/** Snapshot one declaration tuple without consulting caller iteration hooks. */\nfunction snapshotModelKeyMembers(fields: unknown, label: string): string[] {\n if (!Array.isArray(fields)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const memberCount = fields.length;\n const members = new Array<string>(memberCount);\n for (let position = 0; position < memberCount; position++) {\n if (!Object.hasOwn(fields, position)) {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n const member: unknown = fields[position];\n if (typeof member !== \"string\") {\n throw new Error(`${label} fields must be a dense array of strings`);\n }\n members[position] = member;\n }\n return members;\n}\n\n/** Snapshot the four public index options, including inherited accessors. */\nfunction snapshotIndexOptions(options: IndexOptions): IndexOptions {\n const name = options.name;\n const unique = options.unique;\n const type = options.type;\n const where = options.where;\n return {\n ...(name === undefined ? {} : { name }),\n ...(unique === undefined ? {} : { unique }),\n ...(type === undefined ? {} : { type }),\n ...(where === undefined ? {} : { where }),\n };\n}\n\n/** One physical key/index tuple cannot name the same column twice. */\nfunction refuseDuplicateModelKeyMembers(\n fields: readonly string[],\n label: string\n): void {\n if (new Set(fields).size !== fields.length) {\n throw new Error(`${label} cannot repeat a field in one tuple`);\n }\n}\n\n/**\n * Name registry for scalars and relations.\n * Maps scalar/relation keys to their resolved names (ts and sql).\n * This is populated during hydration.\n */\nexport interface NameRegistry {\n /** Scalar names: key -> {ts, sql} */\n fields: Map<string, SchemaNames>;\n}\n\nexport class Model<State extends ModelState> {\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #names: SchemaNames = {};\n // biome-ignore lint/style/useReadonlyClassProperties: <it is reassigned when hydrating schemas>\n #nameRegistry: NameRegistry = {\n fields: new Map(),\n };\n readonly #state: State;\n\n // Cached field metadata (lazily computed on first access)\n #scalarFieldNames: string[] | undefined;\n #relationNames: string[] | undefined;\n #internal: ModelInternal<State> | undefined;\n\n constructor(state: State) {\n this.#state = state;\n }\n\n // Materialize each completed modifier state inline before a recursive getter\n // captures it. A helper alias retains the whole prior modifier chain.\n /**\n * Maps the model to a specific database table name\n */\n map<Name extends string>(tableName: Name) {\n return new Model({ ...this.#state, tableName }) as unknown as Model<{\n [KState in keyof UpdateState<State, { tableName: Name }>]: UpdateState<\n State,\n { tableName: Name }\n >[KState];\n }>;\n }\n\n /**\n * Hide scalars from every result of this model — the schema-level exclusion.\n *\n * Keyed to the model's own SCALARS, so a typo or a relation name is a\n * compile error instead of an `omit` that quietly hides nothing. That\n * matters more here than anywhere else the builder takes field names: this\n * is the spelling used for secrets, and a silently-ignored key is a leaked\n * column. The refusal is per KEY, not per call: `{ secret: true, tokne:\n * true }` fails on `tokne` even though `secret` is real — two secrets with\n * one misspelled is the realistic case, and it is exactly the case an\n * excess-property-only refusal would wave through (see `UnknownOmitKeys`).\n *\n * Every value must be `true`. `false` has no meaning here (model-level omit\n * only ever hides) and a flag that may be `undefined` hides nothing at\n * runtime — `projectableScalarNames` compares against `true` — so\n * `Record<Hidden, true>` refuses both rather than recording a claim the\n * runtime would not honor.\n *\n * The literal survives the round trip — `.omit({ secret: true })` carries\n * exactly `{ secret: true }` into the state, not a widened record — which is\n * what every downstream `keyof State[\"omit\"]` reads. `Hidden` defaults to\n * `never` for the one call with nothing to infer from, `.omit({})`: a bare\n * `extends string` would fall back to `string` there and hand the state a\n * record keyed by every conceivable name.\n */\n omit<Hidden extends string = never>(\n items: Record<Hidden, true> &\n Record<UnknownOmitKeys<Hidden, State>, never> &\n ModelOmitInput<State>\n ) {\n return new Model({\n ...this.#state,\n omit: items,\n }) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n { omit: Record<Hidden, true> }\n >]: UpdateState<State, { omit: Record<Hidden, true> }>[KState];\n }>;\n }\n\n index<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n O extends OrdinaryIndexOptions = OrdinaryIndexOptions,\n >(\n fields: Keys,\n options?: ExactOptions<O, OrdinaryIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: Keys; options: O }> }\n >[KState];\n }>;\n index<\n const Key extends NonNullablePointScalarKeys<State[\"scalars\"]>,\n const O extends GeoPointSpatialIndexOptions,\n >(\n fields: [Key],\n options: ExactOptions<O, GeoPointSpatialIndexOptions>\n ): Model<{\n [KState in keyof UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >]: UpdateState<\n State,\n { indexes: UpdateIndexDefinition<State, { fields: [Key]; options: O }> }\n >[KState];\n }>;\n index(fields: string[], options: IndexOptions = {}): Model<any> {\n const storedFields = snapshotModelKeyMembers(fields, \"Index\");\n refuseDuplicateModelKeyMembers(storedFields, \"Index\");\n const storedOptions = snapshotIndexOptions(options);\n return new Model({\n ...this.#state,\n indexes: mergeIndexDefinitions(this.#state, {\n fields: storedFields,\n options: storedOptions,\n }),\n });\n }\n\n id<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundId\",\n \"Compound ID\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundId: MergeCompound<\n State[\"compoundId\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n unique<\n const Keys extends PortableKeyScalarKeys<State[\"scalars\"]>[],\n const O extends CompoundKeyOptions = Record<never, never>,\n >(fields: Keys, options?: ExactOptions<O, CompoundKeyOptions>) {\n return withCompound(\n this.#state,\n \"compoundUniques\",\n \"Compound unique\",\n fields,\n options\n ) as unknown as Model<{\n [KState in keyof UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >]: UpdateState<\n State,\n {\n compoundUniques: MergeCompound<\n State[\"compoundUniques\"],\n {\n [K in CompoundKeyName<Keys, O>]: ObjectSchema<{\n [K2 in Keys[number]]: State[\"scalars\"][K2][\"~\"][\"state\"][\"base\"];\n }>;\n }\n >;\n }\n >[KState];\n }>;\n }\n\n extends<ETShape extends DeclaredModelShape>(shape: ETShape) {\n const newShape = { ...this.#state.shape, ...shape } as State[\"shape\"] &\n ETShape;\n return new Model({\n ...this.#state,\n shape: newShape,\n scalars: extractScalarMap(newShape),\n relations: extractRelationMap(newShape),\n uniques: extractUniqueScalarMap(newShape),\n }) as unknown as Model<\n UpdateState<\n State,\n {\n shape: State[\"shape\"] & ETShape;\n scalars: ScalarMap<State[\"shape\"] & ETShape>;\n relations: RelationMap<State[\"shape\"] & ETShape>;\n uniques: UniqueScalarMap<State[\"shape\"] & ETShape>;\n }\n >\n >;\n }\n\n get \"~\"(): ModelInternal<State> {\n if (this.#internal) {\n return this.#internal;\n }\n // Capture model instance for use in getters\n const model = this;\n\n this.#internal = {\n state: this.#state,\n // getters so hydration after first access is still observed\n get names() {\n return model.#names;\n },\n get nameRegistry() {\n return model.#nameRegistry;\n },\n /**\n * Get the resolved names for a field.\n * Throws if the schema has not been hydrated.\n */\n getFieldName: (key: string): HydratedSchemaNames => {\n const registered = model.#nameRegistry.fields.get(key);\n if (registered) {\n return registered as HydratedSchemaNames;\n }\n throw new Error(`Scalar \"${key}\" not found in nameRegistry`);\n },\n /** Cached scalar field names (computed once on first access) */\n get scalarFieldNames(): string[] {\n return (model.#scalarFieldNames ??= Object.keys(model.#state.scalars));\n },\n /** Cached relation names (computed once on first access) */\n get relationNames(): string[] {\n return (model.#relationNames ??= Object.keys(model.#state.relations));\n },\n };\n return this.#internal;\n }\n}\n\nexport const model = <TShape extends DeclaredModelShape>(\n shape: TShape\n): Model<InitialModelState<TShape>> =>\n new Model({\n compoundId: undefined,\n compoundUniques: undefined,\n tableName: undefined,\n indexes: [],\n omit: undefined,\n shape,\n scalars: extractScalarMap(shape),\n relations: extractRelationMap(shape),\n uniques: extractUniqueScalarMap(shape),\n });\n\nexport type AnyModel = Model<any>;\n\n/**\n * SQL table name for a model: hydrated name, then .map() tableName, then\n * the given fallback.\n */\nexport function getTableName(model: AnyModel, fallback = \"unknown\"): string {\n return model[\"~\"].names.sql ?? model[\"~\"].state.tableName ?? fallback;\n}\n\n/**\n * SQL column name for a field, resolved through the model's nameRegistry\n * (supports field reuse across models) with .map() and field-name fallbacks.\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n","import { VibORMError, VibORMErrorCode } from \"../../errors/base\";\nimport type { SchemaValidationIssue } from \"./types\";\n\nexport class SchemaValidationError extends VibORMError {\n static override readonly diagnosticName = \"SchemaValidationError\";\n\n declare readonly code: typeof VibORMErrorCode.INVALID_INPUT;\n readonly issues: readonly SchemaValidationIssue[];\n\n constructor(\n issues: readonly SchemaValidationIssue[],\n options?: { cause?: Error | undefined }\n ) {\n // `candidates` is the one array-valued field, so the snapshot freezes it\n // too: a shallow freeze would publish an immutable issue wrapping a\n // caller-mutable list.\n const snapshot = Object.freeze(\n issues.map((issue) =>\n Object.freeze(\n issue.candidates\n ? { ...issue, candidates: Object.freeze([...issue.candidates]) }\n : { ...issue }\n )\n )\n );\n const messages = snapshot.map((issue) =>\n [\n `[${issue.code}] ${issue.message}`,\n issue.candidates?.length\n ? `Candidates: ${issue.candidates.join(\", \")}`\n : \"\",\n issue.repair ?? \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\")\n );\n super(\n `Schema validation failed:\\n${messages.join(\"\\n\")}`,\n VibORMErrorCode.INVALID_INPUT,\n options?.cause ? { cause: options.cause } : undefined\n );\n this.issues = snapshot;\n }\n\n override toJSON(): Record<string, unknown> {\n return { ...super.toJSON(), issues: this.issues };\n }\n}\n\nexport function isSchemaValidationError(\n error: unknown\n): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\n/**\n * ONE reading of a value pulled out of a `catch`, shared by every gate boundary\n * that turns a throw into a diagnostic.\n *\n * The throwers this gate catches are all in-repo and all throw `Error`s — the\n * target once-cell normalizes before the resolver ever sees a getter's throw,\n * and the physical-name owner throws its own error type. Each catch site\n * spelling this narrowing itself made three owners for one rule and three arms\n * that no schema can reach; the narrowing lives here instead, where it is\n * witnessed directly.\n */\nexport function thrownAsError(thrown: unknown): Error {\n return thrown instanceof Error ? thrown : new Error(String(thrown));\n}\n","// Common Scalar Utilities\n// Shared types and helpers for all scalar classes\n\nimport { ValidationError } from \"@errors\";\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { InferInput, VibSchema } from \"@validation\";\nimport type { DecimalDescriptor } from \"@validation/primitives/decimal-codec\";\nimport type { Scalar } from \"./base\";\n\n// =============================================================================\n// SCHEMA NAMES (hydrated by client at initialization)\n// =============================================================================\n\n/**\n * Name slots for models, scalars, and relations.\n * These are hydrated by the client at initialization time when the full\n * schema context is available.\n *\n * - ts: TypeScript/schema key name (e.g., \"email\", \"User\")\n * - sql: Resolved database name (e.g., \"email_column\", \"users\")\n */\nexport interface SchemaNames {\n /** TypeScript key name in the schema */\n ts?: string;\n /** Resolved SQL name (column/table) */\n sql?: string;\n}\n\n/**\n * Hydrated schema names - guaranteed to have both ts and sql defined.\n * Returned by model[\"~\"].getFieldName() for scalar keys.\n */\nexport interface HydratedSchemaNames {\n /** TypeScript key name in the schema */\n ts: string;\n /** Resolved SQL name (column/table) */\n sql: string;\n}\n\n// =============================================================================\n// SCALAR TYPES\n// =============================================================================\n\nexport type ScalarType =\n | \"string\"\n | \"int\"\n | \"number\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport type AutoGenerateType =\n | \"uuid\"\n | \"uuidv7\"\n | \"ulid\"\n | \"ksuid\"\n | \"nanoid\"\n | \"cuid\"\n | \"increment\"\n | \"now\"\n | \"updatedAt\";\n\n/**\n * A generator declaration.\n *\n * `kind` is the only statement of which generator runs. `prefix` and `length`\n * are declaration facts the string generators otherwise bake into their default\n * closure, where nothing can read them back; state is their durable home so a\n * serializer can restate the declaration that produced the closure.\n * `increment`/`now`/`updatedAt` take neither.\n */\nexport interface AutoGenerate {\n kind: AutoGenerateType;\n prefix?: string | undefined;\n length?: number | undefined;\n /**\n * The caller did not NAME this format; `.id()` installed it.\n *\n * The distinction is what separates a key from a domain. `.ulid()` is an\n * assertion about every value the field will ever hold — which is what lets\n * VibORM admit those values, normalize their aliases and store them as\n * sixteen bytes. `.id()` is an assertion about the KEY, carrying a generator\n * so a caller need not supply one; the values it accepts are still whatever\n * a string column accepts, and it stores them as text. `.ulid().id()` says\n * both, and is a ULID key.\n *\n * It lives on the declaration record, beside `kind`, because it IS a fact\n * about how this generator came to be declared — not a second scalar state.\n */\n implicit?: boolean | undefined;\n /** Explicit generation choice; absent formats acquire a default only as IDs. */\n generate?: boolean | undefined;\n}\n\n/**\n * The closures the generator modifiers installed.\n *\n * A generator writes TWO facts: `autoGenerate`, which is the declaration, and\n * `default`, which is the closure that produces the value. A later\n * `.default(fn)` replaces only the second, so `autoGenerate !== undefined` is\n * not evidence that the closure standing in `default` is the generator's — and\n * a consumer that restates a declaration from state (the JSON serializer) would\n * otherwise silently substitute a random generator for a caller's own function.\n *\n * Identity is the only thing that distinguishes them, so identity is what is\n * recorded. One owner, beside the declaration it belongs to; nothing outside\n * the eight modifier writers may add to it.\n */\nconst GENERATOR_DEFAULTS = new WeakSet<object>();\n\n/** Mark a closure as the default a generator modifier installed. */\ndeclare const GENERATED_DEFAULT: unique symbol;\nexport interface GeneratorDefaultBrand {\n readonly [GENERATED_DEFAULT]: true;\n}\nexport function generatorDefault<F extends () => unknown>(\n closure: F\n): F & GeneratorDefaultBrand;\nexport function generatorDefault<F extends () => unknown>(closure: F) {\n GENERATOR_DEFAULTS.add(closure);\n return closure;\n}\n\n/** A scalar generator cannot produce a complete list default. */\nexport function refuseListGenerator(builder: string): never {\n throw new ValidationError(\n { kind: \"schema-builder\", builder, path: \"array\" },\n [\n {\n path: \"array\",\n message:\n \"Scalar generation is not supported on lists; declare an explicit array default\",\n },\n ]\n );\n}\n\n/** Nullable admission supplies null only when no default was already declared. */\nexport function nullableDefault<State extends ScalarState>(\n state: State\n): State[\"hasDefault\"] extends true ? State[\"default\"] : null;\nexport function nullableDefault(state: ScalarState) {\n return state.hasDefault ? state.default : null;\n}\n\n/** Whether this default value IS a generator's own installed closure. */\nexport function isGeneratorDefault(value: unknown): boolean {\n return typeof value === \"function\" && GENERATOR_DEFAULTS.has(value);\n}\n\n// =============================================================================\n// SCALAR STATE\n// =============================================================================\n\n/**\n * Complete state for a scalar instance.\n * This is the single generic that flows through the scalar class.\n */\n\nexport interface ScalarState<T extends ScalarType = ScalarType> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: DefaultValue<any> | undefined;\n autoGenerate: AutoGenerate | undefined;\n /** Runtime create validation for portable auto-increment semantics. */\n disallowZero?: boolean;\n schema: StandardSchemaV1<any, any> | undefined;\n optional: boolean;\n /** Custom column name in the database (set via .map()) */\n columnName: string | undefined;\n base: VibSchema;\n withTimezone?: boolean | undefined;\n /**\n * The declared fixed-decimal domain, frozen at `s.decimal({...})`.\n *\n * It is the ONE source of truth for input validation, physical DDL, literal\n * encoding, result decoding, comparison and aggregate lowering, arithmetic\n * rounding and overflow, list-member encoding, and migration compatibility.\n * No adapter, driver, result parser, or migration component stores a second\n * precision or scale decision, and every modifier carries THIS object by\n * reference rather than rebuilding one.\n */\n decimal?: DecimalDescriptor | undefined;\n /** Fixed vector length for pgvector-backed vector scalars. */\n dimension?: number | undefined;\n /** Custom enum type name in the database (set via .name() on enum scalars) */\n enumName?: string | undefined;\n}\n\n// =============================================================================\n// STATE UPDATE HELPER\n// =============================================================================\n\n/**\n * Computes the new state type after applying an update.\n * Used by chainable methods to derive the return type.\n *\n * @example\n * nullable(): StringScalar<UpdateState<State, { nullable: true }>>\n */\nexport type UpdateState<\n State extends ScalarState,\n Update extends Partial<ScalarState>,\n> = Omit<State, keyof Update> & Update;\n\nexport const updateState = <\n F extends Scalar,\n const Update extends Partial<ScalarState>,\n>(\n scalar: F,\n update: Update\n) => {\n return { ...scalar[\"~\"].state, ...update } as UpdateState<\n F[\"~\"][\"state\"],\n Update\n >;\n};\n\n// =============================================================================\n// TYPE HELPERS\n// =============================================================================\n\n/**\n * Conditionally wraps a type with null\n */\nexport type MaybeNullable<\n T,\n Nullable extends boolean = false,\n> = Nullable extends true ? T | null : T;\n\n/**\n * Conditionally wraps a type as array\n */\nexport type MaybeArray<\n T,\n IsArray extends boolean = false,\n> = IsArray extends true ? T[] : T;\n\n/**\n * Type for default value - can be direct value or factory function\n */\nexport type DefaultValue<T> = T | (() => T);\n\n/**\n * The input accepted by the scalar's current base schema, or a factory for it.\n *\n * The base schema already owns the scalar's nullable and array wrappers. Adding\n * them again here turns a list default into a list of lists at the type level\n * (`string[][]` for `s.string().array()`), while runtime validation correctly\n * expects `string[]`. Read the one trusted shape instead of reconstructing it.\n */\nexport type DefaultValueInput<S extends ScalarState> = DefaultValue<\n InferInput<S[\"base\"]>\n>;\n\n// =============================================================================\n// DEFAULT STATE FACTORY\n// =============================================================================\n\n/** The factory's existing initial state stays named in exported model graphs. */\nexport interface InitialScalarState<T extends ScalarType, B extends VibSchema> {\n type: T;\n nullable: boolean;\n array: boolean;\n hasDefault: boolean;\n isId: boolean;\n isUnique: boolean;\n default: undefined;\n autoGenerate: undefined;\n disallowZero: boolean;\n schema: undefined;\n columnName: undefined;\n optional: boolean;\n withTimezone: boolean;\n base: B;\n}\n\n/**\n * Creates a default initial state for a scalar type\n */\nexport const createDefaultState = <T extends ScalarType, B extends VibSchema>(\n type: T,\n base: B\n): InitialScalarState<T, B> => ({\n type,\n nullable: false,\n array: false,\n hasDefault: false,\n isId: false,\n isUnique: false,\n default: undefined,\n autoGenerate: undefined,\n disallowZero: false,\n schema: undefined,\n columnName: undefined,\n optional: false,\n withTimezone: false,\n base,\n});\n\n// =============================================================================\n// INFER HELPERS (for type-level inference from state)\n// =============================================================================\n\n/**\n * Infers the base TypeScript type from a scalar state\n */\nexport type InferBaseType<\n BaseType,\n State extends ScalarState,\n> = State[\"array\"] extends true\n ? State[\"nullable\"] extends true\n ? (BaseType | null)[]\n : BaseType[]\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n/**\n * Infers the create input type from a scalar state\n */\nexport type InferCreateType<\n BaseType,\n State extends ScalarState,\n> = State[\"hasDefault\"] extends true\n ? State[\"nullable\"] extends true\n ? BaseType | null | undefined\n : BaseType | undefined\n : State[\"nullable\"] extends true\n ? BaseType | null\n : BaseType;\n\n// =============================================================================\n// SCHEMA SHORTHANDS (re-exported from validation primitives)\n// =============================================================================\n\nexport {\n shorthandArray,\n shorthandFilter,\n shorthandUpdate,\n} from \"@validation/primitives/shorthand\";\n","// The closed per-dialect native-type catalog, and the scalar factories' one\n// native-type admission.\n//\n// A native type's `type` is the ONE declaration string a migration driver emits\n// into DDL verbatim — the three drivers write it as a column's type with no\n// escaping, because a coded schema takes it from a typed constant. A schema\n// document is written by whoever hands you one, so it decides what may occupy\n// that position here. Coded maps and tagged declarations share the historical\n// trusted schema-author escape hatch for custom type spellings. The round-1 answer was a word grammar; the reviewer proved it cannot\n// work: `TEXT REFERENCES victims(id)`, `TEXT UNIQUE` and `TEXT CHECK(0)` are\n// letters and spaces with an optional parenthesized group, indistinguishable\n// from a multi-word type name, yet each appends a CONSTRAINT to a column in DDL.\n// No regex over arbitrary SQL words separates a type from a clause.\n//\n// So the admissible set is CLOSED and derived, per dialect, from the one owner\n// that already enumerates native types: the shipped `PG`/`MYSQL`/`SQLITE`\n// constant trees. Derivation, not duplication —\n//\n// - a string leaf (`{ db, type: \"text\" }`) contributes its EXACT value;\n// - a function leaf (a parameterized type) is probe-called at zero, one and\n// two integer arguments to learn its base name and which argument arities it\n// publishes; the catalog then admits that base bare, or with one or two\n// INTEGER arguments, at exactly those arities.\n//\n// The trees produce no word-argument type THROUGH A FUNCTION — `geometry(Point)`\n// is a string leaf, matched exactly — so there is no word-argument rule, which\n// is the narrowest rule the trees justify. A coded schema's constants are\n// catalog members by construction. The schema-document reader and serializer\n// consult this owner for the tagged `native` form; `admitNativeType` validates coded maps structurally. A TAGGED declaration written in code keeps its historical\n// open contract (a custom `{ db, type }` still reaches DDL as written) — only a\n// document refuses one outside the catalog. Nothing downstream sanitizes native\n// types, and nothing can.\n//\n// This lives beside `native-types.ts` rather than in the document module because\n// the scalar factories need it; it imports the constant trees, so the trees'\n// module cannot import it back.\n\nimport { ValidationError } from \"@errors\";\nimport { isRecord } from \"@validation/value-guards\";\nimport {\n type DialectNativeType,\n isTaggedNativeType,\n MYSQL,\n NATIVE_DIALECTS,\n type NativeDialect,\n type NativeTypeDeclaration,\n type NativeTypeMap,\n PG,\n SQLITE,\n} from \"./native-types\";\n\ntype Dialect = NativeDialect;\n\ntype DialectCatalog = {\n /** The exact type strings every string leaf produces. */\n readonly exact: Set<string>;\n /** A parameterized base name → the argument arities it publishes (0 = bare). */\n readonly templates: Map<string, Set<number>>;\n};\n\n/** Distinct non-zero probe arguments, so a produced form is unambiguous. */\nconst PROBE_ARGUMENTS: readonly number[][] = [[], [1], [1, 2]];\n\n/** A parameterized-type argument the trees produce: a non-negative integer. */\nconst INTEGER_ARGUMENT = /^\\d+$/;\n\n/**\n * A native type at the matching boundary: a base identifier, optionally followed\n * by one parenthesized group of comma-separated integers. This gate REJECTS\n * everything a clause needs — a quote, a space, a semicolon, a comment, a second\n * group, a non-integer argument — so what survives is only shaped like a type,\n * and the catalog then decides whether it IS one.\n */\nconst TYPE_EXPRESSION = /^[A-Za-z_][A-Za-z0-9_]*(\\(\\d+(,\\d+)*\\))?$/;\n\nconst CONSTANT_NAMES: Record<Dialect, string> = {\n pg: \"PG\",\n mysql: \"MYSQL\",\n sqlite: \"SQLITE\",\n};\n\n// Built on the first native-type check rather than at import: walking every\n// dialect's constants runs dozens of probe calls, and a schema that declares\n// no native type never asks.\nlet catalogs: Record<Dialect, DialectCatalog> | undefined;\n\n/**\n * Whether `type` is a native type the declared dialect's catalog admits. The\n * gate's single statement, used by the reader and the serializer alike.\n */\nexport function isNativeTypeInCatalog(db: Dialect, type: string): boolean {\n catalogs ??= buildCatalogs();\n const catalog = catalogs[db];\n if (catalog.exact.has(type)) {\n return true;\n }\n if (!TYPE_EXPRESSION.test(type)) {\n return false;\n }\n const open = type.indexOf(\"(\");\n if (open === -1) {\n return catalog.templates.get(type)?.has(0) === true;\n }\n const base = type.slice(0, open);\n const arity = type.slice(open + 1, -1).split(\",\").length;\n return catalog.templates.get(base)?.has(arity) === true;\n}\n\n/**\n * The refusal both directions carry, naming the dialect whose catalog was\n * consulted and pointing at the documented list.\n */\nexport function nativeTypeRefusal(db: Dialect): string {\n return `A \\`native.type\\` is written into DDL verbatim, so a document may carry only a native type from the '${db}' dialect's closed catalog — the values the ${CONSTANT_NAMES[db]} native-type constants produce. See the native types documentation (docs/schema/native-types).`;\n}\n\n// =============================================================================\n// SCALAR FACTORY ADMISSION\n// =============================================================================\n\n/** The one construction-time refusal of a native-type argument. */\nfunction refuse(builder: string, path: string, message: string): never {\n throw new ValidationError({ kind: \"schema-builder\", builder, path }, [\n { path, message },\n ]);\n}\n\n/**\n * A scalar factory's native-type argument, admitted: the declaration the scalar\n * stores and every modifier carries.\n *\n * The tagged shorthand is returned AS GIVEN — its open historical contract,\n * custom spellings and unrelated extra keys included, is unchanged — once it\n * names one of the three dialects as `db` and a string `type` (a value that does\n * not would be silently ignored by every dialect, or reach DDL as `undefined`),\n * and unless it also carries a dialect key, which makes it two declarations at\n * once. A map is the new form and is\n * held to its whole contract here, where types can be bypassed: only the three\n * dialect keys, at least one of them, each an OWN entry of its own dialect whose\n * type the catalog admits. It is then SNAPSHOT into a frozen map of frozen\n * `{ db, type }` entries, so the caller's object — or an entry it shares with\n * another declaration — can change afterwards without changing this scalar.\n */\nexport function admitNativeType(\n builder: string,\n declaration: NativeTypeDeclaration | undefined\n): NativeTypeDeclaration | undefined {\n return declaration === undefined\n ? undefined\n : admitDeclaredNativeType(builder, declaration);\n}\n\n/** A declared native type, out of line: most scalars declare none. */\nfunction admitDeclaredNativeType(\n builder: string,\n declaration: NativeTypeDeclaration\n): NativeTypeDeclaration {\n if (!isRecord(declaration)) {\n refuse(\n builder,\n \"nativeType\",\n \"A native type is a `{ db, type }` constant or a map of them by dialect (`{ pg, mysql, sqlite }`)\"\n );\n }\n if (isTaggedNativeType(declaration)) {\n const { db, type } = declaration;\n if (!NATIVE_DIALECTS.includes(db) || typeof type !== \"string\") {\n refuse(\n builder,\n \"nativeType\",\n `A tagged native type is \\`{ db, type }\\`: \\`db\\` one of ${NATIVE_DIALECTS.join(\", \")} and \\`type\\` a string`\n );\n }\n const beside = NATIVE_DIALECTS.find((dialect) =>\n Object.hasOwn(declaration, dialect)\n );\n if (beside !== undefined) {\n refuse(\n builder,\n `nativeType.${beside}`,\n `A tagged native type ('db: ${db}') cannot also carry a '${beside}' entry: declare one tagged type, or a map by dialect (\\`{ pg, mysql, sqlite }\\`)`\n );\n }\n return declaration;\n }\n return admitNativeTypeMap(builder, declaration);\n}\n\nfunction admitNativeTypeMap(\n builder: string,\n map: NativeTypeMap\n): NativeTypeMap {\n for (const key of Object.keys(map)) {\n if (!NATIVE_DIALECTS.some((dialect) => dialect === key)) {\n refuse(\n builder,\n `nativeType.${key}`,\n `'${key}' is not a dialect: a native-type map names only ${NATIVE_DIALECTS.join(\", \")}`\n );\n }\n }\n const snapshot: {\n pg?: DialectNativeType<\"pg\">;\n mysql?: DialectNativeType<\"mysql\">;\n sqlite?: DialectNativeType<\"sqlite\">;\n } = {};\n if (Object.hasOwn(map, \"pg\")) snapshot.pg = admitEntry(builder, \"pg\", map.pg);\n if (Object.hasOwn(map, \"mysql\")) {\n snapshot.mysql = admitEntry(builder, \"mysql\", map.mysql);\n }\n if (Object.hasOwn(map, \"sqlite\")) {\n snapshot.sqlite = admitEntry(builder, \"sqlite\", map.sqlite);\n }\n if (Object.keys(snapshot).length === 0) {\n refuse(\n builder,\n \"nativeType\",\n \"A native-type map names at least one dialect; omit the argument to keep every automatic column\"\n );\n }\n return Object.freeze(snapshot);\n}\n\n/** One map entry: a native type of exactly its key's dialect, in its catalog. */\nfunction admitEntry<Entry extends Dialect>(\n builder: string,\n dialect: Entry,\n entry: unknown\n): DialectNativeType<Entry> {\n const db = isRecord(entry) ? entry.db : undefined;\n const type = isRecord(entry) ? entry.type : undefined;\n if (db !== dialect || typeof type !== \"string\") {\n refuse(\n builder,\n `nativeType.${dialect}`,\n `The '${dialect}' entry must be a ${CONSTANT_NAMES[dialect]} native type (\\`{ db: \"${dialect}\", type }\\`)`\n );\n }\n return Object.freeze({ db: dialect, type });\n}\n\n// =============================================================================\n// CATALOG CONSTRUCTION\n// =============================================================================\n\nfunction buildCatalogs(): Record<Dialect, DialectCatalog> {\n const catalogs: Record<Dialect, DialectCatalog> = {\n pg: emptyCatalog(),\n mysql: emptyCatalog(),\n sqlite: emptyCatalog(),\n };\n walk(PG, catalogs.pg);\n walk(MYSQL, catalogs.mysql);\n walk(SQLITE, catalogs.sqlite);\n return catalogs;\n}\n\nfunction emptyCatalog(): DialectCatalog {\n return { exact: new Set(), templates: new Map() };\n}\n\n// The trees are trusted, shipped constants — objects, categories and function\n// leaves, never a primitive or null — so this walk reads their shape directly.\n// The node type is `any` because a walk over a heterogeneous tree erases the\n// leaf types, and narrowing back to them would need the casts the house forbids.\nfunction walk(node: any, catalog: DialectCatalog): void {\n if (typeof node === \"function\") {\n deriveFunction(node, catalog);\n return;\n }\n const type = node.type;\n if (typeof type === \"string\") {\n catalog.exact.add(type);\n return;\n }\n for (const value of Object.values(node)) {\n walk(value, catalog);\n }\n}\n\n/** A parameterized-type leaf, called generically — hence the erased type. */\nfunction deriveFunction(factory: any, catalog: DialectCatalog): void {\n for (const args of PROBE_ARGUMENTS) {\n const type: string = factory(...args).type;\n const open = type.indexOf(\"(\");\n if (open === -1) {\n admit(catalog, type, 0);\n continue;\n }\n // A required-argument function called with too few produces `base(undefined)`\n // — never a value the constant yields — so a non-integer argument is skipped.\n const parts = type.slice(open + 1, -1).split(\",\");\n if (parts.every((part) => INTEGER_ARGUMENT.test(part))) {\n admit(catalog, type.slice(0, open), parts.length);\n }\n }\n}\n\nfunction admit(catalog: DialectCatalog, base: string, arity: number): void {\n const arities = catalog.templates.get(base);\n if (arities === undefined) {\n catalog.templates.set(base, new Set([arity]));\n return;\n }\n arities.add(arity);\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: Keccak-f[1600] is a bit\n// permutation. Every operator below is part of the published specification's\n// arithmetic, carried on 32-bit halves because JavaScript has no 64-bit word.\n\n/**\n * SHA3-512, the one hash VibORM computes.\n *\n * FIPS 202's Keccak-f[1600] over 25 lanes of 64 bits, rate 72 bytes, domain\n * padding `0x06 ... 0x80`. One exported function, no streaming, no options, no\n * configuration: the caller hands over the complete message and receives the\n * 64-byte digest.\n *\n * Each 64-bit lane is carried as TWO 32-bit halves rather than a `BigInt`.\n * JavaScript's bitwise operators are 32-bit, so a BigInt lane would allocate a\n * new arbitrary-precision value for every one of the roughly 1,200 operations a\n * single digest performs.\n *\n * Every read goes through a `DataView`, which is the one indexed read this\n * codebase has that is not `T | undefined`: a Keccak round has no in-range\n * check to make and no branch to take, so a fallback on a typed-array read\n * would be a guard whose coverage cannot be named. The halves are stored\n * little-endian at `lane * 8` and `lane * 8 + 4`, which is exactly the lane's\n * own little-endian byte layout — so absorbing a block is a word-wise XOR of\n * the message and squeezing is a copy of the first 64 bytes.\n *\n * The one caller is CUID2 (`@schema/scalars/string/autogenerate`). Nothing else\n * in VibORM may import this module without its own differential proof against a\n * reference implementation.\n */\n\n/** SHA3-512's rate: 1600 - 2*512 bits, as bytes. */\nconst RATE_BYTES = 72;\n/** 512 bits of output. */\nconst DIGEST_BYTES = 64;\nconst LANES = 25;\nconst STATE_BYTES = LANES * 8;\nconst ROUNDS = 24;\n/** SHA-3's domain separation: `01` then the pad10*1 rule's leading bit. */\nconst DOMAIN_PAD = 0x06;\n/** pad10*1's trailing bit, at the top of the block's last byte. */\nconst FINAL_PAD = 0x80;\n\n/**\n * The iota round constants, low half then high half of each round.\n *\n * Filled through the same little-endian writes every other buffer in this\n * module is filled with. A typed array would lay its bytes out in the HOST's\n * order, which is not what the read at the iota step asks for: the two would\n * agree on a little-endian machine and disagree on every other one.\n */\nconst ROUND_CONSTANTS = new DataView(new ArrayBuffer(ROUNDS * 8));\nfor (const [half, constant] of [\n 0x00_00_00_01, 0x00_00_00_00, 0x00_00_80_82, 0x00_00_00_00, 0x00_00_80_8a,\n 0x80_00_00_00, 0x80_00_80_00, 0x80_00_00_00, 0x00_00_80_8b, 0x00_00_00_00,\n 0x80_00_00_01, 0x00_00_00_00, 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_09,\n 0x80_00_00_00, 0x00_00_00_8a, 0x00_00_00_00, 0x00_00_00_88, 0x00_00_00_00,\n 0x80_00_80_09, 0x00_00_00_00, 0x80_00_00_0a, 0x00_00_00_00, 0x80_00_80_8b,\n 0x00_00_00_00, 0x00_00_00_8b, 0x80_00_00_00, 0x00_00_80_89, 0x80_00_00_00,\n 0x00_00_80_03, 0x80_00_00_00, 0x00_00_80_02, 0x80_00_00_00, 0x00_00_00_80,\n 0x80_00_00_00, 0x00_00_80_0a, 0x00_00_00_00, 0x80_00_00_0a, 0x80_00_00_00,\n 0x80_00_80_81, 0x80_00_00_00, 0x00_00_80_80, 0x80_00_00_00, 0x80_00_00_01,\n 0x00_00_00_00, 0x80_00_80_08, 0x80_00_00_00,\n].entries()) {\n ROUND_CONSTANTS.setInt32(half * 4, constant, true);\n}\n\n/** Rho: the rotation each lane receives, indexed by `x + 5y`. */\nconst ROTATIONS = new DataView(\n new Uint8Array([\n 0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8,\n 18, 2, 61, 56, 14,\n ]).buffer\n);\n\n/** Pi: where lane `x + 5y` lands, which is `y + 5*((2x + 3y) mod 5)`. */\nconst DESTINATIONS = new DataView(\n new Uint8Array([\n 0, 10, 20, 5, 15, 16, 1, 11, 21, 6, 7, 17, 2, 12, 22, 23, 8, 18, 3, 13, 14,\n 24, 9, 19, 4,\n ]).buffer\n);\n\n/**\n * The permutation state and its two scratch planes, allocated once.\n *\n * `sha3_512` is synchronous from entry to return and this module has no other\n * caller, so one set of buffers is reused rather than allocating a hundred\n * slots per identifier. Every entry begins by zeroing the state.\n */\nconst stateBytes = new Uint8Array(STATE_BYTES);\nconst state = new DataView(stateBytes.buffer);\nconst plane = new DataView(new ArrayBuffer(STATE_BYTES));\nconst column = new DataView(new ArrayBuffer(5 * 8));\n\n/**\n * Keccak-f[1600]: 24 rounds of theta, rho + pi, chi and iota.\n *\n * A rotation by `n < 32` takes its missing bits from the other half at\n * `32 - n`; a rotation by `n > 32` is the same shape with the halves swapped\n * and `n - 32`. Neither case is reachable with `n = 0` or `n = 32`, which would\n * need a 32-bit shift JavaScript does not have: rho's only zero is lane 0,\n * which is skipped, and 32 is not one of its offsets.\n */\nfunction permute(): void {\n for (let round = 0; round < ROUNDS; round++) {\n // Theta: each column's parity, folded back into every lane of the column.\n for (let x = 0; x < 5; x++) {\n let low = 0;\n let high = 0;\n for (let y = 0; y < LANES; y += 5) {\n low ^= state.getInt32((x + y) * 8, true);\n high ^= state.getInt32((x + y) * 8 + 4, true);\n }\n column.setInt32(x * 8, low, true);\n column.setInt32(x * 8 + 4, high, true);\n }\n for (let x = 0; x < 5; x++) {\n const nextLow = column.getInt32(((x + 1) % 5) * 8, true);\n const nextHigh = column.getInt32(((x + 1) % 5) * 8 + 4, true);\n const deltaLow =\n column.getInt32(((x + 4) % 5) * 8, true) ^\n ((nextLow << 1) | (nextHigh >>> 31));\n const deltaHigh =\n column.getInt32(((x + 4) % 5) * 8 + 4, true) ^\n ((nextHigh << 1) | (nextLow >>> 31));\n for (let y = 0; y < LANES; y += 5) {\n const at = (x + y) * 8;\n state.setInt32(at, state.getInt32(at, true) ^ deltaLow, true);\n state.setInt32(at + 4, state.getInt32(at + 4, true) ^ deltaHigh, true);\n }\n }\n\n // Rho and pi: rotate every lane, then move it to its permuted position.\n plane.setInt32(0, state.getInt32(0, true), true);\n plane.setInt32(4, state.getInt32(4, true), true);\n for (let lane = 1; lane < LANES; lane++) {\n const shift = ROTATIONS.getUint8(lane);\n const low = state.getInt32(lane * 8, true);\n const high = state.getInt32(lane * 8 + 4, true);\n const target = DESTINATIONS.getUint8(lane) * 8;\n if (shift < 32) {\n plane.setInt32(target, (low << shift) | (high >>> (32 - shift)), true);\n plane.setInt32(\n target + 4,\n (high << shift) | (low >>> (32 - shift)),\n true\n );\n } else {\n const rest = shift - 32;\n plane.setInt32(target, (high << rest) | (low >>> (32 - rest)), true);\n plane.setInt32(\n target + 4,\n (low << rest) | (high >>> (32 - rest)),\n true\n );\n }\n }\n\n // Chi: each lane against the next two in its row.\n for (let y = 0; y < LANES; y += 5) {\n for (let x = 0; x < 5; x++) {\n const at = (y + x) * 8;\n const next = (y + ((x + 1) % 5)) * 8;\n const after = (y + ((x + 2) % 5)) * 8;\n state.setInt32(\n at,\n plane.getInt32(at, true) ^\n (~plane.getInt32(next, true) & plane.getInt32(after, true)),\n true\n );\n state.setInt32(\n at + 4,\n plane.getInt32(at + 4, true) ^\n (~plane.getInt32(next + 4, true) & plane.getInt32(after + 4, true)),\n true\n );\n }\n }\n\n // Iota: the round constant, on the first lane only.\n state.setInt32(\n 0,\n state.getInt32(0, true) ^ ROUND_CONSTANTS.getInt32(round * 8, true),\n true\n );\n state.setInt32(\n 4,\n state.getInt32(4, true) ^ ROUND_CONSTANTS.getInt32(round * 8 + 4, true),\n true\n );\n }\n}\n\n/** Absorb one complete rate-sized block and run the permutation. */\nfunction absorb(block: DataView, offset: number): void {\n for (let at = 0; at < RATE_BYTES; at += 4) {\n state.setInt32(\n at,\n state.getInt32(at, true) ^ block.getInt32(offset + at, true),\n true\n );\n }\n permute();\n}\n\n/**\n * The SHA3-512 digest of one complete message.\n *\n * Byte-identical to the reference implementation for every input, which a\n * differential test pins against the NIST known-answer vectors and 10,000\n * random messages crossing every rate boundary.\n */\nexport function sha3_512(bytes: Uint8Array): Uint8Array {\n stateBytes.fill(0);\n\n const length = bytes.length;\n const message = new DataView(bytes.buffer, bytes.byteOffset, length);\n const wholeBlocks = Math.floor(length / RATE_BYTES);\n for (let block = 0; block < wholeBlocks; block++) {\n absorb(message, block * RATE_BYTES);\n }\n\n // The final block is the message tail plus pad10*1. A tail of exactly\n // `RATE_BYTES - 1` puts both pad bits in the same byte, which is the rule\n // rather than a special case.\n const tail = new Uint8Array(RATE_BYTES);\n const tailLength = length - wholeBlocks * RATE_BYTES;\n tail.set(bytes.subarray(wholeBlocks * RATE_BYTES));\n tail[tailLength] = DOMAIN_PAD;\n tail[RATE_BYTES - 1] =\n tailLength === RATE_BYTES - 1 ? DOMAIN_PAD | FINAL_PAD : FINAL_PAD;\n absorb(new DataView(tail.buffer), 0);\n\n // 512 bits is narrower than the rate, so one squeeze with no further\n // permutation is the whole digest — and the halves are already stored in the\n // little-endian order the digest is written in.\n return Uint8Array.from(stateBytes.subarray(0, DIGEST_BYTES));\n}\n","// biome-ignore-all lint/suspicious/noBitwiseOperators: NanoID selects a\n// character with `byte & 63`, the ULID counter carries a byte at a time, and\n// CUID2's digest is read as one big-endian integer. All three are bit layouts.\n\n/**\n * The six identifier generators a string scalar can declare.\n *\n * Each `default*` function is the DECLARATION: it validates what the modifier\n * was spelled with and returns the closure the scalar stores as its default.\n * The closure is what runs per row, synchronously, inside the field's own\n * create schema — so nothing here may be asynchronous, and nothing here may\n * draw entropy before it is called.\n *\n * The byte layouts, alphabets, widths and the one entropy source live in\n * `@validation/primitives/id-formats`, where the storage codec can read them\n * without pulling a scalar class. This module owns only what a GENERATOR adds\n * to a format: the clock it reads, the state it keeps between calls, and the\n * prefix it puts in front of the payload.\n */\n\nimport {\n applyIdPrefix,\n bytesToKsuid,\n bytesToUlid,\n bytesToUuid,\n KSUID_PAYLOAD_LENGTH,\n ksuidBytes,\n MAX_RANDOM_BYTES,\n NANOID_ALPHABET,\n NANOID_DEFAULT_LENGTH,\n randomBytes,\n refuseId,\n ULID_RANDOM_LENGTH,\n UUID_BYTE_LENGTH,\n UUIDV7_RANDOM_LENGTH,\n ulidBytes,\n uuidV4Bytes,\n uuidV7Bytes,\n} from \"@validation/primitives/id-formats\";\nimport { sha3_512 } from \"@validation/primitives/sha3\";\n\nconst MILLISECONDS_PER_SECOND = 1000;\n\n// =============================================================================\n// UUID\n// =============================================================================\n\n/**\n * A UUIDv4.\n *\n * `crypto.randomUUID()` when the runtime has it — it is the platform's own\n * implementation of exactly this format, and it is measurably faster than\n * drawing bytes and tagging them. The manual path is not a fallback to a weaker\n * value: it is the same 122 random bits with the same version and variant, from\n * the same entropy source, for runtimes that expose `getRandomValues` without\n * `randomUUID`.\n */\nfunction uuidV4(): string {\n const source = globalThis.crypto;\n if (typeof source?.randomUUID === \"function\") return source.randomUUID();\n return bytesToUuid(uuidV4Bytes(randomBytes(UUID_BYTE_LENGTH, \"uuid\")));\n}\n\nexport const defaultUuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, uuidV4());\n\nexport const defaultUuidV7 = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToUuid(\n uuidV7Bytes(Date.now(), randomBytes(UUIDV7_RANDOM_LENGTH, \"uuidv7\"))\n )\n );\n\n// =============================================================================\n// ULID\n// =============================================================================\n\n/** The next 80-bit random block, or a refusal when the block is exhausted. */\nfunction incrementUlidRandom(random: Uint8Array): Uint8Array {\n const next = Uint8Array.from(random);\n const view = new DataView(next.buffer);\n for (let index = next.length - 1; index >= 0; index--) {\n const incremented = view.getUint8(index) + 1;\n view.setUint8(index, incremented & 255);\n if (incremented <= 255) return next;\n }\n return refuseId(\n \"s.string().ulid\",\n \"generate\",\n \"This process issued every ULID one millisecond can hold (2^80). Monotonicity cannot be preserved without emitting a smaller identifier\"\n );\n}\n\n/**\n * One monotonic ULID sequence.\n *\n * Within a millisecond the timestamp repeats, so the 80-bit random block is\n * INCREMENTED instead of redrawn: two ULIDs minted in the same millisecond\n * still sort in the order they were issued. A clock that moves backwards keeps\n * emitting the last timestamp for the same reason — a smaller identifier would\n * break the ordering the format promises, and the ORM cannot fix the clock.\n *\n * The whole block is drawn at once from secure bytes, so every bit is uniform.\n *\n * `now` and `random` are injectable because monotonicity, rollback and\n * exhaustion are statements about a SEQUENCE, and a sequence cannot be observed\n * through a real clock. The process-wide generator below takes the defaults.\n */\nexport function createUlidGenerator(\n options: { now?: () => number; random?: (length: number) => Uint8Array } = {}\n): () => string {\n const now = options.now ?? Date.now;\n const draw = options.random ?? ((length) => randomBytes(length, \"ulid\"));\n let last: { time: number; random: Uint8Array } | undefined;\n return () => {\n const time = now();\n last =\n last !== undefined && time <= last.time\n ? { time: last.time, random: incrementUlidRandom(last.random) }\n : { time, random: draw(ULID_RANDOM_LENGTH) };\n return bytesToUlid(ulidBytes(last.time, last.random));\n };\n}\n\n/**\n * ONE monotonic sequence per process, shared by every `.ulid()` and `.id()`\n * field. Monotonicity is a property of the issuing process, not of a field: two\n * models minting ULIDs in the same millisecond must not collide, and a\n * per-field sequence would let them.\n */\nconst nextUlid = createUlidGenerator();\n\nexport const defaultUlid = (prefix?: string) => () =>\n applyIdPrefix(prefix, nextUlid());\n\n// =============================================================================\n// KSUID\n// =============================================================================\n\nexport const defaultKsuid = (prefix?: string) => () =>\n applyIdPrefix(\n prefix,\n bytesToKsuid(\n ksuidBytes(\n Math.floor(Date.now() / MILLISECONDS_PER_SECOND),\n randomBytes(KSUID_PAYLOAD_LENGTH, \"ksuid\")\n )\n )\n );\n\n// =============================================================================\n// NANOID\n// =============================================================================\n\n/**\n * The lengths a nanoid can have, refused where the length is spelled.\n *\n * One character costs one byte of entropy, so the upper bound is the entropy\n * source's own per-call quota: asking for more used to declare cleanly and then\n * throw a raw `QuotaExceededError` from inside the closure, at row-create time,\n * for every row.\n */\nexport const defaultNanoid = (length?: number, prefix?: string) => {\n const size = length ?? NANOID_DEFAULT_LENGTH;\n if (!Number.isInteger(size) || size < 1 || size > MAX_RANDOM_BYTES) {\n refuseId(\n \"s.string().nanoid\",\n \"length\",\n `A nanoid length must be a whole number of characters between 1 and ${MAX_RANDOM_BYTES}; received ${size}`\n );\n }\n return () => {\n let id = \"\";\n for (const byte of randomBytes(size, \"nanoid\")) {\n id += NANOID_ALPHABET.charAt(byte & 63);\n }\n return applyIdPrefix(prefix, id);\n };\n};\n\n// =============================================================================\n// CUID2\n// =============================================================================\n\n/*\n * The CUID2 construction below is a port of @paralleldrive/cuid2 3.3.0, kept\n * byte-identical to it so that identifiers minted by VibORM and identifiers\n * minted by the upstream package belong to the same space. What changed is the\n * arithmetic (native `BigInt` in place of bignumber.js), the entropy source\n * (secure bytes only, never `Math.random()`), and the fingerprint's global\n * object (`globalThis`, which every supported runtime has). A differential test\n * pins the rest against the upstream package.\n *\n * MIT License\n *\n * Copyright (c) 2022 Eric Elliott\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nconst CUID_DEFAULT_LENGTH = 24;\nconst CUID_BIG_LENGTH = 32;\nconst CUID_ALPHABET_SIZE = 26;\nconst BASE36 = 36;\n/** ~22k hosts before a 50% chance of an initial counter collision (upstream). */\nconst CUID_INITIAL_COUNT_MAX = 476_782_367;\n\nconst TEXT_ENCODER = new TextEncoder();\nconst LOWERCASE_LETTERS = \"abcdefghijklmnopqrstuvwxyz\";\n\n/** A float in `[0, 1)` from four secure bytes, read as one 32-bit word. */\nfunction secureFloat(): number {\n const bytes = randomBytes(4, \"cuid\");\n const word = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return word.getUint32(0, true) / 0x1_00_00_00_00;\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n let entropy = \"\";\n while (entropy.length < length) {\n entropy += Math.floor(random() * BASE36).toString(BASE36);\n }\n return entropy;\n}\n\n/**\n * SHA3-512 of `input`, rendered in base36 with the first digit dropped — that\n * digit is biased toward the low end of the alphabet because the digest is not\n * a whole number of base36 digits.\n */\nfunction hashBase36(input: string): string {\n let value = 0n;\n for (const byte of sha3_512(TEXT_ENCODER.encode(input))) {\n value = (value << 8n) | BigInt(byte);\n }\n return value.toString(BASE36).slice(1);\n}\n\n/**\n * A fingerprint of the host environment, mixed into every id so that two\n * processes minting ids at the same millisecond with the same counter still\n * disagree.\n */\nfunction createFingerprint(random: () => number): string {\n const globals = Object.keys(globalThis).toString();\n const entropy = createEntropy(CUID_BIG_LENGTH, random);\n // Upstream writes `globals.length > 0 ? globals + entropy : entropy`. The two\n // arms are the same string — concatenating an empty `globals` IS `entropy` —\n // so the condition names no case, and a branch whose unique coverage cannot\n // be stated is one this codebase does not keep. The digest is unchanged,\n // which the differential test against the pinned upstream package proves.\n return hashBase36(globals + entropy).substring(0, CUID_BIG_LENGTH);\n}\n\n/**\n * One CUID2 sequence.\n *\n * Everything upstream lets a caller replace is replaceable here for the same\n * reason: the fingerprint, counter and random source are the parts that make\n * two processes differ, and a test that cannot fix them cannot compare two\n * implementations at all. `length` is replaceable for the same reason — the\n * salt is as long as the id, so a differential test that only ever saw 24\n * characters would compare one input shape.\n *\n * No length is spellable in a schema: `.cuid(prefix?)` takes none and always\n * mints the published 24, and a schema document that declares one is refused by\n * the reader (J007). The construction therefore states no bound of its own.\n */\nexport function createCuid2(\n options: {\n random?: () => number;\n counter?: () => number;\n length?: number;\n fingerprint?: string;\n } = {}\n): () => string {\n const random = options.random ?? secureFloat;\n const counter =\n options.counter ??\n createCounter(Math.floor(random() * CUID_INITIAL_COUNT_MAX));\n const length = options.length ?? CUID_DEFAULT_LENGTH;\n const fingerprint = options.fingerprint ?? createFingerprint(random);\n return () => {\n const firstLetter = LOWERCASE_LETTERS.charAt(\n Math.floor(random() * CUID_ALPHABET_SIZE)\n );\n const time = Date.now().toString(BASE36);\n const count = counter().toString(BASE36);\n const salt = createEntropy(length, random);\n return (\n firstLetter +\n hashBase36(time + salt + count + fingerprint).substring(1, length)\n );\n };\n}\n\nfunction createCounter(start: number): () => number {\n let count = start;\n return () => {\n const current = count;\n count++;\n return current;\n };\n}\n\n/**\n * The process-wide CUID2 sequence, built on first use.\n *\n * Lazily, because the fingerprint hashes 32 characters of entropy: building it\n * at import would draw randomness from every process that merely loads VibORM,\n * including ones that never mint an id.\n */\nlet processCuid: (() => string) | undefined;\n\nexport const defaultCuid = (prefix?: string) => () =>\n applyIdPrefix(prefix, (processCuid ??= createCuid2())());\n","// String Scalar\n// Standalone scalar class with State generic pattern\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { hasIdPrefix, refuseId } from \"@validation/primitives/id-formats\";\nimport v from \"@validation/primitives/v\";\nimport {\n type AutoGenerate,\n createDefaultState,\n type DefaultValueInput,\n type GeneratorDefaultBrand,\n generatorDefault,\n isGeneratorDefault,\n nullableDefault,\n refuseListGenerator,\n type ScalarState,\n type UpdateState,\n updateState,\n} from \"../common\";\nimport { admitNativeType } from \"../native-catalog\";\nimport type {\n ExactNativeTypeMap,\n NativeDialect,\n NativeTypeArgument,\n NativeTypeDeclaration,\n} from \"../native-types\";\nimport {\n defaultCuid,\n defaultKsuid,\n defaultNanoid,\n defaultUlid,\n defaultUuid,\n defaultUuidV7,\n} from \"./autogenerate\";\n\ninterface FormatOptions {\n prefix?: string;\n generate?: true;\n}\ninterface NanoidOptions extends FormatOptions {\n length?: number;\n}\ninterface KeyOptions {\n generate: false;\n prefix?: string;\n}\ntype IdentifierKind = \"uuid\" | \"uuidv7\" | \"ulid\" | \"ksuid\" | \"nanoid\" | \"cuid\";\ntype ExactOptions<Given, Allowed> = Given extends string | number | undefined\n ? unknown\n : Record<Exclude<keyof Given, keyof Allowed>, never>;\ntype GenerationRequested<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends { generate: true }\n ? true\n : State[\"isId\"];\ntype GenerationChoice<\n State extends ScalarState<\"string\">,\n Given,\n> = Given extends { generate: true }\n ? true\n : Given extends { generate: false }\n ? false\n : State[\"autoGenerate\"] extends {\n generate: infer Choice extends boolean | undefined;\n }\n ? Choice\n : undefined;\ntype HasCustomDefault<State extends ScalarState<\"string\">> =\n State[\"default\"] extends GeneratorDefaultBrand ? false : State[\"hasDefault\"];\ntype FormatState<\n State extends ScalarState<\"string\">,\n Given,\n Kind extends IdentifierKind = IdentifierKind,\n> = {\n autoGenerate: AutoGenerate & {\n kind: Kind;\n implicit?: undefined;\n generate: GenerationChoice<State, Given>;\n };\n hasDefault: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n optional: HasCustomDefault<State> extends true\n ? true\n : GenerationRequested<State, Given>;\n default: HasCustomDefault<State> extends true\n ? State[\"default\"]\n : GenerationRequested<State, Given> extends true\n ? (() => string) & GeneratorDefaultBrand\n : undefined;\n};\ntype KeyState<State extends ScalarState<\"string\">, Given> = Omit<\n FormatState<UpdateState<State, { isId: true }>, Given>,\n \"autoGenerate\"\n> & {\n isId: true;\n isUnique: true;\n autoGenerate: State[\"autoGenerate\"] extends AutoGenerate\n ? Omit<State[\"autoGenerate\"], \"generate\"> & {\n generate: GenerationChoice<State, Given>;\n }\n : {\n kind: \"ulid\";\n implicit: true;\n prefix?: string;\n generate: GenerationChoice<State, Given>;\n };\n};\n\nfunction identifierGenerator(declaration: AutoGenerate): () => string {\n const { kind, prefix, length } = declaration;\n switch (kind) {\n case \"uuid\":\n return defaultUuid(prefix);\n case \"uuidv7\":\n return defaultUuidV7(prefix);\n case \"ulid\":\n return defaultUlid(prefix);\n case \"ksuid\":\n return defaultKsuid(prefix);\n case \"nanoid\":\n return defaultNanoid(length, prefix);\n case \"cuid\":\n return defaultCuid(prefix);\n default:\n return refuseId(\n \"s.string\",\n \"generate\",\n \"This generator is not a string identifier format\"\n );\n }\n}\n\nconst stringBase = v.string();\n\nexport class StringScalar<State extends ScalarState<\"string\">> {\n private readonly state: State;\n private readonly _nativeType?: NativeTypeDeclaration | undefined;\n\n constructor(state: State, _nativeType?: NativeTypeDeclaration) {\n this.state = state;\n this._nativeType = _nativeType;\n }\n\n nullable() {\n return new StringScalar(\n updateState(this, {\n nullable: true,\n hasDefault: true,\n default: nullableDefault(this.state),\n optional: true,\n base: v.string<{\n nullable: true;\n array: State[\"array\"];\n schema: State[\"schema\"];\n }>({\n nullable: true,\n array: this.state.array,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n array() {\n if (isGeneratorDefault(this.state.default)) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n array: true,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: true;\n schema: State[\"schema\"];\n }>({\n nullable: this.state.nullable,\n array: true,\n schema: this.state.schema,\n }),\n }),\n this._nativeType\n );\n }\n\n id<const Given extends string | KeyOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, KeyOptions>\n ): StringScalar<UpdateState<State, KeyState<State, Given>>>;\n id(options?: string | KeyOptions): StringScalar<ScalarState<\"string\">> {\n const generate = typeof options === \"object\" ? options.generate : undefined;\n const prefix = typeof options === \"string\" ? options : options?.prefix;\n const declared = this.state.autoGenerate;\n if (declared && hasIdPrefix(prefix)) refuseSecondIdPrefix(declared);\n const declaration: AutoGenerate = declared\n ? { ...declared, generate: generate ?? declared.generate }\n : { kind: \"ulid\", prefix, implicit: true, generate };\n return this.withIdentifier(declaration, true);\n }\n\n unique() {\n return new StringScalar(\n updateState(this, {\n isUnique: true,\n }),\n this._nativeType\n );\n }\n\n default<V extends DefaultValueInput<State>>(value: V) {\n return new StringScalar(\n updateState(this, {\n hasDefault: true,\n default: value,\n optional: true,\n }),\n this._nativeType\n );\n }\n\n schema<S extends StandardSchemaV1<string>>(schema: S) {\n return new StringScalar(\n updateState(this, {\n schema,\n base: v.string<{\n nullable: State[\"nullable\"];\n array: State[\"array\"];\n schema: S;\n }>({\n nullable: this.state.nullable,\n array: this.state.array,\n schema,\n }),\n }),\n this._nativeType\n );\n }\n\n /**\n * Maps this scalar to a custom column name in the database\n */\n map(columnName: string) {\n return new StringScalar(\n updateState(this, { columnName }),\n this._nativeType\n );\n }\n\n uuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuid\">>>;\n uuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuid\", options);\n }\n\n uuidv7<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"uuidv7\">>>;\n uuidv7(\n options?: string | FormatOptions\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"uuidv7\", options);\n }\n\n ksuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ksuid\">>>;\n ksuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ksuid\", options);\n }\n\n ulid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"ulid\">>>;\n ulid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"ulid\", options);\n }\n\n cuid<const Given extends string | FormatOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, FormatOptions>\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"cuid\">>>;\n cuid(options?: string | FormatOptions): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\"cuid\", options);\n }\n\n nanoid<const Given extends number | NanoidOptions | undefined = undefined>(\n options?: Given & ExactOptions<Given, NanoidOptions>,\n prefix?: string\n ): StringScalar<UpdateState<State, FormatState<State, Given, \"nanoid\">>>;\n nanoid(\n options?: number | NanoidOptions,\n prefix?: string\n ): StringScalar<ScalarState<\"string\">> {\n return this.withFormat(\n \"nanoid\",\n typeof options === \"number\"\n ? { length: options, prefix }\n : (options ?? { prefix })\n );\n }\n\n private withFormat(kind: IdentifierKind, options?: string | NanoidOptions) {\n const configuration: NanoidOptions | undefined =\n typeof options === \"string\" ? { prefix: options } : options;\n return this.withIdentifier(\n {\n kind,\n prefix: configuration?.prefix,\n length: kind === \"nanoid\" ? configuration?.length : undefined,\n generate: configuration?.generate ?? this.state.autoGenerate?.generate,\n },\n this.state.isId\n );\n }\n\n private withIdentifier(declaration: AutoGenerate, isId: boolean) {\n const generator = identifierGenerator(declaration);\n const customDefault =\n this.state.hasDefault && !isGeneratorDefault(this.state.default);\n const generate =\n declaration.generate === true || (isId && declaration.generate !== false);\n const installed = generate && !customDefault;\n if (this.state.array && installed) refuseListGenerator(\"s.string\");\n return new StringScalar(\n updateState(this, {\n isId,\n isUnique: isId || this.state.isUnique,\n autoGenerate: declaration,\n hasDefault: customDefault || installed,\n optional: customDefault || installed,\n default: installed\n ? generatorDefault(generator)\n : customDefault\n ? this.state.default\n : undefined,\n }),\n this._nativeType\n );\n }\n\n private _internal?: {\n state: State;\n nativeType: NativeTypeDeclaration | undefined;\n };\n\n get [\"~\"]() {\n return (this._internal ??= {\n state: this.state,\n nativeType: this._nativeType,\n });\n }\n}\n\nexport const string = <\n Db extends NativeDialect = never,\n const Given extends ExactNativeTypeMap<Given> = never,\n>(\n nativeType?: NativeTypeArgument<Db, Given>\n) => {\n return new StringScalar(\n createDefaultState(\"string\", stringBase),\n admitNativeType(\"s.string\", nativeType)\n );\n};\n\nfunction refuseSecondIdPrefix(declared: {\n readonly kind: string;\n readonly prefix?: string | undefined;\n}): never {\n return refuseId(\n \"s.string().id\",\n \"prefix\",\n `This field already declares a '${declared.kind}' generator${declared.prefix ? ` with the prefix '${declared.prefix}'` : \"\"}. A prefix is spelled once, on the call that declares the format`\n );\n}\n","import type { Model } from \"./model\";\nimport type { SchemaValidationIssue } from \"./validation/types\";\n\n/**\n * Prove that every model object in one registration batch has one schema key.\n *\n * The model's hydrated name is the lifetime claim. The local map covers the\n * still-unhydrated batch, so `{ alpha: shared, beta: shared }` is refused before\n * hydration writes either name. Repeating the same object under the same key is\n * deliberately idempotent.\n */\nexport function preflightModelRegistrationIdentity(\n registrations: Iterable<readonly [string, Model<any>]>\n): SchemaValidationIssue | undefined {\n const claimedInThisPass = new Map<Model<any>, string>();\n for (const [modelKey, model] of registrations) {\n if (\n model === null ||\n typeof model !== \"object\" ||\n !model[\"~\"]?.names ||\n !model[\"~\"]?.state?.scalars\n )\n return {\n code: \"M008\",\n message: `Schema entry '${modelKey}' is not a model; pass an explicit object containing only s.model() definitions`,\n severity: \"error\",\n model: modelKey,\n };\n const claimed = model[\"~\"].names.ts ?? claimedInThisPass.get(model);\n if (claimed !== undefined && claimed !== modelKey)\n return doubleRegistrationIssue(claimed, modelKey);\n claimedInThisPass.set(model, modelKey);\n }\n return undefined;\n}\n\nfunction doubleRegistrationIssue(\n claimed: string,\n modelKey: string\n): SchemaValidationIssue {\n return {\n code: \"M003\",\n message: `Model registered as '${claimed}' cannot also be registered as '${modelKey}'; one model object binds one schema key`,\n severity: \"error\",\n model: modelKey,\n };\n}\n"],"mappings":"2mBAwCA,MAAM,EAAe,sCAEf,EAAqB,CAAC,QAAS,SAAU,SAAS,CAuIxD,SAAgB,wBACd,EACA,EACA,EACwC,CACnC,EAAc,EAAS,EAC1B,EACE,EACA,SACA,0FACD,CAEH,IAAM,EAAc,EAAa,EAAS,CACtC,EAAY,SAAW,GACzB,EACE,EACA,SACA,2CACD,CAEH,IAAM,EAAe,iBAAiB,EAAS,EAAa,EAAQ,CAC9D,EAAwC,EAAE,CAChD,IAAK,IAAM,KAAc,EAAa,CAC/B,EAAwB,EAAW,EACtC,EACE,EACA,UAAU,IACV,gBAAgB,EAAW,oCAC5B,CAEH,IAAM,EAAS,EACb,EACA,EACA,EACA,UAAU,IACX,CACG,OAAO,GAAW,YACpB,EACE,EACA,UAAU,IACV,YAAY,EAAW,6EACxB,CAEH,EAAQ,GAAc,OAAO,OAAO,CAClC,SACA,YAAa,EAAa,IAAe,EAC1C,CAAC,CAEJ,OAAO,OAAO,OAAO,EAAQ,CAS/B,SAAS,iBACP,EACA,EACA,EACwB,CACxB,GAAI,IAAY,IAAA,GAAW,MAAO,EAAE,CAC/B,EAAc,EAAQ,EACzB,EACE,EACA,UACA,sHACD,CAEE,EAAa,EAAa,EAAQ,CAAE,CAAC,SAAS,CAAC,EAClD,EACE,EACA,UACA,kHACD,CAEH,IAAM,EAAS,EACb,EACA,EACA,SACA,iBACD,CACI,EAAc,EAAO,EACxB,EACE,EACA,iBACA,yDACD,CAEH,IAAM,EAAY,EAAa,EAAO,CACjC,EAAa,EAAW,EAAY,EACvC,EACE,EACA,iBACA,kDAAkD,WAAW,EAAY,CAAC,gBAAgB,WAAW,EAAU,GAChH,CAEH,IA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