viborm 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/dist/{adapter-internals-DULbfdmQ.mjs → adapter-internals-DNY4JWFC.mjs} +1 -1
  2. package/dist/{adapter-internals-DULbfdmQ.mjs.map → adapter-internals-DNY4JWFC.mjs.map} +1 -1
  3. package/dist/{adapter-namespace-CFtC8LbT.mjs → adapter-namespace-BMss0hKo.mjs} +2 -2
  4. package/dist/{adapter-namespace-CFtC8LbT.mjs.map → adapter-namespace-BMss0hKo.mjs.map} +1 -1
  5. package/dist/{adapter-result-parser-C0vW9am8.mjs → adapter-result-parser-Bz3WtMBa.mjs} +1 -1
  6. package/dist/{adapter-result-parser-C0vW9am8.mjs.map → adapter-result-parser-Bz3WtMBa.mjs.map} +1 -1
  7. package/dist/adapters.d.mts +1 -1
  8. package/dist/adapters.mjs +1 -1
  9. package/dist/{array-literal-Dohoq5rT.mjs → array-literal-DfgmVxKI.mjs} +1 -1
  10. package/dist/{array-literal-Dohoq5rT.mjs.map → array-literal-DfgmVxKI.mjs.map} +1 -1
  11. package/dist/{batch-refs-cBYAKzaE.mjs → batch-refs-DWMYN0fw.mjs} +1 -1
  12. package/dist/{batch-refs-cBYAKzaE.mjs.map → batch-refs-DWMYN0fw.mjs.map} +1 -1
  13. package/dist/{bind-parameter-capacity-4OU6feZG.mjs → bind-parameter-capacity-Bjgx1lMC.mjs} +1 -1
  14. package/dist/{bind-parameter-capacity-4OU6feZG.mjs.map → bind-parameter-capacity-Bjgx1lMC.mjs.map} +1 -1
  15. package/dist/builder-B4n-7I7Q.mjs +2 -0
  16. package/dist/{builder-D0GQK-fA.mjs.map → builder-B4n-7I7Q.mjs.map} +1 -1
  17. package/dist/bun-sql.d.mts +1 -1
  18. package/dist/bun-sql.mjs +1 -1
  19. package/dist/bun-sqlite.d.mts +1 -1
  20. package/dist/bun-sqlite.mjs +1 -1
  21. package/dist/cache/cloudflare-kv.d.mts +1 -1
  22. package/dist/cache/cloudflare-kv.mjs +1 -1
  23. package/dist/cache/memory.d.mts +1 -1
  24. package/dist/cache/memory.mjs +1 -1
  25. package/dist/cache.d.mts +1 -1
  26. package/dist/cache.mjs +1 -1
  27. package/dist/cache.mjs.map +1 -1
  28. package/dist/{canonical-json-D_FgOt4S.mjs → canonical-json-B6J5VbLv.mjs} +1 -1
  29. package/dist/{canonical-json-D_FgOt4S.mjs.map → canonical-json-B6J5VbLv.mjs.map} +1 -1
  30. package/dist/chain-DVuRxjPO.mjs +2 -0
  31. package/dist/chain-DVuRxjPO.mjs.map +1 -0
  32. package/dist/cli.mjs +1 -1
  33. package/dist/{client-C5BGyg5n.d.mts → client-7ApJka0M.d.mts} +3 -3
  34. package/dist/client-Yqn0LqmI.mjs +2 -0
  35. package/dist/client-Yqn0LqmI.mjs.map +1 -0
  36. package/dist/{client-BCcIdDl8.mjs → client-l7dSOul5.mjs} +12 -12
  37. package/dist/{client-BCcIdDl8.mjs.map → client-l7dSOul5.mjs.map} +1 -1
  38. package/dist/client.d.mts +1 -1
  39. package/dist/client.mjs +1 -1
  40. package/dist/{clock-QtW83Dcm.mjs → clock-DXbsDHLj.mjs} +1 -1
  41. package/dist/{clock-QtW83Dcm.mjs.map → clock-DXbsDHLj.mjs.map} +1 -1
  42. package/dist/config.d.mts +2 -2
  43. package/dist/config.mjs +1 -1
  44. package/dist/{current-CEWlNJcP.mjs → current-nScH-oH5.mjs} +1 -1
  45. package/dist/{current-CEWlNJcP.mjs.map → current-nScH-oH5.mjs.map} +1 -1
  46. package/dist/d1.d.mts +1 -1
  47. package/dist/d1.mjs +1 -1
  48. package/dist/{datetime-physical-codec-Bl6M6vF5.mjs → datetime-physical-codec-DTdvABny.mjs} +2 -2
  49. package/dist/{datetime-physical-codec-Bl6M6vF5.mjs.map → datetime-physical-codec-DTdvABny.mjs.map} +1 -1
  50. package/dist/{driver-szWYBmjD.mjs → driver-CK_IKqDa.mjs} +2 -2
  51. package/dist/{driver-szWYBmjD.mjs.map → driver-CK_IKqDa.mjs.map} +1 -1
  52. package/dist/{driver-Dv2GJyGs.mjs → driver-DaBNytbz.mjs} +2 -2
  53. package/dist/{driver-Dv2GJyGs.mjs.map → driver-DaBNytbz.mjs.map} +1 -1
  54. package/dist/driver.d.mts +1 -1
  55. package/dist/driver.mjs +1 -1
  56. package/dist/{error-mapping-DRY49A3C.mjs → error-mapping-D--MVRCY.mjs} +2 -2
  57. package/dist/{error-mapping-DRY49A3C.mjs.map → error-mapping-D--MVRCY.mjs.map} +1 -1
  58. package/dist/every-6VrIclsx.mjs +2 -0
  59. package/dist/{every-DIG9CPly.mjs.map → every-6VrIclsx.mjs.map} +1 -1
  60. package/dist/{fs-estate-DNCM7hYC.mjs → fs-estate-CfvH8Fxa.mjs} +2 -2
  61. package/dist/{fs-estate-DNCM7hYC.mjs.map → fs-estate-CfvH8Fxa.mjs.map} +1 -1
  62. package/dist/{geo-area-codec-H50rrGiF.mjs → geo-area-codec-DvHcWF3g.mjs} +2 -2
  63. package/dist/{geo-area-codec-H50rrGiF.mjs.map → geo-area-codec-DvHcWF3g.mjs.map} +1 -1
  64. package/dist/geo-point-codec-CIZxuIvE.mjs +2 -0
  65. package/dist/geo-point-codec-CIZxuIvE.mjs.map +1 -0
  66. package/dist/{hydration-BQ7tYLtA.mjs → hydration-BUBkHlCK.mjs} +2 -2
  67. package/dist/{hydration-BQ7tYLtA.mjs.map → hydration-BUBkHlCK.mjs.map} +1 -1
  68. package/dist/identifier-conversion-BXrBYgAq.mjs +2 -0
  69. package/dist/{identifier-conversion-DV63mwKG.mjs.map → identifier-conversion-BXrBYgAq.mjs.map} +1 -1
  70. package/dist/{identity-B75EaVTM.mjs → identity-BtuwgqhS.mjs} +2 -2
  71. package/dist/{identity-B75EaVTM.mjs.map → identity-BtuwgqhS.mjs.map} +1 -1
  72. package/dist/{index-DRX_LLQM.d.mts → index-CsO6vG2h.d.mts} +26 -8
  73. package/dist/index.d.mts +2 -2
  74. package/dist/index.mjs +1 -1
  75. package/dist/insert-value-Cbp_bNxj.mjs +2 -0
  76. package/dist/insert-value-Cbp_bNxj.mjs.map +1 -0
  77. package/dist/instrumentation.d.mts +1 -1
  78. package/dist/instrumentation.mjs +1 -1
  79. package/dist/{invariant-B5znICP_.mjs → invariant-Dw9UB49x.mjs} +1 -1
  80. package/dist/{invariant-B5znICP_.mjs.map → invariant-Dw9UB49x.mjs.map} +1 -1
  81. package/dist/{json-number-DoseUwuo.mjs → json-number-ChtP7ZeY.mjs} +1 -1
  82. package/dist/{json-number-DoseUwuo.mjs.map → json-number-ChtP7ZeY.mjs.map} +1 -1
  83. package/dist/{key-rszcmZdB.mjs → key-Cz83fdLO.mjs} +2 -2
  84. package/dist/{key-rszcmZdB.mjs.map → key-Cz83fdLO.mjs.map} +1 -1
  85. package/dist/keys-EP1Eq2eD.mjs +2 -0
  86. package/dist/keys-EP1Eq2eD.mjs.map +1 -0
  87. package/dist/{libsql-CAZVcr9G.mjs → libsql-ClGi2zY2.mjs} +3 -3
  88. package/dist/{libsql-CAZVcr9G.mjs.map → libsql-ClGi2zY2.mjs.map} +1 -1
  89. package/dist/libsql.d.mts +1 -1
  90. package/dist/libsql.mjs +1 -1
  91. package/dist/{memory-CqWRO6-3.mjs → memory-B1GnzgZr.mjs} +2 -2
  92. package/dist/{memory-CqWRO6-3.mjs.map → memory-B1GnzgZr.mjs.map} +1 -1
  93. package/dist/migrations/mysql.d.mts +5 -5
  94. package/dist/migrations/mysql.mjs +1 -1
  95. package/dist/migrations/postgres.d.mts +5 -5
  96. package/dist/migrations/postgres.mjs +1 -1
  97. package/dist/migrations/sqlite.d.mts +5 -5
  98. package/dist/migrations/sqlite.mjs +1 -1
  99. package/dist/migrations/storage/durable-object.d.mts +1 -1
  100. package/dist/migrations/storage/durable-object.mjs +1 -1
  101. package/dist/migrations/storage/fs.d.mts +1 -1
  102. package/dist/migrations/storage/fs.mjs +1 -1
  103. package/dist/migrations/storage/r2.d.mts +1 -1
  104. package/dist/migrations/storage/r2.mjs +1 -1
  105. package/dist/migrations/tenant.d.mts +3 -3
  106. package/dist/migrations/tenant.mjs +1 -1
  107. package/dist/migrations.d.mts +5 -5
  108. package/dist/migrations.mjs +1 -1
  109. package/dist/model-DsXZ_pHE.mjs +2 -0
  110. package/dist/model-DsXZ_pHE.mjs.map +1 -0
  111. package/dist/{mysql-adapter-Dbo7l0lI.mjs → mysql-adapter-D-Dq2FN9.mjs} +2 -2
  112. package/dist/{mysql-adapter-Dbo7l0lI.mjs.map → mysql-adapter-D-Dq2FN9.mjs.map} +1 -1
  113. package/dist/{mysql-BPPBSJzl.mjs → mysql-hoo290Dd.mjs} +6 -6
  114. package/dist/{mysql-BPPBSJzl.mjs.map → mysql-hoo290Dd.mjs.map} +1 -1
  115. package/dist/mysql2.d.mts +1 -1
  116. package/dist/mysql2.mjs +1 -1
  117. package/dist/{native-types-6wCGP1a1.mjs → native-types-CQH05hcr.mjs} +1 -1
  118. package/dist/{native-types-6wCGP1a1.mjs.map → native-types-CQH05hcr.mjs.map} +1 -1
  119. package/dist/neon-http.d.mts +1 -1
  120. package/dist/neon-http.mjs +1 -1
  121. package/dist/{object-store-Cs3AueG5.d.mts → object-store-9VfS-3sY.d.mts} +4 -4
  122. package/dist/{object-store-DmnlQy7V.mjs → object-store-DdgcT8d9.mjs} +2 -2
  123. package/dist/{object-store-DmnlQy7V.mjs.map → object-store-DdgcT8d9.mjs.map} +1 -1
  124. package/dist/on.d.mts +1 -1
  125. package/dist/on.mjs +1 -1
  126. package/dist/ordering.d.mts +101 -0
  127. package/dist/ordering.mjs +11 -0
  128. package/dist/ordering.mjs.map +1 -0
  129. package/dist/permissions.d.mts +1 -1
  130. package/dist/permissions.mjs +1 -1
  131. package/dist/pg.d.mts +1 -1
  132. package/dist/pg.mjs +1 -1
  133. package/dist/pglite.d.mts +1 -1
  134. package/dist/pglite.mjs +1 -1
  135. package/dist/{physical-DT6C54w7.mjs → physical-t_gDjUCD.mjs} +2 -2
  136. package/dist/{physical-DT6C54w7.mjs.map → physical-t_gDjUCD.mjs.map} +1 -1
  137. package/dist/{pinned-session-BdON2d0V.mjs → pinned-session-De2rDjdO.mjs} +2 -2
  138. package/dist/{pinned-session-BdON2d0V.mjs.map → pinned-session-De2rDjdO.mjs.map} +1 -1
  139. package/dist/planetscale.d.mts +1 -1
  140. package/dist/planetscale.mjs +1 -1
  141. package/dist/{planner-BxCcoO8s.d.mts → planner-Cc3ABIUU.d.mts} +1 -1
  142. package/dist/{postgres-BK_aOx_C.mjs → postgres-CqcP_qv-.mjs} +4 -4
  143. package/dist/{postgres-BK_aOx_C.mjs.map → postgres-CqcP_qv-.mjs.map} +1 -1
  144. package/dist/{postgres-adapter-DxhZu7Qw.mjs → postgres-adapter-CYZAL2uo.mjs} +2 -2
  145. package/dist/{postgres-adapter-DxhZu7Qw.mjs.map → postgres-adapter-CYZAL2uo.mjs.map} +1 -1
  146. package/dist/{postgres-adapter-CVazEDVI.mjs → postgres-adapter-_o6EWuxW.mjs} +2 -2
  147. package/dist/{postgres-adapter-CVazEDVI.mjs.map → postgres-adapter-_o6EWuxW.mjs.map} +1 -1
  148. package/dist/{postgres-result-DYeVeHuT.mjs → postgres-result-D94PyZ78.mjs} +1 -1
  149. package/dist/{postgres-result-DYeVeHuT.mjs.map → postgres-result-D94PyZ78.mjs.map} +1 -1
  150. package/dist/postgres.d.mts +1 -1
  151. package/dist/postgres.mjs +1 -1
  152. package/dist/{provider-limits-zLe7S_0W.mjs → provider-limits-kO9B3KCF.mjs} +2 -2
  153. package/dist/{provider-limits-zLe7S_0W.mjs.map → provider-limits-kO9B3KCF.mjs.map} +1 -1
  154. package/dist/{relation-bound-Bj7X-EUE.mjs → relation-bound-5hindjxU.mjs} +1 -1
  155. package/dist/{relation-bound-Bj7X-EUE.mjs.map → relation-bound-5hindjxU.mjs.map} +1 -1
  156. package/dist/{result-parsing-C2044903.mjs → result-parsing-Dkgy-xcy.mjs} +1 -1
  157. package/dist/{result-parsing-C2044903.mjs.map → result-parsing-Dkgy-xcy.mjs.map} +1 -1
  158. package/dist/result-shape-uaCsF_SZ.mjs +2 -0
  159. package/dist/{result-shape-C8QFUuIt.mjs.map → result-shape-uaCsF_SZ.mjs.map} +1 -1
  160. package/dist/rows-AtX0guAb.mjs +2 -0
  161. package/dist/rows-AtX0guAb.mjs.map +1 -0
  162. package/dist/scalar-CZ_q89Hc.mjs +4 -0
  163. package/dist/scalar-CZ_q89Hc.mjs.map +1 -0
  164. package/dist/schema/json.d.mts +1 -1
  165. package/dist/schema/json.mjs +1 -1
  166. package/dist/schema/json.mjs.map +1 -1
  167. package/dist/schema-CZTCxG2p.mjs +2 -0
  168. package/dist/{schema-CY9kOwJ-.mjs.map → schema-CZTCxG2p.mjs.map} +1 -1
  169. package/dist/{schema-introspection-CfqmM3Cz.mjs → schema-introspection-DoZHc1o7.mjs} +2 -2
  170. package/dist/{schema-introspection-CfqmM3Cz.mjs.map → schema-introspection-DoZHc1o7.mjs.map} +1 -1
  171. package/dist/schema.d.mts +1 -1
  172. package/dist/schema.mjs +1 -1
  173. package/dist/{select-assembly-D7FEenz2.mjs → select-assembly-BtNtBsUh.mjs} +1 -1
  174. package/dist/{select-assembly-D7FEenz2.mjs.map → select-assembly-BtNtBsUh.mjs.map} +1 -1
  175. package/dist/{settle-CObilv26.mjs → settle-v6QhvFkm.mjs} +2 -2
  176. package/dist/{settle-CObilv26.mjs.map → settle-v6QhvFkm.mjs.map} +1 -1
  177. package/dist/{sha256-Da07rzvR.mjs → sha256-D_fCV62w.mjs} +1 -1
  178. package/dist/{sha256-Da07rzvR.mjs.map → sha256-D_fCV62w.mjs.map} +1 -1
  179. package/dist/soft-delete.d.mts +1 -1
  180. package/dist/{sql-statement-tokens-DL3ooNs7.mjs → sql-statement-tokens-CV2qkIKN.mjs} +1 -1
  181. package/dist/{sql-statement-tokens-DL3ooNs7.mjs.map → sql-statement-tokens-CV2qkIKN.mjs.map} +1 -1
  182. package/dist/sql.d.mts +1 -1
  183. package/dist/{sqlite-adapter-DqT6HeDs.mjs → sqlite-adapter-CnAwmszh.mjs} +2 -2
  184. package/dist/{sqlite-adapter-DqT6HeDs.mjs.map → sqlite-adapter-CnAwmszh.mjs.map} +1 -1
  185. package/dist/{sqlite-utils-DeDlMJKj.mjs → sqlite-utils-DztTzv08.mjs} +2 -2
  186. package/dist/{sqlite-utils-DeDlMJKj.mjs.map → sqlite-utils-DztTzv08.mjs.map} +1 -1
  187. package/dist/sqlite3.d.mts +1 -1
  188. package/dist/sqlite3.mjs +1 -1
  189. package/dist/{standard-sql-BErrm6AV.mjs → standard-sql-Ci8ROrql.mjs} +1 -1
  190. package/dist/{standard-sql-BErrm6AV.mjs.map → standard-sql-Ci8ROrql.mjs.map} +1 -1
  191. package/dist/{suppressed-failure-3C4sFXvH.mjs → suppressed-failure-DO0ej03b.mjs} +1 -1
  192. package/dist/{suppressed-failure-3C4sFXvH.mjs.map → suppressed-failure-DO0ej03b.mjs.map} +1 -1
  193. package/dist/to-many-BtLpp5cW.mjs +2 -0
  194. package/dist/{to-many-DqYv9-vp.mjs.map → to-many-BtLpp5cW.mjs.map} +1 -1
  195. package/dist/{transaction-operation-Co3hw8yz.mjs → transaction-operation-Km-Gr-a3.mjs} +1 -1
  196. package/dist/{transaction-operation-Co3hw8yz.mjs.map → transaction-operation-Km-Gr-a3.mjs.map} +1 -1
  197. package/dist/{types-CJgtjXtu.mjs → types-C4v6iAmY.mjs} +1 -1
  198. package/dist/{types-CJgtjXtu.mjs.map → types-C4v6iAmY.mjs.map} +1 -1
  199. package/dist/{utils-DooFtO1V.mjs → utils-CAACs9Jw.mjs} +2 -2
  200. package/dist/{utils-DooFtO1V.mjs.map → utils-CAACs9Jw.mjs.map} +1 -1
  201. package/dist/v-Pb_jJOjC.mjs +2 -0
  202. package/dist/{v-yKivkoka.mjs.map → v-Pb_jJOjC.mjs.map} +1 -1
  203. package/dist/validation-BSpO4DjI.mjs +2 -0
  204. package/dist/{validation-u-sZDdfD.mjs.map → validation-BSpO4DjI.mjs.map} +1 -1
  205. package/dist/validation.d.mts +1 -1
  206. package/dist/validation.mjs +1 -1
  207. package/dist/validator-Dthaj1Hz.mjs +2 -0
  208. package/dist/validator-Dthaj1Hz.mjs.map +1 -0
  209. package/dist/version-DvynkoaW.mjs +2 -0
  210. package/dist/{version-WvqPqZJ4.mjs.map → version-DvynkoaW.mjs.map} +1 -1
  211. package/dist/write-sinks-3IKCDF-S.mjs +2 -0
  212. package/dist/{write-sinks-CoB5PPw9.mjs.map → write-sinks-3IKCDF-S.mjs.map} +1 -1
  213. package/dist/{writes-CD0mNS5-.mjs → writes-BX5fLiw5.mjs} +1 -1
  214. package/dist/{writes-CD0mNS5-.mjs.map → writes-BX5fLiw5.mjs.map} +1 -1
  215. package/package.json +34 -15
  216. package/dist/builder-D0GQK-fA.mjs +0 -2
  217. package/dist/chain-BQoDfo80.mjs +0 -2
  218. package/dist/chain-BQoDfo80.mjs.map +0 -1
  219. package/dist/client-BqgVSbk0.mjs +0 -2
  220. package/dist/client-BqgVSbk0.mjs.map +0 -1
  221. package/dist/every-DIG9CPly.mjs +0 -2
  222. package/dist/geo-point-codec-mjROsQX-.mjs +0 -2
  223. package/dist/geo-point-codec-mjROsQX-.mjs.map +0 -1
  224. package/dist/identifier-conversion-DV63mwKG.mjs +0 -2
  225. package/dist/result-shape-C8QFUuIt.mjs +0 -2
  226. package/dist/rows-D7ns2l0U.mjs +0 -2
  227. package/dist/rows-D7ns2l0U.mjs.map +0 -1
  228. package/dist/scalar-D6QmJ22_.mjs +0 -4
  229. package/dist/scalar-D6QmJ22_.mjs.map +0 -1
  230. package/dist/schema-CY9kOwJ-.mjs +0 -2
  231. package/dist/to-many-DqYv9-vp.mjs +0 -2
  232. package/dist/v-yKivkoka.mjs +0 -2
  233. package/dist/validation-u-sZDdfD.mjs +0 -2
  234. package/dist/validator-XVm02V0K.mjs +0 -2
  235. package/dist/validator-XVm02V0K.mjs.map +0 -1
  236. package/dist/version-WvqPqZJ4.mjs +0 -2
  237. package/dist/write-sinks-CoB5PPw9.mjs +0 -2
  238. /package/dist/{contract-H_WiAUaR.d.mts → contract-CYl0OzhZ.d.mts} +0 -0
  239. /package/dist/{sql-CF5Xi6z-.d.mts → sql-BnXk8adi.d.mts} +0 -0
package/dist/libsql.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { A as Schema, An as TransactionOptionSupport, At as DriverConfig, F as LinkedClientConfig, Fn as QueryResult, Ft as VibORMClient, Pn as QueryExecutionContext, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, kn as DriverTransactionOptions, s as DatabaseAdapter, u as Driver } from "./index-DRX_LLQM.mjs";
1
+ import { A as Schema, An as DriverTransactionOptions, At as DriverConfig, F as LinkedClientConfig, Fn as QueryExecutionContext, Ft as VibORMClient, In as QueryResult, Pt as NoExtraDriverConfigKeys, h as DriverResultParser, jn as TransactionOptionSupport, s as DatabaseAdapter, u as Driver } from "./index-CsO6vG2h.mjs";
2
2
  import { Client, Config, Transaction } from "@libsql/client";
3
3
 
4
4
  //#region src/drivers/libsql/index.d.ts
package/dist/libsql.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-23DWxZVY.mjs";import{l as n}from"./execution-context-_oajgBi4.mjs";import{n as r}from"./base-wlv81COV.mjs";import{m as i,u as a}from"./error-mapping-DRY49A3C.mjs";import{n as o}from"./query-CTna5P9o.mjs";import{n as s}from"./client-BqgVSbk0.mjs";import{c,i as l,r as u,t as d}from"./driver-szWYBmjD.mjs";import{c as f,i as p,l as m,n as h}from"./sqlite-utils-DeDlMJKj.mjs";import{t as g}from"./sqlite-adapter-DqT6HeDs.mjs";const _=new WeakSet,v={client:!0,databaseUrl:!0,dataDir:!0,authToken:!0,options:!0};function convertValuesForLibSQL(e){return e.map(e=>{let t=h(e);if(typeof t==`string`&&t.includes(`\0`))throw TypeError(`libSQL cannot preserve strings containing NUL bytes`);if(p(t))return t instanceof ArrayBuffer?t:f(t);if(t===null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||t instanceof Date)return t;throw TypeError(`Driver "libsql" received an unsupported SQLite parameter value.`)})}const libsqlRowCount=(e,n)=>{let r=t(e.rowsAffected,{provider:`libsql`,operation:n});return e.rows.length>0?e.rows.length:r};var LibSQLDriver=class extends d{adapter=new g;maxBindParametersPerStatement=32766;result=m;serializeTransactions;driverOptions;suppliedClient;constructor(e={}){if(super(`sqlite`,`libsql`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient)this.serializeTransactions=this.suppliedClient.protocol===`file`;else{let e=this.getDatabaseUrl();this.serializeTransactions=e===`:memory:`||e.startsWith(`file:`)}this.suppliedClient&&(this.client=this.suppliedClient,this.serializeTransactions&&Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)}))}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{createClient:e}=await import(`@libsql/client`),t=this.getDatabaseUrl(),n=this.driverOptions.authToken;return e({url:t,authToken:n,timeout:5e3,...this.driverOptions.options??{},intMode:`bigint`})}async closeClient(e){e!==this.suppliedClient&&`close`in e&&(e.close(),`commit`in e||_.delete(e))}async execute(e,t,n,r){let i=r?.operation??`execute`,a=convertValuesForLibSQL(n),o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,a=n?convertValuesForLibSQL(n):[],o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}transactionOptionSupport(){return{isolationLevel:`serializable-only`,isolationLevelReason:`libSQL serializes writers the way SQLite does and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:this.serializeTransactions?`queue`:`acquisition`}}async transaction(e,t,r,o){if(`commit`in e)throw a(this.driverName);let s=await l(()=>this.quarantineOnBusy(e,()=>e.transaction(`write`)),e=>e.close(),o?.maxWaitMs,{driverName:this.driverName,form:`callback`});return i({begin:()=>void 0,callback:()=>t(s),commit:()=>s.commit(),rollback:()=>s.rollback(),phases:n(r),close:()=>s.close()})}transactionCleanupFailed(e){}executeStatement(e,t){return this.quarantineOnBusy(e,()=>e.execute(t))}async quarantineOnBusy(e,t){try{return await t()}catch(t){throw this.serializeTransactions&&!(`commit`in e)&&typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`&&(t.code===`SQLITE_BUSY`||t.code.startsWith(`SQLITE_BUSY_`))&&(_.add(e),this.closeRetryClient=e,this.client=null,this.initPromise=null),t}}async getClient(e){let t=await super.getClient(e);return this.assertLocalClientUsable(t),t}assertLocalClientUsable(e){if(!(`commit`in e)&&_.has(e))throw new o(`Local libSQL execution encountered SQLITE_BUSY; disconnect an owned driver, or close and replace the supplied native client, before reuse.`,{code:r.CONNECTION_CLOSED,meta:{driver:`libsql`}})}getDatabaseUrl(){return this.driverOptions.databaseUrl?this.driverOptions.databaseUrl:this.driverOptions.dataDir?`file:${this.driverOptions.dataDir}`:`file::memory:`}};function createClient(e){c(e,`libsql`,v);let{client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}=e;return s(e,new LibSQLDriver({client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}))}export{LibSQLDriver,createClient};
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{o as t}from"./normalized-result-23DWxZVY.mjs";import{l as n}from"./execution-context-_oajgBi4.mjs";import{n as r}from"./base-wlv81COV.mjs";import{m as i,u as a}from"./error-mapping-D--MVRCY.mjs";import{n as o}from"./query-CTna5P9o.mjs";import{n as s}from"./client-Yqn0LqmI.mjs";import{c,i as l,r as u,t as d}from"./driver-CK_IKqDa.mjs";import{c as f,i as p,l as m,n as h}from"./sqlite-utils-DztTzv08.mjs";import{t as g}from"./sqlite-adapter-CnAwmszh.mjs";const _=new WeakSet,v={client:!0,databaseUrl:!0,dataDir:!0,authToken:!0,options:!0};function convertValuesForLibSQL(e){return e.map(e=>{let t=h(e);if(typeof t==`string`&&t.includes(`\0`))throw TypeError(`libSQL cannot preserve strings containing NUL bytes`);if(p(t))return t instanceof ArrayBuffer?t:f(t);if(t===null||typeof t==`string`||typeof t==`number`||typeof t==`bigint`||typeof t==`boolean`||t instanceof Date)return t;throw TypeError(`Driver "libsql" received an unsupported SQLite parameter value.`)})}const libsqlRowCount=(e,n)=>{let r=t(e.rowsAffected,{provider:`libsql`,operation:n});return e.rows.length>0?e.rows.length:r};var LibSQLDriver=class extends d{adapter=new g;maxBindParametersPerStatement=32766;result=m;serializeTransactions;driverOptions;suppliedClient;constructor(e={}){if(super(`sqlite`,`libsql`),this.driverOptions=e,this.suppliedClient=e.client,this.suppliedClient)this.serializeTransactions=this.suppliedClient.protocol===`file`;else{let e=this.getDatabaseUrl();this.serializeTransactions=e===`:memory:`||e.startsWith(`file:`)}this.suppliedClient&&(this.client=this.suppliedClient,this.serializeTransactions&&Object.defineProperty(this,`connectionQueue`,{value:u(this.suppliedClient)}))}async initClient(){if(this.suppliedClient)return this.suppliedClient;let{createClient:e}=await import(`@libsql/client`),t=this.getDatabaseUrl(),n=this.driverOptions.authToken;return e({url:t,authToken:n,timeout:5e3,...this.driverOptions.options??{},intMode:`bigint`})}async closeClient(e){e!==this.suppliedClient&&`close`in e&&(e.close(),`commit`in e||_.delete(e))}async execute(e,t,n,r){let i=r?.operation??`execute`,a=convertValuesForLibSQL(n),o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}async executeRaw(e,t,n,r){let i=r?.operation??`executeRaw`,a=n?convertValuesForLibSQL(n):[],o=await this.executeStatement(e,{sql:t,args:a});return{rows:o.rows,rowCount:libsqlRowCount(o,i)}}transactionOptionSupport(){return{isolationLevel:`serializable-only`,isolationLevelReason:`libSQL serializes writers the way SQLite does and has no statement to weaken isolation, so only Serializable can be honored truthfully`,timeout:!0,maxWait:this.serializeTransactions?`queue`:`acquisition`}}async transaction(e,t,r,o){if(`commit`in e)throw a(this.driverName);let s=await l(()=>this.quarantineOnBusy(e,()=>e.transaction(`write`)),e=>e.close(),o?.maxWaitMs,{driverName:this.driverName,form:`callback`});return i({begin:()=>void 0,callback:()=>t(s),commit:()=>s.commit(),rollback:()=>s.rollback(),phases:n(r),close:()=>s.close()})}transactionCleanupFailed(e){}executeStatement(e,t){return this.quarantineOnBusy(e,()=>e.execute(t))}async quarantineOnBusy(e,t){try{return await t()}catch(t){throw this.serializeTransactions&&!(`commit`in e)&&typeof t==`object`&&t&&`code`in t&&typeof t.code==`string`&&(t.code===`SQLITE_BUSY`||t.code.startsWith(`SQLITE_BUSY_`))&&(_.add(e),this.closeRetryClient=e,this.client=null,this.initPromise=null),t}}async getClient(e){let t=await super.getClient(e);return this.assertLocalClientUsable(t),t}assertLocalClientUsable(e){if(!(`commit`in e)&&_.has(e))throw new o(`Local libSQL execution encountered SQLITE_BUSY; disconnect an owned driver, or close and replace the supplied native client, before reuse.`,{code:r.CONNECTION_CLOSED,meta:{driver:`libsql`}})}getDatabaseUrl(){return this.driverOptions.databaseUrl?this.driverOptions.databaseUrl:this.driverOptions.dataDir?`file:${this.driverOptions.dataDir}`:`file::memory:`}};function createClient(e){c(e,`libsql`,v);let{client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}=e;return s(e,new LibSQLDriver({client:t,databaseUrl:n,dataDir:r,authToken:i,options:a}))}export{LibSQLDriver,createClient};
2
2
  //# sourceMappingURL=libsql.mjs.map
@@ -1,2 +1,2 @@
1
- import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{D as r}from"./client-BCcIdDl8.mjs";import{n as i}from"./canonical-json-D_FgOt4S.mjs";import{a,c as o}from"./identity-B75EaVTM.mjs";const isCorruption=e=>e instanceof n&&e.code===t.MIGRATION_CORRUPTION;function createStorageConformanceSuite(e){return[{name:`identical content-addressed publish is idempotent`,run:async()=>{let t=e(),n=o(`hello`),i=r(n),a=await t.publishSql(i,n),s=await t.publishSql(i,n);if(a.outcome!==`created`||s.outcome!==`identical`)throw Error(`idempotent publish failed`)}},{name:`same hash with different bytes is corruption`,run:async()=>{let t=e(),n=o(`hello`),i=r(n);await t.publishSql(i,n);try{await t.publishSql(i,o(`other`))}catch(e){if(isCorruption(e))return}throw Error(`corrupt publish was accepted`)}},{name:`listStates returns only committed manifests`,run:async()=>{if((await e().listStates()).length!==0)throw Error(`fresh writer is not empty`)}},{name:`estate publish is idempotent for identical bytes`,run:async()=>{let t=e(),n=o(`{"format":"1"}`),r=await t.publishEstate(n),i=await t.publishEstate(n);if(r.outcome!==`created`||i.outcome!==`identical`)throw Error(`estate idempotent publish failed`)}},{name:`concurrent identical creates report created exactly once`,run:async()=>{let t=e(),n=o(`race-identical`),i=r(n),a=(await Promise.all(Array.from({length:8},()=>t.publishState(i,n)))).filter(e=>e.outcome===`created`).length;if(a!==1)throw Error(`${a} of 8 concurrent creates won`)}},{name:`concurrent conflicting creates keep one winner and refuse the rest`,run:async()=>{let t=e(),n=r(o(`race-conflicting`)),a=Array.from({length:8},(e,t)=>o(`{"racer":${t}}`)),s=await Promise.allSettled(a.map(e=>t.publishState(n,e))),c=a.filter((e,t)=>s[t]?.status===`fulfilled`),l=s.filter(e=>e.status===`rejected`&&isCorruption(e.reason)).length,u=await t.readState(n);if(c.length!==1||l!==7||!(u&&i(u,c[0])))throw Error(`${c.length} winners and ${l} refusals of 8 conflicting creates`)}},{name:`absent artifacts read as null`,run:async()=>{let t=e(),n=r(o(`absent`));if((await Promise.all([t.readState(n),t.readSnapshot(n),t.readSql(n)])).some(e=>e!==null))throw Error(`an absent artifact read as bytes`)}},{name:`published artifacts are listed as soon as publish returns`,run:async()=>{let t=e(),n=Array.from({length:5},(e,t)=>o(`listed-${t}`)),i=n.map(r);for(let[e,r]of i.entries())await t.publishState(r,n[e]),await t.publishSnapshot(r,n[e]),await t.publishSql(r,n[e]);if((await Promise.all([t.listStates(),t.listSnapshots(),t.listSql()])).some(e=>i.some(t=>!e.includes(t))))throw Error(`a published artifact is missing from its listing`)}},{name:`a listed state's snapshot and SQL are already readable (manifest last)`,run:async()=>{let t=e(),n=o(`manifest-last`),i=r(n),a=!1,s=(async()=>{await t.publishSnapshot(i,n),await t.publishSql(i,n),await t.publishState(i,n)})().finally(()=>{a=!0});try{for(;;){let e=a;if((await t.listStates()).includes(i))break;if(e)throw Error(`a published state is not listed`)}let[e,n]=await Promise.all([t.readSnapshot(i),t.readSql(i)]);if(!(e&&n))throw Error(`a listed state's artifacts are not readable yet`)}finally{await s}}}]}var MemoryEstateStorage=class{estate=null;states=new Map;snapshots=new Map;sql=new Map;async readEstate(){return this.estate?this.estate.slice():null}async listStates(){return[...this.states.keys()].sort()}async listSnapshots(){return[...this.snapshots.keys()].sort()}async listSql(){return[...this.sql.keys()].sort()}async readState(e){let t=this.states.get(e);return t?t.slice():null}async readSnapshot(e){let t=this.snapshots.get(e);return t?t.slice():null}async readSql(e){let t=this.sql.get(e);return t?t.slice():null}async publishEstate(e){if(this.estate&&!i(this.estate,e))throw new n(`estate.json already exists with different bytes`,t.MIGRATION_CORRUPTION);return this.estate?{outcome:`identical`}:(this.estate=e.slice(),{outcome:`created`})}async publishSnapshot(e,t){return publishMap(this.snapshots,e,t,`snapshot`)}async publishSql(e,t){return publishMap(this.sql,e,t,`sql`)}async publishState(e,r){if(!a(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return publishMap(this.states,e,r,`state`)}};function publishMap(e,r,a,o){let s=e.get(r);if(s){if(!i(s,a))throw new n(`${o} ${r} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}return e.set(r,a.slice()),{outcome:`created`}}export{createStorageConformanceSuite as n,MemoryEstateStorage as t};
2
- //# sourceMappingURL=memory-CqWRO6-3.mjs.map
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{n as t}from"./base-wlv81COV.mjs";import{t as n}from"./migrations-OE5D32qo.mjs";import{D as r}from"./client-l7dSOul5.mjs";import{n as i}from"./canonical-json-B6J5VbLv.mjs";import{a,c as o}from"./identity-BtuwgqhS.mjs";const isCorruption=e=>e instanceof n&&e.code===t.MIGRATION_CORRUPTION;function createStorageConformanceSuite(e){return[{name:`identical content-addressed publish is idempotent`,run:async()=>{let t=e(),n=o(`hello`),i=r(n),a=await t.publishSql(i,n),s=await t.publishSql(i,n);if(a.outcome!==`created`||s.outcome!==`identical`)throw Error(`idempotent publish failed`)}},{name:`same hash with different bytes is corruption`,run:async()=>{let t=e(),n=o(`hello`),i=r(n);await t.publishSql(i,n);try{await t.publishSql(i,o(`other`))}catch(e){if(isCorruption(e))return}throw Error(`corrupt publish was accepted`)}},{name:`listStates returns only committed manifests`,run:async()=>{if((await e().listStates()).length!==0)throw Error(`fresh writer is not empty`)}},{name:`estate publish is idempotent for identical bytes`,run:async()=>{let t=e(),n=o(`{"format":"1"}`),r=await t.publishEstate(n),i=await t.publishEstate(n);if(r.outcome!==`created`||i.outcome!==`identical`)throw Error(`estate idempotent publish failed`)}},{name:`concurrent identical creates report created exactly once`,run:async()=>{let t=e(),n=o(`race-identical`),i=r(n),a=(await Promise.all(Array.from({length:8},()=>t.publishState(i,n)))).filter(e=>e.outcome===`created`).length;if(a!==1)throw Error(`${a} of 8 concurrent creates won`)}},{name:`concurrent conflicting creates keep one winner and refuse the rest`,run:async()=>{let t=e(),n=r(o(`race-conflicting`)),a=Array.from({length:8},(e,t)=>o(`{"racer":${t}}`)),s=await Promise.allSettled(a.map(e=>t.publishState(n,e))),c=a.filter((e,t)=>s[t]?.status===`fulfilled`),l=s.filter(e=>e.status===`rejected`&&isCorruption(e.reason)).length,u=await t.readState(n);if(c.length!==1||l!==7||!(u&&i(u,c[0])))throw Error(`${c.length} winners and ${l} refusals of 8 conflicting creates`)}},{name:`absent artifacts read as null`,run:async()=>{let t=e(),n=r(o(`absent`));if((await Promise.all([t.readState(n),t.readSnapshot(n),t.readSql(n)])).some(e=>e!==null))throw Error(`an absent artifact read as bytes`)}},{name:`published artifacts are listed as soon as publish returns`,run:async()=>{let t=e(),n=Array.from({length:5},(e,t)=>o(`listed-${t}`)),i=n.map(r);for(let[e,r]of i.entries())await t.publishState(r,n[e]),await t.publishSnapshot(r,n[e]),await t.publishSql(r,n[e]);if((await Promise.all([t.listStates(),t.listSnapshots(),t.listSql()])).some(e=>i.some(t=>!e.includes(t))))throw Error(`a published artifact is missing from its listing`)}},{name:`a listed state's snapshot and SQL are already readable (manifest last)`,run:async()=>{let t=e(),n=o(`manifest-last`),i=r(n),a=!1,s=(async()=>{await t.publishSnapshot(i,n),await t.publishSql(i,n),await t.publishState(i,n)})().finally(()=>{a=!0});try{for(;;){let e=a;if((await t.listStates()).includes(i))break;if(e)throw Error(`a published state is not listed`)}let[e,n]=await Promise.all([t.readSnapshot(i),t.readSql(i)]);if(!(e&&n))throw Error(`a listed state's artifacts are not readable yet`)}finally{await s}}}]}var MemoryEstateStorage=class{estate=null;states=new Map;snapshots=new Map;sql=new Map;async readEstate(){return this.estate?this.estate.slice():null}async listStates(){return[...this.states.keys()].sort()}async listSnapshots(){return[...this.snapshots.keys()].sort()}async listSql(){return[...this.sql.keys()].sort()}async readState(e){let t=this.states.get(e);return t?t.slice():null}async readSnapshot(e){let t=this.snapshots.get(e);return t?t.slice():null}async readSql(e){let t=this.sql.get(e);return t?t.slice():null}async publishEstate(e){if(this.estate&&!i(this.estate,e))throw new n(`estate.json already exists with different bytes`,t.MIGRATION_CORRUPTION);return this.estate?{outcome:`identical`}:(this.estate=e.slice(),{outcome:`created`})}async publishSnapshot(e,t){return publishMap(this.snapshots,e,t,`snapshot`)}async publishSql(e,t){return publishMap(this.sql,e,t,`sql`)}async publishState(e,r){if(!a(e))throw new n(`State id is not a SHA-256 digest`,t.MIGRATION_INVALID_ESTATE);return publishMap(this.states,e,r,`state`)}};function publishMap(e,r,a,o){let s=e.get(r);if(s){if(!i(s,a))throw new n(`${o} ${r} already holds different bytes`,t.MIGRATION_CORRUPTION);return{outcome:`identical`}}return e.set(r,a.slice()),{outcome:`created`}}export{createStorageConformanceSuite as n,MemoryEstateStorage as t};
2
+ //# sourceMappingURL=memory-B1GnzgZr.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"memory-CqWRO6-3.mjs","names":[],"sources":["../src/migrations/storage/conformance.ts","../src/migrations/storage/memory.ts"],"sourcesContent":["/**\n * Reusable storage conformance suite. A writable driver that cannot pass\n * these tests is not a V1 estate owner.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { utf8Bytes } from \"../identity\";\nimport { encodeSqlBlob } from \"../v1-parse\";\nimport type { MigrationStorageWriter } from \"./contract\";\n\nconst RACERS = 8;\nconst LISTED = 5;\n\nconst isCorruption = (error: unknown): boolean =>\n error instanceof MigrationError &&\n error.code === VibORMErrorCode.MIGRATION_CORRUPTION;\n\nexport function createStorageConformanceSuite(\n createWriter: () => MigrationStorageWriter\n): { readonly name: string; readonly run: () => Promise<void> }[] {\n return [\n {\n name: \"identical content-addressed publish is idempotent\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n const first = await storage.publishSql(hash, bytes);\n const second = await storage.publishSql(hash, bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"idempotent publish failed\");\n }\n },\n },\n {\n name: \"same hash with different bytes is corruption\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n await storage.publishSql(hash, bytes);\n try {\n await storage.publishSql(hash, utf8Bytes(\"other\"));\n } catch (error) {\n if (isCorruption(error)) return;\n }\n throw new Error(\"corrupt publish was accepted\");\n },\n },\n {\n name: \"listStates returns only committed manifests\",\n run: async () => {\n const storage = createWriter();\n const listed = await storage.listStates();\n if (listed.length !== 0) throw new Error(\"fresh writer is not empty\");\n },\n },\n {\n name: \"estate publish is idempotent for identical bytes\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes('{\"format\":\"1\"}');\n const first = await storage.publishEstate(bytes);\n const second = await storage.publishEstate(bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"estate idempotent publish failed\");\n }\n },\n },\n {\n name: \"concurrent identical creates report created exactly once\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"race-identical\");\n const id = encodeSqlBlob(bytes);\n const outcomes = await Promise.all(\n Array.from({ length: RACERS }, () => storage.publishState(id, bytes))\n );\n const created = outcomes.filter((o) => o.outcome === \"created\").length;\n if (created !== 1) {\n throw new Error(`${created} of ${RACERS} concurrent creates won`);\n }\n },\n },\n {\n name: \"concurrent conflicting creates keep one winner and refuse the rest\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"race-conflicting\"));\n const candidates = Array.from({ length: RACERS }, (_, n) =>\n utf8Bytes(`{\"racer\":${n}}`)\n );\n const settled = await Promise.allSettled(\n candidates.map((bytes) => storage.publishState(id, bytes))\n );\n const winners = candidates.filter(\n (_, n) => settled[n]?.status === \"fulfilled\"\n );\n const refused = settled.filter(\n (result) =>\n result.status === \"rejected\" && isCorruption(result.reason)\n ).length;\n const stored = await storage.readState(id);\n if (\n winners.length !== 1 ||\n refused !== RACERS - 1 ||\n !(stored && bytesEqual(stored, winners[0]!))\n ) {\n throw new Error(\n `${winners.length} winners and ${refused} refusals of ${RACERS} conflicting creates`\n );\n }\n },\n },\n {\n name: \"absent artifacts read as null\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"absent\"));\n const reads = await Promise.all([\n storage.readState(id),\n storage.readSnapshot(id),\n storage.readSql(id),\n ]);\n if (reads.some((bytes) => bytes !== null)) {\n throw new Error(\"an absent artifact read as bytes\");\n }\n },\n },\n {\n name: \"published artifacts are listed as soon as publish returns\",\n run: async () => {\n const storage = createWriter();\n const artifacts = Array.from({ length: LISTED }, (_, n) =>\n utf8Bytes(`listed-${n}`)\n );\n const ids = artifacts.map(encodeSqlBlob);\n for (const [n, id] of ids.entries()) {\n await storage.publishState(id, artifacts[n]!);\n await storage.publishSnapshot(id, artifacts[n]!);\n await storage.publishSql(id, artifacts[n]!);\n }\n const listings = await Promise.all([\n storage.listStates(),\n storage.listSnapshots(),\n storage.listSql(),\n ]);\n if (listings.some((listed) => ids.some((id) => !listed.includes(id)))) {\n throw new Error(\"a published artifact is missing from its listing\");\n }\n },\n },\n {\n name: \"a listed state's snapshot and SQL are already readable (manifest last)\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"manifest-last\");\n const hash = encodeSqlBlob(bytes);\n let published = false;\n const publishing = (async () => {\n await storage.publishSnapshot(hash, bytes);\n await storage.publishSql(hash, bytes);\n await storage.publishState(hash, bytes);\n })().finally(() => {\n published = true;\n });\n try {\n for (;;) {\n const settled = published;\n if ((await storage.listStates()).includes(hash)) break;\n if (settled) throw new Error(\"a published state is not listed\");\n }\n const [snapshot, sql] = await Promise.all([\n storage.readSnapshot(hash),\n storage.readSql(hash),\n ]);\n if (!(snapshot && sql)) {\n throw new Error(\"a listed state's artifacts are not readable yet\");\n }\n } finally {\n await publishing;\n }\n },\n },\n ];\n}\n","/**\n * In-memory estate writer for tests and conformance.\n * Conditional create: same hash + same bytes is identical; different bytes is corruption.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport class MemoryEstateStorage implements MigrationStorageWriter {\n private estate: Uint8Array | null = null;\n private readonly states = new Map<Sha256, Uint8Array>();\n private readonly snapshots = new Map<Sha256, Uint8Array>();\n private readonly sql = new Map<Sha256, Uint8Array>();\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.estate ? this.estate.slice() : null;\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return [...this.states.keys()].sort();\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return [...this.snapshots.keys()].sort();\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return [...this.sql.keys()].sort();\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n const bytes = this.states.get(id);\n return bytes ? bytes.slice() : null;\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.snapshots.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.sql.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n if (this.estate && !bytesEqual(this.estate, bytes)) {\n throw new MigrationError(\n \"estate.json already exists with different bytes\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (this.estate) return { outcome: \"identical\" };\n this.estate = bytes.slice();\n return { outcome: \"created\" };\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishMap(this.snapshots, hash, bytes, \"snapshot\");\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishMap(this.sql, hash, bytes, \"sql\");\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return publishMap(this.states, id, bytes, \"state\");\n }\n}\n\nfunction publishMap(\n store: Map<Sha256, Uint8Array>,\n key: Sha256,\n bytes: Uint8Array,\n label: string\n): PublishResult {\n const existing = store.get(key);\n if (existing) {\n if (!bytesEqual(existing, bytes)) {\n throw new MigrationError(\n `${label} ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n store.set(key, bytes.slice());\n return { outcome: \"created\" };\n}\n"],"mappings":"yQAWA,MAGM,aAAgB,G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S,UAAW"}
1
+ {"version":3,"file":"memory-B1GnzgZr.mjs","names":[],"sources":["../src/migrations/storage/conformance.ts","../src/migrations/storage/memory.ts"],"sourcesContent":["/**\n * Reusable storage conformance suite. A writable driver that cannot pass\n * these tests is not a V1 estate owner.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { utf8Bytes } from \"../identity\";\nimport { encodeSqlBlob } from \"../v1-parse\";\nimport type { MigrationStorageWriter } from \"./contract\";\n\nconst RACERS = 8;\nconst LISTED = 5;\n\nconst isCorruption = (error: unknown): boolean =>\n error instanceof MigrationError &&\n error.code === VibORMErrorCode.MIGRATION_CORRUPTION;\n\nexport function createStorageConformanceSuite(\n createWriter: () => MigrationStorageWriter\n): { readonly name: string; readonly run: () => Promise<void> }[] {\n return [\n {\n name: \"identical content-addressed publish is idempotent\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n const first = await storage.publishSql(hash, bytes);\n const second = await storage.publishSql(hash, bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"idempotent publish failed\");\n }\n },\n },\n {\n name: \"same hash with different bytes is corruption\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"hello\");\n const hash = encodeSqlBlob(bytes);\n await storage.publishSql(hash, bytes);\n try {\n await storage.publishSql(hash, utf8Bytes(\"other\"));\n } catch (error) {\n if (isCorruption(error)) return;\n }\n throw new Error(\"corrupt publish was accepted\");\n },\n },\n {\n name: \"listStates returns only committed manifests\",\n run: async () => {\n const storage = createWriter();\n const listed = await storage.listStates();\n if (listed.length !== 0) throw new Error(\"fresh writer is not empty\");\n },\n },\n {\n name: \"estate publish is idempotent for identical bytes\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes('{\"format\":\"1\"}');\n const first = await storage.publishEstate(bytes);\n const second = await storage.publishEstate(bytes);\n if (first.outcome !== \"created\" || second.outcome !== \"identical\") {\n throw new Error(\"estate idempotent publish failed\");\n }\n },\n },\n {\n name: \"concurrent identical creates report created exactly once\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"race-identical\");\n const id = encodeSqlBlob(bytes);\n const outcomes = await Promise.all(\n Array.from({ length: RACERS }, () => storage.publishState(id, bytes))\n );\n const created = outcomes.filter((o) => o.outcome === \"created\").length;\n if (created !== 1) {\n throw new Error(`${created} of ${RACERS} concurrent creates won`);\n }\n },\n },\n {\n name: \"concurrent conflicting creates keep one winner and refuse the rest\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"race-conflicting\"));\n const candidates = Array.from({ length: RACERS }, (_, n) =>\n utf8Bytes(`{\"racer\":${n}}`)\n );\n const settled = await Promise.allSettled(\n candidates.map((bytes) => storage.publishState(id, bytes))\n );\n const winners = candidates.filter(\n (_, n) => settled[n]?.status === \"fulfilled\"\n );\n const refused = settled.filter(\n (result) =>\n result.status === \"rejected\" && isCorruption(result.reason)\n ).length;\n const stored = await storage.readState(id);\n if (\n winners.length !== 1 ||\n refused !== RACERS - 1 ||\n !(stored && bytesEqual(stored, winners[0]!))\n ) {\n throw new Error(\n `${winners.length} winners and ${refused} refusals of ${RACERS} conflicting creates`\n );\n }\n },\n },\n {\n name: \"absent artifacts read as null\",\n run: async () => {\n const storage = createWriter();\n const id = encodeSqlBlob(utf8Bytes(\"absent\"));\n const reads = await Promise.all([\n storage.readState(id),\n storage.readSnapshot(id),\n storage.readSql(id),\n ]);\n if (reads.some((bytes) => bytes !== null)) {\n throw new Error(\"an absent artifact read as bytes\");\n }\n },\n },\n {\n name: \"published artifacts are listed as soon as publish returns\",\n run: async () => {\n const storage = createWriter();\n const artifacts = Array.from({ length: LISTED }, (_, n) =>\n utf8Bytes(`listed-${n}`)\n );\n const ids = artifacts.map(encodeSqlBlob);\n for (const [n, id] of ids.entries()) {\n await storage.publishState(id, artifacts[n]!);\n await storage.publishSnapshot(id, artifacts[n]!);\n await storage.publishSql(id, artifacts[n]!);\n }\n const listings = await Promise.all([\n storage.listStates(),\n storage.listSnapshots(),\n storage.listSql(),\n ]);\n if (listings.some((listed) => ids.some((id) => !listed.includes(id)))) {\n throw new Error(\"a published artifact is missing from its listing\");\n }\n },\n },\n {\n name: \"a listed state's snapshot and SQL are already readable (manifest last)\",\n run: async () => {\n const storage = createWriter();\n const bytes = utf8Bytes(\"manifest-last\");\n const hash = encodeSqlBlob(bytes);\n let published = false;\n const publishing = (async () => {\n await storage.publishSnapshot(hash, bytes);\n await storage.publishSql(hash, bytes);\n await storage.publishState(hash, bytes);\n })().finally(() => {\n published = true;\n });\n try {\n for (;;) {\n const settled = published;\n if ((await storage.listStates()).includes(hash)) break;\n if (settled) throw new Error(\"a published state is not listed\");\n }\n const [snapshot, sql] = await Promise.all([\n storage.readSnapshot(hash),\n storage.readSql(hash),\n ]);\n if (!(snapshot && sql)) {\n throw new Error(\"a listed state's artifacts are not readable yet\");\n }\n } finally {\n await publishing;\n }\n },\n },\n ];\n}\n","/**\n * In-memory estate writer for tests and conformance.\n * Conditional create: same hash + same bytes is identical; different bytes is corruption.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { bytesEqual } from \"../canonical-json\";\nimport { isSha256, type Sha256 } from \"../identity\";\nimport type { MigrationStorageWriter, PublishResult } from \"./contract\";\n\nexport class MemoryEstateStorage implements MigrationStorageWriter {\n private estate: Uint8Array | null = null;\n private readonly states = new Map<Sha256, Uint8Array>();\n private readonly snapshots = new Map<Sha256, Uint8Array>();\n private readonly sql = new Map<Sha256, Uint8Array>();\n\n async readEstate(): Promise<Uint8Array | null> {\n return this.estate ? this.estate.slice() : null;\n }\n\n async listStates(): Promise<readonly Sha256[]> {\n return [...this.states.keys()].sort();\n }\n\n async listSnapshots(): Promise<readonly Sha256[]> {\n return [...this.snapshots.keys()].sort();\n }\n\n async listSql(): Promise<readonly Sha256[]> {\n return [...this.sql.keys()].sort();\n }\n\n async readState(id: Sha256): Promise<Uint8Array | null> {\n const bytes = this.states.get(id);\n return bytes ? bytes.slice() : null;\n }\n\n async readSnapshot(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.snapshots.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async readSql(hash: Sha256): Promise<Uint8Array | null> {\n const bytes = this.sql.get(hash);\n return bytes ? bytes.slice() : null;\n }\n\n async publishEstate(bytes: Uint8Array): Promise<PublishResult> {\n if (this.estate && !bytesEqual(this.estate, bytes)) {\n throw new MigrationError(\n \"estate.json already exists with different bytes\",\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n if (this.estate) return { outcome: \"identical\" };\n this.estate = bytes.slice();\n return { outcome: \"created\" };\n }\n\n async publishSnapshot(\n hash: Sha256,\n bytes: Uint8Array\n ): Promise<PublishResult> {\n return publishMap(this.snapshots, hash, bytes, \"snapshot\");\n }\n\n async publishSql(hash: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n return publishMap(this.sql, hash, bytes, \"sql\");\n }\n\n async publishState(id: Sha256, bytes: Uint8Array): Promise<PublishResult> {\n if (!isSha256(id)) {\n throw new MigrationError(\n \"State id is not a SHA-256 digest\",\n VibORMErrorCode.MIGRATION_INVALID_ESTATE\n );\n }\n return publishMap(this.states, id, bytes, \"state\");\n }\n}\n\nfunction publishMap(\n store: Map<Sha256, Uint8Array>,\n key: Sha256,\n bytes: Uint8Array,\n label: string\n): PublishResult {\n const existing = store.get(key);\n if (existing) {\n if (!bytesEqual(existing, bytes)) {\n throw new MigrationError(\n `${label} ${key} already holds different bytes`,\n VibORMErrorCode.MIGRATION_CORRUPTION\n );\n }\n return { outcome: \"identical\" };\n }\n store.set(key, bytes.slice());\n return { outcome: \"created\" };\n}\n"],"mappings":"yQAWA,MAGM,aAAgB,GACpB,aAAiB,GACjB,EAAM,OAAS,EAAgB,qBAEjC,SAAgB,8BACd,EACgE,CAChE,MAAO,CACL,CACE,KAAM,oDACN,IAAK,SAAY,CACf,IA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,EAAQ,KAAK,OAAO,IAAI,EAAG,CACjC,OAAO,EAAQ,EAAM,OAAO,CAAG,KAGjC,MAAM,aAAa,EAA0C,CAC3D,IAAM,EAAQ,KAAK,UAAU,IAAI,EAAK,CACtC,OAAO,EAAQ,EAAM,OAAO,CAAG,KAGjC,MAAM,QAAQ,EAA0C,CACtD,IAAM,EAAQ,KAAK,IAAI,IAAI,EAAK,CAChC,OAAO,EAAQ,EAAM,OAAO,CAAG,KAGjC,MAAM,cAAc,EAA2C,CAC7D,GAAI,KAAK,QAAU,CAAC,EAAW,KAAK,OAAQ,EAAM,CAChD,MAAM,IAAI,EACR,kDACA,EAAgB,qBACjB,CAIH,OAFI,KAAK,OAAe,CAAE,QAAS,YAAa,EAChD,KAAK,OAAS,EAAM,OAAO,CACpB,CAAE,QAAS,UAAW,EAG/B,MAAM,gBACJ,EACA,EACwB,CACxB,OAAO,WAAW,KAAK,UAAW,EAAM,EAAO,WAAW,CAG5D,MAAM,WAAW,EAAc,EAA2C,CACxE,OAAO,WAAW,KAAK,IAAK,EAAM,EAAO,MAAM,CAGjD,MAAM,aAAa,EAAY,EAA2C,CACxE,GAAI,CAAC,EAAS,EAAG,CACf,MAAM,IAAI,EACR,mCACA,EAAgB,yBACjB,CAEH,OAAO,WAAW,KAAK,OAAQ,EAAI,EAAO,QAAQ,GAItD,SAAS,WACP,EACA,EACA,EACA,EACe,CACf,IAAM,EAAW,EAAM,IAAI,EAAI,CAC/B,GAAI,EAAU,CACZ,GAAI,CAAC,EAAW,EAAU,EAAM,CAC9B,MAAM,IAAI,EACR,GAAG,EAAM,GAAG,EAAI,gCAChB,EAAgB,qBACjB,CAEH,MAAO,CAAE,QAAS,YAAa,CAGjC,OADA,EAAM,IAAI,EAAK,EAAM,OAAO,CAAC,CACtB,CAAE,QAAS,UAAW"}
@@ -1,6 +1,6 @@
1
- import { bi as isMigrationError, yi as MigrationError } from "../index-DRX_LLQM.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-BxCcoO8s.mjs";
3
- import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-H_WiAUaR.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-Cs3AueG5.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-C5BGyg5n.mjs";
1
+ import { bi as MigrationError, xi as isMigrationError } from "../index-CsO6vG2h.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-Cc3ABIUU.mjs";
3
+ import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CYl0OzhZ.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-9VfS-3sY.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-7ApJka0M.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,2 +1,2 @@
1
- import{n as e,t}from"../migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-BCcIdDl8.mjs";import{t as d}from"../identifier-conversion-DV63mwKG.mjs";import{t as f}from"../mysql-BPPBSJzl.mjs";import{n as p,t as m}from"../memory-CqWRO6-3.mjs";import{n as h,r as g,t as _}from"../object-store-DmnlQy7V.mjs";o(f);export{_ as MemoryConditionalObjectStore,m as MemoryEstateStorage,t as MigrationError,h as ObjectStoreEstateStorage,n as addDropResolver,s as auditStorage,c as createMigrationClient,u as createPredefinedResolver,p as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,i as lenientResolver,g as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
1
+ import{n as e,t}from"../migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-l7dSOul5.mjs";import{t as d}from"../identifier-conversion-BXrBYgAq.mjs";import{t as f}from"../mysql-hoo290Dd.mjs";import{n as p,t as m}from"../memory-B1GnzgZr.mjs";import{n as h,r as g,t as _}from"../object-store-DdgcT8d9.mjs";o(f);export{_ as MemoryConditionalObjectStore,m as MemoryEstateStorage,t as MigrationError,h as ObjectStoreEstateStorage,n as addDropResolver,s as auditStorage,c as createMigrationClient,u as createPredefinedResolver,p as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,i as lenientResolver,g as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
2
2
  //# sourceMappingURL=mysql.mjs.map
@@ -1,6 +1,6 @@
1
- import { bi as isMigrationError, yi as MigrationError } from "../index-DRX_LLQM.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-BxCcoO8s.mjs";
3
- import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-H_WiAUaR.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-Cs3AueG5.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-C5BGyg5n.mjs";
1
+ import { bi as MigrationError, xi as isMigrationError } from "../index-CsO6vG2h.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-Cc3ABIUU.mjs";
3
+ import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CYl0OzhZ.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-9VfS-3sY.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-7ApJka0M.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,2 +1,2 @@
1
- import{n as e,t}from"../migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-BCcIdDl8.mjs";import{t as d}from"../identifier-conversion-DV63mwKG.mjs";import{t as f}from"../postgres-BK_aOx_C.mjs";import{n as p,t as m}from"../memory-CqWRO6-3.mjs";import{n as h,r as g,t as _}from"../object-store-DmnlQy7V.mjs";o(f);export{_ as MemoryConditionalObjectStore,m as MemoryEstateStorage,t as MigrationError,h as ObjectStoreEstateStorage,n as addDropResolver,s as auditStorage,c as createMigrationClient,u as createPredefinedResolver,p as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,i as lenientResolver,g as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
1
+ import{n as e,t}from"../migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-l7dSOul5.mjs";import{t as d}from"../identifier-conversion-BXrBYgAq.mjs";import{t as f}from"../postgres-CqcP_qv-.mjs";import{n as p,t as m}from"../memory-B1GnzgZr.mjs";import{n as h,r as g,t as _}from"../object-store-DdgcT8d9.mjs";o(f);export{_ as MemoryConditionalObjectStore,m as MemoryEstateStorage,t as MigrationError,h as ObjectStoreEstateStorage,n as addDropResolver,s as auditStorage,c as createMigrationClient,u as createPredefinedResolver,p as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,i as lenientResolver,g as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
2
2
  //# sourceMappingURL=postgres.mjs.map
@@ -1,6 +1,6 @@
1
- import { bi as isMigrationError, yi as MigrationError } from "../index-DRX_LLQM.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-BxCcoO8s.mjs";
3
- import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-H_WiAUaR.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-Cs3AueG5.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-C5BGyg5n.mjs";
1
+ import { bi as MigrationError, xi as isMigrationError } from "../index-CsO6vG2h.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "../planner-Cc3ABIUU.mjs";
3
+ import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "../contract-CYl0OzhZ.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "../object-store-9VfS-3sY.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "../client-7ApJka0M.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,2 +1,2 @@
1
- import{n as e,t}from"../migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-BCcIdDl8.mjs";import{t as d}from"../identifier-conversion-DV63mwKG.mjs";import{n as f,t as p}from"../libsql-CAZVcr9G.mjs";import{n as m,t as h}from"../memory-CqWRO6-3.mjs";import{n as g,r as _,t as v}from"../object-store-DmnlQy7V.mjs";o(f),o(p);export{v as MemoryConditionalObjectStore,h as MemoryEstateStorage,t as MigrationError,g as ObjectStoreEstateStorage,n as addDropResolver,s as auditStorage,c as createMigrationClient,u as createPredefinedResolver,m as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,i as lenientResolver,_ as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
1
+ import{n as e,t}from"../migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,p as o,s,t as c,u as l,w as u}from"../client-l7dSOul5.mjs";import{t as d}from"../identifier-conversion-BXrBYgAq.mjs";import{n as f,t as p}from"../libsql-ClGi2zY2.mjs";import{n as m,t as h}from"../memory-B1GnzgZr.mjs";import{n as g,r as _,t as v}from"../object-store-DdgcT8d9.mjs";o(f),o(p);export{v as MemoryConditionalObjectStore,h as MemoryEstateStorage,t as MigrationError,g as ObjectStoreEstateStorage,n as addDropResolver,s as auditStorage,c as createMigrationClient,u as createPredefinedResolver,m as createStorageConformanceSuite,d as identifierConversionChecks,e as isMigrationError,i as lenientResolver,_ as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,l as sqliteCanonicalTimeExpression};
2
2
  //# sourceMappingURL=sqlite.mjs.map
@@ -1,4 +1,4 @@
1
- import { n as MigrationStorageWriter } from "../../contract-H_WiAUaR.mjs";
1
+ import { n as MigrationStorageWriter } from "../../contract-CYl0OzhZ.mjs";
2
2
  import { DurableObjectStorage } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/migrations/storage/durable-object.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"../../chunk-BuuaeEvq.mjs";import{n as t}from"../../object-store-DmnlQy7V.mjs";const n=`viborm_migration_estate`;function createDurableObjectStorageWriter(e,r={}){let{sql:i}=e,a=r.prefix??``;return i.exec(`CREATE TABLE IF NOT EXISTS ${n} (key TEXT PRIMARY KEY, bytes BLOB NOT NULL)`),new t({putIfAbsent:async(e,t)=>i.exec(`INSERT INTO ${n} (key, bytes) VALUES (?, ?) ON CONFLICT (key) DO NOTHING RETURNING key`,`${a}${e}`,t.slice().buffer).toArray().length===1?`created`:`exists`,get:async e=>{let[t]=i.exec(`SELECT bytes FROM ${n} WHERE key = ?`,`${a}${e}`).toArray();return t?new Uint8Array(t.bytes):null},list:async e=>i.exec(`SELECT key FROM ${n} WHERE substr(key, 1, length(?)) = ? ORDER BY key`,`${a}${e}`,`${a}${e}`).toArray().map(e=>e.key.slice(a.length))})}export{createDurableObjectStorageWriter};
1
+ import{n as e}from"../../chunk-BuuaeEvq.mjs";import{n as t}from"../../object-store-DdgcT8d9.mjs";const n=`viborm_migration_estate`;function createDurableObjectStorageWriter(e,r={}){let{sql:i}=e,a=r.prefix??``;return i.exec(`CREATE TABLE IF NOT EXISTS ${n} (key TEXT PRIMARY KEY, bytes BLOB NOT NULL)`),new t({putIfAbsent:async(e,t)=>i.exec(`INSERT INTO ${n} (key, bytes) VALUES (?, ?) ON CONFLICT (key) DO NOTHING RETURNING key`,`${a}${e}`,t.slice().buffer).toArray().length===1?`created`:`exists`,get:async e=>{let[t]=i.exec(`SELECT bytes FROM ${n} WHERE key = ?`,`${a}${e}`).toArray();return t?new Uint8Array(t.bytes):null},list:async e=>i.exec(`SELECT key FROM ${n} WHERE substr(key, 1, length(?)) = ? ORDER BY key`,`${a}${e}`,`${a}${e}`).toArray().map(e=>e.key.slice(a.length))})}export{createDurableObjectStorageWriter};
2
2
  //# sourceMappingURL=durable-object.mjs.map
@@ -1,4 +1,4 @@
1
- import { n as MigrationStorageWriter } from "../../contract-H_WiAUaR.mjs";
1
+ import { n as MigrationStorageWriter } from "../../contract-CYl0OzhZ.mjs";
2
2
 
3
3
  //#region src/migrations/storage/fs-estate.d.ts
4
4
 
@@ -1 +1 @@
1
- import{t as e}from"../../fs-estate-DNCM7hYC.mjs";export{e as createFsStorageWriter};
1
+ import{t as e}from"../../fs-estate-CfvH8Fxa.mjs";export{e as createFsStorageWriter};
@@ -1,4 +1,4 @@
1
- import { n as MigrationStorageWriter } from "../../contract-H_WiAUaR.mjs";
1
+ import { n as MigrationStorageWriter } from "../../contract-CYl0OzhZ.mjs";
2
2
  import { R2Bucket } from "@cloudflare/workers-types";
3
3
 
4
4
  //#region src/migrations/storage/r2.d.ts
@@ -1,2 +1,2 @@
1
- import{n as e}from"../../chunk-BuuaeEvq.mjs";import{n as t}from"../../object-store-DmnlQy7V.mjs";function createR2StorageWriter(e,n={}){let r=n.prefix??``;return new t({putIfAbsent:async(t,n)=>{let i=`${r}${t}`;try{return await e.put(i,n,{onlyIf:{etagDoesNotMatch:`*`}})?`created`:`exists`}catch(t){if(!(t instanceof Error&&t.message.includes(`(10058)`)&&await e.head(i)!==null))throw t;return`exists`}},get:async t=>{let n=await e.get(`${r}${t}`);return n?new Uint8Array(await n.arrayBuffer()):null},list:async t=>{let n=[],i;do{let a=await e.list({prefix:`${r}${t}`,cursor:i});for(let e of a.objects)n.push(e.key.slice(r.length));i=a.truncated?a.cursor:void 0}while(i);return n}})}export{createR2StorageWriter};
1
+ import{n as e}from"../../chunk-BuuaeEvq.mjs";import{n as t}from"../../object-store-DdgcT8d9.mjs";function createR2StorageWriter(e,n={}){let r=n.prefix??``;return new t({putIfAbsent:async(t,n)=>{let i=`${r}${t}`;try{return await e.put(i,n,{onlyIf:{etagDoesNotMatch:`*`}})?`created`:`exists`}catch(t){if(!(t instanceof Error&&t.message.includes(`(10058)`)&&await e.head(i)!==null))throw t;return`exists`}},get:async t=>{let n=await e.get(`${r}${t}`);return n?new Uint8Array(await n.arrayBuffer()):null},list:async t=>{let n=[],i;do{let a=await e.list({prefix:`${r}${t}`,cursor:i});for(let e of a.objects)n.push(e.key.slice(r.length));i=a.truncated?a.cursor:void 0}while(i);return n}})}export{createR2StorageWriter};
2
2
  //# sourceMappingURL=r2.mjs.map
@@ -1,6 +1,6 @@
1
- import { s as MigrationLimits, t as MigrationClient } from "../planner-BxCcoO8s.mjs";
2
- import { i as Sha256, n as MigrationStorageWriter } from "../contract-H_WiAUaR.mjs";
3
- import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-C5BGyg5n.mjs";
1
+ import { s as MigrationLimits, t as MigrationClient } from "../planner-Cc3ABIUU.mjs";
2
+ import { i as Sha256, n as MigrationStorageWriter } from "../contract-CYl0OzhZ.mjs";
3
+ import { U as MigrationMarkerV1, V as MigrationDecisionV1, c as ReadableMigrations } from "../client-7ApJka0M.mjs";
4
4
 
5
5
  //#region src/migrations/tenant.d.ts
6
6
 
@@ -1,2 +1,2 @@
1
- import{n as e}from"../chunk-BuuaeEvq.mjs";import{i as t,n,r}from"../base-wlv81COV.mjs";import{S as i,i as a,r as o,t as s,w as c}from"../client-BCcIdDl8.mjs";const l=new Set([n.MIGRATION_PARTIAL_EFFECT,n.MIGRATION_AMBIGUOUS_COMMIT,n.MIGRATION_UNFINISHED_ATTEMPT]),u=new Set([n.MIGRATION_FAILED,n.MIGRATION_MARKER_CONFLICT]);function createTenantMigrator({client:e,history:t,tables:n,limits:r}){let i={storage:t,tables:n,limits:r},l=s(e,i),u=Promise.resolve(),exclusive=async(e,t)=>{let n=u,release=()=>void 0;u=new Promise(e=>{release=e}).then(()=>n);try{return await untilAborted(n,t),await e()}finally{release()}},change=async(n,{decisions:r=[],signal:l,beforeDestructive:u}={})=>{let d,f;try{l?.throwIfAborted(),a(o(e),`batch`,`apply()`),f=s({$driver:e.$driver,$schema:n},i);let p=c(r);if(u&&await isDestructive(f,p,t)){l?.throwIfAborted();try{await u()}catch(e){return{kind:`refused`,error:describe(e)}}}l?.throwIfAborted(),d=(await f.generate({resolve:p})).outcome===`published`}catch(e){return{kind:classify(e),error:describe(e)}}for(let e=1;;e+=1)try{let e=await f.apply();return e.outcome===`noop`&&!d?{kind:`noop`}:{kind:`applied`,path:e.path,...e.warnings?{warnings:e.warnings}:{}}}catch(t){let n=classify(t),r=d&&n===`refused`?`failed`:n;if(e===4||r!==`failed`||!retryable(t)||!await backoff(e,l))return withMarker({kind:r,error:describe(t)},f)}};return Object.freeze({change:(e,t)=>exclusive(()=>change(e,t),t?.signal).catch(e=>({kind:`failed`,error:describe(e)})),status:()=>l.status(),log:()=>l.log(),resolve:e=>exclusive(()=>l.resolve(e)),down:e=>exclusive(()=>l.down(e)),reanchor:e=>exclusive(()=>l.reanchor(e)),prune:e=>exclusive(()=>l.prune(e))})}async function isDestructive(e,t,n){if((await e.generate({dryRun:!0,resolve:t})).operations.some(i))return!0;if(!await n.readEstate())return!1;let{states:r,edges:a}=await e.graph();if(r.length===0)return!1;let{path:o}=await e.apply({dryRun:!0});return a.some(e=>o.includes(e.toState)&&(e.approvals.length>0||e.risks.includes(`destructive`)))}function retryable(e){if(t(e)&&e.code===n.MIGRATION_LOCK_FAILED)return!0;for(let t=e;t instanceof Error;t=t.cause)if(r(t))return!0;return!1}function classify(e){return t(e)?l.has(e.code)||e.meta.partial===!0?`ambiguous`:u.has(e.code)||retryable(e)?`failed`:`refused`:`failed`}async function withMarker(e,t){try{return{...e,marker:(await t.status()).marker}}catch{return e}}function describe(e){if(!(e instanceof Error))return{name:`Error`,message:String(e)};let n=e.cause instanceof Error?Reflect.get(e.cause,`code`):null,r=t(e)?e.meta.providerSqlState:void 0;return{name:e.name,...t(e)?{code:e.code}:{},message:e.message,...typeof n==`string`?{causeCode:n}:{},...typeof r==`string`?{providerSqlState:r}:{}}}function untilAborted(e,t){if(!t)return e;t.throwIfAborted();let abort=()=>void 0,n=new Promise((e,n)=>{abort=()=>n(t.reason),t.addEventListener(`abort`,abort,{once:!0})});return Promise.race([e,n]).finally(()=>t.removeEventListener(`abort`,abort))}async function backoff(e,t){let n=200*2**(e-1)*(.5+Math.random()/2);try{return await untilAborted(new Promise(e=>setTimeout(e,n)),t),!0}catch{return!1}}export{createTenantMigrator};
1
+ import{n as e}from"../chunk-BuuaeEvq.mjs";import{i as t,n,r}from"../base-wlv81COV.mjs";import{S as i,i as a,r as o,t as s,w as c}from"../client-l7dSOul5.mjs";const l=new Set([n.MIGRATION_PARTIAL_EFFECT,n.MIGRATION_AMBIGUOUS_COMMIT,n.MIGRATION_UNFINISHED_ATTEMPT]),u=new Set([n.MIGRATION_FAILED,n.MIGRATION_MARKER_CONFLICT]);function createTenantMigrator({client:e,history:t,tables:n,limits:r}){let i={storage:t,tables:n,limits:r},l=s(e,i),u=Promise.resolve(),exclusive=async(e,t)=>{let n=u,release=()=>void 0;u=new Promise(e=>{release=e}).then(()=>n);try{return await untilAborted(n,t),await e()}finally{release()}},change=async(n,{decisions:r=[],signal:l,beforeDestructive:u}={})=>{let d,f;try{l?.throwIfAborted(),a(o(e),`batch`,`apply()`),f=s({$driver:e.$driver,$schema:n},i);let p=c(r);if(u&&await isDestructive(f,p,t)){l?.throwIfAborted();try{await u()}catch(e){return{kind:`refused`,error:describe(e)}}}l?.throwIfAborted(),d=(await f.generate({resolve:p})).outcome===`published`}catch(e){return{kind:classify(e),error:describe(e)}}for(let e=1;;e+=1)try{let e=await f.apply();return e.outcome===`noop`&&!d?{kind:`noop`}:{kind:`applied`,path:e.path,...e.warnings?{warnings:e.warnings}:{}}}catch(t){let n=classify(t),r=d&&n===`refused`?`failed`:n;if(e===4||r!==`failed`||!retryable(t)||!await backoff(e,l))return withMarker({kind:r,error:describe(t)},f)}};return Object.freeze({change:(e,t)=>exclusive(()=>change(e,t),t?.signal).catch(e=>({kind:`failed`,error:describe(e)})),status:()=>l.status(),log:()=>l.log(),resolve:e=>exclusive(()=>l.resolve(e)),down:e=>exclusive(()=>l.down(e)),reanchor:e=>exclusive(()=>l.reanchor(e)),prune:e=>exclusive(()=>l.prune(e))})}async function isDestructive(e,t,n){if((await e.generate({dryRun:!0,resolve:t})).operations.some(i))return!0;if(!await n.readEstate())return!1;let{states:r,edges:a}=await e.graph();if(r.length===0)return!1;let{path:o}=await e.apply({dryRun:!0});return a.some(e=>o.includes(e.toState)&&(e.approvals.length>0||e.risks.includes(`destructive`)))}function retryable(e){if(t(e)&&e.code===n.MIGRATION_LOCK_FAILED)return!0;for(let t=e;t instanceof Error;t=t.cause)if(r(t))return!0;return!1}function classify(e){return t(e)?l.has(e.code)||e.meta.partial===!0?`ambiguous`:u.has(e.code)||retryable(e)?`failed`:`refused`:`failed`}async function withMarker(e,t){try{return{...e,marker:(await t.status()).marker}}catch{return e}}function describe(e){if(!(e instanceof Error))return{name:`Error`,message:String(e)};let n=e.cause instanceof Error?Reflect.get(e.cause,`code`):null,r=t(e)?e.meta.providerSqlState:void 0;return{name:e.name,...t(e)?{code:e.code}:{},message:e.message,...typeof n==`string`?{causeCode:n}:{},...typeof r==`string`?{providerSqlState:r}:{}}}function untilAborted(e,t){if(!t)return e;t.throwIfAborted();let abort=()=>void 0,n=new Promise((e,n)=>{abort=()=>n(t.reason),t.addEventListener(`abort`,abort,{once:!0})});return Promise.race([e,n]).finally(()=>t.removeEventListener(`abort`,abort))}async function backoff(e,t){let n=200*2**(e-1)*(.5+Math.random()/2);try{return await untilAborted(new Promise(e=>setTimeout(e,n)),t),!0}catch{return!1}}export{createTenantMigrator};
2
2
  //# sourceMappingURL=tenant.mjs.map
@@ -1,6 +1,6 @@
1
- import { bi as isMigrationError, yi as MigrationError } from "./index-DRX_LLQM.mjs";
2
- import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-BxCcoO8s.mjs";
3
- import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "./contract-H_WiAUaR.mjs";
4
- import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-Cs3AueG5.mjs";
5
- import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-C5BGyg5n.mjs";
1
+ import { bi as MigrationError, xi as isMigrationError } from "./index-CsO6vG2h.mjs";
2
+ import { a as ResolveChange, i as ResolveCallback, o as SchemaSnapshot, r as MigrationTarget, s as MigrationLimits } from "./planner-Cc3ABIUU.mjs";
3
+ import { n as MigrationStorageWriter, r as PublishResult, t as MigrationStorageReader } from "./contract-CYl0OzhZ.mjs";
4
+ import { a as MemoryEstateStorage, c as auditStorage, d as lenientResolver, f as rejectAllResolver, g as sqliteCanonicalTimeExpression, h as sqliteCanonicalDateTimeExpression, i as refuseWorkersKvWritable, l as addDropResolver, m as identifierConversionChecks, n as ObjectStoreConditionalPut, o as createStorageConformanceSuite, p as IdentifierConversionRequest, r as ObjectStoreEstateStorage, s as StorageColumnAudit, t as MemoryConditionalObjectStore, u as createPredefinedResolver } from "./object-store-9VfS-3sY.mjs";
5
+ import { A as InvalidIndex, B as MigrationCheckInput, C as MigrationStateListItem, D as PruneResult, E as PruneOptions, F as ExactPushOptions, G as PushConsent, H as MigrationEstateDescriptorV1, I as GenerateV1Options, J as ResetV1Options, K as PushOptionsV1, L as ManualMigrationInput, M as BaselineOptions, N as DownPreviewEdgeV1, O as CheckFinding, P as DownV1Options, R as ManualTransitionInput, S as MigrationStateDetails, T as ShowResult, V as MigrationDecisionV1, W as MigrationStateManifestV1, X as StateSelector, Y as ResolveV1Options, _ as PushPreview, a as LiveMigrations, b as MigrationEdgeMetadata, c as ReadableMigrations, d as ResolveResult, f as StatusResult, g as PushApplyResult, h as createMigrationClient, i as GenerateResult, j as ApplyV1Options, k as CheckResult, l as ReanchorResult, m as WritableMigrations, n as BaselineResult, o as LogResult, p as VerifyResult, q as ReanchorOptions, r as DownResult, s as MigrationClientOptions, t as ApplyResult, u as ResetResult, v as GraphResult, w as MigrationStateMetadata, x as MigrationRollbackMetadata, y as ListResult, z as MigrationApprovalV1 } from "./client-7ApJka0M.mjs";
6
6
  export { ApplyV1Options as ApplyOptions, ApplyResult, BaselineOptions, BaselineResult, CheckFinding, CheckResult, DownV1Options as DownOptions, DownPreviewEdgeV1 as DownPreviewEdge, DownResult, ExactPushOptions, GenerateV1Options as GenerateOptions, GenerateResult, GraphResult, IdentifierConversionRequest, InvalidIndex, ListResult, LiveMigrations, LogResult, ManualMigrationInput, ManualTransitionInput, MemoryConditionalObjectStore, MemoryEstateStorage, MigrationApprovalV1 as MigrationApproval, MigrationCheckInput, MigrationClientOptions, MigrationDecisionV1 as MigrationDecision, MigrationEdgeMetadata, MigrationError, MigrationEstateDescriptorV1, MigrationLimits, MigrationRollbackMetadata, MigrationStateDetails, MigrationStateListItem, MigrationStateManifestV1, MigrationStateMetadata, MigrationStorageReader, MigrationStorageWriter, MigrationTarget, ObjectStoreConditionalPut, ObjectStoreEstateStorage, PruneOptions, PruneResult, PublishResult, PushApplyResult, PushConsent, PushOptionsV1 as PushOptions, PushPreview, ReadableMigrations, ReanchorOptions, ReanchorResult, ResetV1Options as ResetOptions, ResetResult, ResolveCallback, ResolveChange, ResolveV1Options as ResolveOptions, ResolveResult, SchemaSnapshot, ShowResult, StateSelector, StatusResult, StorageColumnAudit, VerifyResult, WritableMigrations, addDropResolver, auditStorage, createMigrationClient, createPredefinedResolver, createStorageConformanceSuite, identifierConversionChecks, isMigrationError, lenientResolver, refuseWorkersKvWritable, rejectAllResolver, sqliteCanonicalDateTimeExpression, sqliteCanonicalTimeExpression };
@@ -1,2 +1,2 @@
1
- import{n as e,t}from"./migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,s as o,t as s,u as c,w as l}from"./client-BCcIdDl8.mjs";import{t as u}from"./identifier-conversion-DV63mwKG.mjs";import{t as d}from"./every-DIG9CPly.mjs";import{n as f,t as p}from"./memory-CqWRO6-3.mjs";import{n as m,r as h,t as g}from"./object-store-DmnlQy7V.mjs";d();export{g as MemoryConditionalObjectStore,p as MemoryEstateStorage,t as MigrationError,m as ObjectStoreEstateStorage,n as addDropResolver,o as auditStorage,s as createMigrationClient,l as createPredefinedResolver,f as createStorageConformanceSuite,u as identifierConversionChecks,e as isMigrationError,i as lenientResolver,h as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,c as sqliteCanonicalTimeExpression};
1
+ import{n as e,t}from"./migrations-OE5D32qo.mjs";import{C as n,E as r,T as i,l as a,s as o,t as s,u as c,w as l}from"./client-l7dSOul5.mjs";import{t as u}from"./identifier-conversion-BXrBYgAq.mjs";import{t as d}from"./every-6VrIclsx.mjs";import{n as f,t as p}from"./memory-B1GnzgZr.mjs";import{n as m,r as h,t as g}from"./object-store-DdgcT8d9.mjs";d();export{g as MemoryConditionalObjectStore,p as MemoryEstateStorage,t as MigrationError,m as ObjectStoreEstateStorage,n as addDropResolver,o as auditStorage,s as createMigrationClient,l as createPredefinedResolver,f as createStorageConformanceSuite,u as identifierConversionChecks,e as isMigrationError,i as lenientResolver,h as refuseWorkersKvWritable,r as rejectAllResolver,a as sqliteCanonicalDateTimeExpression,c as sqliteCanonicalTimeExpression};
2
2
  //# sourceMappingURL=migrations.mjs.map
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./chunk-BuuaeEvq.mjs";import{C as t,S as n,_ as r,g as i,h as a,m as o,n as s,v as c,w as l,x as u}from"./v-Pb_jJOjC.mjs";import{Pt as d}from"./geo-point-codec-CIZxuIvE.mjs";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]}const f=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,190}$/,p=[`table`,`source`,`target`];function normalizeVariantEntries(e,n,i){r(n)||l(e,`target`,"A relation target is either `() => model` or a plain map of named `() => model` getters");let o=a(n);o.length===0&&l(e,`target`,`A variant map needs at least one variant`);let s=readStoredValues(e,o,i),c={};for(let r of o){d(r)||l(e,`target.${r}`,`Variant key '${r}' is not a valid schema identifier`);let i=t(e,n,r,`target.${r}`);typeof i!=`function`&&l(e,`target.${r}`,`Variant '${r}' must be a lazy getter; write \`() => model\` rather than the model itself`),c[r]=Object.freeze({getter:i,storedValue:s[r]??r})}return Object.freeze(c)}function readStoredValues(e,n,o){if(o===void 0)return{};r(o)||l(e,`options`,"Relation options must be a plain `{ values }` record; omit the argument to use each variant key as its stored value"),i(a(o),[`values`])||l(e,`options`,"Relation options carry exactly one key, `values`; omit the argument to use each variant key as its stored value");let s=t(e,o,`values`,`options.values`);r(s)||l(e,`options.values`,"`values` must be a plain record keyed by every variant");let c=a(s);i(c,n)||l(e,`options.values`,`\`values\` must be exact over the variant keys ${renderKeys(n)}; it declares ${renderKeys(c)}`);let u={},d=new Set;for(let r of n){let n=t(e,s,r,`options.values.${r}`);(typeof n!=`string`||!f.test(n))&&l(e,`options.values.${r}`,`Stored value for variant '${r}' must match the stored-discriminator grammar`),d.has(n)&&l(e,`options.values.${r}`,`Stored value '${n}' is declared for more than one variant`),d.add(n),u[r]=n}return u}function renderKeys(e){return`[${e.map(e=>`'${e}'`).join(`, `)}]`}function foldMemberJunctions(e,n){let o=Object.keys(e);r(n)||l(`s.toMany`,`through`,"`.through()` takes a plain map keyed by every variant"),i(a(n),o)||l(`s.toMany`,`through`,`\`.through()\` must be exact over the variant keys ${renderKeys(o)}`);let s={};for(let[r,i]of Object.entries(e)){let e=t(`s.toMany`,n,r,`through.${r}`);s[r]=Object.freeze({...i,junction:readJunctionOverride(r,e)})}return Object.freeze(s)}function readJunctionOverride(e,n){let o=`through.${e}`;r(n)||l(`s.toMany`,o,`Member junction '${e}' must be a plain \`{ table, source, target }\` record`);let s=t(`s.toMany`,n,`table`,`${o}.table`),c=t(`s.toMany`,n,`source`,`${o}.source`),u=t(`s.toMany`,n,`target`,`${o}.target`);return(!i(a(n),p)||typeof s!=`string`||typeof c!=`string`||typeof u!=`string`)&&l(`s.toMany`,o,`Member junction '${e}' declares exactly \`table\`, \`source\` and \`target\`, all strings`),Object.freeze({table:s,source:c,target:u})}var m=class VariantToOne{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:o(e=>readVariantGetter(this.#e,e))})}name(e){return new VariantToOne({...this.#e,name:n(`s.toOne`,e)})}optional(){return new VariantToOne({...this.#e,optional:!0})}get"~"(){return this.#t}},h=class VariantToMany{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:o(e=>readVariantGetter(this.#e,e))})}name(e){return new VariantToMany({...this.#e,name:n(`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 m(e)}function variantToManyTerminal(e){return new h(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 g=class ModelToOne{#e;#t;constructor(e){this.#e=Object.freeze(e),this.#t=Object.freeze({state:this.#e,settleTarget:o(()=>this.#e.target.getter)})}name(e){return new ModelToOne({...this.#e,name:n(`s.toOne`,e)})}fields(...e){return new _(this.#e,c(`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&&l(`s.toOne`,e,`'${e}' is available only after \`.fields(...).references(...)\` declares a foreign key`),new ModelToOne({...this.#e,foreignKey:Object.freeze({...n,[e]:u(e,t)})})}get"~"(){return this.#t}},_=class PendingReferences{#e;#t;constructor(e,t){this.#e=e,this.#t=t}name(e){return new PendingReferences({...this.#e,name:n(`s.toOne`,e)},this.#t)}references(...e){let t=c(`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 g({...this.#e,foreignKey:Object.freeze(r)})}};function isReferencesStage(e){return e instanceof _}function toOne(e,t){return typeof e==`function`?(arguments.length>1&&l(`s.toOne`,`options`,`A model-target relation takes exactly one argument`),new g({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 l(`s.toOne`,`references`,`\`.references(...)\` declares ${e} field(s) against ${t} local field(s); a foreign key pairs them positionally`)}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 v=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`&&v.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)&&l(`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 c=compoundMembers(e,a,n);return new y({...e,[t]:{...e[t],[o]:s.object(c,{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 y=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 y({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}export{model as a,variantToManyTerminal as c,put as d,isTotalIndex as i,emptyRecord as l,getColumnName as n,toOne as o,getTableName as r,normalizeVariantEntries as s,y as t,own as u};
2
+ //# sourceMappingURL=model-DsXZ_pHE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-DsXZ_pHE.mjs","names":["#state","#internal","#state","#internal","#withForeignKeyAction","#localFields","v","#state","#internal","model","#names","#nameRegistry","#scalarFieldNames","#relationNames"],"sources":["../src/schema/record.ts","../src/schema/relation/polymorphic.ts","../src/schema/relation/to-one.ts","../src/schema/model/helper.ts","../src/schema/model/model.ts"],"sourcesContent":["// 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","// 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","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"],"mappings":"iMAs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